Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/modules/python/src2/cv2.cpp
16337 views
1
//warning number '5033' not a valid compiler warning in vc12
2
#if defined(_MSC_VER) && (_MSC_VER > 1800)
3
// eliminating duplicated round() declaration
4
#define HAVE_ROUND 1
5
#pragma warning(push)
6
#pragma warning(disable:5033) // 'register' is no longer a supported storage class
7
#endif
8
#include <math.h>
9
#include <Python.h>
10
#if defined(_MSC_VER) && (_MSC_VER > 1800)
11
#pragma warning(pop)
12
#endif
13
14
#include <type_traits> // std::enable_if
15
16
template<typename T, class TEnable = void> // TEnable is used for SFINAE checks
17
struct PyOpenCV_Converter
18
{
19
//static inline bool to(PyObject* obj, T& p, const char* name);
20
//static inline PyObject* from(const T& src);
21
};
22
23
template<typename T> static
24
bool pyopencv_to(PyObject* obj, T& p, const char* name = "<unknown>") { return PyOpenCV_Converter<T>::to(obj, p, name); }
25
26
template<typename T> static
27
PyObject* pyopencv_from(const T& src) { return PyOpenCV_Converter<T>::from(src); }
28
29
30
#define CV_PY_FN_WITH_KW_(fn, flags) (PyCFunction)(void*)(PyCFunctionWithKeywords)(fn), (flags) | METH_VARARGS | METH_KEYWORDS
31
#define CV_PY_FN_NOARGS_(fn, flags) (PyCFunction)(fn), (flags) | METH_NOARGS
32
33
#define CV_PY_FN_WITH_KW(fn) CV_PY_FN_WITH_KW_(fn, 0)
34
#define CV_PY_FN_NOARGS(fn) CV_PY_FN_NOARGS_(fn, 0)
35
36
37
#define MODULESTR "cv2"
38
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
39
#include <numpy/ndarrayobject.h>
40
41
#if PY_MAJOR_VERSION >= 3
42
# define CV_PYTHON_TYPE_HEAD_INIT() PyVarObject_HEAD_INIT(&PyType_Type, 0)
43
#else
44
# define CV_PYTHON_TYPE_HEAD_INIT() PyObject_HEAD_INIT(&PyType_Type) 0,
45
#endif
46
47
#define CV_PY_TO_CLASS(TYPE) \
48
template<> \
49
bool pyopencv_to(PyObject* dst, TYPE& src, const char* name) \
50
{ \
51
if (!dst || dst == Py_None) \
52
return true; \
53
Ptr<TYPE> ptr; \
54
\
55
if (!pyopencv_to(dst, ptr, name)) return false; \
56
src = *ptr; \
57
return true; \
58
}
59
60
#define CV_PY_FROM_CLASS(TYPE) \
61
template<> \
62
PyObject* pyopencv_from(const TYPE& src) \
63
{ \
64
Ptr<TYPE> ptr(new TYPE()); \
65
\
66
*ptr = src; \
67
return pyopencv_from(ptr); \
68
}
69
70
#define CV_PY_TO_CLASS_PTR(TYPE) \
71
template<> \
72
bool pyopencv_to(PyObject* dst, TYPE*& src, const char* name) \
73
{ \
74
if (!dst || dst == Py_None) \
75
return true; \
76
Ptr<TYPE> ptr; \
77
\
78
if (!pyopencv_to(dst, ptr, name)) return false; \
79
src = ptr; \
80
return true; \
81
}
82
83
#define CV_PY_FROM_CLASS_PTR(TYPE) \
84
static PyObject* pyopencv_from(TYPE*& src) \
85
{ \
86
return pyopencv_from(Ptr<TYPE>(src)); \
87
}
88
89
#define CV_PY_TO_ENUM(TYPE) \
90
template<> \
91
bool pyopencv_to(PyObject* dst, TYPE& src, const char* name) \
92
{ \
93
if (!dst || dst == Py_None) \
94
return true; \
95
std::underlying_type<TYPE>::type underlying = 0; \
96
\
97
if (!pyopencv_to(dst, underlying, name)) return false; \
98
src = static_cast<TYPE>(underlying); \
99
return true; \
100
}
101
102
#define CV_PY_FROM_ENUM(TYPE) \
103
template<> \
104
PyObject* pyopencv_from(const TYPE& src) \
105
{ \
106
return pyopencv_from(static_cast<std::underlying_type<TYPE>::type>(src)); \
107
}
108
109
#include "pyopencv_generated_include.h"
110
#include "opencv2/core/types_c.h"
111
112
#include "opencv2/opencv_modules.hpp"
113
114
#include "pycompat.hpp"
115
116
#include <map>
117
118
static PyObject* opencv_error = NULL;
119
120
static int failmsg(const char *fmt, ...)
121
{
122
char str[1000];
123
124
va_list ap;
125
va_start(ap, fmt);
126
vsnprintf(str, sizeof(str), fmt, ap);
127
va_end(ap);
128
129
PyErr_SetString(PyExc_TypeError, str);
130
return 0;
131
}
132
133
struct ArgInfo
134
{
135
const char * name;
136
bool outputarg;
137
// more fields may be added if necessary
138
139
ArgInfo(const char * name_, bool outputarg_)
140
: name(name_)
141
, outputarg(outputarg_) {}
142
143
// to match with older pyopencv_to function signature
144
operator const char *() const { return name; }
145
};
146
147
class PyAllowThreads
148
{
149
public:
150
PyAllowThreads() : _state(PyEval_SaveThread()) {}
151
~PyAllowThreads()
152
{
153
PyEval_RestoreThread(_state);
154
}
155
private:
156
PyThreadState* _state;
157
};
158
159
class PyEnsureGIL
160
{
161
public:
162
PyEnsureGIL() : _state(PyGILState_Ensure()) {}
163
~PyEnsureGIL()
164
{
165
PyGILState_Release(_state);
166
}
167
private:
168
PyGILState_STATE _state;
169
};
170
171
#define ERRWRAP2(expr) \
172
try \
173
{ \
174
PyAllowThreads allowThreads; \
175
expr; \
176
} \
177
catch (const cv::Exception &e) \
178
{ \
179
PyObject_SetAttrString(opencv_error, "file", PyString_FromString(e.file.c_str())); \
180
PyObject_SetAttrString(opencv_error, "func", PyString_FromString(e.func.c_str())); \
181
PyObject_SetAttrString(opencv_error, "line", PyInt_FromLong(e.line)); \
182
PyObject_SetAttrString(opencv_error, "code", PyInt_FromLong(e.code)); \
183
PyObject_SetAttrString(opencv_error, "msg", PyString_FromString(e.msg.c_str())); \
184
PyObject_SetAttrString(opencv_error, "err", PyString_FromString(e.err.c_str())); \
185
PyErr_SetString(opencv_error, e.what()); \
186
return 0; \
187
}
188
189
using namespace cv;
190
191
typedef std::vector<uchar> vector_uchar;
192
typedef std::vector<char> vector_char;
193
typedef std::vector<int> vector_int;
194
typedef std::vector<float> vector_float;
195
typedef std::vector<double> vector_double;
196
typedef std::vector<size_t> vector_size_t;
197
typedef std::vector<Point> vector_Point;
198
typedef std::vector<Point2f> vector_Point2f;
199
typedef std::vector<Point3f> vector_Point3f;
200
typedef std::vector<Vec2f> vector_Vec2f;
201
typedef std::vector<Vec3f> vector_Vec3f;
202
typedef std::vector<Vec4f> vector_Vec4f;
203
typedef std::vector<Vec6f> vector_Vec6f;
204
typedef std::vector<Vec4i> vector_Vec4i;
205
typedef std::vector<Rect> vector_Rect;
206
typedef std::vector<Rect2d> vector_Rect2d;
207
typedef std::vector<RotatedRect> vector_RotatedRect;
208
typedef std::vector<KeyPoint> vector_KeyPoint;
209
typedef std::vector<Mat> vector_Mat;
210
typedef std::vector<std::vector<Mat> > vector_vector_Mat;
211
typedef std::vector<UMat> vector_UMat;
212
typedef std::vector<DMatch> vector_DMatch;
213
typedef std::vector<String> vector_String;
214
typedef std::vector<Scalar> vector_Scalar;
215
216
typedef std::vector<std::vector<char> > vector_vector_char;
217
typedef std::vector<std::vector<Point> > vector_vector_Point;
218
typedef std::vector<std::vector<Point2f> > vector_vector_Point2f;
219
typedef std::vector<std::vector<Point3f> > vector_vector_Point3f;
220
typedef std::vector<std::vector<DMatch> > vector_vector_DMatch;
221
typedef std::vector<std::vector<KeyPoint> > vector_vector_KeyPoint;
222
223
static PyObject* failmsgp(const char *fmt, ...)
224
{
225
char str[1000];
226
227
va_list ap;
228
va_start(ap, fmt);
229
vsnprintf(str, sizeof(str), fmt, ap);
230
va_end(ap);
231
232
PyErr_SetString(PyExc_TypeError, str);
233
return 0;
234
}
235
236
class NumpyAllocator : public MatAllocator
237
{
238
public:
239
NumpyAllocator() { stdAllocator = Mat::getStdAllocator(); }
240
~NumpyAllocator() {}
241
242
UMatData* allocate(PyObject* o, int dims, const int* sizes, int type, size_t* step) const
243
{
244
UMatData* u = new UMatData(this);
245
u->data = u->origdata = (uchar*)PyArray_DATA((PyArrayObject*) o);
246
npy_intp* _strides = PyArray_STRIDES((PyArrayObject*) o);
247
for( int i = 0; i < dims - 1; i++ )
248
step[i] = (size_t)_strides[i];
249
step[dims-1] = CV_ELEM_SIZE(type);
250
u->size = sizes[0]*step[0];
251
u->userdata = o;
252
return u;
253
}
254
255
UMatData* allocate(int dims0, const int* sizes, int type, void* data, size_t* step, AccessFlag flags, UMatUsageFlags usageFlags) const CV_OVERRIDE
256
{
257
if( data != 0 )
258
{
259
// issue #6969: CV_Error(Error::StsAssert, "The data should normally be NULL!");
260
// probably this is safe to do in such extreme case
261
return stdAllocator->allocate(dims0, sizes, type, data, step, flags, usageFlags);
262
}
263
PyEnsureGIL gil;
264
265
int depth = CV_MAT_DEPTH(type);
266
int cn = CV_MAT_CN(type);
267
const int f = (int)(sizeof(size_t)/8);
268
int typenum = depth == CV_8U ? NPY_UBYTE : depth == CV_8S ? NPY_BYTE :
269
depth == CV_16U ? NPY_USHORT : depth == CV_16S ? NPY_SHORT :
270
depth == CV_32S ? NPY_INT : depth == CV_32F ? NPY_FLOAT :
271
depth == CV_64F ? NPY_DOUBLE : f*NPY_ULONGLONG + (f^1)*NPY_UINT;
272
int i, dims = dims0;
273
cv::AutoBuffer<npy_intp> _sizes(dims + 1);
274
for( i = 0; i < dims; i++ )
275
_sizes[i] = sizes[i];
276
if( cn > 1 )
277
_sizes[dims++] = cn;
278
PyObject* o = PyArray_SimpleNew(dims, _sizes.data(), typenum);
279
if(!o)
280
CV_Error_(Error::StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims));
281
return allocate(o, dims0, sizes, type, step);
282
}
283
284
bool allocate(UMatData* u, AccessFlag accessFlags, UMatUsageFlags usageFlags) const CV_OVERRIDE
285
{
286
return stdAllocator->allocate(u, accessFlags, usageFlags);
287
}
288
289
void deallocate(UMatData* u) const CV_OVERRIDE
290
{
291
if(!u)
292
return;
293
PyEnsureGIL gil;
294
CV_Assert(u->urefcount >= 0);
295
CV_Assert(u->refcount >= 0);
296
if(u->refcount == 0)
297
{
298
PyObject* o = (PyObject*)u->userdata;
299
Py_XDECREF(o);
300
delete u;
301
}
302
}
303
304
const MatAllocator* stdAllocator;
305
};
306
307
NumpyAllocator g_numpyAllocator;
308
309
310
enum { ARG_NONE = 0, ARG_MAT = 1, ARG_SCALAR = 2 };
311
312
// special case, when the converter needs full ArgInfo structure
313
static bool pyopencv_to(PyObject* o, Mat& m, const ArgInfo info)
314
{
315
bool allowND = true;
316
if(!o || o == Py_None)
317
{
318
if( !m.data )
319
m.allocator = &g_numpyAllocator;
320
return true;
321
}
322
323
if( PyInt_Check(o) )
324
{
325
double v[] = {static_cast<double>(PyInt_AsLong((PyObject*)o)), 0., 0., 0.};
326
m = Mat(4, 1, CV_64F, v).clone();
327
return true;
328
}
329
if( PyFloat_Check(o) )
330
{
331
double v[] = {PyFloat_AsDouble((PyObject*)o), 0., 0., 0.};
332
m = Mat(4, 1, CV_64F, v).clone();
333
return true;
334
}
335
if( PyTuple_Check(o) )
336
{
337
int i, sz = (int)PyTuple_Size((PyObject*)o);
338
m = Mat(sz, 1, CV_64F);
339
for( i = 0; i < sz; i++ )
340
{
341
PyObject* oi = PyTuple_GET_ITEM(o, i);
342
if( PyInt_Check(oi) )
343
m.at<double>(i) = (double)PyInt_AsLong(oi);
344
else if( PyFloat_Check(oi) )
345
m.at<double>(i) = (double)PyFloat_AsDouble(oi);
346
else
347
{
348
failmsg("%s is not a numerical tuple", info.name);
349
m.release();
350
return false;
351
}
352
}
353
return true;
354
}
355
356
if( !PyArray_Check(o) )
357
{
358
failmsg("%s is not a numpy array, neither a scalar", info.name);
359
return false;
360
}
361
362
PyArrayObject* oarr = (PyArrayObject*) o;
363
364
bool needcopy = false, needcast = false;
365
int typenum = PyArray_TYPE(oarr), new_typenum = typenum;
366
int type = typenum == NPY_UBYTE ? CV_8U :
367
typenum == NPY_BYTE ? CV_8S :
368
typenum == NPY_USHORT ? CV_16U :
369
typenum == NPY_SHORT ? CV_16S :
370
typenum == NPY_INT ? CV_32S :
371
typenum == NPY_INT32 ? CV_32S :
372
typenum == NPY_FLOAT ? CV_32F :
373
typenum == NPY_DOUBLE ? CV_64F : -1;
374
375
if( type < 0 )
376
{
377
if( typenum == NPY_INT64 || typenum == NPY_UINT64 || typenum == NPY_LONG )
378
{
379
needcopy = needcast = true;
380
new_typenum = NPY_INT;
381
type = CV_32S;
382
}
383
else
384
{
385
failmsg("%s data type = %d is not supported", info.name, typenum);
386
return false;
387
}
388
}
389
390
#ifndef CV_MAX_DIM
391
const int CV_MAX_DIM = 32;
392
#endif
393
394
int ndims = PyArray_NDIM(oarr);
395
if(ndims >= CV_MAX_DIM)
396
{
397
failmsg("%s dimensionality (=%d) is too high", info.name, ndims);
398
return false;
399
}
400
401
int size[CV_MAX_DIM+1];
402
size_t step[CV_MAX_DIM+1];
403
size_t elemsize = CV_ELEM_SIZE1(type);
404
const npy_intp* _sizes = PyArray_DIMS(oarr);
405
const npy_intp* _strides = PyArray_STRIDES(oarr);
406
bool ismultichannel = ndims == 3 && _sizes[2] <= CV_CN_MAX;
407
408
for( int i = ndims-1; i >= 0 && !needcopy; i-- )
409
{
410
// these checks handle cases of
411
// a) multi-dimensional (ndims > 2) arrays, as well as simpler 1- and 2-dimensional cases
412
// b) transposed arrays, where _strides[] elements go in non-descending order
413
// c) flipped arrays, where some of _strides[] elements are negative
414
// the _sizes[i] > 1 is needed to avoid spurious copies when NPY_RELAXED_STRIDES is set
415
if( (i == ndims-1 && _sizes[i] > 1 && (size_t)_strides[i] != elemsize) ||
416
(i < ndims-1 && _sizes[i] > 1 && _strides[i] < _strides[i+1]) )
417
needcopy = true;
418
}
419
420
if( ismultichannel && _strides[1] != (npy_intp)elemsize*_sizes[2] )
421
needcopy = true;
422
423
if (needcopy)
424
{
425
if (info.outputarg)
426
{
427
failmsg("Layout of the output array %s is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)", info.name);
428
return false;
429
}
430
431
if( needcast ) {
432
o = PyArray_Cast(oarr, new_typenum);
433
oarr = (PyArrayObject*) o;
434
}
435
else {
436
oarr = PyArray_GETCONTIGUOUS(oarr);
437
o = (PyObject*) oarr;
438
}
439
440
_strides = PyArray_STRIDES(oarr);
441
}
442
443
// Normalize strides in case NPY_RELAXED_STRIDES is set
444
size_t default_step = elemsize;
445
for ( int i = ndims - 1; i >= 0; --i )
446
{
447
size[i] = (int)_sizes[i];
448
if ( size[i] > 1 )
449
{
450
step[i] = (size_t)_strides[i];
451
default_step = step[i] * size[i];
452
}
453
else
454
{
455
step[i] = default_step;
456
default_step *= size[i];
457
}
458
}
459
460
// handle degenerate case
461
if( ndims == 0) {
462
size[ndims] = 1;
463
step[ndims] = elemsize;
464
ndims++;
465
}
466
467
if( ismultichannel )
468
{
469
ndims--;
470
type |= CV_MAKETYPE(0, size[2]);
471
}
472
473
if( ndims > 2 && !allowND )
474
{
475
failmsg("%s has more than 2 dimensions", info.name);
476
return false;
477
}
478
479
m = Mat(ndims, size, type, PyArray_DATA(oarr), step);
480
m.u = g_numpyAllocator.allocate(o, ndims, size, type, step);
481
m.addref();
482
483
if( !needcopy )
484
{
485
Py_INCREF(o);
486
}
487
m.allocator = &g_numpyAllocator;
488
489
return true;
490
}
491
492
template<>
493
bool pyopencv_to(PyObject* o, Mat& m, const char* name)
494
{
495
return pyopencv_to(o, m, ArgInfo(name, 0));
496
}
497
498
template<typename _Tp, int m, int n>
499
bool pyopencv_to(PyObject* o, Matx<_Tp, m, n>& mx, const ArgInfo info)
500
{
501
Mat tmp;
502
if (!pyopencv_to(o, tmp, info)) {
503
return false;
504
}
505
506
tmp.copyTo(mx);
507
return true;
508
}
509
510
template<typename _Tp, int m, int n>
511
bool pyopencv_to(PyObject* o, Matx<_Tp, m, n>& mx, const char* name)
512
{
513
return pyopencv_to(o, mx, ArgInfo(name, 0));
514
}
515
516
template<>
517
PyObject* pyopencv_from(const Mat& m)
518
{
519
if( !m.data )
520
Py_RETURN_NONE;
521
Mat temp, *p = (Mat*)&m;
522
if(!p->u || p->allocator != &g_numpyAllocator)
523
{
524
temp.allocator = &g_numpyAllocator;
525
ERRWRAP2(m.copyTo(temp));
526
p = &temp;
527
}
528
PyObject* o = (PyObject*)p->u->userdata;
529
Py_INCREF(o);
530
return o;
531
}
532
533
template<typename _Tp, int m, int n>
534
PyObject* pyopencv_from(const Matx<_Tp, m, n>& matx)
535
{
536
return pyopencv_from(Mat(matx));
537
}
538
539
template<typename T>
540
struct PyOpenCV_Converter< cv::Ptr<T> >
541
{
542
static PyObject* from(const cv::Ptr<T>& p)
543
{
544
if (!p)
545
Py_RETURN_NONE;
546
return pyopencv_from(*p);
547
}
548
static bool to(PyObject *o, Ptr<T>& p, const char *name)
549
{
550
if (!o || o == Py_None)
551
return true;
552
p = makePtr<T>();
553
return pyopencv_to(o, *p, name);
554
}
555
};
556
557
template<>
558
bool pyopencv_to(PyObject* obj, void*& ptr, const char* name)
559
{
560
CV_UNUSED(name);
561
if (!obj || obj == Py_None)
562
return true;
563
564
if (!PyLong_Check(obj))
565
return false;
566
ptr = PyLong_AsVoidPtr(obj);
567
return ptr != NULL && !PyErr_Occurred();
568
}
569
570
static PyObject* pyopencv_from(void*& ptr)
571
{
572
return PyLong_FromVoidPtr(ptr);
573
}
574
575
static bool pyopencv_to(PyObject *o, Scalar& s, const ArgInfo info)
576
{
577
if(!o || o == Py_None)
578
return true;
579
if (PySequence_Check(o)) {
580
PyObject *fi = PySequence_Fast(o, info.name);
581
if (fi == NULL)
582
return false;
583
if (4 < PySequence_Fast_GET_SIZE(fi))
584
{
585
failmsg("Scalar value for argument '%s' is longer than 4", info.name);
586
return false;
587
}
588
for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
589
PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
590
if (PyFloat_Check(item) || PyInt_Check(item)) {
591
s[(int)i] = PyFloat_AsDouble(item);
592
} else {
593
failmsg("Scalar value for argument '%s' is not numeric", info.name);
594
return false;
595
}
596
}
597
Py_DECREF(fi);
598
} else {
599
if (PyFloat_Check(o) || PyInt_Check(o)) {
600
s[0] = PyFloat_AsDouble(o);
601
} else {
602
failmsg("Scalar value for argument '%s' is not numeric", info.name);
603
return false;
604
}
605
}
606
return true;
607
}
608
609
template<>
610
bool pyopencv_to(PyObject *o, Scalar& s, const char *name)
611
{
612
return pyopencv_to(o, s, ArgInfo(name, 0));
613
}
614
615
template<>
616
PyObject* pyopencv_from(const Scalar& src)
617
{
618
return Py_BuildValue("(dddd)", src[0], src[1], src[2], src[3]);
619
}
620
621
template<>
622
PyObject* pyopencv_from(const bool& value)
623
{
624
return PyBool_FromLong(value);
625
}
626
627
template<>
628
bool pyopencv_to(PyObject* obj, bool& value, const char* name)
629
{
630
CV_UNUSED(name);
631
if(!obj || obj == Py_None)
632
return true;
633
int _val = PyObject_IsTrue(obj);
634
if(_val < 0)
635
return false;
636
value = _val > 0;
637
return true;
638
}
639
640
template<>
641
PyObject* pyopencv_from(const size_t& value)
642
{
643
return PyLong_FromSize_t(value);
644
}
645
646
template<>
647
bool pyopencv_to(PyObject* obj, size_t& value, const char* name)
648
{
649
CV_UNUSED(name);
650
if(!obj || obj == Py_None)
651
return true;
652
value = (int)PyLong_AsUnsignedLong(obj);
653
return value != (size_t)-1 || !PyErr_Occurred();
654
}
655
656
template<>
657
PyObject* pyopencv_from(const int& value)
658
{
659
return PyInt_FromLong(value);
660
}
661
662
template<>
663
bool pyopencv_to(PyObject* obj, int& value, const char* name)
664
{
665
CV_UNUSED(name);
666
if(!obj || obj == Py_None)
667
return true;
668
if(PyInt_Check(obj))
669
value = (int)PyInt_AsLong(obj);
670
else if(PyLong_Check(obj))
671
value = (int)PyLong_AsLong(obj);
672
else
673
return false;
674
return value != -1 || !PyErr_Occurred();
675
}
676
677
// There is conflict between "size_t" and "unsigned int".
678
// They are the same type on some 32-bit platforms.
679
template<typename T>
680
struct PyOpenCV_Converter
681
< T, typename std::enable_if< std::is_same<unsigned int, T>::value && !std::is_same<unsigned int, size_t>::value >::type >
682
{
683
static inline PyObject* from(const unsigned int& value)
684
{
685
return PyLong_FromUnsignedLong(value);
686
}
687
688
static inline bool to(PyObject* obj, unsigned int& value, const char* name)
689
{
690
CV_UNUSED(name);
691
if(!obj || obj == Py_None)
692
return true;
693
if(PyInt_Check(obj))
694
value = (unsigned int)PyInt_AsLong(obj);
695
else if(PyLong_Check(obj))
696
value = (unsigned int)PyLong_AsLong(obj);
697
else
698
return false;
699
return value != (unsigned int)-1 || !PyErr_Occurred();
700
}
701
};
702
703
template<>
704
PyObject* pyopencv_from(const uchar& value)
705
{
706
return PyInt_FromLong(value);
707
}
708
709
template<>
710
bool pyopencv_to(PyObject* obj, uchar& value, const char* name)
711
{
712
CV_UNUSED(name);
713
if(!obj || obj == Py_None)
714
return true;
715
int ivalue = (int)PyInt_AsLong(obj);
716
value = cv::saturate_cast<uchar>(ivalue);
717
return ivalue != -1 || !PyErr_Occurred();
718
}
719
720
template<>
721
PyObject* pyopencv_from(const double& value)
722
{
723
return PyFloat_FromDouble(value);
724
}
725
726
template<>
727
bool pyopencv_to(PyObject* obj, double& value, const char* name)
728
{
729
CV_UNUSED(name);
730
if(!obj || obj == Py_None)
731
return true;
732
if(!!PyInt_CheckExact(obj))
733
value = (double)PyInt_AS_LONG(obj);
734
else
735
value = PyFloat_AsDouble(obj);
736
return !PyErr_Occurred();
737
}
738
739
template<>
740
PyObject* pyopencv_from(const float& value)
741
{
742
return PyFloat_FromDouble(value);
743
}
744
745
template<>
746
bool pyopencv_to(PyObject* obj, float& value, const char* name)
747
{
748
CV_UNUSED(name);
749
if(!obj || obj == Py_None)
750
return true;
751
if(!!PyInt_CheckExact(obj))
752
value = (float)PyInt_AS_LONG(obj);
753
else
754
value = (float)PyFloat_AsDouble(obj);
755
return !PyErr_Occurred();
756
}
757
758
template<>
759
PyObject* pyopencv_from(const int64& value)
760
{
761
return PyLong_FromLongLong(value);
762
}
763
764
template<>
765
PyObject* pyopencv_from(const String& value)
766
{
767
return PyString_FromString(value.empty() ? "" : value.c_str());
768
}
769
770
template<>
771
bool pyopencv_to(PyObject* obj, String& value, const char* name)
772
{
773
CV_UNUSED(name);
774
if(!obj || obj == Py_None)
775
return true;
776
const char* str = PyString_AsString(obj);
777
if(!str)
778
return false;
779
value = String(str);
780
return true;
781
}
782
783
template<>
784
bool pyopencv_to(PyObject* obj, Size& sz, const char* name)
785
{
786
CV_UNUSED(name);
787
if(!obj || obj == Py_None)
788
return true;
789
return PyArg_ParseTuple(obj, "ii", &sz.width, &sz.height) > 0;
790
}
791
792
template<>
793
PyObject* pyopencv_from(const Size& sz)
794
{
795
return Py_BuildValue("(ii)", sz.width, sz.height);
796
}
797
798
template<>
799
bool pyopencv_to(PyObject* obj, Size_<float>& sz, const char* name)
800
{
801
CV_UNUSED(name);
802
if(!obj || obj == Py_None)
803
return true;
804
return PyArg_ParseTuple(obj, "ff", &sz.width, &sz.height) > 0;
805
}
806
807
template<>
808
PyObject* pyopencv_from(const Size_<float>& sz)
809
{
810
return Py_BuildValue("(ff)", sz.width, sz.height);
811
}
812
813
template<>
814
bool pyopencv_to(PyObject* obj, Rect& r, const char* name)
815
{
816
CV_UNUSED(name);
817
if(!obj || obj == Py_None)
818
return true;
819
return PyArg_ParseTuple(obj, "iiii", &r.x, &r.y, &r.width, &r.height) > 0;
820
}
821
822
template<>
823
PyObject* pyopencv_from(const Rect& r)
824
{
825
return Py_BuildValue("(iiii)", r.x, r.y, r.width, r.height);
826
}
827
828
template<>
829
bool pyopencv_to(PyObject* obj, Rect2d& r, const char* name)
830
{
831
CV_UNUSED(name);
832
if(!obj || obj == Py_None)
833
return true;
834
return PyArg_ParseTuple(obj, "dddd", &r.x, &r.y, &r.width, &r.height) > 0;
835
}
836
837
template<>
838
PyObject* pyopencv_from(const Rect2d& r)
839
{
840
return Py_BuildValue("(dddd)", r.x, r.y, r.width, r.height);
841
}
842
843
template<>
844
bool pyopencv_to(PyObject* obj, Range& r, const char* name)
845
{
846
CV_UNUSED(name);
847
if(!obj || obj == Py_None)
848
return true;
849
if(PyObject_Size(obj) == 0)
850
{
851
r = Range::all();
852
return true;
853
}
854
return PyArg_ParseTuple(obj, "ii", &r.start, &r.end) > 0;
855
}
856
857
template<>
858
PyObject* pyopencv_from(const Range& r)
859
{
860
return Py_BuildValue("(ii)", r.start, r.end);
861
}
862
863
template<>
864
bool pyopencv_to(PyObject* obj, Point& p, const char* name)
865
{
866
CV_UNUSED(name);
867
if(!obj || obj == Py_None)
868
return true;
869
if(!!PyComplex_CheckExact(obj))
870
{
871
Py_complex c = PyComplex_AsCComplex(obj);
872
p.x = saturate_cast<int>(c.real);
873
p.y = saturate_cast<int>(c.imag);
874
return true;
875
}
876
return PyArg_ParseTuple(obj, "ii", &p.x, &p.y) > 0;
877
}
878
879
template<>
880
bool pyopencv_to(PyObject* obj, Point2f& p, const char* name)
881
{
882
CV_UNUSED(name);
883
if(!obj || obj == Py_None)
884
return true;
885
if(!!PyComplex_CheckExact(obj))
886
{
887
Py_complex c = PyComplex_AsCComplex(obj);
888
p.x = saturate_cast<float>(c.real);
889
p.y = saturate_cast<float>(c.imag);
890
return true;
891
}
892
return PyArg_ParseTuple(obj, "ff", &p.x, &p.y) > 0;
893
}
894
895
template<>
896
bool pyopencv_to(PyObject* obj, Point2d& p, const char* name)
897
{
898
CV_UNUSED(name);
899
if(!obj || obj == Py_None)
900
return true;
901
if(!!PyComplex_CheckExact(obj))
902
{
903
Py_complex c = PyComplex_AsCComplex(obj);
904
p.x = saturate_cast<double>(c.real);
905
p.y = saturate_cast<double>(c.imag);
906
return true;
907
}
908
return PyArg_ParseTuple(obj, "dd", &p.x, &p.y) > 0;
909
}
910
911
template<>
912
bool pyopencv_to(PyObject* obj, Point3f& p, const char* name)
913
{
914
CV_UNUSED(name);
915
if(!obj || obj == Py_None)
916
return true;
917
return PyArg_ParseTuple(obj, "fff", &p.x, &p.y, &p.z) > 0;
918
}
919
920
template<>
921
bool pyopencv_to(PyObject* obj, Point3d& p, const char* name)
922
{
923
CV_UNUSED(name);
924
if(!obj || obj == Py_None)
925
return true;
926
return PyArg_ParseTuple(obj, "ddd", &p.x, &p.y, &p.z) > 0;
927
}
928
929
template<>
930
PyObject* pyopencv_from(const Point& p)
931
{
932
return Py_BuildValue("(ii)", p.x, p.y);
933
}
934
935
template<>
936
PyObject* pyopencv_from(const Point2f& p)
937
{
938
return Py_BuildValue("(dd)", p.x, p.y);
939
}
940
941
template<>
942
PyObject* pyopencv_from(const Point3f& p)
943
{
944
return Py_BuildValue("(ddd)", p.x, p.y, p.z);
945
}
946
947
static bool pyopencv_to(PyObject* obj, Vec4d& v, ArgInfo info)
948
{
949
CV_UNUSED(info);
950
if (!obj)
951
return true;
952
return PyArg_ParseTuple(obj, "dddd", &v[0], &v[1], &v[2], &v[3]) > 0;
953
}
954
template<>
955
bool pyopencv_to(PyObject* obj, Vec4d& v, const char* name)
956
{
957
return pyopencv_to(obj, v, ArgInfo(name, 0));
958
}
959
960
static bool pyopencv_to(PyObject* obj, Vec4f& v, ArgInfo info)
961
{
962
CV_UNUSED(info);
963
if (!obj)
964
return true;
965
return PyArg_ParseTuple(obj, "ffff", &v[0], &v[1], &v[2], &v[3]) > 0;
966
}
967
template<>
968
bool pyopencv_to(PyObject* obj, Vec4f& v, const char* name)
969
{
970
return pyopencv_to(obj, v, ArgInfo(name, 0));
971
}
972
973
static bool pyopencv_to(PyObject* obj, Vec4i& v, ArgInfo info)
974
{
975
CV_UNUSED(info);
976
if (!obj)
977
return true;
978
return PyArg_ParseTuple(obj, "iiii", &v[0], &v[1], &v[2], &v[3]) > 0;
979
}
980
template<>
981
bool pyopencv_to(PyObject* obj, Vec4i& v, const char* name)
982
{
983
return pyopencv_to(obj, v, ArgInfo(name, 0));
984
}
985
986
static bool pyopencv_to(PyObject* obj, Vec3d& v, ArgInfo info)
987
{
988
CV_UNUSED(info);
989
if (!obj)
990
return true;
991
return PyArg_ParseTuple(obj, "ddd", &v[0], &v[1], &v[2]) > 0;
992
}
993
template<>
994
bool pyopencv_to(PyObject* obj, Vec3d& v, const char* name)
995
{
996
return pyopencv_to(obj, v, ArgInfo(name, 0));
997
}
998
999
static bool pyopencv_to(PyObject* obj, Vec3f& v, ArgInfo info)
1000
{
1001
CV_UNUSED(info);
1002
if (!obj)
1003
return true;
1004
return PyArg_ParseTuple(obj, "fff", &v[0], &v[1], &v[2]) > 0;
1005
}
1006
template<>
1007
bool pyopencv_to(PyObject* obj, Vec3f& v, const char* name)
1008
{
1009
return pyopencv_to(obj, v, ArgInfo(name, 0));
1010
}
1011
1012
static bool pyopencv_to(PyObject* obj, Vec3i& v, ArgInfo info)
1013
{
1014
CV_UNUSED(info);
1015
if (!obj)
1016
return true;
1017
return PyArg_ParseTuple(obj, "iii", &v[0], &v[1], &v[2]) > 0;
1018
}
1019
template<>
1020
bool pyopencv_to(PyObject* obj, Vec3i& v, const char* name)
1021
{
1022
return pyopencv_to(obj, v, ArgInfo(name, 0));
1023
}
1024
1025
static bool pyopencv_to(PyObject* obj, Vec2d& v, ArgInfo info)
1026
{
1027
CV_UNUSED(info);
1028
if (!obj)
1029
return true;
1030
return PyArg_ParseTuple(obj, "dd", &v[0], &v[1]) > 0;
1031
}
1032
template<>
1033
bool pyopencv_to(PyObject* obj, Vec2d& v, const char* name)
1034
{
1035
return pyopencv_to(obj, v, ArgInfo(name, 0));
1036
}
1037
1038
static bool pyopencv_to(PyObject* obj, Vec2f& v, ArgInfo info)
1039
{
1040
CV_UNUSED(info);
1041
if (!obj)
1042
return true;
1043
return PyArg_ParseTuple(obj, "ff", &v[0], &v[1]) > 0;
1044
}
1045
template<>
1046
bool pyopencv_to(PyObject* obj, Vec2f& v, const char* name)
1047
{
1048
return pyopencv_to(obj, v, ArgInfo(name, 0));
1049
}
1050
1051
static bool pyopencv_to(PyObject* obj, Vec2i& v, ArgInfo info)
1052
{
1053
CV_UNUSED(info);
1054
if (!obj)
1055
return true;
1056
return PyArg_ParseTuple(obj, "ii", &v[0], &v[1]) > 0;
1057
}
1058
template<>
1059
bool pyopencv_to(PyObject* obj, Vec2i& v, const char* name)
1060
{
1061
return pyopencv_to(obj, v, ArgInfo(name, 0));
1062
}
1063
1064
template<>
1065
PyObject* pyopencv_from(const Vec4d& v)
1066
{
1067
return Py_BuildValue("(dddd)", v[0], v[1], v[2], v[3]);
1068
}
1069
1070
template<>
1071
PyObject* pyopencv_from(const Vec4f& v)
1072
{
1073
return Py_BuildValue("(ffff)", v[0], v[1], v[2], v[3]);
1074
}
1075
1076
template<>
1077
PyObject* pyopencv_from(const Vec4i& v)
1078
{
1079
return Py_BuildValue("(iiii)", v[0], v[1], v[2], v[3]);
1080
}
1081
1082
template<>
1083
PyObject* pyopencv_from(const Vec3d& v)
1084
{
1085
return Py_BuildValue("(ddd)", v[0], v[1], v[2]);
1086
}
1087
1088
template<>
1089
PyObject* pyopencv_from(const Vec3f& v)
1090
{
1091
return Py_BuildValue("(fff)", v[0], v[1], v[2]);
1092
}
1093
1094
template<>
1095
PyObject* pyopencv_from(const Vec3i& v)
1096
{
1097
return Py_BuildValue("(iii)", v[0], v[1], v[2]);
1098
}
1099
1100
template<>
1101
PyObject* pyopencv_from(const Vec2d& v)
1102
{
1103
return Py_BuildValue("(dd)", v[0], v[1]);
1104
}
1105
1106
template<>
1107
PyObject* pyopencv_from(const Vec2f& v)
1108
{
1109
return Py_BuildValue("(ff)", v[0], v[1]);
1110
}
1111
1112
template<>
1113
PyObject* pyopencv_from(const Vec2i& v)
1114
{
1115
return Py_BuildValue("(ii)", v[0], v[1]);
1116
}
1117
1118
template<>
1119
PyObject* pyopencv_from(const Point2d& p)
1120
{
1121
return Py_BuildValue("(dd)", p.x, p.y);
1122
}
1123
1124
template<>
1125
PyObject* pyopencv_from(const Point3d& p)
1126
{
1127
return Py_BuildValue("(ddd)", p.x, p.y, p.z);
1128
}
1129
1130
template<typename _Tp> struct pyopencvVecConverter
1131
{
1132
static bool to(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
1133
{
1134
typedef typename DataType<_Tp>::channel_type _Cp;
1135
if(!obj || obj == Py_None)
1136
return true;
1137
if (PyArray_Check(obj))
1138
{
1139
Mat m;
1140
pyopencv_to(obj, m, info);
1141
m.copyTo(value);
1142
}
1143
if (!PySequence_Check(obj))
1144
return false;
1145
PyObject *seq = PySequence_Fast(obj, info.name);
1146
if (seq == NULL)
1147
return false;
1148
int i, j, n = (int)PySequence_Fast_GET_SIZE(seq);
1149
value.resize(n);
1150
1151
int type = traits::Type<_Tp>::value;
1152
int depth = CV_MAT_DEPTH(type), channels = CV_MAT_CN(type);
1153
PyObject** items = PySequence_Fast_ITEMS(seq);
1154
1155
for( i = 0; i < n; i++ )
1156
{
1157
PyObject* item = items[i];
1158
PyObject* seq_i = 0;
1159
PyObject** items_i = &item;
1160
_Cp* data = (_Cp*)&value[i];
1161
1162
if( channels == 2 && PyComplex_CheckExact(item) )
1163
{
1164
Py_complex c = PyComplex_AsCComplex(obj);
1165
data[0] = saturate_cast<_Cp>(c.real);
1166
data[1] = saturate_cast<_Cp>(c.imag);
1167
continue;
1168
}
1169
if( channels > 1 )
1170
{
1171
if( PyArray_Check(item))
1172
{
1173
Mat src;
1174
pyopencv_to(item, src, info);
1175
if( src.dims != 2 || src.channels() != 1 ||
1176
((src.cols != 1 || src.rows != channels) &&
1177
(src.cols != channels || src.rows != 1)))
1178
break;
1179
Mat dst(src.rows, src.cols, depth, data);
1180
src.convertTo(dst, type);
1181
if( dst.data != (uchar*)data )
1182
break;
1183
continue;
1184
}
1185
1186
seq_i = PySequence_Fast(item, info.name);
1187
if( !seq_i || (int)PySequence_Fast_GET_SIZE(seq_i) != channels )
1188
{
1189
Py_XDECREF(seq_i);
1190
break;
1191
}
1192
items_i = PySequence_Fast_ITEMS(seq_i);
1193
}
1194
1195
for( j = 0; j < channels; j++ )
1196
{
1197
PyObject* item_ij = items_i[j];
1198
if( PyInt_Check(item_ij))
1199
{
1200
int v = (int)PyInt_AsLong(item_ij);
1201
if( v == -1 && PyErr_Occurred() )
1202
break;
1203
data[j] = saturate_cast<_Cp>(v);
1204
}
1205
else if( PyLong_Check(item_ij))
1206
{
1207
int v = (int)PyLong_AsLong(item_ij);
1208
if( v == -1 && PyErr_Occurred() )
1209
break;
1210
data[j] = saturate_cast<_Cp>(v);
1211
}
1212
else if( PyFloat_Check(item_ij))
1213
{
1214
double v = PyFloat_AsDouble(item_ij);
1215
if( PyErr_Occurred() )
1216
break;
1217
data[j] = saturate_cast<_Cp>(v);
1218
}
1219
else
1220
break;
1221
}
1222
Py_XDECREF(seq_i);
1223
if( j < channels )
1224
break;
1225
}
1226
Py_DECREF(seq);
1227
return i == n;
1228
}
1229
1230
static PyObject* from(const std::vector<_Tp>& value)
1231
{
1232
if(value.empty())
1233
return PyTuple_New(0);
1234
int type = traits::Type<_Tp>::value;
1235
int depth = CV_MAT_DEPTH(type), channels = CV_MAT_CN(type);
1236
Mat src((int)value.size(), channels, depth, (uchar*)&value[0]);
1237
return pyopencv_from(src);
1238
}
1239
};
1240
1241
template<typename _Tp>
1242
bool pyopencv_to(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
1243
{
1244
return pyopencvVecConverter<_Tp>::to(obj, value, info);
1245
}
1246
1247
template<typename _Tp>
1248
PyObject* pyopencv_from(const std::vector<_Tp>& value)
1249
{
1250
return pyopencvVecConverter<_Tp>::from(value);
1251
}
1252
1253
template<typename _Tp> static inline bool pyopencv_to_generic_vec(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
1254
{
1255
if(!obj || obj == Py_None)
1256
return true;
1257
if (!PySequence_Check(obj))
1258
return false;
1259
PyObject *seq = PySequence_Fast(obj, info.name);
1260
if (seq == NULL)
1261
return false;
1262
int i, n = (int)PySequence_Fast_GET_SIZE(seq);
1263
value.resize(n);
1264
1265
PyObject** items = PySequence_Fast_ITEMS(seq);
1266
1267
for( i = 0; i < n; i++ )
1268
{
1269
PyObject* item = items[i];
1270
if(!pyopencv_to(item, value[i], info))
1271
break;
1272
}
1273
Py_DECREF(seq);
1274
return i == n;
1275
}
1276
1277
template<typename _Tp> static inline PyObject* pyopencv_from_generic_vec(const std::vector<_Tp>& value)
1278
{
1279
int i, n = (int)value.size();
1280
PyObject* seq = PyList_New(n);
1281
for( i = 0; i < n; i++ )
1282
{
1283
PyObject* item = pyopencv_from(value[i]);
1284
if(!item)
1285
break;
1286
PyList_SET_ITEM(seq, i, item);
1287
}
1288
if( i < n )
1289
{
1290
Py_DECREF(seq);
1291
return 0;
1292
}
1293
return seq;
1294
}
1295
1296
template<>
1297
PyObject* pyopencv_from(const std::pair<int, double>& src)
1298
{
1299
return Py_BuildValue("(id)", src.first, src.second);
1300
}
1301
1302
template<typename _Tp, typename _Tr> struct pyopencvVecConverter<std::pair<_Tp, _Tr> >
1303
{
1304
static bool to(PyObject* obj, std::vector<std::pair<_Tp, _Tr> >& value, const ArgInfo info)
1305
{
1306
return pyopencv_to_generic_vec(obj, value, info);
1307
}
1308
1309
static PyObject* from(const std::vector<std::pair<_Tp, _Tr> >& value)
1310
{
1311
return pyopencv_from_generic_vec(value);
1312
}
1313
};
1314
1315
template<typename _Tp> struct pyopencvVecConverter<std::vector<_Tp> >
1316
{
1317
static bool to(PyObject* obj, std::vector<std::vector<_Tp> >& value, const ArgInfo info)
1318
{
1319
return pyopencv_to_generic_vec(obj, value, info);
1320
}
1321
1322
static PyObject* from(const std::vector<std::vector<_Tp> >& value)
1323
{
1324
return pyopencv_from_generic_vec(value);
1325
}
1326
};
1327
1328
template<> struct pyopencvVecConverter<Mat>
1329
{
1330
static bool to(PyObject* obj, std::vector<Mat>& value, const ArgInfo info)
1331
{
1332
return pyopencv_to_generic_vec(obj, value, info);
1333
}
1334
1335
static PyObject* from(const std::vector<Mat>& value)
1336
{
1337
return pyopencv_from_generic_vec(value);
1338
}
1339
};
1340
1341
template<> struct pyopencvVecConverter<KeyPoint>
1342
{
1343
static bool to(PyObject* obj, std::vector<KeyPoint>& value, const ArgInfo info)
1344
{
1345
return pyopencv_to_generic_vec(obj, value, info);
1346
}
1347
1348
static PyObject* from(const std::vector<KeyPoint>& value)
1349
{
1350
return pyopencv_from_generic_vec(value);
1351
}
1352
};
1353
1354
template<> struct pyopencvVecConverter<DMatch>
1355
{
1356
static bool to(PyObject* obj, std::vector<DMatch>& value, const ArgInfo info)
1357
{
1358
return pyopencv_to_generic_vec(obj, value, info);
1359
}
1360
1361
static PyObject* from(const std::vector<DMatch>& value)
1362
{
1363
return pyopencv_from_generic_vec(value);
1364
}
1365
};
1366
1367
template<> struct pyopencvVecConverter<String>
1368
{
1369
static bool to(PyObject* obj, std::vector<String>& value, const ArgInfo info)
1370
{
1371
return pyopencv_to_generic_vec(obj, value, info);
1372
}
1373
1374
static PyObject* from(const std::vector<String>& value)
1375
{
1376
return pyopencv_from_generic_vec(value);
1377
}
1378
};
1379
1380
template<> struct pyopencvVecConverter<RotatedRect>
1381
{
1382
static bool to(PyObject* obj, std::vector<RotatedRect>& value, const ArgInfo info)
1383
{
1384
return pyopencv_to_generic_vec(obj, value, info);
1385
}
1386
static PyObject* from(const std::vector<RotatedRect>& value)
1387
{
1388
return pyopencv_from_generic_vec(value);
1389
}
1390
};
1391
1392
template<>
1393
bool pyopencv_to(PyObject *obj, TermCriteria& dst, const char *name)
1394
{
1395
CV_UNUSED(name);
1396
if(!obj)
1397
return true;
1398
return PyArg_ParseTuple(obj, "iid", &dst.type, &dst.maxCount, &dst.epsilon) > 0;
1399
}
1400
1401
template<>
1402
PyObject* pyopencv_from(const TermCriteria& src)
1403
{
1404
return Py_BuildValue("(iid)", src.type, src.maxCount, src.epsilon);
1405
}
1406
1407
template<>
1408
bool pyopencv_to(PyObject *obj, RotatedRect& dst, const char *name)
1409
{
1410
CV_UNUSED(name);
1411
if(!obj)
1412
return true;
1413
return PyArg_ParseTuple(obj, "(ff)(ff)f", &dst.center.x, &dst.center.y, &dst.size.width, &dst.size.height, &dst.angle) > 0;
1414
}
1415
1416
template<>
1417
PyObject* pyopencv_from(const RotatedRect& src)
1418
{
1419
return Py_BuildValue("((ff)(ff)f)", src.center.x, src.center.y, src.size.width, src.size.height, src.angle);
1420
}
1421
1422
template<>
1423
PyObject* pyopencv_from(const Moments& m)
1424
{
1425
return Py_BuildValue("{s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d}",
1426
"m00", m.m00, "m10", m.m10, "m01", m.m01,
1427
"m20", m.m20, "m11", m.m11, "m02", m.m02,
1428
"m30", m.m30, "m21", m.m21, "m12", m.m12, "m03", m.m03,
1429
"mu20", m.mu20, "mu11", m.mu11, "mu02", m.mu02,
1430
"mu30", m.mu30, "mu21", m.mu21, "mu12", m.mu12, "mu03", m.mu03,
1431
"nu20", m.nu20, "nu11", m.nu11, "nu02", m.nu02,
1432
"nu30", m.nu30, "nu21", m.nu21, "nu12", m.nu12, "nu03", m.nu03);
1433
}
1434
1435
static int OnError(int status, const char *func_name, const char *err_msg, const char *file_name, int line, void *userdata)
1436
{
1437
PyGILState_STATE gstate;
1438
gstate = PyGILState_Ensure();
1439
1440
PyObject *on_error = (PyObject*)userdata;
1441
PyObject *args = Py_BuildValue("isssi", status, func_name, err_msg, file_name, line);
1442
1443
PyObject *r = PyObject_Call(on_error, args, NULL);
1444
if (r == NULL) {
1445
PyErr_Print();
1446
} else {
1447
Py_DECREF(r);
1448
}
1449
1450
Py_DECREF(args);
1451
PyGILState_Release(gstate);
1452
1453
return 0; // The return value isn't used
1454
}
1455
1456
static PyObject *pycvRedirectError(PyObject*, PyObject *args, PyObject *kw)
1457
{
1458
const char *keywords[] = { "on_error", NULL };
1459
PyObject *on_error;
1460
1461
if (!PyArg_ParseTupleAndKeywords(args, kw, "O", (char**)keywords, &on_error))
1462
return NULL;
1463
1464
if ((on_error != Py_None) && !PyCallable_Check(on_error)) {
1465
PyErr_SetString(PyExc_TypeError, "on_error must be callable");
1466
return NULL;
1467
}
1468
1469
// Keep track of the previous handler parameter, so we can decref it when no longer used
1470
static PyObject* last_on_error = NULL;
1471
if (last_on_error) {
1472
Py_DECREF(last_on_error);
1473
last_on_error = NULL;
1474
}
1475
1476
if (on_error == Py_None) {
1477
ERRWRAP2(redirectError(NULL));
1478
} else {
1479
last_on_error = on_error;
1480
Py_INCREF(last_on_error);
1481
ERRWRAP2(redirectError(OnError, last_on_error));
1482
}
1483
Py_RETURN_NONE;
1484
}
1485
1486
static void OnMouse(int event, int x, int y, int flags, void* param)
1487
{
1488
PyGILState_STATE gstate;
1489
gstate = PyGILState_Ensure();
1490
1491
PyObject *o = (PyObject*)param;
1492
PyObject *args = Py_BuildValue("iiiiO", event, x, y, flags, PyTuple_GetItem(o, 1));
1493
1494
PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL);
1495
if (r == NULL)
1496
PyErr_Print();
1497
else
1498
Py_DECREF(r);
1499
Py_DECREF(args);
1500
PyGILState_Release(gstate);
1501
}
1502
1503
#ifdef HAVE_OPENCV_HIGHGUI
1504
static PyObject *pycvSetMouseCallback(PyObject*, PyObject *args, PyObject *kw)
1505
{
1506
const char *keywords[] = { "window_name", "on_mouse", "param", NULL };
1507
char* name;
1508
PyObject *on_mouse;
1509
PyObject *param = NULL;
1510
1511
if (!PyArg_ParseTupleAndKeywords(args, kw, "sO|O", (char**)keywords, &name, &on_mouse, &param))
1512
return NULL;
1513
if (!PyCallable_Check(on_mouse)) {
1514
PyErr_SetString(PyExc_TypeError, "on_mouse must be callable");
1515
return NULL;
1516
}
1517
if (param == NULL) {
1518
param = Py_None;
1519
}
1520
PyObject* py_callback_info = Py_BuildValue("OO", on_mouse, param);
1521
static std::map<std::string, PyObject*> registered_callbacks;
1522
std::map<std::string, PyObject*>::iterator i = registered_callbacks.find(name);
1523
if (i != registered_callbacks.end())
1524
{
1525
Py_DECREF(i->second);
1526
i->second = py_callback_info;
1527
}
1528
else
1529
{
1530
registered_callbacks.insert(std::pair<std::string, PyObject*>(std::string(name), py_callback_info));
1531
}
1532
ERRWRAP2(setMouseCallback(name, OnMouse, py_callback_info));
1533
Py_RETURN_NONE;
1534
}
1535
#endif
1536
1537
static void OnChange(int pos, void *param)
1538
{
1539
PyGILState_STATE gstate;
1540
gstate = PyGILState_Ensure();
1541
1542
PyObject *o = (PyObject*)param;
1543
PyObject *args = Py_BuildValue("(i)", pos);
1544
PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL);
1545
if (r == NULL)
1546
PyErr_Print();
1547
else
1548
Py_DECREF(r);
1549
Py_DECREF(args);
1550
PyGILState_Release(gstate);
1551
}
1552
1553
#ifdef HAVE_OPENCV_HIGHGUI
1554
static PyObject *pycvCreateTrackbar(PyObject*, PyObject *args)
1555
{
1556
PyObject *on_change;
1557
char* trackbar_name;
1558
char* window_name;
1559
int *value = new int;
1560
int count;
1561
1562
if (!PyArg_ParseTuple(args, "ssiiO", &trackbar_name, &window_name, value, &count, &on_change))
1563
return NULL;
1564
if (!PyCallable_Check(on_change)) {
1565
PyErr_SetString(PyExc_TypeError, "on_change must be callable");
1566
return NULL;
1567
}
1568
PyObject* py_callback_info = Py_BuildValue("OO", on_change, Py_None);
1569
std::string name = std::string(window_name) + ":" + std::string(trackbar_name);
1570
static std::map<std::string, PyObject*> registered_callbacks;
1571
std::map<std::string, PyObject*>::iterator i = registered_callbacks.find(name);
1572
if (i != registered_callbacks.end())
1573
{
1574
Py_DECREF(i->second);
1575
i->second = py_callback_info;
1576
}
1577
else
1578
{
1579
registered_callbacks.insert(std::pair<std::string, PyObject*>(name, py_callback_info));
1580
}
1581
ERRWRAP2(createTrackbar(trackbar_name, window_name, value, count, OnChange, py_callback_info));
1582
Py_RETURN_NONE;
1583
}
1584
1585
static void OnButtonChange(int state, void *param)
1586
{
1587
PyGILState_STATE gstate;
1588
gstate = PyGILState_Ensure();
1589
1590
PyObject *o = (PyObject*)param;
1591
PyObject *args;
1592
if(PyTuple_GetItem(o, 1) != NULL)
1593
{
1594
args = Py_BuildValue("(iO)", state, PyTuple_GetItem(o,1));
1595
}
1596
else
1597
{
1598
args = Py_BuildValue("(i)", state);
1599
}
1600
1601
PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL);
1602
if (r == NULL)
1603
PyErr_Print();
1604
else
1605
Py_DECREF(r);
1606
Py_DECREF(args);
1607
PyGILState_Release(gstate);
1608
}
1609
1610
static PyObject *pycvCreateButton(PyObject*, PyObject *args, PyObject *kw)
1611
{
1612
const char* keywords[] = {"buttonName", "onChange", "userData", "buttonType", "initialButtonState", NULL};
1613
PyObject *on_change;
1614
PyObject *userdata = NULL;
1615
char* button_name;
1616
int button_type = 0;
1617
int initial_button_state = 0;
1618
1619
if (!PyArg_ParseTupleAndKeywords(args, kw, "sO|Oii", (char**)keywords, &button_name, &on_change, &userdata, &button_type, &initial_button_state))
1620
return NULL;
1621
if (!PyCallable_Check(on_change)) {
1622
PyErr_SetString(PyExc_TypeError, "onChange must be callable");
1623
return NULL;
1624
}
1625
if (userdata == NULL) {
1626
userdata = Py_None;
1627
}
1628
1629
PyObject* py_callback_info = Py_BuildValue("OO", on_change, userdata);
1630
std::string name(button_name);
1631
1632
static std::map<std::string, PyObject*> registered_callbacks;
1633
std::map<std::string, PyObject*>::iterator i = registered_callbacks.find(name);
1634
if (i != registered_callbacks.end())
1635
{
1636
Py_DECREF(i->second);
1637
i->second = py_callback_info;
1638
}
1639
else
1640
{
1641
registered_callbacks.insert(std::pair<std::string, PyObject*>(name, py_callback_info));
1642
}
1643
ERRWRAP2(createButton(button_name, OnButtonChange, py_callback_info, button_type, initial_button_state != 0));
1644
Py_RETURN_NONE;
1645
}
1646
#endif
1647
1648
///////////////////////////////////////////////////////////////////////////////////////
1649
1650
static int convert_to_char(PyObject *o, char *dst, const char *name = "no_name")
1651
{
1652
if (PyString_Check(o) && PyString_Size(o) == 1) {
1653
*dst = PyString_AsString(o)[0];
1654
return 1;
1655
} else {
1656
(*dst) = 0;
1657
return failmsg("Expected single character string for argument '%s'", name);
1658
}
1659
}
1660
1661
#if PY_MAJOR_VERSION >= 3
1662
#define MKTYPE2(NAME) pyopencv_##NAME##_specials(); if (!to_ok(&pyopencv_##NAME##_Type)) return NULL;
1663
#else
1664
#define MKTYPE2(NAME) pyopencv_##NAME##_specials(); if (!to_ok(&pyopencv_##NAME##_Type)) return
1665
#endif
1666
1667
#ifdef __GNUC__
1668
# pragma GCC diagnostic ignored "-Wunused-parameter"
1669
# pragma GCC diagnostic ignored "-Wmissing-field-initializers"
1670
#endif
1671
1672
#include "pyopencv_generated_enums.h"
1673
#include "pyopencv_custom_headers.h"
1674
#include "pyopencv_generated_types.h"
1675
#include "pyopencv_generated_funcs.h"
1676
1677
static PyMethodDef special_methods[] = {
1678
{"redirectError", CV_PY_FN_WITH_KW(pycvRedirectError), "redirectError(onError) -> None"},
1679
#ifdef HAVE_OPENCV_HIGHGUI
1680
{"createTrackbar", (PyCFunction)pycvCreateTrackbar, METH_VARARGS, "createTrackbar(trackbarName, windowName, value, count, onChange) -> None"},
1681
{"createButton", CV_PY_FN_WITH_KW(pycvCreateButton), "createButton(buttonName, onChange [, userData, buttonType, initialButtonState]) -> None"},
1682
{"setMouseCallback", CV_PY_FN_WITH_KW(pycvSetMouseCallback), "setMouseCallback(windowName, onMouse [, param]) -> None"},
1683
#endif
1684
#ifdef HAVE_OPENCV_DNN
1685
{"dnn_registerLayer", CV_PY_FN_WITH_KW(pyopencv_cv_dnn_registerLayer), "registerLayer(type, class) -> None"},
1686
{"dnn_unregisterLayer", CV_PY_FN_WITH_KW(pyopencv_cv_dnn_unregisterLayer), "unregisterLayer(type) -> None"},
1687
#endif
1688
{NULL, NULL},
1689
};
1690
1691
/************************************************************************/
1692
/* Module init */
1693
1694
struct ConstDef
1695
{
1696
const char * name;
1697
long val;
1698
};
1699
1700
static void init_submodule(PyObject * root, const char * name, PyMethodDef * methods, ConstDef * consts)
1701
{
1702
// traverse and create nested submodules
1703
std::string s = name;
1704
size_t i = s.find('.');
1705
while (i < s.length() && i != std::string::npos)
1706
{
1707
size_t j = s.find('.', i);
1708
if (j == std::string::npos)
1709
j = s.length();
1710
std::string short_name = s.substr(i, j-i);
1711
std::string full_name = s.substr(0, j);
1712
i = j+1;
1713
1714
PyObject * d = PyModule_GetDict(root);
1715
PyObject * submod = PyDict_GetItemString(d, short_name.c_str());
1716
if (submod == NULL)
1717
{
1718
submod = PyImport_AddModule(full_name.c_str());
1719
PyDict_SetItemString(d, short_name.c_str(), submod);
1720
}
1721
1722
if (short_name != "")
1723
root = submod;
1724
}
1725
1726
// populate module's dict
1727
PyObject * d = PyModule_GetDict(root);
1728
for (PyMethodDef * m = methods; m->ml_name != NULL; ++m)
1729
{
1730
PyObject * method_obj = PyCFunction_NewEx(m, NULL, NULL);
1731
PyDict_SetItemString(d, m->ml_name, method_obj);
1732
Py_DECREF(method_obj);
1733
}
1734
for (ConstDef * c = consts; c->name != NULL; ++c)
1735
{
1736
PyDict_SetItemString(d, c->name, PyInt_FromLong(c->val));
1737
}
1738
1739
}
1740
1741
#include "pyopencv_generated_ns_reg.h"
1742
1743
static int to_ok(PyTypeObject *to)
1744
{
1745
to->tp_alloc = PyType_GenericAlloc;
1746
to->tp_new = PyType_GenericNew;
1747
to->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
1748
return (PyType_Ready(to) == 0);
1749
}
1750
1751
1752
#if PY_MAJOR_VERSION >= 3
1753
extern "C" CV_EXPORTS PyObject* PyInit_cv2();
1754
static struct PyModuleDef cv2_moduledef =
1755
{
1756
PyModuleDef_HEAD_INIT,
1757
MODULESTR,
1758
"Python wrapper for OpenCV.",
1759
-1, /* size of per-interpreter state of the module,
1760
or -1 if the module keeps state in global variables. */
1761
special_methods
1762
};
1763
1764
PyObject* PyInit_cv2()
1765
#else
1766
extern "C" CV_EXPORTS void initcv2();
1767
1768
void initcv2()
1769
#endif
1770
{
1771
import_array();
1772
1773
#include "pyopencv_generated_type_reg.h"
1774
1775
#if PY_MAJOR_VERSION >= 3
1776
PyObject* m = PyModule_Create(&cv2_moduledef);
1777
#else
1778
PyObject* m = Py_InitModule(MODULESTR, special_methods);
1779
#endif
1780
init_submodules(m); // from "pyopencv_generated_ns_reg.h"
1781
1782
PyObject* d = PyModule_GetDict(m);
1783
1784
PyDict_SetItemString(d, "__version__", PyString_FromString(CV_VERSION));
1785
1786
PyObject *opencv_error_dict = PyDict_New();
1787
PyDict_SetItemString(opencv_error_dict, "file", Py_None);
1788
PyDict_SetItemString(opencv_error_dict, "func", Py_None);
1789
PyDict_SetItemString(opencv_error_dict, "line", Py_None);
1790
PyDict_SetItemString(opencv_error_dict, "code", Py_None);
1791
PyDict_SetItemString(opencv_error_dict, "msg", Py_None);
1792
PyDict_SetItemString(opencv_error_dict, "err", Py_None);
1793
opencv_error = PyErr_NewException((char*)MODULESTR".error", NULL, opencv_error_dict);
1794
Py_DECREF(opencv_error_dict);
1795
PyDict_SetItemString(d, "error", opencv_error);
1796
1797
#if PY_MAJOR_VERSION >= 3
1798
#define PUBLISH_OBJECT(name, type) Py_INCREF(&type);\
1799
PyModule_AddObject(m, name, (PyObject *)&type);
1800
#else
1801
// Unrolled Py_INCREF(&type) without (PyObject*) cast
1802
// due to "warning: dereferencing type-punned pointer will break strict-aliasing rules"
1803
#define PUBLISH_OBJECT(name, type) _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA (&type)->ob_refcnt++;\
1804
PyModule_AddObject(m, name, (PyObject *)&type);
1805
#endif
1806
1807
#include "pyopencv_generated_type_publish.h"
1808
1809
#define PUBLISH(I) PyDict_SetItemString(d, #I, PyInt_FromLong(I))
1810
//#define PUBLISHU(I) PyDict_SetItemString(d, #I, PyLong_FromUnsignedLong(I))
1811
#define PUBLISH2(I, value) PyDict_SetItemString(d, #I, PyLong_FromLong(value))
1812
1813
PUBLISH(CV_8U);
1814
PUBLISH(CV_8UC1);
1815
PUBLISH(CV_8UC2);
1816
PUBLISH(CV_8UC3);
1817
PUBLISH(CV_8UC4);
1818
PUBLISH(CV_8S);
1819
PUBLISH(CV_8SC1);
1820
PUBLISH(CV_8SC2);
1821
PUBLISH(CV_8SC3);
1822
PUBLISH(CV_8SC4);
1823
PUBLISH(CV_16U);
1824
PUBLISH(CV_16UC1);
1825
PUBLISH(CV_16UC2);
1826
PUBLISH(CV_16UC3);
1827
PUBLISH(CV_16UC4);
1828
PUBLISH(CV_16S);
1829
PUBLISH(CV_16SC1);
1830
PUBLISH(CV_16SC2);
1831
PUBLISH(CV_16SC3);
1832
PUBLISH(CV_16SC4);
1833
PUBLISH(CV_32S);
1834
PUBLISH(CV_32SC1);
1835
PUBLISH(CV_32SC2);
1836
PUBLISH(CV_32SC3);
1837
PUBLISH(CV_32SC4);
1838
PUBLISH(CV_32F);
1839
PUBLISH(CV_32FC1);
1840
PUBLISH(CV_32FC2);
1841
PUBLISH(CV_32FC3);
1842
PUBLISH(CV_32FC4);
1843
PUBLISH(CV_64F);
1844
PUBLISH(CV_64FC1);
1845
PUBLISH(CV_64FC2);
1846
PUBLISH(CV_64FC3);
1847
PUBLISH(CV_64FC4);
1848
1849
#if PY_MAJOR_VERSION >= 3
1850
return m;
1851
#endif
1852
}
1853
1854