【问题标题】:How to convert the numpy.ndarray to a cv::Mat using Python/C API?如何使用 Python/C API 将 numpy.ndarray 转换为 cv::Mat?
【发布时间】:2014-05-05 05:09:42
【问题描述】:

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

我的 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?

【问题讨论】:

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


    【解决方案1】:

    我已经有一段时间没有使用原始 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,你需要一个 3 维数组

    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

    【讨论】:

      猜你喜欢
      • 2012-10-22
      • 1970-01-01
      • 2022-06-25
      • 1970-01-01
      • 2017-06-03
      • 2018-07-17
      • 1970-01-01
      • 2016-08-16
      • 2018-04-16
      相关资源
      最近更新 更多