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