python调用c++传送图片踩坑

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

加了上面那句代码后就能完整读取了。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值