将图像从python包装器传递到C ++函数

时间:2019-03-15 13:59:00

标签: c++ python-3.x ctypes opencv-python

我想将图像从python代码传递给c ++函数。我的c ++函数位于.so文件中,并使用ctypes加载到python中。 c ++函数采用类型Mat的参数。参数(即图片)是从Python(使用opencv)传递的。

当我尝试运行上述情况时,它会引发如下错误;

  

ctypes.ArgumentError:参数1::不知道如何转换参数1

我的代码如下: test.py

import cv2
from ctypes import *

testso = CDLL("./libvideoread.so")
cap = cv2.VideoCapture("Bigbunny.mp4")
if(cap.isOpened == False):
    print("error")
else:
    frame_width = int(cap.get(3))
    frame_height = int(cap.get(4))
    cv2.namedWindow('frame',cv2.WINDOW_NORMAL)
    while(cap.isOpened):
       ret,frame = cap.read()
       if ret:
          testso.imgread(frame)
       else:
           break

cap.release()
cv2.destroyAllWindows()

cpp代码:

void imgread(Mat frame)
{
     /*Do something*/
}

在线检查错误,并且知道Opencv-python将图像数据转换为numpy数组。而Opencv-c ++使用Mat类型。因此,如何将numpy数组转换为Mat类型或将python的Image转换为c ++函数。

我不想使用Boost :: python

谢谢。

1 个答案:

答案 0 :(得分:0)

我终于找到了解决问题的办法。

我不得不将mat格式转换为numpy数组。并将此数组作为参数传递给cpp函数 imgread()

cpp函数 imgread()需要将其作为char指针接收,然后将其转换为mat。

修改后的test.py;

import cv2
from ctypes import *

testso = CDLL("./libvideoread.so")
cap = cv2.VideoCapture("Bigbunny.mp4")
if(cap.isOpened == False):
    print("error")
else:
    frame_width = int(cap.get(3)) # Width is 1280
    frame_height = int(cap.get(4)) # Height is 720
    cv2.namedWindow('frame',cv2.WINDOW_NORMAL)
while(cap.isOpened):
   ret,frame = cap.read()
   if ret:
      # Next 3 lines convert frame data to numpy array
      testarray1 = np.fromstring(frame, np.uint8) 
      testarray2 = np.reshape(testarray1, (720, 1280, 3))
      framearray = testarray2.tostring()

      #Send framearray to the cpp function.
      testso.imgread(framearray)
   else:
       break

 cap.release()
 cv2.destroyAllWindows()

在cpp端;

void imgread(unsigned char* framedata)
{
  cv::Mat frame(cv::Size(1280,720), CV_8UC3, framedata);
   /*Do something*/
}

干杯。