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;
87 using cv::softcascade::ChannelFeatureBuilder;
89 typedef std::vector<uchar> vector_uchar;
90 typedef std::vector<char> vector_char;
91 typedef std::vector<int> vector_int;
92 typedef std::vector<float> vector_float;
93 typedef std::vector<double> vector_double;
94 typedef std::vector<Point> vector_Point;
95 typedef std::vector<Point2f> vector_Point2f;
96 typedef std::vector<Vec2f> vector_Vec2f;
97 typedef std::vector<Vec3f> vector_Vec3f;
98 typedef std::vector<Vec4f> vector_Vec4f;
99 typedef std::vector<Vec6f> vector_Vec6f;
100 typedef std::vector<Vec4i> vector_Vec4i;
101 typedef std::vector<Rect> vector_Rect;
102 typedef std::vector<KeyPoint> vector_KeyPoint;
103 typedef std::vector<Mat> vector_Mat;
104 typedef std::vector<DMatch> vector_DMatch;
105 typedef std::vector<String> vector_String;
106 typedef std::vector<Scalar> vector_Scalar;
108 typedef std::vector<std::vector<char> > vector_vector_char;
109 typedef std::vector<std::vector<Point> > vector_vector_Point;
110 typedef std::vector<std::vector<Point2f> > vector_vector_Point2f;
111 typedef std::vector<std::vector<Point3f> > vector_vector_Point3f;
112 typedef std::vector<std::vector<DMatch> > vector_vector_DMatch;
114 typedef cv::softcascade::ChannelFeatureBuilder softcascade_ChannelFeatureBuilder;
116 typedef SimpleBlobDetector::Params SimpleBlobDetector_Params;
118 typedef cvflann::flann_distance_t cvflann_flann_distance_t;
119 typedef cvflann::flann_algorithm_t cvflann_flann_algorithm_t;
122 static PyObject* failmsgp(const char *fmt, ...)
128 vsnprintf(str, sizeof(str), fmt, ap);
131 PyErr_SetString(PyExc_TypeError, str);
135 class NumpyAllocator : public MatAllocator
138 NumpyAllocator() { stdAllocator = Mat::getStdAllocator(); }
141 UMatData* allocate(PyObject* o, int dims, const int* sizes, int type, size_t* step) const
143 UMatData* u = new UMatData(this);
144 u->data = u->origdata = (uchar*)PyArray_DATA((PyArrayObject*) o);
145 npy_intp* _strides = PyArray_STRIDES((PyArrayObject*) o);
146 for( int i = 0; i < dims - 1; i++ )
147 step[i] = (size_t)_strides[i];
148 step[dims-1] = CV_ELEM_SIZE(type);
149 u->size = sizes[0]*step[0];
154 UMatData* allocate(int dims0, const int* sizes, int type, void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const
158 CV_Error(Error::StsAssert, "The data should normally be NULL!");
159 // probably this is safe to do in such extreme case
160 return stdAllocator->allocate(dims0, sizes, type, data, step, flags, usageFlags);
164 int depth = CV_MAT_DEPTH(type);
165 int cn = CV_MAT_CN(type);
166 const int f = (int)(sizeof(size_t)/8);
167 int typenum = depth == CV_8U ? NPY_UBYTE : depth == CV_8S ? NPY_BYTE :
168 depth == CV_16U ? NPY_USHORT : depth == CV_16S ? NPY_SHORT :
169 depth == CV_32S ? NPY_INT : depth == CV_32F ? NPY_FLOAT :
170 depth == CV_64F ? NPY_DOUBLE : f*NPY_ULONGLONG + (f^1)*NPY_UINT;
172 cv::AutoBuffer<npy_intp> _sizes(dims + 1);
173 for( i = 0; i < dims; i++ )
174 _sizes[i] = sizes[i];
177 PyObject* o = PyArray_SimpleNew(dims, _sizes, typenum);
179 CV_Error_(Error::StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims));
180 return allocate(o, dims0, sizes, type, step);
183 bool allocate(UMatData* u, int accessFlags, UMatUsageFlags usageFlags) const
185 return stdAllocator->allocate(u, accessFlags, usageFlags);
188 void deallocate(UMatData* u) const
193 PyObject* o = (PyObject*)u->userdata;
199 const MatAllocator* stdAllocator;
202 NumpyAllocator g_numpyAllocator;
205 template<typename T> static
206 bool pyopencv_to(PyObject* obj, T& p, const char* name = "<unknown>");
208 template<typename T> static
209 PyObject* pyopencv_from(const T& src);
211 enum { ARG_NONE = 0, ARG_MAT = 1, ARG_SCALAR = 2 };
213 // special case, when the convertor needs full ArgInfo structure
214 static bool pyopencv_to(PyObject* o, Mat& m, const ArgInfo info)
217 if(!o || o == Py_None)
220 m.allocator = &g_numpyAllocator;
226 double v[] = {PyInt_AsLong((PyObject*)o), 0., 0., 0.};
227 m = Mat(4, 1, CV_64F, v).clone();
230 if( PyFloat_Check(o) )
232 double v[] = {PyFloat_AsDouble((PyObject*)o), 0., 0., 0.};
233 m = Mat(4, 1, CV_64F, v).clone();
236 if( PyTuple_Check(o) )
238 int i, sz = (int)PyTuple_Size((PyObject*)o);
239 m = Mat(sz, 1, CV_64F);
240 for( i = 0; i < sz; i++ )
242 PyObject* oi = PyTuple_GET_ITEM(o, i);
243 if( PyInt_Check(oi) )
244 m.at<double>(i) = (double)PyInt_AsLong(oi);
245 else if( PyFloat_Check(oi) )
246 m.at<double>(i) = (double)PyFloat_AsDouble(oi);
249 failmsg("%s is not a numerical tuple", info.name);
257 if( !PyArray_Check(o) )
259 failmsg("%s is not a numpy array, neither a scalar", info.name);
263 PyArrayObject* oarr = (PyArrayObject*) o;
265 bool needcopy = false, needcast = false;
266 int typenum = PyArray_TYPE(oarr), new_typenum = typenum;
267 int type = typenum == NPY_UBYTE ? CV_8U :
268 typenum == NPY_BYTE ? CV_8S :
269 typenum == NPY_USHORT ? CV_16U :
270 typenum == NPY_SHORT ? CV_16S :
271 typenum == NPY_INT ? CV_32S :
272 typenum == NPY_INT32 ? CV_32S :
273 typenum == NPY_FLOAT ? CV_32F :
274 typenum == NPY_DOUBLE ? CV_64F : -1;
278 if( typenum == NPY_INT64 || typenum == NPY_UINT64 || type == NPY_LONG )
280 needcopy = needcast = true;
281 new_typenum = NPY_INT;
286 failmsg("%s data type = %d is not supported", info.name, typenum);
292 const int CV_MAX_DIM = 32;
295 int ndims = PyArray_NDIM(oarr);
296 if(ndims >= CV_MAX_DIM)
298 failmsg("%s dimensionality (=%d) is too high", info.name, ndims);
302 int size[CV_MAX_DIM+1];
303 size_t step[CV_MAX_DIM+1];
304 size_t elemsize = CV_ELEM_SIZE1(type);
305 const npy_intp* _sizes = PyArray_DIMS(oarr);
306 const npy_intp* _strides = PyArray_STRIDES(oarr);
307 bool ismultichannel = ndims == 3 && _sizes[2] <= CV_CN_MAX;
309 for( int i = ndims-1; i >= 0 && !needcopy; i-- )
311 // these checks handle cases of
312 // a) multi-dimensional (ndims > 2) arrays, as well as simpler 1- and 2-dimensional cases
313 // b) transposed arrays, where _strides[] elements go in non-descending order
314 // c) flipped arrays, where some of _strides[] elements are negative
315 if( (i == ndims-1 && (size_t)_strides[i] != elemsize) ||
316 (i < ndims-1 && _strides[i] < _strides[i+1]) )
320 if( ismultichannel && _strides[1] != (npy_intp)elemsize*_sizes[2] )
327 failmsg("Layout of the output array %s is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)", info.name);
332 o = PyArray_Cast(oarr, new_typenum);
333 oarr = (PyArrayObject*) o;
336 oarr = PyArray_GETCONTIGUOUS(oarr);
337 o = (PyObject*) oarr;
340 _strides = PyArray_STRIDES(oarr);
343 for(int i = 0; i < ndims; i++)
345 size[i] = (int)_sizes[i];
346 step[i] = (size_t)_strides[i];
349 // handle degenerate case
352 step[ndims] = elemsize;
359 type |= CV_MAKETYPE(0, size[2]);
362 if( ndims > 2 && !allowND )
364 failmsg("%s has more than 2 dimensions", info.name);
368 m = Mat(ndims, size, type, PyArray_DATA(oarr), step);
369 m.u = g_numpyAllocator.allocate(o, ndims, size, type, step);
376 m.allocator = &g_numpyAllocator;
382 PyObject* pyopencv_from(const Mat& m)
386 Mat temp, *p = (Mat*)&m;
387 if(!p->u || p->allocator != &g_numpyAllocator)
389 temp.allocator = &g_numpyAllocator;
390 ERRWRAP2(m.copyTo(temp));
393 PyObject* o = (PyObject*)p->u->userdata;
399 bool pyopencv_to(PyObject *o, Scalar& s, const char *name)
401 if(!o || o == Py_None)
403 if (PySequence_Check(o)) {
404 PyObject *fi = PySequence_Fast(o, name);
407 if (4 < PySequence_Fast_GET_SIZE(fi))
409 failmsg("Scalar value for argument '%s' is longer than 4", name);
412 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
413 PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
414 if (PyFloat_Check(item) || PyInt_Check(item)) {
415 s[(int)i] = PyFloat_AsDouble(item);
417 failmsg("Scalar value for argument '%s' is not numeric", name);
423 if (PyFloat_Check(o) || PyInt_Check(o)) {
424 s[0] = PyFloat_AsDouble(o);
426 failmsg("Scalar value for argument '%s' is not numeric", name);
434 PyObject* pyopencv_from(const Scalar& src)
436 return Py_BuildValue("(dddd)", src[0], src[1], src[2], src[3]);
440 PyObject* pyopencv_from(const bool& value)
442 return PyBool_FromLong(value);
446 bool pyopencv_to(PyObject* obj, bool& value, const char* name)
449 if(!obj || obj == Py_None)
451 int _val = PyObject_IsTrue(obj);
459 PyObject* pyopencv_from(const size_t& value)
461 return PyLong_FromSize_t(value);
465 bool pyopencv_to(PyObject* obj, size_t& value, const char* name)
468 if(!obj || obj == Py_None)
470 value = (int)PyLong_AsUnsignedLong(obj);
471 return value != (size_t)-1 || !PyErr_Occurred();
475 PyObject* pyopencv_from(const int& value)
477 return PyInt_FromLong(value);
481 PyObject* pyopencv_from(const cvflann_flann_algorithm_t& value)
483 return PyInt_FromLong(int(value));
487 PyObject* pyopencv_from(const cvflann_flann_distance_t& value)
489 return PyInt_FromLong(int(value));
493 bool pyopencv_to(PyObject* obj, int& value, const char* name)
496 if(!obj || obj == Py_None)
499 value = (int)PyInt_AsLong(obj);
500 else if(PyLong_Check(obj))
501 value = (int)PyLong_AsLong(obj);
504 return value != -1 || !PyErr_Occurred();
508 PyObject* pyopencv_from(const uchar& value)
510 return PyInt_FromLong(value);
514 bool pyopencv_to(PyObject* obj, uchar& value, const char* name)
517 if(!obj || obj == Py_None)
519 int ivalue = (int)PyInt_AsLong(obj);
520 value = cv::saturate_cast<uchar>(ivalue);
521 return ivalue != -1 || !PyErr_Occurred();
525 PyObject* pyopencv_from(const double& value)
527 return PyFloat_FromDouble(value);
531 bool pyopencv_to(PyObject* obj, double& value, const char* name)
534 if(!obj || obj == Py_None)
536 if(!!PyInt_CheckExact(obj))
537 value = (double)PyInt_AS_LONG(obj);
539 value = PyFloat_AsDouble(obj);
540 return !PyErr_Occurred();
544 PyObject* pyopencv_from(const float& value)
546 return PyFloat_FromDouble(value);
550 bool pyopencv_to(PyObject* obj, float& value, const char* name)
553 if(!obj || obj == Py_None)
555 if(!!PyInt_CheckExact(obj))
556 value = (float)PyInt_AS_LONG(obj);
558 value = (float)PyFloat_AsDouble(obj);
559 return !PyErr_Occurred();
563 PyObject* pyopencv_from(const int64& value)
565 return PyLong_FromLongLong(value);
569 PyObject* pyopencv_from(const String& value)
571 return PyString_FromString(value.empty() ? "" : value.c_str());
575 bool pyopencv_to(PyObject* obj, String& value, const char* name)
578 if(!obj || obj == Py_None)
580 char* str = PyString_AsString(obj);
588 bool pyopencv_to(PyObject* obj, Size& sz, const char* name)
591 if(!obj || obj == Py_None)
593 return PyArg_ParseTuple(obj, "ii", &sz.width, &sz.height) > 0;
597 PyObject* pyopencv_from(const Size& sz)
599 return Py_BuildValue("(ii)", sz.width, sz.height);
603 bool pyopencv_to(PyObject* obj, Rect& r, const char* name)
606 if(!obj || obj == Py_None)
608 return PyArg_ParseTuple(obj, "iiii", &r.x, &r.y, &r.width, &r.height) > 0;
612 PyObject* pyopencv_from(const Rect& r)
614 return Py_BuildValue("(iiii)", r.x, r.y, r.width, r.height);
618 bool pyopencv_to(PyObject* obj, Range& r, const char* name)
621 if(!obj || obj == Py_None)
623 if(PyObject_Size(obj) == 0)
628 return PyArg_ParseTuple(obj, "ii", &r.start, &r.end) > 0;
632 PyObject* pyopencv_from(const Range& r)
634 return Py_BuildValue("(ii)", r.start, r.end);
638 bool pyopencv_to(PyObject* obj, Point& p, const char* name)
641 if(!obj || obj == Py_None)
643 if(!!PyComplex_CheckExact(obj))
645 Py_complex c = PyComplex_AsCComplex(obj);
646 p.x = saturate_cast<int>(c.real);
647 p.y = saturate_cast<int>(c.imag);
650 return PyArg_ParseTuple(obj, "ii", &p.x, &p.y) > 0;
654 bool pyopencv_to(PyObject* obj, Point2f& p, const char* name)
657 if(!obj || obj == Py_None)
659 if(!!PyComplex_CheckExact(obj))
661 Py_complex c = PyComplex_AsCComplex(obj);
662 p.x = saturate_cast<float>(c.real);
663 p.y = saturate_cast<float>(c.imag);
666 return PyArg_ParseTuple(obj, "ff", &p.x, &p.y) > 0;
670 bool pyopencv_to(PyObject* obj, Point2d& p, const char* name)
673 if(!obj || obj == Py_None)
675 if(!!PyComplex_CheckExact(obj))
677 Py_complex c = PyComplex_AsCComplex(obj);
678 p.x = saturate_cast<double>(c.real);
679 p.y = saturate_cast<double>(c.imag);
682 return PyArg_ParseTuple(obj, "dd", &p.x, &p.y) > 0;
687 PyObject* pyopencv_from(const Point& p)
689 return Py_BuildValue("(ii)", p.x, p.y);
693 PyObject* pyopencv_from(const Point2f& p)
695 return Py_BuildValue("(dd)", p.x, p.y);
699 bool pyopencv_to(PyObject* obj, Vec3d& v, const char* name)
704 return PyArg_ParseTuple(obj, "ddd", &v[0], &v[1], &v[2]) > 0;
708 PyObject* pyopencv_from(const Vec3d& v)
710 return Py_BuildValue("(ddd)", v[0], v[1], v[2]);
714 PyObject* pyopencv_from(const Vec2d& v)
716 return Py_BuildValue("(dd)", v[0], v[1]);
720 PyObject* pyopencv_from(const Point2d& p)
722 return Py_BuildValue("(dd)", p.x, p.y);
725 template<typename _Tp> struct pyopencvVecConverter
727 static bool to(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
729 typedef typename DataType<_Tp>::channel_type _Cp;
730 if(!obj || obj == Py_None)
732 if (PyArray_Check(obj))
735 pyopencv_to(obj, m, info);
738 if (!PySequence_Check(obj))
740 PyObject *seq = PySequence_Fast(obj, info.name);
743 int i, j, n = (int)PySequence_Fast_GET_SIZE(seq);
746 int type = DataType<_Tp>::type;
747 int depth = CV_MAT_DEPTH(type), channels = CV_MAT_CN(type);
748 PyObject** items = PySequence_Fast_ITEMS(seq);
750 for( i = 0; i < n; i++ )
752 PyObject* item = items[i];
754 PyObject** items_i = &item;
755 _Cp* data = (_Cp*)&value[i];
757 if( channels == 2 && PyComplex_CheckExact(item) )
759 Py_complex c = PyComplex_AsCComplex(obj);
760 data[0] = saturate_cast<_Cp>(c.real);
761 data[1] = saturate_cast<_Cp>(c.imag);
766 if( PyArray_Check(item))
769 pyopencv_to(item, src, info);
770 if( src.dims != 2 || src.channels() != 1 ||
771 ((src.cols != 1 || src.rows != channels) &&
772 (src.cols != channels || src.rows != 1)))
774 Mat dst(src.rows, src.cols, depth, data);
775 src.convertTo(dst, type);
776 if( dst.data != (uchar*)data )
781 seq_i = PySequence_Fast(item, info.name);
782 if( !seq_i || (int)PySequence_Fast_GET_SIZE(seq_i) != channels )
787 items_i = PySequence_Fast_ITEMS(seq_i);
790 for( j = 0; j < channels; j++ )
792 PyObject* item_ij = items_i[j];
793 if( PyInt_Check(item_ij))
795 int v = (int)PyInt_AsLong(item_ij);
796 if( v == -1 && PyErr_Occurred() )
798 data[j] = saturate_cast<_Cp>(v);
800 else if( PyLong_Check(item_ij))
802 int v = (int)PyLong_AsLong(item_ij);
803 if( v == -1 && PyErr_Occurred() )
805 data[j] = saturate_cast<_Cp>(v);
807 else if( PyFloat_Check(item_ij))
809 double v = PyFloat_AsDouble(item_ij);
810 if( PyErr_Occurred() )
812 data[j] = saturate_cast<_Cp>(v);
825 static PyObject* from(const std::vector<_Tp>& value)
828 return PyTuple_New(0);
829 Mat src((int)value.size(), DataType<_Tp>::channels, DataType<_Tp>::depth, (uchar*)&value[0]);
830 return pyopencv_from(src);
834 template<typename _Tp>
835 bool pyopencv_to(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
837 return pyopencvVecConverter<_Tp>::to(obj, value, info);
840 template<typename _Tp>
841 PyObject* pyopencv_from(const std::vector<_Tp>& value)
843 return pyopencvVecConverter<_Tp>::from(value);
846 template<typename _Tp> static inline bool pyopencv_to_generic_vec(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
848 if(!obj || obj == Py_None)
850 if (!PySequence_Check(obj))
852 PyObject *seq = PySequence_Fast(obj, info.name);
855 int i, n = (int)PySequence_Fast_GET_SIZE(seq);
858 PyObject** items = PySequence_Fast_ITEMS(seq);
860 for( i = 0; i < n; i++ )
862 PyObject* item = items[i];
863 if(!pyopencv_to(item, value[i], info))
870 template<typename _Tp> static inline PyObject* pyopencv_from_generic_vec(const std::vector<_Tp>& value)
872 int i, n = (int)value.size();
873 PyObject* seq = PyList_New(n);
874 for( i = 0; i < n; i++ )
876 PyObject* item = pyopencv_from(value[i]);
879 PyList_SET_ITEM(seq, i, item);
890 template<typename _Tp> struct pyopencvVecConverter<std::vector<_Tp> >
892 static bool to(PyObject* obj, std::vector<std::vector<_Tp> >& value, const ArgInfo info)
894 return pyopencv_to_generic_vec(obj, value, info);
897 static PyObject* from(const std::vector<std::vector<_Tp> >& value)
899 return pyopencv_from_generic_vec(value);
903 template<> struct pyopencvVecConverter<Mat>
905 static bool to(PyObject* obj, std::vector<Mat>& value, const ArgInfo info)
907 return pyopencv_to_generic_vec(obj, value, info);
910 static PyObject* from(const std::vector<Mat>& value)
912 return pyopencv_from_generic_vec(value);
916 template<> struct pyopencvVecConverter<KeyPoint>
918 static bool to(PyObject* obj, std::vector<KeyPoint>& value, const ArgInfo info)
920 return pyopencv_to_generic_vec(obj, value, info);
923 static PyObject* from(const std::vector<KeyPoint>& value)
925 return pyopencv_from_generic_vec(value);
929 template<> struct pyopencvVecConverter<DMatch>
931 static bool to(PyObject* obj, std::vector<DMatch>& value, const ArgInfo info)
933 return pyopencv_to_generic_vec(obj, value, info);
936 static PyObject* from(const std::vector<DMatch>& value)
938 return pyopencv_from_generic_vec(value);
942 template<> struct pyopencvVecConverter<String>
944 static bool to(PyObject* obj, std::vector<String>& value, const ArgInfo info)
946 return pyopencv_to_generic_vec(obj, value, info);
949 static PyObject* from(const std::vector<String>& value)
951 return pyopencv_from_generic_vec(value);
956 bool pyopencv_to(PyObject *obj, TermCriteria& dst, const char *name)
961 return PyArg_ParseTuple(obj, "iid", &dst.type, &dst.maxCount, &dst.epsilon) > 0;
965 PyObject* pyopencv_from(const TermCriteria& src)
967 return Py_BuildValue("(iid)", src.type, src.maxCount, src.epsilon);
971 bool pyopencv_to(PyObject *obj, RotatedRect& dst, const char *name)
976 return PyArg_ParseTuple(obj, "(ff)(ff)f", &dst.center.x, &dst.center.y, &dst.size.width, &dst.size.height, &dst.angle) > 0;
980 PyObject* pyopencv_from(const RotatedRect& src)
982 return Py_BuildValue("((ff)(ff)f)", src.center.x, src.center.y, src.size.width, src.size.height, src.angle);
986 PyObject* pyopencv_from(const Moments& m)
988 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}",
989 "m00", m.m00, "m10", m.m10, "m01", m.m01,
990 "m20", m.m20, "m11", m.m11, "m02", m.m02,
991 "m30", m.m30, "m21", m.m21, "m12", m.m12, "m03", m.m03,
992 "mu20", m.mu20, "mu11", m.mu11, "mu02", m.mu02,
993 "mu30", m.mu30, "mu21", m.mu21, "mu12", m.mu12, "mu03", m.mu03,
994 "nu20", m.nu20, "nu11", m.nu11, "nu02", m.nu02,
995 "nu30", m.nu30, "nu21", m.nu21, "nu12", m.nu12, "nu03", m.nu03);
999 bool pyopencv_to(PyObject *o, cv::flann::IndexParams& p, const char *name)
1003 PyObject* key = NULL;
1004 PyObject* item = NULL;
1007 if(PyDict_Check(o)) {
1008 while(PyDict_Next(o, &pos, &key, &item)) {
1009 if( !PyString_Check(key) ) {
1014 String k = PyString_AsString(key);
1015 if( PyString_Check(item) )
1017 const char* value = PyString_AsString(item);
1018 p.setString(k, value);
1020 else if( !!PyBool_Check(item) )
1021 p.setBool(k, item == Py_True);
1022 else if( PyInt_Check(item) )
1024 int value = (int)PyInt_AsLong(item);
1025 if( strcmp(k.c_str(), "algorithm") == 0 )
1026 p.setAlgorithm(value);
1030 else if( PyFloat_Check(item) )
1032 double value = PyFloat_AsDouble(item);
1033 p.setDouble(k, value);
1043 return ok && !PyErr_Occurred();
1047 bool pyopencv_to(PyObject* obj, cv::flann::SearchParams & value, const char * name)
1049 return pyopencv_to<cv::flann::IndexParams>(obj, value, name);
1052 template <typename T>
1053 bool pyopencv_to(PyObject *o, Ptr<T>& p, const char *name)
1056 return pyopencv_to(o, *p, name);
1060 bool pyopencv_to(PyObject *o, cvflann::flann_distance_t& dist, const char *name)
1063 bool ok = pyopencv_to(o, d, name);
1064 dist = (cvflann::flann_distance_t)d;
1069 ////////////////////////////////////////////////////////////////////////////////////////////////////
1070 // TODO: REMOVE used only by ml wrapper
1073 bool pyopencv_to(PyObject *obj, CvTermCriteria& dst, const char *name)
1078 return PyArg_ParseTuple(obj, "iid", &dst.type, &dst.max_iter, &dst.epsilon) > 0;
1082 bool pyopencv_to(PyObject* obj, CvSlice& r, const char* name)
1085 if(!obj || obj == Py_None)
1087 if(PyObject_Size(obj) == 0)
1092 return PyArg_ParseTuple(obj, "ii", &r.start_index, &r.end_index) > 0;
1096 PyObject* pyopencv_from(CvDTreeNode* const & node)
1098 double value = node->value;
1099 int ivalue = cvRound(value);
1100 return value == ivalue ? PyInt_FromLong(ivalue) : PyFloat_FromDouble(value);
1103 ////////////////////////////////////////////////////////////////////////////////////////////////////
1105 static void OnMouse(int event, int x, int y, int flags, void* param)
1107 PyGILState_STATE gstate;
1108 gstate = PyGILState_Ensure();
1110 PyObject *o = (PyObject*)param;
1111 PyObject *args = Py_BuildValue("iiiiO", event, x, y, flags, PyTuple_GetItem(o, 1));
1113 PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL);
1119 PyGILState_Release(gstate);
1122 static PyObject *pycvSetMouseCallback(PyObject*, PyObject *args, PyObject *kw)
1124 const char *keywords[] = { "window_name", "on_mouse", "param", NULL };
1127 PyObject *param = NULL;
1129 if (!PyArg_ParseTupleAndKeywords(args, kw, "sO|O", (char**)keywords, &name, &on_mouse, ¶m))
1131 if (!PyCallable_Check(on_mouse)) {
1132 PyErr_SetString(PyExc_TypeError, "on_mouse must be callable");
1135 if (param == NULL) {
1138 ERRWRAP2(setMouseCallback(name, OnMouse, Py_BuildValue("OO", on_mouse, param)));
1142 static void OnChange(int pos, void *param)
1144 PyGILState_STATE gstate;
1145 gstate = PyGILState_Ensure();
1147 PyObject *o = (PyObject*)param;
1148 PyObject *args = Py_BuildValue("(i)", pos);
1149 PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL);
1153 PyGILState_Release(gstate);
1156 static PyObject *pycvCreateTrackbar(PyObject*, PyObject *args)
1158 PyObject *on_change;
1159 char* trackbar_name;
1161 int *value = new int;
1164 if (!PyArg_ParseTuple(args, "ssiiO", &trackbar_name, &window_name, value, &count, &on_change))
1166 if (!PyCallable_Check(on_change)) {
1167 PyErr_SetString(PyExc_TypeError, "on_change must be callable");
1170 ERRWRAP2(createTrackbar(trackbar_name, window_name, value, count, OnChange, Py_BuildValue("OO", on_change, Py_None)));
1174 ///////////////////////////////////////////////////////////////////////////////////////
1176 static int convert_to_char(PyObject *o, char *dst, const char *name = "no_name")
1178 if (PyString_Check(o) && PyString_Size(o) == 1) {
1179 *dst = PyString_AsString(o)[0];
1183 return failmsg("Expected single character string for argument '%s'", name);
1187 #if PY_MAJOR_VERSION >= 3
1188 #define MKTYPE2(NAME) pyopencv_##NAME##_specials(); if (!to_ok(&pyopencv_##NAME##_Type)) return NULL;
1190 #define MKTYPE2(NAME) pyopencv_##NAME##_specials(); if (!to_ok(&pyopencv_##NAME##_Type)) return
1194 # pragma GCC diagnostic ignored "-Wunused-parameter"
1195 # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
1198 #include "pyopencv_generated_types.h"
1199 #include "pyopencv_generated_funcs.h"
1201 static PyMethodDef methods[] = {
1203 #include "pyopencv_generated_func_tab.h"
1204 {"createTrackbar", pycvCreateTrackbar, METH_VARARGS, "createTrackbar(trackbarName, windowName, value, count, onChange) -> None"},
1205 {"setMouseCallback", (PyCFunction)pycvSetMouseCallback, METH_VARARGS | METH_KEYWORDS, "setMouseCallback(windowName, onMouse [, param]) -> None"},
1209 /************************************************************************/
1212 static int to_ok(PyTypeObject *to)
1214 to->tp_alloc = PyType_GenericAlloc;
1215 to->tp_new = PyType_GenericNew;
1216 to->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
1217 return (PyType_Ready(to) == 0);
1221 #if PY_MAJOR_VERSION >= 3
1222 extern "C" CV_EXPORTS PyObject* PyInit_cv2();
1223 static struct PyModuleDef cv2_moduledef =
1225 PyModuleDef_HEAD_INIT,
1227 "Python wrapper for OpenCV.",
1228 -1, /* size of per-interpreter state of the module,
1229 or -1 if the module keeps state in global variables. */
1233 PyObject* PyInit_cv2()
1235 extern "C" CV_EXPORTS void initcv2();
1242 #include "pyopencv_generated_type_reg.h"
1244 #if PY_MAJOR_VERSION >= 3
1245 PyObject* m = PyModule_Create(&cv2_moduledef);
1247 PyObject* m = Py_InitModule(MODULESTR, methods);
1249 PyObject* d = PyModule_GetDict(m);
1251 PyDict_SetItemString(d, "__version__", PyString_FromString(CV_VERSION));
1253 opencv_error = PyErr_NewException((char*)MODULESTR".error", NULL, NULL);
1254 PyDict_SetItemString(d, "error", opencv_error);
1256 #define PUBLISH(I) PyDict_SetItemString(d, #I, PyInt_FromLong(I))
1257 //#define PUBLISHU(I) PyDict_SetItemString(d, #I, PyLong_FromUnsignedLong(I))
1258 #define PUBLISH2(I, value) PyDict_SetItemString(d, #I, PyLong_FromLong(value))
1296 #include "pyopencv_generated_const_reg.h"
1297 #if PY_MAJOR_VERSION >= 3