[英]Passing a structre from Python to C++ OR passing a numpy array instead of file address to Yolo
I am trying pass in-memory images to Yolo rather than file addresses. 我正在尝试将内存中的图像传递给Yolo,而不是文件地址。
In the source code it reads the image using openCV. 在源代码中,它使用openCV读取图像。 Since openCV return a mat format in c++ then it converts mat format to image format using
mat_to_image(mat im)
function. 由于openCV返回c格式的mat格式,因此它将使用
mat_to_image(mat im)
函数将mat格式转换为图像格式。 But opencv in python uses numpy.ndarray
so I cant use mat_to_image()
. 但是python中的opencv使用
numpy.ndarray
所以我不能使用mat_to_image()
。
So I tried to put the numpy array in image format myself following the authors code here we have: 所以我尝试按照我们在此处的作者代码将numpy数组自己放入图像格式:
class IMAGE(ctypes.Structure):
_fields_ = [("w", ctypes.c_int),
("h", ctypes.c_int),
("c", ctypes.c_int),
("data", ctypes.POINTER(ctypes.c_float))]
Here is what I have: 这是我所拥有的:
import darknet as dn
im = cv2.imdecode(in-memory_bytelike_object, cv2.IMREAD_COLOR)
h,w,c = im.shape
my_image = IMAGE()
my_image.w = ctypes.c_int(w)
my_image.h = ctypes.c_int(h)
my_image.c = ctypes.c_int(c)
my_image.data = im.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
print(dn.detect(net, meta, my_image))
I also changed detect
function in this way: 我还以这种方式更改了
detect
功能:
def detect(net, meta, image, thresh=.5, hier_thresh=.5, nms=.45):
# im = load_image(image, 0, 0) //image_address->mat (using cv2)-> image (using mat_to_image) and return image
im = image
...
but when I run it I get this error: 但是当我运行它时,出现此错误:
ArgumentError: argument 2: <class 'TypeError'>: expected IMAGE instance instead of IMAGE
I guess the problem is that I am not passing the data structure in the right way but I'm not sure. 我想问题是我没有以正确的方式传递数据结构,但我不确定。
I read some other answers about passing a data structure between Python and C++ but I think in my case there should be a simpler solution. 我阅读了一些其他有关在Python和C ++之间传递数据结构的答案,但我认为应该有一个更简单的解决方案。
Well I managed to do it in this way: 好吧,我设法做到了:
here is how you can convert a numpy array to image format: 这是将numpy数组转换为图像格式的方法:
import darknet as dn
def array_to_image(arr):
arr = arr.transpose(2,0,1)
c = arr.shape[0]
h = arr.shape[1]
w = arr.shape[2]
arr = (arr/255.0).flatten()
data = dn.c_array(dn.c_float, arr)
im = dn.IMAGE(w,h,c,data)
return im
Use the modified version of detect
function as mentioned in the question. 使用问题中提到的
detect
功能的修改版本。
so it goes like this: 所以它是这样的:
im = cv2.imdecode(in-memory_bytelike_object, cv2.IMREAD_COLOR)
im = array_to_image(arr)
dn.rgbgr_image(im)
print(dn.detect(net, meta, im))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.