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