Boost Python无法将图像从python传递到c ++

问题描述 投票:-1回答:1

我正在尝试使用boost.python将图像从python传递到C ++。这是我的python代码:

import cv2
imgs = []
img1 = cv2.imread('img1.jpg')
img2 = cv2.imread('img2.jpg') 
imgs.append(img1)
imgs.append(img2)   
frame_size = imgs[0].shape[:2]
new_img = imwriteInC(imgs, frame.size[1], frame.size[0])

这是c ++代码:

#include <iostream>
#include <boost/pythong.hpp>
#include <Python.h>
using namespace cv;

bp::list imwriteInC(bp::list frames, int img_width, int img_height){
    Mat input_frame, new_frame;

    const char* first_frame = bp::extract<const char*>(bp::str(frames[0]));

    input_frame = Mat(img_height, img_width, CV_8UC3);  

    new_frame.create(input_frame.size(), CV_8UC3);
    size_t memsize = 3 * img_height * img_width;
    memcpy(new_frame.data, first_frame, memsize));

    imwrite("cImage.png", new_frame); 
    ...
    return outputList
}

原始图片应为:

enter image description here

但是,在将此图像传递给C ++之后,imwrite结果变为

enter image description here

我不擅长C ++。谁能指出如何修复它?提前致谢!

python c++ boost-python
1个回答
0
投票

看起来cv2图像通过缓冲协议公开它们的数据。在C层中,您可以使用set of functions来访问此数据。

示例用法,没有错误检查:

// get data into a buffer and check the size
Py_buffer view;
PyObject_GetBuffer(frames[0], &view, PyBUF_SIMPLE);
size_t memsize = 3 * img_height * img_width;
assert( memsize == view.len );

// copy data from buffer
Mat input_frame;
input_frame = Mat(img_height, img_width, CV_8UC3);
memcpy(input_frame.data, view.buf, memsize);

// release buffer
PyBuffer_Release(&view);
© www.soinside.com 2019 - 2024. All rights reserved.