【发布时间】:2019-03-17 16:17:42
【问题描述】:
我正在尝试使用 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
}
原图应为:
但是,将这张图片传入C++之后,imwrite的结果就变成了
我不擅长 C++。谁能指出如何解决它?提前致谢!
【问题讨论】:
-
我们缺少很多代码和细节。确保我们只能使用您提供的信息重现您的问题。如果您无法在没有您错过的信息的情况下复制它,那么我们也不能!
-
@LightnessRacesinOrbit 感谢您的提示。我已经编辑了问题描述。
-
const char* first_frame = bp::extract<const char*>(bp::str(img));好像还缺少什么。img是什么?如果我将这两个代码块复制到文件中并构建它们并运行它,我会得到你的结果吗?还是会出现编译错误? -
我不认为
bp::str(frames[0])做你想做的事。文档表明它与在 python 中调用str(frames[0])相同。您需要一个公开图像底层缓冲区的函数。 -
@Dunes 是的,你是对的。事实证明
bp::str(frames[0])只是将 numpy 数组中的所有内容都转换为字符串,甚至是[符号和空格。你能给我一些关于如何暴露图像底层缓冲区的提示吗?我试过 PyBytes_AsString,它也没有用。谢谢!
标签: python c++ boost-python