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

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

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

我的测试.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;
}

主要.py:

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

结果:

What should I write here?
Any help?

最佳答案

自从我使用原始 C python 绑定(bind)(我通常使用 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 .

关于python - 如何使用 Python/C API 将 numpy.ndarray 转换为 cv::Mat?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22667093/

相关文章:

python - 为什么这个 xlsx 文件打不开?

c++ - 如何使用快速傅立叶变换计算数组元素的乘积之和?

python - openCV python,从闭合曲线中获取区域

Python Scikit Learn GMM 结果与 R Mclust 不一致

python - 用多个字典值替换字符串中的单词?

python - 在 Python 上重命名远程服务器上的文件

c++ - Code::Blocks w/MinGW:将 libpng 静态链接到 dll

c++ - 指针解引用运算符 ( (*) vs -> )

python - Opencv:使用 python 导入 highgui

python - 在hough函数中传递math.pi(pi编号)的原因是什么?