340242f71a2fd6729c5609bf00f5d95f09429d8c
[platform/upstream/opencv.git] / modules / python / src2 / cv2.cpp
1 #if defined(_MSC_VER) && (_MSC_VER >= 1800)
2 // eliminating duplicated round() declaration
3 #define HAVE_ROUND
4 #endif
5
6 #include <Python.h>
7
8 #define MODULESTR "cv2"
9 #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
10 #include <numpy/ndarrayobject.h>
11
12 #include "pyopencv_generated_include.h"
13
14 #include "opencv2/opencv_modules.hpp"
15
16 #include "pycompat.hpp"
17
18
19 static PyObject* opencv_error = 0;
20
21 static int failmsg(const char *fmt, ...)
22 {
23     char str[1000];
24
25     va_list ap;
26     va_start(ap, fmt);
27     vsnprintf(str, sizeof(str), fmt, ap);
28     va_end(ap);
29
30     PyErr_SetString(PyExc_TypeError, str);
31     return 0;
32 }
33
34 struct ArgInfo
35 {
36     const char * name;
37     bool outputarg;
38     // more fields may be added if necessary
39
40     ArgInfo(const char * name_, bool outputarg_)
41         : name(name_)
42         , outputarg(outputarg_) {}
43
44     // to match with older pyopencv_to function signature
45     operator const char *() const { return name; }
46 };
47
48 class PyAllowThreads
49 {
50 public:
51     PyAllowThreads() : _state(PyEval_SaveThread()) {}
52     ~PyAllowThreads()
53     {
54         PyEval_RestoreThread(_state);
55     }
56 private:
57     PyThreadState* _state;
58 };
59
60 class PyEnsureGIL
61 {
62 public:
63     PyEnsureGIL() : _state(PyGILState_Ensure()) {}
64     ~PyEnsureGIL()
65     {
66         PyGILState_Release(_state);
67     }
68 private:
69     PyGILState_STATE _state;
70 };
71
72 #define ERRWRAP2(expr) \
73 try \
74 { \
75     PyAllowThreads allowThreads; \
76     expr; \
77 } \
78 catch (const cv::Exception &e) \
79 { \
80     PyErr_SetString(opencv_error, e.what()); \
81     return 0; \
82 }
83
84 using namespace cv;
85 using cv::flann::IndexParams;
86 using cv::flann::SearchParams;
87 using cv::softcascade::ChannelFeatureBuilder;
88
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;
107
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;
113
114 typedef cv::softcascade::ChannelFeatureBuilder softcascade_ChannelFeatureBuilder;
115
116 typedef SimpleBlobDetector::Params SimpleBlobDetector_Params;
117
118 typedef cvflann::flann_distance_t cvflann_flann_distance_t;
119 typedef cvflann::flann_algorithm_t cvflann_flann_algorithm_t;
120
121
122 static PyObject* failmsgp(const char *fmt, ...)
123 {
124   char str[1000];
125
126   va_list ap;
127   va_start(ap, fmt);
128   vsnprintf(str, sizeof(str), fmt, ap);
129   va_end(ap);
130
131   PyErr_SetString(PyExc_TypeError, str);
132   return 0;
133 }
134
135 class NumpyAllocator : public MatAllocator
136 {
137 public:
138     NumpyAllocator() { stdAllocator = Mat::getStdAllocator(); }
139     ~NumpyAllocator() {}
140
141     UMatData* allocate(PyObject* o, int dims, const int* sizes, int type, size_t* step) const
142     {
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];
150         u->userdata = o;
151         return u;
152     }
153
154     UMatData* allocate(int dims0, const int* sizes, int type, void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const
155     {
156         if( data != 0 )
157         {
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);
161         }
162         PyEnsureGIL gil;
163
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;
171         int i, dims = dims0;
172         cv::AutoBuffer<npy_intp> _sizes(dims + 1);
173         for( i = 0; i < dims; i++ )
174             _sizes[i] = sizes[i];
175         if( cn > 1 )
176             _sizes[dims++] = cn;
177         PyObject* o = PyArray_SimpleNew(dims, _sizes, typenum);
178         if(!o)
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);
181     }
182
183     bool allocate(UMatData* u, int accessFlags, UMatUsageFlags usageFlags) const
184     {
185         return stdAllocator->allocate(u, accessFlags, usageFlags);
186     }
187
188     void deallocate(UMatData* u) const
189     {
190         if(u)
191         {
192             PyEnsureGIL gil;
193             PyObject* o = (PyObject*)u->userdata;
194             Py_XDECREF(o);
195             delete u;
196         }
197     }
198
199     const MatAllocator* stdAllocator;
200 };
201
202 NumpyAllocator g_numpyAllocator;
203
204
205 template<typename T> static
206 bool pyopencv_to(PyObject* obj, T& p, const char* name = "<unknown>");
207
208 template<typename T> static
209 PyObject* pyopencv_from(const T& src);
210
211 enum { ARG_NONE = 0, ARG_MAT = 1, ARG_SCALAR = 2 };
212
213 // special case, when the convertor needs full ArgInfo structure
214 static bool pyopencv_to(PyObject* o, Mat& m, const ArgInfo info)
215 {
216     bool allowND = true;
217     if(!o || o == Py_None)
218     {
219         if( !m.data )
220             m.allocator = &g_numpyAllocator;
221         return true;
222     }
223
224     if( PyInt_Check(o) )
225     {
226         double v[] = {PyInt_AsLong((PyObject*)o), 0., 0., 0.};
227         m = Mat(4, 1, CV_64F, v).clone();
228         return true;
229     }
230     if( PyFloat_Check(o) )
231     {
232         double v[] = {PyFloat_AsDouble((PyObject*)o), 0., 0., 0.};
233         m = Mat(4, 1, CV_64F, v).clone();
234         return true;
235     }
236     if( PyTuple_Check(o) )
237     {
238         int i, sz = (int)PyTuple_Size((PyObject*)o);
239         m = Mat(sz, 1, CV_64F);
240         for( i = 0; i < sz; i++ )
241         {
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);
247             else
248             {
249                 failmsg("%s is not a numerical tuple", info.name);
250                 m.release();
251                 return false;
252             }
253         }
254         return true;
255     }
256
257     if( !PyArray_Check(o) )
258     {
259         failmsg("%s is not a numpy array, neither a scalar", info.name);
260         return false;
261     }
262
263     PyArrayObject* oarr = (PyArrayObject*) o;
264
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;
275
276     if( type < 0 )
277     {
278         if( typenum == NPY_INT64 || typenum == NPY_UINT64 || type == NPY_LONG )
279         {
280             needcopy = needcast = true;
281             new_typenum = NPY_INT;
282             type = CV_32S;
283         }
284         else
285         {
286             failmsg("%s data type = %d is not supported", info.name, typenum);
287             return false;
288         }
289     }
290
291 #ifndef CV_MAX_DIM
292     const int CV_MAX_DIM = 32;
293 #endif
294
295     int ndims = PyArray_NDIM(oarr);
296     if(ndims >= CV_MAX_DIM)
297     {
298         failmsg("%s dimensionality (=%d) is too high", info.name, ndims);
299         return false;
300     }
301
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;
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     m.u = g_numpyAllocator.allocate(o, ndims, size, type, step);
370     m.addref();
371
372     if( !needcopy )
373     {
374         Py_INCREF(o);
375     }
376     m.allocator = &g_numpyAllocator;
377
378     return true;
379 }
380
381 template<>
382 PyObject* pyopencv_from(const Mat& m)
383 {
384     if( !m.data )
385         Py_RETURN_NONE;
386     Mat temp, *p = (Mat*)&m;
387     if(!p->u || p->allocator != &g_numpyAllocator)
388     {
389         temp.allocator = &g_numpyAllocator;
390         ERRWRAP2(m.copyTo(temp));
391         p = &temp;
392     }
393     PyObject* o = (PyObject*)p->u->userdata;
394     Py_INCREF(o);
395     return o;
396 }
397
398 template<>
399 bool pyopencv_to(PyObject *o, Scalar& s, const char *name)
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 template<>
434 PyObject* pyopencv_from(const Scalar& src)
435 {
436     return Py_BuildValue("(dddd)", src[0], src[1], src[2], src[3]);
437 }
438
439 template<>
440 PyObject* pyopencv_from(const bool& value)
441 {
442     return PyBool_FromLong(value);
443 }
444
445 template<>
446 bool pyopencv_to(PyObject* obj, bool& value, const char* name)
447 {
448     (void)name;
449     if(!obj || obj == Py_None)
450         return true;
451     int _val = PyObject_IsTrue(obj);
452     if(_val < 0)
453         return false;
454     value = _val > 0;
455     return true;
456 }
457
458 template<>
459 PyObject* pyopencv_from(const size_t& value)
460 {
461     return PyLong_FromSize_t(value);
462 }
463
464 template<>
465 bool pyopencv_to(PyObject* obj, size_t& value, const char* name)
466 {
467     (void)name;
468     if(!obj || obj == Py_None)
469         return true;
470     value = (int)PyLong_AsUnsignedLong(obj);
471     return value != (size_t)-1 || !PyErr_Occurred();
472 }
473
474 template<>
475 PyObject* pyopencv_from(const int& value)
476 {
477     return PyInt_FromLong(value);
478 }
479
480 template<>
481 PyObject* pyopencv_from(const cvflann_flann_algorithm_t& value)
482 {
483     return PyInt_FromLong(int(value));
484 }
485
486 template<>
487 PyObject* pyopencv_from(const cvflann_flann_distance_t& value)
488 {
489     return PyInt_FromLong(int(value));
490 }
491
492 template<>
493 bool pyopencv_to(PyObject* obj, int& value, const char* name)
494 {
495     (void)name;
496     if(!obj || obj == Py_None)
497         return true;
498     if(PyInt_Check(obj))
499         value = (int)PyInt_AsLong(obj);
500     else if(PyLong_Check(obj))
501         value = (int)PyLong_AsLong(obj);
502     else
503         return false;
504     return value != -1 || !PyErr_Occurred();
505 }
506
507 template<>
508 PyObject* pyopencv_from(const uchar& value)
509 {
510     return PyInt_FromLong(value);
511 }
512
513 template<>
514 bool pyopencv_to(PyObject* obj, uchar& value, const char* name)
515 {
516     (void)name;
517     if(!obj || obj == Py_None)
518         return true;
519     int ivalue = (int)PyInt_AsLong(obj);
520     value = cv::saturate_cast<uchar>(ivalue);
521     return ivalue != -1 || !PyErr_Occurred();
522 }
523
524 template<>
525 PyObject* pyopencv_from(const double& value)
526 {
527     return PyFloat_FromDouble(value);
528 }
529
530 template<>
531 bool pyopencv_to(PyObject* obj, double& value, const char* name)
532 {
533     (void)name;
534     if(!obj || obj == Py_None)
535         return true;
536     if(!!PyInt_CheckExact(obj))
537         value = (double)PyInt_AS_LONG(obj);
538     else
539         value = PyFloat_AsDouble(obj);
540     return !PyErr_Occurred();
541 }
542
543 template<>
544 PyObject* pyopencv_from(const float& value)
545 {
546     return PyFloat_FromDouble(value);
547 }
548
549 template<>
550 bool pyopencv_to(PyObject* obj, float& value, const char* name)
551 {
552     (void)name;
553     if(!obj || obj == Py_None)
554         return true;
555     if(!!PyInt_CheckExact(obj))
556         value = (float)PyInt_AS_LONG(obj);
557     else
558         value = (float)PyFloat_AsDouble(obj);
559     return !PyErr_Occurred();
560 }
561
562 template<>
563 PyObject* pyopencv_from(const int64& value)
564 {
565     return PyLong_FromLongLong(value);
566 }
567
568 template<>
569 PyObject* pyopencv_from(const String& value)
570 {
571     return PyString_FromString(value.empty() ? "" : value.c_str());
572 }
573
574 template<>
575 bool pyopencv_to(PyObject* obj, String& value, const char* name)
576 {
577     (void)name;
578     if(!obj || obj == Py_None)
579         return true;
580     char* str = PyString_AsString(obj);
581     if(!str)
582         return false;
583     value = String(str);
584     return true;
585 }
586
587 template<>
588 bool pyopencv_to(PyObject* obj, Size& sz, const char* name)
589 {
590     (void)name;
591     if(!obj || obj == Py_None)
592         return true;
593     return PyArg_ParseTuple(obj, "ii", &sz.width, &sz.height) > 0;
594 }
595
596 template<>
597 PyObject* pyopencv_from(const Size& sz)
598 {
599     return Py_BuildValue("(ii)", sz.width, sz.height);
600 }
601
602 template<>
603 bool pyopencv_to(PyObject* obj, Rect& r, const char* name)
604 {
605     (void)name;
606     if(!obj || obj == Py_None)
607         return true;
608     return PyArg_ParseTuple(obj, "iiii", &r.x, &r.y, &r.width, &r.height) > 0;
609 }
610
611 template<>
612 PyObject* pyopencv_from(const Rect& r)
613 {
614     return Py_BuildValue("(iiii)", r.x, r.y, r.width, r.height);
615 }
616
617 template<>
618 bool pyopencv_to(PyObject* obj, Range& r, const char* name)
619 {
620     (void)name;
621     if(!obj || obj == Py_None)
622         return true;
623     if(PyObject_Size(obj) == 0)
624     {
625         r = Range::all();
626         return true;
627     }
628     return PyArg_ParseTuple(obj, "ii", &r.start, &r.end) > 0;
629 }
630
631 template<>
632 PyObject* pyopencv_from(const Range& r)
633 {
634     return Py_BuildValue("(ii)", r.start, r.end);
635 }
636
637 template<>
638 bool pyopencv_to(PyObject* obj, Point& p, const char* name)
639 {
640     (void)name;
641     if(!obj || obj == Py_None)
642         return true;
643     if(!!PyComplex_CheckExact(obj))
644     {
645         Py_complex c = PyComplex_AsCComplex(obj);
646         p.x = saturate_cast<int>(c.real);
647         p.y = saturate_cast<int>(c.imag);
648         return true;
649     }
650     return PyArg_ParseTuple(obj, "ii", &p.x, &p.y) > 0;
651 }
652
653 template<>
654 bool pyopencv_to(PyObject* obj, Point2f& p, const char* name)
655 {
656     (void)name;
657     if(!obj || obj == Py_None)
658         return true;
659     if(!!PyComplex_CheckExact(obj))
660     {
661         Py_complex c = PyComplex_AsCComplex(obj);
662         p.x = saturate_cast<float>(c.real);
663         p.y = saturate_cast<float>(c.imag);
664         return true;
665     }
666     return PyArg_ParseTuple(obj, "ff", &p.x, &p.y) > 0;
667 }
668
669 template<>
670 bool pyopencv_to(PyObject* obj, Point2d& p, const char* name)
671 {
672     (void)name;
673     if(!obj || obj == Py_None)
674         return true;
675     if(!!PyComplex_CheckExact(obj))
676     {
677         Py_complex c = PyComplex_AsCComplex(obj);
678         p.x = saturate_cast<double>(c.real);
679         p.y = saturate_cast<double>(c.imag);
680         return true;
681     }
682     return PyArg_ParseTuple(obj, "dd", &p.x, &p.y) > 0;
683 }
684
685
686 template<>
687 PyObject* pyopencv_from(const Point& p)
688 {
689     return Py_BuildValue("(ii)", p.x, p.y);
690 }
691
692 template<>
693 PyObject* pyopencv_from(const Point2f& p)
694 {
695     return Py_BuildValue("(dd)", p.x, p.y);
696 }
697
698 template<>
699 bool pyopencv_to(PyObject* obj, Vec3d& v, const char* name)
700 {
701     (void)name;
702     if(!obj)
703         return true;
704     return PyArg_ParseTuple(obj, "ddd", &v[0], &v[1], &v[2]) > 0;
705 }
706
707 template<>
708 PyObject* pyopencv_from(const Vec3d& v)
709 {
710     return Py_BuildValue("(ddd)", v[0], v[1], v[2]);
711 }
712
713 template<>
714 PyObject* pyopencv_from(const Vec2d& v)
715 {
716     return Py_BuildValue("(dd)", v[0], v[1]);
717 }
718
719 template<>
720 PyObject* pyopencv_from(const Point2d& p)
721 {
722     return Py_BuildValue("(dd)", p.x, p.y);
723 }
724
725 template<typename _Tp> struct pyopencvVecConverter
726 {
727     static bool to(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
728     {
729         typedef typename DataType<_Tp>::channel_type _Cp;
730         if(!obj || obj == Py_None)
731             return true;
732         if (PyArray_Check(obj))
733         {
734             Mat m;
735             pyopencv_to(obj, m, info);
736             m.copyTo(value);
737         }
738         if (!PySequence_Check(obj))
739             return false;
740         PyObject *seq = PySequence_Fast(obj, info.name);
741         if (seq == NULL)
742             return false;
743         int i, j, n = (int)PySequence_Fast_GET_SIZE(seq);
744         value.resize(n);
745
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);
749
750         for( i = 0; i < n; i++ )
751         {
752             PyObject* item = items[i];
753             PyObject* seq_i = 0;
754             PyObject** items_i = &item;
755             _Cp* data = (_Cp*)&value[i];
756
757             if( channels == 2 && PyComplex_CheckExact(item) )
758             {
759                 Py_complex c = PyComplex_AsCComplex(obj);
760                 data[0] = saturate_cast<_Cp>(c.real);
761                 data[1] = saturate_cast<_Cp>(c.imag);
762                 continue;
763             }
764             if( channels > 1 )
765             {
766                 if( PyArray_Check(item))
767                 {
768                     Mat src;
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)))
773                         break;
774                     Mat dst(src.rows, src.cols, depth, data);
775                     src.convertTo(dst, type);
776                     if( dst.data != (uchar*)data )
777                         break;
778                     continue;
779                 }
780
781                 seq_i = PySequence_Fast(item, info.name);
782                 if( !seq_i || (int)PySequence_Fast_GET_SIZE(seq_i) != channels )
783                 {
784                     Py_XDECREF(seq_i);
785                     break;
786                 }
787                 items_i = PySequence_Fast_ITEMS(seq_i);
788             }
789
790             for( j = 0; j < channels; j++ )
791             {
792                 PyObject* item_ij = items_i[j];
793                 if( PyInt_Check(item_ij))
794                 {
795                     int v = (int)PyInt_AsLong(item_ij);
796                     if( v == -1 && PyErr_Occurred() )
797                         break;
798                     data[j] = saturate_cast<_Cp>(v);
799                 }
800                 else if( PyLong_Check(item_ij))
801                 {
802                     int v = (int)PyLong_AsLong(item_ij);
803                     if( v == -1 && PyErr_Occurred() )
804                         break;
805                     data[j] = saturate_cast<_Cp>(v);
806                 }
807                 else if( PyFloat_Check(item_ij))
808                 {
809                     double v = PyFloat_AsDouble(item_ij);
810                     if( PyErr_Occurred() )
811                         break;
812                     data[j] = saturate_cast<_Cp>(v);
813                 }
814                 else
815                     break;
816             }
817             Py_XDECREF(seq_i);
818             if( j < channels )
819                 break;
820         }
821         Py_DECREF(seq);
822         return i == n;
823     }
824
825     static PyObject* from(const std::vector<_Tp>& value)
826     {
827         if(value.empty())
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);
831     }
832 };
833
834 template<typename _Tp>
835 bool pyopencv_to(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
836 {
837     return pyopencvVecConverter<_Tp>::to(obj, value, info);
838 }
839
840 template<typename _Tp>
841 PyObject* pyopencv_from(const std::vector<_Tp>& value)
842 {
843     return pyopencvVecConverter<_Tp>::from(value);
844 }
845
846 template<typename _Tp> static inline bool pyopencv_to_generic_vec(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
847 {
848     if(!obj || obj == Py_None)
849        return true;
850     if (!PySequence_Check(obj))
851         return false;
852     PyObject *seq = PySequence_Fast(obj, info.name);
853     if (seq == NULL)
854         return false;
855     int i, n = (int)PySequence_Fast_GET_SIZE(seq);
856     value.resize(n);
857
858     PyObject** items = PySequence_Fast_ITEMS(seq);
859
860     for( i = 0; i < n; i++ )
861     {
862         PyObject* item = items[i];
863         if(!pyopencv_to(item, value[i], info))
864             break;
865     }
866     Py_DECREF(seq);
867     return i == n;
868 }
869
870 template<typename _Tp> static inline PyObject* pyopencv_from_generic_vec(const std::vector<_Tp>& value)
871 {
872     int i, n = (int)value.size();
873     PyObject* seq = PyList_New(n);
874     for( i = 0; i < n; i++ )
875     {
876         PyObject* item = pyopencv_from(value[i]);
877         if(!item)
878             break;
879         PyList_SET_ITEM(seq, i, item);
880     }
881     if( i < n )
882     {
883         Py_DECREF(seq);
884         return 0;
885     }
886     return seq;
887 }
888
889
890 template<typename _Tp> struct pyopencvVecConverter<std::vector<_Tp> >
891 {
892     static bool to(PyObject* obj, std::vector<std::vector<_Tp> >& value, const ArgInfo info)
893     {
894         return pyopencv_to_generic_vec(obj, value, info);
895     }
896
897     static PyObject* from(const std::vector<std::vector<_Tp> >& value)
898     {
899         return pyopencv_from_generic_vec(value);
900     }
901 };
902
903 template<> struct pyopencvVecConverter<Mat>
904 {
905     static bool to(PyObject* obj, std::vector<Mat>& value, const ArgInfo info)
906     {
907         return pyopencv_to_generic_vec(obj, value, info);
908     }
909
910     static PyObject* from(const std::vector<Mat>& value)
911     {
912         return pyopencv_from_generic_vec(value);
913     }
914 };
915
916 template<> struct pyopencvVecConverter<KeyPoint>
917 {
918     static bool to(PyObject* obj, std::vector<KeyPoint>& value, const ArgInfo info)
919     {
920         return pyopencv_to_generic_vec(obj, value, info);
921     }
922
923     static PyObject* from(const std::vector<KeyPoint>& value)
924     {
925         return pyopencv_from_generic_vec(value);
926     }
927 };
928
929 template<> struct pyopencvVecConverter<DMatch>
930 {
931     static bool to(PyObject* obj, std::vector<DMatch>& value, const ArgInfo info)
932     {
933         return pyopencv_to_generic_vec(obj, value, info);
934     }
935
936     static PyObject* from(const std::vector<DMatch>& value)
937     {
938         return pyopencv_from_generic_vec(value);
939     }
940 };
941
942 template<> struct pyopencvVecConverter<String>
943 {
944     static bool to(PyObject* obj, std::vector<String>& value, const ArgInfo info)
945     {
946         return pyopencv_to_generic_vec(obj, value, info);
947     }
948
949     static PyObject* from(const std::vector<String>& value)
950     {
951         return pyopencv_from_generic_vec(value);
952     }
953 };
954
955 template<>
956 bool pyopencv_to(PyObject *obj, TermCriteria& dst, const char *name)
957 {
958     (void)name;
959     if(!obj)
960         return true;
961     return PyArg_ParseTuple(obj, "iid", &dst.type, &dst.maxCount, &dst.epsilon) > 0;
962 }
963
964 template<>
965 PyObject* pyopencv_from(const TermCriteria& src)
966 {
967     return Py_BuildValue("(iid)", src.type, src.maxCount, src.epsilon);
968 }
969
970 template<>
971 bool pyopencv_to(PyObject *obj, RotatedRect& dst, const char *name)
972 {
973     (void)name;
974     if(!obj)
975         return true;
976     return PyArg_ParseTuple(obj, "(ff)(ff)f", &dst.center.x, &dst.center.y, &dst.size.width, &dst.size.height, &dst.angle) > 0;
977 }
978
979 template<>
980 PyObject* pyopencv_from(const RotatedRect& src)
981 {
982     return Py_BuildValue("((ff)(ff)f)", src.center.x, src.center.y, src.size.width, src.size.height, src.angle);
983 }
984
985 template<>
986 PyObject* pyopencv_from(const Moments& m)
987 {
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);
996 }
997
998 template<>
999 bool pyopencv_to(PyObject *o, cv::flann::IndexParams& p, const char *name)
1000 {
1001     (void)name;
1002     bool ok = true;
1003     PyObject* key = NULL;
1004     PyObject* item = NULL;
1005     Py_ssize_t pos = 0;
1006
1007     if(PyDict_Check(o)) {
1008         while(PyDict_Next(o, &pos, &key, &item)) {
1009             if( !PyString_Check(key) ) {
1010                 ok = false;
1011                 break;
1012             }
1013
1014             String k = PyString_AsString(key);
1015             if( PyString_Check(item) )
1016             {
1017                 const char* value = PyString_AsString(item);
1018                 p.setString(k, value);
1019             }
1020             else if( !!PyBool_Check(item) )
1021                 p.setBool(k, item == Py_True);
1022             else if( PyInt_Check(item) )
1023             {
1024                 int value = (int)PyInt_AsLong(item);
1025                 if( strcmp(k.c_str(), "algorithm") == 0 )
1026                     p.setAlgorithm(value);
1027                 else
1028                     p.setInt(k, value);
1029             }
1030             else if( PyFloat_Check(item) )
1031             {
1032                 double value = PyFloat_AsDouble(item);
1033                 p.setDouble(k, value);
1034             }
1035             else
1036             {
1037                 ok = false;
1038                 break;
1039             }
1040         }
1041     }
1042
1043     return ok && !PyErr_Occurred();
1044 }
1045
1046 template<>
1047 bool pyopencv_to(PyObject* obj, cv::flann::SearchParams & value, const char * name)
1048 {
1049     return pyopencv_to<cv::flann::IndexParams>(obj, value, name);
1050 }
1051
1052 template <typename T>
1053 bool pyopencv_to(PyObject *o, Ptr<T>& p, const char *name)
1054 {
1055     p = makePtr<T>();
1056     return pyopencv_to(o, *p, name);
1057 }
1058
1059 template<>
1060 bool pyopencv_to(PyObject *o, cvflann::flann_distance_t& dist, const char *name)
1061 {
1062     int d = (int)dist;
1063     bool ok = pyopencv_to(o, d, name);
1064     dist = (cvflann::flann_distance_t)d;
1065     return ok;
1066 }
1067
1068
1069 ////////////////////////////////////////////////////////////////////////////////////////////////////
1070 // TODO: REMOVE used only by ml wrapper
1071
1072 template<>
1073 bool pyopencv_to(PyObject *obj, CvTermCriteria& dst, const char *name)
1074 {
1075     (void)name;
1076     if(!obj)
1077         return true;
1078     return PyArg_ParseTuple(obj, "iid", &dst.type, &dst.max_iter, &dst.epsilon) > 0;
1079 }
1080
1081 template<>
1082 bool pyopencv_to(PyObject* obj, CvSlice& r, const char* name)
1083 {
1084     (void)name;
1085     if(!obj || obj == Py_None)
1086         return true;
1087     if(PyObject_Size(obj) == 0)
1088     {
1089         r = CV_WHOLE_SEQ;
1090         return true;
1091     }
1092     return PyArg_ParseTuple(obj, "ii", &r.start_index, &r.end_index) > 0;
1093 }
1094
1095 template<>
1096 PyObject* pyopencv_from(CvDTreeNode* const & node)
1097 {
1098     double value = node->value;
1099     int ivalue = cvRound(value);
1100     return value == ivalue ? PyInt_FromLong(ivalue) : PyFloat_FromDouble(value);
1101 }
1102
1103 ////////////////////////////////////////////////////////////////////////////////////////////////////
1104
1105 static void OnMouse(int event, int x, int y, int flags, void* param)
1106 {
1107     PyGILState_STATE gstate;
1108     gstate = PyGILState_Ensure();
1109
1110     PyObject *o = (PyObject*)param;
1111     PyObject *args = Py_BuildValue("iiiiO", event, x, y, flags, PyTuple_GetItem(o, 1));
1112
1113     PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL);
1114     if (r == NULL)
1115         PyErr_Print();
1116     else
1117         Py_DECREF(r);
1118     Py_DECREF(args);
1119     PyGILState_Release(gstate);
1120 }
1121
1122 static PyObject *pycvSetMouseCallback(PyObject*, PyObject *args, PyObject *kw)
1123 {
1124     const char *keywords[] = { "window_name", "on_mouse", "param", NULL };
1125     char* name;
1126     PyObject *on_mouse;
1127     PyObject *param = NULL;
1128
1129     if (!PyArg_ParseTupleAndKeywords(args, kw, "sO|O", (char**)keywords, &name, &on_mouse, &param))
1130         return NULL;
1131     if (!PyCallable_Check(on_mouse)) {
1132         PyErr_SetString(PyExc_TypeError, "on_mouse must be callable");
1133         return NULL;
1134     }
1135     if (param == NULL) {
1136         param = Py_None;
1137     }
1138     ERRWRAP2(setMouseCallback(name, OnMouse, Py_BuildValue("OO", on_mouse, param)));
1139     Py_RETURN_NONE;
1140 }
1141
1142 static void OnChange(int pos, void *param)
1143 {
1144     PyGILState_STATE gstate;
1145     gstate = PyGILState_Ensure();
1146
1147     PyObject *o = (PyObject*)param;
1148     PyObject *args = Py_BuildValue("(i)", pos);
1149     PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL);
1150     if (r == NULL)
1151         PyErr_Print();
1152     Py_DECREF(args);
1153     PyGILState_Release(gstate);
1154 }
1155
1156 static PyObject *pycvCreateTrackbar(PyObject*, PyObject *args)
1157 {
1158     PyObject *on_change;
1159     char* trackbar_name;
1160     char* window_name;
1161     int *value = new int;
1162     int count;
1163
1164     if (!PyArg_ParseTuple(args, "ssiiO", &trackbar_name, &window_name, value, &count, &on_change))
1165         return NULL;
1166     if (!PyCallable_Check(on_change)) {
1167         PyErr_SetString(PyExc_TypeError, "on_change must be callable");
1168         return NULL;
1169     }
1170     ERRWRAP2(createTrackbar(trackbar_name, window_name, value, count, OnChange, Py_BuildValue("OO", on_change, Py_None)));
1171     Py_RETURN_NONE;
1172 }
1173
1174 ///////////////////////////////////////////////////////////////////////////////////////
1175
1176 static int convert_to_char(PyObject *o, char *dst, const char *name = "no_name")
1177 {
1178   if (PyString_Check(o) && PyString_Size(o) == 1) {
1179     *dst = PyString_AsString(o)[0];
1180     return 1;
1181   } else {
1182     (*dst) = 0;
1183     return failmsg("Expected single character string for argument '%s'", name);
1184   }
1185 }
1186
1187 #if PY_MAJOR_VERSION >= 3
1188 #define MKTYPE2(NAME) pyopencv_##NAME##_specials(); if (!to_ok(&pyopencv_##NAME##_Type)) return NULL;
1189 #else
1190 #define MKTYPE2(NAME) pyopencv_##NAME##_specials(); if (!to_ok(&pyopencv_##NAME##_Type)) return
1191 #endif
1192
1193 #ifdef __GNUC__
1194 #  pragma GCC diagnostic ignored "-Wunused-parameter"
1195 #  pragma GCC diagnostic ignored "-Wmissing-field-initializers"
1196 #endif
1197
1198 #include "pyopencv_generated_types.h"
1199 #include "pyopencv_generated_funcs.h"
1200
1201 static PyMethodDef methods[] = {
1202
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"},
1206   {NULL, NULL},
1207 };
1208
1209 /************************************************************************/
1210 /* Module init */
1211
1212 static int to_ok(PyTypeObject *to)
1213 {
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);
1218 }
1219
1220
1221 #if PY_MAJOR_VERSION >= 3
1222 extern "C" CV_EXPORTS PyObject* PyInit_cv2();
1223 static struct PyModuleDef cv2_moduledef =
1224 {
1225     PyModuleDef_HEAD_INIT,
1226     MODULESTR,
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. */
1230     methods
1231 };
1232
1233 PyObject* PyInit_cv2()
1234 #else
1235 extern "C" CV_EXPORTS void initcv2();
1236
1237 void initcv2()
1238 #endif
1239 {
1240   import_array();
1241
1242 #include "pyopencv_generated_type_reg.h"
1243
1244 #if PY_MAJOR_VERSION >= 3
1245   PyObject* m = PyModule_Create(&cv2_moduledef);
1246 #else
1247   PyObject* m = Py_InitModule(MODULESTR, methods);
1248 #endif
1249   PyObject* d = PyModule_GetDict(m);
1250
1251   PyDict_SetItemString(d, "__version__", PyString_FromString(CV_VERSION));
1252
1253   opencv_error = PyErr_NewException((char*)MODULESTR".error", NULL, NULL);
1254   PyDict_SetItemString(d, "error", opencv_error);
1255
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))
1259
1260   PUBLISH(CV_8U);
1261   PUBLISH(CV_8UC1);
1262   PUBLISH(CV_8UC2);
1263   PUBLISH(CV_8UC3);
1264   PUBLISH(CV_8UC4);
1265   PUBLISH(CV_8S);
1266   PUBLISH(CV_8SC1);
1267   PUBLISH(CV_8SC2);
1268   PUBLISH(CV_8SC3);
1269   PUBLISH(CV_8SC4);
1270   PUBLISH(CV_16U);
1271   PUBLISH(CV_16UC1);
1272   PUBLISH(CV_16UC2);
1273   PUBLISH(CV_16UC3);
1274   PUBLISH(CV_16UC4);
1275   PUBLISH(CV_16S);
1276   PUBLISH(CV_16SC1);
1277   PUBLISH(CV_16SC2);
1278   PUBLISH(CV_16SC3);
1279   PUBLISH(CV_16SC4);
1280   PUBLISH(CV_32S);
1281   PUBLISH(CV_32SC1);
1282   PUBLISH(CV_32SC2);
1283   PUBLISH(CV_32SC3);
1284   PUBLISH(CV_32SC4);
1285   PUBLISH(CV_32F);
1286   PUBLISH(CV_32FC1);
1287   PUBLISH(CV_32FC2);
1288   PUBLISH(CV_32FC3);
1289   PUBLISH(CV_32FC4);
1290   PUBLISH(CV_64F);
1291   PUBLISH(CV_64FC1);
1292   PUBLISH(CV_64FC2);
1293   PUBLISH(CV_64FC3);
1294   PUBLISH(CV_64FC4);
1295
1296 #include "pyopencv_generated_const_reg.h"
1297 #if PY_MAJOR_VERSION >= 3
1298     return m;
1299 #endif
1300 }