如何使用Python / C API将numpy.ndarray转换为cv :: Mat?

时间:2014-03-26 16:18:37

标签: python c++ opencv numpy python-c-api

我使用python作为操作图像的接口,但是当我需要编写一些自定义函数来操作矩阵时,我发现当我迭代时numpy.ndarray太慢了。我想将数组传输到cv :: Mat,以便我可以轻松处理它,因为我曾经根据cv :: Mat结构编写用于图像处理的C ++代码。

my test.cpp:

#include <Python.h>
#include <iostream>

using namespace std;

static PyObject *func(PyObject *self, PyObject *args) {
    printf("What should I write here?\n");
    // How to parse the args to get an np.ndarray?
    // cv::Mat m = whateverFunction(theParsedArray);
    return Py_BuildValue("s", "Any help?");
}

static PyMethodDef My_methods[] = {
    { "func", (PyCFunction) func, METH_VARARGS, NULL },
   { NULL, NULL, 0, NULL }
};

PyMODINIT_FUNC initydw_cvpy(void) {
    PyObject *m=Py_InitModule("ydw_cvpy", My_methods);

    if (m == NULL)
        return;
}

main.py:

if __name__ == '__main__':
    print ydw_cvpy.func()

结果:

What should I write here?
Any help?

1 个答案:

答案 0 :(得分:0)

自从我使用原始C python绑定(我通常使用boost::python)以来,已经有一段时间了,但关键是PyArray_FromAny。一些未经测试的示例代码看起来像

PyObject* source = /* somehow get this from the argument list */

PyArrayObject* contig = (PyArrayObject*)PyArray_FromAny(source,
        PyArray_DescrFromType(NPY_UINT8),
        2, 2, NPY_ARRAY_CARRAY, NULL);
if (contig == nullptr) {
  // Throw an exception
  return;
}

cv::Mat mat(PyArray_DIM(contig, 0), PyArray_DIM(contig, 1), CV_8UC1,
            PyArray_DATA(contig));

/* Use mat here */

PyDECREF(contig); // You can't use mat after this line

请注意,这假设您有一个CV_8UC1数组。如果您有CV_8UC3,则需要要求三维数组

PyArrayObject* contig = (PyArrayObject*)PyArray_FromAny(source,
    PyArray_DescrFromType(NPY_UINT8),
    3, 3, NPY_ARRAY_CARRAY, NULL);
assert(contig && PyArray_DIM(contig, 2) == 3);

如果您需要处理任何随机类型的数组,您可能还想查看this answer