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