CLAHE Python bindings
[profile/ivi/opencv.git] / modules / python / src2 / cv2.cpp
1 #include <Python.h>
2
3 #if !PYTHON_USE_NUMPY
4 #error "The module can only be built if NumPy is available"
5 #endif
6
7 #define MODULESTR "cv2"
8
9 #include "numpy/ndarrayobject.h"
10
11 #include "opencv2/core/core.hpp"
12 #include "opencv2/contrib/contrib.hpp"
13 #include "opencv2/flann/miniflann.hpp"
14 #include "opencv2/imgproc/imgproc.hpp"
15 #include "opencv2/calib3d/calib3d.hpp"
16 #include "opencv2/ml/ml.hpp"
17 #include "opencv2/features2d/features2d.hpp"
18 #include "opencv2/objdetect/objdetect.hpp"
19 #include "opencv2/video/tracking.hpp"
20 #include "opencv2/video/background_segm.hpp"
21 #include "opencv2/photo/photo.hpp"
22 #include "opencv2/highgui/highgui.hpp"
23
24 #include "opencv2/opencv_modules.hpp"
25
26 #ifdef HAVE_OPENCV_NONFREE
27 #  include "opencv2/nonfree/nonfree.hpp"
28 #endif
29
30 using cv::flann::IndexParams;
31 using cv::flann::SearchParams;
32
33 static PyObject* opencv_error = 0;
34
35 static int failmsg(const char *fmt, ...)
36 {
37     char str[1000];
38
39     va_list ap;
40     va_start(ap, fmt);
41     vsnprintf(str, sizeof(str), fmt, ap);
42     va_end(ap);
43
44     PyErr_SetString(PyExc_TypeError, str);
45     return 0;
46 }
47
48 struct ArgInfo
49 {
50     const char * name;
51     bool outputarg;
52     // more fields may be added if necessary
53
54     ArgInfo(const char * name_, bool outputarg_)
55         : name(name_)
56         , outputarg(outputarg_) {}
57
58     // to match with older pyopencv_to function signature
59     operator const char *() const { return name; }
60 };
61
62 class PyAllowThreads
63 {
64 public:
65     PyAllowThreads() : _state(PyEval_SaveThread()) {}
66     ~PyAllowThreads()
67     {
68         PyEval_RestoreThread(_state);
69     }
70 private:
71     PyThreadState* _state;
72 };
73
74 class PyEnsureGIL
75 {
76 public:
77     PyEnsureGIL() : _state(PyGILState_Ensure()) {}
78     ~PyEnsureGIL()
79     {
80         PyGILState_Release(_state);
81     }
82 private:
83     PyGILState_STATE _state;
84 };
85
86 #define ERRWRAP2(expr) \
87 try \
88 { \
89     PyAllowThreads allowThreads; \
90     expr; \
91 } \
92 catch (const cv::Exception &e) \
93 { \
94     PyErr_SetString(opencv_error, e.what()); \
95     return 0; \
96 }
97
98 using namespace cv;
99
100 typedef vector<uchar> vector_uchar;
101 typedef vector<int> vector_int;
102 typedef vector<float> vector_float;
103 typedef vector<double> vector_double;
104 typedef vector<Point> vector_Point;
105 typedef vector<Point2f> vector_Point2f;
106 typedef vector<Vec2f> vector_Vec2f;
107 typedef vector<Vec3f> vector_Vec3f;
108 typedef vector<Vec4f> vector_Vec4f;
109 typedef vector<Vec6f> vector_Vec6f;
110 typedef vector<Vec4i> vector_Vec4i;
111 typedef vector<Rect> vector_Rect;
112 typedef vector<KeyPoint> vector_KeyPoint;
113 typedef vector<Mat> vector_Mat;
114 typedef vector<DMatch> vector_DMatch;
115 typedef vector<string> vector_string;
116 typedef vector<vector<Point> > vector_vector_Point;
117 typedef vector<vector<Point2f> > vector_vector_Point2f;
118 typedef vector<vector<Point3f> > vector_vector_Point3f;
119 typedef vector<vector<DMatch> > vector_vector_DMatch;
120
121 typedef Ptr<Algorithm> Ptr_Algorithm;
122 typedef Ptr<FeatureDetector> Ptr_FeatureDetector;
123 typedef Ptr<DescriptorExtractor> Ptr_DescriptorExtractor;
124 typedef Ptr<Feature2D> Ptr_Feature2D;
125 typedef Ptr<DescriptorMatcher> Ptr_DescriptorMatcher;
126 typedef Ptr<CLAHE> Ptr_CLAHE; 
127
128 typedef SimpleBlobDetector::Params SimpleBlobDetector_Params;
129
130 typedef cvflann::flann_distance_t cvflann_flann_distance_t;
131 typedef cvflann::flann_algorithm_t cvflann_flann_algorithm_t;
132 typedef Ptr<flann::IndexParams> Ptr_flann_IndexParams;
133 typedef Ptr<flann::SearchParams> Ptr_flann_SearchParams;
134
135 typedef Ptr<FaceRecognizer> Ptr_FaceRecognizer;
136 typedef vector<Scalar> vector_Scalar;
137
138 static PyObject* failmsgp(const char *fmt, ...)
139 {
140   char str[1000];
141
142   va_list ap;
143   va_start(ap, fmt);
144   vsnprintf(str, sizeof(str), fmt, ap);
145   va_end(ap);
146
147   PyErr_SetString(PyExc_TypeError, str);
148   return 0;
149 }
150
151 static size_t REFCOUNT_OFFSET = (size_t)&(((PyObject*)0)->ob_refcnt) +
152     (0x12345678 != *(const size_t*)"\x78\x56\x34\x12\0\0\0\0\0")*sizeof(int);
153
154 static inline PyObject* pyObjectFromRefcount(const int* refcount)
155 {
156     return (PyObject*)((size_t)refcount - REFCOUNT_OFFSET);
157 }
158
159 static inline int* refcountFromPyObject(const PyObject* obj)
160 {
161     return (int*)((size_t)obj + REFCOUNT_OFFSET);
162 }
163
164 class NumpyAllocator : public MatAllocator
165 {
166 public:
167     NumpyAllocator() {}
168     ~NumpyAllocator() {}
169
170     void allocate(int dims, const int* sizes, int type, int*& refcount,
171                   uchar*& datastart, uchar*& data, size_t* step)
172     {
173         PyEnsureGIL gil;
174
175         int depth = CV_MAT_DEPTH(type);
176         int cn = CV_MAT_CN(type);
177         const int f = (int)(sizeof(size_t)/8);
178         int typenum = depth == CV_8U ? NPY_UBYTE : depth == CV_8S ? NPY_BYTE :
179                       depth == CV_16U ? NPY_USHORT : depth == CV_16S ? NPY_SHORT :
180                       depth == CV_32S ? NPY_INT : depth == CV_32F ? NPY_FLOAT :
181                       depth == CV_64F ? NPY_DOUBLE : f*NPY_ULONGLONG + (f^1)*NPY_UINT;
182         int i;
183         npy_intp _sizes[CV_MAX_DIM+1];
184         for( i = 0; i < dims; i++ )
185             _sizes[i] = sizes[i];
186         if( cn > 1 )
187         {
188             /*if( _sizes[dims-1] == 1 )
189                 _sizes[dims-1] = cn;
190             else*/
191                 _sizes[dims++] = cn;
192         }
193         PyObject* o = PyArray_SimpleNew(dims, _sizes, typenum);
194         if(!o)
195             CV_Error_(CV_StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims));
196         refcount = refcountFromPyObject(o);
197         npy_intp* _strides = PyArray_STRIDES(o);
198         for( i = 0; i < dims - (cn > 1); i++ )
199             step[i] = (size_t)_strides[i];
200         datastart = data = (uchar*)PyArray_DATA(o);
201     }
202
203     void deallocate(int* refcount, uchar*, uchar*)
204     {
205         PyEnsureGIL gil;
206         if( !refcount )
207             return;
208         PyObject* o = pyObjectFromRefcount(refcount);
209         Py_INCREF(o);
210         Py_DECREF(o);
211     }
212 };
213
214 NumpyAllocator g_numpyAllocator;
215
216 enum { ARG_NONE = 0, ARG_MAT = 1, ARG_SCALAR = 2 };
217
218 // special case, when the convertor needs full ArgInfo structure
219 static int pyopencv_to(const PyObject* o, Mat& m, const ArgInfo info, bool allowND=true)
220 {
221     if(!o || o == Py_None)
222     {
223         if( !m.data )
224             m.allocator = &g_numpyAllocator;
225         return true;
226     }
227
228     if( PyInt_Check(o) )
229     {
230         double v[] = {PyInt_AsLong((PyObject*)o), 0., 0., 0.};
231         m = Mat(4, 1, CV_64F, v).clone();
232         return true;
233     }
234     if( PyFloat_Check(o) )
235     {
236         double v[] = {PyFloat_AsDouble((PyObject*)o), 0., 0., 0.};
237         m = Mat(4, 1, CV_64F, v).clone();
238         return true;
239     }
240     if( PyTuple_Check(o) )
241     {
242         int i, sz = (int)PyTuple_Size((PyObject*)o);
243         m = Mat(sz, 1, CV_64F);
244         for( i = 0; i < sz; i++ )
245         {
246             PyObject* oi = PyTuple_GET_ITEM(o, i);
247             if( PyInt_Check(oi) )
248                 m.at<double>(i) = (double)PyInt_AsLong(oi);
249             else if( PyFloat_Check(oi) )
250                 m.at<double>(i) = (double)PyFloat_AsDouble(oi);
251             else
252             {
253                 failmsg("%s is not a numerical tuple", info.name);
254                 m.release();
255                 return false;
256             }
257         }
258         return true;
259     }
260
261     if( !PyArray_Check(o) )
262     {
263         failmsg("%s is not a numpy array, neither a scalar", info.name);
264         return false;
265     }
266
267     bool needcopy = false, needcast = false;
268     int typenum = PyArray_TYPE(o), new_typenum = typenum;
269     int type = typenum == NPY_UBYTE ? CV_8U :
270                typenum == NPY_BYTE ? CV_8S :
271                typenum == NPY_USHORT ? CV_16U :
272                typenum == NPY_SHORT ? CV_16S :
273                typenum == NPY_INT ? CV_32S :
274                typenum == NPY_INT32 ? CV_32S :
275                typenum == NPY_FLOAT ? CV_32F :
276                typenum == NPY_DOUBLE ? CV_64F : -1;
277
278     if( type < 0 )
279     {
280         if( typenum == NPY_INT64 || typenum == NPY_UINT64 || type == NPY_LONG )
281         {
282             needcopy = needcast = true;
283             new_typenum = NPY_INT;
284             type = CV_32S;
285         }
286         else
287         {
288             failmsg("%s data type = %d is not supported", info.name, typenum);
289             return false;
290         }
291     }
292
293     int ndims = PyArray_NDIM(o);
294     if(ndims >= CV_MAX_DIM)
295     {
296         failmsg("%s dimensionality (=%d) is too high", info.name, ndims);
297         return false;
298     }
299
300     int size[CV_MAX_DIM+1];
301     size_t step[CV_MAX_DIM+1], elemsize = CV_ELEM_SIZE1(type);
302     const npy_intp* _sizes = PyArray_DIMS(o);
303     const npy_intp* _strides = PyArray_STRIDES(o);
304     bool ismultichannel = ndims == 3 && _sizes[2] <= CV_CN_MAX;
305
306     for( int i = ndims-1; i >= 0 && !needcopy; i-- )
307     {
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]) )
314             needcopy = true;
315     }
316
317     if( ismultichannel && _strides[1] != (npy_intp)elemsize*_sizes[2] )
318         needcopy = true;
319
320     if (needcopy)
321     {
322         if (info.outputarg)
323         {
324             failmsg("Layout of the output array %s is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)", info.name);
325             return false;
326         }
327         if( needcast )
328             o = (PyObject*)PyArray_Cast((PyArrayObject*)o, new_typenum);
329         else
330             o = (PyObject*)PyArray_GETCONTIGUOUS((PyArrayObject*)o);
331         _strides = PyArray_STRIDES(o);
332     }
333
334     for(int i = 0; i < ndims; i++)
335     {
336         size[i] = (int)_sizes[i];
337         step[i] = (size_t)_strides[i];
338     }
339
340     // handle degenerate case
341     if( ndims == 0) {
342         size[ndims] = 1;
343         step[ndims] = elemsize;
344         ndims++;
345     }
346
347     if( ismultichannel )
348     {
349         ndims--;
350         type |= CV_MAKETYPE(0, size[2]);
351     }
352
353     if( ndims > 2 && !allowND )
354     {
355         failmsg("%s has more than 2 dimensions", info.name);
356         return false;
357     }
358
359     m = Mat(ndims, size, type, PyArray_DATA(o), step);
360
361     if( m.data )
362     {
363         m.refcount = refcountFromPyObject(o);
364         if (!needcopy)
365         {
366             m.addref(); // protect the original numpy array from deallocation
367                         // (since Mat destructor will decrement the reference counter)
368         }
369     };
370     m.allocator = &g_numpyAllocator;
371
372     return true;
373 }
374
375 static PyObject* pyopencv_from(const Mat& m)
376 {
377     if( !m.data )
378         Py_RETURN_NONE;
379     Mat temp, *p = (Mat*)&m;
380     if(!p->refcount || p->allocator != &g_numpyAllocator)
381     {
382         temp.allocator = &g_numpyAllocator;
383         ERRWRAP2(m.copyTo(temp));
384         p = &temp;
385     }
386     p->addref();
387     return pyObjectFromRefcount(p->refcount);
388 }
389
390 static bool pyopencv_to(PyObject *o, Scalar& s, const char *name = "<unknown>")
391 {
392     if(!o || o == Py_None)
393         return true;
394     if (PySequence_Check(o)) {
395         PyObject *fi = PySequence_Fast(o, name);
396         if (fi == NULL)
397             return false;
398         if (4 < PySequence_Fast_GET_SIZE(fi))
399         {
400             failmsg("Scalar value for argument '%s' is longer than 4", name);
401             return false;
402         }
403         for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
404             PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
405             if (PyFloat_Check(item) || PyInt_Check(item)) {
406                 s[(int)i] = PyFloat_AsDouble(item);
407             } else {
408                 failmsg("Scalar value for argument '%s' is not numeric", name);
409                 return false;
410             }
411         }
412         Py_DECREF(fi);
413     } else {
414         if (PyFloat_Check(o) || PyInt_Check(o)) {
415             s[0] = PyFloat_AsDouble(o);
416         } else {
417             failmsg("Scalar value for argument '%s' is not numeric", name);
418             return false;
419         }
420     }
421     return true;
422 }
423
424 static inline PyObject* pyopencv_from(const Scalar& src)
425 {
426     return Py_BuildValue("(dddd)", src[0], src[1], src[2], src[3]);
427 }
428
429 static PyObject* pyopencv_from(bool value)
430 {
431     return PyBool_FromLong(value);
432 }
433
434 static bool pyopencv_to(PyObject* obj, bool& value, const char* name = "<unknown>")
435 {
436     (void)name;
437     if(!obj || obj == Py_None)
438         return true;
439     int _val = PyObject_IsTrue(obj);
440     if(_val < 0)
441         return false;
442     value = _val > 0;
443     return true;
444 }
445
446 static PyObject* pyopencv_from(size_t value)
447 {
448     return PyLong_FromUnsignedLong((unsigned long)value);
449 }
450
451 static bool pyopencv_to(PyObject* obj, size_t& value, const char* name = "<unknown>")
452 {
453     (void)name;
454     if(!obj || obj == Py_None)
455         return true;
456     value = (int)PyLong_AsUnsignedLong(obj);
457     return value != (size_t)-1 || !PyErr_Occurred();
458 }
459
460 static PyObject* pyopencv_from(int value)
461 {
462     return PyInt_FromLong(value);
463 }
464
465 static PyObject* pyopencv_from(cvflann_flann_algorithm_t value)
466 {
467     return PyInt_FromLong(int(value));
468 }
469
470 static PyObject* pyopencv_from(cvflann_flann_distance_t value)
471 {
472     return PyInt_FromLong(int(value));
473 }
474
475 static bool pyopencv_to(PyObject* obj, int& value, const char* name = "<unknown>")
476 {
477     (void)name;
478     if(!obj || obj == Py_None)
479         return true;
480     if(PyInt_Check(obj))
481         value = (int)PyInt_AsLong(obj);
482     else if(PyLong_Check(obj))
483         value = (int)PyLong_AsLong(obj);
484     else
485         return false;
486     return value != -1 || !PyErr_Occurred();
487 }
488
489 static PyObject* pyopencv_from(uchar value)
490 {
491     return PyInt_FromLong(value);
492 }
493
494 static bool pyopencv_to(PyObject* obj, uchar& value, const char* name = "<unknown>")
495 {
496     (void)name;
497     if(!obj || obj == Py_None)
498         return true;
499     int ivalue = (int)PyInt_AsLong(obj);
500     value = cv::saturate_cast<uchar>(ivalue);
501     return ivalue != -1 || !PyErr_Occurred();
502 }
503
504 static PyObject* pyopencv_from(double value)
505 {
506     return PyFloat_FromDouble(value);
507 }
508
509 static bool pyopencv_to(PyObject* obj, double& value, const char* name = "<unknown>")
510 {
511     (void)name;
512     if(!obj || obj == Py_None)
513         return true;
514     if(!!PyInt_CheckExact(obj))
515         value = (double)PyInt_AS_LONG(obj);
516     else
517         value = PyFloat_AsDouble(obj);
518     return !PyErr_Occurred();
519 }
520
521 static PyObject* pyopencv_from(float value)
522 {
523     return PyFloat_FromDouble(value);
524 }
525
526 static bool pyopencv_to(PyObject* obj, float& value, const char* name = "<unknown>")
527 {
528     (void)name;
529     if(!obj || obj == Py_None)
530         return true;
531     if(!!PyInt_CheckExact(obj))
532         value = (float)PyInt_AS_LONG(obj);
533     else
534         value = (float)PyFloat_AsDouble(obj);
535     return !PyErr_Occurred();
536 }
537
538 static PyObject* pyopencv_from(int64 value)
539 {
540     return PyFloat_FromDouble((double)value);
541 }
542
543 static PyObject* pyopencv_from(const string& value)
544 {
545     return PyString_FromString(value.empty() ? "" : value.c_str());
546 }
547
548 static bool pyopencv_to(PyObject* obj, string& value, const char* name = "<unknown>")
549 {
550     (void)name;
551     if(!obj || obj == Py_None)
552         return true;
553     char* str = PyString_AsString(obj);
554     if(!str)
555         return false;
556     value = string(str);
557     return true;
558 }
559
560 static inline bool pyopencv_to(PyObject* obj, Size& sz, const char* name = "<unknown>")
561 {
562     (void)name;
563     if(!obj || obj == Py_None)
564         return true;
565     return PyArg_ParseTuple(obj, "ii", &sz.width, &sz.height) > 0;
566 }
567
568 static inline PyObject* pyopencv_from(const Size& sz)
569 {
570     return Py_BuildValue("(ii)", sz.width, sz.height);
571 }
572
573 static inline bool pyopencv_to(PyObject* obj, Rect& r, const char* name = "<unknown>")
574 {
575     (void)name;
576     if(!obj || obj == Py_None)
577         return true;
578     return PyArg_ParseTuple(obj, "iiii", &r.x, &r.y, &r.width, &r.height) > 0;
579 }
580
581 static inline PyObject* pyopencv_from(const Rect& r)
582 {
583     return Py_BuildValue("(iiii)", r.x, r.y, r.width, r.height);
584 }
585
586 static inline bool pyopencv_to(PyObject* obj, Range& r, const char* name = "<unknown>")
587 {
588     (void)name;
589     if(!obj || obj == Py_None)
590         return true;
591     if(PyObject_Size(obj) == 0)
592     {
593         r = Range::all();
594         return true;
595     }
596     return PyArg_ParseTuple(obj, "ii", &r.start, &r.end) > 0;
597 }
598
599 static inline PyObject* pyopencv_from(const Range& r)
600 {
601     return Py_BuildValue("(ii)", r.start, r.end);
602 }
603
604 static inline bool pyopencv_to(PyObject* obj, CvSlice& r, const char* name = "<unknown>")
605 {
606     (void)name;
607     if(!obj || obj == Py_None)
608         return true;
609     if(PyObject_Size(obj) == 0)
610     {
611         r = CV_WHOLE_SEQ;
612         return true;
613     }
614     return PyArg_ParseTuple(obj, "ii", &r.start_index, &r.end_index) > 0;
615 }
616
617 static inline PyObject* pyopencv_from(const CvSlice& r)
618 {
619     return Py_BuildValue("(ii)", r.start_index, r.end_index);
620 }
621
622 static inline bool pyopencv_to(PyObject* obj, Point& p, const char* name = "<unknown>")
623 {
624     (void)name;
625     if(!obj || obj == Py_None)
626         return true;
627     if(!!PyComplex_CheckExact(obj))
628     {
629         Py_complex c = PyComplex_AsCComplex(obj);
630         p.x = saturate_cast<int>(c.real);
631         p.y = saturate_cast<int>(c.imag);
632         return true;
633     }
634     return PyArg_ParseTuple(obj, "ii", &p.x, &p.y) > 0;
635 }
636
637 static inline bool pyopencv_to(PyObject* obj, Point2f& p, const char* name = "<unknown>")
638 {
639     (void)name;
640     if(!obj || obj == Py_None)
641         return true;
642     if(!!PyComplex_CheckExact(obj))
643     {
644         Py_complex c = PyComplex_AsCComplex(obj);
645         p.x = saturate_cast<float>(c.real);
646         p.y = saturate_cast<float>(c.imag);
647         return true;
648     }
649     return PyArg_ParseTuple(obj, "ff", &p.x, &p.y) > 0;
650 }
651
652 static inline PyObject* pyopencv_from(const Point& p)
653 {
654     return Py_BuildValue("(ii)", p.x, p.y);
655 }
656
657 static inline PyObject* pyopencv_from(const Point2f& p)
658 {
659     return Py_BuildValue("(dd)", p.x, p.y);
660 }
661
662 static inline bool pyopencv_to(PyObject* obj, Vec3d& v, const char* name = "<unknown>")
663 {
664     (void)name;
665     if(!obj)
666         return true;
667     return PyArg_ParseTuple(obj, "ddd", &v[0], &v[1], &v[2]) > 0;
668 }
669
670 static inline PyObject* pyopencv_from(const Vec3d& v)
671 {
672     return Py_BuildValue("(ddd)", v[0], v[1], v[2]);
673 }
674
675 static inline PyObject* pyopencv_from(const Point2d& p)
676 {
677     return Py_BuildValue("(dd)", p.x, p.y);
678 }
679
680 template<typename _Tp> struct pyopencvVecConverter
681 {
682     static bool to(PyObject* obj, vector<_Tp>& value, const ArgInfo info)
683     {
684         typedef typename DataType<_Tp>::channel_type _Cp;
685         if(!obj || obj == Py_None)
686             return true;
687         if (PyArray_Check(obj))
688         {
689             Mat m;
690             pyopencv_to(obj, m, info);
691             m.copyTo(value);
692         }
693         if (!PySequence_Check(obj))
694             return false;
695         PyObject *seq = PySequence_Fast(obj, info.name);
696         if (seq == NULL)
697             return false;
698         int i, j, n = (int)PySequence_Fast_GET_SIZE(seq);
699         value.resize(n);
700
701         int type = DataType<_Tp>::type;
702         int depth = CV_MAT_DEPTH(type), channels = CV_MAT_CN(type);
703         PyObject** items = PySequence_Fast_ITEMS(seq);
704
705         for( i = 0; i < n; i++ )
706         {
707             PyObject* item = items[i];
708             PyObject* seq_i = 0;
709             PyObject** items_i = &item;
710             _Cp* data = (_Cp*)&value[i];
711
712             if( channels == 2 && PyComplex_CheckExact(item) )
713             {
714                 Py_complex c = PyComplex_AsCComplex(obj);
715                 data[0] = saturate_cast<_Cp>(c.real);
716                 data[1] = saturate_cast<_Cp>(c.imag);
717                 continue;
718             }
719             if( channels > 1 )
720             {
721                 if( PyArray_Check(item))
722                 {
723                     Mat src;
724                     pyopencv_to(item, src, info);
725                     if( src.dims != 2 || src.channels() != 1 ||
726                        ((src.cols != 1 || src.rows != channels) &&
727                         (src.cols != channels || src.rows != 1)))
728                         break;
729                     Mat dst(src.rows, src.cols, depth, data);
730                     src.convertTo(dst, type);
731                     if( dst.data != (uchar*)data )
732                         break;
733                     continue;
734                 }
735
736                 seq_i = PySequence_Fast(item, info.name);
737                 if( !seq_i || (int)PySequence_Fast_GET_SIZE(seq_i) != channels )
738                 {
739                     Py_XDECREF(seq_i);
740                     break;
741                 }
742                 items_i = PySequence_Fast_ITEMS(seq_i);
743             }
744
745             for( j = 0; j < channels; j++ )
746             {
747                 PyObject* item_ij = items_i[j];
748                 if( PyInt_Check(item_ij))
749                 {
750                     int v = (int)PyInt_AsLong(item_ij);
751                     if( v == -1 && PyErr_Occurred() )
752                         break;
753                     data[j] = saturate_cast<_Cp>(v);
754                 }
755                 else if( PyLong_Check(item_ij))
756                 {
757                     int v = (int)PyLong_AsLong(item_ij);
758                     if( v == -1 && PyErr_Occurred() )
759                         break;
760                     data[j] = saturate_cast<_Cp>(v);
761                 }
762                 else if( PyFloat_Check(item_ij))
763                 {
764                     double v = PyFloat_AsDouble(item_ij);
765                     if( PyErr_Occurred() )
766                         break;
767                     data[j] = saturate_cast<_Cp>(v);
768                 }
769                 else
770                     break;
771             }
772             Py_XDECREF(seq_i);
773             if( j < channels )
774                 break;
775         }
776         Py_DECREF(seq);
777         return i == n;
778     }
779
780     static PyObject* from(const vector<_Tp>& value)
781     {
782         if(value.empty())
783             return PyTuple_New(0);
784         Mat src((int)value.size(), DataType<_Tp>::channels, DataType<_Tp>::depth, (uchar*)&value[0]);
785         return pyopencv_from(src);
786     }
787 };
788
789
790 template<typename _Tp> static inline bool pyopencv_to(PyObject* obj, vector<_Tp>& value, const ArgInfo info)
791 {
792     return pyopencvVecConverter<_Tp>::to(obj, value, info);
793 }
794
795 template<typename _Tp> static inline PyObject* pyopencv_from(const vector<_Tp>& value)
796 {
797     return pyopencvVecConverter<_Tp>::from(value);
798 }
799
800 static PyObject* pyopencv_from(const KeyPoint&);
801 static PyObject* pyopencv_from(const DMatch&);
802
803 template<typename _Tp> static inline bool pyopencv_to_generic_vec(PyObject* obj, vector<_Tp>& value, const ArgInfo info)
804 {
805     if(!obj || obj == Py_None)
806        return true;
807     if (!PySequence_Check(obj))
808         return false;
809     PyObject *seq = PySequence_Fast(obj, info.name);
810     if (seq == NULL)
811         return false;
812     int i, n = (int)PySequence_Fast_GET_SIZE(seq);
813     value.resize(n);
814
815     PyObject** items = PySequence_Fast_ITEMS(seq);
816
817     for( i = 0; i < n; i++ )
818     {
819         PyObject* item = items[i];
820         if(!pyopencv_to(item, value[i], info))
821             break;
822     }
823     Py_DECREF(seq);
824     return i == n;
825 }
826
827 template<typename _Tp> static inline PyObject* pyopencv_from_generic_vec(const vector<_Tp>& value)
828 {
829     int i, n = (int)value.size();
830     PyObject* seq = PyList_New(n);
831     for( i = 0; i < n; i++ )
832     {
833         PyObject* item = pyopencv_from(value[i]);
834         if(!item)
835             break;
836         PyList_SET_ITEM(seq, i, item);
837     }
838     if( i < n )
839     {
840         Py_DECREF(seq);
841         return 0;
842     }
843     return seq;
844 }
845
846
847 template<typename _Tp> struct pyopencvVecConverter<vector<_Tp> >
848 {
849     static bool to(PyObject* obj, vector<vector<_Tp> >& value, const char* name="<unknown>")
850     {
851         return pyopencv_to_generic_vec(obj, value, name);
852     }
853
854     static PyObject* from(const vector<vector<_Tp> >& value)
855     {
856         return pyopencv_from_generic_vec(value);
857     }
858 };
859
860 template<> struct pyopencvVecConverter<Mat>
861 {
862     static bool to(PyObject* obj, vector<Mat>& value, const ArgInfo info)
863     {
864         return pyopencv_to_generic_vec(obj, value, info);
865     }
866
867     static PyObject* from(const vector<Mat>& value)
868     {
869         return pyopencv_from_generic_vec(value);
870     }
871 };
872
873 template<> struct pyopencvVecConverter<KeyPoint>
874 {
875     static bool to(PyObject* obj, vector<KeyPoint>& value, const ArgInfo info)
876     {
877         return pyopencv_to_generic_vec(obj, value, info);
878     }
879
880     static PyObject* from(const vector<KeyPoint>& value)
881     {
882         return pyopencv_from_generic_vec(value);
883     }
884 };
885
886 template<> struct pyopencvVecConverter<DMatch>
887 {
888     static bool to(PyObject* obj, vector<DMatch>& value, const ArgInfo info)
889     {
890         return pyopencv_to_generic_vec(obj, value, info);
891     }
892
893     static PyObject* from(const vector<DMatch>& value)
894     {
895         return pyopencv_from_generic_vec(value);
896     }
897 };
898
899 template<> struct pyopencvVecConverter<string>
900 {
901     static bool to(PyObject* obj, vector<string>& value, const ArgInfo info)
902     {
903         return pyopencv_to_generic_vec(obj, value, info);
904     }
905
906     static PyObject* from(const vector<string>& value)
907     {
908         return pyopencv_from_generic_vec(value);
909     }
910 };
911
912
913 static inline bool pyopencv_to(PyObject *obj, CvTermCriteria& dst, const char *name="<unknown>")
914 {
915     (void)name;
916     if(!obj)
917         return true;
918     return PyArg_ParseTuple(obj, "iid", &dst.type, &dst.max_iter, &dst.epsilon) > 0;
919 }
920
921 static inline PyObject* pyopencv_from(const CvTermCriteria& src)
922 {
923     return Py_BuildValue("(iid)", src.type, src.max_iter, src.epsilon);
924 }
925
926 static inline bool pyopencv_to(PyObject *obj, TermCriteria& dst, const char *name="<unknown>")
927 {
928     (void)name;
929     if(!obj)
930         return true;
931     return PyArg_ParseTuple(obj, "iid", &dst.type, &dst.maxCount, &dst.epsilon) > 0;
932 }
933
934 static inline PyObject* pyopencv_from(const TermCriteria& src)
935 {
936     return Py_BuildValue("(iid)", src.type, src.maxCount, src.epsilon);
937 }
938
939 static inline bool pyopencv_to(PyObject *obj, RotatedRect& dst, const char *name="<unknown>")
940 {
941     (void)name;
942     if(!obj)
943         return true;
944     return PyArg_ParseTuple(obj, "(ff)(ff)f", &dst.center.x, &dst.center.y, &dst.size.width, &dst.size.height, &dst.angle) > 0;
945 }
946
947 static inline PyObject* pyopencv_from(const RotatedRect& src)
948 {
949     return Py_BuildValue("((ff)(ff)f)", src.center.x, src.center.y, src.size.width, src.size.height, src.angle);
950 }
951
952 static inline PyObject* pyopencv_from(const Moments& m)
953 {
954     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}",
955                          "m00", m.m00, "m10", m.m10, "m01", m.m01,
956                          "m20", m.m20, "m11", m.m11, "m02", m.m02,
957                          "m30", m.m30, "m21", m.m21, "m12", m.m12, "m03", m.m03,
958                          "mu20", m.mu20, "mu11", m.mu11, "mu02", m.mu02,
959                          "mu30", m.mu30, "mu21", m.mu21, "mu12", m.mu12, "mu03", m.mu03,
960                          "nu20", m.nu20, "nu11", m.nu11, "nu02", m.nu02,
961                          "nu30", m.nu30, "nu21", m.nu21, "nu12", m.nu12, "nu03", m.nu03);
962 }
963
964 static inline PyObject* pyopencv_from(const CvDTreeNode* node)
965 {
966     double value = node->value;
967     int ivalue = cvRound(value);
968     return value == ivalue ? PyInt_FromLong(ivalue) : PyFloat_FromDouble(value);
969 }
970
971 static bool pyopencv_to(PyObject *o, cv::flann::IndexParams& p, const char *name="<unknown>")
972 {
973     (void)name;
974     bool ok = false;
975     PyObject* keys = PyObject_CallMethod(o,(char*)"keys",0);
976     PyObject* values = PyObject_CallMethod(o,(char*)"values",0);
977
978     if( keys && values )
979     {
980         int i, n = (int)PyList_GET_SIZE(keys);
981         for( i = 0; i < n; i++ )
982         {
983             PyObject* key = PyList_GET_ITEM(keys, i);
984             PyObject* item = PyList_GET_ITEM(values, i);
985             if( !PyString_Check(key) )
986                 break;
987             std::string k = PyString_AsString(key);
988             if( PyString_Check(item) )
989             {
990                 const char* value = PyString_AsString(item);
991                 p.setString(k, value);
992             }
993             else if( !!PyBool_Check(item) )
994                 p.setBool(k, item == Py_True);
995             else if( PyInt_Check(item) )
996             {
997                 int value = (int)PyInt_AsLong(item);
998                 if( strcmp(k.c_str(), "algorithm") == 0 )
999                     p.setAlgorithm(value);
1000                 else
1001                     p.setInt(k, value);
1002             }
1003             else if( PyFloat_Check(item) )
1004             {
1005                 double value = PyFloat_AsDouble(item);
1006                 p.setDouble(k, value);
1007             }
1008             else
1009                 break;
1010         }
1011         ok = i == n && !PyErr_Occurred();
1012     }
1013
1014     Py_XDECREF(keys);
1015     Py_XDECREF(values);
1016     return ok;
1017 }
1018
1019 template <class T>
1020 static bool pyopencv_to(PyObject *o, Ptr<T>& p, const char *name="<unknown>")
1021 {
1022     p = new T();
1023     return pyopencv_to(o, *p, name);
1024 }
1025
1026
1027 static bool pyopencv_to(PyObject *o, cvflann::flann_distance_t& dist, const char *name="<unknown>")
1028 {
1029     int d = (int)dist;
1030     bool ok = pyopencv_to(o, d, name);
1031     dist = (cvflann::flann_distance_t)d;
1032     return ok;
1033 }
1034
1035 ////////////////////////////////////////////////////////////////////////////////////////////////////
1036
1037 static void OnMouse(int event, int x, int y, int flags, void* param)
1038 {
1039     PyGILState_STATE gstate;
1040     gstate = PyGILState_Ensure();
1041
1042     PyObject *o = (PyObject*)param;
1043     PyObject *args = Py_BuildValue("iiiiO", event, x, y, flags, PyTuple_GetItem(o, 1));
1044
1045     PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL);
1046     if (r == NULL)
1047         PyErr_Print();
1048     else
1049         Py_DECREF(r);
1050     Py_DECREF(args);
1051     PyGILState_Release(gstate);
1052 }
1053
1054 static PyObject *pycvSetMouseCallback(PyObject*, PyObject *args, PyObject *kw)
1055 {
1056     const char *keywords[] = { "window_name", "on_mouse", "param", NULL };
1057     char* name;
1058     PyObject *on_mouse;
1059     PyObject *param = NULL;
1060
1061     if (!PyArg_ParseTupleAndKeywords(args, kw, "sO|O", (char**)keywords, &name, &on_mouse, &param))
1062         return NULL;
1063     if (!PyCallable_Check(on_mouse)) {
1064         PyErr_SetString(PyExc_TypeError, "on_mouse must be callable");
1065         return NULL;
1066     }
1067     if (param == NULL) {
1068         param = Py_None;
1069     }
1070     ERRWRAP2(cvSetMouseCallback(name, OnMouse, Py_BuildValue("OO", on_mouse, param)));
1071     Py_RETURN_NONE;
1072 }
1073
1074 static void OnChange(int pos, void *param)
1075 {
1076     PyGILState_STATE gstate;
1077     gstate = PyGILState_Ensure();
1078
1079     PyObject *o = (PyObject*)param;
1080     PyObject *args = Py_BuildValue("(i)", pos);
1081     PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL);
1082     if (r == NULL)
1083         PyErr_Print();
1084     Py_DECREF(args);
1085     PyGILState_Release(gstate);
1086 }
1087
1088 static PyObject *pycvCreateTrackbar(PyObject*, PyObject *args)
1089 {
1090     PyObject *on_change;
1091     char* trackbar_name;
1092     char* window_name;
1093     int *value = new int;
1094     int count;
1095
1096     if (!PyArg_ParseTuple(args, "ssiiO", &trackbar_name, &window_name, value, &count, &on_change))
1097         return NULL;
1098     if (!PyCallable_Check(on_change)) {
1099         PyErr_SetString(PyExc_TypeError, "on_change must be callable");
1100         return NULL;
1101     }
1102     ERRWRAP2(cvCreateTrackbar2(trackbar_name, window_name, value, count, OnChange, Py_BuildValue("OO", on_change, Py_None)));
1103     Py_RETURN_NONE;
1104 }
1105
1106 ///////////////////////////////////////////////////////////////////////////////////////
1107
1108 #define MKTYPE2(NAME) pyopencv_##NAME##_specials(); if (!to_ok(&pyopencv_##NAME##_Type)) return
1109
1110 #ifdef __GNUC__
1111 #  pragma GCC diagnostic ignored "-Wunused-parameter"
1112 #  pragma GCC diagnostic ignored "-Wmissing-field-initializers"
1113 #endif
1114
1115 #include "pyopencv_generated_types.h"
1116 #include "pyopencv_generated_funcs.h"
1117
1118 static PyMethodDef methods[] = {
1119
1120 #include "pyopencv_generated_func_tab.h"
1121   {"createTrackbar", pycvCreateTrackbar, METH_VARARGS, "createTrackbar(trackbarName, windowName, value, count, onChange) -> None"},
1122   {"setMouseCallback", (PyCFunction)pycvSetMouseCallback, METH_KEYWORDS, "setMouseCallback(windowName, onMouse [, param]) -> None"},
1123   {NULL, NULL},
1124 };
1125
1126 /************************************************************************/
1127 /* Module init */
1128
1129 static int to_ok(PyTypeObject *to)
1130 {
1131   to->tp_alloc = PyType_GenericAlloc;
1132   to->tp_new = PyType_GenericNew;
1133   to->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
1134   return (PyType_Ready(to) == 0);
1135 }
1136
1137 #include "cv2.cv.hpp"
1138
1139 extern "C"
1140 #if defined WIN32 || defined _WIN32
1141 __declspec(dllexport)
1142 #endif
1143 void initcv2();
1144
1145 void initcv2()
1146 {
1147 #if PYTHON_USE_NUMPY
1148     import_array();
1149 #endif
1150
1151 #if PYTHON_USE_NUMPY
1152 #include "pyopencv_generated_type_reg.h"
1153 #endif
1154
1155   PyObject* m = Py_InitModule(MODULESTR, methods);
1156   PyObject* d = PyModule_GetDict(m);
1157
1158   PyDict_SetItemString(d, "__version__", PyString_FromString(CV_VERSION));
1159
1160   opencv_error = PyErr_NewException((char*)MODULESTR".error", NULL, NULL);
1161   PyDict_SetItemString(d, "error", opencv_error);
1162
1163   PyObject* cv_m = init_cv();
1164
1165   PyDict_SetItemString(d, "cv", cv_m);
1166
1167 #define PUBLISH(I) PyDict_SetItemString(d, #I, PyInt_FromLong(I))
1168 #define PUBLISHU(I) PyDict_SetItemString(d, #I, PyLong_FromUnsignedLong(I))
1169 #define PUBLISH2(I, value) PyDict_SetItemString(d, #I, PyLong_FromLong(value))
1170
1171   PUBLISHU(IPL_DEPTH_8U);
1172   PUBLISHU(IPL_DEPTH_8S);
1173   PUBLISHU(IPL_DEPTH_16U);
1174   PUBLISHU(IPL_DEPTH_16S);
1175   PUBLISHU(IPL_DEPTH_32S);
1176   PUBLISHU(IPL_DEPTH_32F);
1177   PUBLISHU(IPL_DEPTH_64F);
1178
1179   PUBLISH(CV_LOAD_IMAGE_COLOR);
1180   PUBLISH(CV_LOAD_IMAGE_GRAYSCALE);
1181   PUBLISH(CV_LOAD_IMAGE_UNCHANGED);
1182   PUBLISH(CV_HIST_ARRAY);
1183   PUBLISH(CV_HIST_SPARSE);
1184   PUBLISH(CV_8U);
1185   PUBLISH(CV_8UC1);
1186   PUBLISH(CV_8UC2);
1187   PUBLISH(CV_8UC3);
1188   PUBLISH(CV_8UC4);
1189   PUBLISH(CV_8S);
1190   PUBLISH(CV_8SC1);
1191   PUBLISH(CV_8SC2);
1192   PUBLISH(CV_8SC3);
1193   PUBLISH(CV_8SC4);
1194   PUBLISH(CV_16U);
1195   PUBLISH(CV_16UC1);
1196   PUBLISH(CV_16UC2);
1197   PUBLISH(CV_16UC3);
1198   PUBLISH(CV_16UC4);
1199   PUBLISH(CV_16S);
1200   PUBLISH(CV_16SC1);
1201   PUBLISH(CV_16SC2);
1202   PUBLISH(CV_16SC3);
1203   PUBLISH(CV_16SC4);
1204   PUBLISH(CV_32S);
1205   PUBLISH(CV_32SC1);
1206   PUBLISH(CV_32SC2);
1207   PUBLISH(CV_32SC3);
1208   PUBLISH(CV_32SC4);
1209   PUBLISH(CV_32F);
1210   PUBLISH(CV_32FC1);
1211   PUBLISH(CV_32FC2);
1212   PUBLISH(CV_32FC3);
1213   PUBLISH(CV_32FC4);
1214   PUBLISH(CV_64F);
1215   PUBLISH(CV_64FC1);
1216   PUBLISH(CV_64FC2);
1217   PUBLISH(CV_64FC3);
1218   PUBLISH(CV_64FC4);
1219   PUBLISH(CV_NEXT_AROUND_ORG);
1220   PUBLISH(CV_NEXT_AROUND_DST);
1221   PUBLISH(CV_PREV_AROUND_ORG);
1222   PUBLISH(CV_PREV_AROUND_DST);
1223   PUBLISH(CV_NEXT_AROUND_LEFT);
1224   PUBLISH(CV_NEXT_AROUND_RIGHT);
1225   PUBLISH(CV_PREV_AROUND_LEFT);
1226   PUBLISH(CV_PREV_AROUND_RIGHT);
1227
1228   PUBLISH(CV_WINDOW_AUTOSIZE);
1229
1230   PUBLISH(CV_PTLOC_INSIDE);
1231   PUBLISH(CV_PTLOC_ON_EDGE);
1232   PUBLISH(CV_PTLOC_VERTEX);
1233   PUBLISH(CV_PTLOC_OUTSIDE_RECT);
1234
1235   PUBLISH(GC_BGD);
1236   PUBLISH(GC_FGD);
1237   PUBLISH(GC_PR_BGD);
1238   PUBLISH(GC_PR_FGD);
1239   PUBLISH(GC_INIT_WITH_RECT);
1240   PUBLISH(GC_INIT_WITH_MASK);
1241   PUBLISH(GC_EVAL);
1242
1243   PUBLISH(CV_ROW_SAMPLE);
1244   PUBLISH(CV_VAR_NUMERICAL);
1245   PUBLISH(CV_VAR_ORDERED);
1246   PUBLISH(CV_VAR_CATEGORICAL);
1247
1248   PUBLISH(CV_AA);
1249
1250 #include "pyopencv_generated_const_reg.h"
1251 }
1252