cv2.cpp 36.9 KB
Newer Older
1 2
#if defined(_MSC_VER) && (_MSC_VER >= 1800)
// eliminating duplicated round() declaration
3
#define HAVE_ROUND 1
4 5
#endif

6 7 8
#include <Python.h>

#define MODULESTR "cv2"
9
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
A
Andrey Kamaev 已提交
10
#include <numpy/ndarrayobject.h>
11

12
#include "pyopencv_generated_include.h"
13
#include "opencv2/core/types_c.h"
14

15 16
#include "opencv2/opencv_modules.hpp"

17 18
#include "pycompat.hpp"

19

20 21 22 23 24
static PyObject* opencv_error = 0;

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

26 27 28 29
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(str, sizeof(str), fmt, ap);
    va_end(ap);
30

31 32 33 34
    PyErr_SetString(PyExc_TypeError, str);
    return 0;
}

35 36 37 38 39 40
struct ArgInfo
{
    const char * name;
    bool outputarg;
    // more fields may be added if necessary

41
    ArgInfo(const char * name_, bool outputarg_)
42 43 44 45 46 47 48
        : name(name_)
        , outputarg(outputarg_) {}

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

49 50 51 52
class PyAllowThreads
{
public:
    PyAllowThreads() : _state(PyEval_SaveThread()) {}
53
    ~PyAllowThreads()
54 55 56 57 58 59 60
    {
        PyEval_RestoreThread(_state);
    }
private:
    PyThreadState* _state;
};

A
Alexander Mordvintsev 已提交
61 62 63 64
class PyEnsureGIL
{
public:
    PyEnsureGIL() : _state(PyGILState_Ensure()) {}
65
    ~PyEnsureGIL()
A
Alexander Mordvintsev 已提交
66 67 68 69 70 71 72
    {
        PyGILState_Release(_state);
    }
private:
    PyGILState_STATE _state;
};

73 74 75
#define ERRWRAP2(expr) \
try \
{ \
76
    PyAllowThreads allowThreads; \
77 78 79 80 81 82 83 84
    expr; \
} \
catch (const cv::Exception &e) \
{ \
    PyErr_SetString(opencv_error, e.what()); \
    return 0; \
}

V
Vadim Pisarevsky 已提交
85 86
using namespace cv;

87
typedef std::vector<uchar> vector_uchar;
A
abidrahmank 已提交
88
typedef std::vector<char> vector_char;
89 90 91 92 93
typedef std::vector<int> vector_int;
typedef std::vector<float> vector_float;
typedef std::vector<double> vector_double;
typedef std::vector<Point> vector_Point;
typedef std::vector<Point2f> vector_Point2f;
W
Wangyida 已提交
94
typedef std::vector<Point3f> vector_Point3f;
95 96 97 98 99 100
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 已提交
101
typedef std::vector<Rect2d> vector_Rect2d;
102 103 104
typedef std::vector<KeyPoint> vector_KeyPoint;
typedef std::vector<Mat> vector_Mat;
typedef std::vector<DMatch> vector_DMatch;
105
typedef std::vector<String> vector_String;
106
typedef std::vector<Scalar> vector_Scalar;
A
abidrahmank 已提交
107 108

typedef std::vector<std::vector<char> > vector_vector_char;
109 110 111 112
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;
113

114
#ifdef HAVE_OPENCV_FEATURES2D
115
typedef SimpleBlobDetector::Params SimpleBlobDetector_Params;
116
#endif
117

118
#ifdef HAVE_OPENCV_FLANN
119 120
typedef cvflann::flann_distance_t cvflann_flann_distance_t;
typedef cvflann::flann_algorithm_t cvflann_flann_algorithm_t;
121
#endif
122

123
#ifdef HAVE_OPENCV_STITCHING
124
typedef Stitcher::Status Status;
125
#endif
126

V
Vadim Pisarevsky 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139
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;
}

140 141 142
class NumpyAllocator : public MatAllocator
{
public:
143
    NumpyAllocator() { stdAllocator = Mat::getStdAllocator(); }
144
    ~NumpyAllocator() {}
145

146 147 148 149 150 151 152 153 154 155 156 157 158
    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;
    }

159
    UMatData* allocate(int dims0, const int* sizes, int type, void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const
160
    {
161 162 163 164
        if( data != 0 )
        {
            CV_Error(Error::StsAssert, "The data should normally be NULL!");
            // probably this is safe to do in such extreme case
165
            return stdAllocator->allocate(dims0, sizes, type, data, step, flags, usageFlags);
166
        }
A
Alexander Mordvintsev 已提交
167 168
        PyEnsureGIL gil;

169 170 171 172
        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 :
173 174 175 176
        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 已提交
177
        cv::AutoBuffer<npy_intp> _sizes(dims + 1);
178 179 180
        for( i = 0; i < dims; i++ )
            _sizes[i] = sizes[i];
        if( cn > 1 )
A
Andrey Kamaev 已提交
181
            _sizes[dims++] = cn;
182 183
        PyObject* o = PyArray_SimpleNew(dims, _sizes, typenum);
        if(!o)
A
Andrey Kamaev 已提交
184
            CV_Error_(Error::StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims));
185
        return allocate(o, dims0, sizes, type, step);
186
    }
187

188
    bool allocate(UMatData* u, int accessFlags, UMatUsageFlags usageFlags) const
189
    {
190
        return stdAllocator->allocate(u, accessFlags, usageFlags);
191 192 193 194
    }

    void deallocate(UMatData* u) const
    {
195 196 197 198 199 200
        if(!u)
            return;
        PyEnsureGIL gil;
        CV_Assert(u->urefcount >= 0);
        CV_Assert(u->refcount >= 0);
        if(u->refcount == 0)
201 202
        {
            PyObject* o = (PyObject*)u->userdata;
203
            Py_XDECREF(o);
204 205
            delete u;
        }
206
    }
207 208

    const MatAllocator* stdAllocator;
209 210 211
};

NumpyAllocator g_numpyAllocator;
212

213 214 215 216 217 218 219

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);

220 221
enum { ARG_NONE = 0, ARG_MAT = 1, ARG_SCALAR = 2 };

222
// special case, when the convertor needs full ArgInfo structure
223
static bool pyopencv_to(PyObject* o, Mat& m, const ArgInfo info)
224
{
225
    bool allowND = true;
V
Vadim Pisarevsky 已提交
226 227 228 229 230 231
    if(!o || o == Py_None)
    {
        if( !m.data )
            m.allocator = &g_numpyAllocator;
        return true;
    }
232

233 234
    if( PyInt_Check(o) )
    {
235
        double v[] = {static_cast<double>(PyInt_AsLong((PyObject*)o)), 0., 0., 0.};
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
        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 已提交
266 267
    if( !PyArray_Check(o) )
    {
268
        failmsg("%s is not a numpy array, neither a scalar", info.name);
V
Vadim Pisarevsky 已提交
269
        return false;
270
    }
271

272 273
    PyArrayObject* oarr = (PyArrayObject*) o;

274
    bool needcopy = false, needcast = false;
275
    int typenum = PyArray_TYPE(oarr), new_typenum = typenum;
276 277 278 279
    int type = typenum == NPY_UBYTE ? CV_8U :
               typenum == NPY_BYTE ? CV_8S :
               typenum == NPY_USHORT ? CV_16U :
               typenum == NPY_SHORT ? CV_16S :
280
               typenum == NPY_INT ? CV_32S :
281
               typenum == NPY_INT32 ? CV_32S :
282 283
               typenum == NPY_FLOAT ? CV_32F :
               typenum == NPY_DOUBLE ? CV_64F : -1;
284

285 286
    if( type < 0 )
    {
B
boatx 已提交
287
        if( typenum == NPY_INT64 || typenum == NPY_UINT64 || typenum == NPY_LONG )
288 289
        {
            needcopy = needcast = true;
290
            new_typenum = NPY_INT;
291 292 293 294 295 296 297
            type = CV_32S;
        }
        else
        {
            failmsg("%s data type = %d is not supported", info.name, typenum);
            return false;
        }
298
    }
299

A
Andrey Kamaev 已提交
300 301 302 303
#ifndef CV_MAX_DIM
    const int CV_MAX_DIM = 32;
#endif

304
    int ndims = PyArray_NDIM(oarr);
305 306
    if(ndims >= CV_MAX_DIM)
    {
307
        failmsg("%s dimensionality (=%d) is too high", info.name, ndims);
V
Vadim Pisarevsky 已提交
308
        return false;
309
    }
310

311
    int size[CV_MAX_DIM+1];
A
Andrey Kamaev 已提交
312 313
    size_t step[CV_MAX_DIM+1];
    size_t elemsize = CV_ELEM_SIZE1(type);
314 315
    const npy_intp* _sizes = PyArray_DIMS(oarr);
    const npy_intp* _strides = PyArray_STRIDES(oarr);
316 317
    bool ismultichannel = ndims == 3 && _sizes[2] <= CV_CN_MAX;

318 319 320 321 322 323
    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
324 325 326
        // 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]) )
327 328
            needcopy = true;
    }
329

330 331 332
    if( ismultichannel && _strides[1] != (npy_intp)elemsize*_sizes[2] )
        needcopy = true;

333 334 335 336
    if (needcopy)
    {
        if (info.outputarg)
        {
337
            failmsg("Layout of the output array %s is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)", info.name);
338 339
            return false;
        }
340 341 342 343 344 345 346 347 348 349 350

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

        _strides = PyArray_STRIDES(oarr);
351
    }
352

353 354 355
    // Normalize strides in case NPY_RELAXED_STRIDES is set
    size_t default_step = elemsize;
    for ( int i = ndims - 1; i >= 0; --i )
356 357
    {
        size[i] = (int)_sizes[i];
358 359 360 361 362 363 364 365 366 367
        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];
        }
368
    }
369

370 371
    // handle degenerate case
    if( ndims == 0) {
372 373 374 375
        size[ndims] = 1;
        step[ndims] = elemsize;
        ndims++;
    }
376

377
    if( ismultichannel )
V
Vadim Pisarevsky 已提交
378 379 380 381
    {
        ndims--;
        type |= CV_MAKETYPE(0, size[2]);
    }
382

V
Vadim Pisarevsky 已提交
383
    if( ndims > 2 && !allowND )
384
    {
385
        failmsg("%s has more than 2 dimensions", info.name);
V
Vadim Pisarevsky 已提交
386
        return false;
387
    }
388

389
    m = Mat(ndims, size, type, PyArray_DATA(oarr), step);
390
    m.u = g_numpyAllocator.allocate(o, ndims, size, type, step);
A
Alexander Alekhin 已提交
391
    m.addref();
392

393
    if( !needcopy )
394
    {
395 396
        Py_INCREF(o);
    }
397
    m.allocator = &g_numpyAllocator;
398

V
Vadim Pisarevsky 已提交
399
    return true;
400 401
}

402 403 404 405 406 407
template<>
bool pyopencv_to(PyObject* o, Mat& m, const char* name)
{
    return pyopencv_to(o, m, ArgInfo(name, 0));
}

408 409
template<>
PyObject* pyopencv_from(const Mat& m)
410
{
411
    if( !m.data )
412
        Py_RETURN_NONE;
V
Vadim Pisarevsky 已提交
413
    Mat temp, *p = (Mat*)&m;
414
    if(!p->u || p->allocator != &g_numpyAllocator)
V
Vadim Pisarevsky 已提交
415
    {
V
Vadim Pisarevsky 已提交
416
        temp.allocator = &g_numpyAllocator;
417
        ERRWRAP2(m.copyTo(temp));
V
Vadim Pisarevsky 已提交
418 419
        p = &temp;
    }
420 421 422
    PyObject* o = (PyObject*)p->u->userdata;
    Py_INCREF(o);
    return o;
423 424
}

425 426
template<>
bool pyopencv_to(PyObject *o, Scalar& s, const char *name)
427
{
V
Vadim Pisarevsky 已提交
428 429
    if(!o || o == Py_None)
        return true;
430 431 432
    if (PySequence_Check(o)) {
        PyObject *fi = PySequence_Fast(o, name);
        if (fi == NULL)
V
Vadim Pisarevsky 已提交
433
            return false;
434 435 436
        if (4 < PySequence_Fast_GET_SIZE(fi))
        {
            failmsg("Scalar value for argument '%s' is longer than 4", name);
V
Vadim Pisarevsky 已提交
437
            return false;
438 439 440 441
        }
        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)) {
442
                s[(int)i] = PyFloat_AsDouble(item);
443 444
            } else {
                failmsg("Scalar value for argument '%s' is not numeric", name);
V
Vadim Pisarevsky 已提交
445
                return false;
446 447 448 449 450 451 452 453
            }
        }
        Py_DECREF(fi);
    } else {
        if (PyFloat_Check(o) || PyInt_Check(o)) {
            s[0] = PyFloat_AsDouble(o);
        } else {
            failmsg("Scalar value for argument '%s' is not numeric", name);
V
Vadim Pisarevsky 已提交
454
            return false;
455 456
        }
    }
V
Vadim Pisarevsky 已提交
457
    return true;
458 459
}

460 461
template<>
PyObject* pyopencv_from(const Scalar& src)
V
Vadim Pisarevsky 已提交
462 463 464
{
    return Py_BuildValue("(dddd)", src[0], src[1], src[2], src[3]);
}
465

466 467
template<>
PyObject* pyopencv_from(const bool& value)
468
{
V
Vadim Pisarevsky 已提交
469 470 471
    return PyBool_FromLong(value);
}

472
#ifdef HAVE_OPENCV_STITCHING
473 474 475 476 477
template<>
PyObject* pyopencv_from(const Status& value)
{
    return PyInt_FromLong(value);
}
478
#endif
479

480 481
template<>
bool pyopencv_to(PyObject* obj, bool& value, const char* name)
V
Vadim Pisarevsky 已提交
482
{
A
Andrey Kamaev 已提交
483
    (void)name;
V
Vadim Pisarevsky 已提交
484 485 486 487 488 489 490 491 492
    if(!obj || obj == Py_None)
        return true;
    int _val = PyObject_IsTrue(obj);
    if(_val < 0)
        return false;
    value = _val > 0;
    return true;
}

493 494
template<>
PyObject* pyopencv_from(const size_t& value)
V
Vadim Pisarevsky 已提交
495
{
496
    return PyLong_FromSize_t(value);
V
Vadim Pisarevsky 已提交
497
}
498

499 500
template<>
bool pyopencv_to(PyObject* obj, size_t& value, const char* name)
501
{
A
Andrey Kamaev 已提交
502
    (void)name;
503 504 505
    if(!obj || obj == Py_None)
        return true;
    value = (int)PyLong_AsUnsignedLong(obj);
506
    return value != (size_t)-1 || !PyErr_Occurred();
507 508
}

509 510
template<>
PyObject* pyopencv_from(const int& value)
V
Vadim Pisarevsky 已提交
511 512
{
    return PyInt_FromLong(value);
513 514
}

515
#ifdef HAVE_OPENCV_FLANN
516 517
template<>
PyObject* pyopencv_from(const cvflann_flann_algorithm_t& value)
A
Andrey Kamaev 已提交
518 519 520 521
{
    return PyInt_FromLong(int(value));
}

522 523
template<>
PyObject* pyopencv_from(const cvflann_flann_distance_t& value)
A
Andrey Kamaev 已提交
524 525 526
{
    return PyInt_FromLong(int(value));
}
527
#endif
A
Andrey Kamaev 已提交
528

529 530
template<>
bool pyopencv_to(PyObject* obj, int& value, const char* name)
531
{
A
Andrey Kamaev 已提交
532
    (void)name;
533 534
    if(!obj || obj == Py_None)
        return true;
535 536 537 538 539 540
    if(PyInt_Check(obj))
        value = (int)PyInt_AsLong(obj);
    else if(PyLong_Check(obj))
        value = (int)PyLong_AsLong(obj);
    else
        return false;
541 542 543
    return value != -1 || !PyErr_Occurred();
}

544 545
template<>
PyObject* pyopencv_from(const uchar& value)
546 547 548 549
{
    return PyInt_FromLong(value);
}

550 551
template<>
bool pyopencv_to(PyObject* obj, uchar& value, const char* name)
552
{
A
Andrey Kamaev 已提交
553
    (void)name;
V
Vadim Pisarevsky 已提交
554 555
    if(!obj || obj == Py_None)
        return true;
556 557 558
    int ivalue = (int)PyInt_AsLong(obj);
    value = cv::saturate_cast<uchar>(ivalue);
    return ivalue != -1 || !PyErr_Occurred();
V
Vadim Pisarevsky 已提交
559 560
}

561 562
template<>
PyObject* pyopencv_from(const double& value)
V
Vadim Pisarevsky 已提交
563 564 565 566
{
    return PyFloat_FromDouble(value);
}

567 568
template<>
bool pyopencv_to(PyObject* obj, double& value, const char* name)
V
Vadim Pisarevsky 已提交
569
{
A
Andrey Kamaev 已提交
570
    (void)name;
V
Vadim Pisarevsky 已提交
571 572
    if(!obj || obj == Py_None)
        return true;
573
    if(!!PyInt_CheckExact(obj))
V
Vadim Pisarevsky 已提交
574
        value = (double)PyInt_AS_LONG(obj);
575
    else
V
Vadim Pisarevsky 已提交
576 577
        value = PyFloat_AsDouble(obj);
    return !PyErr_Occurred();
578 579
}

580 581
template<>
PyObject* pyopencv_from(const float& value)
582
{
V
Vadim Pisarevsky 已提交
583
    return PyFloat_FromDouble(value);
584
}
V
Vadim Pisarevsky 已提交
585

586 587
template<>
bool pyopencv_to(PyObject* obj, float& value, const char* name)
588
{
A
Andrey Kamaev 已提交
589
    (void)name;
V
Vadim Pisarevsky 已提交
590 591
    if(!obj || obj == Py_None)
        return true;
592
    if(!!PyInt_CheckExact(obj))
V
Vadim Pisarevsky 已提交
593 594 595 596
        value = (float)PyInt_AS_LONG(obj);
    else
        value = (float)PyFloat_AsDouble(obj);
    return !PyErr_Occurred();
597 598
}

599 600
template<>
PyObject* pyopencv_from(const int64& value)
601
{
602
    return PyLong_FromLongLong(value);
603 604
}

605 606
template<>
PyObject* pyopencv_from(const String& value)
V
Vadim Pisarevsky 已提交
607 608 609
{
    return PyString_FromString(value.empty() ? "" : value.c_str());
}
610

611 612
template<>
bool pyopencv_to(PyObject* obj, String& value, const char* name)
613
{
A
Andrey Kamaev 已提交
614
    (void)name;
V
Vadim Pisarevsky 已提交
615 616 617 618 619
    if(!obj || obj == Py_None)
        return true;
    char* str = PyString_AsString(obj);
    if(!str)
        return false;
620
    value = String(str);
V
Vadim Pisarevsky 已提交
621 622 623
    return true;
}

624 625
template<>
bool pyopencv_to(PyObject* obj, Size& sz, const char* name)
V
Vadim Pisarevsky 已提交
626
{
A
Andrey Kamaev 已提交
627
    (void)name;
V
Vadim Pisarevsky 已提交
628 629
    if(!obj || obj == Py_None)
        return true;
A
Alexander Mordvintsev 已提交
630
    return PyArg_ParseTuple(obj, "ii", &sz.width, &sz.height) > 0;
V
Vadim Pisarevsky 已提交
631 632
}

633 634
template<>
PyObject* pyopencv_from(const Size& sz)
V
Vadim Pisarevsky 已提交
635 636 637 638
{
    return Py_BuildValue("(ii)", sz.width, sz.height);
}

639 640
template<>
bool pyopencv_to(PyObject* obj, Rect& r, const char* name)
V
Vadim Pisarevsky 已提交
641
{
A
Andrey Kamaev 已提交
642
    (void)name;
V
Vadim Pisarevsky 已提交
643 644
    if(!obj || obj == Py_None)
        return true;
A
Alexander Mordvintsev 已提交
645
    return PyArg_ParseTuple(obj, "iiii", &r.x, &r.y, &r.width, &r.height) > 0;
V
Vadim Pisarevsky 已提交
646 647
}

648 649
template<>
PyObject* pyopencv_from(const Rect& r)
V
Vadim Pisarevsky 已提交
650 651 652 653
{
    return Py_BuildValue("(iiii)", r.x, r.y, r.width, r.height);
}

B
berak 已提交
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
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);
}

669 670
template<>
bool pyopencv_to(PyObject* obj, Range& r, const char* name)
V
Vadim Pisarevsky 已提交
671
{
A
Andrey Kamaev 已提交
672
    (void)name;
V
Vadim Pisarevsky 已提交
673 674 675
    if(!obj || obj == Py_None)
        return true;
    if(PyObject_Size(obj) == 0)
676
    {
V
Vadim Pisarevsky 已提交
677 678
        r = Range::all();
        return true;
679
    }
A
Alexander Mordvintsev 已提交
680
    return PyArg_ParseTuple(obj, "ii", &r.start, &r.end) > 0;
V
Vadim Pisarevsky 已提交
681 682
}

683 684
template<>
PyObject* pyopencv_from(const Range& r)
V
Vadim Pisarevsky 已提交
685 686 687 688
{
    return Py_BuildValue("(ii)", r.start, r.end);
}

689 690
template<>
bool pyopencv_to(PyObject* obj, Point& p, const char* name)
V
Vadim Pisarevsky 已提交
691
{
A
Andrey Kamaev 已提交
692
    (void)name;
V
Vadim Pisarevsky 已提交
693 694
    if(!obj || obj == Py_None)
        return true;
695
    if(!!PyComplex_CheckExact(obj))
V
Vadim Pisarevsky 已提交
696 697 698 699 700 701
    {
        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 已提交
702
    return PyArg_ParseTuple(obj, "ii", &p.x, &p.y) > 0;
V
Vadim Pisarevsky 已提交
703 704
}

705 706
template<>
bool pyopencv_to(PyObject* obj, Point2f& p, const char* name)
V
Vadim Pisarevsky 已提交
707
{
A
Andrey Kamaev 已提交
708
    (void)name;
V
Vadim Pisarevsky 已提交
709 710
    if(!obj || obj == Py_None)
        return true;
711
    if(!!PyComplex_CheckExact(obj))
712
    {
V
Vadim Pisarevsky 已提交
713 714 715 716 717
        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 已提交
718
    return PyArg_ParseTuple(obj, "ff", &p.x, &p.y) > 0;
V
Vadim Pisarevsky 已提交
719 720
}

721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
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 已提交
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
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;
}
754

755 756
template<>
PyObject* pyopencv_from(const Point& p)
V
Vadim Pisarevsky 已提交
757 758 759 760
{
    return Py_BuildValue("(ii)", p.x, p.y);
}

761 762
template<>
PyObject* pyopencv_from(const Point2f& p)
V
Vadim Pisarevsky 已提交
763 764 765 766
{
    return Py_BuildValue("(dd)", p.x, p.y);
}

W
Wangyida 已提交
767 768 769 770 771 772
template<>
PyObject* pyopencv_from(const Point3f& p)
{
    return Py_BuildValue("(ddd)", p.x, p.y, p.z);
}

773 774
template<>
bool pyopencv_to(PyObject* obj, Vec3d& v, const char* name)
V
Vadim Pisarevsky 已提交
775
{
A
Andrey Kamaev 已提交
776
    (void)name;
V
Vadim Pisarevsky 已提交
777 778
    if(!obj)
        return true;
A
Alexander Mordvintsev 已提交
779
    return PyArg_ParseTuple(obj, "ddd", &v[0], &v[1], &v[2]) > 0;
V
Vadim Pisarevsky 已提交
780 781
}

782 783
template<>
PyObject* pyopencv_from(const Vec3d& v)
V
Vadim Pisarevsky 已提交
784 785 786 787
{
    return Py_BuildValue("(ddd)", v[0], v[1], v[2]);
}

788 789
template<>
PyObject* pyopencv_from(const Vec2d& v)
A
Andrey Kamaev 已提交
790 791 792 793
{
    return Py_BuildValue("(dd)", v[0], v[1]);
}

794 795
template<>
PyObject* pyopencv_from(const Point2d& p)
V
Vadim Pisarevsky 已提交
796 797 798 799
{
    return Py_BuildValue("(dd)", p.x, p.y);
}

W
Wangyida 已提交
800 801 802 803 804 805
template<>
PyObject* pyopencv_from(const Point3d& p)
{
    return Py_BuildValue("(ddd)", p.x, p.y, p.y);
}

V
Vadim Pisarevsky 已提交
806 807
template<typename _Tp> struct pyopencvVecConverter
{
808
    static bool to(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
809 810
    {
        typedef typename DataType<_Tp>::channel_type _Cp;
V
Vadim Pisarevsky 已提交
811
        if(!obj || obj == Py_None)
V
Vadim Pisarevsky 已提交
812 813 814 815
            return true;
        if (PyArray_Check(obj))
        {
            Mat m;
816
            pyopencv_to(obj, m, info);
V
Vadim Pisarevsky 已提交
817 818 819 820
            m.copyTo(value);
        }
        if (!PySequence_Check(obj))
            return false;
821
        PyObject *seq = PySequence_Fast(obj, info.name);
V
Vadim Pisarevsky 已提交
822 823 824 825
        if (seq == NULL)
            return false;
        int i, j, n = (int)PySequence_Fast_GET_SIZE(seq);
        value.resize(n);
826

V
Vadim Pisarevsky 已提交
827 828 829
        int type = DataType<_Tp>::type;
        int depth = CV_MAT_DEPTH(type), channels = CV_MAT_CN(type);
        PyObject** items = PySequence_Fast_ITEMS(seq);
830

V
Vadim Pisarevsky 已提交
831 832 833 834 835 836
        for( i = 0; i < n; i++ )
        {
            PyObject* item = items[i];
            PyObject* seq_i = 0;
            PyObject** items_i = &item;
            _Cp* data = (_Cp*)&value[i];
837

V
Vadim Pisarevsky 已提交
838 839 840 841 842 843 844 845 846
            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 已提交
847
                if( PyArray_Check(item))
V
Vadim Pisarevsky 已提交
848 849
                {
                    Mat src;
850
                    pyopencv_to(item, src, info);
V
Vadim Pisarevsky 已提交
851 852 853 854 855 856 857 858 859 860
                    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;
                }
861

862
                seq_i = PySequence_Fast(item, info.name);
V
Vadim Pisarevsky 已提交
863 864 865 866 867 868 869
                if( !seq_i || (int)PySequence_Fast_GET_SIZE(seq_i) != channels )
                {
                    Py_XDECREF(seq_i);
                    break;
                }
                items_i = PySequence_Fast_ITEMS(seq_i);
            }
870

V
Vadim Pisarevsky 已提交
871 872 873 874 875
            for( j = 0; j < channels; j++ )
            {
                PyObject* item_ij = items_i[j];
                if( PyInt_Check(item_ij))
                {
876 877 878 879 880 881 882 883
                    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 已提交
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
                    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;
904
    }
905

906
    static PyObject* from(const std::vector<_Tp>& value)
V
Vadim Pisarevsky 已提交
907 908 909 910 911 912 913 914
    {
        if(value.empty())
            return PyTuple_New(0);
        Mat src((int)value.size(), DataType<_Tp>::channels, DataType<_Tp>::depth, (uchar*)&value[0]);
        return pyopencv_from(src);
    }
};

A
abidrahmank 已提交
915
template<typename _Tp>
916
bool pyopencv_to(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
917
{
918
    return pyopencvVecConverter<_Tp>::to(obj, value, info);
V
Vadim Pisarevsky 已提交
919 920
}

921 922
template<typename _Tp>
PyObject* pyopencv_from(const std::vector<_Tp>& value)
V
Vadim Pisarevsky 已提交
923 924 925 926
{
    return pyopencvVecConverter<_Tp>::from(value);
}

927
template<typename _Tp> static inline bool pyopencv_to_generic_vec(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
928
{
V
Vadim Pisarevsky 已提交
929 930
    if(!obj || obj == Py_None)
       return true;
V
Vadim Pisarevsky 已提交
931 932
    if (!PySequence_Check(obj))
        return false;
933
    PyObject *seq = PySequence_Fast(obj, info.name);
V
Vadim Pisarevsky 已提交
934 935 936 937
    if (seq == NULL)
        return false;
    int i, n = (int)PySequence_Fast_GET_SIZE(seq);
    value.resize(n);
938

V
Vadim Pisarevsky 已提交
939
    PyObject** items = PySequence_Fast_ITEMS(seq);
940

V
Vadim Pisarevsky 已提交
941 942 943
    for( i = 0; i < n; i++ )
    {
        PyObject* item = items[i];
944
        if(!pyopencv_to(item, value[i], info))
V
Vadim Pisarevsky 已提交
945 946 947 948 949 950
            break;
    }
    Py_DECREF(seq);
    return i == n;
}

951
template<typename _Tp> static inline PyObject* pyopencv_from_generic_vec(const std::vector<_Tp>& value)
V
Vadim Pisarevsky 已提交
952 953
{
    int i, n = (int)value.size();
V
Vadim Pisarevsky 已提交
954
    PyObject* seq = PyList_New(n);
V
Vadim Pisarevsky 已提交
955
    for( i = 0; i < n; i++ )
956
    {
V
Vadim Pisarevsky 已提交
957 958 959
        PyObject* item = pyopencv_from(value[i]);
        if(!item)
            break;
V
Vadim Pisarevsky 已提交
960
        PyList_SET_ITEM(seq, i, item);
V
Vadim Pisarevsky 已提交
961 962
    }
    if( i < n )
963
    {
V
Vadim Pisarevsky 已提交
964
        Py_DECREF(seq);
965 966
        return 0;
    }
V
Vadim Pisarevsky 已提交
967 968 969 970
    return seq;
}


971
template<typename _Tp> struct pyopencvVecConverter<std::vector<_Tp> >
V
Vadim Pisarevsky 已提交
972
{
A
abidrahmank 已提交
973
    static bool to(PyObject* obj, std::vector<std::vector<_Tp> >& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
974
    {
A
abidrahmank 已提交
975
        return pyopencv_to_generic_vec(obj, value, info);
V
Vadim Pisarevsky 已提交
976
    }
977

978
    static PyObject* from(const std::vector<std::vector<_Tp> >& value)
V
Vadim Pisarevsky 已提交
979 980 981 982 983 984 985
    {
        return pyopencv_from_generic_vec(value);
    }
};

template<> struct pyopencvVecConverter<Mat>
{
986
    static bool to(PyObject* obj, std::vector<Mat>& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
987
    {
988
        return pyopencv_to_generic_vec(obj, value, info);
V
Vadim Pisarevsky 已提交
989
    }
990

991
    static PyObject* from(const std::vector<Mat>& value)
V
Vadim Pisarevsky 已提交
992 993 994 995
    {
        return pyopencv_from_generic_vec(value);
    }
};
996

V
Vadim Pisarevsky 已提交
997
template<> struct pyopencvVecConverter<KeyPoint>
998
{
999
    static bool to(PyObject* obj, std::vector<KeyPoint>& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
1000
    {
1001
        return pyopencv_to_generic_vec(obj, value, info);
V
Vadim Pisarevsky 已提交
1002
    }
1003

1004
    static PyObject* from(const std::vector<KeyPoint>& value)
V
Vadim Pisarevsky 已提交
1005 1006 1007 1008 1009
    {
        return pyopencv_from_generic_vec(value);
    }
};

1010 1011
template<> struct pyopencvVecConverter<DMatch>
{
1012
    static bool to(PyObject* obj, std::vector<DMatch>& value, const ArgInfo info)
1013
    {
1014
        return pyopencv_to_generic_vec(obj, value, info);
1015
    }
1016

1017
    static PyObject* from(const std::vector<DMatch>& value)
1018 1019 1020 1021 1022
    {
        return pyopencv_from_generic_vec(value);
    }
};

1023
template<> struct pyopencvVecConverter<String>
V
Vadim Pisarevsky 已提交
1024
{
1025
    static bool to(PyObject* obj, std::vector<String>& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
1026
    {
1027
        return pyopencv_to_generic_vec(obj, value, info);
V
Vadim Pisarevsky 已提交
1028
    }
1029

1030
    static PyObject* from(const std::vector<String>& value)
V
Vadim Pisarevsky 已提交
1031 1032 1033 1034 1035
    {
        return pyopencv_from_generic_vec(value);
    }
};

1036 1037
template<>
bool pyopencv_to(PyObject *obj, TermCriteria& dst, const char *name)
1038
{
A
Andrey Kamaev 已提交
1039
    (void)name;
V
Vadim Pisarevsky 已提交
1040 1041 1042
    if(!obj)
        return true;
    return PyArg_ParseTuple(obj, "iid", &dst.type, &dst.maxCount, &dst.epsilon) > 0;
1043 1044
}

1045 1046
template<>
PyObject* pyopencv_from(const TermCriteria& src)
1047
{
V
Vadim Pisarevsky 已提交
1048
    return Py_BuildValue("(iid)", src.type, src.maxCount, src.epsilon);
1049 1050
}

1051 1052
template<>
bool pyopencv_to(PyObject *obj, RotatedRect& dst, const char *name)
1053
{
A
Andrey Kamaev 已提交
1054
    (void)name;
V
Vadim Pisarevsky 已提交
1055 1056 1057
    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;
1058 1059
}

1060 1061
template<>
PyObject* pyopencv_from(const RotatedRect& src)
1062
{
V
Vadim Pisarevsky 已提交
1063
    return Py_BuildValue("((ff)(ff)f)", src.center.x, src.center.y, src.size.width, src.size.height, src.angle);
1064 1065
}

1066 1067
template<>
PyObject* pyopencv_from(const Moments& m)
1068
{
V
Vadim Pisarevsky 已提交
1069 1070 1071 1072 1073 1074 1075
    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,
1076
                         "nu30", m.nu30, "nu21", m.nu21, "nu12", m.nu12, "nu03", m.nu03);
1077 1078
}

1079
#ifdef HAVE_OPENCV_FLANN
1080 1081
template<>
bool pyopencv_to(PyObject *o, cv::flann::IndexParams& p, const char *name)
1082
{
A
Andrey Kamaev 已提交
1083
    (void)name;
1084 1085 1086 1087 1088 1089 1090 1091 1092
    bool ok = true;
    PyObject* key = NULL;
    PyObject* item = NULL;
    Py_ssize_t pos = 0;

    if(PyDict_Check(o)) {
        while(PyDict_Next(o, &pos, &key, &item)) {
            if( !PyString_Check(key) ) {
                ok = false;
1093
                break;
1094 1095
            }

1096
            String k = PyString_AsString(key);
1097
            if( PyString_Check(item) )
1098 1099 1100 1101
            {
                const char* value = PyString_AsString(item);
                p.setString(k, value);
            }
1102
            else if( !!PyBool_Check(item) )
1103
                p.setBool(k, item == Py_True);
1104
            else if( PyInt_Check(item) )
1105 1106 1107 1108 1109 1110 1111
            {
                int value = (int)PyInt_AsLong(item);
                if( strcmp(k.c_str(), "algorithm") == 0 )
                    p.setAlgorithm(value);
                else
                    p.setInt(k, value);
            }
1112
            else if( PyFloat_Check(item) )
1113 1114 1115 1116
            {
                double value = PyFloat_AsDouble(item);
                p.setDouble(k, value);
            }
1117
            else
1118 1119
            {
                ok = false;
1120
                break;
1121
            }
1122 1123
        }
    }
1124

1125
    return ok && !PyErr_Occurred();
1126 1127
}

1128 1129 1130 1131 1132
template<>
bool pyopencv_to(PyObject* obj, cv::flann::SearchParams & value, const char * name)
{
    return pyopencv_to<cv::flann::IndexParams>(obj, value, name);
}
1133
#endif
1134

1135 1136
template <typename T>
bool pyopencv_to(PyObject *o, Ptr<T>& p, const char *name)
1137
{
1138
    p = makePtr<T>();
1139 1140 1141
    return pyopencv_to(o, *p, name);
}

1142
#ifdef HAVE_OPENCV_FLANN
1143 1144
template<>
bool pyopencv_to(PyObject *o, cvflann::flann_distance_t& dist, const char *name)
1145
{
1146
    int d = (int)dist;
1147
    bool ok = pyopencv_to(o, d, name);
1148
    dist = (cvflann::flann_distance_t)d;
1149 1150
    return ok;
}
1151
#endif
1152

A
Andrey Kamaev 已提交
1153 1154 1155 1156

////////////////////////////////////////////////////////////////////////////////////////////////////
// TODO: REMOVE used only by ml wrapper

1157 1158
template<>
bool pyopencv_to(PyObject *obj, CvTermCriteria& dst, const char *name)
A
Andrey Kamaev 已提交
1159 1160 1161 1162 1163 1164 1165
{
    (void)name;
    if(!obj)
        return true;
    return PyArg_ParseTuple(obj, "iid", &dst.type, &dst.max_iter, &dst.epsilon) > 0;
}

1166 1167
template<>
bool pyopencv_to(PyObject* obj, CvSlice& r, const char* name)
A
Andrey Kamaev 已提交
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
{
    (void)name;
    if(!obj || obj == Py_None)
        return true;
    if(PyObject_Size(obj) == 0)
    {
        r = CV_WHOLE_SEQ;
        return true;
    }
    return PyArg_ParseTuple(obj, "ii", &r.start_index, &r.end_index) > 0;
}

1180 1181 1182 1183 1184 1185
////////////////////////////////////////////////////////////////////////////////////////////////////

static void OnMouse(int event, int x, int y, int flags, void* param)
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();
1186

1187 1188
    PyObject *o = (PyObject*)param;
    PyObject *args = Py_BuildValue("iiiiO", event, x, y, flags, PyTuple_GetItem(o, 1));
1189

1190 1191 1192 1193 1194 1195 1196 1197 1198
    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);
}

1199
#ifdef HAVE_OPENCV_HIGHGUI
A
Andrey Kamaev 已提交
1200
static PyObject *pycvSetMouseCallback(PyObject*, PyObject *args, PyObject *kw)
1201 1202 1203 1204 1205
{
    const char *keywords[] = { "window_name", "on_mouse", "param", NULL };
    char* name;
    PyObject *on_mouse;
    PyObject *param = NULL;
1206

1207 1208 1209 1210 1211 1212 1213 1214 1215
    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;
    }
A
Andrey Kamaev 已提交
1216
    ERRWRAP2(setMouseCallback(name, OnMouse, Py_BuildValue("OO", on_mouse, param)));
1217 1218
    Py_RETURN_NONE;
}
1219
#endif
1220

1221
static void OnChange(int pos, void *param)
1222 1223 1224
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();
1225

1226 1227 1228 1229 1230 1231 1232 1233 1234
    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();
    Py_DECREF(args);
    PyGILState_Release(gstate);
}

1235
#ifdef HAVE_OPENCV_HIGHGUI
A
Andrey Kamaev 已提交
1236
static PyObject *pycvCreateTrackbar(PyObject*, PyObject *args)
1237 1238 1239 1240 1241 1242
{
    PyObject *on_change;
    char* trackbar_name;
    char* window_name;
    int *value = new int;
    int count;
1243

1244 1245 1246 1247 1248 1249
    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;
    }
A
Andrey Kamaev 已提交
1250
    ERRWRAP2(createTrackbar(trackbar_name, window_name, value, count, OnChange, Py_BuildValue("OO", on_change, Py_None)));
1251 1252
    Py_RETURN_NONE;
}
1253
#endif
1254 1255 1256

///////////////////////////////////////////////////////////////////////////////////////

1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
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);
  }
}

1268 1269 1270
#if PY_MAJOR_VERSION >= 3
#define MKTYPE2(NAME) pyopencv_##NAME##_specials(); if (!to_ok(&pyopencv_##NAME##_Type)) return NULL;
#else
1271
#define MKTYPE2(NAME) pyopencv_##NAME##_specials(); if (!to_ok(&pyopencv_##NAME##_Type)) return
1272
#endif
1273

A
Andrey Kamaev 已提交
1274 1275 1276 1277 1278
#ifdef __GNUC__
#  pragma GCC diagnostic ignored "-Wunused-parameter"
#  pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#endif

1279 1280 1281
#include "pyopencv_generated_types.h"
#include "pyopencv_generated_funcs.h"

A
Alexander Mordvintsev 已提交
1282
static PyMethodDef special_methods[] = {
1283
#ifdef HAVE_OPENCV_HIGHGUI
1284
  {"createTrackbar", pycvCreateTrackbar, METH_VARARGS, "createTrackbar(trackbarName, windowName, value, count, onChange) -> None"},
1285
  {"setMouseCallback", (PyCFunction)pycvSetMouseCallback, METH_VARARGS | METH_KEYWORDS, "setMouseCallback(windowName, onMouse [, param]) -> None"},
1286
#endif
1287 1288 1289 1290 1291 1292
  {NULL, NULL},
};

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

1293 1294 1295 1296 1297 1298 1299
struct ConstDef
{
    const char * name;
    long val;
};

static void init_submodule(PyObject * root, const char * name, PyMethodDef * methods, ConstDef * consts)
1300
{
1301
  // traverse and create nested submodules
1302
  std::string s = name;
1303 1304
  size_t i = s.find('.');
  while (i < s.length() && i != std::string::npos)
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
  {
    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 已提交
1320 1321 1322

    if (short_name != "")
        root = submod;
1323 1324
  }

1325
  // populate module's dict
1326 1327 1328 1329 1330 1331 1332
  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);
  }
1333 1334 1335 1336 1337
  for (ConstDef * c = consts; c->name != NULL; ++c)
  {
    PyDict_SetItemString(d, c->name, PyInt_FromLong(c->val));
  }

1338 1339 1340 1341
}

#include "pyopencv_generated_ns_reg.h"

1342 1343 1344 1345 1346 1347 1348 1349
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);
}

1350 1351 1352 1353 1354 1355 1356 1357 1358 1359

#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 已提交
1360
    special_methods
1361 1362 1363 1364
};

PyObject* PyInit_cv2()
#else
1365
extern "C" CV_EXPORTS void initcv2();
1366 1367

void initcv2()
1368
#endif
1369
{
A
Andrey Kamaev 已提交
1370
  import_array();
1371

1372 1373
#include "pyopencv_generated_type_reg.h"

1374 1375 1376
#if PY_MAJOR_VERSION >= 3
  PyObject* m = PyModule_Create(&cv2_moduledef);
#else
A
Alexander Mordvintsev 已提交
1377
  PyObject* m = Py_InitModule(MODULESTR, special_methods);
1378
#endif
1379 1380
  init_submodules(m); // from "pyopencv_generated_ns_reg.h"

1381 1382
  PyObject* d = PyModule_GetDict(m);

V
Vadim Pisarevsky 已提交
1383
  PyDict_SetItemString(d, "__version__", PyString_FromString(CV_VERSION));
1384 1385 1386

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

1388
#define PUBLISH(I) PyDict_SetItemString(d, #I, PyInt_FromLong(I))
A
Andrey Kamaev 已提交
1389
//#define PUBLISHU(I) PyDict_SetItemString(d, #I, PyLong_FromUnsignedLong(I))
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
#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);
1427

1428 1429 1430
#if PY_MAJOR_VERSION >= 3
    return m;
#endif
A
Andrey Kamaev 已提交
1431
}