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