cv2.cpp 34.3 KB
Newer Older
1 2 3 4 5 6 7 8 9
#include <Python.h>

#if !PYTHON_USE_NUMPY
#error "The module can only be built if NumPy is available"
#endif

#define MODULESTR "cv2"

#include "numpy/ndarrayobject.h"
10

11 12
#include "opencv2/core.hpp"
#include "opencv2/contrib.hpp"
13
#include "opencv2/flann/miniflann.hpp"
14 15 16 17 18 19
#include "opencv2/imgproc.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/ml.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/objdetect.hpp"
#include "opencv2/softcascade.hpp"
V
Vadim Pisarevsky 已提交
20 21
#include "opencv2/video/tracking.hpp"
#include "opencv2/video/background_segm.hpp"
22 23
#include "opencv2/photo.hpp"
#include "opencv2/highgui.hpp"
24

25
#include "opencv2/opencv_modules.hpp"
26

27
#ifdef HAVE_OPENCV_NONFREE
28
#  include "opencv2/nonfree.hpp"
29 30
#endif

31 32 33
using cv::flann::IndexParams;
using cv::flann::SearchParams;

34 35 36 37 38
static PyObject* opencv_error = 0;

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

40 41 42 43
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(str, sizeof(str), fmt, ap);
    va_end(ap);
44

45 46 47 48
    PyErr_SetString(PyExc_TypeError, str);
    return 0;
}

49 50 51 52 53 54
struct ArgInfo
{
    const char * name;
    bool outputarg;
    // more fields may be added if necessary

55
    ArgInfo(const char * name_, bool outputarg_)
56 57 58 59 60 61 62
        : name(name_)
        , outputarg(outputarg_) {}

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

63 64 65 66
class PyAllowThreads
{
public:
    PyAllowThreads() : _state(PyEval_SaveThread()) {}
67
    ~PyAllowThreads()
68 69 70 71 72 73 74
    {
        PyEval_RestoreThread(_state);
    }
private:
    PyThreadState* _state;
};

A
Alexander Mordvintsev 已提交
75 76 77 78
class PyEnsureGIL
{
public:
    PyEnsureGIL() : _state(PyGILState_Ensure()) {}
79
    ~PyEnsureGIL()
A
Alexander Mordvintsev 已提交
80 81 82 83 84 85 86
    {
        PyGILState_Release(_state);
    }
private:
    PyGILState_STATE _state;
};

87 88 89
#define ERRWRAP2(expr) \
try \
{ \
90
    PyAllowThreads allowThreads; \
91 92 93 94 95 96 97 98
    expr; \
} \
catch (const cv::Exception &e) \
{ \
    PyErr_SetString(opencv_error, e.what()); \
    return 0; \
}

V
Vadim Pisarevsky 已提交
99
using namespace cv;
100
typedef cv::softcascade::ChannelFeatureBuilder softcascade_ChannelFeatureBuilder;
V
Vadim Pisarevsky 已提交
101

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
typedef std::vector<uchar> vector_uchar;
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;
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;
typedef std::vector<KeyPoint> vector_KeyPoint;
typedef std::vector<Mat> vector_Mat;
typedef std::vector<DMatch> vector_DMatch;
typedef std::vector<std::string> vector_string;
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;
122

V
Vadim Pisarevsky 已提交
123
typedef Ptr<Algorithm> Ptr_Algorithm;
124 125
typedef Ptr<FeatureDetector> Ptr_FeatureDetector;
typedef Ptr<DescriptorExtractor> Ptr_DescriptorExtractor;
126
typedef Ptr<Feature2D> Ptr_Feature2D;
127
typedef Ptr<DescriptorMatcher> Ptr_DescriptorMatcher;
128
typedef Ptr<BackgroundSubtractor> Ptr_BackgroundSubtractor;
V
Vadim Pisarevsky 已提交
129

130
typedef Ptr<cv::softcascade::ChannelFeatureBuilder> Ptr_ChannelFeatureBuilder;
131

132 133
typedef SimpleBlobDetector::Params SimpleBlobDetector_Params;

134 135 136 137 138
typedef cvflann::flann_distance_t cvflann_flann_distance_t;
typedef cvflann::flann_algorithm_t cvflann_flann_algorithm_t;
typedef Ptr<flann::IndexParams> Ptr_flann_IndexParams;
typedef Ptr<flann::SearchParams> Ptr_flann_SearchParams;

139
typedef Ptr<FaceRecognizer> Ptr_FaceRecognizer;
140
typedef std::vector<Scalar> vector_Scalar;
141

V
Vadim Pisarevsky 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154
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;
}

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
static size_t REFCOUNT_OFFSET = (size_t)&(((PyObject*)0)->ob_refcnt) +
    (0x12345678 != *(const size_t*)"\x78\x56\x34\x12\0\0\0\0\0")*sizeof(int);

static inline PyObject* pyObjectFromRefcount(const int* refcount)
{
    return (PyObject*)((size_t)refcount - REFCOUNT_OFFSET);
}

static inline int* refcountFromPyObject(const PyObject* obj)
{
    return (int*)((size_t)obj + REFCOUNT_OFFSET);
}

class NumpyAllocator : public MatAllocator
{
public:
    NumpyAllocator() {}
    ~NumpyAllocator() {}
173

174 175 176
    void allocate(int dims, const int* sizes, int type, int*& refcount,
                  uchar*& datastart, uchar*& data, size_t* step)
    {
A
Alexander Mordvintsev 已提交
177 178
        PyEnsureGIL gil;

179 180 181 182 183 184 185 186 187 188 189 190 191
        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 :
                      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;
        npy_intp _sizes[CV_MAX_DIM+1];
        for( i = 0; i < dims; i++ )
            _sizes[i] = sizes[i];
        if( cn > 1 )
        {
192
            /*if( _sizes[dims-1] == 1 )
193
                _sizes[dims-1] = cn;
194
            else*/
195 196 197 198 199 200 201
                _sizes[dims++] = cn;
        }
        PyObject* o = PyArray_SimpleNew(dims, _sizes, typenum);
        if(!o)
            CV_Error_(CV_StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims));
        refcount = refcountFromPyObject(o);
        npy_intp* _strides = PyArray_STRIDES(o);
V
Vadim Pisarevsky 已提交
202
        for( i = 0; i < dims - (cn > 1); i++ )
203 204 205
            step[i] = (size_t)_strides[i];
        datastart = data = (uchar*)PyArray_DATA(o);
    }
206

A
Andrey Kamaev 已提交
207
    void deallocate(int* refcount, uchar*, uchar*)
208
    {
A
Alexander Mordvintsev 已提交
209
        PyEnsureGIL gil;
210 211 212
        if( !refcount )
            return;
        PyObject* o = pyObjectFromRefcount(refcount);
V
Vadim Pisarevsky 已提交
213
        Py_INCREF(o);
214 215 216 217 218
        Py_DECREF(o);
    }
};

NumpyAllocator g_numpyAllocator;
219

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

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

232 233 234 235 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
    if( PyInt_Check(o) )
    {
        double v[] = {PyInt_AsLong((PyObject*)o), 0., 0., 0.};
        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 已提交
265 266
    if( !PyArray_Check(o) )
    {
267
        failmsg("%s is not a numpy array, neither a scalar", info.name);
V
Vadim Pisarevsky 已提交
268
        return false;
269
    }
270

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

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

297 298 299
    int ndims = PyArray_NDIM(o);
    if(ndims >= CV_MAX_DIM)
    {
300
        failmsg("%s dimensionality (=%d) is too high", info.name, ndims);
V
Vadim Pisarevsky 已提交
301
        return false;
302
    }
303

304
    int size[CV_MAX_DIM+1];
V
Vadim Pisarevsky 已提交
305
    size_t step[CV_MAX_DIM+1], elemsize = CV_ELEM_SIZE1(type);
306 307
    const npy_intp* _sizes = PyArray_DIMS(o);
    const npy_intp* _strides = PyArray_STRIDES(o);
308 309
    bool ismultichannel = ndims == 3 && _sizes[2] <= CV_CN_MAX;

310 311 312 313 314 315 316 317 318 319
    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
        if( (i == ndims-1 && (size_t)_strides[i] != elemsize) ||
            (i < ndims-1 && _strides[i] < _strides[i+1]) )
            needcopy = true;
    }
320

321 322 323
    if( ismultichannel && _strides[1] != (npy_intp)elemsize*_sizes[2] )
        needcopy = true;

324 325 326 327
    if (needcopy)
    {
        if (info.outputarg)
        {
328
            failmsg("Layout of the output array %s is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)", info.name);
329 330
            return false;
        }
331 332 333 334
        if( needcast )
            o = (PyObject*)PyArray_Cast((PyArrayObject*)o, new_typenum);
        else
            o = (PyObject*)PyArray_GETCONTIGUOUS((PyArrayObject*)o);
335 336
        _strides = PyArray_STRIDES(o);
    }
337

338 339 340 341 342
    for(int i = 0; i < ndims; i++)
    {
        size[i] = (int)_sizes[i];
        step[i] = (size_t)_strides[i];
    }
343

344 345
    // handle degenerate case
    if( ndims == 0) {
346 347 348 349
        size[ndims] = 1;
        step[ndims] = elemsize;
        ndims++;
    }
350

351
    if( ismultichannel )
V
Vadim Pisarevsky 已提交
352 353 354 355
    {
        ndims--;
        type |= CV_MAKETYPE(0, size[2]);
    }
356

V
Vadim Pisarevsky 已提交
357
    if( ndims > 2 && !allowND )
358
    {
359
        failmsg("%s has more than 2 dimensions", info.name);
V
Vadim Pisarevsky 已提交
360
        return false;
361
    }
362

V
Vadim Pisarevsky 已提交
363
    m = Mat(ndims, size, type, PyArray_DATA(o), step);
364

365 366 367
    if( m.data )
    {
        m.refcount = refcountFromPyObject(o);
368 369 370 371 372
        if (!needcopy)
        {
            m.addref(); // protect the original numpy array from deallocation
                        // (since Mat destructor will decrement the reference counter)
        }
373 374
    };
    m.allocator = &g_numpyAllocator;
375

V
Vadim Pisarevsky 已提交
376
    return true;
377 378
}

V
Vadim Pisarevsky 已提交
379
static PyObject* pyopencv_from(const Mat& m)
380
{
381
    if( !m.data )
382
        Py_RETURN_NONE;
V
Vadim Pisarevsky 已提交
383 384 385
    Mat temp, *p = (Mat*)&m;
    if(!p->refcount || p->allocator != &g_numpyAllocator)
    {
V
Vadim Pisarevsky 已提交
386
        temp.allocator = &g_numpyAllocator;
V
Vadim Pisarevsky 已提交
387 388 389 390 391
        m.copyTo(temp);
        p = &temp;
    }
    p->addref();
    return pyObjectFromRefcount(p->refcount);
392 393
}

V
Vadim Pisarevsky 已提交
394
static bool pyopencv_to(PyObject *o, Scalar& s, const char *name = "<unknown>")
395
{
V
Vadim Pisarevsky 已提交
396 397
    if(!o || o == Py_None)
        return true;
398 399 400
    if (PySequence_Check(o)) {
        PyObject *fi = PySequence_Fast(o, name);
        if (fi == NULL)
V
Vadim Pisarevsky 已提交
401
            return false;
402 403 404
        if (4 < PySequence_Fast_GET_SIZE(fi))
        {
            failmsg("Scalar value for argument '%s' is longer than 4", name);
V
Vadim Pisarevsky 已提交
405
            return false;
406 407 408 409
        }
        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)) {
410
                s[(int)i] = PyFloat_AsDouble(item);
411 412
            } else {
                failmsg("Scalar value for argument '%s' is not numeric", name);
V
Vadim Pisarevsky 已提交
413
                return false;
414 415 416 417 418 419 420 421
            }
        }
        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 已提交
422
            return false;
423 424
        }
    }
V
Vadim Pisarevsky 已提交
425
    return true;
426 427
}

V
Vadim Pisarevsky 已提交
428 429 430 431
static inline PyObject* pyopencv_from(const Scalar& src)
{
    return Py_BuildValue("(dddd)", src[0], src[1], src[2], src[3]);
}
432

V
Vadim Pisarevsky 已提交
433
static PyObject* pyopencv_from(bool value)
434
{
V
Vadim Pisarevsky 已提交
435 436 437 438 439
    return PyBool_FromLong(value);
}

static bool pyopencv_to(PyObject* obj, bool& value, const char* name = "<unknown>")
{
A
Andrey Kamaev 已提交
440
    (void)name;
V
Vadim Pisarevsky 已提交
441 442 443 444 445 446 447 448 449 450 451
    if(!obj || obj == Py_None)
        return true;
    int _val = PyObject_IsTrue(obj);
    if(_val < 0)
        return false;
    value = _val > 0;
    return true;
}

static PyObject* pyopencv_from(size_t value)
{
452
    return PyLong_FromSize_t(value);
V
Vadim Pisarevsky 已提交
453
}
454

455 456
static bool pyopencv_to(PyObject* obj, size_t& value, const char* name = "<unknown>")
{
A
Andrey Kamaev 已提交
457
    (void)name;
458 459 460
    if(!obj || obj == Py_None)
        return true;
    value = (int)PyLong_AsUnsignedLong(obj);
461
    return value != (size_t)-1 || !PyErr_Occurred();
462 463
}

V
Vadim Pisarevsky 已提交
464 465 466
static PyObject* pyopencv_from(int value)
{
    return PyInt_FromLong(value);
467 468
}

A
Andrey Kamaev 已提交
469 470 471 472 473 474 475 476 477 478
static PyObject* pyopencv_from(cvflann_flann_algorithm_t value)
{
    return PyInt_FromLong(int(value));
}

static PyObject* pyopencv_from(cvflann_flann_distance_t value)
{
    return PyInt_FromLong(int(value));
}

V
Vadim Pisarevsky 已提交
479
static bool pyopencv_to(PyObject* obj, int& value, const char* name = "<unknown>")
480
{
A
Andrey Kamaev 已提交
481
    (void)name;
482 483
    if(!obj || obj == Py_None)
        return true;
484 485 486 487 488 489
    if(PyInt_Check(obj))
        value = (int)PyInt_AsLong(obj);
    else if(PyLong_Check(obj))
        value = (int)PyLong_AsLong(obj);
    else
        return false;
490 491 492 493 494 495 496 497 498
    return value != -1 || !PyErr_Occurred();
}

static PyObject* pyopencv_from(uchar value)
{
    return PyInt_FromLong(value);
}

static bool pyopencv_to(PyObject* obj, uchar& value, const char* name = "<unknown>")
499
{
A
Andrey Kamaev 已提交
500
    (void)name;
V
Vadim Pisarevsky 已提交
501 502
    if(!obj || obj == Py_None)
        return true;
503 504 505
    int ivalue = (int)PyInt_AsLong(obj);
    value = cv::saturate_cast<uchar>(ivalue);
    return ivalue != -1 || !PyErr_Occurred();
V
Vadim Pisarevsky 已提交
506 507 508 509 510 511 512 513 514
}

static PyObject* pyopencv_from(double value)
{
    return PyFloat_FromDouble(value);
}

static bool pyopencv_to(PyObject* obj, double& value, const char* name = "<unknown>")
{
A
Andrey Kamaev 已提交
515
    (void)name;
V
Vadim Pisarevsky 已提交
516 517
    if(!obj || obj == Py_None)
        return true;
518
    if(!!PyInt_CheckExact(obj))
V
Vadim Pisarevsky 已提交
519
        value = (double)PyInt_AS_LONG(obj);
520
    else
V
Vadim Pisarevsky 已提交
521 522
        value = PyFloat_AsDouble(obj);
    return !PyErr_Occurred();
523 524
}

V
Vadim Pisarevsky 已提交
525
static PyObject* pyopencv_from(float value)
526
{
V
Vadim Pisarevsky 已提交
527
    return PyFloat_FromDouble(value);
528
}
V
Vadim Pisarevsky 已提交
529 530

static bool pyopencv_to(PyObject* obj, float& value, const char* name = "<unknown>")
531
{
A
Andrey Kamaev 已提交
532
    (void)name;
V
Vadim Pisarevsky 已提交
533 534
    if(!obj || obj == Py_None)
        return true;
535
    if(!!PyInt_CheckExact(obj))
V
Vadim Pisarevsky 已提交
536 537 538 539
        value = (float)PyInt_AS_LONG(obj);
    else
        value = (float)PyFloat_AsDouble(obj);
    return !PyErr_Occurred();
540 541
}

542 543
static PyObject* pyopencv_from(int64 value)
{
544
    return PyLong_FromLongLong(value);
545 546
}

547
static PyObject* pyopencv_from(const std::string& value)
V
Vadim Pisarevsky 已提交
548 549 550
{
    return PyString_FromString(value.empty() ? "" : value.c_str());
}
551

552
static bool pyopencv_to(PyObject* obj, std::string& value, const char* name = "<unknown>")
553
{
A
Andrey Kamaev 已提交
554
    (void)name;
V
Vadim Pisarevsky 已提交
555 556 557 558 559
    if(!obj || obj == Py_None)
        return true;
    char* str = PyString_AsString(obj);
    if(!str)
        return false;
560
    value = std::string(str);
V
Vadim Pisarevsky 已提交
561 562 563 564 565
    return true;
}

static inline bool pyopencv_to(PyObject* obj, Size& sz, const char* name = "<unknown>")
{
A
Andrey Kamaev 已提交
566
    (void)name;
V
Vadim Pisarevsky 已提交
567 568
    if(!obj || obj == Py_None)
        return true;
A
Alexander Mordvintsev 已提交
569
    return PyArg_ParseTuple(obj, "ii", &sz.width, &sz.height) > 0;
V
Vadim Pisarevsky 已提交
570 571 572 573 574 575 576 577 578
}

static inline PyObject* pyopencv_from(const Size& sz)
{
    return Py_BuildValue("(ii)", sz.width, sz.height);
}

static inline bool pyopencv_to(PyObject* obj, Rect& r, const char* name = "<unknown>")
{
A
Andrey Kamaev 已提交
579
    (void)name;
V
Vadim Pisarevsky 已提交
580 581
    if(!obj || obj == Py_None)
        return true;
A
Alexander Mordvintsev 已提交
582
    return PyArg_ParseTuple(obj, "iiii", &r.x, &r.y, &r.width, &r.height) > 0;
V
Vadim Pisarevsky 已提交
583 584 585 586 587 588 589 590 591
}

static inline PyObject* pyopencv_from(const Rect& r)
{
    return Py_BuildValue("(iiii)", r.x, r.y, r.width, r.height);
}

static inline bool pyopencv_to(PyObject* obj, Range& r, const char* name = "<unknown>")
{
A
Andrey Kamaev 已提交
592
    (void)name;
V
Vadim Pisarevsky 已提交
593 594 595
    if(!obj || obj == Py_None)
        return true;
    if(PyObject_Size(obj) == 0)
596
    {
V
Vadim Pisarevsky 已提交
597 598
        r = Range::all();
        return true;
599
    }
A
Alexander Mordvintsev 已提交
600
    return PyArg_ParseTuple(obj, "ii", &r.start, &r.end) > 0;
V
Vadim Pisarevsky 已提交
601 602 603 604 605 606 607 608 609
}

static inline PyObject* pyopencv_from(const Range& r)
{
    return Py_BuildValue("(ii)", r.start, r.end);
}

static inline bool pyopencv_to(PyObject* obj, CvSlice& r, const char* name = "<unknown>")
{
A
Andrey Kamaev 已提交
610
    (void)name;
V
Vadim Pisarevsky 已提交
611 612 613 614 615 616 617
    if(!obj || obj == Py_None)
        return true;
    if(PyObject_Size(obj) == 0)
    {
        r = CV_WHOLE_SEQ;
        return true;
    }
A
Alexander Mordvintsev 已提交
618
    return PyArg_ParseTuple(obj, "ii", &r.start_index, &r.end_index) > 0;
V
Vadim Pisarevsky 已提交
619
}
620

V
Vadim Pisarevsky 已提交
621 622 623
static inline PyObject* pyopencv_from(const CvSlice& r)
{
    return Py_BuildValue("(ii)", r.start_index, r.end_index);
624 625
}

V
Vadim Pisarevsky 已提交
626 627
static inline bool pyopencv_to(PyObject* obj, Point& p, const char* name = "<unknown>")
{
A
Andrey Kamaev 已提交
628
    (void)name;
V
Vadim Pisarevsky 已提交
629 630
    if(!obj || obj == Py_None)
        return true;
631
    if(!!PyComplex_CheckExact(obj))
V
Vadim Pisarevsky 已提交
632 633 634 635 636 637
    {
        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 已提交
638
    return PyArg_ParseTuple(obj, "ii", &p.x, &p.y) > 0;
V
Vadim Pisarevsky 已提交
639 640 641 642
}

static inline bool pyopencv_to(PyObject* obj, Point2f& p, const char* name = "<unknown>")
{
A
Andrey Kamaev 已提交
643
    (void)name;
V
Vadim Pisarevsky 已提交
644 645
    if(!obj || obj == Py_None)
        return true;
646
    if(!!PyComplex_CheckExact(obj))
647
    {
V
Vadim Pisarevsky 已提交
648 649 650 651 652
        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 已提交
653
    return PyArg_ParseTuple(obj, "ff", &p.x, &p.y) > 0;
V
Vadim Pisarevsky 已提交
654 655 656 657 658 659 660 661 662 663 664 665 666 667
}

static inline PyObject* pyopencv_from(const Point& p)
{
    return Py_BuildValue("(ii)", p.x, p.y);
}

static inline PyObject* pyopencv_from(const Point2f& p)
{
    return Py_BuildValue("(dd)", p.x, p.y);
}

static inline bool pyopencv_to(PyObject* obj, Vec3d& v, const char* name = "<unknown>")
{
A
Andrey Kamaev 已提交
668
    (void)name;
V
Vadim Pisarevsky 已提交
669 670
    if(!obj)
        return true;
A
Alexander Mordvintsev 已提交
671
    return PyArg_ParseTuple(obj, "ddd", &v[0], &v[1], &v[2]) > 0;
V
Vadim Pisarevsky 已提交
672 673 674 675 676 677 678 679 680 681 682 683 684 685
}

static inline PyObject* pyopencv_from(const Vec3d& v)
{
    return Py_BuildValue("(ddd)", v[0], v[1], v[2]);
}

static inline PyObject* pyopencv_from(const Point2d& p)
{
    return Py_BuildValue("(dd)", p.x, p.y);
}

template<typename _Tp> struct pyopencvVecConverter
{
686
    static bool to(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
687 688
    {
        typedef typename DataType<_Tp>::channel_type _Cp;
V
Vadim Pisarevsky 已提交
689
        if(!obj || obj == Py_None)
V
Vadim Pisarevsky 已提交
690 691 692 693
            return true;
        if (PyArray_Check(obj))
        {
            Mat m;
694
            pyopencv_to(obj, m, info);
V
Vadim Pisarevsky 已提交
695 696 697 698
            m.copyTo(value);
        }
        if (!PySequence_Check(obj))
            return false;
699
        PyObject *seq = PySequence_Fast(obj, info.name);
V
Vadim Pisarevsky 已提交
700 701 702 703
        if (seq == NULL)
            return false;
        int i, j, n = (int)PySequence_Fast_GET_SIZE(seq);
        value.resize(n);
704

V
Vadim Pisarevsky 已提交
705 706 707
        int type = DataType<_Tp>::type;
        int depth = CV_MAT_DEPTH(type), channels = CV_MAT_CN(type);
        PyObject** items = PySequence_Fast_ITEMS(seq);
708

V
Vadim Pisarevsky 已提交
709 710 711 712 713 714
        for( i = 0; i < n; i++ )
        {
            PyObject* item = items[i];
            PyObject* seq_i = 0;
            PyObject** items_i = &item;
            _Cp* data = (_Cp*)&value[i];
715

V
Vadim Pisarevsky 已提交
716 717 718 719 720 721 722 723 724
            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 已提交
725
                if( PyArray_Check(item))
V
Vadim Pisarevsky 已提交
726 727
                {
                    Mat src;
728
                    pyopencv_to(item, src, info);
V
Vadim Pisarevsky 已提交
729 730 731 732 733 734 735 736 737 738
                    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;
                }
739

740
                seq_i = PySequence_Fast(item, info.name);
V
Vadim Pisarevsky 已提交
741 742 743 744 745 746 747
                if( !seq_i || (int)PySequence_Fast_GET_SIZE(seq_i) != channels )
                {
                    Py_XDECREF(seq_i);
                    break;
                }
                items_i = PySequence_Fast_ITEMS(seq_i);
            }
748

V
Vadim Pisarevsky 已提交
749 750 751 752 753
            for( j = 0; j < channels; j++ )
            {
                PyObject* item_ij = items_i[j];
                if( PyInt_Check(item_ij))
                {
754 755 756 757 758 759 760 761
                    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 已提交
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
                    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;
782
    }
783

784
    static PyObject* from(const std::vector<_Tp>& value)
V
Vadim Pisarevsky 已提交
785 786 787 788 789 790 791 792 793
    {
        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);
    }
};


794
template<typename _Tp> static inline bool pyopencv_to(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
795
{
796
    return pyopencvVecConverter<_Tp>::to(obj, value, info);
V
Vadim Pisarevsky 已提交
797 798
}

799
template<typename _Tp> static inline PyObject* pyopencv_from(const std::vector<_Tp>& value)
V
Vadim Pisarevsky 已提交
800 801 802 803 804
{
    return pyopencvVecConverter<_Tp>::from(value);
}

static PyObject* pyopencv_from(const KeyPoint&);
805
static PyObject* pyopencv_from(const DMatch&);
V
Vadim Pisarevsky 已提交
806

807
template<typename _Tp> static inline bool pyopencv_to_generic_vec(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
808
{
V
Vadim Pisarevsky 已提交
809 810
    if(!obj || obj == Py_None)
       return true;
V
Vadim Pisarevsky 已提交
811 812
    if (!PySequence_Check(obj))
        return false;
813
    PyObject *seq = PySequence_Fast(obj, info.name);
V
Vadim Pisarevsky 已提交
814 815 816 817
    if (seq == NULL)
        return false;
    int i, n = (int)PySequence_Fast_GET_SIZE(seq);
    value.resize(n);
818

V
Vadim Pisarevsky 已提交
819
    PyObject** items = PySequence_Fast_ITEMS(seq);
820

V
Vadim Pisarevsky 已提交
821 822 823
    for( i = 0; i < n; i++ )
    {
        PyObject* item = items[i];
824
        if(!pyopencv_to(item, value[i], info))
V
Vadim Pisarevsky 已提交
825 826 827 828 829 830
            break;
    }
    Py_DECREF(seq);
    return i == n;
}

831
template<typename _Tp> static inline PyObject* pyopencv_from_generic_vec(const std::vector<_Tp>& value)
V
Vadim Pisarevsky 已提交
832 833
{
    int i, n = (int)value.size();
V
Vadim Pisarevsky 已提交
834
    PyObject* seq = PyList_New(n);
V
Vadim Pisarevsky 已提交
835
    for( i = 0; i < n; i++ )
836
    {
V
Vadim Pisarevsky 已提交
837 838 839
        PyObject* item = pyopencv_from(value[i]);
        if(!item)
            break;
V
Vadim Pisarevsky 已提交
840
        PyList_SET_ITEM(seq, i, item);
V
Vadim Pisarevsky 已提交
841 842
    }
    if( i < n )
843
    {
V
Vadim Pisarevsky 已提交
844
        Py_DECREF(seq);
845 846
        return 0;
    }
V
Vadim Pisarevsky 已提交
847 848 849 850
    return seq;
}


851
template<typename _Tp> struct pyopencvVecConverter<std::vector<_Tp> >
V
Vadim Pisarevsky 已提交
852
{
853
    static bool to(PyObject* obj, std::vector<std::vector<_Tp> >& value, const char* name="<unknown>")
V
Vadim Pisarevsky 已提交
854 855 856
    {
        return pyopencv_to_generic_vec(obj, value, name);
    }
857

858
    static PyObject* from(const std::vector<std::vector<_Tp> >& value)
V
Vadim Pisarevsky 已提交
859 860 861 862 863 864 865
    {
        return pyopencv_from_generic_vec(value);
    }
};

template<> struct pyopencvVecConverter<Mat>
{
866
    static bool to(PyObject* obj, std::vector<Mat>& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
867
    {
868
        return pyopencv_to_generic_vec(obj, value, info);
V
Vadim Pisarevsky 已提交
869
    }
870

871
    static PyObject* from(const std::vector<Mat>& value)
V
Vadim Pisarevsky 已提交
872 873 874 875
    {
        return pyopencv_from_generic_vec(value);
    }
};
876

V
Vadim Pisarevsky 已提交
877
template<> struct pyopencvVecConverter<KeyPoint>
878
{
879
    static bool to(PyObject* obj, std::vector<KeyPoint>& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
880
    {
881
        return pyopencv_to_generic_vec(obj, value, info);
V
Vadim Pisarevsky 已提交
882
    }
883

884
    static PyObject* from(const std::vector<KeyPoint>& value)
V
Vadim Pisarevsky 已提交
885 886 887 888 889
    {
        return pyopencv_from_generic_vec(value);
    }
};

890 891
template<> struct pyopencvVecConverter<DMatch>
{
892
    static bool to(PyObject* obj, std::vector<DMatch>& value, const ArgInfo info)
893
    {
894
        return pyopencv_to_generic_vec(obj, value, info);
895
    }
896

897
    static PyObject* from(const std::vector<DMatch>& value)
898 899 900 901 902
    {
        return pyopencv_from_generic_vec(value);
    }
};

903
template<> struct pyopencvVecConverter<std::string>
V
Vadim Pisarevsky 已提交
904
{
905
    static bool to(PyObject* obj, std::vector<std::string>& value, const ArgInfo info)
V
Vadim Pisarevsky 已提交
906
    {
907
        return pyopencv_to_generic_vec(obj, value, info);
V
Vadim Pisarevsky 已提交
908
    }
909

910
    static PyObject* from(const std::vector<std::string>& value)
V
Vadim Pisarevsky 已提交
911 912 913 914 915
    {
        return pyopencv_from_generic_vec(value);
    }
};

916

V
Vadim Pisarevsky 已提交
917
static inline bool pyopencv_to(PyObject *obj, CvTermCriteria& dst, const char *name="<unknown>")
918
{
A
Andrey Kamaev 已提交
919
    (void)name;
V
Vadim Pisarevsky 已提交
920 921 922
    if(!obj)
        return true;
    return PyArg_ParseTuple(obj, "iid", &dst.type, &dst.max_iter, &dst.epsilon) > 0;
923 924
}

V
Vadim Pisarevsky 已提交
925
static inline PyObject* pyopencv_from(const CvTermCriteria& src)
926
{
V
Vadim Pisarevsky 已提交
927
    return Py_BuildValue("(iid)", src.type, src.max_iter, src.epsilon);
928 929
}

V
Vadim Pisarevsky 已提交
930
static inline bool pyopencv_to(PyObject *obj, TermCriteria& dst, const char *name="<unknown>")
931
{
A
Andrey Kamaev 已提交
932
    (void)name;
V
Vadim Pisarevsky 已提交
933 934 935
    if(!obj)
        return true;
    return PyArg_ParseTuple(obj, "iid", &dst.type, &dst.maxCount, &dst.epsilon) > 0;
936 937
}

V
Vadim Pisarevsky 已提交
938
static inline PyObject* pyopencv_from(const TermCriteria& src)
939
{
V
Vadim Pisarevsky 已提交
940
    return Py_BuildValue("(iid)", src.type, src.maxCount, src.epsilon);
941 942
}

V
Vadim Pisarevsky 已提交
943
static inline bool pyopencv_to(PyObject *obj, RotatedRect& dst, const char *name="<unknown>")
944
{
A
Andrey Kamaev 已提交
945
    (void)name;
V
Vadim Pisarevsky 已提交
946 947 948
    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;
949 950
}

V
Vadim Pisarevsky 已提交
951
static inline PyObject* pyopencv_from(const RotatedRect& src)
952
{
V
Vadim Pisarevsky 已提交
953
    return Py_BuildValue("((ff)(ff)f)", src.center.x, src.center.y, src.size.width, src.size.height, src.angle);
954 955
}

V
Vadim Pisarevsky 已提交
956
static inline PyObject* pyopencv_from(const Moments& m)
957
{
V
Vadim Pisarevsky 已提交
958 959 960 961 962 963 964 965
    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,
                         "nu30", m.nu30, "nu21", m.nu21, "nu12", m.nu12, "mu03", m.nu03);
966 967
}

968 969 970 971 972 973 974
static inline PyObject* pyopencv_from(const CvDTreeNode* node)
{
    double value = node->value;
    int ivalue = cvRound(value);
    return value == ivalue ? PyInt_FromLong(ivalue) : PyFloat_FromDouble(value);
}

975 976
static bool pyopencv_to(PyObject *o, cv::flann::IndexParams& p, const char *name="<unknown>")
{
A
Andrey Kamaev 已提交
977
    (void)name;
978
    bool ok = false;
979 980
    PyObject* keys = PyObject_CallMethod(o,(char*)"keys",0);
    PyObject* values = PyObject_CallMethod(o,(char*)"values",0);
981

982 983 984 985 986 987 988 989 990 991 992
    if( keys && values )
    {
        int i, n = (int)PyList_GET_SIZE(keys);
        for( i = 0; i < n; i++ )
        {
            PyObject* key = PyList_GET_ITEM(keys, i);
            PyObject* item = PyList_GET_ITEM(values, i);
            if( !PyString_Check(key) )
                break;
            std::string k = PyString_AsString(key);
            if( PyString_Check(item) )
993 994 995 996
            {
                const char* value = PyString_AsString(item);
                p.setString(k, value);
            }
997
            else if( !!PyBool_Check(item) )
998
                p.setBool(k, item == Py_True);
999
            else if( PyInt_Check(item) )
1000 1001 1002 1003 1004 1005 1006
            {
                int value = (int)PyInt_AsLong(item);
                if( strcmp(k.c_str(), "algorithm") == 0 )
                    p.setAlgorithm(value);
                else
                    p.setInt(k, value);
            }
1007
            else if( PyFloat_Check(item) )
1008 1009 1010 1011
            {
                double value = PyFloat_AsDouble(item);
                p.setDouble(k, value);
            }
1012 1013 1014 1015 1016
            else
                break;
        }
        ok = i == n && !PyErr_Occurred();
    }
1017

1018 1019 1020 1021 1022
    Py_XDECREF(keys);
    Py_XDECREF(values);
    return ok;
}

1023 1024 1025 1026 1027 1028 1029 1030
template <class T>
static bool pyopencv_to(PyObject *o, Ptr<T>& p, const char *name="<unknown>")
{
    p = new T();
    return pyopencv_to(o, *p, name);
}


1031
static bool pyopencv_to(PyObject *o, cvflann::flann_distance_t& dist, const char *name="<unknown>")
1032
{
1033
    int d = (int)dist;
1034
    bool ok = pyopencv_to(o, d, name);
1035
    dist = (cvflann::flann_distance_t)d;
1036 1037
    return ok;
}
1038 1039 1040 1041 1042 1043 1044

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

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

1046 1047
    PyObject *o = (PyObject*)param;
    PyObject *args = Py_BuildValue("iiiiO", event, x, y, flags, PyTuple_GetItem(o, 1));
1048

1049 1050 1051 1052 1053 1054 1055 1056 1057
    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);
}

A
Andrey Kamaev 已提交
1058
static PyObject *pycvSetMouseCallback(PyObject*, PyObject *args, PyObject *kw)
1059 1060 1061 1062 1063
{
    const char *keywords[] = { "window_name", "on_mouse", "param", NULL };
    char* name;
    PyObject *on_mouse;
    PyObject *param = NULL;
1064

1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
    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;
    }
    ERRWRAP2(cvSetMouseCallback(name, OnMouse, Py_BuildValue("OO", on_mouse, param)));
    Py_RETURN_NONE;
}

1078
static void OnChange(int pos, void *param)
1079 1080 1081
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();
1082

1083 1084 1085 1086 1087 1088 1089 1090 1091
    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);
}

A
Andrey Kamaev 已提交
1092
static PyObject *pycvCreateTrackbar(PyObject*, PyObject *args)
1093 1094 1095 1096 1097 1098
{
    PyObject *on_change;
    char* trackbar_name;
    char* window_name;
    int *value = new int;
    int count;
1099

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
    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;
    }
    ERRWRAP2(cvCreateTrackbar2(trackbar_name, window_name, value, count, OnChange, Py_BuildValue("OO", on_change, Py_None)));
    Py_RETURN_NONE;
}

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

1112 1113
#define MKTYPE2(NAME) pyopencv_##NAME##_specials(); if (!to_ok(&pyopencv_##NAME##_Type)) return

A
Andrey Kamaev 已提交
1114 1115 1116 1117 1118
#ifdef __GNUC__
#  pragma GCC diagnostic ignored "-Wunused-parameter"
#  pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#endif

1119 1120 1121 1122 1123 1124
#include "pyopencv_generated_types.h"
#include "pyopencv_generated_funcs.h"

static PyMethodDef methods[] = {

#include "pyopencv_generated_func_tab.h"
1125 1126
  {"createTrackbar", pycvCreateTrackbar, METH_VARARGS, "createTrackbar(trackbarName, windowName, value, count, onChange) -> None"},
  {"setMouseCallback", (PyCFunction)pycvSetMouseCallback, METH_KEYWORDS, "setMouseCallback(windowName, onMouse [, param]) -> None"},
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
  {NULL, NULL},
};

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

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

1141 1142
#include "cv2.cv.hpp"

1143 1144 1145 1146
extern "C"
#if defined WIN32 || defined _WIN32
__declspec(dllexport)
#endif
1147
void initcv2();
1148 1149 1150 1151 1152 1153

void initcv2()
{
#if PYTHON_USE_NUMPY
    import_array();
#endif
1154

1155 1156
#if PYTHON_USE_NUMPY
#include "pyopencv_generated_type_reg.h"
1157
#endif
1158

1159
  PyObject* m = Py_InitModule(MODULESTR, methods);
1160 1161
  PyObject* d = PyModule_GetDict(m);

V
Vadim Pisarevsky 已提交
1162
  PyDict_SetItemString(d, "__version__", PyString_FromString(CV_VERSION));
1163 1164 1165

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

1167
  PyObject* cv_m = init_cv();
1168

1169
  PyDict_SetItemString(d, "cv", cv_m);
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 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246

#define PUBLISH(I) PyDict_SetItemString(d, #I, PyInt_FromLong(I))
#define PUBLISHU(I) PyDict_SetItemString(d, #I, PyLong_FromUnsignedLong(I))
#define PUBLISH2(I, value) PyDict_SetItemString(d, #I, PyLong_FromLong(value))

  PUBLISHU(IPL_DEPTH_8U);
  PUBLISHU(IPL_DEPTH_8S);
  PUBLISHU(IPL_DEPTH_16U);
  PUBLISHU(IPL_DEPTH_16S);
  PUBLISHU(IPL_DEPTH_32S);
  PUBLISHU(IPL_DEPTH_32F);
  PUBLISHU(IPL_DEPTH_64F);

  PUBLISH(CV_LOAD_IMAGE_COLOR);
  PUBLISH(CV_LOAD_IMAGE_GRAYSCALE);
  PUBLISH(CV_LOAD_IMAGE_UNCHANGED);
  PUBLISH(CV_HIST_ARRAY);
  PUBLISH(CV_HIST_SPARSE);
  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);
  PUBLISH(CV_NEXT_AROUND_ORG);
  PUBLISH(CV_NEXT_AROUND_DST);
  PUBLISH(CV_PREV_AROUND_ORG);
  PUBLISH(CV_PREV_AROUND_DST);
  PUBLISH(CV_NEXT_AROUND_LEFT);
  PUBLISH(CV_NEXT_AROUND_RIGHT);
  PUBLISH(CV_PREV_AROUND_LEFT);
  PUBLISH(CV_PREV_AROUND_RIGHT);

  PUBLISH(CV_WINDOW_AUTOSIZE);

  PUBLISH(CV_PTLOC_INSIDE);
  PUBLISH(CV_PTLOC_ON_EDGE);
  PUBLISH(CV_PTLOC_VERTEX);
  PUBLISH(CV_PTLOC_OUTSIDE_RECT);

  PUBLISH(GC_BGD);
  PUBLISH(GC_FGD);
  PUBLISH(GC_PR_BGD);
  PUBLISH(GC_PR_FGD);
  PUBLISH(GC_INIT_WITH_RECT);
  PUBLISH(GC_INIT_WITH_MASK);
  PUBLISH(GC_EVAL);

1247 1248 1249 1250 1251 1252 1253
  PUBLISH(CV_ROW_SAMPLE);
  PUBLISH(CV_VAR_NUMERICAL);
  PUBLISH(CV_VAR_ORDERED);
  PUBLISH(CV_VAR_CATEGORICAL);

  PUBLISH(CV_AA);

1254 1255 1256
#include "pyopencv_generated_const_reg.h"
}