Exposing OpenCV-based C++ function with Mat/Numpy conversion to Python

对着背影说爱祢 提交于 2019-12-06 02:26:12

The problem was not the

PyEnsureGIL gil;

statement. That only didn't work if I tried to use an external C++ function. The problem actually happened when I tried to pack two output values into one here:

return Py_BuildValue("(NN)", pyopencv_from(edgeGrad), pyopencv_from(edgeOri));

The temporary work-around was just to use the following statement:

return pyopencv_from(edgeGrad);

EDIT: Sorry, I messed up again. The Py_BuildValue works just fine. Just tested my function again, it works perfectly. I must have forgotten to put the return keyword last time I tested it, so it gave me "error return without exception set."

Here's the full function code (I hope it's useful for anyone porting OpenCV stuff to python)

static PyObject* pycvex_findEdgesCGTG(PyObject* , PyObject* args, PyObject* kw)
{
    PyObject* pyobj_source = NULL;
    Mat source;
    Mat edgeGrad;
    Mat edgeOri;
    const char* keywords[] = { "src", NULL };
    if( PyArg_ParseTupleAndKeywords(args, kw, "O:findEdgesCGTG", (char**)keywords, &pyobj_source) &&
        pyopencv_to(pyobj_source, source));
    {
        ERRWRAP2(findEdgesCGTG(source,edgeGrad,edgeOri));
        return Py_BuildValue("(NN)", pyopencv_from(edgeGrad), pyopencv_from(edgeOri));
    }
    return NULL;
}

UPDATE:

Here is the github repo with the open C++ code I wrote for exposing code using OpenCV's Mat class with as little pain as possible. This is for OpenCV 3.X.

For OpenCV 2.X you can use this code / example by Yati Sagade. If you'd like to expose functions using the opencv Mat class without worrying about explicit conversions, it's easy to adapt the Booost converters from my code with the conversion functions in Yati's code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!