cv2.cpp 68.1 KB
Newer Older
1 2
//warning number '5033' not a valid compiler warning in vc12
#if defined(_MSC_VER) && (_MSC_VER > 1800)
3
// eliminating duplicated round() declaration
4
#define HAVE_ROUND 1
5 6
#pragma warning(push)
#pragma warning(disable:5033)  // 'register' is no longer a supported storage class
7
#endif
8 9 10 11 12 13 14 15

// #define CVPY_DYNAMIC_INIT
// #define Py_DEBUG

#if defined(CVPY_DYNAMIC_INIT) && !defined(Py_DEBUG)
#   define Py_LIMITED_API 0x03030000
#endif

16
#include <cmath>
17
#include <Python.h>
18
#include <limits>
19 20 21

#if PY_MAJOR_VERSION < 3
#undef CVPY_DYNAMIC_INIT
22 23
#else
#define CV_PYTHON_3 1
24 25
#endif

26
#if defined(_MSC_VER) && (_MSC_VER > 1800)
27 28
#pragma warning(pop)
#endif
29

30 31 32 33
#define MODULESTR "cv2"
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/ndarrayobject.h>

34 35
#include "opencv2/opencv_modules.hpp"
#include "opencv2/core.hpp"
36 37
#include "opencv2/core/utils/configuration.private.hpp"
#include "opencv2/core/utils/logger.hpp"
38
#include "opencv2/core/utils/tls.hpp"
39

40 41 42 43 44
#include "pyopencv_generated_include.h"
#include "opencv2/core/types_c.h"
#include "pycompat.hpp"
#include <map>

45 46
#define CV_HAS_CONVERSION_ERROR(x) (((x) == -1) && PyErr_Occurred())

47
static PyObject* opencv_error = NULL;
48

A
Alexander Alekhin 已提交
49 50 51
class ArgInfo
{
public:
52
    const char* name;
A
Alexander Alekhin 已提交
53 54 55
    bool outputarg;
    // more fields may be added if necessary

56
    ArgInfo(const char* name_, bool outputarg_) : name(name_), outputarg(outputarg_) {}
A
Alexander Alekhin 已提交
57 58 59 60 61 62

private:
    ArgInfo(const ArgInfo&); // = delete
    ArgInfo& operator=(const ArgInfo&); // = delete
};

63 64 65
template<typename T, class TEnable = void>  // TEnable is used for SFINAE checks
struct PyOpenCV_Converter
{
A
Alexander Alekhin 已提交
66
    //static inline bool to(PyObject* obj, T& p, const ArgInfo& info);
67 68 69
    //static inline PyObject* from(const T& src);
};

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
// exception-safe pyopencv_to
template<typename _Tp> static
bool pyopencv_to_safe(PyObject* obj, _Tp& value, const ArgInfo& info)
{
    try
    {
        return pyopencv_to(obj, value, info);
    }
    catch (const std::exception &e)
    {
        PyErr_SetString(opencv_error, cv::format("Conversion error: %s, what: %s", info.name, e.what()).c_str());
        return false;
    }
    catch (...)
    {
        PyErr_SetString(opencv_error, cv::format("Conversion error: %s", info.name).c_str());
        return false;
    }
}

90
template<typename T> static
A
Alexander Alekhin 已提交
91
bool pyopencv_to(PyObject* obj, T& p, const ArgInfo& info) { return PyOpenCV_Converter<T>::to(obj, p, info); }
92 93 94 95

template<typename T> static
PyObject* pyopencv_from(const T& src) { return PyOpenCV_Converter<T>::from(src); }

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
static bool isPythonBindingsDebugEnabled()
{
    static bool param_debug = cv::utils::getConfigurationParameterBool("OPENCV_PYTHON_DEBUG", false);
    return param_debug;
}

static void emit_failmsg(PyObject * exc, const char *msg)
{
    static bool param_debug = isPythonBindingsDebugEnabled();
    if (param_debug)
    {
        CV_LOG_WARNING(NULL, "Bindings conversion failed: " << msg);
    }
    PyErr_SetString(exc, msg);
}

112 113 114
static int failmsg(const char *fmt, ...)
{
    char str[1000];
115

116 117 118 119
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(str, sizeof(str), fmt, ap);
    va_end(ap);
120

121 122 123 124 125 126 127 128 129 130 131 132 133 134
    emit_failmsg(PyExc_TypeError, str);
    return 0;
}

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

    emit_failmsg(PyExc_TypeError, str);
135 136 137
    return 0;
}

138 139 140 141
class PyAllowThreads
{
public:
    PyAllowThreads() : _state(PyEval_SaveThread()) {}
142
    ~PyAllowThreads()
143 144 145 146 147 148 149
    {
        PyEval_RestoreThread(_state);
    }
private:
    PyThreadState* _state;
};

A
Alexander Mordvintsev 已提交
150 151 152 153
class PyEnsureGIL
{
public:
    PyEnsureGIL() : _state(PyGILState_Ensure()) {}
154
    ~PyEnsureGIL()
A
Alexander Mordvintsev 已提交
155 156 157 158 159 160 161
    {
        PyGILState_Release(_state);
    }
private:
    PyGILState_STATE _state;
};

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
/**
 * Light weight RAII wrapper for `PyObject*` owning references.
 * In comparisson to C++11 `std::unique_ptr` with custom deleter, it provides
 * implicit conversion functions that might be useful to initialize it with
 * Python functions those returns owning references through the `PyObject**`
 * e.g. `PyErr_Fetch` or directly pass it to functions those want to borrow
 * reference to object (doesn't extend object lifetime) e.g. `PyObject_Str`.
 */
class PySafeObject
{
public:
    PySafeObject() : obj_(NULL) {}

    explicit PySafeObject(PyObject* obj) : obj_(obj) {}

    ~PySafeObject()
    {
        Py_CLEAR(obj_);
    }

    operator PyObject*()
    {
        return obj_;
    }

    operator PyObject**()
    {
        return &obj_;
    }

    PyObject* release()
    {
        PyObject* obj = obj_;
        obj_ = NULL;
        return obj;
    }

private:
    PyObject* obj_;

    // Explicitly disable copy operations
    PySafeObject(const PySafeObject*); // = delete
    PySafeObject& operator=(const PySafeObject&); // = delete
};

207 208 209 210 211 212 213 214 215 216 217
static void pyRaiseCVException(const cv::Exception &e)
{
    PyObject_SetAttrString(opencv_error, "file", PyString_FromString(e.file.c_str()));
    PyObject_SetAttrString(opencv_error, "func", PyString_FromString(e.func.c_str()));
    PyObject_SetAttrString(opencv_error, "line", PyInt_FromLong(e.line));
    PyObject_SetAttrString(opencv_error, "code", PyInt_FromLong(e.code));
    PyObject_SetAttrString(opencv_error, "msg", PyString_FromString(e.msg.c_str()));
    PyObject_SetAttrString(opencv_error, "err", PyString_FromString(e.err.c_str()));
    PyErr_SetString(opencv_error, e.what());
}

218 219 220
#define ERRWRAP2(expr) \
try \
{ \
221
    PyAllowThreads allowThreads; \
222 223 224 225
    expr; \
} \
catch (const cv::Exception &e) \
{ \
226
    pyRaiseCVException(e); \
227
    return 0; \
228 229 230 231 232
} \
catch (const std::exception &e) \
{ \
    PyErr_SetString(opencv_error, e.what()); \
    return 0; \
233 234 235 236 237
} \
catch (...) \
{ \
    PyErr_SetString(opencv_error, "Unknown C++ exception from OpenCV code"); \
    return 0; \
238 239
}

V
Vadim Pisarevsky 已提交
240 241
using namespace cv;

242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368

namespace {
template<class T>
NPY_TYPES asNumpyType()
{
    return NPY_OBJECT;
}

template<>
NPY_TYPES asNumpyType<bool>()
{
    return NPY_BOOL;
}

#define CV_GENERATE_INTEGRAL_TYPE_NPY_CONVERSION(src, dst) \
    template<>                                             \
    NPY_TYPES asNumpyType<src>()                           \
    {                                                      \
        return NPY_##dst;                                  \
    }                                                      \
    template<>                                             \
    NPY_TYPES asNumpyType<u##src>()                        \
    {                                                      \
        return NPY_U##dst;                                 \
    }

CV_GENERATE_INTEGRAL_TYPE_NPY_CONVERSION(int8_t, INT8);

CV_GENERATE_INTEGRAL_TYPE_NPY_CONVERSION(int16_t, INT16);

CV_GENERATE_INTEGRAL_TYPE_NPY_CONVERSION(int32_t, INT32);

CV_GENERATE_INTEGRAL_TYPE_NPY_CONVERSION(int64_t, INT64);

#undef CV_GENERATE_INTEGRAL_TYPE_NPY_CONVERSION

template<>
NPY_TYPES asNumpyType<float>()
{
    return NPY_FLOAT;
}

template<>
NPY_TYPES asNumpyType<double>()
{
    return NPY_DOUBLE;
}

template <class T>
PyArray_Descr* getNumpyTypeDescriptor()
{
    return PyArray_DescrFromType(asNumpyType<T>());
}

template <>
PyArray_Descr* getNumpyTypeDescriptor<size_t>()
{
#if SIZE_MAX == ULONG_MAX
    return PyArray_DescrFromType(NPY_ULONG);
#elif SIZE_MAX == ULLONG_MAX
    return PyArray_DescrFromType(NPY_ULONGLONG);
#else
    return PyArray_DescrFromType(NPY_UINT);
#endif
}

template <class T, class U>
bool isRepresentable(U value) {
    return (std::numeric_limits<T>::min() <= value) && (value <= std::numeric_limits<T>::max());
}

template<class T>
bool canBeSafelyCasted(PyObject* obj, PyArray_Descr* to)
{
    return PyArray_CanCastTo(PyArray_DescrFromScalar(obj), to) != 0;
}


template<>
bool canBeSafelyCasted<size_t>(PyObject* obj, PyArray_Descr* to)
{
    PyArray_Descr* from = PyArray_DescrFromScalar(obj);
    if (PyArray_CanCastTo(from, to))
    {
        return true;
    }
    else
    {
        // False negative scenarios:
        // - Signed input is positive so it can be safely cast to unsigned output
        // - Input has wider limits but value is representable within output limits
        // - All the above
        if (PyDataType_ISSIGNED(from))
        {
            int64_t input = 0;
            PyArray_CastScalarToCtype(obj, &input, getNumpyTypeDescriptor<int64_t>());
            return (input >= 0) && isRepresentable<size_t>(static_cast<uint64_t>(input));
        }
        else
        {
            uint64_t input = 0;
            PyArray_CastScalarToCtype(obj, &input, getNumpyTypeDescriptor<uint64_t>());
            return isRepresentable<size_t>(input);
        }
        return false;
    }
}


template<class T>
bool parseNumpyScalar(PyObject* obj, T& value)
{
    if (PyArray_CheckScalar(obj))
    {
        // According to the numpy documentation:
        // There are 21 statically-defined PyArray_Descr objects for the built-in data-types
        // So descriptor pointer is not owning.
        PyArray_Descr* to = getNumpyTypeDescriptor<T>();
        if (canBeSafelyCasted<T>(obj, to))
        {
            PyArray_CastScalarToCtype(obj, &value, to);
            return true;
        }
    }
    return false;
}

369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
TLSData<std::vector<std::string> > conversionErrorsTLS;

inline void pyPrepareArgumentConversionErrorsStorage(std::size_t size)
{
    std::vector<std::string>& conversionErrors = conversionErrorsTLS.getRef();
    conversionErrors.clear();
    conversionErrors.reserve(size);
}

void pyRaiseCVOverloadException(const std::string& functionName)
{
    const std::vector<std::string>& conversionErrors = conversionErrorsTLS.getRef();
    const std::size_t conversionErrorsCount = conversionErrors.size();
    if (conversionErrorsCount > 0)
    {
        // In modern std libraries small string optimization is used = no dynamic memory allocations,
        // but it can be applied only for string with length < 18 symbols (in GCC)
        const std::string bullet = "\n - ";

        // Estimate required buffer size - save dynamic memory allocations = faster
        std::size_t requiredBufferSize = bullet.size() * conversionErrorsCount;
        for (std::size_t i = 0; i < conversionErrorsCount; ++i)
        {
            requiredBufferSize += conversionErrors[i].size();
        }

        // Only string concatenation is required so std::string is way faster than
        // std::ostringstream
        std::string errorMessage("Overload resolution failed:");
        errorMessage.reserve(errorMessage.size() + requiredBufferSize);
        for (std::size_t i = 0; i < conversionErrorsCount; ++i)
        {
            errorMessage += bullet;
            errorMessage += conversionErrors[i];
        }
        cv::Exception exception(CV_StsBadArg, errorMessage, functionName, "", -1);
        pyRaiseCVException(exception);
    }
    else
    {
        cv::Exception exception(CV_StsInternal, "Overload resolution failed, but no errors reported",
                                functionName, "", -1);
        pyRaiseCVException(exception);
    }
}

void pyPopulateArgumentConversionErrors()
{
    if (PyErr_Occurred())
    {
        PySafeObject exception_type;
        PySafeObject exception_value;
        PySafeObject exception_traceback;
        PyErr_Fetch(exception_type, exception_value, exception_traceback);
        PyErr_NormalizeException(exception_type, exception_value,
                                 exception_traceback);

        PySafeObject exception_message(PyObject_Str(exception_value));
        std::string message;
        getUnicodeString(exception_message, message);
#ifdef CV_CXX11
        conversionErrorsTLS.getRef().push_back(std::move(message));
#else
        conversionErrorsTLS.getRef().push_back(message);
#endif
    }
}

437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
struct SafeSeqItem
{
    PyObject * item;
    SafeSeqItem(PyObject *obj, size_t idx) { item = PySequence_GetItem(obj, idx); }
    ~SafeSeqItem() { Py_XDECREF(item); }

private:
    SafeSeqItem(const SafeSeqItem&); // = delete
    SafeSeqItem& operator=(const SafeSeqItem&); // = delete
};

template <class T>
class RefWrapper
{
public:
    RefWrapper(T& item) : item_(item) {}

    T& get() CV_NOEXCEPT { return item_; }

private:
    T& item_;
};

// In order to support this conversion on 3.x branch - use custom reference_wrapper
// and C-style array instead of std::array<T, N>
template <class T, std::size_t N>
bool parseSequence(PyObject* obj, RefWrapper<T> (&value)[N], const ArgInfo& info)
{
    if (!obj || obj == Py_None)
    {
        return true;
    }
    if (!PySequence_Check(obj))
    {
        failmsg("Can't parse '%s'. Input argument doesn't provide sequence "
                "protocol", info.name);
        return false;
    }
    const std::size_t sequenceSize = PySequence_Size(obj);
    if (sequenceSize != N)
    {
        failmsg("Can't parse '%s'. Expected sequence length %lu, got %lu",
                info.name, N, sequenceSize);
        return false;
    }
    for (std::size_t i = 0; i < N; ++i)
    {
        SafeSeqItem seqItem(obj, i);
        if (!pyopencv_to(seqItem.item, value[i].get(), info))
        {
            failmsg("Can't parse '%s'. Sequence item with index %lu has a "
                    "wrong type", info.name, i);
            return false;
        }
    }
    return true;
}
494 495
} // namespace

496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
namespace traits {
template <bool Value>
struct BooleanConstant
{
    static const bool value = Value;
    typedef BooleanConstant<Value> type;
};

typedef BooleanConstant<true> TrueType;
typedef BooleanConstant<false> FalseType;

template <class T>
struct VoidType {
    typedef void type;
};

template <class T, class DType = void>
struct IsRepresentableAsMatDataType : FalseType
{
};

template <class T>
struct IsRepresentableAsMatDataType<T, typename VoidType<typename DataType<T>::channel_type>::type> : TrueType
{
};
521 522 523 524

// https://github.com/opencv/opencv/issues/20930
template <> struct IsRepresentableAsMatDataType<RotatedRect, void> : FalseType {};

525 526
} // namespace traits

527
typedef std::vector<uchar> vector_uchar;
A
abidrahmank 已提交
528
typedef std::vector<char> vector_char;
529 530 531
typedef std::vector<int> vector_int;
typedef std::vector<float> vector_float;
typedef std::vector<double> vector_double;
532
typedef std::vector<size_t> vector_size_t;
533 534
typedef std::vector<Point> vector_Point;
typedef std::vector<Point2f> vector_Point2f;
W
Wangyida 已提交
535
typedef std::vector<Point3f> vector_Point3f;
536
typedef std::vector<Size> vector_Size;
537 538 539 540 541 542
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 已提交
543
typedef std::vector<Rect2d> vector_Rect2d;
B
berak 已提交
544
typedef std::vector<RotatedRect> vector_RotatedRect;
545 546
typedef std::vector<KeyPoint> vector_KeyPoint;
typedef std::vector<Mat> vector_Mat;
547
typedef std::vector<std::vector<Mat> > vector_vector_Mat;
548
typedef std::vector<UMat> vector_UMat;
549
typedef std::vector<DMatch> vector_DMatch;
550
typedef std::vector<String> vector_String;
551
typedef std::vector<Scalar> vector_Scalar;
A
abidrahmank 已提交
552 553

typedef std::vector<std::vector<char> > vector_vector_char;
554 555 556 557
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;
558
typedef std::vector<std::vector<KeyPoint> > vector_vector_KeyPoint;
559

560 561 562
class NumpyAllocator : public MatAllocator
{
public:
563
    NumpyAllocator() { stdAllocator = Mat::getStdAllocator(); }
564
    ~NumpyAllocator() {}
565

566 567 568 569 570 571 572 573 574 575 576 577 578
    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;
    }

579
    UMatData* allocate(int dims0, const int* sizes, int type, void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const CV_OVERRIDE
580
    {
581 582
        if( data != 0 )
        {
583
            // issue #6969: CV_Error(Error::StsAssert, "The data should normally be NULL!");
584
            // probably this is safe to do in such extreme case
585
            return stdAllocator->allocate(dims0, sizes, type, data, step, flags, usageFlags);
586
        }
A
Alexander Mordvintsev 已提交
587 588
        PyEnsureGIL gil;

589 590 591 592
        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 :
593 594 595 596
        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 已提交
597
        cv::AutoBuffer<npy_intp> _sizes(dims + 1);
598 599 600
        for( i = 0; i < dims; i++ )
            _sizes[i] = sizes[i];
        if( cn > 1 )
A
Andrey Kamaev 已提交
601
            _sizes[dims++] = cn;
602
        PyObject* o = PyArray_SimpleNew(dims, _sizes.data(), typenum);
603
        if(!o)
A
Andrey Kamaev 已提交
604
            CV_Error_(Error::StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims));
605
        return allocate(o, dims0, sizes, type, step);
606
    }
607

608
    bool allocate(UMatData* u, int accessFlags, UMatUsageFlags usageFlags) const CV_OVERRIDE
609
    {
610
        return stdAllocator->allocate(u, accessFlags, usageFlags);
611 612
    }

613
    void deallocate(UMatData* u) const CV_OVERRIDE
614
    {
615 616 617 618 619 620
        if(!u)
            return;
        PyEnsureGIL gil;
        CV_Assert(u->urefcount >= 0);
        CV_Assert(u->refcount >= 0);
        if(u->refcount == 0)
621 622
        {
            PyObject* o = (PyObject*)u->userdata;
623
            Py_XDECREF(o);
624 625
            delete u;
        }
626
    }
627 628

    const MatAllocator* stdAllocator;
629 630 631
};

NumpyAllocator g_numpyAllocator;
632

633

634 635
enum { ARG_NONE = 0, ARG_MAT = 1, ARG_SCALAR = 2 };

636 637 638 639 640
static bool isBool(PyObject* obj) CV_NOEXCEPT
{
    return PyArray_IsScalar(obj, Bool) || PyBool_Check(obj);
}

L
luz.paz 已提交
641
// special case, when the converter needs full ArgInfo structure
A
Alexander Alekhin 已提交
642
static bool pyopencv_to(PyObject* o, Mat& m, const ArgInfo& info)
643
{
644
    bool allowND = true;
V
Vadim Pisarevsky 已提交
645 646 647 648 649 650
    if(!o || o == Py_None)
    {
        if( !m.data )
            m.allocator = &g_numpyAllocator;
        return true;
    }
651

652 653
    if( PyInt_Check(o) )
    {
654
        double v[] = {static_cast<double>(PyInt_AsLong((PyObject*)o)), 0., 0., 0.};
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
        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++ )
        {
670
            PyObject* oi = PyTuple_GetItem(o, i);
671 672 673 674 675 676 677 678 679 680 681 682 683 684
            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 已提交
685 686
    if( !PyArray_Check(o) )
    {
687
        failmsg("%s is not a numpy array, neither a scalar", info.name);
V
Vadim Pisarevsky 已提交
688
        return false;
689
    }
690

691 692
    PyArrayObject* oarr = (PyArrayObject*) o;

693
    bool needcopy = false, needcast = false;
694
    int typenum = PyArray_TYPE(oarr), new_typenum = typenum;
695 696 697 698
    int type = typenum == NPY_UBYTE ? CV_8U :
               typenum == NPY_BYTE ? CV_8S :
               typenum == NPY_USHORT ? CV_16U :
               typenum == NPY_SHORT ? CV_16S :
699
               typenum == NPY_INT ? CV_32S :
700
               typenum == NPY_INT32 ? CV_32S :
701 702
               typenum == NPY_FLOAT ? CV_32F :
               typenum == NPY_DOUBLE ? CV_64F : -1;
703

704 705
    if( type < 0 )
    {
B
boatx 已提交
706
        if( typenum == NPY_INT64 || typenum == NPY_UINT64 || typenum == NPY_LONG )
707 708
        {
            needcopy = needcast = true;
709
            new_typenum = NPY_INT;
710 711 712 713 714 715 716
            type = CV_32S;
        }
        else
        {
            failmsg("%s data type = %d is not supported", info.name, typenum);
            return false;
        }
717
    }
718

A
Andrey Kamaev 已提交
719 720 721 722
#ifndef CV_MAX_DIM
    const int CV_MAX_DIM = 32;
#endif

723
    int ndims = PyArray_NDIM(oarr);
724 725
    if(ndims >= CV_MAX_DIM)
    {
726
        failmsg("%s dimensionality (=%d) is too high", info.name, ndims);
V
Vadim Pisarevsky 已提交
727
        return false;
728
    }
729

730
    int size[CV_MAX_DIM+1];
A
Andrey Kamaev 已提交
731 732
    size_t step[CV_MAX_DIM+1];
    size_t elemsize = CV_ELEM_SIZE1(type);
733 734
    const npy_intp* _sizes = PyArray_DIMS(oarr);
    const npy_intp* _strides = PyArray_STRIDES(oarr);
735 736
    bool ismultichannel = ndims == 3 && _sizes[2] <= CV_CN_MAX;

737 738 739 740 741 742
    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
743 744 745
        // 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]) )
746 747
            needcopy = true;
    }
748

749 750 751
    if( ismultichannel && _strides[1] != (npy_intp)elemsize*_sizes[2] )
        needcopy = true;

752 753 754 755
    if (needcopy)
    {
        if (info.outputarg)
        {
756
            failmsg("Layout of the output array %s is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)", info.name);
757 758
            return false;
        }
759 760 761 762 763 764 765 766 767 768 769

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

        _strides = PyArray_STRIDES(oarr);
770
    }
771

772 773 774
    // Normalize strides in case NPY_RELAXED_STRIDES is set
    size_t default_step = elemsize;
    for ( int i = ndims - 1; i >= 0; --i )
775 776
    {
        size[i] = (int)_sizes[i];
777 778 779 780 781 782 783 784 785 786
        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];
        }
787
    }
788

789 790
    // handle degenerate case
    if( ndims == 0) {
791 792 793 794
        size[ndims] = 1;
        step[ndims] = elemsize;
        ndims++;
    }
795

796
    if( ismultichannel )
V
Vadim Pisarevsky 已提交
797 798 799 800
    {
        ndims--;
        type |= CV_MAKETYPE(0, size[2]);
    }
801

V
Vadim Pisarevsky 已提交
802
    if( ndims > 2 && !allowND )
803
    {
804
        failmsg("%s has more than 2 dimensions", info.name);
V
Vadim Pisarevsky 已提交
805
        return false;
806
    }
807

808
    m = Mat(ndims, size, type, PyArray_DATA(oarr), step);
809
    m.u = g_numpyAllocator.allocate(o, ndims, size, type, step);
A
Alexander Alekhin 已提交
810
    m.addref();
811

812
    if( !needcopy )
813
    {
814 815
        Py_INCREF(o);
    }
816
    m.allocator = &g_numpyAllocator;
817

V
Vadim Pisarevsky 已提交
818
    return true;
819 820
}

V
Vitaly Tuzov 已提交
821
template<typename _Tp, int m, int n>
A
Alexander Alekhin 已提交
822
bool pyopencv_to(PyObject* o, Matx<_Tp, m, n>& mx, const ArgInfo& info)
V
Vitaly Tuzov 已提交
823 824 825 826 827 828 829 830 831 832
{
    Mat tmp;
    if (!pyopencv_to(o, tmp, info)) {
        return false;
    }

    tmp.copyTo(mx);
    return true;
}

A
Alexander Alekhin 已提交
833 834
template<typename _Tp, int cn>
bool pyopencv_to(PyObject* o, Vec<_Tp, cn>& vec, const ArgInfo& info)
V
Vitaly Tuzov 已提交
835
{
A
Alexander Alekhin 已提交
836
    return pyopencv_to(o, (Matx<_Tp, cn, 1>&)vec, info);
V
Vitaly Tuzov 已提交
837 838
}

839 840
template<>
PyObject* pyopencv_from(const Mat& m)
841
{
842
    if( !m.data )
843
        Py_RETURN_NONE;
V
Vadim Pisarevsky 已提交
844
    Mat temp, *p = (Mat*)&m;
845
    if(!p->u || p->allocator != &g_numpyAllocator)
V
Vadim Pisarevsky 已提交
846
    {
V
Vadim Pisarevsky 已提交
847
        temp.allocator = &g_numpyAllocator;
848
        ERRWRAP2(m.copyTo(temp));
V
Vadim Pisarevsky 已提交
849 850
        p = &temp;
    }
851 852 853
    PyObject* o = (PyObject*)p->u->userdata;
    Py_INCREF(o);
    return o;
854 855
}

H
Hamdi Sahloul 已提交
856 857 858 859 860
template<typename _Tp, int m, int n>
PyObject* pyopencv_from(const Matx<_Tp, m, n>& matx)
{
    return pyopencv_from(Mat(matx));
}
861

862
template<typename T>
863
struct PyOpenCV_Converter< cv::Ptr<T> >
864
{
865
    static PyObject* from(const cv::Ptr<T>& p)
866
    {
867 868 869
        if (!p)
            Py_RETURN_NONE;
        return pyopencv_from(*p);
870
    }
A
Alexander Alekhin 已提交
871
    static bool to(PyObject *o, Ptr<T>& p, const ArgInfo& info)
872
    {
873 874 875
        if (!o || o == Py_None)
            return true;
        p = makePtr<T>();
A
Alexander Alekhin 已提交
876
        return pyopencv_to(o, *p, info);
877
    }
878
};
879

880
template<>
A
Alexander Alekhin 已提交
881
bool pyopencv_to(PyObject* obj, void*& ptr, const ArgInfo& info)
882
{
A
Alexander Alekhin 已提交
883
    CV_UNUSED(info);
884
    if (!obj || obj == Py_None)
885 886
        return true;

887
    if (!PyLong_Check(obj))
888
        return false;
889 890
    ptr = PyLong_AsVoidPtr(obj);
    return ptr != NULL && !PyErr_Occurred();
891 892
}

893
static PyObject* pyopencv_from(void*& ptr)
894
{
895
    return PyLong_FromVoidPtr(ptr);
896 897
}

A
Alexander Alekhin 已提交
898
static bool pyopencv_to(PyObject *o, Scalar& s, const ArgInfo& info)
899
{
V
Vadim Pisarevsky 已提交
900 901
    if(!o || o == Py_None)
        return true;
902
    if (PySequence_Check(o)) {
903
        if (4 < PySequence_Size(o))
904
        {
V
Vitaly Tuzov 已提交
905
            failmsg("Scalar value for argument '%s' is longer than 4", info.name);
V
Vadim Pisarevsky 已提交
906
            return false;
907
        }
908 909 910
        for (Py_ssize_t i = 0; i < PySequence_Size(o); i++) {
            SafeSeqItem item_wrap(o, i);
            PyObject *item = item_wrap.item;
911
            if (PyFloat_Check(item) || PyInt_Check(item)) {
912
                s[(int)i] = PyFloat_AsDouble(item);
913
            } else {
V
Vitaly Tuzov 已提交
914
                failmsg("Scalar value for argument '%s' is not numeric", info.name);
V
Vadim Pisarevsky 已提交
915
                return false;
916 917 918 919 920 921
            }
        }
    } else {
        if (PyFloat_Check(o) || PyInt_Check(o)) {
            s[0] = PyFloat_AsDouble(o);
        } else {
V
Vitaly Tuzov 已提交
922
            failmsg("Scalar value for argument '%s' is not numeric", info.name);
V
Vadim Pisarevsky 已提交
923
            return false;
924 925
        }
    }
V
Vadim Pisarevsky 已提交
926
    return true;
927 928
}

929 930
template<>
PyObject* pyopencv_from(const Scalar& src)
V
Vadim Pisarevsky 已提交
931 932 933
{
    return Py_BuildValue("(dddd)", src[0], src[1], src[2], src[3]);
}
934

935 936
template<>
PyObject* pyopencv_from(const bool& value)
937
{
V
Vadim Pisarevsky 已提交
938 939 940
    return PyBool_FromLong(value);
}

941
template<>
A
Alexander Alekhin 已提交
942
bool pyopencv_to(PyObject* obj, bool& value, const ArgInfo& info)
V
Vadim Pisarevsky 已提交
943
{
944 945
    if (!obj || obj == Py_None)
    {
V
Vadim Pisarevsky 已提交
946
        return true;
947 948 949 950 951 952 953 954 955 956 957 958 959
    }
    if (isBool(obj) || PyArray_IsIntegerScalar(obj))
    {
        npy_bool npy_value = NPY_FALSE;
        const int ret_code = PyArray_BoolConverter(obj, &npy_value);
        if (ret_code >= 0)
        {
            value = (npy_value == NPY_TRUE);
            return true;
        }
    }
    failmsg("Argument '%s' is not convertable to bool", info.name);
    return false;
V
Vadim Pisarevsky 已提交
960 961
}

962 963
template<>
PyObject* pyopencv_from(const size_t& value)
V
Vadim Pisarevsky 已提交
964
{
965
    return PyLong_FromSize_t(value);
V
Vadim Pisarevsky 已提交
966
}
967

968
template<>
A
Alexander Alekhin 已提交
969
bool pyopencv_to(PyObject* obj, size_t& value, const ArgInfo& info)
970
{
971 972
    if (!obj || obj == Py_None)
    {
973
        return true;
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
    }
    if (isBool(obj))
    {
        failmsg("Argument '%s' must be integer type, not bool", info.name);
        return false;
    }
    if (PyArray_IsIntegerScalar(obj))
    {
        if (PyLong_Check(obj))
        {
#if defined(CV_PYTHON_3)
            value = PyLong_AsSize_t(obj);
#else
    #if ULONG_MAX == SIZE_MAX
            value = PyLong_AsUnsignedLong(obj);
    #else
            value = PyLong_AsUnsignedLongLong(obj);
    #endif
#endif
        }
#if !defined(CV_PYTHON_3)
        // Python 2.x has PyIntObject which is not a subtype of PyLongObject
        // Overflow check here is unnecessary because object will be converted to long on the
        // interpreter side
        else if (PyInt_Check(obj))
        {
            const long res = PyInt_AsLong(obj);
            if (res < 0) {
                failmsg("Argument '%s' can not be safely parsed to 'size_t'", info.name);
                return false;
            }
    #if ULONG_MAX == SIZE_MAX
            value = PyInt_AsUnsignedLongMask(obj);
    #else
            value = PyInt_AsUnsignedLongLongMask(obj);
    #endif
        }
#endif
        else
        {
            const bool isParsed = parseNumpyScalar<size_t>(obj, value);
            if (!isParsed) {
                failmsg("Argument '%s' can not be safely parsed to 'size_t'", info.name);
                return false;
            }
        }
    }
    else
    {
        failmsg("Argument '%s' is required to be an integer", info.name);
        return false;
    }
    return !PyErr_Occurred();
1027 1028
}

1029 1030
template<>
PyObject* pyopencv_from(const int& value)
V
Vadim Pisarevsky 已提交
1031 1032
{
    return PyInt_FromLong(value);
1033 1034
}

1035
template<>
A
Alexander Alekhin 已提交
1036
bool pyopencv_to(PyObject* obj, int& value, const ArgInfo& info)
1037
{
1038 1039
    if (!obj || obj == Py_None)
    {
1040
        return true;
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
    }
    if (isBool(obj))
    {
        failmsg("Argument '%s' must be integer, not bool", info.name);
        return false;
    }
    if (PyArray_IsIntegerScalar(obj))
    {
        value = PyArray_PyIntAsInt(obj);
    }
1051
    else
1052 1053
    {
        failmsg("Argument '%s' is required to be an integer", info.name);
1054
        return false;
1055 1056
    }
    return !CV_HAS_CONVERSION_ERROR(value);
1057 1058
}

1059 1060
template<>
PyObject* pyopencv_from(const uchar& value)
1061 1062 1063 1064
{
    return PyInt_FromLong(value);
}

1065
template<>
A
Alexander Alekhin 已提交
1066
bool pyopencv_to(PyObject* obj, uchar& value, const ArgInfo& info)
1067
{
A
Alexander Alekhin 已提交
1068
    CV_UNUSED(info);
V
Vadim Pisarevsky 已提交
1069 1070
    if(!obj || obj == Py_None)
        return true;
1071 1072 1073
    int ivalue = (int)PyInt_AsLong(obj);
    value = cv::saturate_cast<uchar>(ivalue);
    return ivalue != -1 || !PyErr_Occurred();
V
Vadim Pisarevsky 已提交
1074 1075
}

1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
template<>
bool pyopencv_to(PyObject* obj, char& value, const ArgInfo& info)
{
    if (!obj || obj == Py_None)
    {
        return true;
    }
    if (isBool(obj))
    {
        failmsg("Argument '%s' must be an integer, not bool", info.name);
        return false;
    }
    if (PyArray_IsIntegerScalar(obj))
    {
        value = saturate_cast<char>(PyArray_PyIntAsInt(obj));
    }
    else
    {
        failmsg("Argument '%s' is required to be an integer", info.name);
        return false;
    }
    return !CV_HAS_CONVERSION_ERROR(value);
}

1100 1101
template<>
PyObject* pyopencv_from(const double& value)
V
Vadim Pisarevsky 已提交
1102 1103 1104 1105
{
    return PyFloat_FromDouble(value);
}

1106
template<>
A
Alexander Alekhin 已提交
1107
bool pyopencv_to(PyObject* obj, double& value, const ArgInfo& info)
V
Vadim Pisarevsky 已提交
1108
{
1109 1110
    if (!obj || obj == Py_None)
    {
V
Vadim Pisarevsky 已提交
1111
        return true;
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
    }
    if (isBool(obj))
    {
        failmsg("Argument '%s' must be double, not bool", info.name);
        return false;
    }
    if (PyArray_IsPythonNumber(obj))
    {
        if (PyLong_Check(obj))
        {
            value = PyLong_AsDouble(obj);
        }
        else
        {
            value = PyFloat_AsDouble(obj);
        }
    }
    else if (PyArray_CheckScalar(obj))
    {
        const bool isParsed = parseNumpyScalar<double>(obj, value);
        if (!isParsed) {
            failmsg("Argument '%s' can not be safely parsed to 'double'", info.name);
            return false;
        }
    }
1137
    else
1138 1139 1140 1141
    {
        failmsg("Argument '%s' can not be treated as a double", info.name);
        return false;
    }
V
Vadim Pisarevsky 已提交
1142
    return !PyErr_Occurred();
1143 1144
}

1145 1146
template<>
PyObject* pyopencv_from(const float& value)
1147
{
V
Vadim Pisarevsky 已提交
1148
    return PyFloat_FromDouble(value);
1149
}
V
Vadim Pisarevsky 已提交
1150

1151
template<>
A
Alexander Alekhin 已提交
1152
bool pyopencv_to(PyObject* obj, float& value, const ArgInfo& info)
1153
{
1154 1155
    if (!obj || obj == Py_None)
    {
V
Vadim Pisarevsky 已提交
1156
        return true;
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
    }
    if (isBool(obj))
    {
        failmsg("Argument '%s' must be float, not bool", info.name);
        return false;
    }
    if (PyArray_IsPythonNumber(obj))
    {
        if (PyLong_Check(obj))
        {
            double res = PyLong_AsDouble(obj);
            value = static_cast<float>(res);
        }
        else
        {
            double res = PyFloat_AsDouble(obj);
            value = static_cast<float>(res);
        }
    }
    else if (PyArray_CheckScalar(obj))
    {
       const bool isParsed = parseNumpyScalar<float>(obj, value);
        if (!isParsed) {
            failmsg("Argument '%s' can not be safely parsed to 'float'", info.name);
            return false;
        }
    }
V
Vadim Pisarevsky 已提交
1184
    else
1185 1186 1187 1188
    {
        failmsg("Argument '%s' can't be treated as a float", info.name);
        return false;
    }
V
Vadim Pisarevsky 已提交
1189
    return !PyErr_Occurred();
1190 1191
}

1192 1193
template<>
PyObject* pyopencv_from(const int64& value)
1194
{
1195
    return PyLong_FromLongLong(value);
1196 1197
}

1198 1199
template<>
PyObject* pyopencv_from(const String& value)
V
Vadim Pisarevsky 已提交
1200 1201 1202
{
    return PyString_FromString(value.empty() ? "" : value.c_str());
}
1203

1204 1205 1206 1207 1208 1209 1210 1211
#if CV_VERSION_MAJOR == 3
template<>
PyObject* pyopencv_from(const std::string& value)
{
    return PyString_FromString(value.empty() ? "" : value.c_str());
}
#endif

1212
template<>
A
Alexander Alekhin 已提交
1213
bool pyopencv_to(PyObject* obj, String &value, const ArgInfo& info)
1214
{
V
Vadim Pisarevsky 已提交
1215
    if(!obj || obj == Py_None)
1216
    {
V
Vadim Pisarevsky 已提交
1217
        return true;
1218
    }
1219 1220 1221 1222 1223 1224
    std::string str;
    if (getUnicodeString(obj, str))
    {
        value = str;
        return true;
    }
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
    else
    {
        // If error hasn't been already set by Python conversion functions
        if (!PyErr_Occurred())
        {
            // Direct access to underlying slots of PyObjectType is not allowed
            // when limited API is enabled
#ifdef Py_LIMITED_API
            failmsg("Can't convert object to 'str' for '%s'", info.name);
#else
            failmsg("Can't convert object of type '%s' to 'str' for '%s'",
                    obj->ob_type->tp_name, info.name);
#endif
        }
    }
1240
    return false;
V
Vadim Pisarevsky 已提交
1241 1242
}

1243
template<>
A
Alexander Alekhin 已提交
1244
bool pyopencv_to(PyObject* obj, Size& sz, const ArgInfo& info)
V
Vadim Pisarevsky 已提交
1245
{
1246 1247 1248
    RefWrapper<int> values[] = {RefWrapper<int>(sz.width),
                                RefWrapper<int>(sz.height)};
    return parseSequence(obj, values, info);
V
Vadim Pisarevsky 已提交
1249 1250
}

1251 1252
template<>
PyObject* pyopencv_from(const Size& sz)
V
Vadim Pisarevsky 已提交
1253 1254 1255 1256
{
    return Py_BuildValue("(ii)", sz.width, sz.height);
}

1257
template<>
A
Alexander Alekhin 已提交
1258
bool pyopencv_to(PyObject* obj, Size_<float>& sz, const ArgInfo& info)
1259
{
1260 1261 1262
    RefWrapper<float> values[] = {RefWrapper<float>(sz.width),
                                  RefWrapper<float>(sz.height)};
    return parseSequence(obj, values, info);
1263 1264 1265 1266 1267 1268 1269 1270
}

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

1271
template<>
A
Alexander Alekhin 已提交
1272
bool pyopencv_to(PyObject* obj, Rect& r, const ArgInfo& info)
V
Vadim Pisarevsky 已提交
1273
{
1274 1275 1276 1277
    RefWrapper<int> values[] = {RefWrapper<int>(r.x), RefWrapper<int>(r.y),
                                RefWrapper<int>(r.width),
                                RefWrapper<int>(r.height)};
    return parseSequence(obj, values, info);
V
Vadim Pisarevsky 已提交
1278 1279
}

1280 1281
template<>
PyObject* pyopencv_from(const Rect& r)
V
Vadim Pisarevsky 已提交
1282 1283 1284 1285
{
    return Py_BuildValue("(iiii)", r.x, r.y, r.width, r.height);
}

B
berak 已提交
1286
template<>
A
Alexander Alekhin 已提交
1287
bool pyopencv_to(PyObject* obj, Rect2d& r, const ArgInfo& info)
B
berak 已提交
1288
{
1289 1290 1291 1292
    RefWrapper<double> values[] = {
        RefWrapper<double>(r.x), RefWrapper<double>(r.y),
        RefWrapper<double>(r.width), RefWrapper<double>(r.height)};
    return parseSequence(obj, values, info);
B
berak 已提交
1293 1294 1295 1296 1297 1298 1299 1300
}

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

1301
template<>
A
Alexander Alekhin 已提交
1302
bool pyopencv_to(PyObject* obj, Range& r, const ArgInfo& info)
V
Vadim Pisarevsky 已提交
1303
{
1304
    if (!obj || obj == Py_None)
1305 1306 1307
    {
        return true;
    }
1308
    if (PyObject_Size(obj) == 0)
1309
    {
V
Vadim Pisarevsky 已提交
1310 1311
        r = Range::all();
        return true;
1312
    }
1313 1314
    RefWrapper<int> values[] = {RefWrapper<int>(r.start), RefWrapper<int>(r.end)};
    return parseSequence(obj, values, info);
V
Vadim Pisarevsky 已提交
1315 1316
}

1317 1318
template<>
PyObject* pyopencv_from(const Range& r)
V
Vadim Pisarevsky 已提交
1319 1320 1321 1322
{
    return Py_BuildValue("(ii)", r.start, r.end);
}

1323
template<>
A
Alexander Alekhin 已提交
1324
bool pyopencv_to(PyObject* obj, Point& p, const ArgInfo& info)
V
Vadim Pisarevsky 已提交
1325
{
1326 1327
    RefWrapper<int> values[] = {RefWrapper<int>(p.x), RefWrapper<int>(p.y)};
    return parseSequence(obj, values, info);
V
Vadim Pisarevsky 已提交
1328 1329
}

1330
template <>
A
Alexander Alekhin 已提交
1331
bool pyopencv_to(PyObject* obj, Point2f& p, const ArgInfo& info)
V
Vadim Pisarevsky 已提交
1332
{
1333 1334 1335
    RefWrapper<float> values[] = {RefWrapper<float>(p.x),
                                  RefWrapper<float>(p.y)};
    return parseSequence(obj, values, info);
V
Vadim Pisarevsky 已提交
1336 1337
}

1338
template<>
A
Alexander Alekhin 已提交
1339
bool pyopencv_to(PyObject* obj, Point2d& p, const ArgInfo& info)
1340
{
1341 1342 1343
    RefWrapper<double> values[] = {RefWrapper<double>(p.x),
                                   RefWrapper<double>(p.y)};
    return parseSequence(obj, values, info);
1344 1345
}

W
Wangyida 已提交
1346
template<>
A
Alexander Alekhin 已提交
1347
bool pyopencv_to(PyObject* obj, Point3f& p, const ArgInfo& info)
W
Wangyida 已提交
1348
{
1349 1350 1351 1352
    RefWrapper<float> values[] = {RefWrapper<float>(p.x),
                                  RefWrapper<float>(p.y),
                                  RefWrapper<float>(p.z)};
    return parseSequence(obj, values, info);
W
Wangyida 已提交
1353 1354 1355
}

template<>
A
Alexander Alekhin 已提交
1356
bool pyopencv_to(PyObject* obj, Point3d& p, const ArgInfo& info)
W
Wangyida 已提交
1357
{
1358 1359 1360 1361
    RefWrapper<double> values[] = {RefWrapper<double>(p.x),
                                   RefWrapper<double>(p.y),
                                   RefWrapper<double>(p.z)};
    return parseSequence(obj, values, info);
W
Wangyida 已提交
1362
}
1363

1364 1365
template<>
PyObject* pyopencv_from(const Point& p)
V
Vadim Pisarevsky 已提交
1366 1367 1368 1369
{
    return Py_BuildValue("(ii)", p.x, p.y);
}

1370 1371
template<>
PyObject* pyopencv_from(const Point2f& p)
V
Vadim Pisarevsky 已提交
1372 1373 1374 1375
{
    return Py_BuildValue("(dd)", p.x, p.y);
}

W
Wangyida 已提交
1376 1377 1378 1379 1380 1381
template<>
PyObject* pyopencv_from(const Point3f& p)
{
    return Py_BuildValue("(ddd)", p.x, p.y, p.z);
}

A
Alexander Alekhin 已提交
1382
static bool pyopencv_to(PyObject* obj, Vec4d& v, ArgInfo& info)
V
Vitaly Tuzov 已提交
1383
{
1384 1385 1386
    RefWrapper<double> values[] = {RefWrapper<double>(v[0]), RefWrapper<double>(v[1]),
                                   RefWrapper<double>(v[2]), RefWrapper<double>(v[3])};
    return parseSequence(obj, values, info);
V
Vitaly Tuzov 已提交
1387 1388
}

A
Alexander Alekhin 已提交
1389
static bool pyopencv_to(PyObject* obj, Vec4f& v, ArgInfo& info)
V
Vitaly Tuzov 已提交
1390
{
1391 1392 1393
    RefWrapper<float> values[] = {RefWrapper<float>(v[0]), RefWrapper<float>(v[1]),
                                  RefWrapper<float>(v[2]), RefWrapper<float>(v[3])};
    return parseSequence(obj, values, info);
V
Vitaly Tuzov 已提交
1394 1395
}

A
Alexander Alekhin 已提交
1396
static bool pyopencv_to(PyObject* obj, Vec4i& v, ArgInfo& info)
V
Vitaly Tuzov 已提交
1397
{
1398 1399 1400
    RefWrapper<int> values[] = {RefWrapper<int>(v[0]), RefWrapper<int>(v[1]),
                                RefWrapper<int>(v[2]), RefWrapper<int>(v[3])};
    return parseSequence(obj, values, info);
V
Vitaly Tuzov 已提交
1401 1402
}

A
Alexander Alekhin 已提交
1403
static bool pyopencv_to(PyObject* obj, Vec3d& v, ArgInfo& info)
V
Vitaly Tuzov 已提交
1404
{
1405 1406 1407 1408
    RefWrapper<double> values[] = {RefWrapper<double>(v[0]),
                                   RefWrapper<double>(v[1]),
                                   RefWrapper<double>(v[2])};
    return parseSequence(obj, values, info);
V
Vadim Pisarevsky 已提交
1409
}
V
Vitaly Tuzov 已提交
1410

A
Alexander Alekhin 已提交
1411
static bool pyopencv_to(PyObject* obj, Vec3f& v, ArgInfo& info)
V
Vitaly Tuzov 已提交
1412
{
1413 1414 1415 1416
    RefWrapper<float> values[] = {RefWrapper<float>(v[0]),
                                  RefWrapper<float>(v[1]),
                                  RefWrapper<float>(v[2])};
    return parseSequence(obj, values, info);
V
Vitaly Tuzov 已提交
1417 1418
}

A
Alexander Alekhin 已提交
1419
static bool pyopencv_to(PyObject* obj, Vec3i& v, ArgInfo& info)
V
Vitaly Tuzov 已提交
1420
{
1421 1422 1423
    RefWrapper<int> values[] = {RefWrapper<int>(v[0]), RefWrapper<int>(v[1]),
                                RefWrapper<int>(v[2])};
    return parseSequence(obj, values, info);
V
Vitaly Tuzov 已提交
1424 1425
}

A
Alexander Alekhin 已提交
1426
static bool pyopencv_to(PyObject* obj, Vec2d& v, ArgInfo& info)
V
Vitaly Tuzov 已提交
1427
{
1428 1429 1430
    RefWrapper<double> values[] = {RefWrapper<double>(v[0]),
                                   RefWrapper<double>(v[1])};
    return parseSequence(obj, values, info);
V
Vitaly Tuzov 已提交
1431 1432
}

A
Alexander Alekhin 已提交
1433
static bool pyopencv_to(PyObject* obj, Vec2f& v, ArgInfo& info)
V
Vitaly Tuzov 已提交
1434
{
1435 1436 1437
    RefWrapper<float> values[] = {RefWrapper<float>(v[0]),
                                  RefWrapper<float>(v[1])};
    return parseSequence(obj, values, info);
V
Vitaly Tuzov 已提交
1438 1439
}

A
Alexander Alekhin 已提交
1440
static bool pyopencv_to(PyObject* obj, Vec2i& v, ArgInfo& info)
V
Vitaly Tuzov 已提交
1441
{
1442 1443
    RefWrapper<int> values[] = {RefWrapper<int>(v[0]), RefWrapper<int>(v[1])};
    return parseSequence(obj, values, info);
V
Vitaly Tuzov 已提交
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
}

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

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

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

1464 1465
template<>
PyObject* pyopencv_from(const Vec3d& v)
V
Vadim Pisarevsky 已提交
1466 1467 1468 1469
{
    return Py_BuildValue("(ddd)", v[0], v[1], v[2]);
}

V
Vitaly Tuzov 已提交
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
template<>
PyObject* pyopencv_from(const Vec3f& v)
{
    return Py_BuildValue("(fff)", v[0], v[1], v[2]);
}

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

1482 1483
template<>
PyObject* pyopencv_from(const Vec2d& v)
A
Andrey Kamaev 已提交
1484 1485 1486 1487
{
    return Py_BuildValue("(dd)", v[0], v[1]);
}

V
Vitaly Tuzov 已提交
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
template<>
PyObject* pyopencv_from(const Vec2f& v)
{
    return Py_BuildValue("(ff)", v[0], v[1]);
}

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

1500 1501
template<>
PyObject* pyopencv_from(const Point2d& p)
V
Vadim Pisarevsky 已提交
1502 1503 1504 1505
{
    return Py_BuildValue("(dd)", p.x, p.y);
}

W
Wangyida 已提交
1506 1507 1508
template<>
PyObject* pyopencv_from(const Point3d& p)
{
1509
    return Py_BuildValue("(ddd)", p.x, p.y, p.z);
W
Wangyida 已提交
1510 1511
}

1512 1513 1514 1515 1516 1517
template<>
PyObject* pyopencv_from(const std::pair<int, double>& src)
{
    return Py_BuildValue("(id)", src.first, src.second);
}

1518
template<>
1519
bool pyopencv_to(PyObject* obj, TermCriteria& dst, const ArgInfo& info)
1520
{
1521 1522
    if (!obj || obj == Py_None)
    {
V
Vadim Pisarevsky 已提交
1523
        return true;
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
    }
    if (!PySequence_Check(obj))
    {
        failmsg("Can't parse '%s' as TermCriteria."
                "Input argument doesn't provide sequence protocol",
                info.name);
        return false;
    }
    const std::size_t sequenceSize = PySequence_Size(obj);
    if (sequenceSize != 3) {
        failmsg("Can't parse '%s' as TermCriteria. Expected sequence length 3, "
                "got %lu",
                info.name, sequenceSize);
        return false;
    }
    {
        const String typeItemName = format("'%s' criteria type", info.name);
        const ArgInfo typeItemInfo(typeItemName.c_str(), false);
        SafeSeqItem typeItem(obj, 0);
        if (!pyopencv_to(typeItem.item, dst.type, typeItemInfo))
        {
            return false;
        }
    }
    {
        const String maxCountItemName = format("'%s' max count", info.name);
        const ArgInfo maxCountItemInfo(maxCountItemName.c_str(), false);
        SafeSeqItem maxCountItem(obj, 1);
        if (!pyopencv_to(maxCountItem.item, dst.maxCount, maxCountItemInfo))
        {
            return false;
        }
    }
    {
        const String epsilonItemName = format("'%s' epsilon", info.name);
        const ArgInfo epsilonItemInfo(epsilonItemName.c_str(), false);
        SafeSeqItem epsilonItem(obj, 2);
        if (!pyopencv_to(epsilonItem.item, dst.epsilon, epsilonItemInfo))
        {
            return false;
        }
    }
    return true;
1567 1568
}

1569 1570
template<>
PyObject* pyopencv_from(const TermCriteria& src)
1571
{
V
Vadim Pisarevsky 已提交
1572
    return Py_BuildValue("(iid)", src.type, src.maxCount, src.epsilon);
1573 1574
}

1575
template<>
1576
bool pyopencv_to(PyObject* obj, RotatedRect& dst, const ArgInfo& info)
1577
{
1578 1579
    if (!obj || obj == Py_None)
    {
V
Vadim Pisarevsky 已提交
1580
        return true;
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
    }
    if (!PySequence_Check(obj))
    {
        failmsg("Can't parse '%s' as RotatedRect."
                "Input argument doesn't provide sequence protocol",
                info.name);
        return false;
    }
    const std::size_t sequenceSize = PySequence_Size(obj);
    if (sequenceSize != 3)
    {
        failmsg("Can't parse '%s' as RotatedRect. Expected sequence length 3, got %lu",
                info.name, sequenceSize);
        return false;
    }
    {
        const String centerItemName = format("'%s' center point", info.name);
        const ArgInfo centerItemInfo(centerItemName.c_str(), false);
        SafeSeqItem centerItem(obj, 0);
        if (!pyopencv_to(centerItem.item, dst.center, centerItemInfo))
        {
            return false;
        }
    }
    {
        const String sizeItemName = format("'%s' size", info.name);
        const ArgInfo sizeItemInfo(sizeItemName.c_str(), false);
        SafeSeqItem sizeItem(obj, 1);
        if (!pyopencv_to(sizeItem.item, dst.size, sizeItemInfo))
        {
            return false;
        }
    }
    {
        const String angleItemName = format("'%s' angle", info.name);
        const ArgInfo angleItemInfo(angleItemName.c_str(), false);
        SafeSeqItem angleItem(obj, 2);
        if (!pyopencv_to(angleItem.item, dst.angle, angleItemInfo))
        {
            return false;
        }
    }
    return true;
1624 1625
}

1626 1627
template<>
PyObject* pyopencv_from(const RotatedRect& src)
1628
{
V
Vadim Pisarevsky 已提交
1629
    return Py_BuildValue("((ff)(ff)f)", src.center.x, src.center.y, src.size.width, src.size.height, src.angle);
1630 1631
}

1632 1633
template<>
PyObject* pyopencv_from(const Moments& m)
1634
{
V
Vadim Pisarevsky 已提交
1635 1636 1637 1638 1639 1640 1641
    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,
1642
                         "nu30", m.nu30, "nu21", m.nu21, "nu12", m.nu12, "nu03", m.nu03);
1643 1644
}

1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
template <typename Tp>
struct pyopencvVecConverter;

template <typename Tp>
bool pyopencv_to(PyObject* obj, std::vector<Tp>& value, const ArgInfo& info)
{
    if (!obj || obj == Py_None)
    {
        return true;
    }
    return pyopencvVecConverter<Tp>::to(obj, value, info);
}

template <typename Tp>
PyObject* pyopencv_from(const std::vector<Tp>& value)
{
    return pyopencvVecConverter<Tp>::from(value);
}

template <typename Tp>
static bool pyopencv_to_generic_vec(PyObject* obj, std::vector<Tp>& value, const ArgInfo& info)
{
    if (!obj || obj == Py_None)
    {
        return true;
    }
    if (!PySequence_Check(obj))
    {
        failmsg("Can't parse '%s'. Input argument doesn't provide sequence protocol", info.name);
        return false;
    }
    const size_t n = static_cast<size_t>(PySequence_Size(obj));
    value.resize(n);
    for (size_t i = 0; i < n; i++)
    {
        SafeSeqItem item_wrap(obj, i);
        if (!pyopencv_to(item_wrap.item, value[i], info))
        {
            failmsg("Can't parse '%s'. Sequence item with index %lu has a wrong type", info.name, i);
            return false;
        }
    }
    return true;
}

template <typename Tp>
static PyObject* pyopencv_from_generic_vec(const std::vector<Tp>& value)
{
    Py_ssize_t n = static_cast<Py_ssize_t>(value.size());
    PySafeObject seq(PyTuple_New(n));
    for (Py_ssize_t i = 0; i < n; i++)
    {
        PyObject* item = pyopencv_from(value[i]);
        // If item can't be assigned - PyTuple_SetItem raises exception and returns -1.
        if (!item || PyTuple_SetItem(seq, i, item) == -1)
        {
            return NULL;
        }
    }
    return seq.release();
}

template <typename Tp>
struct pyopencvVecConverter
{
    typedef typename std::vector<Tp>::iterator VecIt;

    static bool to(PyObject* obj, std::vector<Tp>& value, const ArgInfo& info)
    {
        if (!PyArray_Check(obj))
        {
            return pyopencv_to_generic_vec(obj, value, info);
        }
        // If user passed an array it is possible to make faster conversions in several cases
        PyArrayObject* array_obj = reinterpret_cast<PyArrayObject*>(obj);
        const NPY_TYPES target_type = asNumpyType<Tp>();
        const NPY_TYPES source_type = static_cast<NPY_TYPES>(PyArray_TYPE(array_obj));
        if (target_type == NPY_OBJECT)
        {
            // Non-planar arrays representing objects (e.g. array of N Rect is an array of shape Nx4) have NPY_OBJECT
            // as their target type.
            return pyopencv_to_generic_vec(obj, value, info);
        }
        if (PyArray_NDIM(array_obj) > 1)
        {
            failmsg("Can't parse %dD array as '%s' vector argument", PyArray_NDIM(array_obj), info.name);
            return false;
        }
        if (target_type != source_type)
        {
            // Source type requires conversion
            // Allowed conversions for target type is handled in the corresponding pyopencv_to function
            return pyopencv_to_generic_vec(obj, value, info);
        }
        // For all other cases, all array data can be directly copied to std::vector data
        // Simple `memcpy` is not possible because NumPy array can reference a slice of the bigger array:
        // ```
        // arr = np.ones((8, 4, 5), dtype=np.int32)
        // convertible_to_vector_of_int = arr[:, 0, 1]
        // ```
        value.resize(static_cast<size_t>(PyArray_SIZE(array_obj)));
        const npy_intp item_step = PyArray_STRIDE(array_obj, 0) / PyArray_ITEMSIZE(array_obj);
        const Tp* data_ptr = static_cast<Tp*>(PyArray_DATA(array_obj));
        for (VecIt it = value.begin(); it != value.end(); ++it, data_ptr += item_step) {
            *it = *data_ptr;
        }
        return true;
    }

    static PyObject* from(const std::vector<Tp>& value)
    {
        if (value.empty())
        {
            return PyTuple_New(0);
        }
        return from(value, ::traits::IsRepresentableAsMatDataType<Tp>());
    }

private:
    static PyObject* from(const std::vector<Tp>& value, ::traits::FalseType)
    {
        // Underlying type is not representable as Mat Data Type
        return pyopencv_from_generic_vec(value);
    }

    static PyObject* from(const std::vector<Tp>& value, ::traits::TrueType)
    {
        // Underlying type is representable as Mat Data Type, so faster return type is available
        typedef DataType<Tp> DType;
        typedef typename DType::channel_type UnderlyingArrayType;

        // If Mat is always exposed as NumPy array this code path can be reduced to the following snipped:
        //        Mat src(value);
        //        PyObject* array = pyopencv_from(src);
        //        return PyArray_Squeeze(reinterpret_cast<PyArrayObject*>(array));
        // This puts unnecessary restrictions on Mat object those might be avoided without losing the performance.
        // Moreover, this version is a bit faster, because it doesn't create temporary objects with reference counting.

        const NPY_TYPES target_type = asNumpyType<UnderlyingArrayType>();
        const int cols = DType::channels;
1785
        PyObject* array = NULL;
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
        if (cols == 1)
        {
            npy_intp dims = static_cast<npy_intp>(value.size());
            array = PyArray_SimpleNew(1, &dims, target_type);
        }
        else
        {
            npy_intp dims[2] = {static_cast<npy_intp>(value.size()), cols};
            array = PyArray_SimpleNew(2, dims, target_type);
        }
        if(!array)
        {
            // NumPy arrays with shape (N, 1) and (N) are not equal, so correct error message should distinguish
            // them too.
            String shape;
            if (cols > 1)
            {
1803
                shape = format("(%d x %d)", static_cast<int>(value.size()), cols);
1804 1805 1806
            }
            else
            {
1807
                shape = format("(%d)", static_cast<int>(value.size()));
1808
            }
1809 1810 1811 1812
            const String error_message = format("Can't allocate NumPy array for vector with dtype=%d and shape=%s",
                                                static_cast<int>(target_type), shape.c_str());
            emit_failmsg(PyExc_MemoryError, error_message.c_str());
            return array;
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
        }
        // Fill the array
        PyArrayObject* array_obj = reinterpret_cast<PyArrayObject*>(array);
        UnderlyingArrayType* array_data = static_cast<UnderlyingArrayType*>(PyArray_DATA(array_obj));
        // if Tp is representable as Mat DataType, so the following cast is pretty safe...
        const UnderlyingArrayType* value_data = reinterpret_cast<const UnderlyingArrayType*>(value.data());
        memcpy(array_data, value_data, sizeof(UnderlyingArrayType) * value.size() * static_cast<size_t>(cols));
        return array;
    }
};

1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
static int OnError(int status, const char *func_name, const char *err_msg, const char *file_name, int line, void *userdata)
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();

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

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

    Py_DECREF(args);
    PyGILState_Release(gstate);

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

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

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

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

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

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

1875 1876 1877 1878
static void OnMouse(int event, int x, int y, int flags, void* param)
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();
1879

1880 1881
    PyObject *o = (PyObject*)param;
    PyObject *args = Py_BuildValue("iiiiO", event, x, y, flags, PyTuple_GetItem(o, 1));
1882

1883 1884 1885 1886 1887 1888 1889 1890 1891
    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);
}

1892
#ifdef HAVE_OPENCV_HIGHGUI
A
Andrey Kamaev 已提交
1893
static PyObject *pycvSetMouseCallback(PyObject*, PyObject *args, PyObject *kw)
1894 1895 1896 1897 1898
{
    const char *keywords[] = { "window_name", "on_mouse", "param", NULL };
    char* name;
    PyObject *on_mouse;
    PyObject *param = NULL;
1899

1900 1901 1902 1903 1904 1905 1906 1907 1908
    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;
    }
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
    PyObject* py_callback_info = Py_BuildValue("OO", on_mouse, param);
    static std::map<std::string, PyObject*> registered_callbacks;
    std::map<std::string, PyObject*>::iterator i = registered_callbacks.find(name);
    if (i != registered_callbacks.end())
    {
        Py_DECREF(i->second);
        i->second = py_callback_info;
    }
    else
    {
        registered_callbacks.insert(std::pair<std::string, PyObject*>(std::string(name), py_callback_info));
D
Dan Mašek 已提交
1920
    }
1921
    ERRWRAP2(setMouseCallback(name, OnMouse, py_callback_info));
1922 1923
    Py_RETURN_NONE;
}
1924
#endif
1925

1926
static void OnChange(int pos, void *param)
1927 1928 1929
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();
1930

1931 1932 1933 1934 1935
    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();
1936 1937
    else
        Py_DECREF(r);
1938 1939 1940 1941
    Py_DECREF(args);
    PyGILState_Release(gstate);
}

1942
#ifdef HAVE_OPENCV_HIGHGUI
B
berak 已提交
1943 1944 1945 1946 1947 1948 1949 1950
// workaround for #20408, use nullptr, set value later
static int _createTrackbar(const String &trackbar_name, const String &window_name, int value, int count,
                    TrackbarCallback onChange, PyObject* py_callback_info)
{
    int n = createTrackbar(trackbar_name, window_name, NULL, count, onChange, py_callback_info);
    setTrackbarPos(trackbar_name, window_name, value);
    return n;
}
A
Andrey Kamaev 已提交
1951
static PyObject *pycvCreateTrackbar(PyObject*, PyObject *args)
1952 1953 1954 1955
{
    PyObject *on_change;
    char* trackbar_name;
    char* window_name;
B
berak 已提交
1956
    int value;
1957
    int count;
1958

B
berak 已提交
1959
    if (!PyArg_ParseTuple(args, "ssiiO", &trackbar_name, &window_name, &value, &count, &on_change))
1960 1961 1962 1963 1964
        return NULL;
    if (!PyCallable_Check(on_change)) {
        PyErr_SetString(PyExc_TypeError, "on_change must be callable");
        return NULL;
    }
1965 1966 1967 1968 1969 1970 1971 1972
    PyObject* py_callback_info = Py_BuildValue("OO", on_change, Py_None);
    std::string name = std::string(window_name) + ":" + std::string(trackbar_name);
    static std::map<std::string, PyObject*> registered_callbacks;
    std::map<std::string, PyObject*>::iterator i = registered_callbacks.find(name);
    if (i != registered_callbacks.end())
    {
        Py_DECREF(i->second);
        i->second = py_callback_info;
D
Dan Mašek 已提交
1973
    }
1974 1975 1976 1977
    else
    {
        registered_callbacks.insert(std::pair<std::string, PyObject*>(name, py_callback_info));
    }
B
berak 已提交
1978
    ERRWRAP2(_createTrackbar(trackbar_name, window_name, value, count, OnChange, py_callback_info));
1979 1980 1981
    Py_RETURN_NONE;
}

1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
static void OnButtonChange(int state, void *param)
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();

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

    PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL);
    if (r == NULL)
        PyErr_Print();
2001 2002
    else
        Py_DECREF(r);
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
    Py_DECREF(args);
    PyGILState_Release(gstate);
}

static PyObject *pycvCreateButton(PyObject*, PyObject *args, PyObject *kw)
{
    const char* keywords[] = {"buttonName", "onChange", "userData", "buttonType", "initialButtonState", NULL};
    PyObject *on_change;
    PyObject *userdata = NULL;
    char* button_name;
    int button_type = 0;
2014
    int initial_button_state = 0;
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025

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

2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
    PyObject* py_callback_info = Py_BuildValue("OO", on_change, userdata);
    std::string name(button_name);

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

2045 2046
///////////////////////////////////////////////////////////////////////////////////////

A
Alexander Alekhin 已提交
2047
static int convert_to_char(PyObject *o, char *dst, const ArgInfo& info)
2048
{
2049 2050 2051 2052 2053 2054
    std::string str;
    if (getUnicodeString(o, str))
    {
        *dst = str[0];
        return 1;
    }
2055
    (*dst) = 0;
A
Alexander Alekhin 已提交
2056
    return failmsg("Expected single character string for argument '%s'", info.name);
2057 2058
}

A
Andrey Kamaev 已提交
2059 2060 2061 2062 2063
#ifdef __GNUC__
#  pragma GCC diagnostic ignored "-Wunused-parameter"
#  pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#endif

2064

2065
#include "pyopencv_generated_enums.h"
2066
#include "pyopencv_custom_headers.h"
2067 2068

#ifdef CVPY_DYNAMIC_INIT
2069
#define CVPY_TYPE(WNAME, NAME, STORAGE, SNAME, _1, _2) CVPY_TYPE_DECLARE_DYNAMIC(WNAME, NAME, STORAGE, SNAME)
2070
#else
2071
#define CVPY_TYPE(WNAME, NAME, STORAGE, SNAME, _1, _2) CVPY_TYPE_DECLARE(WNAME, NAME, STORAGE, SNAME)
2072
#endif
2073
#include "pyopencv_generated_types.h"
2074 2075 2076
#undef CVPY_TYPE

#include "pyopencv_generated_types_content.h"
2077 2078
#include "pyopencv_generated_funcs.h"

2079

A
Alexander Mordvintsev 已提交
2080
static PyMethodDef special_methods[] = {
2081
  {"redirectError", CV_PY_FN_WITH_KW(pycvRedirectError), "redirectError(onError) -> None"},
2082
#ifdef HAVE_OPENCV_HIGHGUI
2083 2084 2085
  {"createTrackbar", (PyCFunction)pycvCreateTrackbar, METH_VARARGS, "createTrackbar(trackbarName, windowName, value, count, onChange) -> None"},
  {"createButton", CV_PY_FN_WITH_KW(pycvCreateButton), "createButton(buttonName, onChange [, userData, buttonType, initialButtonState]) -> None"},
  {"setMouseCallback", CV_PY_FN_WITH_KW(pycvSetMouseCallback), "setMouseCallback(windowName, onMouse [, param]) -> None"},
2086 2087
#endif
#ifdef HAVE_OPENCV_DNN
2088 2089
  {"dnn_registerLayer", CV_PY_FN_WITH_KW(pyopencv_cv_dnn_registerLayer), "registerLayer(type, class) -> None"},
  {"dnn_unregisterLayer", CV_PY_FN_WITH_KW(pyopencv_cv_dnn_unregisterLayer), "unregisterLayer(type) -> None"},
2090
#endif
2091 2092 2093 2094 2095 2096
  {NULL, NULL},
};

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

2097 2098 2099
struct ConstDef
{
    const char * name;
2100
    long long val;
2101 2102
};

2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186
static inline bool strStartsWith(const std::string& str, const std::string& prefix) {
    return prefix.empty() || \
        (str.size() >= prefix.size() && std::memcmp(str.data(), prefix.data(), prefix.size()) == 0);
}

static inline bool strEndsWith(const std::string& str, char symbol) {
    return !str.empty() && str[str.size() - 1] == symbol;
}

/**
 * \brief Creates a submodule of the `root`. Missing parents submodules
 * are created as needed. If name equals to parent module name than
 * borrowed reference to parent module is returned (no reference counting
 * are done).
 * Submodule lifetime is managed by the parent module.
 * If nested submodules are created than the lifetime is managed by the
 * predecessor submodule in a list.
 *
 * \param parent_module Parent module object.
 * \param name Submodule name.
 * \return borrowed reference to the created submodule.
 *         If any of submodules can't be created than NULL is returned.
 */
static PyObject* createSubmodule(PyObject* parent_module, const std::string& name)
{
    if (!parent_module)
    {
        return PyErr_Format(PyExc_ImportError,
            "Bindings generation error. "
            "Parent module is NULL during the submodule '%s' creation",
            name.c_str()
        );
    }
    if (strEndsWith(name, '.'))
    {
        return PyErr_Format(PyExc_ImportError,
            "Bindings generation error. "
            "Submodule can't end with a dot. Got: %s", name.c_str()
        );
    }

    const std::string parent_name = PyModule_GetName(parent_module);

    /// Special case handling when caller tries to register a submodule of the parent module with
    /// the same name
    if (name == parent_name) {
        return parent_module;
    }

    if (!strStartsWith(name, parent_name))
    {
        return PyErr_Format(PyExc_ImportError,
            "Bindings generation error. "
            "Submodule name should always start with a parent module name. "
            "Parent name: %s. Submodule name: %s", parent_name.c_str(),
            name.c_str()
        );
    }

    size_t submodule_name_end = name.find('.', parent_name.size() + 1);
    /// There is no intermediate submodules in the provided name
    if (submodule_name_end == std::string::npos)
    {
        submodule_name_end = name.size();
    }

    PyObject* submodule = parent_module;

    for (size_t submodule_name_start = parent_name.size() + 1;
         submodule_name_start < name.size(); )
    {
        const std::string submodule_name = name.substr(submodule_name_start,
                                                       submodule_name_end - submodule_name_start);

        const std::string full_submodule_name = name.substr(0, submodule_name_end);


        PyObject* parent_module_dict = PyModule_GetDict(submodule);
        /// If submodule already exists it can be found in the parent module dictionary,
        /// otherwise it should be added to it.
        submodule = PyDict_GetItemString(parent_module_dict,
                                         submodule_name.c_str());
        if (!submodule)
        {
2187
            /// Populates global modules dictionary and returns borrowed reference to it
2188
            submodule = PyImport_AddModule(full_submodule_name.c_str());
2189 2190 2191 2192 2193 2194 2195 2196
            if (!submodule)
            {
                /// Return `PyImport_AddModule` NULL with an exception set on failure.
                return NULL;
            }
            /// Populates parent module dictionary. Submodule lifetime should be managed
            /// by the global modules dictionary and parent module dictionary, so Py_DECREF after
            /// successfull call to the `PyDict_SetItemString` is redundant.
2197 2198 2199 2200 2201 2202 2203
            if (PyDict_SetItemString(parent_module_dict, submodule_name.c_str(), submodule) < 0) {
                return PyErr_Format(PyExc_ImportError,
                    "Can't register a submodule '%s' (full name: '%s')",
                    submodule_name.c_str(), full_submodule_name.c_str()
                );
            }
        }
2204

2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251
        submodule_name_start = submodule_name_end + 1;

        submodule_name_end = name.find('.', submodule_name_start);
        if (submodule_name_end == std::string::npos) {
            submodule_name_end = name.size();
        }
    }
    return submodule;
}

static bool init_submodule(PyObject * root, const char * name, PyMethodDef * methods, ConstDef * consts)
{
    // traverse and create nested submodules
    PyObject* submodule = createSubmodule(root, name);
    if (!submodule)
    {
        return false;
    }
    // populate module's dict
    PyObject * d = PyModule_GetDict(submodule);
    for (PyMethodDef * m = methods; m->ml_name != NULL; ++m)
    {
        PyObject * method_obj = PyCFunction_NewEx(m, NULL, NULL);
        if (PyDict_SetItemString(d, m->ml_name, method_obj) < 0)
        {
            PyErr_Format(PyExc_ImportError,
                "Can't register function %s in module: %s", m->ml_name, name
            );
            Py_CLEAR(method_obj);
            return false;
        }
        Py_DECREF(method_obj);
    }
    for (ConstDef * c = consts; c->name != NULL; ++c)
    {
        PyObject* const_obj = PyLong_FromLongLong(c->val);
        if (PyDict_SetItemString(d, c->name, const_obj) < 0)
        {
            PyErr_Format(PyExc_ImportError,
                "Can't register constant %s in module %s", c->name, name
            );
            Py_CLEAR(const_obj);
            return false;
        }
        Py_DECREF(const_obj);
    }
    return true;
2252 2253
}

2254
#include "pyopencv_generated_modules_content.h"
2255

2256
static bool init_body(PyObject * m)
2257
{
2258
#define CVPY_MODULE(NAMESTR, NAME) \
2259 2260 2261 2262
    if (!init_submodule(m, MODULESTR NAMESTR, methods_##NAME, consts_##NAME)) \
    { \
        return false; \
    }
2263 2264 2265 2266
    #include "pyopencv_generated_modules.h"
#undef CVPY_MODULE

#ifdef CVPY_DYNAMIC_INIT
2267
#define CVPY_TYPE(WNAME, NAME, _1, _2, BASE, CONSTRUCTOR) CVPY_TYPE_INIT_DYNAMIC(WNAME, NAME, return false, BASE, CONSTRUCTOR)
2268 2269
    PyObject * pyopencv_NoBase_TypePtr = NULL;
#else
2270
#define CVPY_TYPE(WNAME, NAME, _1, _2, BASE, CONSTRUCTOR) CVPY_TYPE_INIT_STATIC(WNAME, NAME, return false, BASE, CONSTRUCTOR)
2271 2272 2273 2274 2275 2276
    PyTypeObject * pyopencv_NoBase_TypePtr = NULL;
#endif
    #include "pyopencv_generated_types.h"
#undef CVPY_TYPE

    PyObject* d = PyModule_GetDict(m);
2277

2278

2279 2280 2281 2282 2283 2284 2285
    PyObject* version_obj = PyString_FromString(CV_VERSION);
    if (PyDict_SetItemString(d, "__version__", version_obj) < 0) {
        PyErr_SetString(PyExc_ImportError, "Can't update module version");
        Py_CLEAR(version_obj);
        return false;
    }
    Py_DECREF(version_obj);
2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298

    PyObject *opencv_error_dict = PyDict_New();
    PyDict_SetItemString(opencv_error_dict, "file", Py_None);
    PyDict_SetItemString(opencv_error_dict, "func", Py_None);
    PyDict_SetItemString(opencv_error_dict, "line", Py_None);
    PyDict_SetItemString(opencv_error_dict, "code", Py_None);
    PyDict_SetItemString(opencv_error_dict, "msg", Py_None);
    PyDict_SetItemString(opencv_error_dict, "err", Py_None);
    opencv_error = PyErr_NewException((char*)MODULESTR".error", NULL, opencv_error_dict);
    Py_DECREF(opencv_error_dict);
    PyDict_SetItemString(d, "error", opencv_error);


2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310
#define PUBLISH_(I, var_name, type_obj) \
    PyObject* type_obj = PyInt_FromLong(I); \
    if (PyDict_SetItemString(d, var_name, type_obj) < 0) \
    { \
        PyErr_SetString(PyExc_ImportError, "Can't register "  var_name " constant"); \
        Py_CLEAR(type_obj); \
        return false; \
    } \
    Py_DECREF(type_obj);

#define PUBLISH(I) PUBLISH_(I, #I, I ## _obj)

2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
    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);
2346
#undef PUBLISH_
2347 2348 2349 2350 2351
#undef PUBLISH

    return true;
}

A
Alexander Alekhin 已提交
2352 2353 2354 2355
#if defined(__GNUC__)
#pragma GCC visibility push(default)
#endif

2356
#if defined(CV_PYTHON_3)
2357 2358
// === Python 3

2359 2360 2361 2362 2363 2364 2365
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 已提交
2366
    special_methods
2367 2368
};

2369
PyMODINIT_FUNC PyInit_cv2();
2370
PyObject* PyInit_cv2()
2371 2372 2373 2374 2375 2376 2377 2378
{
    import_array(); // from numpy
    PyObject* m = PyModule_Create(&cv2_moduledef);
    if (!init_body(m))
        return NULL;
    return m;
}

2379
#else
2380
// === Python 2
A
Alexander Alekhin 已提交
2381
PyMODINIT_FUNC initcv2();
2382 2383
void initcv2()
{
2384 2385 2386 2387
    import_array(); // from numpy
    PyObject* m = Py_InitModule(MODULESTR, special_methods);
    init_body(m);
}
2388

2389
#endif