cv2.cpp 55.0 KB
Newer Older
1 2
#if defined(_MSC_VER) && (_MSC_VER >= 1800)
// eliminating duplicated round() declaration
3
#define HAVE_ROUND 1
4 5
#pragma warning(push)
#pragma warning(disable:5033)  // 'register' is no longer a supported storage class
6
#endif
A
Andrei Costinescu 已提交
7
#include <math.h>
8
#include <Python.h>
9 10 11
#if defined(_MSC_VER) && (_MSC_VER >= 1800)
#pragma warning(pop)
#endif
12

13 14 15 16 17 18 19
#define CV_PY_FN_WITH_KW_(fn, flags) (PyCFunction)(void*)(PyCFunctionWithKeywords)(fn), (flags) | METH_VARARGS | METH_KEYWORDS
#define CV_PY_FN_NOARGS_(fn, flags) (PyCFunction)(fn), (flags) | METH_NOARGS

#define CV_PY_FN_WITH_KW(fn) CV_PY_FN_WITH_KW_(fn, 0)
#define CV_PY_FN_NOARGS(fn) CV_PY_FN_NOARGS_(fn, 0)


20
#define MODULESTR "cv2"
21
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
A
Andrey Kamaev 已提交
22
#include <numpy/ndarrayobject.h>
23

24 25 26 27 28 29
#if PY_MAJOR_VERSION >= 3
#  define CV_PYTHON_TYPE_HEAD_INIT() PyVarObject_HEAD_INIT(&PyType_Type, 0)
#else
#  define CV_PYTHON_TYPE_HEAD_INIT() PyObject_HEAD_INIT(&PyType_Type) 0,
#endif

30
#include "pyopencv_generated_include.h"
31
#include "opencv2/core/types_c.h"
32

33 34
#include "opencv2/opencv_modules.hpp"

35 36
#include "pycompat.hpp"

37
#include <map>
38

39 40 41 42 43
static PyObject* opencv_error = 0;

static int failmsg(const char *fmt, ...)
{
    char str[1000];
44

45 46 47 48
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(str, sizeof(str), fmt, ap);
    va_end(ap);
49

50 51 52 53
    PyErr_SetString(PyExc_TypeError, str);
    return 0;
}

54 55 56 57 58 59
struct ArgInfo
{
    const char * name;
    bool outputarg;
    // more fields may be added if necessary

60
    ArgInfo(const char * name_, bool outputarg_)
61 62 63 64 65 66 67
        : name(name_)
        , outputarg(outputarg_) {}

    // to match with older pyopencv_to function signature
    operator const char *() const { return name; }
};

68 69 70 71
class PyAllowThreads
{
public:
    PyAllowThreads() : _state(PyEval_SaveThread()) {}
72
    ~PyAllowThreads()
73 74 75 76 77 78 79
    {
        PyEval_RestoreThread(_state);
    }
private:
    PyThreadState* _state;
};

A
Alexander Mordvintsev 已提交
80 81 82 83
class PyEnsureGIL
{
public:
    PyEnsureGIL() : _state(PyGILState_Ensure()) {}
84
    ~PyEnsureGIL()
A
Alexander Mordvintsev 已提交
85 86 87 88 89 90 91
    {
        PyGILState_Release(_state);
    }
private:
    PyGILState_STATE _state;
};

92 93 94
#define ERRWRAP2(expr) \
try \
{ \
95
    PyAllowThreads allowThreads; \
96 97 98 99 100 101 102 103
    expr; \
} \
catch (const cv::Exception &e) \
{ \
    PyErr_SetString(opencv_error, e.what()); \
    return 0; \
}

V
Vadim Pisarevsky 已提交
104 105
using namespace cv;

106
typedef std::vector<uchar> vector_uchar;
A
abidrahmank 已提交
107
typedef std::vector<char> vector_char;
108 109 110
typedef std::vector<int> vector_int;
typedef std::vector<float> vector_float;
typedef std::vector<double> vector_double;
111
typedef std::vector<size_t> vector_size_t;
112 113
typedef std::vector<Point> vector_Point;
typedef std::vector<Point2f> vector_Point2f;
W
Wangyida 已提交
114
typedef std::vector<Point3f> vector_Point3f;
115 116 117 118 119 120
typedef std::vector<Vec2f> vector_Vec2f;
typedef std::vector<Vec3f> vector_Vec3f;
typedef std::vector<Vec4f> vector_Vec4f;
typedef std::vector<Vec6f> vector_Vec6f;
typedef std::vector<Vec4i> vector_Vec4i;
typedef std::vector<Rect> vector_Rect;
B
berak 已提交
121
typedef std::vector<Rect2d> vector_Rect2d;
122 123
typedef std::vector<KeyPoint> vector_KeyPoint;
typedef std::vector<Mat> vector_Mat;
124
typedef std::vector<std::vector<Mat> > vector_vector_Mat;
125
typedef std::vector<UMat> vector_UMat;
126
typedef std::vector<DMatch> vector_DMatch;
127
typedef std::vector<String> vector_String;
128
typedef std::vector<Scalar> vector_Scalar;
A
abidrahmank 已提交
129 130

typedef std::vector<std::vector<char> > vector_vector_char;
131 132 133 134
typedef std::vector<std::vector<Point> > vector_vector_Point;
typedef std::vector<std::vector<Point2f> > vector_vector_Point2f;
typedef std::vector<std::vector<Point3f> > vector_vector_Point3f;
typedef std::vector<std::vector<DMatch> > vector_vector_DMatch;
135
typedef std::vector<std::vector<KeyPoint> > vector_vector_KeyPoint;
136

V
Vadim Pisarevsky 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149
static PyObject* failmsgp(const char *fmt, ...)
{
  char str[1000];

  va_list ap;
  va_start(ap, fmt);
  vsnprintf(str, sizeof(str), fmt, ap);
  va_end(ap);

  PyErr_SetString(PyExc_TypeError, str);
  return 0;
}

150 151 152
class NumpyAllocator : public MatAllocator
{
public:
153
    NumpyAllocator() { stdAllocator = Mat::getStdAllocator(); }
154
    ~NumpyAllocator() {}
155

156 157 158 159 160 161 162 163 164 165 166 167 168
    UMatData* allocate(PyObject* o, int dims, const int* sizes, int type, size_t* step) const
    {
        UMatData* u = new UMatData(this);
        u->data = u->origdata = (uchar*)PyArray_DATA((PyArrayObject*) o);
        npy_intp* _strides = PyArray_STRIDES((PyArrayObject*) o);
        for( int i = 0; i < dims - 1; i++ )
            step[i] = (size_t)_strides[i];
        step[dims-1] = CV_ELEM_SIZE(type);
        u->size = sizes[0]*step[0];
        u->userdata = o;
        return u;
    }

169
    UMatData* allocate(int dims0, const int* sizes, int type, void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const CV_OVERRIDE
170
    {
171 172
        if( data != 0 )
        {
173
            // issue #6969: CV_Error(Error::StsAssert, "The data should normally be NULL!");
174
            // probably this is safe to do in such extreme case
175
            return stdAllocator->allocate(dims0, sizes, type, data, step, flags, usageFlags);
176
        }
A
Alexander Mordvintsev 已提交
177 178
        PyEnsureGIL gil;

179 180 181 182
        int depth = CV_MAT_DEPTH(type);
        int cn = CV_MAT_CN(type);
        const int f = (int)(sizeof(size_t)/8);
        int typenum = depth == CV_8U ? NPY_UBYTE : depth == CV_8S ? NPY_BYTE :
183 184 185 186
        depth == CV_16U ? NPY_USHORT : depth == CV_16S ? NPY_SHORT :
        depth == CV_32S ? NPY_INT : depth == CV_32F ? NPY_FLOAT :
        depth == CV_64F ? NPY_DOUBLE : f*NPY_ULONGLONG + (f^1)*NPY_UINT;
        int i, dims = dims0;
A
Andrey Kamaev 已提交
187
        cv::AutoBuffer<npy_intp> _sizes(dims + 1);
188 189 190
        for( i = 0; i < dims; i++ )
            _sizes[i] = sizes[i];
        if( cn > 1 )
A
Andrey Kamaev 已提交
191
            _sizes[dims++] = cn;
192 193
        PyObject* o = PyArray_SimpleNew(dims, _sizes, typenum);
        if(!o)
A
Andrey Kamaev 已提交
194
            CV_Error_(Error::StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims));
195
        return allocate(o, dims0, sizes, type, step);
196
    }
197

198
    bool allocate(UMatData* u, int accessFlags, UMatUsageFlags usageFlags) const CV_OVERRIDE
199
    {
200
        return stdAllocator->allocate(u, accessFlags, usageFlags);
201 202
    }

203
    void deallocate(UMatData* u) const CV_OVERRIDE
204
    {
205 206 207 208 209 210
        if(!u)
            return;
        PyEnsureGIL gil;
        CV_Assert(u->urefcount >= 0);
        CV_Assert(u->refcount >= 0);
        if(u->refcount == 0)
211 212
        {
            PyObject* o = (PyObject*)u->userdata;
213
            Py_XDECREF(o);
214 215
            delete u;
        }
216
    }
217 218

    const MatAllocator* stdAllocator;
219 220 221
};

NumpyAllocator g_numpyAllocator;
222

223 224 225 226 227 228 229

template<typename T> static
bool pyopencv_to(PyObject* obj, T& p, const char* name = "<unknown>");

template<typename T> static
PyObject* pyopencv_from(const T& src);

230 231
enum { ARG_NONE = 0, ARG_MAT = 1, ARG_SCALAR = 2 };

L
luz.paz 已提交
232
// special case, when the converter needs full ArgInfo structure
233
static bool pyopencv_to(PyObject* o, Mat& m, const ArgInfo info)
234
{
235
    bool allowND = true;
V
Vadim Pisarevsky 已提交
236 237 238 239 240 241
    if(!o || o == Py_None)
    {
        if( !m.data )
            m.allocator = &g_numpyAllocator;
        return true;
    }
242

243 244
    if( PyInt_Check(o) )
    {
245
        double v[] = {static_cast<double>(PyInt_AsLong((PyObject*)o)), 0., 0., 0.};
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
        m = Mat(4, 1, CV_64F, v).clone();
        return true;
    }
    if( PyFloat_Check(o) )
    {
        double v[] = {PyFloat_AsDouble((PyObject*)o), 0., 0., 0.};
        m = Mat(4, 1, CV_64F, v).clone();
        return true;
    }
    if( PyTuple_Check(o) )
    {
        int i, sz = (int)PyTuple_Size((PyObject*)o);
        m = Mat(sz, 1, CV_64F);
        for( i = 0; i < sz; i++ )
        {
            PyObject* oi = PyTuple_GET_ITEM(o, i);
            if( PyInt_Check(oi) )
                m.at<double>(i) = (double)PyInt_AsLong(oi);
            else if( PyFloat_Check(oi) )
                m.at<double>(i) = (double)PyFloat_AsDouble(oi);
            else
            {
                failmsg("%s is not a numerical tuple", info.name);
                m.release();
                return false;
            }
        }
        return true;
    }

V
Vadim Pisarevsky 已提交
276 277
    if( !PyArray_Check(o) )
    {
278
        failmsg("%s is not a numpy array, neither a scalar", info.name);
V
Vadim Pisarevsky 已提交
279
        return false;
280
    }
281

282 283
    PyArrayObject* oarr = (PyArrayObject*) o;

284
    bool needcopy = false, needcast = false;
285
    int typenum = PyArray_TYPE(oarr), new_typenum = typenum;
286 287 288 289
    int type = typenum == NPY_UBYTE ? CV_8U :
               typenum == NPY_BYTE ? CV_8S :
               typenum == NPY_USHORT ? CV_16U :
               typenum == NPY_SHORT ? CV_16S :
290
               typenum == NPY_INT ? CV_32S :
291
               typenum == NPY_INT32 ? CV_32S :
292 293
               typenum == NPY_FLOAT ? CV_32F :
               typenum == NPY_DOUBLE ? CV_64F : -1;
294

295 296
    if( type < 0 )
    {
B
boatx 已提交
297
        if( typenum == NPY_INT64 || typenum == NPY_UINT64 || typenum == NPY_LONG )
298 299
        {
            needcopy = needcast = true;
300
            new_typenum = NPY_INT;
301 302 303 304 305 306 307
            type = CV_32S;
        }
        else
        {
            failmsg("%s data type = %d is not supported", info.name, typenum);
            return false;
        }
308
    }
309

A
Andrey Kamaev 已提交
310 311 312 313
#ifndef CV_MAX_DIM
    const int CV_MAX_DIM = 32;
#endif

314
    int ndims = PyArray_NDIM(oarr);
315 316
    if(ndims >= CV_MAX_DIM)
    {
317
        failmsg("%s dimensionality (=%d) is too high", info.name, ndims);
V
Vadim Pisarevsky 已提交
318
        return false;
319
    }
320

321
    int size[CV_MAX_DIM+1];
A
Andrey Kamaev 已提交
322 323
    size_t step[CV_MAX_DIM+1];
    size_t elemsize = CV_ELEM_SIZE1(type);
324 325
    const npy_intp* _sizes = PyArray_DIMS(oarr);
    const npy_intp* _strides = PyArray_STRIDES(oarr);
326 327
    bool ismultichannel = ndims == 3 && _sizes[2] <= CV_CN_MAX;

328 329 330 331 332 333
    for( int i = ndims-1; i >= 0 && !needcopy; i-- )
    {
        // these checks handle cases of
        //  a) multi-dimensional (ndims > 2) arrays, as well as simpler 1- and 2-dimensional cases
        //  b) transposed arrays, where _strides[] elements go in non-descending order
        //  c) flipped arrays, where some of _strides[] elements are negative
334 335 336
        // the _sizes[i] > 1 is needed to avoid spurious copies when NPY_RELAXED_STRIDES is set
        if( (i == ndims-1 && _sizes[i] > 1 && (size_t)_strides[i] != elemsize) ||
            (i < ndims-1 && _sizes[i] > 1 && _strides[i] < _strides[i+1]) )
337 338
            needcopy = true;
    }
339

340 341 342
    if( ismultichannel && _strides[1] != (npy_intp)elemsize*_sizes[2] )
        needcopy = true;

343 344 345 346
    if (needcopy)
    {
        if (info.outputarg)
        {
347
            failmsg("Layout of the output array %s is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)", info.name);
348 349
            return false;
        }
350 351 352 353 354 355 356 357 358 359 360

        if( needcast ) {
            o = PyArray_Cast(oarr, new_typenum);
            oarr = (PyArrayObject*) o;
        }
        else {
            oarr = PyArray_GETCONTIGUOUS(oarr);
            o = (PyObject*) oarr;
        }

        _strides = PyArray_STRIDES(oarr);
361
    }
362

363 364 365
    // Normalize strides in case NPY_RELAXED_STRIDES is set
    size_t default_step = elemsize;
    for ( int i = ndims - 1; i >= 0; --i )
366 367
    {
        size[i] = (int)_sizes[i];
368 369 370 371 372 373 374 375 376 377
        if ( size[i] > 1 )
        {
            step[i] = (size_t)_strides[i];
            default_step = step[i] * size[i];
        }
        else
        {
            step[i] = default_step;
            default_step *= size[i];
        }
378
    }
379

380 381
    // handle degenerate case
    if( ndims == 0) {
382 383 384 385
        size[ndims] = 1;
        step[ndims] = elemsize;
        ndims++;
    }
386

387
    if( ismultichannel )
V
Vadim Pisarevsky 已提交
388 389 390 391
    {
        ndims--;
        type |= CV_MAKETYPE(0, size[2]);
    }
392

V
Vadim Pisarevsky 已提交
393
    if( ndims > 2 && !allowND )
394
    {
395
        failmsg("%s has more than 2 dimensions", info.name);
V
Vadim Pisarevsky 已提交
396
        return false;
397
    }
398

399
    m = Mat(ndims, size, type, PyArray_DATA(oarr), step);
400
    m.u = g_numpyAllocator.allocate(o, ndims, size, type, step);
A
Alexander Alekhin 已提交
401
    m.addref();
402

403
    if( !needcopy )
404
    {
405 406
        Py_INCREF(o);
    }
407
    m.allocator = &g_numpyAllocator;
408

V
Vadim Pisarevsky 已提交
409
    return true;
410 411
}

412 413 414 415 416 417
template<>
bool pyopencv_to(PyObject* o, Mat& m, const char* name)
{
    return pyopencv_to(o, m, ArgInfo(name, 0));
}

V
Vitaly Tuzov 已提交
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
template<typename _Tp, int m, int n>
bool pyopencv_to(PyObject* o, Matx<_Tp, m, n>& mx, const ArgInfo info)
{
    Mat tmp;
    if (!pyopencv_to(o, tmp, info)) {
        return false;
    }

    tmp.copyTo(mx);
    return true;
}

template<typename _Tp, int m, int n>
bool pyopencv_to(PyObject* o, Matx<_Tp, m, n>& mx, const char* name)
{
    return pyopencv_to(o, mx, ArgInfo(name, 0));
}

436 437 438 439 440 441 442 443 444
template <typename T>
bool pyopencv_to(PyObject *o, Ptr<T>& p, const char *name)
{
    if (!o || o == Py_None)
        return true;
    p = makePtr<T>();
    return pyopencv_to(o, *p, name);
}

445 446
template<>
PyObject* pyopencv_from(const Mat& m)
447
{
448
    if( !m.data )
449
        Py_RETURN_NONE;
V
Vadim Pisarevsky 已提交
450
    Mat temp, *p = (Mat*)&m;
451
    if(!p->u || p->allocator != &g_numpyAllocator)
V
Vadim Pisarevsky 已提交
452
    {
V
Vadim Pisarevsky 已提交
453
        temp.allocator = &g_numpyAllocator;
454
        ERRWRAP2(m.copyTo(temp));
V
Vadim Pisarevsky 已提交
455 456
        p = &temp;
    }
457 458 459
    PyObject* o = (PyObject*)p->u->userdata;
    Py_INCREF(o);
    return o;
460 461
}

H
Hamdi Sahloul 已提交
462 463 464 465 466
template<typename _Tp, int m, int n>
PyObject* pyopencv_from(const Matx<_Tp, m, n>& matx)
{
    return pyopencv_from(Mat(matx));
}
467

468 469 470 471 472 473 474 475
template<typename T>
PyObject* pyopencv_from(const cv::Ptr<T>& p)
{
    if (!p)
        Py_RETURN_NONE;
    return pyopencv_from(*p);
}

476 477 478 479 480
typedef struct {
    PyObject_HEAD
    UMat* um;
} cv2_UMatWrapperObject;

481 482 483
static bool PyObject_IsUMat(PyObject *o);

// UMatWrapper init - try to map arguments from python to UMat constructors
484
static int UMatWrapper_init(PyObject* self_, PyObject *args, PyObject *kwds)
485
{
486 487 488 489 490 491
    cv2_UMatWrapperObject* self = (cv2_UMatWrapperObject*)self_;
    if (self == NULL)
    {
        PyErr_SetString(PyExc_TypeError, "Internal error");
        return -1;
    }
492 493 494 495 496 497 498 499 500
    self->um = NULL;
    {
        // constructor ()
        const char *kwlist[] = {NULL};
        if (PyArg_ParseTupleAndKeywords(args, kwds, "", (char**) kwlist)) {
            self->um = new UMat();
            return 0;
        }
        PyErr_Clear();
501
    }
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
    {
        // constructor (rows, cols, type)
        const char *kwlist[] = {"rows", "cols", "type", NULL};
        int rows, cols, type;
        if (PyArg_ParseTupleAndKeywords(args, kwds, "iii", (char**) kwlist, &rows, &cols, &type)) {
            self->um = new UMat(rows, cols, type);
            return 0;
        }
        PyErr_Clear();
    }
    {
        // constructor (m, rowRange, colRange)
        const char *kwlist[] = {"m", "rowRange", "colRange", NULL};
        PyObject *obj = NULL;
        int y0 = -1, y1 = -1, x0 = -1, x1 = -1;
        if (PyArg_ParseTupleAndKeywords(args, kwds, "O(ii)|(ii)", (char**) kwlist, &obj, &y0, &y1, &x0, &x1) && PyObject_IsUMat(obj)) {
            UMat *um_other = ((cv2_UMatWrapperObject *) obj)->um;
            Range rowRange(y0, y1);
            Range colRange = (x0 >= 0 && x1 >= 0) ? Range(x0, x1) : Range::all();
            self->um = new UMat(*um_other, rowRange, colRange);
            return 0;
        }
        PyErr_Clear();
    }
    {
        // constructor (m)
        const char *kwlist[] = {"m", NULL};
        PyObject *obj = NULL;
        if (PyArg_ParseTupleAndKeywords(args, kwds, "O", (char**) kwlist, &obj)) {
            // constructor (UMat m)
            if (PyObject_IsUMat(obj)) {
                UMat *um_other = ((cv2_UMatWrapperObject *) obj)->um;
                self->um = new UMat(*um_other);
                return 0;
            }
            // python specific constructor from array like object
            Mat m;
            if (pyopencv_to(obj, m, ArgInfo("UMatWrapper.np_mat", 0))) {
                self->um = new UMat();
                m.copyTo(*self->um);
                return 0;
            }
        }
        PyErr_Clear();
    }
    PyErr_SetString(PyExc_TypeError, "no matching UMat constructor found/supported");
    return -1;
549 550 551 552
}

static void UMatWrapper_dealloc(cv2_UMatWrapperObject* self)
{
553 554
    if (self->um)
        delete self->um;
555 556 557 558 559 560 561 562 563
#if PY_MAJOR_VERSION >= 3
    Py_TYPE(self)->tp_free((PyObject*)self);
#else
    self->ob_type->tp_free((PyObject*)self);
#endif
}

// UMatWrapper.get() - returns numpy array by transferring UMat data to Mat and than wrapping it to numpy array
// (using numpy allocator - and so without unnecessary copy)
564
static PyObject * UMatWrapper_get(PyObject* self_, PyObject * /*args*/)
565
{
566 567 568
    cv2_UMatWrapperObject* self = (cv2_UMatWrapperObject*)self_;
    if (self == NULL)
        return failmsgp("Incorrect type of self (must be 'cv2_UMatWrapperObject')");
569 570 571 572 573 574 575
    Mat m;
    m.allocator = &g_numpyAllocator;
    self->um->copyTo(m);

    return pyopencv_from(m);
}

576
// UMatWrapper.handle() - returns the OpenCL handle of the UMat object
577
static PyObject * UMatWrapper_handle(PyObject* self_, PyObject *args, PyObject *kwds)
578
{
579 580 581
    cv2_UMatWrapperObject* self = (cv2_UMatWrapperObject*)self_;
    if (self == NULL)
        return failmsgp("Incorrect type of self (must be 'cv2_UMatWrapperObject')");
582 583 584 585 586 587 588 589
    const char *kwlist[] = {"accessFlags", NULL};
    int accessFlags;
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "i", (char**) kwlist, &accessFlags))
        return 0;
    return PyLong_FromVoidPtr(self->um->handle(accessFlags));
}

// UMatWrapper.isContinuous() - returns true if the matrix data is continuous
590
static PyObject * UMatWrapper_isContinuous(PyObject* self_, PyObject * /*args*/)
591
{
592 593 594
    cv2_UMatWrapperObject* self = (cv2_UMatWrapperObject*)self_;
    if (self == NULL)
        return failmsgp("Incorrect type of self (must be 'cv2_UMatWrapperObject')");
595 596 597 598
    return PyBool_FromLong(self->um->isContinuous());
}

// UMatWrapper.isContinuous() - returns true if the matrix is a submatrix of another matrix
599
static PyObject * UMatWrapper_isSubmatrix(PyObject* self_, PyObject * /*args*/)
600
{
601 602 603
    cv2_UMatWrapperObject* self = (cv2_UMatWrapperObject*)self_;
    if (self == NULL)
        return failmsgp("Incorrect type of self (must be 'cv2_UMatWrapperObject')");
604 605 606 607
    return PyBool_FromLong(self->um->isSubmatrix());
}

// UMatWrapper.context() - returns the OpenCL context used by OpenCV UMat
608
static PyObject * UMatWrapper_context(PyObject* /*self_*/, PyObject * /*args*/)
609 610 611 612 613
{
    return PyLong_FromVoidPtr(cv::ocl::Context::getDefault().ptr());
}

// UMatWrapper.context() - returns the OpenCL queue used by OpenCV UMat
614
static PyObject * UMatWrapper_queue(PyObject* /*self_*/, PyObject * /*args*/)
615 616 617 618
{
    return PyLong_FromVoidPtr(cv::ocl::Queue::getDefault().ptr());
}

619
static PyObject * UMatWrapper_offset_getter(PyObject* self_, void*)
620
{
621 622 623
    cv2_UMatWrapperObject* self = (cv2_UMatWrapperObject*)self_;
    if (self == NULL)
        return failmsgp("Incorrect type of self (must be 'cv2_UMatWrapperObject')");
624 625 626
    return PyLong_FromSsize_t(self->um->offset);
}

627
static PyMethodDef UMatWrapper_methods[] = {
628
        {"get", CV_PY_FN_NOARGS(UMatWrapper_get),
629 630
                "Returns numpy array"
        },
631
        {"handle", CV_PY_FN_WITH_KW(UMatWrapper_handle),
632 633
                "Returns UMat native handle"
        },
634
        {"isContinuous", CV_PY_FN_NOARGS(UMatWrapper_isContinuous),
635 636
                "Returns true if the matrix data is continuous"
        },
637
        {"isSubmatrix", CV_PY_FN_NOARGS(UMatWrapper_isSubmatrix),
638 639
                "Returns true if the matrix is a submatrix of another matrix"
        },
640
        {"context", CV_PY_FN_NOARGS_(UMatWrapper_context, METH_STATIC),
641 642
                "Returns OpenCL context handle"
        },
643
        {"queue", CV_PY_FN_NOARGS_(UMatWrapper_queue, METH_STATIC),
644 645
                "Returns OpenCL queue handle"
        },
646 647 648
        {NULL, NULL, 0, NULL}  /* Sentinel */
};

649 650 651 652
static PyGetSetDef UMatWrapper_getset[] = {
        {(char*) "offset", (getter) UMatWrapper_offset_getter, NULL, NULL, NULL},
        {NULL, NULL, NULL, NULL, NULL}  /* Sentinel */
};
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688

static PyTypeObject cv2_UMatWrapperType = {
#if PY_MAJOR_VERSION >= 3
        PyVarObject_HEAD_INIT(NULL, 0)
#else
        PyObject_HEAD_INIT(NULL)
        0,                             /*ob_size*/
#endif
        "cv2.UMat",                    /* tp_name */
        sizeof(cv2_UMatWrapperObject), /* tp_basicsize */
        0,                             /* tp_itemsize */
      (destructor)UMatWrapper_dealloc, /* tp_dealloc */
        0,                             /* tp_print */
        0,                             /* tp_getattr */
        0,                             /* tp_setattr */
        0,                             /* tp_reserved */
        0,                             /* tp_repr */
        0,                             /* tp_as_number */
        0,                             /* tp_as_sequence */
        0,                             /* tp_as_mapping */
        0,                             /* tp_hash  */
        0,                             /* tp_call */
        0,                             /* tp_str */
        0,                             /* tp_getattro */
        0,                             /* tp_setattro */
        0,                             /* tp_as_buffer */
        Py_TPFLAGS_DEFAULT,            /* tp_flags */
        "OpenCV 3 UMat wrapper. Used for T-API support.", /* tp_doc */
        0,                             /* tp_traverse */
        0,                             /* tp_clear */
        0,                             /* tp_richcompare */
        0,                             /* tp_weaklistoffset */
        0,                             /* tp_iter */
        0,                             /* tp_iternext */
        UMatWrapper_methods,           /* tp_methods */
        0,                             /* tp_members */
689
        UMatWrapper_getset,            /* tp_getset */
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
        0,                             /* tp_base */
        0,                             /* tp_dict */
        0,                             /* tp_descr_get */
        0,                             /* tp_descr_set */
        0,                             /* tp_dictoffset */
        (initproc)UMatWrapper_init,    /* tp_init */
        0,                             /* tp_alloc */
        PyType_GenericNew,             /* tp_new */
        0,                             /* tp_free */
        0,                             /* tp_is_gc */
        0,                             /* tp_bases */
        0,                             /* tp_mro */
        0,                             /* tp_cache */
        0,                             /* tp_subclasses */
        0,                             /* tp_weaklist */
        0,                             /* tp_del */
        0,                             /* tp_version_tag */
#if PY_MAJOR_VERSION >= 3
        0,                             /* tp_finalize */
#endif
};

712 713 714 715
static bool PyObject_IsUMat(PyObject *o) {
    return (o != NULL) && PyObject_TypeCheck(o, &cv2_UMatWrapperType);
}

716
static bool pyopencv_to(PyObject* o, UMat& um, const ArgInfo info) {
717
    if (PyObject_IsUMat(o)) {
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
        um = *((cv2_UMatWrapperObject *) o)->um;
        return true;
    }

    Mat m;
    if (!pyopencv_to(o, m, info)) {
        return false;
    }

    m.copyTo(um);
    return true;
}

template<>
bool pyopencv_to(PyObject* o, UMat& um, const char* name)
{
    return pyopencv_to(o, um, ArgInfo(name, 0));
}

template<>
PyObject* pyopencv_from(const UMat& m) {
    PyObject *o = PyObject_CallObject((PyObject *) &cv2_UMatWrapperType, NULL);
    *((cv2_UMatWrapperObject *) o)->um = m;
    return o;
}

V
Vitaly Tuzov 已提交
744
static bool pyopencv_to(PyObject *o, Scalar& s, const ArgInfo info)
745
{
V
Vadim Pisarevsky 已提交
746 747
    if(!o || o == Py_None)
        return true;
748
    if (PySequence_Check(o)) {
V
Vitaly Tuzov 已提交
749
        PyObject *fi = PySequence_Fast(o, info.name);
750
        if (fi == NULL)
V
Vadim Pisarevsky 已提交
751
            return false;
752 753
        if (4 < PySequence_Fast_GET_SIZE(fi))
        {
V
Vitaly Tuzov 已提交
754
            failmsg("Scalar value for argument '%s' is longer than 4", info.name);
V
Vadim Pisarevsky 已提交
755
            return false;
756 757 758 759
        }
        for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
            PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
            if (PyFloat_Check(item) || PyInt_Check(item)) {
760
                s[(int)i] = PyFloat_AsDouble(item);
761
            } else {
V
Vitaly Tuzov 已提交
762
                failmsg("Scalar value for argument '%s' is not numeric", info.name);
V
Vadim Pisarevsky 已提交
763
                return false;
764 765 766 767 768 769 770
            }
        }
        Py_DECREF(fi);
    } else {
        if (PyFloat_Check(o) || PyInt_Check(o)) {
            s[0] = PyFloat_AsDouble(o);
        } else {
V
Vitaly Tuzov 已提交
771
            failmsg("Scalar value for argument '%s' is not numeric", info.name);
V
Vadim Pisarevsky 已提交
772
            return false;
773 774
        }
    }
V
Vadim Pisarevsky 已提交
775
    return true;
776 777
}

V
Vitaly Tuzov 已提交
778 779 780 781 782 783
template<>
bool pyopencv_to(PyObject *o, Scalar& s, const char *name)
{
    return pyopencv_to(o, s, ArgInfo(name, 0));
}

784 785
template<>
PyObject* pyopencv_from(const Scalar& src)
V
Vadim Pisarevsky 已提交
786 787 788
{
    return Py_BuildValue("(dddd)", src[0], src[1], src[2], src[3]);
}
789

790 791
template<>
PyObject* pyopencv_from(const bool& value)
792
{
V
Vadim Pisarevsky 已提交
793 794 795
    return PyBool_FromLong(value);
}

796 797
template<>
bool pyopencv_to(PyObject* obj, bool& value, const char* name)
V
Vadim Pisarevsky 已提交
798
{
A
Andrey Kamaev 已提交
799
    (void)name;
V
Vadim Pisarevsky 已提交
800 801 802 803 804 805 806 807 808
    if(!obj || obj == Py_None)
        return true;
    int _val = PyObject_IsTrue(obj);
    if(_val < 0)
        return false;
    value = _val > 0;
    return true;
}

809 810
template<>
PyObject* pyopencv_from(const size_t& value)
V
Vadim Pisarevsky 已提交
811
{
812
    return PyLong_FromSize_t(value);
V
Vadim Pisarevsky 已提交
813
}
814

815 816
template<>
bool pyopencv_to(PyObject* obj, size_t& value, const char* name)
817
{
A
Andrey Kamaev 已提交
818
    (void)name;
819 820 821
    if(!obj || obj == Py_None)
        return true;
    value = (int)PyLong_AsUnsignedLong(obj);
822
    return value != (size_t)-1 || !PyErr_Occurred();
823 824
}

825 826
template<>
PyObject* pyopencv_from(const int& value)
V
Vadim Pisarevsky 已提交
827 828
{
    return PyInt_FromLong(value);
829 830
}

831 832
template<>
bool pyopencv_to(PyObject* obj, int& value, const char* name)
833
{
A
Andrey Kamaev 已提交
834
    (void)name;
835 836
    if(!obj || obj == Py_None)
        return true;
837 838 839 840 841 842
    if(PyInt_Check(obj))
        value = (int)PyInt_AsLong(obj);
    else if(PyLong_Check(obj))
        value = (int)PyLong_AsLong(obj);
    else
        return false;
843 844 845
    return value != -1 || !PyErr_Occurred();
}

846 847
template<>
PyObject* pyopencv_from(const uchar& value)
848 849 850 851
{
    return PyInt_FromLong(value);
}

852 853
template<>
bool pyopencv_to(PyObject* obj, uchar& value, const char* name)
854
{
A
Andrey Kamaev 已提交
855
    (void)name;
V
Vadim Pisarevsky 已提交
856 857
    if(!obj || obj == Py_None)
        return true;
858 859 860
    int ivalue = (int)PyInt_AsLong(obj);
    value = cv::saturate_cast<uchar>(ivalue);
    return ivalue != -1 || !PyErr_Occurred();
V
Vadim Pisarevsky 已提交
861 862
}

863 864
template<>
PyObject* pyopencv_from(const double& value)
V
Vadim Pisarevsky 已提交
865 866 867 868
{
    return PyFloat_FromDouble(value);
}

869 870
template<>
bool pyopencv_to(PyObject* obj, double& value, const char* name)
V
Vadim Pisarevsky 已提交
871
{
A
Andrey Kamaev 已提交
872
    (void)name;
V
Vadim Pisarevsky 已提交
873 874
    if(!obj || obj == Py_None)
        return true;
875
    if(!!PyInt_CheckExact(obj))
V
Vadim Pisarevsky 已提交
876
        value = (double)PyInt_AS_LONG(obj);
877
    else
V
Vadim Pisarevsky 已提交
878 879
        value = PyFloat_AsDouble(obj);
    return !PyErr_Occurred();
880 881
}

882 883
template<>
PyObject* pyopencv_from(const float& value)
884
{
V
Vadim Pisarevsky 已提交
885
    return PyFloat_FromDouble(value);
886
}
V
Vadim Pisarevsky 已提交
887

888 889
template<>
bool pyopencv_to(PyObject* obj, float& value, const char* name)
890
{
A
Andrey Kamaev 已提交
891
    (void)name;
V
Vadim Pisarevsky 已提交
892 893
    if(!obj || obj == Py_None)
        return true;
894
    if(!!PyInt_CheckExact(obj))
V
Vadim Pisarevsky 已提交
895 896 897 898
        value = (float)PyInt_AS_LONG(obj);
    else
        value = (float)PyFloat_AsDouble(obj);
    return !PyErr_Occurred();
899 900
}

901 902
template<>
PyObject* pyopencv_from(const int64& value)
903
{
904
    return PyLong_FromLongLong(value);
905 906
}

907 908
template<>
PyObject* pyopencv_from(const String& value)
V
Vadim Pisarevsky 已提交
909 910 911
{
    return PyString_FromString(value.empty() ? "" : value.c_str());
}
912

913 914
template<>
bool pyopencv_to(PyObject* obj, String& value, const char* name)
915
{
A
Andrey Kamaev 已提交
916
    (void)name;
V
Vadim Pisarevsky 已提交
917 918 919 920 921
    if(!obj || obj == Py_None)
        return true;
    char* str = PyString_AsString(obj);
    if(!str)
        return false;
922
    value = String(str);
V
Vadim Pisarevsky 已提交
923 924 925
    return true;
}

926 927
template<>
bool pyopencv_to(PyObject* obj, Size& sz, const char* name)
V
Vadim Pisarevsky 已提交
928
{
A
Andrey Kamaev 已提交
929
    (void)name;
V
Vadim Pisarevsky 已提交
930 931
    if(!obj || obj == Py_None)
        return true;
A
Alexander Mordvintsev 已提交
932
    return PyArg_ParseTuple(obj, "ii", &sz.width, &sz.height) > 0;
V
Vadim Pisarevsky 已提交
933 934
}

935 936
template<>
PyObject* pyopencv_from(const Size& sz)
V
Vadim Pisarevsky 已提交
937 938 939 940
{
    return Py_BuildValue("(ii)", sz.width, sz.height);
}

941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
template<>
bool pyopencv_to(PyObject* obj, Size_<float>& sz, const char* name)
{
    (void)name;
    if(!obj || obj == Py_None)
        return true;
    return PyArg_ParseTuple(obj, "ff", &sz.width, &sz.height) > 0;
}

template<>
PyObject* pyopencv_from(const Size_<float>& sz)
{
    return Py_BuildValue("(ff)", sz.width, sz.height);
}

956 957
template<>
bool pyopencv_to(PyObject* obj, Rect& r, const char* name)
V
Vadim Pisarevsky 已提交
958
{
A
Andrey Kamaev 已提交
959
    (void)name;
V
Vadim Pisarevsky 已提交
960 961
    if(!obj || obj == Py_None)
        return true;
A
Alexander Mordvintsev 已提交
962
    return PyArg_ParseTuple(obj, "iiii", &r.x, &r.y, &r.width, &r.height) > 0;
V
Vadim Pisarevsky 已提交
963 964
}

965 966
template<>
PyObject* pyopencv_from(const Rect& r)
V
Vadim Pisarevsky 已提交
967 968 969 970
{
    return Py_BuildValue("(iiii)", r.x, r.y, r.width, r.height);
}

B
berak 已提交
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
template<>
bool pyopencv_to(PyObject* obj, Rect2d& r, const char* name)
{
    (void)name;
    if(!obj || obj == Py_None)
        return true;
    return PyArg_ParseTuple(obj, "dddd", &r.x, &r.y, &r.width, &r.height) > 0;
}

template<>
PyObject* pyopencv_from(const Rect2d& r)
{
    return Py_BuildValue("(dddd)", r.x, r.y, r.width, r.height);
}

986 987
template<>
bool pyopencv_to(PyObject* obj, Range& r, const char* name)
V
Vadim Pisarevsky 已提交
988
{
A
Andrey Kamaev 已提交
989
    (void)name;
V
Vadim Pisarevsky 已提交
990 991 992
    if(!obj || obj == Py_None)
        return true;
    if(PyObject_Size(obj) == 0)
993
    {
V
Vadim Pisarevsky 已提交
994 995
        r = Range::all();
        return true;
996
    }
A
Alexander Mordvintsev 已提交
997
    return PyArg_ParseTuple(obj, "ii", &r.start, &r.end) > 0;
V
Vadim Pisarevsky 已提交
998 999
}

1000 1001
template<>
PyObject* pyopencv_from(const Range& r)
V
Vadim Pisarevsky 已提交
1002 1003 1004 1005
{
    return Py_BuildValue("(ii)", r.start, r.end);
}

1006 1007
template<>
bool pyopencv_to(PyObject* obj, Point& p, const char* name)
V
Vadim Pisarevsky 已提交
1008
{
A
Andrey Kamaev 已提交
1009
    (void)name;
V
Vadim Pisarevsky 已提交
1010 1011
    if(!obj || obj == Py_None)
        return true;
1012
    if(!!PyComplex_CheckExact(obj))
V
Vadim Pisarevsky 已提交
1013 1014 1015 1016 1017 1018
    {
        Py_complex c = PyComplex_AsCComplex(obj);
        p.x = saturate_cast<int>(c.real);
        p.y = saturate_cast<int>(c.imag);
        return true;
    }
A
Alexander Mordvintsev 已提交
1019
    return PyArg_ParseTuple(obj, "ii", &p.x, &p.y) > 0;
V
Vadim Pisarevsky 已提交
1020 1021
}

1022 1023
template<>
bool pyopencv_to(PyObject* obj, Point2f& p, const char* name)
V
Vadim Pisarevsky 已提交
1024
{
A
Andrey Kamaev 已提交
1025
    (void)name;
V
Vadim Pisarevsky 已提交
1026 1027
    if(!obj || obj == Py_None)
        return true;
1028
    if(!!PyComplex_CheckExact(obj))
1029
    {
V
Vadim Pisarevsky 已提交
1030 1031 1032 1033 1034
        Py_complex c = PyComplex_AsCComplex(obj);
        p.x = saturate_cast<float>(c.real);
        p.y = saturate_cast<float>(c.imag);
        return true;
    }
A
Alexander Mordvintsev 已提交
1035
    return PyArg_ParseTuple(obj, "ff", &p.x, &p.y) > 0;
V
Vadim Pisarevsky 已提交
1036 1037
}

1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
template<>
bool pyopencv_to(PyObject* obj, Point2d& p, const char* name)
{
    (void)name;
    if(!obj || obj == Py_None)
        return true;
    if(!!PyComplex_CheckExact(obj))
    {
        Py_complex c = PyComplex_AsCComplex(obj);
        p.x = saturate_cast<double>(c.real);
        p.y = saturate_cast<double>(c.imag);
        return true;
    }
    return PyArg_ParseTuple(obj, "dd", &p.x, &p.y) > 0;
}

W
Wangyida 已提交
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
template<>
bool pyopencv_to(PyObject* obj, Point3f& p, const char* name)
{
    (void)name;
    if(!obj || obj == Py_None)
        return true;
    return PyArg_ParseTuple(obj, "fff", &p.x, &p.y, &p.z) > 0;
}

template<>
bool pyopencv_to(PyObject* obj, Point3d& p, const char* name)
{
    (void)name;
    if(!obj || obj == Py_None)
        return true;
    return PyArg_ParseTuple(obj, "ddd", &p.x, &p.y, &p.z) > 0;
}
1071

1072 1073
template<>
PyObject* pyopencv_from(const Point& p)
V
Vadim Pisarevsky 已提交
1074 1075 1076 1077
{
    return Py_BuildValue("(ii)", p.x, p.y);
}

1078 1079
template<>
PyObject* pyopencv_from(const Point2f& p)
V
Vadim Pisarevsky 已提交
1080 1081 1082 1083
{
    return Py_BuildValue("(dd)", p.x, p.y);
}

W
Wangyida 已提交
1084 1085 1086 1087 1088 1089
template<>
PyObject* pyopencv_from(const Point3f& p)
{
    return Py_BuildValue("(ddd)", p.x, p.y, p.z);
}

V
Vitaly Tuzov 已提交
1090 1091 1092 1093 1094 1095 1096
static bool pyopencv_to(PyObject* obj, Vec4d& v, ArgInfo info)
{
    (void)info;
    if (!obj)
        return true;
    return PyArg_ParseTuple(obj, "dddd", &v[0], &v[1], &v[2], &v[3]) > 0;
}
1097
template<>
V
Vitaly Tuzov 已提交
1098
bool pyopencv_to(PyObject* obj, Vec4d& v, const char* name)
V
Vadim Pisarevsky 已提交
1099
{
V
Vitaly Tuzov 已提交
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
    return pyopencv_to(obj, v, ArgInfo(name, 0));
}

static bool pyopencv_to(PyObject* obj, Vec4f& v, ArgInfo info)
{
    (void)info;
    if (!obj)
        return true;
    return PyArg_ParseTuple(obj, "ffff", &v[0], &v[1], &v[2], &v[3]) > 0;
}
template<>
bool pyopencv_to(PyObject* obj, Vec4f& v, const char* name)
{
    return pyopencv_to(obj, v, ArgInfo(name, 0));
}

static bool pyopencv_to(PyObject* obj, Vec4i& v, ArgInfo info)
{
    (void)info;
    if (!obj)
        return true;
    return PyArg_ParseTuple(obj, "iiii", &v[0], &v[1], &v[2], &v[3]) > 0;
}
template<>
bool pyopencv_to(PyObject* obj, Vec4i& v, const char* name)
{
    return pyopencv_to(obj, v, ArgInfo(name, 0));
}

static bool pyopencv_to(PyObject* obj, Vec3d& v, ArgInfo info)
{
    (void)info;
    if (!obj)
V
Vadim Pisarevsky 已提交
1133
        return true;
A
Alexander Mordvintsev 已提交
1134
    return PyArg_ParseTuple(obj, "ddd", &v[0], &v[1], &v[2]) > 0;
V
Vadim Pisarevsky 已提交
1135
}
V
Vitaly Tuzov 已提交
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
template<>
bool pyopencv_to(PyObject* obj, Vec3d& v, const char* name)
{
    return pyopencv_to(obj, v, ArgInfo(name, 0));
}

static bool pyopencv_to(PyObject* obj, Vec3f& v, ArgInfo info)
{
    (void)info;
    if (!obj)
        return true;
    return PyArg_ParseTuple(obj, "fff", &v[0], &v[1], &v[2]) > 0;
}
template<>
bool pyopencv_to(PyObject* obj, Vec3f& v, const char* name)
{
    return pyopencv_to(obj, v, ArgInfo(name, 0));
}

static bool pyopencv_to(PyObject* obj, Vec3i& v, ArgInfo info)
{
    (void)info;
    if (!obj)
        return true;
    return PyArg_ParseTuple(obj, "iii", &v[0], &v[1], &v[2]) > 0;
}
template<>
bool pyopencv_to(PyObject* obj, Vec3i& v, const char* name)
{
    return pyopencv_to(obj, v, ArgInfo(name, 0));
}

static bool pyopencv_to(PyObject* obj, Vec2d& v, ArgInfo info)
{
    (void)info;
    if (!obj)
        return true;
    return PyArg_ParseTuple(obj, "dd", &v[0], &v[1]) > 0;
}
template<>
bool pyopencv_to(PyObject* obj, Vec2d& v, const char* name)
{
    return pyopencv_to(obj, v, ArgInfo(name, 0));
}

static bool pyopencv_to(PyObject* obj, Vec2f& v, ArgInfo info)
{
    (void)info;
    if (!obj)
        return true;
    return PyArg_ParseTuple(obj, "ff", &v[0], &v[1]) > 0;
}
template<>
bool pyopencv_to(PyObject* obj, Vec2f& v, const char* name)
{
    return pyopencv_to(obj, v, ArgInfo(name, 0));
}

static bool pyopencv_to(PyObject* obj, Vec2i& v, ArgInfo info)
{
    (void)info;
    if (!obj)
        return true;
    return PyArg_ParseTuple(obj, "ii", &v[0], &v[1]) > 0;
}
template<>
bool pyopencv_to(PyObject* obj, Vec2i& v, const char* name)
{
    return pyopencv_to(obj, v, ArgInfo(name, 0));
}

template<>
PyObject* pyopencv_from(const Vec4d& v)
{
    return Py_BuildValue("(dddd)", v[0], v[1], v[2], v[3]);
}

template<>
PyObject* pyopencv_from(const Vec4f& v)
{
    return Py_BuildValue("(ffff)", v[0], v[1], v[2], v[3]);
}

template<>
PyObject* pyopencv_from(const Vec4i& v)
{
    return Py_BuildValue("(iiii)", v[0], v[1], v[2], v[3]);
}
V
Vadim Pisarevsky 已提交
1224

1225 1226
template<>
PyObject* pyopencv_from(const Vec3d& v)
V
Vadim Pisarevsky 已提交
1227 1228 1229 1230
{
    return Py_BuildValue("(ddd)", v[0], v[1], v[2]);
}

V
Vitaly Tuzov 已提交
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
template<>
PyObject* pyopencv_from(const Vec3f& v)
{
    return Py_BuildValue("(fff)", v[0], v[1], v[2]);
}

template<>
PyObject* pyopencv_from(const Vec3i& v)
{
    return Py_BuildValue("(iii)", v[0], v[1], v[2]);
}

1243 1244
template<>
PyObject* pyopencv_from(const Vec2d& v)
A
Andrey Kamaev 已提交
1245 1246 1247 1248
{
    return Py_BuildValue("(dd)", v[0], v[1]);
}

V
Vitaly Tuzov 已提交
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
template<>
PyObject* pyopencv_from(const Vec2f& v)
{
    return Py_BuildValue("(ff)", v[0], v[1]);
}

template<>
PyObject* pyopencv_from(const Vec2i& v)
{
    return Py_BuildValue("(ii)", v[0], v[1]);
}

1261 1262
template<>
PyObject* pyopencv_from(const Point2d& p)
V
Vadim Pisarevsky 已提交
1263 1264 1265 1266
{
    return Py_BuildValue("(dd)", p.x, p.y);
}

W
Wangyida 已提交
1267 1268 1269
template<>
PyObject* pyopencv_from(const Point3d& p)
{
1270
    return Py_BuildValue("(ddd)", p.x, p.y, p.z);
W
Wangyida 已提交
1271 1272
}

V
Vadim Pisarevsky 已提交
1273 1274
template<typename _Tp> struct pyopencvVecConverter
{
1275
    static bool to(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
1276 1277
    {
        typedef typename DataType<_Tp>::channel_type _Cp;
V
Vadim Pisarevsky 已提交
1278
        if(!obj || obj == Py_None)
V
Vadim Pisarevsky 已提交
1279 1280 1281 1282
            return true;
        if (PyArray_Check(obj))
        {
            Mat m;
1283
            pyopencv_to(obj, m, info);
V
Vadim Pisarevsky 已提交
1284 1285 1286 1287
            m.copyTo(value);
        }
        if (!PySequence_Check(obj))
            return false;
1288
        PyObject *seq = PySequence_Fast(obj, info.name);
V
Vadim Pisarevsky 已提交
1289 1290 1291 1292
        if (seq == NULL)
            return false;
        int i, j, n = (int)PySequence_Fast_GET_SIZE(seq);
        value.resize(n);
1293

A
Alexander Alekhin 已提交
1294
        int type = traits::Type<_Tp>::value;
V
Vadim Pisarevsky 已提交
1295 1296
        int depth = CV_MAT_DEPTH(type), channels = CV_MAT_CN(type);
        PyObject** items = PySequence_Fast_ITEMS(seq);
1297

V
Vadim Pisarevsky 已提交
1298 1299 1300 1301 1302 1303
        for( i = 0; i < n; i++ )
        {
            PyObject* item = items[i];
            PyObject* seq_i = 0;
            PyObject** items_i = &item;
            _Cp* data = (_Cp*)&value[i];
1304

V
Vadim Pisarevsky 已提交
1305 1306 1307 1308 1309 1310 1311 1312 1313
            if( channels == 2 && PyComplex_CheckExact(item) )
            {
                Py_complex c = PyComplex_AsCComplex(obj);
                data[0] = saturate_cast<_Cp>(c.real);
                data[1] = saturate_cast<_Cp>(c.imag);
                continue;
            }
            if( channels > 1 )
            {
V
Vadim Pisarevsky 已提交
1314
                if( PyArray_Check(item))
V
Vadim Pisarevsky 已提交
1315 1316
                {
                    Mat src;
1317
                    pyopencv_to(item, src, info);
V
Vadim Pisarevsky 已提交
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
                    if( src.dims != 2 || src.channels() != 1 ||
                       ((src.cols != 1 || src.rows != channels) &&
                        (src.cols != channels || src.rows != 1)))
                        break;
                    Mat dst(src.rows, src.cols, depth, data);
                    src.convertTo(dst, type);
                    if( dst.data != (uchar*)data )
                        break;
                    continue;
                }
1328

1329
                seq_i = PySequence_Fast(item, info.name);
V
Vadim Pisarevsky 已提交
1330 1331 1332 1333 1334 1335 1336
                if( !seq_i || (int)PySequence_Fast_GET_SIZE(seq_i) != channels )
                {
                    Py_XDECREF(seq_i);
                    break;
                }
                items_i = PySequence_Fast_ITEMS(seq_i);
            }
1337

V
Vadim Pisarevsky 已提交
1338 1339 1340 1341 1342
            for( j = 0; j < channels; j++ )
            {
                PyObject* item_ij = items_i[j];
                if( PyInt_Check(item_ij))
                {
1343 1344 1345 1346 1347 1348 1349 1350
                    int v = (int)PyInt_AsLong(item_ij);
                    if( v == -1 && PyErr_Occurred() )
                        break;
                    data[j] = saturate_cast<_Cp>(v);
                }
                else if( PyLong_Check(item_ij))
                {
                    int v = (int)PyLong_AsLong(item_ij);
V
Vadim Pisarevsky 已提交
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
                    if( v == -1 && PyErr_Occurred() )
                        break;
                    data[j] = saturate_cast<_Cp>(v);
                }
                else if( PyFloat_Check(item_ij))
                {
                    double v = PyFloat_AsDouble(item_ij);
                    if( PyErr_Occurred() )
                        break;
                    data[j] = saturate_cast<_Cp>(v);
                }
                else
                    break;
            }
            Py_XDECREF(seq_i);
            if( j < channels )
                break;
        }
        Py_DECREF(seq);
        return i == n;
1371
    }
1372

1373
    static PyObject* from(const std::vector<_Tp>& value)
V
Vadim Pisarevsky 已提交
1374 1375 1376
    {
        if(value.empty())
            return PyTuple_New(0);
A
Alexander Alekhin 已提交
1377 1378 1379
        int type = traits::Type<_Tp>::value;
        int depth = CV_MAT_DEPTH(type), channels = CV_MAT_CN(type);
        Mat src((int)value.size(), channels, depth, (uchar*)&value[0]);
V
Vadim Pisarevsky 已提交
1380 1381 1382 1383
        return pyopencv_from(src);
    }
};

A
abidrahmank 已提交
1384
template<typename _Tp>
1385
bool pyopencv_to(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
1386
{
1387
    return pyopencvVecConverter<_Tp>::to(obj, value, info);
V
Vadim Pisarevsky 已提交
1388 1389
}

1390 1391
template<typename _Tp>
PyObject* pyopencv_from(const std::vector<_Tp>& value)
V
Vadim Pisarevsky 已提交
1392 1393 1394 1395
{
    return pyopencvVecConverter<_Tp>::from(value);
}

1396
template<typename _Tp> static inline bool pyopencv_to_generic_vec(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
1397
{
V
Vadim Pisarevsky 已提交
1398 1399
    if(!obj || obj == Py_None)
       return true;
V
Vadim Pisarevsky 已提交
1400 1401
    if (!PySequence_Check(obj))
        return false;
1402
    PyObject *seq = PySequence_Fast(obj, info.name);
V
Vadim Pisarevsky 已提交
1403 1404 1405 1406
    if (seq == NULL)
        return false;
    int i, n = (int)PySequence_Fast_GET_SIZE(seq);
    value.resize(n);
1407

V
Vadim Pisarevsky 已提交
1408
    PyObject** items = PySequence_Fast_ITEMS(seq);
1409

V
Vadim Pisarevsky 已提交
1410 1411 1412
    for( i = 0; i < n; i++ )
    {
        PyObject* item = items[i];
1413
        if(!pyopencv_to(item, value[i], info))
V
Vadim Pisarevsky 已提交
1414 1415 1416 1417 1418 1419
            break;
    }
    Py_DECREF(seq);
    return i == n;
}

1420
template<typename _Tp> static inline PyObject* pyopencv_from_generic_vec(const std::vector<_Tp>& value)
V
Vadim Pisarevsky 已提交
1421 1422
{
    int i, n = (int)value.size();
V
Vadim Pisarevsky 已提交
1423
    PyObject* seq = PyList_New(n);
V
Vadim Pisarevsky 已提交
1424
    for( i = 0; i < n; i++ )
1425
    {
V
Vadim Pisarevsky 已提交
1426 1427 1428
        PyObject* item = pyopencv_from(value[i]);
        if(!item)
            break;
V
Vadim Pisarevsky 已提交
1429
        PyList_SET_ITEM(seq, i, item);
V
Vadim Pisarevsky 已提交
1430 1431
    }
    if( i < n )
1432
    {
V
Vadim Pisarevsky 已提交
1433
        Py_DECREF(seq);
1434 1435
        return 0;
    }
V
Vadim Pisarevsky 已提交
1436 1437 1438
    return seq;
}

1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
template<>
PyObject* pyopencv_from(const std::pair<int, double>& src)
{
    return Py_BuildValue("(id)", src.first, src.second);
}

template<typename _Tp, typename _Tr> struct pyopencvVecConverter<std::pair<_Tp, _Tr> >
{
    static bool to(PyObject* obj, std::vector<std::pair<_Tp, _Tr> >& value, const ArgInfo info)
    {
        return pyopencv_to_generic_vec(obj, value, info);
    }

    static PyObject* from(const std::vector<std::pair<_Tp, _Tr> >& value)
    {
        return pyopencv_from_generic_vec(value);
    }
};
V
Vadim Pisarevsky 已提交
1457

1458
template<typename _Tp> struct pyopencvVecConverter<std::vector<_Tp> >
V
Vadim Pisarevsky 已提交
1459
{
A
abidrahmank 已提交
1460
    static bool to(PyObject* obj, std::vector<std::vector<_Tp> >& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
1461
    {
A
abidrahmank 已提交
1462
        return pyopencv_to_generic_vec(obj, value, info);
V
Vadim Pisarevsky 已提交
1463
    }
1464

1465
    static PyObject* from(const std::vector<std::vector<_Tp> >& value)
V
Vadim Pisarevsky 已提交
1466 1467 1468 1469 1470 1471 1472
    {
        return pyopencv_from_generic_vec(value);
    }
};

template<> struct pyopencvVecConverter<Mat>
{
1473
    static bool to(PyObject* obj, std::vector<Mat>& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
1474
    {
1475
        return pyopencv_to_generic_vec(obj, value, info);
V
Vadim Pisarevsky 已提交
1476
    }
1477

1478
    static PyObject* from(const std::vector<Mat>& value)
V
Vadim Pisarevsky 已提交
1479 1480 1481 1482
    {
        return pyopencv_from_generic_vec(value);
    }
};
1483

V
Vadim Pisarevsky 已提交
1484
template<> struct pyopencvVecConverter<KeyPoint>
1485
{
1486
    static bool to(PyObject* obj, std::vector<KeyPoint>& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
1487
    {
1488
        return pyopencv_to_generic_vec(obj, value, info);
V
Vadim Pisarevsky 已提交
1489
    }
1490

1491
    static PyObject* from(const std::vector<KeyPoint>& value)
V
Vadim Pisarevsky 已提交
1492 1493 1494 1495 1496
    {
        return pyopencv_from_generic_vec(value);
    }
};

1497 1498
template<> struct pyopencvVecConverter<DMatch>
{
1499
    static bool to(PyObject* obj, std::vector<DMatch>& value, const ArgInfo info)
1500
    {
1501
        return pyopencv_to_generic_vec(obj, value, info);
1502
    }
1503

1504
    static PyObject* from(const std::vector<DMatch>& value)
1505 1506 1507 1508 1509
    {
        return pyopencv_from_generic_vec(value);
    }
};

1510
template<> struct pyopencvVecConverter<String>
V
Vadim Pisarevsky 已提交
1511
{
1512
    static bool to(PyObject* obj, std::vector<String>& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
1513
    {
1514
        return pyopencv_to_generic_vec(obj, value, info);
V
Vadim Pisarevsky 已提交
1515
    }
1516

1517
    static PyObject* from(const std::vector<String>& value)
V
Vadim Pisarevsky 已提交
1518 1519 1520 1521 1522
    {
        return pyopencv_from_generic_vec(value);
    }
};

1523 1524
template<>
bool pyopencv_to(PyObject *obj, TermCriteria& dst, const char *name)
1525
{
A
Andrey Kamaev 已提交
1526
    (void)name;
V
Vadim Pisarevsky 已提交
1527 1528 1529
    if(!obj)
        return true;
    return PyArg_ParseTuple(obj, "iid", &dst.type, &dst.maxCount, &dst.epsilon) > 0;
1530 1531
}

1532 1533
template<>
PyObject* pyopencv_from(const TermCriteria& src)
1534
{
V
Vadim Pisarevsky 已提交
1535
    return Py_BuildValue("(iid)", src.type, src.maxCount, src.epsilon);
1536 1537
}

1538 1539
template<>
bool pyopencv_to(PyObject *obj, RotatedRect& dst, const char *name)
1540
{
A
Andrey Kamaev 已提交
1541
    (void)name;
V
Vadim Pisarevsky 已提交
1542 1543 1544
    if(!obj)
        return true;
    return PyArg_ParseTuple(obj, "(ff)(ff)f", &dst.center.x, &dst.center.y, &dst.size.width, &dst.size.height, &dst.angle) > 0;
1545 1546
}

1547 1548
template<>
PyObject* pyopencv_from(const RotatedRect& src)
1549
{
V
Vadim Pisarevsky 已提交
1550
    return Py_BuildValue("((ff)(ff)f)", src.center.x, src.center.y, src.size.width, src.size.height, src.angle);
1551 1552
}

1553 1554
template<>
PyObject* pyopencv_from(const Moments& m)
1555
{
V
Vadim Pisarevsky 已提交
1556 1557 1558 1559 1560 1561 1562
    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}",
                         "m00", m.m00, "m10", m.m10, "m01", m.m01,
                         "m20", m.m20, "m11", m.m11, "m02", m.m02,
                         "m30", m.m30, "m21", m.m21, "m12", m.m12, "m03", m.m03,
                         "mu20", m.mu20, "mu11", m.mu11, "mu02", m.mu02,
                         "mu30", m.mu30, "mu21", m.mu21, "mu12", m.mu12, "mu03", m.mu03,
                         "nu20", m.nu20, "nu11", m.nu11, "nu02", m.nu02,
1563
                         "nu30", m.nu30, "nu21", m.nu21, "nu12", m.nu12, "nu03", m.nu03);
1564 1565
}

1566
#include "pyopencv_custom_headers.h"
1567

1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
static int OnError(int status, const char *func_name, const char *err_msg, const char *file_name, int line, void *userdata)
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();

    PyObject *on_error = (PyObject*)userdata;
    PyObject *args = Py_BuildValue("isssi", status, func_name, err_msg, file_name, line);

    PyObject *r = PyObject_Call(on_error, args, NULL);
    if (r == NULL) {
        PyErr_Print();
    } else {
        Py_DECREF(r);
    }

    Py_DECREF(args);
    PyGILState_Release(gstate);

    return 0; // The return value isn't used
}

static PyObject *pycvRedirectError(PyObject*, PyObject *args, PyObject *kw)
{
    const char *keywords[] = { "on_error", NULL };
    PyObject *on_error;

    if (!PyArg_ParseTupleAndKeywords(args, kw, "O", (char**)keywords, &on_error))
        return NULL;

    if ((on_error != Py_None) && !PyCallable_Check(on_error))  {
        PyErr_SetString(PyExc_TypeError, "on_error must be callable");
        return NULL;
    }

    // Keep track of the previous handler parameter, so we can decref it when no longer used
    static PyObject* last_on_error = NULL;
    if (last_on_error) {
        Py_DECREF(last_on_error);
        last_on_error = NULL;
    }

    if (on_error == Py_None) {
        ERRWRAP2(redirectError(NULL));
    } else {
        last_on_error = on_error;
        Py_INCREF(last_on_error);
        ERRWRAP2(redirectError(OnError, last_on_error));
    }
    Py_RETURN_NONE;
}

1619 1620 1621 1622
static void OnMouse(int event, int x, int y, int flags, void* param)
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();
1623

1624 1625
    PyObject *o = (PyObject*)param;
    PyObject *args = Py_BuildValue("iiiiO", event, x, y, flags, PyTuple_GetItem(o, 1));
1626

1627 1628 1629 1630 1631 1632 1633 1634 1635
    PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL);
    if (r == NULL)
        PyErr_Print();
    else
        Py_DECREF(r);
    Py_DECREF(args);
    PyGILState_Release(gstate);
}

1636
#ifdef HAVE_OPENCV_HIGHGUI
A
Andrey Kamaev 已提交
1637
static PyObject *pycvSetMouseCallback(PyObject*, PyObject *args, PyObject *kw)
1638 1639 1640 1641 1642
{
    const char *keywords[] = { "window_name", "on_mouse", "param", NULL };
    char* name;
    PyObject *on_mouse;
    PyObject *param = NULL;
1643

1644 1645 1646 1647 1648 1649 1650 1651 1652
    if (!PyArg_ParseTupleAndKeywords(args, kw, "sO|O", (char**)keywords, &name, &on_mouse, &param))
        return NULL;
    if (!PyCallable_Check(on_mouse)) {
        PyErr_SetString(PyExc_TypeError, "on_mouse must be callable");
        return NULL;
    }
    if (param == NULL) {
        param = Py_None;
    }
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
    PyObject* py_callback_info = Py_BuildValue("OO", on_mouse, param);
    static std::map<std::string, PyObject*> registered_callbacks;
    std::map<std::string, PyObject*>::iterator i = registered_callbacks.find(name);
    if (i != registered_callbacks.end())
    {
        Py_DECREF(i->second);
        i->second = py_callback_info;
    }
    else
    {
        registered_callbacks.insert(std::pair<std::string, PyObject*>(std::string(name), py_callback_info));
D
Dan Mašek 已提交
1664
    }
1665
    ERRWRAP2(setMouseCallback(name, OnMouse, py_callback_info));
1666 1667
    Py_RETURN_NONE;
}
1668
#endif
1669

1670
static void OnChange(int pos, void *param)
1671 1672 1673
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();
1674

1675 1676 1677 1678 1679
    PyObject *o = (PyObject*)param;
    PyObject *args = Py_BuildValue("(i)", pos);
    PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL);
    if (r == NULL)
        PyErr_Print();
1680 1681
    else
        Py_DECREF(r);
1682 1683 1684 1685
    Py_DECREF(args);
    PyGILState_Release(gstate);
}

1686
#ifdef HAVE_OPENCV_HIGHGUI
A
Andrey Kamaev 已提交
1687
static PyObject *pycvCreateTrackbar(PyObject*, PyObject *args)
1688 1689 1690 1691 1692 1693
{
    PyObject *on_change;
    char* trackbar_name;
    char* window_name;
    int *value = new int;
    int count;
1694

1695 1696 1697 1698 1699 1700
    if (!PyArg_ParseTuple(args, "ssiiO", &trackbar_name, &window_name, value, &count, &on_change))
        return NULL;
    if (!PyCallable_Check(on_change)) {
        PyErr_SetString(PyExc_TypeError, "on_change must be callable");
        return NULL;
    }
1701 1702 1703 1704 1705 1706 1707 1708
    PyObject* py_callback_info = Py_BuildValue("OO", on_change, Py_None);
    std::string name = std::string(window_name) + ":" + std::string(trackbar_name);
    static std::map<std::string, PyObject*> registered_callbacks;
    std::map<std::string, PyObject*>::iterator i = registered_callbacks.find(name);
    if (i != registered_callbacks.end())
    {
        Py_DECREF(i->second);
        i->second = py_callback_info;
D
Dan Mašek 已提交
1709
    }
1710 1711 1712 1713 1714
    else
    {
        registered_callbacks.insert(std::pair<std::string, PyObject*>(name, py_callback_info));
    }
    ERRWRAP2(createTrackbar(trackbar_name, window_name, value, count, OnChange, py_callback_info));
1715 1716 1717
    Py_RETURN_NONE;
}

1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
static void OnButtonChange(int state, void *param)
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();

    PyObject *o = (PyObject*)param;
    PyObject *args;
    if(PyTuple_GetItem(o, 1) != NULL)
    {
        args = Py_BuildValue("(iO)", state, PyTuple_GetItem(o,1));
    }
    else
    {
        args = Py_BuildValue("(i)", state);
    }

    PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL);
    if (r == NULL)
        PyErr_Print();
1737 1738
    else
        Py_DECREF(r);
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
    Py_DECREF(args);
    PyGILState_Release(gstate);
}

static PyObject *pycvCreateButton(PyObject*, PyObject *args, PyObject *kw)
{
    const char* keywords[] = {"buttonName", "onChange", "userData", "buttonType", "initialButtonState", NULL};
    PyObject *on_change;
    PyObject *userdata = NULL;
    char* button_name;
    int button_type = 0;
1750
    int initial_button_state = 0;
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761

    if (!PyArg_ParseTupleAndKeywords(args, kw, "sO|Oii", (char**)keywords, &button_name, &on_change, &userdata, &button_type, &initial_button_state))
        return NULL;
    if (!PyCallable_Check(on_change)) {
        PyErr_SetString(PyExc_TypeError, "onChange must be callable");
        return NULL;
    }
    if (userdata == NULL) {
        userdata = Py_None;
    }

1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
    PyObject* py_callback_info = Py_BuildValue("OO", on_change, userdata);
    std::string name(button_name);

    static std::map<std::string, PyObject*> registered_callbacks;
    std::map<std::string, PyObject*>::iterator i = registered_callbacks.find(name);
    if (i != registered_callbacks.end())
    {
        Py_DECREF(i->second);
        i->second = py_callback_info;
    }
    else
    {
        registered_callbacks.insert(std::pair<std::string, PyObject*>(name, py_callback_info));
D
Dan Mašek 已提交
1775
    }
1776
    ERRWRAP2(createButton(button_name, OnButtonChange, py_callback_info, button_type, initial_button_state != 0));
1777 1778 1779 1780
    Py_RETURN_NONE;
}
#endif

1781 1782
///////////////////////////////////////////////////////////////////////////////////////

1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793
static int convert_to_char(PyObject *o, char *dst, const char *name = "no_name")
{
  if (PyString_Check(o) && PyString_Size(o) == 1) {
    *dst = PyString_AsString(o)[0];
    return 1;
  } else {
    (*dst) = 0;
    return failmsg("Expected single character string for argument '%s'", name);
  }
}

1794 1795 1796
#if PY_MAJOR_VERSION >= 3
#define MKTYPE2(NAME) pyopencv_##NAME##_specials(); if (!to_ok(&pyopencv_##NAME##_Type)) return NULL;
#else
1797
#define MKTYPE2(NAME) pyopencv_##NAME##_specials(); if (!to_ok(&pyopencv_##NAME##_Type)) return
1798
#endif
1799

A
Andrey Kamaev 已提交
1800 1801 1802 1803 1804
#ifdef __GNUC__
#  pragma GCC diagnostic ignored "-Wunused-parameter"
#  pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#endif

1805 1806 1807
#include "pyopencv_generated_types.h"
#include "pyopencv_generated_funcs.h"

A
Alexander Mordvintsev 已提交
1808
static PyMethodDef special_methods[] = {
1809
  {"redirectError", CV_PY_FN_WITH_KW(pycvRedirectError), "redirectError(onError) -> None"},
1810
#ifdef HAVE_OPENCV_HIGHGUI
1811 1812 1813
  {"createTrackbar", (PyCFunction)pycvCreateTrackbar, METH_VARARGS, "createTrackbar(trackbarName, windowName, value, count, onChange) -> None"},
  {"createButton", CV_PY_FN_WITH_KW(pycvCreateButton), "createButton(buttonName, onChange [, userData, buttonType, initialButtonState]) -> None"},
  {"setMouseCallback", CV_PY_FN_WITH_KW(pycvSetMouseCallback), "setMouseCallback(windowName, onMouse [, param]) -> None"},
1814 1815
#endif
#ifdef HAVE_OPENCV_DNN
1816 1817
  {"dnn_registerLayer", CV_PY_FN_WITH_KW(pyopencv_cv_dnn_registerLayer), "registerLayer(type, class) -> None"},
  {"dnn_unregisterLayer", CV_PY_FN_WITH_KW(pyopencv_cv_dnn_unregisterLayer), "unregisterLayer(type) -> None"},
1818
#endif
1819 1820 1821 1822 1823 1824
  {NULL, NULL},
};

/************************************************************************/
/* Module init */

1825 1826 1827 1828 1829 1830 1831
struct ConstDef
{
    const char * name;
    long val;
};

static void init_submodule(PyObject * root, const char * name, PyMethodDef * methods, ConstDef * consts)
1832
{
1833
  // traverse and create nested submodules
1834
  std::string s = name;
1835 1836
  size_t i = s.find('.');
  while (i < s.length() && i != std::string::npos)
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
  {
    size_t j = s.find('.', i);
    if (j == std::string::npos)
        j = s.length();
    std::string short_name = s.substr(i, j-i);
    std::string full_name = s.substr(0, j);
    i = j+1;

    PyObject * d = PyModule_GetDict(root);
    PyObject * submod = PyDict_GetItemString(d, short_name.c_str());
    if (submod == NULL)
    {
        submod = PyImport_AddModule(full_name.c_str());
        PyDict_SetItemString(d, short_name.c_str(), submod);
    }
A
Adam Greig 已提交
1852 1853 1854

    if (short_name != "")
        root = submod;
1855 1856
  }

1857
  // populate module's dict
1858 1859 1860 1861 1862 1863 1864
  PyObject * d = PyModule_GetDict(root);
  for (PyMethodDef * m = methods; m->ml_name != NULL; ++m)
  {
    PyObject * method_obj = PyCFunction_NewEx(m, NULL, NULL);
    PyDict_SetItemString(d, m->ml_name, method_obj);
    Py_DECREF(method_obj);
  }
1865 1866 1867 1868 1869
  for (ConstDef * c = consts; c->name != NULL; ++c)
  {
    PyDict_SetItemString(d, c->name, PyInt_FromLong(c->val));
  }

1870 1871 1872 1873
}

#include "pyopencv_generated_ns_reg.h"

1874 1875 1876 1877 1878 1879 1880 1881
static int to_ok(PyTypeObject *to)
{
  to->tp_alloc = PyType_GenericAlloc;
  to->tp_new = PyType_GenericNew;
  to->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
  return (PyType_Ready(to) == 0);
}

1882 1883 1884 1885 1886 1887 1888 1889 1890 1891

#if PY_MAJOR_VERSION >= 3
extern "C" CV_EXPORTS PyObject* PyInit_cv2();
static struct PyModuleDef cv2_moduledef =
{
    PyModuleDef_HEAD_INIT,
    MODULESTR,
    "Python wrapper for OpenCV.",
    -1,     /* size of per-interpreter state of the module,
               or -1 if the module keeps state in global variables. */
A
Alexander Mordvintsev 已提交
1892
    special_methods
1893 1894 1895 1896
};

PyObject* PyInit_cv2()
#else
1897
extern "C" CV_EXPORTS void initcv2();
1898 1899

void initcv2()
1900
#endif
1901
{
A
Andrey Kamaev 已提交
1902
  import_array();
1903

1904 1905
#include "pyopencv_generated_type_reg.h"

1906 1907 1908
#if PY_MAJOR_VERSION >= 3
  PyObject* m = PyModule_Create(&cv2_moduledef);
#else
A
Alexander Mordvintsev 已提交
1909
  PyObject* m = Py_InitModule(MODULESTR, special_methods);
1910
#endif
1911 1912
  init_submodules(m); // from "pyopencv_generated_ns_reg.h"

1913 1914
  PyObject* d = PyModule_GetDict(m);

V
Vadim Pisarevsky 已提交
1915
  PyDict_SetItemString(d, "__version__", PyString_FromString(CV_VERSION));
1916 1917 1918

  opencv_error = PyErr_NewException((char*)MODULESTR".error", NULL, NULL);
  PyDict_SetItemString(d, "error", opencv_error);
1919

1920 1921 1922 1923 1924 1925 1926 1927
//Registering UMatWrapper python class in cv2 module:
  if (PyType_Ready(&cv2_UMatWrapperType) < 0)
#if PY_MAJOR_VERSION >= 3
    return NULL;
#else
    return;
#endif

1928

1929
#if PY_MAJOR_VERSION >= 3
1930 1931
#define PUBLISH_OBJECT(name, type) Py_INCREF(&type);\
  PyModule_AddObject(m, name, (PyObject *)&type);
1932
#else
1933 1934 1935 1936
// Unrolled Py_INCREF(&type) without (PyObject*) cast
// due to "warning: dereferencing type-punned pointer will break strict-aliasing rules"
#define PUBLISH_OBJECT(name, type) _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA (&type)->ob_refcnt++;\
  PyModule_AddObject(m, name, (PyObject *)&type);
1937
#endif
1938 1939 1940 1941

  PUBLISH_OBJECT("UMat", cv2_UMatWrapperType);

#include "pyopencv_generated_type_publish.h"
1942

1943
#define PUBLISH(I) PyDict_SetItemString(d, #I, PyInt_FromLong(I))
A
Andrey Kamaev 已提交
1944
//#define PUBLISHU(I) PyDict_SetItemString(d, #I, PyLong_FromUnsignedLong(I))
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
#define PUBLISH2(I, value) PyDict_SetItemString(d, #I, PyLong_FromLong(value))

  PUBLISH(CV_8U);
  PUBLISH(CV_8UC1);
  PUBLISH(CV_8UC2);
  PUBLISH(CV_8UC3);
  PUBLISH(CV_8UC4);
  PUBLISH(CV_8S);
  PUBLISH(CV_8SC1);
  PUBLISH(CV_8SC2);
  PUBLISH(CV_8SC3);
  PUBLISH(CV_8SC4);
  PUBLISH(CV_16U);
  PUBLISH(CV_16UC1);
  PUBLISH(CV_16UC2);
  PUBLISH(CV_16UC3);
  PUBLISH(CV_16UC4);
  PUBLISH(CV_16S);
  PUBLISH(CV_16SC1);
  PUBLISH(CV_16SC2);
  PUBLISH(CV_16SC3);
  PUBLISH(CV_16SC4);
  PUBLISH(CV_32S);
  PUBLISH(CV_32SC1);
  PUBLISH(CV_32SC2);
  PUBLISH(CV_32SC3);
  PUBLISH(CV_32SC4);
  PUBLISH(CV_32F);
  PUBLISH(CV_32FC1);
  PUBLISH(CV_32FC2);
  PUBLISH(CV_32FC3);
  PUBLISH(CV_32FC4);
  PUBLISH(CV_64F);
  PUBLISH(CV_64FC1);
  PUBLISH(CV_64FC2);
  PUBLISH(CV_64FC3);
  PUBLISH(CV_64FC4);
1982

1983 1984 1985
#if PY_MAJOR_VERSION >= 3
    return m;
#endif
A
Andrey Kamaev 已提交
1986
}