我想用C ++计算某些东西并将结果返回给python。这是C ++代码的一部分:
mTextPaint.setColor
运行python脚本时的错误是:
private BitmapDrawable addTextOnImage(BitmapDrawable bitmapDrawable) {
Spanned caption = Html.fromHtml("<b style=\"color: rgb(255, 0, 0);\">Test</b>", Html.FROM_HTML_MODE_LEGACY);
Bitmap bitmap_largest_image = bitmapDrawable.getBitmap().copy(Bitmap.Config.ARGB_8888, true);
TextPaint mTextPaint = new TextPaint();
//mTextPaint.setColor(Color.WHITE);
mTextPaint.setTextSize(30);
StaticLayout mTextLayout_caption = StaticLayout.Builder.obtain(caption, 0, caption.length(), mTextPaint, bitmap_largest_image.getWidth()).build();
Paint backgrounds_paint = new Paint();
backgrounds_paint.setColor(Color.BLACK);
backgrounds_paint.setStyle(Paint.Style.FILL);
Bitmap final_bitmap = Bitmap.createBitmap(bitmap_largest_image.getWidth(), mTextLayout_caption.getHeight() + bitmap_largest_image.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(final_bitmap);
canvas.drawRect(0, 0, bitmap_largest_image.getWidth(), mTextLayout_caption.getHeight(), backgrounds_paint);
mTextLayout_caption.draw(canvas);
canvas.drawBitmap(Bitmap.createScaledBitmap(bitmap_largest_image, bitmap_largest_image.getWidth(), bitmap_largest_image.getHeight(), false), 0, mTextLayout_caption.getHeight(), new Paint());
return new BitmapDrawable(getActivity().getResources(), final_bitmap);
}
调试后,我发现错误来自以下行:
const Mat& flow_map_x, flow_map_y;
std::vector<unchar> encoded_x, encoded_y;
flow_map_x = ...;
flow_map_y = ...;
Mat flow_img_x(flow_map_x.size(), CV_8UC1);
Mat flow_img_y(flow_map_y.size(), CV_8UC1);
encoded_x.resize(flow_img_x.total());
encoded_y.resize(flow_img_y.total());
memcpy(encoded_x.data(), flow_img_x.data, flow_img_x.total());
memcpy(encoded_y.data(), flow_img_y.data, flow_img_y.total());
bp::str tmp = bp::str((const char*) encoded_x.data())
我不擅长C ++。谁能告诉我如何解决该错误?预先感谢!
答案 0 :(得分:0)
您不能这样做,因为encoded_x.data()
不是UTF-8。您可能需要bytes
作为原始数据的副本:
使用PyObject* PyBytes_FromStringAndSize(const char *v, Py_ssize_t len)
。或者,您可以将PyByteArray_FromStringAndSize
用于具有相同参数的bytearray
。
bp::object tmp(bp::handle<>(PyBytes_FromStringAndSize(
// Data to make `bytes` object from
reinterpret_cast<const char*>(encoded_x.data()),
// Amount of data to read
static_cast<Py_ssize_t>(encoded_x.size())
)));
在这种情况下,您可以摆脱向量并直接使用flow_img_x.data
和flow_img_x.total()
。
或者使用memoryview
来不复制数据,而只是访问std::vector
的数据
使用PyObject* PyMemoryView_FromMemory(char *mem, Py_ssize_t size, int flags)
bp::object tmp(bp::handle<>(PyMemoryView_FromMemory(
reinterpret_cast<char*>(encoded_x.data()),
static_cast<Py_ssize_t>(encoded_x.size()),
PyBUF_WRITE // Or `PyBUF_READ` i if you want a read-only view
)));
(如果向量是const,则您将const_cast<char*>(reinterpret_cast<const char*>(encoded_x.data()))
并且仅使用PyBUF_READ
)
在这种情况下,您必须确保引导程序仍然有效,但是不会创建不必要的副本。