1 #include "opencv2/legacy/legacy.hpp"
2 #include "opencv2/legacy/compat.hpp"
4 #define OLD_MODULESTR "cv2.cv"
37 struct cvhistogram_t {
43 struct cvmemstorage_t {
51 PyObject *container; // Containing cvmemstorage_t
57 PyObject *container; // Containing cvmemstorage_t
64 PyObject *container; // Containing cvmemstorage_t
67 struct cvsubdiv2dpoint_t {
70 PyObject *container; // Containing cvmemstorage_t
73 struct cvsubdiv2dedge_t {
76 PyObject *container; // Containing cvmemstorage_t
79 struct cvlineiterator_t {
86 typedef IplImage ROIplImage;
87 typedef const CvMat ROCvMat;
88 typedef PyObject PyCallableObject;
95 struct cvcontourtree_t {
105 static int is_iplimage(PyObject *o);
106 static int is_cvmat(PyObject *o);
107 static int is_cvmatnd(PyObject *o);
108 static int convert_to_CvArr(PyObject *o, CvArr **dst, const char *name = "no_name");
109 static int convert_to_IplImage(PyObject *o, IplImage **dst, const char *name = "no_name");
110 static int convert_to_CvMat(PyObject *o, CvMat **dst, const char *name = "no_name");
111 static int convert_to_CvMatND(PyObject *o, CvMatND **dst, const char *name = "no_name");
112 static PyObject *what_data(PyObject *o);
113 static PyObject *FROM_CvMat(CvMat *r);
114 static PyObject *FROM_ROCvMatPTR(ROCvMat *r);
115 static PyObject *shareDataND(PyObject *donor, CvMatND *pdonor, CvMatND *precipient);
117 #define FROM_double(r) PyFloat_FromDouble(r)
118 #define FROM_float(r) PyFloat_FromDouble(r)
119 #define FROM_int(r) PyInt_FromLong(r)
120 #define FROM_int64(r) PyLong_FromLongLong(r)
121 #define FROM_unsigned(r) PyLong_FromUnsignedLong(r)
122 #define FROM_CvBox2D(r) Py_BuildValue("(ff)(ff)f", r.center.x, r.center.y, r.size.width, r.size.height, r.angle)
123 #define FROM_CvScalar(r) Py_BuildValue("(ffff)", r.val[0], r.val[1], r.val[2], r.val[3])
124 #define FROM_CvPoint(r) Py_BuildValue("(ii)", r.x, r.y)
125 #define FROM_CvPoint2D32f(r) Py_BuildValue("(ff)", r.x, r.y)
126 #define FROM_CvPoint3D64f(r) Py_BuildValue("(fff)", r.x, r.y, r.z)
127 #define FROM_CvSize(r) Py_BuildValue("(ii)", r.width, r.height)
128 #define FROM_CvRect(r) Py_BuildValue("(iiii)", r.x, r.y, r.width, r.height)
129 #define FROM_CvSeqPTR(r) _FROM_CvSeqPTR(r, pyobj_storage)
130 #define FROM_CvSubdiv2DPTR(r) _FROM_CvSubdiv2DPTR(r, pyobj_storage)
131 #define FROM_CvPoint2D64f(r) Py_BuildValue("(ff)", r.x, r.y)
132 #define FROM_CvConnectedComp(r) Py_BuildValue("(fNN)", (r).area, FROM_CvScalar((r).value), FROM_CvRect((r).rect))
135 static PyObject *fromarray(PyObject *o, int allowND);
138 static void translate_error_to_exception(void)
140 PyErr_SetString(opencv_error, cvErrorStr(cvGetErrStatus()));
144 #define ERRCHK do { if (cvGetErrStatus() != 0) { translate_error_to_exception(); return 0; } } while (0)
145 #define ERRWRAPN(F, N) \
151 catch (const cv::Exception &e) \
153 PyErr_SetString(opencv_error, e.err.c_str()); \
158 #define ERRWRAP(F) ERRWRAPN(F, NULL) // for most functions, exception -> NULL return
160 /************************************************************************/
162 /* These get/setters are polymorphic, used in both iplimage and cvmat */
164 static PyObject *PyObject_FromCvScalar(CvScalar s, int type)
166 int i, spe = CV_MAT_CN(type);
169 r = PyTuple_New(spe);
170 for (i = 0; i < spe; i++)
171 PyTuple_SET_ITEM(r, i, PyFloat_FromDouble(s.val[i]));
173 r = PyFloat_FromDouble(s.val[0]);
178 static PyObject *cvarr_GetItem(PyObject *o, PyObject *key);
179 static int cvarr_SetItem(PyObject *o, PyObject *key, PyObject *v);
181 // o is a Python string or buffer object. Return its size.
183 static Py_ssize_t what_size(PyObject *o)
186 Py_ssize_t buffer_len;
188 if (PyString_Check(o)) {
189 return PyString_Size(o);
190 } else if (PyObject_AsWriteBuffer(o, &buffer, &buffer_len) == 0) {
193 assert(0); // argument must be string or buffer.
199 /************************************************************************/
201 CvMat *PyCvMat_AsCvMat(PyObject *o)
203 assert(0); // not yet implemented: reference counting for CvMat in Kalman is unclear...
207 #define cvReleaseIplConvKernel(x) cvReleaseStructuringElement(x)
208 #include "generated3.i"
212 static void iplimage_dealloc(PyObject *self)
214 iplimage_t *pc = (iplimage_t*)self;
215 cvReleaseImageHeader((IplImage**)&pc->a);
220 static PyObject *iplimage_repr(PyObject *self)
222 iplimage_t *cva = (iplimage_t*)self;
223 IplImage* ipl = (IplImage*)(cva->a);
225 sprintf(str, "<iplimage(");
226 char *d = str + strlen(str);
227 sprintf(d, "nChannels=%d ", ipl->nChannels);
229 sprintf(d, "width=%d ", ipl->width);
231 sprintf(d, "height=%d ", ipl->height);
233 sprintf(d, "widthStep=%d ", ipl->widthStep);
236 return PyString_FromString(str);
239 static PyObject *iplimage_tostring(PyObject *self, PyObject *args)
242 if (!convert_to_IplImage(self, &i, "self"))
247 size_t esz = img.elemSize();
248 int nrows = img.rows, ncols = img.cols;
250 if( !img.isContinuous() )
252 return PyString_FromStringAndSize((char*)img.data, (Py_ssize_t)(esz*nrows*ncols));
255 static struct PyMethodDef iplimage_methods[] =
257 {"tostring", iplimage_tostring, METH_VARARGS},
261 static PyObject *iplimage_getnChannels(iplimage_t *cva)
263 return PyInt_FromLong(((IplImage*)(cva->a))->nChannels);
265 static PyObject *iplimage_getwidth(iplimage_t *cva)
267 return PyInt_FromLong(((IplImage*)(cva->a))->width);
269 static PyObject *iplimage_getheight(iplimage_t *cva)
271 return PyInt_FromLong(((IplImage*)(cva->a))->height);
273 static PyObject *iplimage_getdepth(iplimage_t *cva)
275 return PyLong_FromUnsignedLong((unsigned)((IplImage*)(cva->a))->depth);
277 static PyObject *iplimage_getorigin(iplimage_t *cva)
279 return PyInt_FromLong(((IplImage*)(cva->a))->origin);
281 static void iplimage_setorigin(iplimage_t *cva, PyObject *v)
283 ((IplImage*)(cva->a))->origin = PyInt_AsLong(v);
286 static PyGetSetDef iplimage_getseters[] = {
287 {(char*)"nChannels", (getter)iplimage_getnChannels, (setter)NULL, (char*)"nChannels", NULL},
288 {(char*)"channels", (getter)iplimage_getnChannels, (setter)NULL, (char*)"nChannels", NULL},
289 {(char*)"width", (getter)iplimage_getwidth, (setter)NULL, (char*)"width", NULL},
290 {(char*)"height", (getter)iplimage_getheight, (setter)NULL, (char*)"height", NULL},
291 {(char*)"depth", (getter)iplimage_getdepth, (setter)NULL, (char*)"depth", NULL},
292 {(char*)"origin", (getter)iplimage_getorigin, (setter)iplimage_setorigin, (char*)"origin", NULL},
293 {NULL} /* Sentinel */
296 static PyMappingMethods iplimage_as_map = {
302 static PyTypeObject iplimage_Type = {
303 PyObject_HEAD_INIT(&PyType_Type)
305 OLD_MODULESTR".iplimage", /*name*/
306 sizeof(iplimage_t), /*basicsize*/
309 static void iplimage_specials(void)
311 iplimage_Type.tp_dealloc = iplimage_dealloc;
312 iplimage_Type.tp_as_mapping = &iplimage_as_map;
313 iplimage_Type.tp_repr = iplimage_repr;
314 iplimage_Type.tp_methods = iplimage_methods;
315 iplimage_Type.tp_getset = iplimage_getseters;
318 static int is_iplimage(PyObject *o)
320 return PyType_IsSubtype(o->ob_type, &iplimage_Type);
323 /************************************************************************/
327 static void cvmat_dealloc(PyObject *self)
329 cvmat_t *pc = (cvmat_t*)self;
330 Py_XDECREF(pc->data);
331 //cvDecRefData(pc->a);
336 static PyObject *cvmat_repr(PyObject *self)
338 CvMat *m = ((cvmat_t*)self)->a;
340 sprintf(str, "<cvmat(");
341 char *d = str + strlen(str);
342 sprintf(d, "type=%08x ", m->type);
344 switch (CV_MAT_DEPTH(m->type)) {
345 case CV_8U: strcpy(d, "8U"); break;
346 case CV_8S: strcpy(d, "8S"); break;
347 case CV_16U: strcpy(d, "16U"); break;
348 case CV_16S: strcpy(d, "16S"); break;
349 case CV_32S: strcpy(d, "32S"); break;
350 case CV_32F: strcpy(d, "32F"); break;
351 case CV_64F: strcpy(d, "64F"); break;
354 sprintf(d, "C%d ", CV_MAT_CN(m->type));
356 sprintf(d, "rows=%d ", m->rows);
358 sprintf(d, "cols=%d ", m->cols);
360 sprintf(d, "step=%d ", m->step);
363 return PyString_FromString(str);
366 static PyObject *cvmat_tostring(PyObject *self, PyObject *args)
369 if (!convert_to_CvMat(self, &m, "self"))
372 int bps; // bytes per sample
374 switch (CV_MAT_DEPTH(m->type)) {
377 bps = CV_MAT_CN(m->type) * 1;
381 bps = CV_MAT_CN(m->type) * 2;
385 bps = CV_MAT_CN(m->type) * 4;
388 bps = CV_MAT_CN(m->type) * 8;
391 return failmsg("Unrecognised depth %d", CV_MAT_DEPTH(m->type)), (PyObject*)0;
394 int bpl = m->cols * bps; // bytes per line
395 cvmat_t *pc = (cvmat_t*)self;
396 if (PyString_Check(pc->data) && bpl == m->step && pc->offset == 0 && ((bpl * m->rows) == what_size(pc->data))) {
400 int l = bpl * m->rows;
401 char *s = new char[l];
403 for (y = 0; y < m->rows; y++) {
404 memcpy(s + y * bpl, m->data.ptr + y * m->step, bpl);
406 PyObject *r = PyString_FromStringAndSize(s, l);
412 static struct PyMethodDef cvmat_methods[] =
414 {"tostring", cvmat_tostring, METH_VARARGS},
418 static PyObject *cvmat_gettype(cvmat_t *cva)
420 return PyInt_FromLong(cvGetElemType(cva->a));
423 static PyObject *cvmat_getstep(cvmat_t *cva)
425 return PyInt_FromLong(cva->a->step);
428 static PyObject *cvmat_getrows(cvmat_t *cva)
430 return PyInt_FromLong(cva->a->rows);
433 static PyObject *cvmat_getcols(cvmat_t *cva)
435 return PyInt_FromLong(cva->a->cols);
438 static PyObject *cvmat_getchannels(cvmat_t *cva)
440 return PyInt_FromLong(CV_MAT_CN(cva->a->type));
444 #include "numpy/ndarrayobject.h"
446 // A PyArrayInterface, with an associated python object that should be DECREF'ed on release
452 static void arrayTrackDtor(void *p)
454 struct arrayTrack *at = (struct arrayTrack *)p;
455 delete[] at->s.shape;
456 delete[] at->s.strides;
458 Py_DECREF(at->s.descr);
462 // Fill in fields of PyArrayInterface s using mtype. This code is common
463 // to cvmat and cvmatnd
465 static void arrayinterface_common(PyArrayInterface *s, int mtype)
469 switch (CV_MAT_DEPTH(mtype)) {
502 s->flags = NPY_WRITEABLE | NPY_NOTSWAPPED;
505 static PyObject *cvmat_array_struct(cvmat_t *cva)
508 convert_to_CvMat((PyObject *)cva, &m, "");
510 arrayTrack *at = new arrayTrack;
511 PyArrayInterface *s = &at->s;
516 arrayinterface_common(s, m->type);
518 if (CV_MAT_CN(m->type) == 1) {
520 s->shape = new npy_intp[2];
521 s->shape[0] = m->rows;
522 s->shape[1] = m->cols;
523 s->strides = new npy_intp[2];
524 s->strides[0] = m->step;
525 s->strides[1] = s->itemsize;
528 s->shape = new npy_intp[3];
529 s->shape[0] = m->rows;
530 s->shape[1] = m->cols;
531 s->shape[2] = CV_MAT_CN(m->type);
532 s->strides = new npy_intp[3];
533 s->strides[0] = m->step;
534 s->strides[1] = s->itemsize * CV_MAT_CN(m->type);
535 s->strides[2] = s->itemsize;
537 s->data = (void*)(m->data.ptr);
538 s->descr = PyList_New(1);
540 sprintf(typestr, "<%c%d", s->typekind, s->itemsize);
541 PyList_SetItem(s->descr, 0, Py_BuildValue("(ss)", "x", typestr));
543 return PyCObject_FromVoidPtr(s, arrayTrackDtor);
546 static PyObject *cvmatnd_array_struct(cvmatnd_t *cva)
549 convert_to_CvMatND((PyObject *)cva, &m, "");
551 arrayTrack *at = new arrayTrack;
552 PyArrayInterface *s = &at->s;
557 arrayinterface_common(s, m->type);
560 if (CV_MAT_CN(m->type) == 1) {
562 s->shape = new npy_intp[s->nd];
563 for (i = 0; i < s->nd; i++)
564 s->shape[i] = m->dim[i].size;
565 s->strides = new npy_intp[s->nd];
566 for (i = 0; i < (s->nd - 1); i++)
567 s->strides[i] = m->dim[i].step;
568 s->strides[s->nd - 1] = s->itemsize;
571 s->shape = new npy_intp[s->nd];
572 for (i = 0; i < (s->nd - 1); i++)
573 s->shape[i] = m->dim[i].size;
574 s->shape[s->nd - 1] = CV_MAT_CN(m->type);
576 s->strides = new npy_intp[s->nd];
577 for (i = 0; i < (s->nd - 2); i++)
578 s->strides[i] = m->dim[i].step;
579 s->strides[s->nd - 2] = s->itemsize * CV_MAT_CN(m->type);
580 s->strides[s->nd - 1] = s->itemsize;
582 s->data = (void*)(m->data.ptr);
583 s->descr = PyList_New(1);
585 sprintf(typestr, "<%c%d", s->typekind, s->itemsize);
586 PyList_SetItem(s->descr, 0, Py_BuildValue("(ss)", "x", typestr));
588 return PyCObject_FromVoidPtr(s, arrayTrackDtor);
592 static PyGetSetDef cvmat_getseters[] = {
593 {(char*)"type", (getter)cvmat_gettype, (setter)NULL, (char*)"type", NULL},
594 {(char*)"step", (getter)cvmat_getstep, (setter)NULL, (char*)"step", NULL},
595 {(char*)"rows", (getter)cvmat_getrows, (setter)NULL, (char*)"rows", NULL},
596 {(char*)"cols", (getter)cvmat_getcols, (setter)NULL, (char*)"cols", NULL},
597 {(char*)"channels",(getter)cvmat_getchannels, (setter)NULL, (char*)"channels", NULL},
598 {(char*)"width", (getter)cvmat_getcols, (setter)NULL, (char*)"width", NULL},
599 {(char*)"height", (getter)cvmat_getrows, (setter)NULL, (char*)"height", NULL},
601 {(char*)"__array_struct__", (getter)cvmat_array_struct, (setter)NULL, (char*)"__array_struct__", NULL},
603 {NULL} /* Sentinel */
606 static PyMappingMethods cvmat_as_map = {
612 static PyTypeObject cvmat_Type = {
613 PyObject_HEAD_INIT(&PyType_Type)
615 OLD_MODULESTR".cvmat", /*name*/
616 sizeof(cvmat_t), /*basicsize*/
619 static int illegal_init(PyObject *self, PyObject *args, PyObject *kwds)
621 PyErr_SetString(opencv_error, "Cannot create cvmat directly; use CreateMat() instead");
625 static void cvmat_specials(void)
627 cvmat_Type.tp_dealloc = cvmat_dealloc;
628 cvmat_Type.tp_as_mapping = &cvmat_as_map;
629 cvmat_Type.tp_repr = cvmat_repr;
630 cvmat_Type.tp_methods = cvmat_methods;
631 cvmat_Type.tp_getset = cvmat_getseters;
632 cvmat_Type.tp_init = illegal_init;
635 static int is_cvmat(PyObject *o)
637 return PyType_IsSubtype(o->ob_type, &cvmat_Type);
640 /************************************************************************/
644 static void cvmatnd_dealloc(PyObject *self)
646 cvmatnd_t *pc = (cvmatnd_t*)self;
647 Py_XDECREF(pc->data);
653 static PyObject *cvmatnd_repr(PyObject *self)
655 CvMatND *m = ((cvmatnd_t*)self)->a;
657 sprintf(str, "<cvmatnd(");
658 char *d = str + strlen(str);
659 sprintf(d, "type=%08x ", m->type);
662 return PyString_FromString(str);
665 static size_t cvmatnd_size(CvMatND *m)
668 switch (CV_MAT_DEPTH(m->type)) {
671 bps = CV_MAT_CN(m->type) * 1;
675 bps = CV_MAT_CN(m->type) * 2;
679 bps = CV_MAT_CN(m->type) * 4;
682 bps = CV_MAT_CN(m->type) * 8;
688 for (int d = 0; d < m->dims; d++) {
694 static PyObject *cvmatnd_tostring(PyObject *self, PyObject *args)
697 if (!convert_to_CvMatND(self, &m, "self"))
701 switch (CV_MAT_DEPTH(m->type)) {
704 bps = CV_MAT_CN(m->type) * 1;
708 bps = CV_MAT_CN(m->type) * 2;
712 bps = CV_MAT_CN(m->type) * 4;
715 bps = CV_MAT_CN(m->type) * 8;
718 return failmsg("Unrecognised depth %d", CV_MAT_DEPTH(m->type)), (PyObject*)0;
722 for (d = 0; d < m->dims; d++) {
726 for (d = 0; d < m->dims; d++) {
729 int rowsize = m->dim[m->dims-1].size * bps;
730 char *s = new char[l];
735 memcpy(ps, cvPtrND(m, i), rowsize);
737 for (d = m->dims - 2; 0 <= d; d--) {
738 if (++i[d] < cvGetDimSize(m, d)) {
748 return PyString_FromStringAndSize(s, ps - s);
751 static struct PyMethodDef cvmatnd_methods[] =
753 {"tostring", cvmatnd_tostring, METH_VARARGS},
757 static PyObject *cvmatnd_getchannels(cvmatnd_t *cva)
759 return PyInt_FromLong(CV_MAT_CN(cva->a->type));
762 static PyGetSetDef cvmatnd_getseters[] = {
764 {(char*)"__array_struct__", (getter)cvmatnd_array_struct, (setter)NULL, (char*)"__array_struct__", NULL},
766 {(char*)"channels",(getter)cvmatnd_getchannels, (setter)NULL, (char*)"channels", NULL},
767 {NULL} /* Sentinel */
770 static PyMappingMethods cvmatnd_as_map = {
776 static PyTypeObject cvmatnd_Type = {
777 PyObject_HEAD_INIT(&PyType_Type)
779 OLD_MODULESTR".cvmatnd", /*name*/
780 sizeof(cvmatnd_t), /*basicsize*/
783 static void cvmatnd_specials(void)
785 cvmatnd_Type.tp_dealloc = cvmatnd_dealloc;
786 cvmatnd_Type.tp_as_mapping = &cvmatnd_as_map;
787 cvmatnd_Type.tp_repr = cvmatnd_repr;
788 cvmatnd_Type.tp_methods = cvmatnd_methods;
789 cvmatnd_Type.tp_getset = cvmatnd_getseters;
792 static int is_cvmatnd(PyObject *o)
794 return PyType_IsSubtype(o->ob_type, &cvmatnd_Type);
797 /************************************************************************/
801 static void cvhistogram_dealloc(PyObject *self)
803 cvhistogram_t *cvh = (cvhistogram_t*)self;
804 Py_DECREF(cvh->bins);
808 static PyTypeObject cvhistogram_Type = {
809 PyObject_HEAD_INIT(&PyType_Type)
811 OLD_MODULESTR".cvhistogram", /*name*/
812 sizeof(cvhistogram_t), /*basicsize*/
815 static PyObject *cvhistogram_getbins(cvhistogram_t *cvh)
817 Py_INCREF(cvh->bins);
821 static PyGetSetDef cvhistogram_getseters[] = {
822 {(char*)"bins", (getter)cvhistogram_getbins, (setter)NULL, (char*)"bins", NULL},
823 {NULL} /* Sentinel */
826 static void cvhistogram_specials(void)
828 cvhistogram_Type.tp_dealloc = cvhistogram_dealloc;
829 cvhistogram_Type.tp_getset = cvhistogram_getseters;
832 /************************************************************************/
836 static PyObject *cvlineiterator_iter(PyObject *o)
842 static PyObject *cvlineiterator_next(PyObject *o)
844 cvlineiterator_t *pi = (cvlineiterator_t*)o;
850 cvRawDataToScalar( (void*)(pi->iter.ptr), pi->type, &r);
851 PyObject *pr = PyObject_FromCvScalar(r, pi->type);
853 CV_NEXT_LINE_POINT(pi->iter);
861 static PyTypeObject cvlineiterator_Type = {
862 PyObject_HEAD_INIT(&PyType_Type)
864 OLD_MODULESTR".cvlineiterator", /*name*/
865 sizeof(cvlineiterator_t), /*basicsize*/
868 static void cvlineiterator_specials(void)
870 cvlineiterator_Type.tp_iter = cvlineiterator_iter;
871 cvlineiterator_Type.tp_iternext = cvlineiterator_next;
874 /************************************************************************/
878 /* Motivation for memtrack is when the storage for a Mat is an array or buffer
879 object. By setting 'data' to be a memtrack, can deallocate the storage at
882 For array objects, 'backing' is the actual storage object. memtrack holds the reference,
883 then DECREF's it at dealloc.
885 For MatND's, we need to cvDecRefData() on release, and this is what field 'backingmat' is for.
887 If freeptr is true, then a straight cvFree() of ptr happens.
892 static void memtrack_dealloc(PyObject *self)
894 memtrack_t *pi = (memtrack_t*)self;
896 Py_DECREF(pi->backing);
898 cvDecRefData(pi->backingmat);
904 static PyTypeObject memtrack_Type = {
905 PyObject_HEAD_INIT(&PyType_Type)
907 OLD_MODULESTR".memtrack", /*name*/
908 sizeof(memtrack_t), /*basicsize*/
911 Py_ssize_t memtrack_getreadbuffer(PyObject *self, Py_ssize_t segment, void **ptrptr)
913 *ptrptr = &((memtrack_t*)self)->ptr;
914 return ((memtrack_t*)self)->size;
917 Py_ssize_t memtrack_getwritebuffer(PyObject *self, Py_ssize_t segment, void **ptrptr)
919 *ptrptr = ((memtrack_t*)self)->ptr;
920 return ((memtrack_t*)self)->size;
923 Py_ssize_t memtrack_getsegcount(PyObject *self, Py_ssize_t *lenp)
925 return (Py_ssize_t)1;
928 PyBufferProcs memtrack_as_buffer = {
929 memtrack_getreadbuffer,
930 memtrack_getwritebuffer,
934 static void memtrack_specials(void)
936 memtrack_Type.tp_dealloc = memtrack_dealloc;
937 memtrack_Type.tp_as_buffer = &memtrack_as_buffer;
940 /************************************************************************/
944 static void cvmemstorage_dealloc(PyObject *self)
946 cvmemstorage_t *ps = (cvmemstorage_t*)self;
947 cvReleaseMemStorage(&(ps->a));
951 static PyTypeObject cvmemstorage_Type = {
952 PyObject_HEAD_INIT(&PyType_Type)
954 OLD_MODULESTR".cvmemstorage", /*name*/
955 sizeof(cvmemstorage_t), /*basicsize*/
958 static void cvmemstorage_specials(void)
960 cvmemstorage_Type.tp_dealloc = cvmemstorage_dealloc;
963 /************************************************************************/
967 static PyTypeObject cvfont_Type = {
968 PyObject_HEAD_INIT(&PyType_Type)
970 OLD_MODULESTR".cvfont", /*name*/
971 sizeof(cvfont_t), /*basicsize*/
974 static void cvfont_specials(void) { }
976 /************************************************************************/
980 static PyTypeObject cvrng_Type = {
981 PyObject_HEAD_INIT(&PyType_Type)
983 OLD_MODULESTR".cvrng", /*name*/
984 sizeof(cvrng_t), /*basicsize*/
987 static void cvrng_specials(void)
991 /************************************************************************/
995 static PyTypeObject cvcontourtree_Type = {
996 PyObject_HEAD_INIT(&PyType_Type)
998 OLD_MODULESTR".cvcontourtree", /*name*/
999 sizeof(cvcontourtree_t), /*basicsize*/
1002 static void cvcontourtree_specials(void) { }
1005 /************************************************************************/
1007 /* cvsubdiv2dedge */
1009 static PyTypeObject cvsubdiv2dedge_Type = {
1010 PyObject_HEAD_INIT(&PyType_Type)
1012 OLD_MODULESTR".cvsubdiv2dedge", /*name*/
1013 sizeof(cvsubdiv2dedge_t), /*basicsize*/
1016 static int cvsubdiv2dedge_compare(PyObject *o1, PyObject *o2)
1018 cvsubdiv2dedge_t *e1 = (cvsubdiv2dedge_t*)o1;
1019 cvsubdiv2dedge_t *e2 = (cvsubdiv2dedge_t*)o2;
1022 else if (e1->a > e2->a)
1028 static PyObject *cvquadedge_repr(PyObject *self)
1030 CvSubdiv2DEdge m = ((cvsubdiv2dedge_t*)self)->a;
1032 sprintf(str, "<cvsubdiv2dedge(");
1033 char *d = str + strlen(str);
1034 sprintf(d, "%lux.%d", (unsigned long)(m & ~3), (int)(m & 3));
1037 return PyString_FromString(str);
1040 static void cvsubdiv2dedge_specials(void) {
1041 cvsubdiv2dedge_Type.tp_compare = cvsubdiv2dedge_compare;
1042 cvsubdiv2dedge_Type.tp_repr = cvquadedge_repr;
1045 /************************************************************************/
1049 static void cvseq_dealloc(PyObject *self)
1051 cvseq_t *ps = (cvseq_t*)self;
1052 Py_DECREF(ps->container);
1056 static PyObject *cvseq_h_next(PyObject *self, PyObject *args);
1057 static PyObject *cvseq_h_prev(PyObject *self, PyObject *args);
1058 static PyObject *cvseq_v_next(PyObject *self, PyObject *args);
1059 static PyObject *cvseq_v_prev(PyObject *self, PyObject *args);
1061 static struct PyMethodDef cvseq_methods[] =
1063 {"h_next", cvseq_h_next, METH_VARARGS},
1064 {"h_prev", cvseq_h_prev, METH_VARARGS},
1065 {"v_next", cvseq_v_next, METH_VARARGS},
1066 {"v_prev", cvseq_v_prev, METH_VARARGS},
1070 static Py_ssize_t cvseq_seq_length(PyObject *o)
1072 cvseq_t *ps = (cvseq_t*)o;
1074 return (Py_ssize_t)0;
1076 return (Py_ssize_t)(ps->a->total);
1079 static PyObject* cvseq_seq_getitem(PyObject *o, Py_ssize_t i)
1081 cvseq_t *ps = (cvseq_t*)o;
1089 if (i < cvseq_seq_length(o)) {
1090 switch (CV_SEQ_ELTYPE(ps->a)) {
1092 case CV_SEQ_ELTYPE_POINT:
1093 pt = CV_GET_SEQ_ELEM(CvPoint, ps->a, (int)i);
1094 return Py_BuildValue("ii", pt->x, pt->y);
1096 case CV_SEQ_ELTYPE_GENERIC:
1097 switch (ps->a->elem_size) {
1098 case sizeof(CvQuadEdge2D):
1100 cvsubdiv2dedge_t *r = PyObject_NEW(cvsubdiv2dedge_t, &cvsubdiv2dedge_Type);
1101 r->a = (CvSubdiv2DEdge)CV_GET_SEQ_ELEM(CvQuadEdge2D, ps->a, (int)i);
1102 r->container = ps->container;
1103 Py_INCREF(r->container);
1104 return (PyObject*)r;
1106 case sizeof(CvConnectedComp):
1108 CvConnectedComp *cc = CV_GET_SEQ_ELEM(CvConnectedComp, ps->a, (int)i);
1109 return FROM_CvConnectedComp(*cc);
1112 printf("seq elem size is %d\n", ps->a->elem_size);
1113 printf("KIND %d\n", CV_SEQ_KIND(ps->a));
1116 return PyInt_FromLong(*CV_GET_SEQ_ELEM(unsigned char, ps->a, (int)i));
1118 case CV_SEQ_ELTYPE_PTR:
1119 case CV_SEQ_ELTYPE_INDEX:
1120 return PyInt_FromLong(*CV_GET_SEQ_ELEM(int, ps->a, (int)i));
1123 pp = CV_GET_SEQ_ELEM(pointpair, ps->a, (int)i);
1124 return Py_BuildValue("(ii),(ii)", pp->a.x, pp->a.y, pp->b.x, pp->b.y);
1127 pt2 = CV_GET_SEQ_ELEM(CvPoint2D32f, ps->a, (int)i);
1128 return Py_BuildValue("ff", pt2->x, pt2->y);
1130 case CV_SEQ_ELTYPE_POINT3D:
1131 pt3 = CV_GET_SEQ_ELEM(CvPoint3D32f, ps->a, (int)i);
1132 return Py_BuildValue("fff", pt3->x, pt3->y, pt3->z);
1135 printf("Unknown element type %08x\n", CV_SEQ_ELTYPE(ps->a));
1143 static PyObject* cvseq_map_getitem(PyObject *o, PyObject *item)
1145 if (PyInt_Check(item)) {
1146 int i = (int)PyInt_AS_LONG(item);
1148 i += (int)cvseq_seq_length(o);
1149 return cvseq_seq_getitem(o, i);
1150 } else if (PySlice_Check(item)) {
1151 Py_ssize_t start, stop, step, slicelength, cur, i;
1154 if (PySlice_GetIndicesEx((PySliceObject*)item, cvseq_seq_length(o),
1155 &start, &stop, &step, &slicelength) < 0) {
1159 if (slicelength <= 0) {
1160 return PyList_New(0);
1162 result = PyList_New(slicelength);
1163 if (!result) return NULL;
1165 for (cur = start, i = 0; i < slicelength;
1167 PyList_SET_ITEM(result, i, cvseq_seq_getitem(o, cur));
1173 PyErr_SetString(PyExc_TypeError, "CvSeq indices must be integers");
1179 PySequenceMethods cvseq_sequence = {
1186 static PyMappingMethods cvseq_mapping = {
1192 static PyTypeObject cvseq_Type = {
1193 PyObject_HEAD_INIT(&PyType_Type)
1195 OLD_MODULESTR".cvseq", /*name*/
1196 sizeof(cvseq_t), /*basicsize*/
1199 static void cvseq_specials(void)
1201 cvseq_Type.tp_dealloc = cvseq_dealloc;
1202 cvseq_Type.tp_as_sequence = &cvseq_sequence;
1203 cvseq_Type.tp_as_mapping = &cvseq_mapping;
1204 cvseq_Type.tp_methods = cvseq_methods;
1207 #define MK_ACCESSOR(FIELD) \
1208 static PyObject *cvseq_##FIELD(PyObject *self, PyObject *args) \
1210 cvseq_t *ps = (cvseq_t*)self; \
1212 if (s->FIELD == NULL) { \
1215 cvseq_t *r = PyObject_NEW(cvseq_t, &cvseq_Type); \
1217 r->container = ps->container; \
1218 Py_INCREF(r->container); \
1219 return (PyObject*)r; \
1229 /************************************************************************/
1233 static void cvset_dealloc(PyObject *self)
1235 cvset_t *ps = (cvset_t*)self;
1236 Py_DECREF(ps->container);
1240 static PyTypeObject cvset_Type = {
1241 PyObject_HEAD_INIT(&PyType_Type)
1243 OLD_MODULESTR".cvset", /*name*/
1244 sizeof(cvset_t), /*basicsize*/
1247 static PyObject *cvset_iter(PyObject *o)
1250 cvset_t *ps = (cvset_t*)o;
1255 static PyObject *cvset_next(PyObject *o)
1257 cvset_t *ps = (cvset_t*)o;
1259 while (ps->i < ps->a->total) {
1260 CvSetElem *e = cvGetSetElem(ps->a, ps->i);
1261 int prev_i = ps->i++;
1263 return cvseq_seq_getitem(o, prev_i);
1269 static void cvset_specials(void)
1271 cvset_Type.tp_dealloc = cvset_dealloc;
1272 cvset_Type.tp_iter = cvset_iter;
1273 cvset_Type.tp_iternext = cvset_next;
1276 /************************************************************************/
1280 static PyTypeObject cvsubdiv2d_Type = {
1281 PyObject_HEAD_INIT(&PyType_Type)
1283 OLD_MODULESTR".cvsubdiv2d", /*name*/
1284 sizeof(cvsubdiv2d_t), /*basicsize*/
1287 static PyObject *cvsubdiv2d_getattro(PyObject *o, PyObject *name)
1289 cvsubdiv2d_t *p = (cvsubdiv2d_t*)o;
1290 if (strcmp(PyString_AsString(name), "edges") == 0) {
1291 cvset_t *r = PyObject_NEW(cvset_t, &cvset_Type);
1293 r->container = p->container;
1294 Py_INCREF(r->container);
1295 return (PyObject*)r;
1297 PyErr_SetString(PyExc_TypeError, "cvsubdiv2d has no such attribute");
1302 static void cvsubdiv2d_specials(void)
1304 cvsubdiv2d_Type.tp_getattro = cvsubdiv2d_getattro;
1307 /************************************************************************/
1309 /* cvsubdiv2dpoint */
1311 static PyTypeObject cvsubdiv2dpoint_Type = {
1312 PyObject_HEAD_INIT(&PyType_Type)
1314 OLD_MODULESTR".cvsubdiv2dpoint", /*name*/
1315 sizeof(cvsubdiv2dpoint_t), /*basicsize*/
1318 static PyObject *cvsubdiv2dpoint_getattro(PyObject *o, PyObject *name)
1320 cvsubdiv2dpoint_t *p = (cvsubdiv2dpoint_t*)o;
1321 if (strcmp(PyString_AsString(name), "first") == 0) {
1322 cvsubdiv2dedge_t *r = PyObject_NEW(cvsubdiv2dedge_t, &cvsubdiv2dedge_Type);
1324 r->container = p->container;
1325 Py_INCREF(r->container);
1326 return (PyObject*)r;
1327 } else if (strcmp(PyString_AsString(name), "pt") == 0) {
1328 return Py_BuildValue("(ff)", p->a->pt.x, p->a->pt.y);
1330 PyErr_SetString(PyExc_TypeError, "cvsubdiv2dpoint has no such attribute");
1335 static void cvsubdiv2dpoint_specials(void)
1337 cvsubdiv2dpoint_Type.tp_getattro = cvsubdiv2dpoint_getattro;
1340 /************************************************************************/
1341 /* convert_to_X: used after PyArg_ParseTuple in the generated code */
1343 /*static int convert_to_PyObjectPTR(PyObject *o, PyObject **dst, const char *name = "no_name")
1349 static int convert_to_PyCallableObjectPTR(PyObject *o, PyObject **dst, const char *name = "no_name")
1355 static int convert_to_char(PyObject *o, char *dst, const char *name = "no_name")
1357 if (PyString_Check(o) && PyString_Size(o) == 1) {
1358 *dst = PyString_AsString(o)[0];
1362 return failmsg("Expected single character string for argument '%s'", name);
1366 static int convert_to_CvMemStorage(PyObject *o, CvMemStorage **dst, const char *name = "no_name")
1368 if (PyType_IsSubtype(o->ob_type, &cvmemstorage_Type)) {
1369 (*dst) = (((cvmemstorage_t*)o)->a);
1372 (*dst) = (CvMemStorage*)NULL;
1373 return failmsg("Expected CvMemStorage for argument '%s'", name);
1377 static int convert_to_CvSeq(PyObject *o, CvSeq **dst, const char *name = "no_name")
1379 if (PyType_IsSubtype(o->ob_type, &cvseq_Type)) {
1380 (*dst) = (((cvseq_t*)o)->a);
1383 (*dst) = (CvSeq*)NULL;
1384 return failmsg("Expected CvSeq for argument '%s'", name);
1388 static int convert_to_CvSize(PyObject *o, CvSize *dst, const char *name = "no_name")
1390 if (!PyArg_ParseTuple(o, "ii", &dst->width, &dst->height))
1391 return failmsg("CvSize argument '%s' expects two integers", name);
1396 static int convert_to_CvScalar(PyObject *o, CvScalar *s, const char *name = "no_name")
1398 if (PySequence_Check(o)) {
1399 PyObject *fi = PySequence_Fast(o, name);
1402 if (4 < PySequence_Fast_GET_SIZE(fi))
1403 return failmsg("CvScalar value for argument '%s' is longer than 4", name);
1404 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
1405 PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
1406 if (PyFloat_Check(item) || PyInt_Check(item)) {
1407 s->val[i] = PyFloat_AsDouble(item);
1409 return failmsg("CvScalar value for argument '%s' is not numeric", name);
1414 if (PyFloat_Check(o) || PyInt_Check(o)) {
1415 s->val[0] = PyFloat_AsDouble(o);
1417 return failmsg("CvScalar value for argument '%s' is not numeric", name);
1423 static int convert_to_CvPointPTR(PyObject *o, CvPoint **p, const char *name = "no_name")
1425 if (!PySequence_Check(o))
1426 return failmsg("Expected sequence for point list argument '%s'", name);
1427 PyObject *fi = PySequence_Fast(o, name);
1430 *p = new CvPoint[PySequence_Fast_GET_SIZE(fi)];
1431 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
1432 PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
1433 if (!PyTuple_Check(item))
1434 return failmsg("Expected tuple for element in point list argument '%s'", name);
1435 if (!PyArg_ParseTuple(item, "ii", &((*p)[i].x), &((*p)[i].y))) {
1443 static int convert_to_CvPoint2D32fPTR(PyObject *o, CvPoint2D32f **p, const char *name = "no_name")
1445 PyObject *fi = PySequence_Fast(o, name);
1448 *p = new CvPoint2D32f[PySequence_Fast_GET_SIZE(fi)];
1449 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
1450 PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
1451 if (!PyTuple_Check(item))
1452 return failmsg("Expected tuple for CvPoint2D32f argument '%s'", name);
1453 if (!PyArg_ParseTuple(item, "ff", &((*p)[i].x), &((*p)[i].y))) {
1462 static int convert_to_CvPoint3D32fPTR(PyObject *o, CvPoint3D32f **p, const char *name = "no_name")
1464 PyObject *fi = PySequence_Fast(o, name);
1467 *p = new CvPoint3D32f[PySequence_Fast_GET_SIZE(fi)];
1468 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
1469 PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
1470 if (!PyTuple_Check(item))
1471 return failmsg("Expected tuple for CvPoint3D32f argument '%s'", name);
1472 if (!PyArg_ParseTuple(item, "fff", &((*p)[i].x), &((*p)[i].y), &((*p)[i].z))) {
1481 static int convert_to_CvStarDetectorParams(PyObject *o, CvStarDetectorParams *dst, const char *name = "no_name")
1483 if (!PyArg_ParseTuple(o,
1486 &dst->responseThreshold,
1487 &dst->lineThresholdProjected,
1488 &dst->lineThresholdBinarized,
1489 &dst->suppressNonmaxSize))
1490 return failmsg("CvRect argument '%s' expects four integers", name);
1495 static int convert_to_CvRect(PyObject *o, CvRect *dst, const char *name = "no_name")
1497 if (!PyArg_ParseTuple(o, "iiii", &dst->x, &dst->y, &dst->width, &dst->height))
1498 return failmsg("CvRect argument '%s' expects four integers", name);
1503 static int convert_to_CvRectPTR(PyObject *o, CvRect **dst, const char *name = "no_name")
1506 if (!PyArg_ParseTuple(o, "iiii", &(*dst)->x, &(*dst)->y, &(*dst)->width, &(*dst)->height))
1507 return failmsg("CvRect argument '%s' expects four integers", name);
1512 static int convert_to_CvSlice(PyObject *o, CvSlice *dst, const char *name = "no_name")
1514 if (!PyArg_ParseTuple(o, "ii", &dst->start_index, &dst->end_index))
1515 return failmsg("CvSlice argument '%s' expects two integers", name);
1520 static int convert_to_CvPoint(PyObject *o, CvPoint *dst, const char *name = "no_name")
1522 if (!PyArg_ParseTuple(o, "ii", &dst->x, &dst->y))
1523 return failmsg("CvPoint argument '%s' expects two integers", name);
1528 static int convert_to_CvPoint2D32f(PyObject *o, CvPoint2D32f *dst, const char *name = "no_name")
1530 if (!PyArg_ParseTuple(o, "ff", &dst->x, &dst->y))
1531 return failmsg("CvPoint2D32f argument '%s' expects two floats", name);
1536 static int convert_to_CvPoint3D32f(PyObject *o, CvPoint3D32f *dst, const char *name = "no_name")
1538 if (!PyArg_ParseTuple(o, "fff", &dst->x, &dst->y, &dst->z))
1539 return failmsg("CvPoint3D32f argument '%s' expects three floats", name);
1544 static int convert_to_IplImage(PyObject *o, IplImage **dst, const char *name)
1546 iplimage_t *ipl = (iplimage_t*)o;
1548 Py_ssize_t buffer_len;
1550 if (!is_iplimage(o)) {
1551 return failmsg("Argument '%s' must be IplImage", name);
1552 } else if (PyString_Check(ipl->data)) {
1553 cvSetData(ipl->a, PyString_AsString(ipl->data) + ipl->offset, ipl->a->widthStep);
1554 assert(cvGetErrStatus() == 0);
1557 } else if (ipl->data && PyObject_AsWriteBuffer(ipl->data, &buffer, &buffer_len) == 0) {
1558 cvSetData(ipl->a, (void*)((char*)buffer + ipl->offset), ipl->a->widthStep);
1559 assert(cvGetErrStatus() == 0);
1563 return failmsg("IplImage argument '%s' has no data", name);
1567 static int convert_to_CvMat(PyObject *o, CvMat **dst, const char *name)
1569 cvmat_t *m = (cvmat_t*)o;
1571 Py_ssize_t buffer_len;
1574 //#if !PYTHON_USE_NUMPY
1575 return failmsg("Argument '%s' must be CvMat. Use fromarray() to convert numpy arrays to CvMat", name);
1577 PyObject *asmat = fromarray(o, 0);
1579 return failmsg("Argument '%s' must be CvMat", name);
1580 // now have the array obect as a cvmat, can use regular conversion
1581 return convert_to_CvMat(asmat, dst, name);
1584 m->a->refcount = NULL;
1585 if (m->data && PyString_Check(m->data)) {
1586 assert(cvGetErrStatus() == 0);
1587 char *ptr = PyString_AsString(m->data) + m->offset;
1588 cvSetData(m->a, ptr, m->a->step);
1589 assert(cvGetErrStatus() == 0);
1592 } else if (m->data && PyObject_AsWriteBuffer(m->data, &buffer, &buffer_len) == 0) {
1593 cvSetData(m->a, (void*)((char*)buffer + m->offset), m->a->step);
1594 assert(cvGetErrStatus() == 0);
1597 } else if (m->data && m->a->data.ptr){
1602 return failmsg("CvMat argument '%s' has no data", name);
1607 static int convert_to_CvMatND(PyObject *o, CvMatND **dst, const char *name)
1609 cvmatnd_t *m = (cvmatnd_t*)o;
1611 Py_ssize_t buffer_len;
1613 if (!is_cvmatnd(o)) {
1614 return failmsg("Argument '%s' must be CvMatND", name);
1615 } else if (m->data && PyString_Check(m->data)) {
1616 m->a->data.ptr = ((uchar*)PyString_AsString(m->data)) + m->offset;
1619 } else if (m->data && PyObject_AsWriteBuffer(m->data, &buffer, &buffer_len) == 0) {
1620 m->a->data.ptr = ((uchar*)buffer + m->offset);
1624 return failmsg("CvMatND argument '%s' has no data", name);
1628 static int convert_to_CvArr(PyObject *o, CvArr **dst, const char *name)
1633 } else if (is_iplimage(o)) {
1634 return convert_to_IplImage(o, (IplImage**)dst, name);
1635 } else if (is_cvmat(o)) {
1636 return convert_to_CvMat(o, (CvMat**)dst, name);
1637 } else if (is_cvmatnd(o)) {
1638 return convert_to_CvMatND(o, (CvMatND**)dst, name);
1640 //#if !PYTHON_USE_NUMPY
1641 return failmsg("CvArr argument '%s' must be IplImage, CvMat or CvMatND. Use fromarray() to convert numpy arrays to CvMat or cvMatND", name);
1643 PyObject *asmat = fromarray(o, 0);
1645 return failmsg("CvArr argument '%s' must be IplImage, CvMat, CvMatND, or support the array interface", name);
1646 // now have the array obect as a cvmat, can use regular conversion
1647 return convert_to_CvArr(asmat, dst, name);
1652 static int convert_to_CvHistogram(PyObject *o, CvHistogram **dst, const char *name = "no_name")
1654 if (PyType_IsSubtype(o->ob_type, &cvhistogram_Type)) {
1655 cvhistogram_t *ht = (cvhistogram_t*)o;
1657 return convert_to_CvArr(ht->bins, &(ht->h.bins), "bins");
1659 *dst = (CvHistogram *)NULL;
1660 return failmsg("Expected CvHistogram for argument '%s'", name);
1664 // Used by FillPoly, FillConvexPoly, PolyLine
1665 struct pts_npts_contours {
1671 static int convert_to_pts_npts_contours(PyObject *o, pts_npts_contours *dst, const char *name = "no_name")
1673 PyObject *fi = PySequence_Fast(o, name);
1676 dst->contours = (int)PySequence_Fast_GET_SIZE(fi);
1677 dst->pts = new CvPoint*[dst->contours];
1678 dst->npts = new int[dst->contours];
1679 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
1680 if (!convert_to_CvPointPTR(PySequence_Fast_GET_ITEM(fi, i), &dst->pts[i], name))
1682 dst->npts[i] = (int)PySequence_Size(PySequence_Fast_GET_ITEM(fi, i)); // safe because convert_ just succeeded
1700 cvReleaseMat((CvMat**)&mat);
1705 static int is_convertible_to_mat(PyObject *o)
1707 #if PYTHON_USE_NUMPY
1708 if (PyObject_HasAttrString(o, "__array_struct__")) {
1709 PyObject *ao = PyObject_GetAttrString(o, "__array_struct__");
1711 PyCObject_Check(ao) &&
1712 ((PyArrayInterface*)PyCObject_AsVoidPtr(ao))->two == 2) {
1717 return is_iplimage(o) && is_cvmat(o) && is_cvmatnd(o);
1720 static int convert_to_cvarrseq(PyObject *o, cvarrseq *dst, const char *name = "no_name")
1722 if (PyType_IsSubtype(o->ob_type, &cvseq_Type)) {
1723 return convert_to_CvSeq(o, &(dst->seq), name);
1724 } else if (is_convertible_to_mat(o)) {
1725 int r = convert_to_CvArr(o, &(dst->mat), name);
1727 } else if (PySequence_Check(o)) {
1728 PyObject *fi = PySequence_Fast(o, name);
1731 Py_ssize_t size = -1;
1732 // Make a pass through the sequence, checking that each element is
1733 // a sequence and that they are all the same size
1734 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
1735 PyObject *e = PySequence_Fast_GET_ITEM(fi, i);
1737 if (!PySequence_Check(e))
1738 return failmsg("Sequence '%s' must contain sequences", name);
1740 size = (int)PySequence_Size(e);
1741 else if (size != PySequence_Size(e))
1742 return failmsg("All elements of sequence '%s' must be same size", name);
1745 CvMat *mt = cvCreateMat((int)PySequence_Fast_GET_SIZE(fi), 1, CV_32SC((int)size));
1746 dst->freemat = true; // dealloc this mat when done
1747 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
1748 PyObject *e = PySequence_Fast_GET_ITEM(fi, i);
1749 PyObject *fe = PySequence_Fast(e, name);
1751 int *pdst = (int*)cvPtr2D(mt, (int)i, 0);
1752 for (Py_ssize_t j = 0; j < size; j++) {
1753 PyObject *num = PySequence_Fast_GET_ITEM(fe, j);
1754 if (!PyNumber_Check(num)) {
1755 return failmsg("Sequence must contain numbers", name);
1757 *pdst++ = PyInt_AsLong(num);
1765 return failmsg("Argument '%s' must be CvSeq, CvArr, or a sequence of numbers");
1769 struct cvarr_count {
1774 static int convert_to_cvarr_count(PyObject *o, cvarr_count *dst, const char *name = "no_name")
1776 PyObject *fi = PySequence_Fast(o, name);
1779 dst->count = (int)PySequence_Fast_GET_SIZE(fi);
1780 dst->cvarr = new CvArr*[dst->count];
1781 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
1782 if (!convert_to_CvArr(PySequence_Fast_GET_ITEM(fi, i), &dst->cvarr[i], name))
1795 static int convert_to_intpair(PyObject *o, intpair *dst, const char *name = "no_name")
1797 PyObject *fi = PySequence_Fast(o, name);
1800 dst->count = (int)PySequence_Fast_GET_SIZE(fi);
1801 dst->pairs = new int[2 * dst->count];
1802 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
1803 PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
1804 if (!PyArg_ParseTuple(item, "ii", &dst->pairs[2 * i], &dst->pairs[2 * i + 1])) {
1812 struct cvpoint2d32f_count {
1813 CvPoint2D32f* points;
1817 static int convert_to_cvpoint2d32f_count(PyObject *o, cvpoint2d32f_count *dst, const char *name = "no_name")
1819 if (PyInt_Check(o)) {
1820 dst->count = PyInt_AsLong(o);
1821 dst->points = new CvPoint2D32f[dst->count];
1824 return failmsg("Expected integer for CvPoint2D32f count");
1832 static int convert_to_floats(PyObject *o, floats *dst, const char *name = "no_name")
1834 if (PySequence_Check(o)) {
1835 PyObject *fi = PySequence_Fast(o, name);
1838 dst->count = (int)PySequence_Fast_GET_SIZE(fi);
1839 dst->f = new float[dst->count];
1840 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
1841 PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
1842 dst->f[i] = (float)PyFloat_AsDouble(item);
1845 } else if (PyNumber_Check(o)) {
1847 dst->f = new float[1];
1848 dst->f[0] = (float)PyFloat_AsDouble(o);
1850 return failmsg("Expected list of floats, or float for argument '%s'", name);
1859 /// convert_to_chars not used
1865 static int convert_to_CvPoints(PyObject *o, CvPoints *dst, const char *name = "no_name")
1867 PyObject *fi = PySequence_Fast(o, name);
1870 dst->count = (int)PySequence_Fast_GET_SIZE(fi);
1871 dst->p = new CvPoint[dst->count];
1872 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
1873 PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
1874 convert_to_CvPoint(item, &dst->p[i], name);
1880 struct CvPoint3D32fs {
1884 static int convert_to_CvPoint3D32fs(PyObject *o, CvPoint3D32fs *dst, const char *name = "no_name")
1886 PyObject *fi = PySequence_Fast(o, name);
1889 dst->count = (int)PySequence_Fast_GET_SIZE(fi);
1890 dst->p = new CvPoint3D32f[dst->count];
1891 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
1892 PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
1893 convert_to_CvPoint3D32f(item, &dst->p[i], name);
1899 struct CvPoint2D32fs {
1903 static int convert_to_CvPoint2D32fs(PyObject *o, CvPoint2D32fs *dst, const char *name = "no_name")
1905 PyObject *fi = PySequence_Fast(o, name);
1908 dst->count = (int)PySequence_Fast_GET_SIZE(fi);
1909 dst->p = new CvPoint2D32f[dst->count];
1910 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
1911 PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
1912 convert_to_CvPoint2D32f(item, &dst->p[i], name);
1922 static int convert_to_ints(PyObject *o, ints *dst, const char *name = "no_name")
1924 PyObject *fi = PySequence_Fast(o, name);
1927 dst->count = (int)PySequence_Fast_GET_SIZE(fi);
1928 dst->i = new int[dst->count];
1929 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
1930 PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
1931 dst->i[i] = PyInt_AsLong(item);
1941 static int convert_to_ints0(PyObject *o, ints0 *dst, const char *name = "no_name")
1943 PyObject *fi = PySequence_Fast(o, name);
1946 dst->count = (int)PySequence_Fast_GET_SIZE(fi);
1947 dst->i = new int[dst->count + 1];
1948 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
1949 PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
1950 dst->i[i] = PyInt_AsLong(item);
1952 dst->i[dst->count] = 0;
1961 int step[CV_MAX_DIM];
1962 int length[CV_MAX_DIM];
1965 static int convert_to_dim(PyObject *item, int i, dims *dst, CvArr *cva, const char *name = "no_name")
1967 if (PySlice_Check(item)) {
1968 Py_ssize_t start, stop, step, slicelength;
1969 PySlice_GetIndicesEx((PySliceObject*)item, cvGetDimSize(cva, i), &start, &stop, &step, &slicelength);
1970 dst->i[i] = (int)start;
1971 dst->step[i] = (int)step;
1972 dst->length[i] = (int)slicelength;
1974 int index = PyInt_AsLong(item);
1978 dst->i[i] = cvGetDimSize(cva, i) + index;
1985 static int convert_to_dims(PyObject *o, dims *dst, CvArr *cva, const char *name = "no_name")
1987 if (!PyTuple_Check(o)) {
1989 return convert_to_dim(o, 0, dst, cva, name);
1991 PyObject *fi = PySequence_Fast(o, name);
1993 PyErr_SetString(PyExc_TypeError, "Expected tuple for index");
1996 dst->count = (int)PySequence_Fast_GET_SIZE(fi);
1997 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
1998 if (i >= cvGetDims(cva)) {
1999 return failmsg("Access specifies %d dimensions, but array only has %d", PySequence_Fast_GET_SIZE(fi), cvGetDims(cva));
2001 PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
2002 if (!convert_to_dim(item, (int)i, dst, cva, name))
2014 static int convert_to_IplImages(PyObject *o, IplImages *dst, const char *name = "no_name")
2016 PyObject *fi = PySequence_Fast(o, name);
2019 dst->count = (int)PySequence_Fast_GET_SIZE(fi);
2020 dst->ims = new IplImage*[dst->count];
2021 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
2022 PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
2023 if (!convert_to_IplImage(item, &dst->ims[i]))
2034 static int convert_to_CvArrs(PyObject *o, CvArrs *dst, const char *name = "no_name")
2036 PyObject *fi = PySequence_Fast(o, name);
2039 dst->count = (int)PySequence_Fast_GET_SIZE(fi);
2040 dst->ims = new CvArr*[dst->count];
2041 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
2042 PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
2043 if (!convert_to_CvArr(item, &dst->ims[i]))
2050 /*static int convert_to_floatPTRPTR(PyObject *o, float*** dst, const char *name = "no_name")
2052 PyObject *fi = PySequence_Fast(o, name);
2055 Py_ssize_t sz = (int)PySequence_Fast_GET_SIZE(fi);
2056 float **r = new float*[sz];
2057 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
2058 PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
2060 if (!convert_to_floats(item, &ff))
2068 static int convert_to_CvFontPTR(PyObject *o, CvFont** dst, const char *name = "no_name")
2070 if (PyType_IsSubtype(o->ob_type, &cvfont_Type)) {
2071 (*dst) = &(((cvfont_t*)o)->a);
2074 (*dst) = (CvFont*)NULL;
2075 return failmsg("Expected CvFont for argument '%s'", name);
2079 /*static int convert_to_CvContourTreePTR(PyObject *o, CvContourTree** dst, const char *name = "no_name")
2081 if (PyType_IsSubtype(o->ob_type, &cvcontourtree_Type)) {
2082 (*dst) = ((cvcontourtree_t*)o)->a;
2086 return failmsg("Expected CvContourTree for argument '%s'", name);
2090 static int convert_to_CvRNGPTR(PyObject *o, CvRNG** dst, const char *name = "no_name")
2092 if (PyType_IsSubtype(o->ob_type, &cvrng_Type)) {
2093 (*dst) = &(((cvrng_t*)o)->a);
2096 (*dst) = (CvRNG*)NULL;
2097 return failmsg("Expected CvRNG for argument '%s'", name);
2101 typedef void* generic;
2102 static int convert_to_generic(PyObject *o, generic *dst, const char *name = "no_name")
2104 if (PyType_IsSubtype(o->ob_type, &iplimage_Type))
2105 return convert_to_IplImage(o, (IplImage**)dst, name);
2106 else if (PyType_IsSubtype(o->ob_type, &cvmat_Type))
2107 return convert_to_CvMat(o, (CvMat**)dst, name);
2108 else if (PyType_IsSubtype(o->ob_type, &cvmatnd_Type))
2109 return convert_to_CvMatND(o, (CvMatND**)dst, name);
2111 return failmsg("Cannot identify type of '%s'", name);
2115 static int convert_to_CvTermCriteria(PyObject *o, CvTermCriteria* dst, const char *name = "no_name")
2117 if (!PyArg_ParseTuple(o, "iid", &dst->type, &dst->max_iter, &dst->epsilon))
2122 static int convert_to_CvBox2D(PyObject *o, CvBox2D* dst, const char *name = "no_name")
2124 if (!PyArg_ParseTuple(o, "(ff)(ff)f", &dst->center.x, &dst->center.y, &dst->size.width, &dst->size.height, &dst->angle))
2129 static int convert_to_CvSubdiv2DPTR(PyObject *o, CvSubdiv2D** dst, const char *name = "no_name")
2131 if (PyType_IsSubtype(o->ob_type, &cvsubdiv2d_Type)) {
2132 (*dst) = (((cvsubdiv2d_t*)o)->a);
2135 (*dst) = (CvSubdiv2D*)NULL;
2136 return failmsg("Expected CvSubdiv2D for argument '%s'", name);
2140 static int convert_to_CvNextEdgeType(PyObject *o, CvNextEdgeType *dst, const char *name = "no_name")
2142 if (!PyInt_Check(o)) {
2143 *dst = (CvNextEdgeType)NULL;
2144 return failmsg("Expected number for CvNextEdgeType argument '%s'", name);
2146 *dst = (CvNextEdgeType)PyInt_AsLong(o);
2151 static int convert_to_CvSubdiv2DEdge(PyObject *o, CvSubdiv2DEdge *dst, const char *name = "no_name")
2153 if (PyType_IsSubtype(o->ob_type, &cvsubdiv2dedge_Type)) {
2154 (*dst) = (((cvsubdiv2dedge_t*)o)->a);
2158 return failmsg("Expected CvSubdiv2DEdge for argument '%s'", name);
2162 /************************************************************************/
2164 static PyObject *pythonize_CvMat(cvmat_t *m)
2166 // Need to make this CvMat look like any other, with a Python
2167 // buffer object as its data.
2169 assert(mat->step != 0);
2171 PyObject *data = PyString_FromStringAndSize((char*)(mat->data.ptr), mat->rows * mat->step);
2173 memtrack_t *o = PyObject_NEW(memtrack_t, &memtrack_Type);
2174 size_t gap = mat->data.ptr - (uchar*)mat->refcount;
2175 o->ptr = mat->refcount;
2176 o->owner = __LINE__;
2178 o->size = gap + mat->rows * mat->step;
2180 o->backingmat = NULL;
2181 PyObject *data = PyBuffer_FromReadWriteObject((PyObject*)o, (size_t)gap, mat->rows * mat->step);
2189 // Now m has a reference to data, which has a reference to o.
2191 return (PyObject*)m;
2194 static PyObject *pythonize_IplImage(iplimage_t *cva)
2196 // Need to make this iplimage look like any other, with a Python
2197 // string as its data.
2198 // So copy the image data into a Python string object, then release
2201 IplImage *ipl = (IplImage*)(cva->a);
2202 // PyObject *data = PyString_FromStringAndSize(ipl->imageData, ipl->imageSize);
2204 memtrack_t *o = PyObject_NEW(memtrack_t, &memtrack_Type);
2205 assert(ipl->imageDataOrigin == ipl->imageData);
2206 o->ptr = ipl->imageDataOrigin;
2207 o->owner = __LINE__;
2209 o->size = ipl->height * ipl->widthStep;
2211 o->backingmat = NULL;
2212 PyObject *data = PyBuffer_FromReadWriteObject((PyObject*)o, (size_t)0, o->size);
2219 return (PyObject*)cva;
2222 static PyObject *pythonize_CvMatND(cvmatnd_t *m, PyObject *backing = NULL)
2225 // Need to make this CvMatND look like any other, with a Python
2226 // buffer object as its data.
2229 CvMatND *mat = m->a;
2230 assert(mat->dim[0].step != 0);
2232 PyObject *data = PyString_FromStringAndSize((char*)(mat->data.ptr), mat->dim[0].size * mat->dim[0].step);
2234 memtrack_t *o = PyObject_NEW(memtrack_t, &memtrack_Type);
2235 o->ptr = mat->data.ptr;
2236 o->owner = __LINE__;
2238 o->size = cvmatnd_size(mat);
2239 Py_XINCREF(backing);
2240 o->backing = backing;
2241 o->backingmat = mat;
2242 PyObject *data = PyBuffer_FromReadWriteObject((PyObject*)o, (size_t)0, o->size);
2243 Py_DECREF(o); // Now 'data' holds the only reference to 'o'
2250 return (PyObject*)m;
2253 /************************************************************************/
2254 /* FROM_xxx: C -> Python converters.
2256 * Turn various OpenCV types (and some aggregate types above)
2257 * into Python objects. Used by the generated code.
2259 * All these functions and macros return a new reference.
2263 static PyObject *_FROM_CvSeqPTR(CvSeq *s, PyObject *storage)
2265 cvseq_t *ps = PyObject_NEW(cvseq_t, &cvseq_Type);
2267 ps->container = storage;
2268 Py_INCREF(ps->container);
2269 return (PyObject*)ps;
2272 static PyObject *_FROM_CvSubdiv2DPTR(CvSubdiv2D *s, PyObject *storage)
2274 cvsubdiv2d_t *ps = PyObject_NEW(cvsubdiv2d_t, &cvsubdiv2d_Type);
2276 ps->container = storage;
2277 Py_INCREF(ps->container);
2278 return (PyObject*)ps;
2281 static PyObject *FROM_floats(floats r)
2285 pr = PyList_New(r.count);
2286 for (Py_ssize_t i = 0; i < (Py_ssize_t)r.count; i++) {
2287 PyList_SetItem(pr, i, PyFloat_FromDouble(r.f[i]));
2292 static PyObject *FROM_chars(chars r)
2296 pr = PyList_New(r.count);
2297 for (Py_ssize_t i = 0; i < (Py_ssize_t)r.count; i++) {
2298 PyList_SetItem(pr, i, PyInt_FromLong(r.f[i]));
2303 static PyObject *FROM_cvpoint2d32f_count(cvpoint2d32f_count r)
2307 pr = PyList_New(r.count);
2308 for (Py_ssize_t i = 0; i < (Py_ssize_t)r.count; i++) {
2309 PyList_SetItem(pr, i, FROM_CvPoint2D32f(r.points[i]));
2314 static PyObject *FROM_CvPoint2D32fs(CvPoint2D32fs r)
2318 pr = PyList_New(r.count);
2319 for (Py_ssize_t i = 0; i < (Py_ssize_t)r.count; i++) {
2320 PyList_SetItem(pr, i, FROM_CvPoint2D32f(r.p[i]));
2325 typedef CvSeq CvSeqOfCvConvexityDefect;
2326 static PyObject *FROM_CvSeqOfCvConvexityDefectPTR(CvSeqOfCvConvexityDefect *r)
2329 pr = PyList_New(r->total);
2330 for (int i = 0; i < r->total; i++) {
2331 CvConvexityDefect *pd = CV_GET_SEQ_ELEM(CvConvexityDefect, r, i);
2332 PyList_SetItem(pr, i, Py_BuildValue("(ii)(ii)(ii)f",
2333 pd->start->x, pd->start->y,
2334 pd->end->x, pd->end->y,
2335 pd->depth_point->x, pd->depth_point->y,
2338 // This function has copied the CvSeq data into a list. Hence the
2339 // CvSeq is not being returned to the caller. Hence, no reference
2340 // count increase for the storage, unlike _FROM_CvSeqPTR.
2344 typedef CvSeq CvSeqOfCvAvgComp;
2345 static PyObject *FROM_CvSeqOfCvAvgCompPTR(CvSeqOfCvAvgComp *r)
2348 pr = PyList_New(r->total);
2349 for (int i = 0; i < r->total; i++) {
2350 CvAvgComp *pd = CV_GET_SEQ_ELEM(CvAvgComp, r, i);
2351 PyList_SetItem(pr, i, Py_BuildValue("(iiii)i",
2352 pd->rect.x, pd->rect.y,
2353 pd->rect.width, pd->rect.height,
2356 // This function has copied the CvSeq data into a list. Hence the
2357 // CvSeq is not being returned to the caller. Hence, no reference
2358 // count increase for the storage, unlike _FROM_CvSeqPTR.
2362 typedef CvSeq CvSeqOfCvStarKeypoint;
2363 static PyObject *FROM_CvSeqOfCvStarKeypointPTR(CvSeqOfCvStarKeypoint *r)
2366 pr = PyList_New(r->total);
2367 for (int i = 0; i < r->total; i++) {
2368 CvStarKeypoint *pd = CV_GET_SEQ_ELEM(CvStarKeypoint, r, i);
2369 PyList_SetItem(pr, i, Py_BuildValue("(ii)if",
2374 // This function has copied the CvSeq data into a list. Hence the
2375 // CvSeq is not being returned to the caller. Hence, no reference
2376 // count increase for the storage, unlike _FROM_CvSeqPTR.
2380 typedef CvSeq CvSeqOfCvSURFPoint;
2381 static PyObject *FROM_CvSeqOfCvSURFPointPTR(CvSeqOfCvSURFPoint *r)
2384 pr = PyList_New(r->total);
2385 for (int i = 0; i < r->total; i++) {
2386 CvSURFPoint *pd = CV_GET_SEQ_ELEM(CvSURFPoint, r, i);
2387 PyList_SetItem(pr, i, Py_BuildValue("(ff)iiff",
2394 // This function has copied the CvSeq data into a list. Hence the
2395 // CvSeq is not being returned to the caller. Hence, no reference
2396 // count increase for the storage, unlike _FROM_CvSeqPTR.
2400 typedef CvSeq CvSeqOfCvSURFDescriptor;
2401 static PyObject *FROM_CvSeqOfCvSURFDescriptorPTR(CvSeqOfCvSURFDescriptor *r)
2404 pr = PyList_New(r->total);
2405 for (int i = 0; i < r->total; i++) {
2406 float *pd = (float*)cvGetSeqElem(r, i);
2407 int count = r->elem_size / sizeof(float);
2408 PyObject *oi = PyList_New(count);
2409 for (int j = 0; j < count; j++) {
2410 PyList_SetItem(oi, j, PyFloat_FromDouble(pd[j]));
2412 PyList_SetItem(pr, i, oi);
2414 // This function has copied the CvSeq data into a list. Hence the
2415 // CvSeq is not being returned to the caller. Hence, no reference
2416 // count increase for the storage, unlike _FROM_CvSeqPTR.
2420 typedef CvPoint2D32f CvPoint2D32f_4[4];
2421 static PyObject *FROM_CvPoint2D32f_4(CvPoint2D32f* r)
2423 return Py_BuildValue("(ff)(ff)(ff)(ff)",
2430 typedef float CvMatr32f_i[9];
2432 static PyObject *FROM_CvMatr32f_i(CvMatr32f_i r)
2434 return Py_BuildValue("(fff)(fff)(fff)",
2440 typedef float CvVect32f_i[3];
2441 static PyObject *FROM_CvVect32f_i(CvVect32f_i r)
2443 return Py_BuildValue("fff",
2447 static PyObject *FROM_CvFont(CvFont r)
2449 cvfont_t *cf = PyObject_NEW(cvfont_t, &cvfont_Type);
2451 return (PyObject*)cf;
2454 static PyObject *FROM_CvSubdiv2DPointPTR(CvSubdiv2DPoint* r)
2457 cvsubdiv2dpoint_t *cf = PyObject_NEW(cvsubdiv2dpoint_t, &cvsubdiv2dpoint_Type);
2459 return (PyObject*)cf;
2466 static PyObject *FROM_IplImagePTR(IplImage *r)
2468 iplimage_t *cva = PyObject_NEW(iplimage_t, &iplimage_Type);
2470 return pythonize_IplImage(cva);
2473 static PyObject *FROM_ROIplImagePTR(ROIplImage *r)
2476 iplimage_t *cva = PyObject_NEW(iplimage_t, &iplimage_Type);
2477 cva->a = cvCreateImageHeader(cvSize(100,100), 8, 1);
2479 cva->data = PyBuffer_FromReadWriteMemory(r->imageData, r->height * r->widthStep);
2481 return (PyObject*)cva;
2487 static PyObject *FROM_ROCvMatPTR(ROCvMat *r)
2490 cvmat_t *cva = PyObject_NEW(cvmat_t, &cvmat_Type);
2491 cva->a = cvCreateMatHeader(100, 100, CV_8U);
2493 cva->data = PyBuffer_FromReadWriteMemory(r->data.ptr, r->rows * r->step);
2495 return (PyObject*)cva;
2501 static PyObject *FROM_CvMatPTR(CvMat *r)
2503 cvmat_t *cvm = PyObject_NEW(cvmat_t, &cvmat_Type);
2506 return pythonize_CvMat(cvm);
2509 static PyObject *FROM_CvMat(CvMat *r)
2511 cvmat_t *m = PyObject_NEW(cvmat_t, &cvmat_Type);
2513 return pythonize_CvMat(m);
2516 static PyObject *FROM_CvMatNDPTR(CvMatND *r)
2518 cvmatnd_t *m = PyObject_NEW(cvmatnd_t, &cvmatnd_Type);
2520 return pythonize_CvMatND(m);
2523 static PyObject *FROM_CvRNG(CvRNG r)
2525 cvrng_t *m = PyObject_NEW(cvrng_t, &cvrng_Type);
2527 return (PyObject*)m;
2530 /*static PyObject *FROM_CvContourTreePTR(CvContourTree *r)
2532 cvcontourtree_t *m = PyObject_NEW(cvcontourtree_t, &cvcontourtree_Type);
2534 return (PyObject*)m;
2537 static PyObject *FROM_generic(generic r)
2540 failmsg("OpenCV returned NULL");
2543 CvTypeInfo* t = cvTypeOf(r);
2544 if (strcmp(t->type_name, "opencv-image") == 0)
2545 return FROM_IplImagePTR((IplImage*)r);
2546 else if (strcmp(t->type_name, "opencv-matrix") == 0)
2547 return FROM_CvMat((CvMat*)r);
2548 else if (strcmp(t->type_name, "opencv-nd-matrix") == 0)
2549 return FROM_CvMatNDPTR((CvMatND*)r);
2550 else if (strcmp(t->type_name, "opencv-haar-classifier") == 0)
2551 return FROM_CvHaarClassifierCascadePTR((CvHaarClassifierCascade*)r);
2553 failmsg("Unknown OpenCV type '%s'", t->type_name);
2558 static PyObject *FROM_CvSubdiv2DEdge(CvSubdiv2DEdge r)
2560 cvsubdiv2dedge_t *m = PyObject_NEW(cvsubdiv2dedge_t, &cvsubdiv2dedge_Type);
2562 m->container = Py_None; // XXX
2563 Py_INCREF(m->container);
2564 return (PyObject*)m;
2567 static PyObject *FROM_CvPoints(CvPoints src)
2570 pr = PyList_New(src.count);
2571 for (int i = 0; i < src.count; i++) {
2572 PyList_SetItem(pr, i, FROM_CvPoint(src.p[i]));
2577 /************************************************************************/
2579 /* A few functions are too odd to be generated,
2580 * so are handwritten here */
2582 static PyObject *pycvWaitKey(PyObject *self, PyObject *args, PyObject *kw)
2586 const char *keywords[] = { "delay", NULL };
2587 if (!PyArg_ParseTupleAndKeywords(args, kw, "|i", (char**)keywords, &delay))
2590 Py_BEGIN_ALLOW_THREADS
2591 r = cvWaitKey(delay);
2592 Py_END_ALLOW_THREADS
2596 static PyObject *pycvLoadImage(PyObject *self, PyObject *args, PyObject *kw)
2598 const char *keywords[] = { "filename", "iscolor", NULL };
2600 int iscolor = CV_LOAD_IMAGE_COLOR;
2602 if (!PyArg_ParseTupleAndKeywords(args, kw, "s|i", (char**)keywords, &filename, &iscolor))
2605 // Inside ALLOW_THREADS, must not reference 'filename' because it might move.
2606 // So make a local copy 'filename_copy'.
2607 char filename_copy[2048];
2608 strncpy(filename_copy, filename, sizeof(filename_copy));
2611 Py_BEGIN_ALLOW_THREADS
2612 r = cvLoadImage(filename_copy, iscolor);
2613 Py_END_ALLOW_THREADS
2616 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
2619 return FROM_IplImagePTR(r);
2623 static PyObject *pycvLoadImageM(PyObject *self, PyObject *args, PyObject *kw)
2625 const char *keywords[] = { "filename", "iscolor", NULL };
2627 int iscolor = CV_LOAD_IMAGE_COLOR;
2629 if (!PyArg_ParseTupleAndKeywords(args, kw, "s|i", (char**)keywords, &filename, &iscolor))
2632 // Inside ALLOW_THREADS, must not reference 'filename' because it might move.
2633 // So make a local copy 'filename_copy'.
2634 char filename_copy[2048];
2635 strncpy(filename_copy, filename, sizeof(filename_copy));
2638 Py_BEGIN_ALLOW_THREADS
2639 r = cvLoadImageM(filename_copy, iscolor);
2640 Py_END_ALLOW_THREADS
2643 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
2646 return FROM_CvMatPTR(r);
2650 static PyObject *pycvCreateImageHeader(PyObject *self, PyObject *args)
2652 int w, h, depth, channels;
2653 if (!PyArg_ParseTuple(args, "(ii)Ii", &w, &h, &depth, &channels))
2655 iplimage_t *cva = PyObject_NEW(iplimage_t, &iplimage_Type);
2656 cva->a = cvCreateImageHeader(cvSize(w, h), depth, channels);
2657 if (cva->a == NULL) {
2658 PyErr_SetString(PyExc_TypeError, "CreateImage failed");
2661 cva->data = Py_None;
2662 Py_INCREF(cva->data);
2665 return (PyObject*)cva;
2669 static PyObject *pycvCreateImage(PyObject *self, PyObject *args)
2671 int w, h, depth, channels;
2672 if (!PyArg_ParseTuple(args, "(ii)Ii:CreateImage", &w, &h, &depth, &channels))
2674 iplimage_t *cva = PyObject_NEW(iplimage_t, &iplimage_Type);
2675 ERRWRAP(cva->a = cvCreateImage(cvSize(w, h), depth, channels));
2676 if (cva->a == NULL) {
2677 PyErr_SetString(PyExc_TypeError, "CreateImage failed");
2680 return pythonize_IplImage(cva);
2684 static PyObject *pycvCreateMatHeader(PyObject *self, PyObject *args)
2686 int rows, cols, type;
2687 if (!PyArg_ParseTuple(args, "iii", &rows, &cols, &type))
2689 cvmat_t *m = PyObject_NEW(cvmat_t, &cvmat_Type);
2690 ERRWRAP(m->a = cvCreateMatHeader(rows, cols, type));
2692 PyErr_SetString(PyExc_TypeError, "CreateMat failed");
2698 return (PyObject*)m;
2702 static PyObject *pycvCreateMat(PyObject *self, PyObject *args)
2704 int rows, cols, type;
2705 if (!PyArg_ParseTuple(args, "iii", &rows, &cols, &type))
2707 cvmat_t *m = PyObject_NEW(cvmat_t, &cvmat_Type);
2708 ERRWRAP(m->a = cvCreateMat(rows, cols, type));
2710 PyErr_SetString(PyExc_TypeError, "CreateMat failed");
2713 return pythonize_CvMat(m);
2717 static PyObject *pycvCreateMatNDHeader(PyObject *self, PyObject *args)
2722 if (!PyArg_ParseTuple(args, "O&i", convert_to_ints, (void*)&dims, &type))
2724 cvmatnd_t *m = PyObject_NEW(cvmatnd_t, &cvmatnd_Type);
2725 ERRWRAP(m->a = cvCreateMatNDHeader(dims.count, dims.i, type));
2730 return (PyObject*)m;
2734 static PyObject *pycvCreateMatND(PyObject *self, PyObject *args)
2739 if (!PyArg_ParseTuple(args, "O&i", convert_to_ints, (void*)&dims, &type))
2741 cvmatnd_t *m = PyObject_NEW(cvmatnd_t, &cvmatnd_Type);
2742 ERRWRAP(m->a = cvCreateMatND(dims.count, dims.i, type));
2744 return pythonize_CvMatND(m);
2747 #if PYTHON_USE_NUMPY
2748 static PyObject *pycvfromarray(PyObject *self, PyObject *args, PyObject *kw)
2750 const char *keywords[] = { "arr", "allowND", NULL };
2754 if (!PyArg_ParseTupleAndKeywords(args, kw, "O|i", (char**)keywords, &o, &allowND))
2756 return fromarray(o, allowND);
2759 static PyObject *fromarray(PyObject *o, int allowND)
2761 PyObject *ao = PyObject_GetAttrString(o, "__array_struct__");
2764 if ((ao == NULL) || !PyCObject_Check(ao)) {
2765 PyErr_SetString(PyExc_TypeError, "object does not have array interface");
2768 PyArrayInterface *pai = (PyArrayInterface*)PyCObject_AsVoidPtr(ao);
2769 if (pai->two != 2) {
2770 PyErr_SetString(PyExc_TypeError, "object does not have array interface");
2777 switch (pai->typekind) {
2779 if (pai->itemsize == 1)
2781 else if (pai->itemsize == 2)
2783 else if (pai->itemsize == 4)
2788 if (pai->itemsize == 1)
2790 else if (pai->itemsize == 2)
2795 if (pai->itemsize == 4)
2797 else if (pai->itemsize == 8)
2803 PyErr_SetString(PyExc_TypeError, "the array type is not supported by OpenCV");
2809 cvmat_t *m = PyObject_NEW(cvmat_t, &cvmat_Type);
2811 if (pai->strides[1] != pai->itemsize) {
2812 return failmsg("cv.fromarray array can only accept arrays with contiguous data"), (PyObject*)0;
2814 ERRWRAP(m->a = cvCreateMatHeader((int)pai->shape[0], (int)pai->shape[1], type));
2815 m->a->step = (int)pai->strides[0];
2816 } else if (pai->nd == 3) {
2817 if (pai->shape[2] > CV_CN_MAX) {
2819 return failmsg("cv.fromarray too many channels, see allowND argument"), (PyObject*)0;
2821 ERRWRAP(m->a = cvCreateMatHeader((int)pai->shape[0], (int)pai->shape[1], type + ((int)(pai->shape[2] - 1) << CV_CN_SHIFT)));
2822 m->a->step = (int)pai->strides[0];
2825 return failmsg("cv.fromarray array can be 2D or 3D only, see allowND argument"), (PyObject*)0;
2827 m->a->data.ptr = (uchar*)pai->data;
2828 //retval = pythonize_foreign_CvMat(m);
2831 retval = (PyObject*)m;
2833 int dims[CV_MAX_DIM];
2835 for (i = 0; i < pai->nd; i++)
2836 dims[i] = (int)pai->shape[i];
2837 cvmatnd_t *m = PyObject_NEW(cvmatnd_t, &cvmatnd_Type);
2838 ERRWRAP(m->a = cvCreateMatNDHeader(pai->nd, dims, type));
2839 m->a->data.ptr = (uchar*)pai->data;
2842 retval = (PyObject*)m;
2843 //retval = pythonize_CvMatND(m, ao);
2859 int fromobj(PyObject *o, const char *name = "no_name") {
2860 PyObject *fi = PySequence_Fast(o, name);
2863 len = (int)PySequence_Fast_GET_SIZE(fi);
2864 rr = new float*[len];
2865 for (Py_ssize_t i = 0; i < len; i++) {
2866 PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
2868 if (!convert_to_floats(item, &ff))
2876 for (Py_ssize_t i = 0; i < len; i++)
2882 static int ranges_converter(PyObject *o, ranges* dst)
2884 return dst->fromobj(o);
2887 static PyObject *pycvCreateHist(PyObject *self, PyObject *args, PyObject *kw)
2889 const char *keywords[] = { "dims", "type", "ranges", "uniform", NULL };
2894 if (!PyArg_ParseTupleAndKeywords(args, kw, "Oi|O&i", (char**)keywords, &dims, &type, ranges_converter, (void*)&r, &uniform)) {
2897 cvhistogram_t *h = PyObject_NEW(cvhistogram_t, &cvhistogram_Type);
2898 args = Py_BuildValue("Oi", dims, CV_32FC1);
2899 memset(&h->h, 0, sizeof(h->h));
2900 h->bins = pycvCreateMatND(self, args);
2902 if (h->bins == NULL) {
2905 h->h.type = CV_HIST_MAGIC_VAL + CV_HIST_UNIFORM_FLAG;
2906 if (!convert_to_CvArr(h->bins, &(h->h.bins), "bins"))
2911 ERRWRAP(cvSetHistBinRanges(&(h->h), r.rr, uniform));
2914 return (PyObject*)h;
2917 static PyObject *pycvInitLineIterator(PyObject *self, PyObject *args, PyObject *kw)
2919 const char *keywords[] = { "image", "pt1", "pt2", "connectivity", "left_to_right", NULL };
2923 int connectivity = 8;
2924 int left_to_right = 0;
2926 if (!PyArg_ParseTupleAndKeywords(args, kw, "O&O&O&|ii", (char**)keywords,
2927 convert_to_CvArr, &image,
2928 convert_to_CvPoint, &pt1,
2929 convert_to_CvPoint, &pt2,
2934 cvlineiterator_t *pi = PyObject_NEW(cvlineiterator_t, &cvlineiterator_Type);
2935 pi->count = cvInitLineIterator(image, pt1, pt2, &pi->iter, connectivity, left_to_right);
2936 ERRWRAP(pi->type = cvGetElemType(image));
2937 return (PyObject*)pi;
2940 static PyObject *pycvCreateMemStorage(PyObject *self, PyObject *args)
2943 if (!PyArg_ParseTuple(args, "|i", &block_size))
2945 cvmemstorage_t *pm = PyObject_NEW(cvmemstorage_t, &cvmemstorage_Type);
2946 pm->a = cvCreateMemStorage(block_size);
2947 return (PyObject*)pm;
2950 // single index: return row
2951 // 2 indices: row, column
2952 // both row and column can be slices. column slice must have a step of 1.
2954 // returns a scalar when all dimensions are specified and all are integers. Otherwise returns a CvMat.
2956 static PyObject *cvarr_GetItem(PyObject *o, PyObject *key)
2961 if (!convert_to_CvArr(o, &cva, "src"))
2964 if (!convert_to_dims(key, &dd, cva, "key")) {
2968 // Figure out if all supplied indices have a stride of zero - means they are not slices
2969 // and if all indices are positive
2971 for (int i = 0; i < dd.count; i++) {
2972 all0 &= (dd.step[i] == 0) && (0 <= dd.i[i]);
2975 // if every dimension supplied, and none are slices, return the scalar
2976 if ((cvGetDims(cva) == dd.count) && all0) {
2978 ERRWRAP(s = cvGetND(cva, dd.i));
2979 return PyObject_FromCvScalar(s, cvGetElemType(cva));
2981 // pad missing dimensions
2982 for (int i = dd.count; i < cvGetDims(cva); i++) {
2985 dd.length[i] = cvGetDimSize(cva, i);
2987 dd.count = cvGetDims(cva);
2989 // negative steps are illegal for OpenCV
2990 for (int i = 0; i < dd.count; i++) {
2992 return failmsg("Negative step is illegal"), (PyObject*)0;
2995 // zero length illegal for OpenCV
2996 for (int i = 0; i < dd.count; i++) {
2997 if (dd.length[i] == 0)
2998 return failmsg("Zero sized dimension is illegal"), (PyObject*)0;
3001 // column step can only be 0 or 1
3002 if ((dd.step[dd.count-1] != 0) && (dd.step[dd.count-1] != 1))
3003 return failmsg("Column step is illegal"), (PyObject*)0;
3005 if (is_cvmat(o) || is_iplimage(o)) {
3006 cvmat_t *sub = PyObject_NEW(cvmat_t, &cvmat_Type);
3007 sub->a = cvCreateMatHeader(dd.length[0], dd.length[1], cvGetElemType(cva));
3008 uchar *old0; // pointer to first element in old mat
3010 cvGetRawData(cva, &old0, &oldstep);
3011 uchar *new0; // pointer to first element in new mat
3012 ERRWRAP(new0 = cvPtrND(cva, dd.i));
3014 sub->a->step = oldstep * dd.step[0];
3015 sub->data = what_data(o);
3016 Py_INCREF(sub->data);
3017 sub->offset = new0 - old0;
3018 return (PyObject*)sub;
3020 cvmatnd_t *sub = PyObject_NEW(cvmatnd_t, &cvmatnd_Type);
3021 sub->a = cvCreateMatNDHeader(dd.count, dd.length, cvGetElemType(cva));
3022 uchar *old0; // pointer to first element in old mat
3023 cvGetRawData(cva, &old0);
3024 uchar *new0; // pointer to first element in new mat
3025 ERRWRAP(new0 = cvPtrND(cva, dd.i));
3027 for (int d = 0; d < dd.count; d++) {
3028 int stp = dd.step[d];
3029 sub->a->dim[d].step = ((CvMatND*)cva)->dim[d].step * ((stp == 0) ? 1 : stp);
3030 sub->a->dim[d].size = dd.length[d];
3032 sub->data = what_data(o);
3033 Py_INCREF(sub->data);
3034 sub->offset = new0 - old0;
3035 return (PyObject*)sub;
3040 static int cvarr_SetItem(PyObject *o, PyObject *key, PyObject *v)
3045 if (!convert_to_CvArr(o, &cva, "src"))
3048 if (!convert_to_dims(key, &dd, cva, "key")) {
3052 if (cvGetDims(cva) != dd.count) {
3053 PyErr_SetString(PyExc_TypeError, "key length does not match array dimension");
3058 if (PySequence_Check(v)) {
3059 PyObject *fi = PySequence_Fast(v, "v");
3062 if (PySequence_Fast_GET_SIZE(fi) != CV_MAT_CN(cvGetElemType(cva))) {
3063 PyErr_SetString(PyExc_TypeError, "sequence size must be same as channel count");
3066 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++)
3067 s.val[i] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(fi, i));
3070 if (1 != CV_MAT_CN(cvGetElemType(cva))) {
3071 PyErr_SetString(PyExc_TypeError, "scalar supplied but channel count does not equal 1");
3074 s.val[0] = PyFloat_AsDouble(v);
3078 ERRWRAPN(cvSet1D(cva, dd.i[0], s), -1);
3081 ERRWRAPN(cvSet2D(cva, dd.i[0], dd.i[1], s), -1);
3084 ERRWRAPN(cvSet3D(cva, dd.i[0], dd.i[1], dd.i[2], s), -1);
3087 ERRWRAPN(cvSetND(cva, dd.i, s), -1);
3088 // XXX - OpenCV bug? - seems as if an error in cvSetND does not set error status?
3091 if (cvGetErrStatus() != 0) {
3092 translate_error_to_exception();
3100 static PyObject *pycvSetData(PyObject *self, PyObject *args)
3103 int step = CV_AUTO_STEP;
3105 if (!PyArg_ParseTuple(args, "OO|i", &o, &s, &step))
3107 if (is_iplimage(o)) {
3108 iplimage_t *ipl = (iplimage_t*)o;
3109 ipl->a->widthStep = step;
3110 Py_DECREF(ipl->data);
3112 Py_INCREF(ipl->data);
3113 } else if (is_cvmat(o)) {
3114 cvmat_t *m = (cvmat_t*)o;
3119 } else if (is_cvmatnd(o)) {
3120 cvmatnd_t *m = (cvmatnd_t*)o;
3125 PyErr_SetString(PyExc_TypeError, "SetData argument must be either IplImage, CvMat or CvMatND");
3132 static PyObject *what_data(PyObject *o)
3134 if (is_iplimage(o)) {
3135 iplimage_t *ipl = (iplimage_t*)o;
3137 } else if (is_cvmat(o)) {
3138 cvmat_t *m = (cvmat_t*)o;
3140 } else if (is_cvmatnd(o)) {
3141 cvmatnd_t *m = (cvmatnd_t*)o;
3149 static PyObject *pycvCreateData(PyObject *self, PyObject *args)
3153 if (!PyArg_ParseTuple(args, "O", &o))
3157 if (!convert_to_CvArr(o, &a, "arr"))
3159 ERRWRAP(cvCreateData(a));
3161 Py_DECREF(what_data(o));
3162 if (is_iplimage(o)) {
3163 iplimage_t *ipl = (iplimage_t*)o;
3164 pythonize_IplImage(ipl);
3165 } else if (is_cvmat(o)) {
3166 cvmat_t *m = (cvmat_t*)o;
3168 } else if (is_cvmatnd(o)) {
3169 cvmatnd_t *m = (cvmatnd_t*)o;
3170 pythonize_CvMatND(m);
3172 PyErr_SetString(PyExc_TypeError, "CreateData argument must be either IplImage, CvMat or CvMatND");
3179 static PyObject *pycvGetDims(PyObject *self, PyObject *args)
3183 if (!PyArg_ParseTuple(args, "O", &o))
3186 if (!convert_to_CvArr(o, &cva, "src"))
3190 ERRWRAP(nd = cvGetDims(cva));
3191 PyObject *r = PyTuple_New(nd);
3192 for (i = 0; i < nd; i++)
3193 PyTuple_SetItem(r, i, PyInt_FromLong(cvGetDimSize(cva, i)));
3197 static PyObject *pycvGetImage(PyObject *self, PyObject *args)
3201 if (!PyArg_ParseTuple(args, "O", &o))
3203 if (is_iplimage(o)) {
3207 IplImage *ipl = cvCreateImageHeader(cvSize(100,100), 8, 1); // these args do not matter, because overwritten
3209 if (!convert_to_CvArr(o, &cva, "src"))
3211 ERRWRAP(cvGetImage(cva, ipl));
3213 iplimage_t *oipl = PyObject_NEW(iplimage_t, &iplimage_Type);
3215 oipl->data = what_data(o);
3216 Py_INCREF(oipl->data);
3219 r = (PyObject*)oipl;
3224 static PyObject *pycvGetMat(PyObject *self, PyObject *args, PyObject *kw)
3226 const char *keywords[] = { "arr", "allowND", NULL };
3230 if (!PyArg_ParseTupleAndKeywords(args, kw, "O|i", (char**)keywords, &o, &allowND))
3236 CvMat *m = cvCreateMatHeader(100,100, 1); // these args do not matter, because overwritten
3238 if (!convert_to_CvArr(o, &cva, "src"))
3240 ERRWRAP(cvGetMat(cva, m, NULL, allowND));
3242 cvmat_t *om = PyObject_NEW(cvmat_t, &cvmat_Type);
3244 om->data = what_data(o);
3245 Py_INCREF(om->data);
3253 static PyObject *pycvReshape(PyObject *self, PyObject *args)
3259 if (!PyArg_ParseTuple(args, "Oi|i", &o, &new_cn, &new_rows))
3262 CvMat *m = cvCreateMatHeader(100,100, 1); // these args do not matter, because overwritten
3264 if (!convert_to_CvArr(o, &cva, "src"))
3266 ERRWRAP(cvReshape(cva, m, new_cn, new_rows));
3268 cvmat_t *om = PyObject_NEW(cvmat_t, &cvmat_Type);
3270 om->data = what_data(o);
3271 Py_INCREF(om->data);
3274 return (PyObject*)om;
3277 static PyObject *pycvReshapeMatND(PyObject *self, PyObject *args)
3281 PyObject *new_dims = NULL;
3283 if (!PyArg_ParseTuple(args, "OiO", &o, &new_cn, &new_dims))
3287 if (!convert_to_CvMatND(o, &cva, "src"))
3290 if (new_dims != NULL) {
3291 if (!convert_to_ints(new_dims, &dims, "new_dims"))
3296 new_cn = CV_MAT_CN(cvGetElemType(cva));
3299 int count = CV_MAT_CN(cvGetElemType(cva));
3300 for (i = 0; i < cva->dims; i++)
3301 count *= cva->dim[i].size;
3303 int newcount = new_cn;
3304 for (i = 0; i < dims.count; i++)
3305 newcount *= dims.i[i];
3307 if (count != newcount) {
3308 PyErr_SetString(PyExc_TypeError, "Total number of elements must be unchanged");
3312 CvMatND *pn = cvCreateMatNDHeader(dims.count, dims.i, CV_MAKETYPE(CV_MAT_TYPE(cva->type), new_cn));
3313 return shareDataND(o, cva, pn);
3316 static PyObject *pycvFindContours(PyObject *self, PyObject *args, PyObject *kw)
3319 PyObject *pyobj_image = NULL;
3320 CvMemStorage* storage;
3321 PyObject *pyobj_storage = NULL;
3322 CvSeq* first_contour;
3323 int header_size = sizeof(CvContour);
3324 int mode = CV_RETR_LIST;
3325 int method = CV_CHAIN_APPROX_SIMPLE;
3326 CvPoint offset = cvPoint(0,0);
3327 PyObject *pyobj_offset = NULL;
3329 const char *keywords[] = { "image", "storage", "mode", "method", "offset", NULL };
3330 if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|iiO", (char**)keywords, &pyobj_image, &pyobj_storage, &mode, &method, &pyobj_offset))
3332 if (!convert_to_CvArr(pyobj_image, &image, "image")) return NULL;
3333 if (!convert_to_CvMemStorage(pyobj_storage, &storage, "storage")) return NULL;
3334 if ((pyobj_offset != NULL) && !convert_to_CvPoint(pyobj_offset, &offset, "offset")) return NULL;
3335 ERRWRAP(cvFindContours(image, storage, &first_contour, header_size, mode, method, offset));
3336 cvseq_t *ps = PyObject_NEW(cvseq_t, &cvseq_Type);
3337 ps->a = first_contour;
3338 ps->container = PyTuple_GetItem(args, 1); // storage
3339 Py_INCREF(ps->container);
3340 return (PyObject*)ps;
3343 static PyObject *pycvApproxPoly(PyObject *self, PyObject *args, PyObject *kw)
3346 PyObject *pyobj_src_seq = NULL;
3347 int header_size = sizeof(CvContour);
3348 CvMemStorage* storage;
3349 PyObject *pyobj_storage = NULL;
3351 double parameter = 0;
3354 const char *keywords[] = { "src_seq", "storage", "method", "parameter", "parameter2", NULL };
3355 if (!PyArg_ParseTupleAndKeywords(args, kw, "OOi|di", (char**)keywords, &pyobj_src_seq, &pyobj_storage, &method, ¶meter, ¶meter2))
3357 if (!convert_to_cvarrseq(pyobj_src_seq, &src_seq, "src_seq")) return NULL;
3358 if (!convert_to_CvMemStorage(pyobj_storage, &storage, "storage")) return NULL;
3360 ERRWRAP(r = cvApproxPoly(src_seq.mat, header_size, storage, method, parameter, parameter2));
3361 return FROM_CvSeqPTR(r);
3364 static float distance_function_glue( const float* a, const float* b, void* user_param )
3366 PyObject *o = (PyObject*)user_param;
3367 PyObject *args = Py_BuildValue("(ff)(ff)O", a[0], a[1], b[0], b[1], PyTuple_GetItem(o, 1));
3368 PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL);
3370 return (float)PyFloat_AsDouble(r);
3373 static PyObject *pycvCalcEMD2(PyObject *self, PyObject *args, PyObject *kw)
3375 const char *keywords[] = { "signature1", "signature2", "distance_type", "distance_func", "cost_matrix", "flow", "lower_bound", "userdata", NULL };
3377 PyObject *pyobj_signature1;
3379 PyObject *pyobj_signature2;
3381 PyObject *distance_func = NULL;
3382 CvArr* cost_matrix=NULL;
3383 PyObject *pyobj_cost_matrix = NULL;
3385 PyObject *pyobj_flow = NULL;
3386 float lower_bound = 0.0;
3387 PyObject *userdata = NULL;
3389 if (!PyArg_ParseTupleAndKeywords(args, kw, "OOi|OOOfO", (char**)keywords,
3399 if (!convert_to_CvArr(pyobj_signature1, &signature1, "signature1")) return NULL;
3400 if (!convert_to_CvArr(pyobj_signature2, &signature2, "signature2")) return NULL;
3401 if (pyobj_cost_matrix && !convert_to_CvArr(pyobj_cost_matrix, &cost_matrix, "cost_matrix")) return NULL;
3402 if (pyobj_flow && !convert_to_CvArr(pyobj_flow, &flow, "flow")) return NULL;
3404 if (distance_func == NULL) {
3405 distance_func = Py_None;
3407 if (userdata == NULL) {
3411 PyObject *ud = Py_BuildValue("OO", distance_func, userdata);
3413 ERRWRAP(r = cvCalcEMD2(signature1, signature2, distance_type, distance_function_glue, cost_matrix, flow, &lower_bound, (void*)ud));
3416 return PyFloat_FromDouble(r);
3419 static PyObject *pycvSubdiv2DLocate(PyObject *self, PyObject *args)
3421 PyObject *pyobj_subdiv;
3425 CvSubdiv2DEdge edge;
3426 CvSubdiv2DPoint* vertex;
3428 if (!PyArg_ParseTuple(args, "OO", &pyobj_subdiv, &pyobj_pt))
3430 if (!convert_to_CvSubdiv2DPTR(pyobj_subdiv, &subdiv, "subdiv"))
3432 if (!convert_to_CvPoint2D32f(pyobj_pt, &pt, "pt"))
3435 CvSubdiv2DPointLocation loc = cvSubdiv2DLocate(subdiv, pt, &edge, &vertex);
3438 case CV_PTLOC_INSIDE:
3439 case CV_PTLOC_ON_EDGE:
3440 r = FROM_CvSubdiv2DEdge(edge);
3442 case CV_PTLOC_VERTEX:
3443 r = FROM_CvSubdiv2DPointPTR(vertex);
3445 case CV_PTLOC_OUTSIDE_RECT:
3450 return failmsg("Unexpected loc from cvSubdiv2DLocate"), (PyObject*)0;
3452 return Py_BuildValue("iO", (int)loc, r);
3455 static PyObject *pycvCalcOpticalFlowPyrLK(PyObject *self, PyObject *args)
3458 PyObject *pyobj_prev = NULL;
3460 PyObject *pyobj_curr = NULL;
3462 PyObject *pyobj_prev_pyr = NULL;
3464 PyObject *pyobj_curr_pyr = NULL;
3465 CvPoint2D32f* prev_features;
3466 PyObject *pyobj_prev_features = NULL;
3467 PyObject *pyobj_curr_features = NULL;
3468 CvPoint2D32f* curr_features;
3471 CvTermCriteria criteria;
3474 if (!PyArg_ParseTuple(args, "OOOOO(ii)i(iif)i|O",
3475 &pyobj_prev, &pyobj_curr, &pyobj_prev_pyr, &pyobj_curr_pyr,
3476 &pyobj_prev_features,
3477 &win_size.width, &win_size.height, &level,
3478 &criteria.type, &criteria.max_iter, &criteria.epsilon,
3480 &pyobj_curr_features))
3482 if (!convert_to_CvArr(pyobj_prev, &prev, "prev")) return NULL;
3483 if (!convert_to_CvArr(pyobj_curr, &curr, "curr")) return NULL;
3484 if (!convert_to_CvArr(pyobj_prev_pyr, &prev_pyr, "prev_pyr")) return NULL;
3485 if (!convert_to_CvArr(pyobj_curr_pyr, &curr_pyr, "curr_pyr")) return NULL;
3486 if (!convert_to_CvPoint2D32fPTR(pyobj_prev_features, &prev_features, "prev_features")) return NULL;
3487 int count = (int)PySequence_Length(pyobj_prev_features);
3488 if (flags & CV_LKFLOW_INITIAL_GUESSES) {
3489 failmsg("flag CV_LKFLOW_INITIAL_GUESSES is determined automatically from function arguments - it is not required");
3492 if (!pyobj_curr_features) {
3493 curr_features = new CvPoint2D32f[count];
3495 if (PySequence_Length(pyobj_curr_features) != count) {
3496 failmsg("curr_features must have same length as prev_features");
3499 if (!convert_to_CvPoint2D32fPTR(pyobj_curr_features, &curr_features, "curr_features")) return NULL;
3500 flags |= CV_LKFLOW_INITIAL_GUESSES;
3502 float *track_error = new float[count];
3503 char* status = new char[count];
3504 ERRWRAP(cvCalcOpticalFlowPyrLK(prev, curr, prev_pyr, curr_pyr, prev_features, curr_features, count, win_size, level, status, track_error, criteria, flags));
3506 cvpoint2d32f_count r0;
3507 r0.points = curr_features;
3518 return Py_BuildValue("NNN", FROM_cvpoint2d32f_count(r0), FROM_chars(r1), FROM_floats(r2));
3521 // pt1,pt2 are input and output arguments here
3523 static PyObject *pycvClipLine(PyObject *self, PyObject *args)
3526 PyObject *pyobj_img_size = NULL;
3528 PyObject *pyobj_pt1 = NULL;
3530 PyObject *pyobj_pt2 = NULL;
3532 if (!PyArg_ParseTuple(args, "OOO", &pyobj_img_size, &pyobj_pt1, &pyobj_pt2))
3534 if (!convert_to_CvSize(pyobj_img_size, &img_size, "img_size")) return NULL;
3535 if (!convert_to_CvPoint(pyobj_pt1, &pt1, "pt1")) return NULL;
3536 if (!convert_to_CvPoint(pyobj_pt2, &pt2, "pt2")) return NULL;
3538 ERRWRAP(r = cvClipLine(img_size, &pt1, &pt2));
3542 return Py_BuildValue("NN", FROM_CvPoint(pt1), FROM_CvPoint(pt2));
3546 static PyObject *pyfinddatamatrix(PyObject *self, PyObject *args)
3549 if (!PyArg_ParseTuple(args, "O", &pyim))
3553 if (!convert_to_CvMat(pyim, &image, "image")) return NULL;
3555 std::deque <CvDataMatrixCode> codes;
3556 ERRWRAP(codes = cvFindDataMatrix(image));
3558 PyObject *pycodes = PyList_New(codes.size());
3559 for (size_t i = 0; i < codes.size(); i++) {
3560 CvDataMatrixCode *pc = &codes[i];
3561 PyList_SetItem(pycodes, i, Py_BuildValue("(sOO)", pc->msg, FROM_CvMat(pc->corners), FROM_CvMat(pc->original)));
3567 static PyObject *temp_test(PyObject *self, PyObject *args)
3570 CvArr *im = cvLoadImage("../samples/c/lena.jpg", 0);
3571 printf("im=%p\n", im);
3572 CvMat *m = cvEncodeImage(".jpeg", im);
3575 CvArr *im = cvLoadImage("lena.jpg", 0);
3576 float r0[] = { 0, 255 };
3577 float *ranges[] = { r0 };
3578 int hist_size[] = { 256 };
3579 CvHistogram *hist = cvCreateHist(1, hist_size, CV_HIST_ARRAY, ranges, 1);
3580 cvCalcHist(im, hist, 0, 0);
3584 CvMat* mat = cvCreateMat( 3, 3, CV_32F );
3585 CvMat row_header, *row;
3586 row = cvReshape( mat, &row_header, 0, 1 );
3587 printf("%d,%d\n", row_header.rows, row_header.cols);
3588 printf("ge %08x\n", cvGetElemType(mat));
3592 CvMat *m = cvCreateMat(1, 10, CV_8UC1);
3593 printf("CvMat stride ===> %d\n", m->step);
3597 CvPoint2D32f src[3] = { { 0,0 }, { 1,0 }, { 0,1 } };
3598 CvPoint2D32f dst[3] = { { 0,0 }, { 17,0 }, { 0,17 } };
3600 CvMat* mapping = cvCreateMat(2, 3, CV_32FC1);
3601 cvGetAffineTransform(src, dst, mapping);
3602 printf("===> %f\n", cvGetReal2D(mapping, 0, 0));
3606 CvArr *im = cvLoadImage("checker77.png");
3607 CvPoint2D32f corners[49];
3609 cvFindChessboardCorners(im, cvSize(7,7), corners, &count, 0);
3610 printf("count=%d\n", count);
3614 CvMat *src = cvCreateMat(512, 512, CV_8UC3);
3615 CvMat *dst = cvCreateMat(512, 512, CV_8UC3);
3616 cvPyrMeanShiftFiltering(src, dst, 5, 5);
3617 return FROM_CvMat(src);
3620 return PyFloat_FromDouble(0.0);
3623 static PyObject *pycvFindChessboardCorners(PyObject *self, PyObject *args, PyObject *kw)
3626 PyObject *pyobj_image = NULL;
3627 CvSize pattern_size;
3628 PyObject *pyobj_pattern_size = NULL;
3629 cvpoint2d32f_count corners;
3630 int flags = CV_CALIB_CB_ADAPTIVE_THRESH;
3632 const char *keywords[] = { "image", "pattern_size", "flags", NULL };
3633 if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|i", (char**)keywords, &pyobj_image, &pyobj_pattern_size, &flags))
3635 if (!convert_to_CvArr(pyobj_image, &image, "image")) return NULL;
3636 if (!convert_to_CvSize(pyobj_pattern_size, &pattern_size, "pattern_size")) return NULL;
3638 corners.points = new CvPoint2D32f[pattern_size.width * pattern_size.height];
3639 ERRWRAP(r = cvFindChessboardCorners(image, pattern_size, corners.points,&corners.count, flags));
3640 return Py_BuildValue("NN", FROM_int(r), FROM_cvpoint2d32f_count(corners));
3643 // For functions GetSubRect, GetRow, GetCol.
3644 // recipient has a view into donor's data, and needs to share it.
3645 // make recipient use the donor's data, compute the offset,
3646 // and manage reference counts.
3648 static void preShareData(CvArr *donor, CvMat **recipient)
3650 *recipient = cvCreateMatHeader(4, 4, cvGetElemType(donor));
3653 static PyObject *shareData(PyObject *donor, CvArr *pdonor, CvMat *precipient)
3655 PyObject *recipient = (PyObject*)PyObject_NEW(cvmat_t, &cvmat_Type);
3656 ((cvmat_t*)recipient)->a = precipient;
3657 ((cvmat_t*)recipient)->offset = cvPtr1D(precipient, 0) - cvPtr1D(pdonor, 0);
3660 if (is_cvmat(donor)) {
3661 arr_data = ((cvmat_t*)donor)->data;
3662 ((cvmat_t*)recipient)->offset += ((cvmat_t*)donor)->offset;
3663 } else if (is_iplimage(donor)) {
3664 arr_data = ((iplimage_t*)donor)->data;
3665 ((cvmat_t*)recipient)->offset += ((iplimage_t*)donor)->offset;
3667 return failmsg("Argument 'mat' must be either IplImage or CvMat"), (PyObject*)0;
3669 ((cvmat_t*)recipient)->data = arr_data;
3670 Py_INCREF(arr_data);
3674 static PyObject *shareDataND(PyObject *donor, CvMatND *pdonor, CvMatND *precipient)
3676 PyObject *recipient = (PyObject*)PyObject_NEW(cvmatnd_t, &cvmatnd_Type);
3677 ((cvmatnd_t*)recipient)->a = precipient;
3678 ((cvmatnd_t*)recipient)->offset = 0;
3681 arr_data = ((cvmatnd_t*)donor)->data;
3682 ((cvmatnd_t*)recipient)->data = arr_data;
3683 Py_INCREF(arr_data);
3687 static PyObject *pycvGetHuMoments(PyObject *self, PyObject *args)
3690 PyObject *pyobj_moments = NULL;
3692 if (!PyArg_ParseTuple(args, "O", &pyobj_moments))
3694 if (!convert_to_CvMomentsPTR(pyobj_moments, &moments, "moments")) return NULL;
3696 ERRWRAP(cvGetHuMoments(moments, &r));
3697 return Py_BuildValue("ddddddd", r.hu1, r.hu2, r.hu3, r.hu4, r.hu5, r.hu6, r.hu7);
3700 static PyObject *pycvFitLine(PyObject *self, PyObject *args)
3703 PyObject *pyobj_points = NULL;
3710 if (!PyArg_ParseTuple(args, "Oifff", &pyobj_points, &dist_type, ¶m, &reps, &aeps))
3712 if (!convert_to_cvarrseq(pyobj_points, &points, "points")) return NULL;
3713 ERRWRAP(cvFitLine(points.mat, dist_type, param, reps, aeps, r));
3715 if (strcmp("opencv-matrix", cvTypeOf(points.mat)->type_name) == 0)
3716 dimension = CV_MAT_CN(cvGetElemType(points.mat));
3718 // sequence case... don't think there is a sequence of 3d points,
3723 return Py_BuildValue("dddd", r[0], r[1], r[2], r[3]);
3725 return Py_BuildValue("dddddd", r[0], r[1], r[2], r[3], r[4], r[5]);
3728 static PyObject *pycvGetMinMaxHistValue(PyObject *self, PyObject *args)
3731 PyObject *pyobj_hist = NULL;
3734 int min_loc[CV_MAX_DIM];
3735 int max_loc[CV_MAX_DIM];
3737 if (!PyArg_ParseTuple(args, "O", &pyobj_hist))
3739 if (!convert_to_CvHistogram(pyobj_hist, &hist, "hist")) return NULL;
3740 ERRWRAP(cvGetMinMaxHistValue(hist, &min_val, &max_val, min_loc, max_loc));
3741 int d = cvGetDims(hist->bins);
3742 PyObject *pminloc = PyTuple_New(d), *pmaxloc = PyTuple_New(d);
3743 for (int i = 0; i < d; i++) {
3744 PyTuple_SetItem(pminloc, i, PyInt_FromLong(min_loc[i]));
3745 PyTuple_SetItem(pmaxloc, i, PyInt_FromLong(max_loc[i]));
3747 return Py_BuildValue("ffNN", min_val, max_val, pminloc, pmaxloc);
3750 static CvSeq* cvHOGDetectMultiScale( const CvArr* image, CvMemStorage* storage,
3751 const CvArr* svm_classifier=NULL, CvSize win_stride=cvSize(0,0),
3752 double hit_threshold=0, double scale=1.05,
3753 int group_threshold=2, CvSize padding=cvSize(0,0),
3754 CvSize win_size=cvSize(64,128), CvSize block_size=cvSize(16,16),
3755 CvSize block_stride=cvSize(8,8), CvSize cell_size=cvSize(8,8),
3756 int nbins=9, int gammaCorrection=1 )
3758 cv::HOGDescriptor hog(win_size, block_size, block_stride, cell_size, nbins, 1, -1, cv::HOGDescriptor::L2Hys, 0.2, gammaCorrection!=0);
3759 if(win_stride.width == 0 && win_stride.height == 0)
3760 win_stride = block_stride;
3761 cv::Mat img = cv::cvarrToMat(image);
3762 std::vector<cv::Rect> found;
3765 CvMat stub, *m = cvGetMat(svm_classifier, &stub);
3766 int sz = m->cols*m->rows;
3767 CV_Assert(CV_IS_MAT_CONT(m->type) && (m->cols == 1 || m->rows == 1) && CV_MAT_TYPE(m->type) == CV_32FC1);
3768 std::vector<float> w(sz);
3769 std::copy(m->data.fl, m->data.fl + sz, w.begin());
3770 hog.setSVMDetector(w);
3773 hog.setSVMDetector(cv::HOGDescriptor::getDefaultPeopleDetector());
3774 hog.detectMultiScale(img, found, hit_threshold, win_stride, padding, scale, group_threshold);
3775 CvSeq* seq = cvCreateSeq(cv::DataType<cv::Rect>::type, sizeof(CvSeq), sizeof(cv::Rect), storage);
3777 cvSeqPushMulti(seq, &found[0], (int)found.size());
3781 static void cvGrabCut(CvArr *image,
3789 cv::Mat _image = cv::cvarrToMat(image);
3790 cv::Mat _mask = cv::cvarrToMat(mask);
3791 cv::Mat _bgdModel = cv::cvarrToMat(bgdModel);
3792 cv::Mat _fgdModel = cv::cvarrToMat(fgdModel);
3793 grabCut(_image, _mask, rect, _bgdModel, _fgdModel, iterCount, mode);
3796 static int zero = 0;
3798 /************************************************************************/
3799 /* Custom Validators */
3801 #define CVPY_VALIDATE_DrawChessboardCorners() do { \
3802 if ((patternSize.width * patternSize.height) != corners.count) \
3803 return (PyObject*)failmsg("Size is %dx%d, but corner list is length %d", patternSize.width, patternSize.height, corners.count); \
3806 #define cvGetRotationMatrix2D cv2DRotationMatrix
3808 /************************************************************************/
3809 /* Generated functions */
3811 #define constCvMat const CvMat
3812 #define FROM_constCvMatPTR(x) FROM_CvMatPTR((CvMat*)x)
3814 #define cvSnakeImage(image, points, length, a, b, g, win, criteria, calc_gradient) \
3817 if ((alpha.count == 1) && (beta.count == 1) && (gamma.count == 1)) \
3818 coeff_usage = CV_VALUE; \
3819 else if ((length == alpha.count) && (alpha.count == beta.count) && (beta.count == gamma.count)) \
3820 coeff_usage = CV_ARRAY; \
3822 return (PyObject*)failmsg("SnakeImage weights invalid"); \
3823 cvSnakeImage(image, points, length, a, b, g, coeff_usage, win, criteria, calc_gradient); \
3826 static double cppKMeans(const CvArr* _samples, int cluster_count, CvArr* _labels,
3827 CvTermCriteria termcrit, int attempts, int flags, CvArr* _centers)
3829 cv::Mat data = cv::cvarrToMat(_samples), labels = cv::cvarrToMat(_labels), centers;
3831 centers = cv::cvarrToMat(_centers);
3832 CV_Assert( labels.isContinuous() && labels.type() == CV_32S &&
3833 (labels.cols == 1 || labels.rows == 1) &&
3834 labels.cols + labels.rows - 1 == data.rows );
3835 return cv::kmeans(data, cluster_count, labels, termcrit, attempts,
3836 flags, _centers ? cv::_OutputArray(centers) : cv::_OutputArray() );
3839 #define cvKMeans2(samples, nclusters, labels, termcrit, attempts, flags, centers) \
3840 cppKMeans(samples, nclusters, labels, termcrit, attempts, flags, centers)
3842 #include "generated0.i"
3844 static PyMethodDef old_methods[] = {
3846 #if PYTHON_USE_NUMPY
3847 {"fromarray", (PyCFunction)pycvfromarray, METH_KEYWORDS, "fromarray(array) -> cvmatnd"},
3850 {"FindDataMatrix", pyfinddatamatrix, METH_VARARGS},
3851 {"temp_test", temp_test, METH_VARARGS},
3853 #include "generated1.i"
3858 /************************************************************************/
3864 cvSetErrMode(CV_ErrModeParent);
3866 #define MKTYPE(NAME) NAME##_specials(); to_ok(&NAME##_Type)
3868 MKTYPE(cvcontourtree);
3870 MKTYPE(cvhistogram);
3871 MKTYPE(cvlineiterator);
3874 MKTYPE(cvmemstorage);
3875 MKTYPE(cvsubdiv2dedge);
3880 MKTYPE(cvsubdiv2dpoint);
3884 #include "generated4.i"
3888 m = Py_InitModule(OLD_MODULESTR, old_methods);
3889 d = PyModule_GetDict(m);
3891 PyDict_SetItemString(d, "__version__", PyString_FromString("$Rev: 4557 $"));
3892 PyDict_SetItemString(d, "error", opencv_error);
3894 // Couple of warnings about strict aliasing here. Not clear how to fix.
3899 convert.to = &iplimage_Type;
3900 PyDict_SetItemString(d, "iplimage", convert.o);
3901 convert.to = &cvmat_Type;
3902 PyDict_SetItemString(d, "cvmat", convert.o);
3904 // AFAIK the only floating-point constant
3905 PyDict_SetItemString(d, "CV_PI", PyFloat_FromDouble(CV_PI));
3907 #define PUBLISH(I) PyDict_SetItemString(d, #I, PyInt_FromLong(I))
3908 #define PUBLISHU(I) PyDict_SetItemString(d, #I, PyLong_FromUnsignedLong(I))
3909 #define PUBLISH2(I, value) PyDict_SetItemString(d, #I, PyLong_FromLong(value))
3911 PUBLISHU(IPL_DEPTH_8U);
3912 PUBLISHU(IPL_DEPTH_8S);
3913 PUBLISHU(IPL_DEPTH_16U);
3914 PUBLISHU(IPL_DEPTH_16S);
3915 PUBLISHU(IPL_DEPTH_32S);
3916 PUBLISHU(IPL_DEPTH_32F);
3917 PUBLISHU(IPL_DEPTH_64F);
3919 PUBLISH(CV_LOAD_IMAGE_COLOR);
3920 PUBLISH(CV_LOAD_IMAGE_GRAYSCALE);
3921 PUBLISH(CV_LOAD_IMAGE_UNCHANGED);
3922 PUBLISH(CV_HIST_ARRAY);
3923 PUBLISH(CV_HIST_SPARSE);
3959 PUBLISH(CV_NEXT_AROUND_ORG);
3960 PUBLISH(CV_NEXT_AROUND_DST);
3961 PUBLISH(CV_PREV_AROUND_ORG);
3962 PUBLISH(CV_PREV_AROUND_DST);
3963 PUBLISH(CV_NEXT_AROUND_LEFT);
3964 PUBLISH(CV_NEXT_AROUND_RIGHT);
3965 PUBLISH(CV_PREV_AROUND_LEFT);
3966 PUBLISH(CV_PREV_AROUND_RIGHT);
3968 PUBLISH(CV_WINDOW_AUTOSIZE);
3970 PUBLISH(CV_PTLOC_INSIDE);
3971 PUBLISH(CV_PTLOC_ON_EDGE);
3972 PUBLISH(CV_PTLOC_VERTEX);
3973 PUBLISH(CV_PTLOC_OUTSIDE_RECT);
3979 PUBLISH(GC_INIT_WITH_RECT);
3980 PUBLISH(GC_INIT_WITH_MASK);
3983 #include "generated2.i"