~paparazzi-uav/paparazzi/v5.0-manual

« back to all changes in this revision

Viewing changes to sw/ext/opencv_bebop/opencv/modules/python/src2/cv2.cpp

  • Committer: Paparazzi buildbot
  • Date: 2016-05-18 15:00:29 UTC
  • Revision ID: felix.ruess+docbot@gmail.com-20160518150029-e8lgzi5kvb4p7un9
Manual import commit 4b8bbb730080dac23cf816b98908dacfabe2a8ec from v5.0 branch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#if defined(_MSC_VER) && (_MSC_VER >= 1800)
 
2
// eliminating duplicated round() declaration
 
3
#define HAVE_ROUND 1
 
4
#endif
 
5
 
 
6
#include <Python.h>
 
7
 
 
8
#define MODULESTR "cv2"
 
9
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
 
10
#include <numpy/ndarrayobject.h>
 
11
 
 
12
#include "pyopencv_generated_include.h"
 
13
#include "opencv2/core/types_c.h"
 
14
 
 
15
#include "opencv2/opencv_modules.hpp"
 
16
 
 
17
#include "pycompat.hpp"
 
18
 
 
19
 
 
20
static PyObject* opencv_error = 0;
 
21
 
 
22
static int failmsg(const char *fmt, ...)
 
23
{
 
24
    char str[1000];
 
25
 
 
26
    va_list ap;
 
27
    va_start(ap, fmt);
 
28
    vsnprintf(str, sizeof(str), fmt, ap);
 
29
    va_end(ap);
 
30
 
 
31
    PyErr_SetString(PyExc_TypeError, str);
 
32
    return 0;
 
33
}
 
34
 
 
35
struct ArgInfo
 
36
{
 
37
    const char * name;
 
38
    bool outputarg;
 
39
    // more fields may be added if necessary
 
40
 
 
41
    ArgInfo(const char * name_, bool outputarg_)
 
42
        : name(name_)
 
43
        , outputarg(outputarg_) {}
 
44
 
 
45
    // to match with older pyopencv_to function signature
 
46
    operator const char *() const { return name; }
 
47
};
 
48
 
 
49
class PyAllowThreads
 
50
{
 
51
public:
 
52
    PyAllowThreads() : _state(PyEval_SaveThread()) {}
 
53
    ~PyAllowThreads()
 
54
    {
 
55
        PyEval_RestoreThread(_state);
 
56
    }
 
57
private:
 
58
    PyThreadState* _state;
 
59
};
 
60
 
 
61
class PyEnsureGIL
 
62
{
 
63
public:
 
64
    PyEnsureGIL() : _state(PyGILState_Ensure()) {}
 
65
    ~PyEnsureGIL()
 
66
    {
 
67
        PyGILState_Release(_state);
 
68
    }
 
69
private:
 
70
    PyGILState_STATE _state;
 
71
};
 
72
 
 
73
#define ERRWRAP2(expr) \
 
74
try \
 
75
{ \
 
76
    PyAllowThreads allowThreads; \
 
77
    expr; \
 
78
} \
 
79
catch (const cv::Exception &e) \
 
80
{ \
 
81
    PyErr_SetString(opencv_error, e.what()); \
 
82
    return 0; \
 
83
}
 
84
 
 
85
using namespace cv;
 
86
 
 
87
typedef std::vector<uchar> vector_uchar;
 
88
typedef std::vector<char> vector_char;
 
89
typedef std::vector<int> vector_int;
 
90
typedef std::vector<float> vector_float;
 
91
typedef std::vector<double> vector_double;
 
92
typedef std::vector<Point> vector_Point;
 
93
typedef std::vector<Point2f> vector_Point2f;
 
94
typedef std::vector<Point3f> vector_Point3f;
 
95
typedef std::vector<Vec2f> vector_Vec2f;
 
96
typedef std::vector<Vec3f> vector_Vec3f;
 
97
typedef std::vector<Vec4f> vector_Vec4f;
 
98
typedef std::vector<Vec6f> vector_Vec6f;
 
99
typedef std::vector<Vec4i> vector_Vec4i;
 
100
typedef std::vector<Rect> vector_Rect;
 
101
typedef std::vector<Rect2d> vector_Rect2d;
 
102
typedef std::vector<KeyPoint> vector_KeyPoint;
 
103
typedef std::vector<Mat> vector_Mat;
 
104
typedef std::vector<DMatch> vector_DMatch;
 
105
typedef std::vector<String> vector_String;
 
106
typedef std::vector<Scalar> vector_Scalar;
 
107
 
 
108
typedef std::vector<std::vector<char> > vector_vector_char;
 
109
typedef std::vector<std::vector<Point> > vector_vector_Point;
 
110
typedef std::vector<std::vector<Point2f> > vector_vector_Point2f;
 
111
typedef std::vector<std::vector<Point3f> > vector_vector_Point3f;
 
112
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
typedef cvflann::flann_distance_t cvflann_flann_distance_t;
 
120
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
 
 
127
static PyObject* failmsgp(const char *fmt, ...)
 
128
{
 
129
  char str[1000];
 
130
 
 
131
  va_list ap;
 
132
  va_start(ap, fmt);
 
133
  vsnprintf(str, sizeof(str), fmt, ap);
 
134
  va_end(ap);
 
135
 
 
136
  PyErr_SetString(PyExc_TypeError, str);
 
137
  return 0;
 
138
}
 
139
 
 
140
class NumpyAllocator : public MatAllocator
 
141
{
 
142
public:
 
143
    NumpyAllocator() { stdAllocator = Mat::getStdAllocator(); }
 
144
    ~NumpyAllocator() {}
 
145
 
 
146
    UMatData* allocate(PyObject* o, int dims, const int* sizes, int type, size_t* step) const
 
147
    {
 
148
        UMatData* u = new UMatData(this);
 
149
        u->data = u->origdata = (uchar*)PyArray_DATA((PyArrayObject*) o);
 
150
        npy_intp* _strides = PyArray_STRIDES((PyArrayObject*) o);
 
151
        for( int i = 0; i < dims - 1; i++ )
 
152
            step[i] = (size_t)_strides[i];
 
153
        step[dims-1] = CV_ELEM_SIZE(type);
 
154
        u->size = sizes[0]*step[0];
 
155
        u->userdata = o;
 
156
        return u;
 
157
    }
 
158
 
 
159
    UMatData* allocate(int dims0, const int* sizes, int type, void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const
 
160
    {
 
161
        if( data != 0 )
 
162
        {
 
163
            CV_Error(Error::StsAssert, "The data should normally be NULL!");
 
164
            // probably this is safe to do in such extreme case
 
165
            return stdAllocator->allocate(dims0, sizes, type, data, step, flags, usageFlags);
 
166
        }
 
167
        PyEnsureGIL gil;
 
168
 
 
169
        int depth = CV_MAT_DEPTH(type);
 
170
        int cn = CV_MAT_CN(type);
 
171
        const int f = (int)(sizeof(size_t)/8);
 
172
        int typenum = depth == CV_8U ? NPY_UBYTE : depth == CV_8S ? NPY_BYTE :
 
173
        depth == CV_16U ? NPY_USHORT : depth == CV_16S ? NPY_SHORT :
 
174
        depth == CV_32S ? NPY_INT : depth == CV_32F ? NPY_FLOAT :
 
175
        depth == CV_64F ? NPY_DOUBLE : f*NPY_ULONGLONG + (f^1)*NPY_UINT;
 
176
        int i, dims = dims0;
 
177
        cv::AutoBuffer<npy_intp> _sizes(dims + 1);
 
178
        for( i = 0; i < dims; i++ )
 
179
            _sizes[i] = sizes[i];
 
180
        if( cn > 1 )
 
181
            _sizes[dims++] = cn;
 
182
        PyObject* o = PyArray_SimpleNew(dims, _sizes, typenum);
 
183
        if(!o)
 
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
    void deallocate(UMatData* u) const
 
194
    {
 
195
        if(!u)
 
196
            return;
 
197
        PyEnsureGIL gil;
 
198
        CV_Assert(u->urefcount >= 0);
 
199
        CV_Assert(u->refcount >= 0);
 
200
        if(u->refcount == 0)
 
201
        {
 
202
            PyObject* o = (PyObject*)u->userdata;
 
203
            Py_XDECREF(o);
 
204
            delete u;
 
205
        }
 
206
    }
 
207
 
 
208
    const MatAllocator* stdAllocator;
 
209
};
 
210
 
 
211
NumpyAllocator g_numpyAllocator;
 
212
 
 
213
 
 
214
template<typename T> static
 
215
bool pyopencv_to(PyObject* obj, T& p, const char* name = "<unknown>");
 
216
 
 
217
template<typename T> static
 
218
PyObject* pyopencv_from(const T& src);
 
219
 
 
220
enum { ARG_NONE = 0, ARG_MAT = 1, ARG_SCALAR = 2 };
 
221
 
 
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;
 
226
    if(!o || o == Py_None)
 
227
    {
 
228
        if( !m.data )
 
229
            m.allocator = &g_numpyAllocator;
 
230
        return true;
 
231
    }
 
232
 
 
233
    if( PyInt_Check(o) )
 
234
    {
 
235
        double v[] = {static_cast<double>(PyInt_AsLong((PyObject*)o)), 0., 0., 0.};
 
236
        m = Mat(4, 1, CV_64F, v).clone();
 
237
        return true;
 
238
    }
 
239
    if( PyFloat_Check(o) )
 
240
    {
 
241
        double v[] = {PyFloat_AsDouble((PyObject*)o), 0., 0., 0.};
 
242
        m = Mat(4, 1, CV_64F, v).clone();
 
243
        return true;
 
244
    }
 
245
    if( PyTuple_Check(o) )
 
246
    {
 
247
        int i, sz = (int)PyTuple_Size((PyObject*)o);
 
248
        m = Mat(sz, 1, CV_64F);
 
249
        for( i = 0; i < sz; i++ )
 
250
        {
 
251
            PyObject* oi = PyTuple_GET_ITEM(o, i);
 
252
            if( PyInt_Check(oi) )
 
253
                m.at<double>(i) = (double)PyInt_AsLong(oi);
 
254
            else if( PyFloat_Check(oi) )
 
255
                m.at<double>(i) = (double)PyFloat_AsDouble(oi);
 
256
            else
 
257
            {
 
258
                failmsg("%s is not a numerical tuple", info.name);
 
259
                m.release();
 
260
                return false;
 
261
            }
 
262
        }
 
263
        return true;
 
264
    }
 
265
 
 
266
    if( !PyArray_Check(o) )
 
267
    {
 
268
        failmsg("%s is not a numpy array, neither a scalar", info.name);
 
269
        return false;
 
270
    }
 
271
 
 
272
    PyArrayObject* oarr = (PyArrayObject*) o;
 
273
 
 
274
    bool needcopy = false, needcast = false;
 
275
    int typenum = PyArray_TYPE(oarr), new_typenum = typenum;
 
276
    int type = typenum == NPY_UBYTE ? CV_8U :
 
277
               typenum == NPY_BYTE ? CV_8S :
 
278
               typenum == NPY_USHORT ? CV_16U :
 
279
               typenum == NPY_SHORT ? CV_16S :
 
280
               typenum == NPY_INT ? CV_32S :
 
281
               typenum == NPY_INT32 ? CV_32S :
 
282
               typenum == NPY_FLOAT ? CV_32F :
 
283
               typenum == NPY_DOUBLE ? CV_64F : -1;
 
284
 
 
285
    if( type < 0 )
 
286
    {
 
287
        if( typenum == NPY_INT64 || typenum == NPY_UINT64 || typenum == NPY_LONG )
 
288
        {
 
289
            needcopy = needcast = true;
 
290
            new_typenum = NPY_INT;
 
291
            type = CV_32S;
 
292
        }
 
293
        else
 
294
        {
 
295
            failmsg("%s data type = %d is not supported", info.name, typenum);
 
296
            return false;
 
297
        }
 
298
    }
 
299
 
 
300
#ifndef CV_MAX_DIM
 
301
    const int CV_MAX_DIM = 32;
 
302
#endif
 
303
 
 
304
    int ndims = PyArray_NDIM(oarr);
 
305
    if(ndims >= CV_MAX_DIM)
 
306
    {
 
307
        failmsg("%s dimensionality (=%d) is too high", info.name, ndims);
 
308
        return false;
 
309
    }
 
310
 
 
311
    int size[CV_MAX_DIM+1];
 
312
    size_t step[CV_MAX_DIM+1];
 
313
    size_t elemsize = CV_ELEM_SIZE1(type);
 
314
    const npy_intp* _sizes = PyArray_DIMS(oarr);
 
315
    const npy_intp* _strides = PyArray_STRIDES(oarr);
 
316
    bool ismultichannel = ndims == 3 && _sizes[2] <= CV_CN_MAX;
 
317
 
 
318
    for( int i = ndims-1; i >= 0 && !needcopy; i-- )
 
319
    {
 
320
        // these checks handle cases of
 
321
        //  a) multi-dimensional (ndims > 2) arrays, as well as simpler 1- and 2-dimensional cases
 
322
        //  b) transposed arrays, where _strides[] elements go in non-descending order
 
323
        //  c) flipped arrays, where some of _strides[] elements are negative
 
324
        // the _sizes[i] > 1 is needed to avoid spurious copies when NPY_RELAXED_STRIDES is set
 
325
        if( (i == ndims-1 && _sizes[i] > 1 && (size_t)_strides[i] != elemsize) ||
 
326
            (i < ndims-1 && _sizes[i] > 1 && _strides[i] < _strides[i+1]) )
 
327
            needcopy = true;
 
328
    }
 
329
 
 
330
    if( ismultichannel && _strides[1] != (npy_intp)elemsize*_sizes[2] )
 
331
        needcopy = true;
 
332
 
 
333
    if (needcopy)
 
334
    {
 
335
        if (info.outputarg)
 
336
        {
 
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
            return false;
 
339
        }
 
340
 
 
341
        if( needcast ) {
 
342
            o = PyArray_Cast(oarr, new_typenum);
 
343
            oarr = (PyArrayObject*) o;
 
344
        }
 
345
        else {
 
346
            oarr = PyArray_GETCONTIGUOUS(oarr);
 
347
            o = (PyObject*) oarr;
 
348
        }
 
349
 
 
350
        _strides = PyArray_STRIDES(oarr);
 
351
    }
 
352
 
 
353
    // Normalize strides in case NPY_RELAXED_STRIDES is set
 
354
    size_t default_step = elemsize;
 
355
    for ( int i = ndims - 1; i >= 0; --i )
 
356
    {
 
357
        size[i] = (int)_sizes[i];
 
358
        if ( size[i] > 1 )
 
359
        {
 
360
            step[i] = (size_t)_strides[i];
 
361
            default_step = step[i] * size[i];
 
362
        }
 
363
        else
 
364
        {
 
365
            step[i] = default_step;
 
366
            default_step *= size[i];
 
367
        }
 
368
    }
 
369
 
 
370
    // handle degenerate case
 
371
    if( ndims == 0) {
 
372
        size[ndims] = 1;
 
373
        step[ndims] = elemsize;
 
374
        ndims++;
 
375
    }
 
376
 
 
377
    if( ismultichannel )
 
378
    {
 
379
        ndims--;
 
380
        type |= CV_MAKETYPE(0, size[2]);
 
381
    }
 
382
 
 
383
    if( ndims > 2 && !allowND )
 
384
    {
 
385
        failmsg("%s has more than 2 dimensions", info.name);
 
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);
 
391
    m.addref();
 
392
 
 
393
    if( !needcopy )
 
394
    {
 
395
        Py_INCREF(o);
 
396
    }
 
397
    m.allocator = &g_numpyAllocator;
 
398
 
 
399
    return true;
 
400
}
 
401
 
 
402
template<>
 
403
bool pyopencv_to(PyObject* o, Mat& m, const char* name)
 
404
{
 
405
    return pyopencv_to(o, m, ArgInfo(name, 0));
 
406
}
 
407
 
 
408
template<>
 
409
PyObject* pyopencv_from(const Mat& m)
 
410
{
 
411
    if( !m.data )
 
412
        Py_RETURN_NONE;
 
413
    Mat temp, *p = (Mat*)&m;
 
414
    if(!p->u || p->allocator != &g_numpyAllocator)
 
415
    {
 
416
        temp.allocator = &g_numpyAllocator;
 
417
        ERRWRAP2(m.copyTo(temp));
 
418
        p = &temp;
 
419
    }
 
420
    PyObject* o = (PyObject*)p->u->userdata;
 
421
    Py_INCREF(o);
 
422
    return o;
 
423
}
 
424
 
 
425
template<>
 
426
bool pyopencv_to(PyObject *o, Scalar& s, const char *name)
 
427
{
 
428
    if(!o || o == Py_None)
 
429
        return true;
 
430
    if (PySequence_Check(o)) {
 
431
        PyObject *fi = PySequence_Fast(o, name);
 
432
        if (fi == NULL)
 
433
            return false;
 
434
        if (4 < PySequence_Fast_GET_SIZE(fi))
 
435
        {
 
436
            failmsg("Scalar value for argument '%s' is longer than 4", name);
 
437
            return false;
 
438
        }
 
439
        for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(fi); i++) {
 
440
            PyObject *item = PySequence_Fast_GET_ITEM(fi, i);
 
441
            if (PyFloat_Check(item) || PyInt_Check(item)) {
 
442
                s[(int)i] = PyFloat_AsDouble(item);
 
443
            } else {
 
444
                failmsg("Scalar value for argument '%s' is not numeric", name);
 
445
                return false;
 
446
            }
 
447
        }
 
448
        Py_DECREF(fi);
 
449
    } else {
 
450
        if (PyFloat_Check(o) || PyInt_Check(o)) {
 
451
            s[0] = PyFloat_AsDouble(o);
 
452
        } else {
 
453
            failmsg("Scalar value for argument '%s' is not numeric", name);
 
454
            return false;
 
455
        }
 
456
    }
 
457
    return true;
 
458
}
 
459
 
 
460
template<>
 
461
PyObject* pyopencv_from(const Scalar& src)
 
462
{
 
463
    return Py_BuildValue("(dddd)", src[0], src[1], src[2], src[3]);
 
464
}
 
465
 
 
466
template<>
 
467
PyObject* pyopencv_from(const bool& value)
 
468
{
 
469
    return PyBool_FromLong(value);
 
470
}
 
471
 
 
472
#ifdef HAVE_OPENCV_STITCHING
 
473
template<>
 
474
PyObject* pyopencv_from(const Status& value)
 
475
{
 
476
    return PyInt_FromLong(value);
 
477
}
 
478
#endif
 
479
 
 
480
template<>
 
481
bool pyopencv_to(PyObject* obj, bool& value, const char* name)
 
482
{
 
483
    (void)name;
 
484
    if(!obj || obj == Py_None)
 
485
        return true;
 
486
    int _val = PyObject_IsTrue(obj);
 
487
    if(_val < 0)
 
488
        return false;
 
489
    value = _val > 0;
 
490
    return true;
 
491
}
 
492
 
 
493
template<>
 
494
PyObject* pyopencv_from(const size_t& value)
 
495
{
 
496
    return PyLong_FromSize_t(value);
 
497
}
 
498
 
 
499
template<>
 
500
bool pyopencv_to(PyObject* obj, size_t& value, const char* name)
 
501
{
 
502
    (void)name;
 
503
    if(!obj || obj == Py_None)
 
504
        return true;
 
505
    value = (int)PyLong_AsUnsignedLong(obj);
 
506
    return value != (size_t)-1 || !PyErr_Occurred();
 
507
}
 
508
 
 
509
template<>
 
510
PyObject* pyopencv_from(const int& value)
 
511
{
 
512
    return PyInt_FromLong(value);
 
513
}
 
514
 
 
515
#ifdef HAVE_OPENCV_FLANN
 
516
template<>
 
517
PyObject* pyopencv_from(const cvflann_flann_algorithm_t& value)
 
518
{
 
519
    return PyInt_FromLong(int(value));
 
520
}
 
521
 
 
522
template<>
 
523
PyObject* pyopencv_from(const cvflann_flann_distance_t& value)
 
524
{
 
525
    return PyInt_FromLong(int(value));
 
526
}
 
527
#endif
 
528
 
 
529
template<>
 
530
bool pyopencv_to(PyObject* obj, int& value, const char* name)
 
531
{
 
532
    (void)name;
 
533
    if(!obj || obj == Py_None)
 
534
        return true;
 
535
    if(PyInt_Check(obj))
 
536
        value = (int)PyInt_AsLong(obj);
 
537
    else if(PyLong_Check(obj))
 
538
        value = (int)PyLong_AsLong(obj);
 
539
    else
 
540
        return false;
 
541
    return value != -1 || !PyErr_Occurred();
 
542
}
 
543
 
 
544
template<>
 
545
PyObject* pyopencv_from(const uchar& value)
 
546
{
 
547
    return PyInt_FromLong(value);
 
548
}
 
549
 
 
550
template<>
 
551
bool pyopencv_to(PyObject* obj, uchar& value, const char* name)
 
552
{
 
553
    (void)name;
 
554
    if(!obj || obj == Py_None)
 
555
        return true;
 
556
    int ivalue = (int)PyInt_AsLong(obj);
 
557
    value = cv::saturate_cast<uchar>(ivalue);
 
558
    return ivalue != -1 || !PyErr_Occurred();
 
559
}
 
560
 
 
561
template<>
 
562
PyObject* pyopencv_from(const double& value)
 
563
{
 
564
    return PyFloat_FromDouble(value);
 
565
}
 
566
 
 
567
template<>
 
568
bool pyopencv_to(PyObject* obj, double& value, const char* name)
 
569
{
 
570
    (void)name;
 
571
    if(!obj || obj == Py_None)
 
572
        return true;
 
573
    if(!!PyInt_CheckExact(obj))
 
574
        value = (double)PyInt_AS_LONG(obj);
 
575
    else
 
576
        value = PyFloat_AsDouble(obj);
 
577
    return !PyErr_Occurred();
 
578
}
 
579
 
 
580
template<>
 
581
PyObject* pyopencv_from(const float& value)
 
582
{
 
583
    return PyFloat_FromDouble(value);
 
584
}
 
585
 
 
586
template<>
 
587
bool pyopencv_to(PyObject* obj, float& value, const char* name)
 
588
{
 
589
    (void)name;
 
590
    if(!obj || obj == Py_None)
 
591
        return true;
 
592
    if(!!PyInt_CheckExact(obj))
 
593
        value = (float)PyInt_AS_LONG(obj);
 
594
    else
 
595
        value = (float)PyFloat_AsDouble(obj);
 
596
    return !PyErr_Occurred();
 
597
}
 
598
 
 
599
template<>
 
600
PyObject* pyopencv_from(const int64& value)
 
601
{
 
602
    return PyLong_FromLongLong(value);
 
603
}
 
604
 
 
605
template<>
 
606
PyObject* pyopencv_from(const String& value)
 
607
{
 
608
    return PyString_FromString(value.empty() ? "" : value.c_str());
 
609
}
 
610
 
 
611
template<>
 
612
bool pyopencv_to(PyObject* obj, String& value, const char* name)
 
613
{
 
614
    (void)name;
 
615
    if(!obj || obj == Py_None)
 
616
        return true;
 
617
    char* str = PyString_AsString(obj);
 
618
    if(!str)
 
619
        return false;
 
620
    value = String(str);
 
621
    return true;
 
622
}
 
623
 
 
624
template<>
 
625
bool pyopencv_to(PyObject* obj, Size& sz, const char* name)
 
626
{
 
627
    (void)name;
 
628
    if(!obj || obj == Py_None)
 
629
        return true;
 
630
    return PyArg_ParseTuple(obj, "ii", &sz.width, &sz.height) > 0;
 
631
}
 
632
 
 
633
template<>
 
634
PyObject* pyopencv_from(const Size& sz)
 
635
{
 
636
    return Py_BuildValue("(ii)", sz.width, sz.height);
 
637
}
 
638
 
 
639
template<>
 
640
bool pyopencv_to(PyObject* obj, Rect& r, const char* name)
 
641
{
 
642
    (void)name;
 
643
    if(!obj || obj == Py_None)
 
644
        return true;
 
645
    return PyArg_ParseTuple(obj, "iiii", &r.x, &r.y, &r.width, &r.height) > 0;
 
646
}
 
647
 
 
648
template<>
 
649
PyObject* pyopencv_from(const Rect& r)
 
650
{
 
651
    return Py_BuildValue("(iiii)", r.x, r.y, r.width, r.height);
 
652
}
 
653
 
 
654
template<>
 
655
bool pyopencv_to(PyObject* obj, Rect2d& r, const char* name)
 
656
{
 
657
    (void)name;
 
658
    if(!obj || obj == Py_None)
 
659
        return true;
 
660
    return PyArg_ParseTuple(obj, "dddd", &r.x, &r.y, &r.width, &r.height) > 0;
 
661
}
 
662
 
 
663
template<>
 
664
PyObject* pyopencv_from(const Rect2d& r)
 
665
{
 
666
    return Py_BuildValue("(dddd)", r.x, r.y, r.width, r.height);
 
667
}
 
668
 
 
669
template<>
 
670
bool pyopencv_to(PyObject* obj, Range& r, const char* name)
 
671
{
 
672
    (void)name;
 
673
    if(!obj || obj == Py_None)
 
674
        return true;
 
675
    if(PyObject_Size(obj) == 0)
 
676
    {
 
677
        r = Range::all();
 
678
        return true;
 
679
    }
 
680
    return PyArg_ParseTuple(obj, "ii", &r.start, &r.end) > 0;
 
681
}
 
682
 
 
683
template<>
 
684
PyObject* pyopencv_from(const Range& r)
 
685
{
 
686
    return Py_BuildValue("(ii)", r.start, r.end);
 
687
}
 
688
 
 
689
template<>
 
690
bool pyopencv_to(PyObject* obj, Point& p, const char* name)
 
691
{
 
692
    (void)name;
 
693
    if(!obj || obj == Py_None)
 
694
        return true;
 
695
    if(!!PyComplex_CheckExact(obj))
 
696
    {
 
697
        Py_complex c = PyComplex_AsCComplex(obj);
 
698
        p.x = saturate_cast<int>(c.real);
 
699
        p.y = saturate_cast<int>(c.imag);
 
700
        return true;
 
701
    }
 
702
    return PyArg_ParseTuple(obj, "ii", &p.x, &p.y) > 0;
 
703
}
 
704
 
 
705
template<>
 
706
bool pyopencv_to(PyObject* obj, Point2f& p, const char* name)
 
707
{
 
708
    (void)name;
 
709
    if(!obj || obj == Py_None)
 
710
        return true;
 
711
    if(!!PyComplex_CheckExact(obj))
 
712
    {
 
713
        Py_complex c = PyComplex_AsCComplex(obj);
 
714
        p.x = saturate_cast<float>(c.real);
 
715
        p.y = saturate_cast<float>(c.imag);
 
716
        return true;
 
717
    }
 
718
    return PyArg_ParseTuple(obj, "ff", &p.x, &p.y) > 0;
 
719
}
 
720
 
 
721
template<>
 
722
bool pyopencv_to(PyObject* obj, Point2d& p, const char* name)
 
723
{
 
724
    (void)name;
 
725
    if(!obj || obj == Py_None)
 
726
        return true;
 
727
    if(!!PyComplex_CheckExact(obj))
 
728
    {
 
729
        Py_complex c = PyComplex_AsCComplex(obj);
 
730
        p.x = saturate_cast<double>(c.real);
 
731
        p.y = saturate_cast<double>(c.imag);
 
732
        return true;
 
733
    }
 
734
    return PyArg_ParseTuple(obj, "dd", &p.x, &p.y) > 0;
 
735
}
 
736
 
 
737
template<>
 
738
bool pyopencv_to(PyObject* obj, Point3f& p, const char* name)
 
739
{
 
740
    (void)name;
 
741
    if(!obj || obj == Py_None)
 
742
        return true;
 
743
    return PyArg_ParseTuple(obj, "fff", &p.x, &p.y, &p.z) > 0;
 
744
}
 
745
 
 
746
template<>
 
747
bool pyopencv_to(PyObject* obj, Point3d& p, const char* name)
 
748
{
 
749
    (void)name;
 
750
    if(!obj || obj == Py_None)
 
751
        return true;
 
752
    return PyArg_ParseTuple(obj, "ddd", &p.x, &p.y, &p.z) > 0;
 
753
}
 
754
 
 
755
template<>
 
756
PyObject* pyopencv_from(const Point& p)
 
757
{
 
758
    return Py_BuildValue("(ii)", p.x, p.y);
 
759
}
 
760
 
 
761
template<>
 
762
PyObject* pyopencv_from(const Point2f& p)
 
763
{
 
764
    return Py_BuildValue("(dd)", p.x, p.y);
 
765
}
 
766
 
 
767
template<>
 
768
PyObject* pyopencv_from(const Point3f& p)
 
769
{
 
770
    return Py_BuildValue("(ddd)", p.x, p.y, p.z);
 
771
}
 
772
 
 
773
template<>
 
774
bool pyopencv_to(PyObject* obj, Vec3d& v, const char* name)
 
775
{
 
776
    (void)name;
 
777
    if(!obj)
 
778
        return true;
 
779
    return PyArg_ParseTuple(obj, "ddd", &v[0], &v[1], &v[2]) > 0;
 
780
}
 
781
 
 
782
template<>
 
783
PyObject* pyopencv_from(const Vec3d& v)
 
784
{
 
785
    return Py_BuildValue("(ddd)", v[0], v[1], v[2]);
 
786
}
 
787
 
 
788
template<>
 
789
PyObject* pyopencv_from(const Vec2d& v)
 
790
{
 
791
    return Py_BuildValue("(dd)", v[0], v[1]);
 
792
}
 
793
 
 
794
template<>
 
795
PyObject* pyopencv_from(const Point2d& p)
 
796
{
 
797
    return Py_BuildValue("(dd)", p.x, p.y);
 
798
}
 
799
 
 
800
template<>
 
801
PyObject* pyopencv_from(const Point3d& p)
 
802
{
 
803
    return Py_BuildValue("(ddd)", p.x, p.y, p.y);
 
804
}
 
805
 
 
806
template<typename _Tp> struct pyopencvVecConverter
 
807
{
 
808
    static bool to(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
 
809
    {
 
810
        typedef typename DataType<_Tp>::channel_type _Cp;
 
811
        if(!obj || obj == Py_None)
 
812
            return true;
 
813
        if (PyArray_Check(obj))
 
814
        {
 
815
            Mat m;
 
816
            pyopencv_to(obj, m, info);
 
817
            m.copyTo(value);
 
818
        }
 
819
        if (!PySequence_Check(obj))
 
820
            return false;
 
821
        PyObject *seq = PySequence_Fast(obj, info.name);
 
822
        if (seq == NULL)
 
823
            return false;
 
824
        int i, j, n = (int)PySequence_Fast_GET_SIZE(seq);
 
825
        value.resize(n);
 
826
 
 
827
        int type = DataType<_Tp>::type;
 
828
        int depth = CV_MAT_DEPTH(type), channels = CV_MAT_CN(type);
 
829
        PyObject** items = PySequence_Fast_ITEMS(seq);
 
830
 
 
831
        for( i = 0; i < n; i++ )
 
832
        {
 
833
            PyObject* item = items[i];
 
834
            PyObject* seq_i = 0;
 
835
            PyObject** items_i = &item;
 
836
            _Cp* data = (_Cp*)&value[i];
 
837
 
 
838
            if( channels == 2 && PyComplex_CheckExact(item) )
 
839
            {
 
840
                Py_complex c = PyComplex_AsCComplex(obj);
 
841
                data[0] = saturate_cast<_Cp>(c.real);
 
842
                data[1] = saturate_cast<_Cp>(c.imag);
 
843
                continue;
 
844
            }
 
845
            if( channels > 1 )
 
846
            {
 
847
                if( PyArray_Check(item))
 
848
                {
 
849
                    Mat src;
 
850
                    pyopencv_to(item, src, info);
 
851
                    if( src.dims != 2 || src.channels() != 1 ||
 
852
                       ((src.cols != 1 || src.rows != channels) &&
 
853
                        (src.cols != channels || src.rows != 1)))
 
854
                        break;
 
855
                    Mat dst(src.rows, src.cols, depth, data);
 
856
                    src.convertTo(dst, type);
 
857
                    if( dst.data != (uchar*)data )
 
858
                        break;
 
859
                    continue;
 
860
                }
 
861
 
 
862
                seq_i = PySequence_Fast(item, info.name);
 
863
                if( !seq_i || (int)PySequence_Fast_GET_SIZE(seq_i) != channels )
 
864
                {
 
865
                    Py_XDECREF(seq_i);
 
866
                    break;
 
867
                }
 
868
                items_i = PySequence_Fast_ITEMS(seq_i);
 
869
            }
 
870
 
 
871
            for( j = 0; j < channels; j++ )
 
872
            {
 
873
                PyObject* item_ij = items_i[j];
 
874
                if( PyInt_Check(item_ij))
 
875
                {
 
876
                    int v = (int)PyInt_AsLong(item_ij);
 
877
                    if( v == -1 && PyErr_Occurred() )
 
878
                        break;
 
879
                    data[j] = saturate_cast<_Cp>(v);
 
880
                }
 
881
                else if( PyLong_Check(item_ij))
 
882
                {
 
883
                    int v = (int)PyLong_AsLong(item_ij);
 
884
                    if( v == -1 && PyErr_Occurred() )
 
885
                        break;
 
886
                    data[j] = saturate_cast<_Cp>(v);
 
887
                }
 
888
                else if( PyFloat_Check(item_ij))
 
889
                {
 
890
                    double v = PyFloat_AsDouble(item_ij);
 
891
                    if( PyErr_Occurred() )
 
892
                        break;
 
893
                    data[j] = saturate_cast<_Cp>(v);
 
894
                }
 
895
                else
 
896
                    break;
 
897
            }
 
898
            Py_XDECREF(seq_i);
 
899
            if( j < channels )
 
900
                break;
 
901
        }
 
902
        Py_DECREF(seq);
 
903
        return i == n;
 
904
    }
 
905
 
 
906
    static PyObject* from(const std::vector<_Tp>& value)
 
907
    {
 
908
        if(value.empty())
 
909
            return PyTuple_New(0);
 
910
        Mat src((int)value.size(), DataType<_Tp>::channels, DataType<_Tp>::depth, (uchar*)&value[0]);
 
911
        return pyopencv_from(src);
 
912
    }
 
913
};
 
914
 
 
915
template<typename _Tp>
 
916
bool pyopencv_to(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
 
917
{
 
918
    return pyopencvVecConverter<_Tp>::to(obj, value, info);
 
919
}
 
920
 
 
921
template<typename _Tp>
 
922
PyObject* pyopencv_from(const std::vector<_Tp>& value)
 
923
{
 
924
    return pyopencvVecConverter<_Tp>::from(value);
 
925
}
 
926
 
 
927
template<typename _Tp> static inline bool pyopencv_to_generic_vec(PyObject* obj, std::vector<_Tp>& value, const ArgInfo info)
 
928
{
 
929
    if(!obj || obj == Py_None)
 
930
       return true;
 
931
    if (!PySequence_Check(obj))
 
932
        return false;
 
933
    PyObject *seq = PySequence_Fast(obj, info.name);
 
934
    if (seq == NULL)
 
935
        return false;
 
936
    int i, n = (int)PySequence_Fast_GET_SIZE(seq);
 
937
    value.resize(n);
 
938
 
 
939
    PyObject** items = PySequence_Fast_ITEMS(seq);
 
940
 
 
941
    for( i = 0; i < n; i++ )
 
942
    {
 
943
        PyObject* item = items[i];
 
944
        if(!pyopencv_to(item, value[i], info))
 
945
            break;
 
946
    }
 
947
    Py_DECREF(seq);
 
948
    return i == n;
 
949
}
 
950
 
 
951
template<typename _Tp> static inline PyObject* pyopencv_from_generic_vec(const std::vector<_Tp>& value)
 
952
{
 
953
    int i, n = (int)value.size();
 
954
    PyObject* seq = PyList_New(n);
 
955
    for( i = 0; i < n; i++ )
 
956
    {
 
957
        PyObject* item = pyopencv_from(value[i]);
 
958
        if(!item)
 
959
            break;
 
960
        PyList_SET_ITEM(seq, i, item);
 
961
    }
 
962
    if( i < n )
 
963
    {
 
964
        Py_DECREF(seq);
 
965
        return 0;
 
966
    }
 
967
    return seq;
 
968
}
 
969
 
 
970
 
 
971
template<typename _Tp> struct pyopencvVecConverter<std::vector<_Tp> >
 
972
{
 
973
    static bool to(PyObject* obj, std::vector<std::vector<_Tp> >& value, const ArgInfo info)
 
974
    {
 
975
        return pyopencv_to_generic_vec(obj, value, info);
 
976
    }
 
977
 
 
978
    static PyObject* from(const std::vector<std::vector<_Tp> >& value)
 
979
    {
 
980
        return pyopencv_from_generic_vec(value);
 
981
    }
 
982
};
 
983
 
 
984
template<> struct pyopencvVecConverter<Mat>
 
985
{
 
986
    static bool to(PyObject* obj, std::vector<Mat>& value, const ArgInfo info)
 
987
    {
 
988
        return pyopencv_to_generic_vec(obj, value, info);
 
989
    }
 
990
 
 
991
    static PyObject* from(const std::vector<Mat>& value)
 
992
    {
 
993
        return pyopencv_from_generic_vec(value);
 
994
    }
 
995
};
 
996
 
 
997
template<> struct pyopencvVecConverter<KeyPoint>
 
998
{
 
999
    static bool to(PyObject* obj, std::vector<KeyPoint>& value, const ArgInfo info)
 
1000
    {
 
1001
        return pyopencv_to_generic_vec(obj, value, info);
 
1002
    }
 
1003
 
 
1004
    static PyObject* from(const std::vector<KeyPoint>& value)
 
1005
    {
 
1006
        return pyopencv_from_generic_vec(value);
 
1007
    }
 
1008
};
 
1009
 
 
1010
template<> struct pyopencvVecConverter<DMatch>
 
1011
{
 
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
        return pyopencv_from_generic_vec(value);
 
1020
    }
 
1021
};
 
1022
 
 
1023
template<> struct pyopencvVecConverter<String>
 
1024
{
 
1025
    static bool to(PyObject* obj, std::vector<String>& value, const ArgInfo info)
 
1026
    {
 
1027
        return pyopencv_to_generic_vec(obj, value, info);
 
1028
    }
 
1029
 
 
1030
    static PyObject* from(const std::vector<String>& value)
 
1031
    {
 
1032
        return pyopencv_from_generic_vec(value);
 
1033
    }
 
1034
};
 
1035
 
 
1036
template<>
 
1037
bool pyopencv_to(PyObject *obj, TermCriteria& dst, const char *name)
 
1038
{
 
1039
    (void)name;
 
1040
    if(!obj)
 
1041
        return true;
 
1042
    return PyArg_ParseTuple(obj, "iid", &dst.type, &dst.maxCount, &dst.epsilon) > 0;
 
1043
}
 
1044
 
 
1045
template<>
 
1046
PyObject* pyopencv_from(const TermCriteria& src)
 
1047
{
 
1048
    return Py_BuildValue("(iid)", src.type, src.maxCount, src.epsilon);
 
1049
}
 
1050
 
 
1051
template<>
 
1052
bool pyopencv_to(PyObject *obj, RotatedRect& dst, const char *name)
 
1053
{
 
1054
    (void)name;
 
1055
    if(!obj)
 
1056
        return true;
 
1057
    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
template<>
 
1061
PyObject* pyopencv_from(const RotatedRect& src)
 
1062
{
 
1063
    return Py_BuildValue("((ff)(ff)f)", src.center.x, src.center.y, src.size.width, src.size.height, src.angle);
 
1064
}
 
1065
 
 
1066
template<>
 
1067
PyObject* pyopencv_from(const Moments& m)
 
1068
{
 
1069
    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}",
 
1070
                         "m00", m.m00, "m10", m.m10, "m01", m.m01,
 
1071
                         "m20", m.m20, "m11", m.m11, "m02", m.m02,
 
1072
                         "m30", m.m30, "m21", m.m21, "m12", m.m12, "m03", m.m03,
 
1073
                         "mu20", m.mu20, "mu11", m.mu11, "mu02", m.mu02,
 
1074
                         "mu30", m.mu30, "mu21", m.mu21, "mu12", m.mu12, "mu03", m.mu03,
 
1075
                         "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
template<>
 
1081
bool pyopencv_to(PyObject *o, cv::flann::IndexParams& p, const char *name)
 
1082
{
 
1083
    (void)name;
 
1084
    bool ok = true;
 
1085
    PyObject* key = NULL;
 
1086
    PyObject* item = NULL;
 
1087
    Py_ssize_t pos = 0;
 
1088
 
 
1089
    if(PyDict_Check(o)) {
 
1090
        while(PyDict_Next(o, &pos, &key, &item)) {
 
1091
            if( !PyString_Check(key) ) {
 
1092
                ok = false;
 
1093
                break;
 
1094
            }
 
1095
 
 
1096
            String k = PyString_AsString(key);
 
1097
            if( PyString_Check(item) )
 
1098
            {
 
1099
                const char* value = PyString_AsString(item);
 
1100
                p.setString(k, value);
 
1101
            }
 
1102
            else if( !!PyBool_Check(item) )
 
1103
                p.setBool(k, item == Py_True);
 
1104
            else if( PyInt_Check(item) )
 
1105
            {
 
1106
                int value = (int)PyInt_AsLong(item);
 
1107
                if( strcmp(k.c_str(), "algorithm") == 0 )
 
1108
                    p.setAlgorithm(value);
 
1109
                else
 
1110
                    p.setInt(k, value);
 
1111
            }
 
1112
            else if( PyFloat_Check(item) )
 
1113
            {
 
1114
                double value = PyFloat_AsDouble(item);
 
1115
                p.setDouble(k, value);
 
1116
            }
 
1117
            else
 
1118
            {
 
1119
                ok = false;
 
1120
                break;
 
1121
            }
 
1122
        }
 
1123
    }
 
1124
 
 
1125
    return ok && !PyErr_Occurred();
 
1126
}
 
1127
 
 
1128
template<>
 
1129
bool pyopencv_to(PyObject* obj, cv::flann::SearchParams & value, const char * name)
 
1130
{
 
1131
    return pyopencv_to<cv::flann::IndexParams>(obj, value, name);
 
1132
}
 
1133
#endif
 
1134
 
 
1135
template <typename T>
 
1136
bool pyopencv_to(PyObject *o, Ptr<T>& p, const char *name)
 
1137
{
 
1138
    p = makePtr<T>();
 
1139
    return pyopencv_to(o, *p, name);
 
1140
}
 
1141
 
 
1142
#ifdef HAVE_OPENCV_FLANN
 
1143
template<>
 
1144
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
    return ok;
 
1150
}
 
1151
#endif
 
1152
 
 
1153
 
 
1154
////////////////////////////////////////////////////////////////////////////////////////////////////
 
1155
// TODO: REMOVE used only by ml wrapper
 
1156
 
 
1157
template<>
 
1158
bool pyopencv_to(PyObject *obj, CvTermCriteria& dst, const char *name)
 
1159
{
 
1160
    (void)name;
 
1161
    if(!obj)
 
1162
        return true;
 
1163
    return PyArg_ParseTuple(obj, "iid", &dst.type, &dst.max_iter, &dst.epsilon) > 0;
 
1164
}
 
1165
 
 
1166
template<>
 
1167
bool pyopencv_to(PyObject* obj, CvSlice& r, const char* name)
 
1168
{
 
1169
    (void)name;
 
1170
    if(!obj || obj == Py_None)
 
1171
        return true;
 
1172
    if(PyObject_Size(obj) == 0)
 
1173
    {
 
1174
        r = CV_WHOLE_SEQ;
 
1175
        return true;
 
1176
    }
 
1177
    return PyArg_ParseTuple(obj, "ii", &r.start_index, &r.end_index) > 0;
 
1178
}
 
1179
 
 
1180
////////////////////////////////////////////////////////////////////////////////////////////////////
 
1181
 
 
1182
static void OnMouse(int event, int x, int y, int flags, void* param)
 
1183
{
 
1184
    PyGILState_STATE gstate;
 
1185
    gstate = PyGILState_Ensure();
 
1186
 
 
1187
    PyObject *o = (PyObject*)param;
 
1188
    PyObject *args = Py_BuildValue("iiiiO", event, x, y, flags, PyTuple_GetItem(o, 1));
 
1189
 
 
1190
    PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL);
 
1191
    if (r == NULL)
 
1192
        PyErr_Print();
 
1193
    else
 
1194
        Py_DECREF(r);
 
1195
    Py_DECREF(args);
 
1196
    PyGILState_Release(gstate);
 
1197
}
 
1198
 
 
1199
#ifdef HAVE_OPENCV_HIGHGUI
 
1200
static PyObject *pycvSetMouseCallback(PyObject*, PyObject *args, PyObject *kw)
 
1201
{
 
1202
    const char *keywords[] = { "window_name", "on_mouse", "param", NULL };
 
1203
    char* name;
 
1204
    PyObject *on_mouse;
 
1205
    PyObject *param = NULL;
 
1206
 
 
1207
    if (!PyArg_ParseTupleAndKeywords(args, kw, "sO|O", (char**)keywords, &name, &on_mouse, &param))
 
1208
        return NULL;
 
1209
    if (!PyCallable_Check(on_mouse)) {
 
1210
        PyErr_SetString(PyExc_TypeError, "on_mouse must be callable");
 
1211
        return NULL;
 
1212
    }
 
1213
    if (param == NULL) {
 
1214
        param = Py_None;
 
1215
    }
 
1216
    ERRWRAP2(setMouseCallback(name, OnMouse, Py_BuildValue("OO", on_mouse, param)));
 
1217
    Py_RETURN_NONE;
 
1218
}
 
1219
#endif
 
1220
 
 
1221
static void OnChange(int pos, void *param)
 
1222
{
 
1223
    PyGILState_STATE gstate;
 
1224
    gstate = PyGILState_Ensure();
 
1225
 
 
1226
    PyObject *o = (PyObject*)param;
 
1227
    PyObject *args = Py_BuildValue("(i)", pos);
 
1228
    PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL);
 
1229
    if (r == NULL)
 
1230
        PyErr_Print();
 
1231
    Py_DECREF(args);
 
1232
    PyGILState_Release(gstate);
 
1233
}
 
1234
 
 
1235
#ifdef HAVE_OPENCV_HIGHGUI
 
1236
static PyObject *pycvCreateTrackbar(PyObject*, PyObject *args)
 
1237
{
 
1238
    PyObject *on_change;
 
1239
    char* trackbar_name;
 
1240
    char* window_name;
 
1241
    int *value = new int;
 
1242
    int count;
 
1243
 
 
1244
    if (!PyArg_ParseTuple(args, "ssiiO", &trackbar_name, &window_name, value, &count, &on_change))
 
1245
        return NULL;
 
1246
    if (!PyCallable_Check(on_change)) {
 
1247
        PyErr_SetString(PyExc_TypeError, "on_change must be callable");
 
1248
        return NULL;
 
1249
    }
 
1250
    ERRWRAP2(createTrackbar(trackbar_name, window_name, value, count, OnChange, Py_BuildValue("OO", on_change, Py_None)));
 
1251
    Py_RETURN_NONE;
 
1252
}
 
1253
#endif
 
1254
 
 
1255
///////////////////////////////////////////////////////////////////////////////////////
 
1256
 
 
1257
static int convert_to_char(PyObject *o, char *dst, const char *name = "no_name")
 
1258
{
 
1259
  if (PyString_Check(o) && PyString_Size(o) == 1) {
 
1260
    *dst = PyString_AsString(o)[0];
 
1261
    return 1;
 
1262
  } else {
 
1263
    (*dst) = 0;
 
1264
    return failmsg("Expected single character string for argument '%s'", name);
 
1265
  }
 
1266
}
 
1267
 
 
1268
#if PY_MAJOR_VERSION >= 3
 
1269
#define MKTYPE2(NAME) pyopencv_##NAME##_specials(); if (!to_ok(&pyopencv_##NAME##_Type)) return NULL;
 
1270
#else
 
1271
#define MKTYPE2(NAME) pyopencv_##NAME##_specials(); if (!to_ok(&pyopencv_##NAME##_Type)) return
 
1272
#endif
 
1273
 
 
1274
#ifdef __GNUC__
 
1275
#  pragma GCC diagnostic ignored "-Wunused-parameter"
 
1276
#  pragma GCC diagnostic ignored "-Wmissing-field-initializers"
 
1277
#endif
 
1278
 
 
1279
#include "pyopencv_generated_types.h"
 
1280
#include "pyopencv_generated_funcs.h"
 
1281
 
 
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
  {NULL, NULL},
 
1288
};
 
1289
 
 
1290
/************************************************************************/
 
1291
/* Module init */
 
1292
 
 
1293
struct ConstDef
 
1294
{
 
1295
    const char * name;
 
1296
    long val;
 
1297
};
 
1298
 
 
1299
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
  size_t i = s.find('.');
 
1304
  while (i < s.length() && i != std::string::npos)
 
1305
  {
 
1306
    size_t j = s.find('.', i);
 
1307
    if (j == std::string::npos)
 
1308
        j = s.length();
 
1309
    std::string short_name = s.substr(i, j-i);
 
1310
    std::string full_name = s.substr(0, j);
 
1311
    i = j+1;
 
1312
 
 
1313
    PyObject * d = PyModule_GetDict(root);
 
1314
    PyObject * submod = PyDict_GetItemString(d, short_name.c_str());
 
1315
    if (submod == NULL)
 
1316
    {
 
1317
        submod = PyImport_AddModule(full_name.c_str());
 
1318
        PyDict_SetItemString(d, short_name.c_str(), submod);
 
1319
    }
 
1320
 
 
1321
    if (short_name != "")
 
1322
        root = submod;
 
1323
  }
 
1324
 
 
1325
  // populate module's dict
 
1326
  PyObject * d = PyModule_GetDict(root);
 
1327
  for (PyMethodDef * m = methods; m->ml_name != NULL; ++m)
 
1328
  {
 
1329
    PyObject * method_obj = PyCFunction_NewEx(m, NULL, NULL);
 
1330
    PyDict_SetItemString(d, m->ml_name, method_obj);
 
1331
    Py_DECREF(method_obj);
 
1332
  }
 
1333
  for (ConstDef * c = consts; c->name != NULL; ++c)
 
1334
  {
 
1335
    PyDict_SetItemString(d, c->name, PyInt_FromLong(c->val));
 
1336
  }
 
1337
 
 
1338
}
 
1339
 
 
1340
#include "pyopencv_generated_ns_reg.h"
 
1341
 
 
1342
static int to_ok(PyTypeObject *to)
 
1343
{
 
1344
  to->tp_alloc = PyType_GenericAlloc;
 
1345
  to->tp_new = PyType_GenericNew;
 
1346
  to->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
 
1347
  return (PyType_Ready(to) == 0);
 
1348
}
 
1349
 
 
1350
 
 
1351
#if PY_MAJOR_VERSION >= 3
 
1352
extern "C" CV_EXPORTS PyObject* PyInit_cv2();
 
1353
static struct PyModuleDef cv2_moduledef =
 
1354
{
 
1355
    PyModuleDef_HEAD_INIT,
 
1356
    MODULESTR,
 
1357
    "Python wrapper for OpenCV.",
 
1358
    -1,     /* size of per-interpreter state of the module,
 
1359
               or -1 if the module keeps state in global variables. */
 
1360
    special_methods
 
1361
};
 
1362
 
 
1363
PyObject* PyInit_cv2()
 
1364
#else
 
1365
extern "C" CV_EXPORTS void initcv2();
 
1366
 
 
1367
void initcv2()
 
1368
#endif
 
1369
{
 
1370
  import_array();
 
1371
 
 
1372
#include "pyopencv_generated_type_reg.h"
 
1373
 
 
1374
#if PY_MAJOR_VERSION >= 3
 
1375
  PyObject* m = PyModule_Create(&cv2_moduledef);
 
1376
#else
 
1377
  PyObject* m = Py_InitModule(MODULESTR, special_methods);
 
1378
#endif
 
1379
  init_submodules(m); // from "pyopencv_generated_ns_reg.h"
 
1380
 
 
1381
  PyObject* d = PyModule_GetDict(m);
 
1382
 
 
1383
  PyDict_SetItemString(d, "__version__", PyString_FromString(CV_VERSION));
 
1384
 
 
1385
  opencv_error = PyErr_NewException((char*)MODULESTR".error", NULL, NULL);
 
1386
  PyDict_SetItemString(d, "error", opencv_error);
 
1387
 
 
1388
#define PUBLISH(I) PyDict_SetItemString(d, #I, PyInt_FromLong(I))
 
1389
//#define PUBLISHU(I) PyDict_SetItemString(d, #I, PyLong_FromUnsignedLong(I))
 
1390
#define PUBLISH2(I, value) PyDict_SetItemString(d, #I, PyLong_FromLong(value))
 
1391
 
 
1392
  PUBLISH(CV_8U);
 
1393
  PUBLISH(CV_8UC1);
 
1394
  PUBLISH(CV_8UC2);
 
1395
  PUBLISH(CV_8UC3);
 
1396
  PUBLISH(CV_8UC4);
 
1397
  PUBLISH(CV_8S);
 
1398
  PUBLISH(CV_8SC1);
 
1399
  PUBLISH(CV_8SC2);
 
1400
  PUBLISH(CV_8SC3);
 
1401
  PUBLISH(CV_8SC4);
 
1402
  PUBLISH(CV_16U);
 
1403
  PUBLISH(CV_16UC1);
 
1404
  PUBLISH(CV_16UC2);
 
1405
  PUBLISH(CV_16UC3);
 
1406
  PUBLISH(CV_16UC4);
 
1407
  PUBLISH(CV_16S);
 
1408
  PUBLISH(CV_16SC1);
 
1409
  PUBLISH(CV_16SC2);
 
1410
  PUBLISH(CV_16SC3);
 
1411
  PUBLISH(CV_16SC4);
 
1412
  PUBLISH(CV_32S);
 
1413
  PUBLISH(CV_32SC1);
 
1414
  PUBLISH(CV_32SC2);
 
1415
  PUBLISH(CV_32SC3);
 
1416
  PUBLISH(CV_32SC4);
 
1417
  PUBLISH(CV_32F);
 
1418
  PUBLISH(CV_32FC1);
 
1419
  PUBLISH(CV_32FC2);
 
1420
  PUBLISH(CV_32FC3);
 
1421
  PUBLISH(CV_32FC4);
 
1422
  PUBLISH(CV_64F);
 
1423
  PUBLISH(CV_64FC1);
 
1424
  PUBLISH(CV_64FC2);
 
1425
  PUBLISH(CV_64FC3);
 
1426
  PUBLISH(CV_64FC4);
 
1427
 
 
1428
#if PY_MAJOR_VERSION >= 3
 
1429
    return m;
 
1430
#endif
 
1431
}