1 #if defined(_MSC_VER) && (_MSC_VER >= 1800)
2 // eliminating duplicated round() declaration
8 #define MODULESTR "cv2"
9 #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
10 #include <numpy/ndarrayobject.h>
12 #include "pyopencv_generated_include.h"
14 #include "opencv2/opencv_modules.hpp"
16 #include "pycompat.hpp"
19 static PyObject* opencv_error = 0;
21 static int failmsg(const char *fmt, ...)
27 vsnprintf(str, sizeof(str), fmt, ap);
30 PyErr_SetString(PyExc_TypeError, str);
38 // more fields may be added if necessary
40 ArgInfo(const char * name_, bool outputarg_)
42 , outputarg(outputarg_) {}
44 // to match with older pyopencv_to function signature
45 operator const char *() const { return name; }
51 PyAllowThreads() : _state(PyEval_SaveThread()) {}
54 PyEval_RestoreThread(_state);
57 PyThreadState* _state;
63 PyEnsureGIL() : _state(PyGILState_Ensure()) {}
66 PyGILState_Release(_state);
69 PyGILState_STATE _state;
72 #define ERRWRAP2(expr) \
75 PyAllowThreads allowThreads; \
78 catch (const cv::Exception &e) \
80 PyErr_SetString(opencv_error, e.what()); \
85 using cv::flann::IndexParams;
86 using cv::flann::SearchParams;
88 typedef std::vector<uchar> vector_uchar;
89 typedef std::vector<char> vector_char;
90 typedef std::vector<int> vector_int;
91 typedef std::vector<float> vector_float;
92 typedef std::vector<double> vector_double;
93 typedef std::vector<Point> vector_Point;
94 typedef std::vector<Point2f> vector_Point2f;
95 typedef std::vector<Vec2f> vector_Vec2f;
96 typedef std::vector<Vec3f> vector_Vec3f;
97 typedef std::vector<Vec4f> vector_Vec4f;
98 typedef std::vector<Vec6f> vector_Vec6f;
99 typedef std::vector<Vec4i> vector_Vec4i;
100 typedef std::vector<Rect> vector_Rect;
101 typedef std::vector<KeyPoint> vector_KeyPoint;
102 typedef std::vector<Mat> vector_Mat;
103 typedef std::vector<DMatch> vector_DMatch;
104 typedef std::vector<String> vector_String;
105 typedef std::vector<Scalar> vector_Scalar;
107 typedef std::vector<std::vector<char> > vector_vector_char;
108 typedef std::vector<std::vector<Point> > vector_vector_Point;
109 typedef std::vector<std::vector<Point2f> > vector_vector_Point2f;
110 typedef std::vector<std::vector<Point3f> > vector_vector_Point3f;
111 typedef std::vector<std::vector<DMatch> > vector_vector_DMatch;
113 typedef SimpleBlobDetector::Params SimpleBlobDetector_Params;
115 typedef cvflann::flann_distance_t cvflann_flann_distance_t;
116 typedef cvflann::flann_algorithm_t cvflann_flann_algorithm_t;
119 static PyObject* failmsgp(const char *fmt, ...)
125 vsnprintf(str, sizeof(str), fmt, ap);
128 PyErr_SetString(PyExc_TypeError, str);
132 class NumpyAllocator : public MatAllocator
135 NumpyAllocator() { stdAllocator = Mat::getStdAllocator(); }
138 UMatData* allocate(PyObject* o, int dims, const int* sizes, int type, size_t* step) const
140 UMatData* u = new UMatData(this);
141 u->data = u->origdata = (uchar*)PyArray_DATA((PyArrayObject*) o);
142 npy_intp* _strides = PyArray_STRIDES((PyArrayObject*) o);
143 for( int i = 0; i < dims - 1; i++ )
144 step[i] = (size_t)_strides[i];
145 step[dims-1] = CV_ELEM_SIZE(type);
146 u->size = sizes[0]*step[0];
151 UMatData* allocate(int dims0, const int* sizes, int type, void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const
155 CV_Error(Error::StsAssert, "The data should normally be NULL!");
156 // probably this is safe to do in such extreme case
157 return stdAllocator->allocate(dims0, sizes, type, data, step, flags, usageFlags);
161 int depth = CV_MAT_DEPTH(type);
162 int cn = CV_MAT_CN(type);
163 const int f = (int)(sizeof(size_t)/8);
164 int typenum = depth == CV_8U ? NPY_UBYTE : depth == CV_8S ? NPY_BYTE :
165 depth == CV_16U ? NPY_USHORT : depth == CV_16S ? NPY_SHORT :
166 depth == CV_32S ? NPY_INT : depth == CV_32F ? NPY_FLOAT :
167 depth == CV_64F ? NPY_DOUBLE : f*NPY_ULONGLONG + (f^1)*NPY_UINT;
169 cv::AutoBuffer<npy_intp> _sizes(dims + 1);
170 for( i = 0; i < dims; i++ )
171 _sizes[i] = sizes[i];
174 PyObject* o = PyArray_SimpleNew(dims, _sizes, typenum);
176 CV_Error_(Error::StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims));
177 return allocate(o, dims0, sizes, type, step);
180 bool allocate(UMatData* u, int accessFlags, UMatUsageFlags usageFlags) const
182 return stdAllocator->allocate(u, accessFlags, usageFlags);
185 void deallocate(UMatData* u) const
190 PyObject* o = (PyObject*)u->userdata;
196 const MatAllocator* stdAllocator;
199 NumpyAllocator g_numpyAllocator;
202 template<typename T> static
203 bool pyopencv_to(PyObject* obj, T& p, const char* name = "<unknown>");
205 template<typename T> static
206 PyObject* pyopencv_from(const T& src);
208 enum { ARG_NONE = 0, ARG_MAT = 1, ARG_SCALAR = 2 };
210 // special case, when the convertor needs full ArgInfo structure
211 static bool pyopencv_to(PyObject* o, Mat& m, const ArgInfo info)
214 if(!o || o == Py_None)
217 m.allocator = &g_numpyAllocator;
223 double v[] = {PyInt_AsLong((PyObject*)o), 0., 0., 0.};
224 m = Mat(4, 1, CV_64F, v).clone();
227 if( PyFloat_Check(o) )
229 double v[] = {PyFloat_AsDouble((PyObject*)o), 0., 0., 0.};
230 m = Mat(4, 1, CV_64F, v).clone();
233 if( PyTuple_Check(o) )
235 int i, sz = (int)PyTuple_Size((PyObject*)o);
236 m = Mat(sz, 1, CV_64F);
237 for( i = 0; i < sz; i++ )
239 PyObject* oi = PyTuple_GET_ITEM(o, i);
240 if( PyInt_Check(oi) )
241 m.at<double>(i) = (double)PyInt_AsLong(oi);
242 else if( PyFloat_Check(oi) )
243 m.at<double>(i) = (double)PyFloat_AsDouble(oi);
246 failmsg("%s is not a numerical tuple", info.name);
254 if( !PyArray_Check(o) )
256 failmsg("%s is not a numpy array, neither a scalar", info.name);
260 PyArrayObject* oarr = (PyArrayObject*) o;
262 bool needcopy = false, needcast = false;
263 int typenum = PyArray_TYPE(oarr), new_typenum = typenum;
264 int type = typenum == NPY_UBYTE ? CV_8U :
265 typenum == NPY_BYTE ? CV_8S :
266 typenum == NPY_USHORT ? CV_16U :
267 typenum == NPY_SHORT ? CV_16S :
268 typenum == NPY_INT ? CV_32S :
269 typenum == NPY_INT32 ? CV_32S :
270 typenum == NPY_FLOAT ? CV_32F :
271 typenum == NPY_DOUBLE ? CV_64F : -1;
275 if( typenum == NPY_INT64 || typenum == NPY_UINT64 || type == NPY_LONG )
277 needcopy = needcast = true;
278 new_typenum = NPY_INT;
283 failmsg("%s data type = %d is not supported", info.name, typenum);
289 const int CV_MAX_DIM = 32;
292 int ndims = PyArray_NDIM(oarr);
293 if(ndims >= CV_MAX_DIM)
295 failmsg("%s dimensionality (=%d) is too high", info.name, ndims);
299 int size[CV_MAX_DIM+1];
300 size_t step[CV_MAX_DIM+1];
301 size_t elemsize = CV_ELEM_SIZE1(type);
302 const npy_intp* _sizes = PyArray_DIMS(oarr);
303 const npy_intp* _strides = PyArray_STRIDES(oarr);
304 bool ismultichannel = ndims == 3 && _sizes[2] <= CV_CN_MAX;
306 for( int i = ndims-1; i >= 0 && !needcopy; i-- )
308 // these checks handle cases of
309 // a) multi-dimensional (ndims > 2) arrays, as well as simpler 1- and 2-dimensional cases
310 // b) transposed arrays, where _strides[] elements go in non-descending order
311 // c) flipped arrays, where some of _strides[] elements are negative
312 if( (i == ndims-1 && (size_t)_strides[i] != elemsize) ||
313 (i < ndims-1 && _strides[i] < _strides[i+1]) )
317 if( ismultichannel && _strides[1] != (npy_intp)elemsize*_sizes[2] )
324 failmsg("Layout of the output array %s is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)", info.name);
329 o = PyArray_Cast(oarr, new_typenum);
330 oarr = (PyArrayObject*) o;
333 oarr = PyArray_GETCONTIGUOUS(oarr);
334 o = (PyObject*) oarr;
337 _strides = PyArray_STRIDES(oarr);
340 for(int i = 0; i < ndims; i++)
342 size[i] = (int)_sizes[i];
343 step[i] = (size_t)_strides[i];
346 // handle degenerate case
349 step[ndims] = elemsize;
356 type |= CV_MAKETYPE(0, size[2]);
359 if( ndims > 2 && !allowND )
361 failmsg("%s has more than 2 dimensions", info.name);
365 m = Mat(ndims, size, type, PyArray_DATA(oarr), step);
366 m.u = g_numpyAllocator.allocate(o, ndims, size, type, step);
373 m.allocator = &g_numpyAllocator;
379 PyObject* pyopencv_from(const Mat& m)
383 Mat temp, *p = (Mat*)&m;
384 if(!p->u || p->allocator != &g_numpyAllocator)
386 temp.allocator = &g_numpyAllocator;
387 ERRWRAP2(m.copyTo(temp));
390 PyObject* o = (PyObject*)p->u->userdata;
396 bool pyopencv_to(PyObject *o, Scalar& s, const char *name)
398 if(!o || o == Py_None)
400 if (PySequence_Check(o)) {
401 PyObject *fi = PySequence_Fast(o, name);
404 if (4 < PySequence_Fast_GET_SIZE(fi))
406 failmsg("Scalar value for argument '%s' is longer than 4", name);
409 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
410 PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
411 if (PyFloat_Check(item) || PyInt_Check(item)) {
412 s[(int)i] = PyFloat_AsDouble(item);
414 failmsg("Scalar value for argument '%s' is not numeric", name);
420 if (PyFloat_Check(o) || PyInt_Check(o)) {
421 s[0] = PyFloat_AsDouble(o);
423 failmsg("Scalar value for argument '%s' is not numeric", name);
431 PyObject* pyopencv_from(const Scalar& src)
433 return Py_BuildValue("(dddd)", src[0], src[1], src[2], src[3]);
437 PyObject* pyopencv_from(const bool& value)
439 return PyBool_FromLong(value);
443 bool pyopencv_to(PyObject* obj, bool& value, const char* name)
446 if(!obj || obj == Py_None)
448 int _val = PyObject_IsTrue(obj);
456 PyObject* pyopencv_from(const size_t& value)
458 return PyLong_FromSize_t(value);
462 bool pyopencv_to(PyObject* obj, size_t& value, const char* name)
465 if(!obj || obj == Py_None)
467 value = (int)PyLong_AsUnsignedLong(obj);
468 return value != (size_t)-1 || !PyErr_Occurred();
472 PyObject* pyopencv_from(const int& value)
474 return PyInt_FromLong(value);
478 PyObject* pyopencv_from(const cvflann_flann_algorithm_t& value)
480 return PyInt_FromLong(int(value));
484 PyObject* pyopencv_from(const cvflann_flann_distance_t& value)
486 return PyInt_FromLong(int(value));
490 bool pyopencv_to(PyObject* obj, int& value, const char* name)
493 if(!obj || obj == Py_None)
496 value = (int)PyInt_AsLong(obj);
497 else if(PyLong_Check(obj))
498 value = (int)PyLong_AsLong(obj);
501 return value != -1 || !PyErr_Occurred();
505 PyObject* pyopencv_from(const uchar& value)
507 return PyInt_FromLong(value);
511 bool pyopencv_to(PyObject* obj, uchar& value, const char* name)
514 if(!obj || obj == Py_None)
516 int ivalue = (int)PyInt_AsLong(obj);
517 value = cv::saturate_cast<uchar>(ivalue);
518 return ivalue != -1 || !PyErr_Occurred();
522 PyObject* pyopencv_from(const double& value)
524 return PyFloat_FromDouble(value);
528 bool pyopencv_to(PyObject* obj, double& value, const char* name)
531 if(!obj || obj == Py_None)
533 if(!!PyInt_CheckExact(obj))
534 value = (double)PyInt_AS_LONG(obj);
536 value = PyFloat_AsDouble(obj);
537 return !PyErr_Occurred();
541 PyObject* pyopencv_from(const float& value)
543 return PyFloat_FromDouble(value);
547 bool pyopencv_to(PyObject* obj, float& value, const char* name)
550 if(!obj || obj == Py_None)
552 if(!!PyInt_CheckExact(obj))
553 value = (float)PyInt_AS_LONG(obj);
555 value = (float)PyFloat_AsDouble(obj);
556 return !PyErr_Occurred();
560 PyObject* pyopencv_from(const int64& value)
562 return PyLong_FromLongLong(value);
566 PyObject* pyopencv_from(const String& value)
568 return PyString_FromString(value.empty() ? "" : value.c_str());
572 bool pyopencv_to(PyObject* obj, String& value, const char* name)
575 if(!obj || obj == Py_None)
577 char* str = PyString_AsString(obj);
585 bool pyopencv_to(PyObject* obj, Size& sz, const char* name)
588 if(!obj || obj == Py_None)
590 return PyArg_ParseTuple(obj, "ii", &sz.width, &sz.height) > 0;
594 PyObject* pyopencv_from(const Size& sz)
596 return Py_BuildValue("(ii)", sz.width, sz.height);
600 bool pyopencv_to(PyObject* obj, Rect& r, const char* name)
603 if(!obj || obj == Py_None)
605 return PyArg_ParseTuple(obj, "iiii", &r.x, &r.y, &r.width, &r.height) > 0;
609 PyObject* pyopencv_from(const Rect& r)
611 return Py_BuildValue("(iiii)", r.x, r.y, r.width, r.height);
615 bool pyopencv_to(PyObject* obj, Range& r, const char* name)
618 if(!obj || obj == Py_None)
620 if(PyObject_Size(obj) == 0)
625 return PyArg_ParseTuple(obj, "ii", &r.start, &r.end) > 0;
629 PyObject* pyopencv_from(const Range& r)
631 return Py_BuildValue("(ii)", r.start, r.end);
635 bool pyopencv_to(PyObject* obj, Point& p, const char* name)
638 if(!obj || obj == Py_None)
640 if(!!PyComplex_CheckExact(obj))
642 Py_complex c = PyComplex_AsCComplex(obj);
643 p.x = saturate_cast<int>(c.real);
644 p.y = saturate_cast<int>(c.imag);
647 return PyArg_ParseTuple(obj, "ii", &p.x, &p.y) > 0;
651 bool pyopencv_to(PyObject* obj, Point2f& p, const char* name)
654 if(!obj || obj == Py_None)
656 if(!!PyComplex_CheckExact(obj))
658 Py_complex c = PyComplex_AsCComplex(obj);
659 p.x = saturate_cast<float>(c.real);
660 p.y = saturate_cast<float>(c.imag);
663 return PyArg_ParseTuple(obj, "ff", &p.x, &p.y) > 0;
667 bool pyopencv_to(PyObject* obj, Point2d& p, const char* name)
670 if(!obj || obj == Py_None)
672 if(!!PyComplex_CheckExact(obj))
674 Py_complex c = PyComplex_AsCComplex(obj);
675 p.x = saturate_cast<double>(c.real);
676 p.y = saturate_cast<double>(c.imag);
679 return PyArg_ParseTuple(obj, "dd", &p.x, &p.y) > 0;
684 PyObject* pyopencv_from(const Point& p)
686 return Py_BuildValue("(ii)", p.x, p.y);
690 PyObject* pyopencv_from(const Point2f& p)
692 return Py_BuildValue("(dd)", p.x, p.y);
696 bool pyopencv_to(PyObject* obj, Vec3d& v, const char* name)
701 return PyArg_ParseTuple(obj, "ddd", &v[0], &v[1], &v[2]) > 0;
705 PyObject* pyopencv_from(const Vec3d& v)
707 return Py_BuildValue("(ddd)", v[0], v[1], v[2]);
711 PyObject* pyopencv_from(const Vec2d& v)
713 return Py_BuildValue("(dd)", v[0], v[1]);
717 PyObject* pyopencv_from(const Point2d& p)
719 return Py_BuildValue("(dd)", p.x, p.y);
722 template<typename _Tp> struct pyopencvVecConverter
724 static bool to(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
726 typedef typename DataType<_Tp>::channel_type _Cp;
727 if(!obj || obj == Py_None)
729 if (PyArray_Check(obj))
732 pyopencv_to(obj, m, info);
735 if (!PySequence_Check(obj))
737 PyObject *seq = PySequence_Fast(obj, info.name);
740 int i, j, n = (int)PySequence_Fast_GET_SIZE(seq);
743 int type = DataType<_Tp>::type;
744 int depth = CV_MAT_DEPTH(type), channels = CV_MAT_CN(type);
745 PyObject** items = PySequence_Fast_ITEMS(seq);
747 for( i = 0; i < n; i++ )
749 PyObject* item = items[i];
751 PyObject** items_i = &item;
752 _Cp* data = (_Cp*)&value[i];
754 if( channels == 2 && PyComplex_CheckExact(item) )
756 Py_complex c = PyComplex_AsCComplex(obj);
757 data[0] = saturate_cast<_Cp>(c.real);
758 data[1] = saturate_cast<_Cp>(c.imag);
763 if( PyArray_Check(item))
766 pyopencv_to(item, src, info);
767 if( src.dims != 2 || src.channels() != 1 ||
768 ((src.cols != 1 || src.rows != channels) &&
769 (src.cols != channels || src.rows != 1)))
771 Mat dst(src.rows, src.cols, depth, data);
772 src.convertTo(dst, type);
773 if( dst.data != (uchar*)data )
778 seq_i = PySequence_Fast(item, info.name);
779 if( !seq_i || (int)PySequence_Fast_GET_SIZE(seq_i) != channels )
784 items_i = PySequence_Fast_ITEMS(seq_i);
787 for( j = 0; j < channels; j++ )
789 PyObject* item_ij = items_i[j];
790 if( PyInt_Check(item_ij))
792 int v = (int)PyInt_AsLong(item_ij);
793 if( v == -1 && PyErr_Occurred() )
795 data[j] = saturate_cast<_Cp>(v);
797 else if( PyLong_Check(item_ij))
799 int v = (int)PyLong_AsLong(item_ij);
800 if( v == -1 && PyErr_Occurred() )
802 data[j] = saturate_cast<_Cp>(v);
804 else if( PyFloat_Check(item_ij))
806 double v = PyFloat_AsDouble(item_ij);
807 if( PyErr_Occurred() )
809 data[j] = saturate_cast<_Cp>(v);
822 static PyObject* from(const std::vector<_Tp>& value)
825 return PyTuple_New(0);
826 Mat src((int)value.size(), DataType<_Tp>::channels, DataType<_Tp>::depth, (uchar*)&value[0]);
827 return pyopencv_from(src);
831 template<typename _Tp>
832 bool pyopencv_to(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
834 return pyopencvVecConverter<_Tp>::to(obj, value, info);
837 template<typename _Tp>
838 PyObject* pyopencv_from(const std::vector<_Tp>& value)
840 return pyopencvVecConverter<_Tp>::from(value);
843 template<typename _Tp> static inline bool pyopencv_to_generic_vec(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
845 if(!obj || obj == Py_None)
847 if (!PySequence_Check(obj))
849 PyObject *seq = PySequence_Fast(obj, info.name);
852 int i, n = (int)PySequence_Fast_GET_SIZE(seq);
855 PyObject** items = PySequence_Fast_ITEMS(seq);
857 for( i = 0; i < n; i++ )
859 PyObject* item = items[i];
860 if(!pyopencv_to(item, value[i], info))
867 template<typename _Tp> static inline PyObject* pyopencv_from_generic_vec(const std::vector<_Tp>& value)
869 int i, n = (int)value.size();
870 PyObject* seq = PyList_New(n);
871 for( i = 0; i < n; i++ )
873 PyObject* item = pyopencv_from(value[i]);
876 PyList_SET_ITEM(seq, i, item);
887 template<typename _Tp> struct pyopencvVecConverter<std::vector<_Tp> >
889 static bool to(PyObject* obj, std::vector<std::vector<_Tp> >& value, const ArgInfo info)
891 return pyopencv_to_generic_vec(obj, value, info);
894 static PyObject* from(const std::vector<std::vector<_Tp> >& value)
896 return pyopencv_from_generic_vec(value);
900 template<> struct pyopencvVecConverter<Mat>
902 static bool to(PyObject* obj, std::vector<Mat>& value, const ArgInfo info)
904 return pyopencv_to_generic_vec(obj, value, info);
907 static PyObject* from(const std::vector<Mat>& value)
909 return pyopencv_from_generic_vec(value);
913 template<> struct pyopencvVecConverter<KeyPoint>
915 static bool to(PyObject* obj, std::vector<KeyPoint>& value, const ArgInfo info)
917 return pyopencv_to_generic_vec(obj, value, info);
920 static PyObject* from(const std::vector<KeyPoint>& value)
922 return pyopencv_from_generic_vec(value);
926 template<> struct pyopencvVecConverter<DMatch>
928 static bool to(PyObject* obj, std::vector<DMatch>& value, const ArgInfo info)
930 return pyopencv_to_generic_vec(obj, value, info);
933 static PyObject* from(const std::vector<DMatch>& value)
935 return pyopencv_from_generic_vec(value);
939 template<> struct pyopencvVecConverter<String>
941 static bool to(PyObject* obj, std::vector<String>& value, const ArgInfo info)
943 return pyopencv_to_generic_vec(obj, value, info);
946 static PyObject* from(const std::vector<String>& value)
948 return pyopencv_from_generic_vec(value);
953 bool pyopencv_to(PyObject *obj, TermCriteria& dst, const char *name)
958 return PyArg_ParseTuple(obj, "iid", &dst.type, &dst.maxCount, &dst.epsilon) > 0;
962 PyObject* pyopencv_from(const TermCriteria& src)
964 return Py_BuildValue("(iid)", src.type, src.maxCount, src.epsilon);
968 bool pyopencv_to(PyObject *obj, RotatedRect& dst, const char *name)
973 return PyArg_ParseTuple(obj, "(ff)(ff)f", &dst.center.x, &dst.center.y, &dst.size.width, &dst.size.height, &dst.angle) > 0;
977 PyObject* pyopencv_from(const RotatedRect& src)
979 return Py_BuildValue("((ff)(ff)f)", src.center.x, src.center.y, src.size.width, src.size.height, src.angle);
983 PyObject* pyopencv_from(const Moments& m)
985 return Py_BuildValue("{s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d}",
986 "m00", m.m00, "m10", m.m10, "m01", m.m01,
987 "m20", m.m20, "m11", m.m11, "m02", m.m02,
988 "m30", m.m30, "m21", m.m21, "m12", m.m12, "m03", m.m03,
989 "mu20", m.mu20, "mu11", m.mu11, "mu02", m.mu02,
990 "mu30", m.mu30, "mu21", m.mu21, "mu12", m.mu12, "mu03", m.mu03,
991 "nu20", m.nu20, "nu11", m.nu11, "nu02", m.nu02,
992 "nu30", m.nu30, "nu21", m.nu21, "nu12", m.nu12, "nu03", m.nu03);
996 bool pyopencv_to(PyObject *o, cv::flann::IndexParams& p, const char *name)
1000 PyObject* key = NULL;
1001 PyObject* item = NULL;
1004 if(PyDict_Check(o)) {
1005 while(PyDict_Next(o, &pos, &key, &item)) {
1006 if( !PyString_Check(key) ) {
1011 String k = PyString_AsString(key);
1012 if( PyString_Check(item) )
1014 const char* value = PyString_AsString(item);
1015 p.setString(k, value);
1017 else if( !!PyBool_Check(item) )
1018 p.setBool(k, item == Py_True);
1019 else if( PyInt_Check(item) )
1021 int value = (int)PyInt_AsLong(item);
1022 if( strcmp(k.c_str(), "algorithm") == 0 )
1023 p.setAlgorithm(value);
1027 else if( PyFloat_Check(item) )
1029 double value = PyFloat_AsDouble(item);
1030 p.setDouble(k, value);
1040 return ok && !PyErr_Occurred();
1044 bool pyopencv_to(PyObject* obj, cv::flann::SearchParams & value, const char * name)
1046 return pyopencv_to<cv::flann::IndexParams>(obj, value, name);
1049 template <typename T>
1050 bool pyopencv_to(PyObject *o, Ptr<T>& p, const char *name)
1053 return pyopencv_to(o, *p, name);
1057 bool pyopencv_to(PyObject *o, cvflann::flann_distance_t& dist, const char *name)
1060 bool ok = pyopencv_to(o, d, name);
1061 dist = (cvflann::flann_distance_t)d;
1066 ////////////////////////////////////////////////////////////////////////////////////////////////////
1067 // TODO: REMOVE used only by ml wrapper
1070 bool pyopencv_to(PyObject *obj, CvTermCriteria& dst, const char *name)
1075 return PyArg_ParseTuple(obj, "iid", &dst.type, &dst.max_iter, &dst.epsilon) > 0;
1079 bool pyopencv_to(PyObject* obj, CvSlice& r, const char* name)
1082 if(!obj || obj == Py_None)
1084 if(PyObject_Size(obj) == 0)
1089 return PyArg_ParseTuple(obj, "ii", &r.start_index, &r.end_index) > 0;
1093 PyObject* pyopencv_from(CvDTreeNode* const & node)
1095 double value = node->value;
1096 int ivalue = cvRound(value);
1097 return value == ivalue ? PyInt_FromLong(ivalue) : PyFloat_FromDouble(value);
1100 ////////////////////////////////////////////////////////////////////////////////////////////////////
1102 static void OnMouse(int event, int x, int y, int flags, void* param)
1104 PyGILState_STATE gstate;
1105 gstate = PyGILState_Ensure();
1107 PyObject *o = (PyObject*)param;
1108 PyObject *args = Py_BuildValue("iiiiO", event, x, y, flags, PyTuple_GetItem(o, 1));
1110 PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL);
1116 PyGILState_Release(gstate);
1119 static PyObject *pycvSetMouseCallback(PyObject*, PyObject *args, PyObject *kw)
1121 const char *keywords[] = { "window_name", "on_mouse", "param", NULL };
1124 PyObject *param = NULL;
1126 if (!PyArg_ParseTupleAndKeywords(args, kw, "sO|O", (char**)keywords, &name, &on_mouse, ¶m))
1128 if (!PyCallable_Check(on_mouse)) {
1129 PyErr_SetString(PyExc_TypeError, "on_mouse must be callable");
1132 if (param == NULL) {
1135 ERRWRAP2(setMouseCallback(name, OnMouse, Py_BuildValue("OO", on_mouse, param)));
1139 static void OnChange(int pos, void *param)
1141 PyGILState_STATE gstate;
1142 gstate = PyGILState_Ensure();
1144 PyObject *o = (PyObject*)param;
1145 PyObject *args = Py_BuildValue("(i)", pos);
1146 PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL);
1150 PyGILState_Release(gstate);
1153 static PyObject *pycvCreateTrackbar(PyObject*, PyObject *args)
1155 PyObject *on_change;
1156 char* trackbar_name;
1158 int *value = new int;
1161 if (!PyArg_ParseTuple(args, "ssiiO", &trackbar_name, &window_name, value, &count, &on_change))
1163 if (!PyCallable_Check(on_change)) {
1164 PyErr_SetString(PyExc_TypeError, "on_change must be callable");
1167 ERRWRAP2(createTrackbar(trackbar_name, window_name, value, count, OnChange, Py_BuildValue("OO", on_change, Py_None)));
1171 ///////////////////////////////////////////////////////////////////////////////////////
1173 static int convert_to_char(PyObject *o, char *dst, const char *name = "no_name")
1175 if (PyString_Check(o) && PyString_Size(o) == 1) {
1176 *dst = PyString_AsString(o)[0];
1180 return failmsg("Expected single character string for argument '%s'", name);
1184 #if PY_MAJOR_VERSION >= 3
1185 #define MKTYPE2(NAME) pyopencv_##NAME##_specials(); if (!to_ok(&pyopencv_##NAME##_Type)) return NULL;
1187 #define MKTYPE2(NAME) pyopencv_##NAME##_specials(); if (!to_ok(&pyopencv_##NAME##_Type)) return
1191 # pragma GCC diagnostic ignored "-Wunused-parameter"
1192 # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
1195 #include "pyopencv_generated_types.h"
1196 #include "pyopencv_generated_funcs.h"
1198 static PyMethodDef methods[] = {
1200 #include "pyopencv_generated_func_tab.h"
1201 {"createTrackbar", pycvCreateTrackbar, METH_VARARGS, "createTrackbar(trackbarName, windowName, value, count, onChange) -> None"},
1202 {"setMouseCallback", (PyCFunction)pycvSetMouseCallback, METH_VARARGS | METH_KEYWORDS, "setMouseCallback(windowName, onMouse [, param]) -> None"},
1206 /************************************************************************/
1209 static int to_ok(PyTypeObject *to)
1211 to->tp_alloc = PyType_GenericAlloc;
1212 to->tp_new = PyType_GenericNew;
1213 to->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
1214 return (PyType_Ready(to) == 0);
1218 #if PY_MAJOR_VERSION >= 3
1219 extern "C" CV_EXPORTS PyObject* PyInit_cv2();
1220 static struct PyModuleDef cv2_moduledef =
1222 PyModuleDef_HEAD_INIT,
1224 "Python wrapper for OpenCV.",
1225 -1, /* size of per-interpreter state of the module,
1226 or -1 if the module keeps state in global variables. */
1230 PyObject* PyInit_cv2()
1232 extern "C" CV_EXPORTS void initcv2();
1239 #include "pyopencv_generated_type_reg.h"
1241 #if PY_MAJOR_VERSION >= 3
1242 PyObject* m = PyModule_Create(&cv2_moduledef);
1244 PyObject* m = Py_InitModule(MODULESTR, methods);
1246 PyObject* d = PyModule_GetDict(m);
1248 PyDict_SetItemString(d, "__version__", PyString_FromString(CV_VERSION));
1250 opencv_error = PyErr_NewException((char*)MODULESTR".error", NULL, NULL);
1251 PyDict_SetItemString(d, "error", opencv_error);
1253 #define PUBLISH(I) PyDict_SetItemString(d, #I, PyInt_FromLong(I))
1254 //#define PUBLISHU(I) PyDict_SetItemString(d, #I, PyLong_FromUnsignedLong(I))
1255 #define PUBLISH2(I, value) PyDict_SetItemString(d, #I, PyLong_FromLong(value))
1293 #include "pyopencv_generated_const_reg.h"
1294 #if PY_MAJOR_VERSION >= 3