我必须将 C++ 中的图像矩阵转换为字符串。 我找到了两种方法:
const char *inputD = (const char*)(img.data);
Size imageSiz = img.size();
int w = imageSiz.width;
int h = imageSiz.height;
int ch = img.channels();
_return.append(inputD, w*h*ch);
其中 _return 是:
std::string& _return
而且这个一直在工作。但我还找到了另一种方法:
string matAsStringL (imgL.begin<unsigned char>(), imgL.end<unsigned char>());
_return.push_back(matAsStringL);
当然 _return 是不同的:
std::vector<std::string> & _return
但第二个不适用于彩色图像,而仅适用于灰度图像。为什么?我想了解一下。
我从第二个错误中得到的错误是: 未知函数中断言失败 (elemSize() == sizeof(_Tp))。在mat.hpp中
一个例子是:
img1 = imread(filenameL , 0); //Gray_scale
string matAsStringI(img1.begin<unsigned char>(), img1.end<unsigned char>());
//now in matAsString I have the info I need
cvtColor(img1, coloredImage1, CV_GRAY2RGB);
string matAsStringC(coloredImage1.begin<unsigned char>(), coloredImage1.end<unsigned char>()); //crash here with the assertion error
不适用于 colorImage1,但适用于 img1。如果我更改为 colorImage1 并且使用第一种方法,它工作得很好。
最佳答案
您可以直接在字符串构造函数中使用 mat 迭代器,但您只会获得每个像素的第一个无符号字符,而不是所有数据。
您必须对第一个和第二个解决方案做出妥协,例如
#include <string>
#include <vector>
#include <opencv2/opencv.hpp>
int main()
{
const char *path = "/home/gerard_gaudeau/Downloads/image.jpg";
cv::Mat mat = cv::imread(path);
cv::Size size = mat.size();
int total = size.width * size.height * mat.channels();
std::cout << "Mat size = " << total << std::endl;
std::vector<uchar> data(mat.ptr(), mat.ptr() + total);
std::string s(data.begin(), data.end());
std::cout << "String size = " << s.length() << std::endl;
return 0;
}
关于c++ - 图像矩阵转字符串 OpenCV C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23391503/