从 numpy 数组获取指针以将图像发送到C++

Get pointer from numpy array to send image to C++

本文关键字:图像 C++ numpy 数组 获取 指针      更新时间:2023-10-16

我正在做一个项目,我必须处理PythonC++之间的图像。为了将图像从C++发送到 Python,我在图像的第一个像素上发送一个指针(是库中Mat对象OpenCV在 Python 中有两个 for 循环,我使用此指针创建了一个 2D numpy 数组。

但是我没有成功地以另一种方式做同样的事情:获取numpy 2D数组(图像(的第一个像素的内存地址并将其传递给C++。

假设 x 是我的图像(2D numpy 数组(,我尝试了这样的解决方案:

  • x.__array_interface__['data'][0]但这给出了一个整数,而不是一个地址
  • x.data每次调用它时都会给出不同的值,因为它给了我临时缓冲区的地址,而不是图像本身

提前感谢您的任何建议/帮助。

我找到了一种"简单"的方法:

在C++中,该函数必须将void * ptr作为参数,像这样,我可以使用从 Python 发送的指针创建一个 Mat 对象:

void myCfunction(void* ptr){
Mat matrix = Mat(sizes, CV_8UC1, (uchar*)ptr);
}

并且,在Python中,使用__array_interface__获取内存地址(int 类型,奇怪(:

mydll.myFunction(myNumpyArray.__array_interface__['data'][0], ...)

在如何获取 C 的 numpy 数组的内存地址中也用__array_interface__,返回的整数是指向数组数据的指针,没有内存地址:

数据(可选(

一个 2 元组,其第一个参数是一个整数(如有必要,是一个长整数(,它指向存储数组内容的数据区域。 此指针必须指向数据的第一个元素(换句话说 在这种情况下,任何偏移量始终被忽略(。第二个条目 元组是只读标志(true 表示数据区域是只读的(。

此属性也可以是公开将用于共享数据的缓冲区接口的对象。如果此键不存在(或 返回 None(,然后内存共享将通过缓冲区完成 对象本身的接口。在这种情况下,偏移键可以是 用于指示缓冲区的开始。对对象的引用 公开数组接口必须由新对象存储,如果 内存区域是要保护的。

默认值:无

来源 : https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.interface.html

您可以看到__array_interface__返回的整个词典的内容print x.__array_interface__[]

__array_struct__包含一个指向数组第一个元素的不同 C 指针,您可以从 C(++( 代码中访问它,示例如下 http://blog.audio-tk.com/2008/11/04/exposing-an-array-interface-with-swig-for-a-cc-structure/:

'

C 结构访问

这种阵列接口方法允许更快地访问 数组仅使用一个属性查找和定义良好的 C 结构。

__array_struct__

A :c:type:PyCObject,其voidptr成员包含指向填充的PyArrayInterface结构的指针。结构的内存是 动态创建,并且 PyCObject 也使用 适当的析构函数,因此此属性的检索器只需具有 将Py_DECREF应用于此属性返回的对象,当它 完成。此外,要么需要复制数据,要么需要引用 必须向对象公开此属性,以确保数据 没有被释放。公开__array_struct__接口的对象必须 如果其他对象正在引用,也不会重新分配其内存 他们。

PyArrayInterface 结构在numpy/ndarrayobject.h中定义为:

typedef struct {
int two;              /* contains the integer 2 -- simple sanity check */
int nd;               /* number of dimensions */
char typekind;        /* kind in array --- character code of typestr */
int itemsize;         /* size of each element */
int flags;            /* flags indicating how the data should be interpreted */
/*   must set ARR_HAS_DESCR bit to validate descr */
Py_intptr_t *shape;   /* A length-nd array of shape information */
Py_intptr_t *strides; /* A length-nd array of stride information */
void *data;          --------> /* A pointer to the first element of the array */ < ------
PyObject *descr;      /* NULL or data-description (same as descr key
of __array_interface__) -- must set ARR_HAS_DESCR
flag or this will be ignored. */
} PyArrayInterface;

来源 : https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.interface.html