从numpy数组获取指针以将图像发送到C ++ [英] Get pointer from numpy array to send image to C++
问题描述
我正在做一个项目,必须处理 Python 和 C ++ 之间的图像.为了将图像从C ++发送到Python,我在图像的第一个像素上发送了一个指针(是OpenCV
库中的Mat
对象),在Python中有两个for循环,我使用了该指针来创建2D numpy数组.
I am working on a project on which I have to deal with images between Python and C++. In order to send an image from C++ to Python, I send a pointer on the first pixel of my image (being a Mat
object from OpenCV
library) and in Python with two for loops I used this pointer to create a 2D numpy array.
但是我不能以另一种方式做同样的事情:获取numpy 2D数组(图像)的第一个像素的内存地址,并将其传递给C ++.
But I don't succeed to do the same in the other way : get the memory address of the first pixel of the numpy 2D array (an image) and pass it to the C++.
假设x是我的图像(二维numpy数组),我尝试了以下解决方案:
Assume x is my image (2D numpy array), I tried solution like :
-
x.__array_interface__['data'][0]
,但这给出一个整数,而不是地址 -
x.data
每次调用它都会赋予不同的值,因为它给了我一个临时缓冲区的地址,而不是图像本身
x.__array_interface__['data'][0]
but this give an integer, not an addressx.data
which give different values each time I call it because it gives me the address of a temporary buffer, not the image itself
在此先感谢您的任何建议/帮助.
Thank you in advance for any advice/help.
推荐答案
我发现了一种简单"的方法:
I found a "simple" way to do that:
在 C ++ 中,该函数必须将void * ptr
作为参数,这样,我可以使用从Python发送来的指针创建Mat对象:
In C++, the function has to take as argument a void * ptr
, and like this I can create a Mat object using the pointer sent from Python :
void myCfunction(void* ptr){
Mat matrix = Mat(sizes, CV_8UC1, (uchar*)ptr);
}
然后,在 Python 中,使用__array_interface__
获取内存地址(以int类型,很奇怪):
And, in Python, use __array_interface__
to get the memory address (in int type, weird) :
mydll.myFunction(myNumpyArray.__array_interface__['data'][0], ...)
这篇关于从numpy数组获取指针以将图像发送到C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!