我使用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/