bv.cpp 51 KB

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