【问题标题】:Boost Python cannot pass image from python to c++Boost Python无法将图像从python传递到c++
【发布时间】: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&lt;const char*&gt;(bp::str(img)); 好像还缺少什么。 img 是什么?如果我将这两个代码块复制到文件中并构建它们并运行它,我会得到你的结果吗?还是会出现编译错误?
  • 我不认为bp::str(frames[0]) 做你想做的事。文档表明它与在 python 中调用 str(frames[0]) 相同。您需要一个公开图像底层缓冲区的函数。
  • @Dunes 是的,你是对的。事实证明 bp::str(frames[0]) 只是将 numpy 数组中的所有内容都转换为字符串,甚至是 [ 符号和空格。你能给我一些关于如何暴露图像底层缓冲区的提示吗?我试过 PyBytes_AsString,它也没有用。谢谢!

标签: python c++ boost-python


【解决方案1】:

看起来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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 2014-02-22
    • 2017-09-21
    • 1970-01-01
    • 2019-01-20
    • 2012-08-25
    相关资源
    最近更新 更多