lib = ctypes.CDLL(r'D:\code\cpp\demo\x64\Debug\demo.dll')
# 定义函数参数
filename = 'D:\\code\\capt.png' # 替换为你的图片路径
width = c_int(0)
height = c_int(0)
channels = c_int(0)
# 调用C++函数
lib.ReadImage.restype=ctypes.POINTER(ctypes.c_ubyte)
imageData=lib.ReadImage(c_char_p(filename.encode()), pointer(width), pointer(height), pointer(channels))
data=ctypes.cast(imageData,ctypes.POINTER(ctypes.c_ubyte*width.value*height.value*3)).contents
# 从ctypes类型转换为Python类型
image_array = np.frombuffer(data, dtype=np.uint8,count=-1).reshape((height.value, width.value, channels.value))
# 使用OpenCV显示图像
cv2.imshow('Image', image_array)
cv2.waitKey(0)
cv2.destroyAllWindows()
#include <opencv2/opencv.hpp>
extern "C" {
__declspec(dllexport) unsigned char* ReadImage(const char* filename, int* width, int* height, int* channels) {
cv::Mat img = cv::imread(filename, cv::IMREAD_COLOR);
if (img.empty()) {
*width = *height = *channels = 0;
return nullptr;
}
*width = img.cols;
*height = img.rows;
*channels = img.channels();
unsigned char* imageData = new unsigned char[img.cols * img.rows * img.channels()*sizeof(unsigned char)];
memcpy(imageData, img.data, img.cols * img.rows * img.channels() *sizeof(unsigned char));
return imageData;
}
}
尝试使用c++读取图片数据然后传送给python,python端收到的数据远小于传送的数据,经排查发现ctypes会在'\0'处截断,所以需要给定读取的范围。
data=ctypes.cast(imageData,ctypes.POINTER(ctypes.c_ubyte*width.value*height.value*3)).contents
加了上面那句代码后就能完整读取了。