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