Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

How to write python wrapper for OpenCV C++ code

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( ! )
    Mat temp, *p = (Mat*)&m;
    if(!p->refcount || p->allocator != &g_numpyAllocator)
        temp.allocator = &g_numpyAllocator;
        m.copyTo(temp); // Segmentation fault here.
        p = &temp;
    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?