How to write python wrapper for OpenCV C++ code

asked 2012-10-18 21:50:37 -0500

lightalchemist gravatar image

Hi, I'm trying to write a python wrapper for some C++ code that make use of OpenCV but I'm having difficulties returning the result, which is a OpenCV C++ Mat object, to the python interpreter.

At the moment, I'm using Boost Python to interface between Python and C++. While I'm able to pass my image from python to the C++ function (using some conversion code taken from OpenCV's legacy code that converts to CvMat/IplImage), I'm unable to return a Boost Python wrapped object to the python interpreter.

I know that I'm suppose to write a boost python converter but the resources I've found online (specifically the Boost Python website) only provide bits and pieces of code and does not clearly indicate how the bits of code should fit together.

I've also looked at the OpenCV source. I found some conversion functions in the file "cv2.cpp". In particular, the following seems relevant:

static PyObject* pyopencv_from(const Mat& m)
{
    if( !m.data )
        Py_RETURN_NONE;
    Mat temp, *p = (Mat*)&m;
    if(!p->refcount || p->allocator != &g_numpyAllocator)
    {
        temp.allocator = &g_numpyAllocator;
        m.copyTo(temp); // Segmentation fault here.
        p = &temp;
    }
    p->addref();
    return pyObjectFromRefcount(p->refcount);
}

However, while I'm able to run the code, it gives a segmentation fault at the commented line above. Can anyone point me to resources on how to wrap OpenCV code for Python?

edit retag flag offensive close merge delete

Comments

Have you figured out a way to do this?

b_m gravatar imageb_m ( 2013-03-04 09:43:17 -0500 )edit

has anyone resolved it?

deathracer99 gravatar imagedeathracer99 ( 2017-03-07 03:25:26 -0500 )edit

You need to write import_array() in the first line of this body, because apparently it is needed for initialization

kartik2112 gravatar imagekartik2112 ( 2017-12-01 00:47:46 -0500 )edit