我有一个cv::Mat
大小的2064x1544
,我想将其另存为std::string
。
我的代码很简单:
std::string image_string(image.begin<unsigned char>(), image.end<unsigned char>());
json["image"] = image_string;
正如我在问题标题中所写的那样,我遇到了这个错误:
std::bad_alloc
出什么问题了?
答案 0 :(得分:1)
我建议您在尝试使用OpenCV的cv::imencode
函数,因为它更灵活,更安全。
您可以使用此功能将cv::Mat
转换为std::string
。
请注意,您需要指定图像格式。您可能想要将“ .png”更改为“ .jpg”或cv::imencode(...)
支持的任何内容。
std::string get_mat_as_string(const cv::Mat& cv_buffer_orig) {
std::stringstream ss;
if (!cv_buffer_orig.empty()) {
try {
std::vector<uint8_t> buffer;
cv::imencode(".png", cv_buffer_orig, buffer);
for (auto c : buffer) ss << c;
} catch (std::exception& e) { std::cerr << e.what() << std::endl; }
}
return ss.str();
}
要在您要使用的std :: string中检索编码的cv :: Mat
std::string buffer; // must contain encoded image from above function
std::vector<byte> pic_data(buffer.begin(), buffer.end());
cv::Mat mat(pic_data, true);
mat = cv::imdecode(mat, cv::IMREAD_COLOR);
现在mat
包含原始的cv :: Mat。
我最初编写此代码(略作编辑)是为了通过网络传输cv::Mat
,您可以自行决定使用它。