我是opencv编程的初学者,我试图读取图像(cv :: Mat)并将其数据复制到Uchar的某个矢量,然后从矢量中创建图像。
即阅读Mat,将Mat转换为std :: vector,然后再次从该向量创建Mat。
像素数据的中间转换需要矢量。 我提到了 Convert Mat to Array/Vector in OpenCV
对于vector-Mat的转换。
int main()
{
Mat image = imread("c:\\cv\\abc.bmp");
std::vector<unsigned char> src_vec;
src_vec.assign(image.datastart, image.dataend);
cv::Mat dest(src_vec, true);
try {
imwrite("dest.bmp", dest);
}
catch (runtime_error& ex) {
fprintf(stderr, "Exception saving the image: %s\n", ex.what());
return 1;
}
return 0;
}
输出图像似乎是垃圾,如何使用矢量数据设置dest Mat,或者我是以错误的方式创建矢量本身。 任何指导都会有所帮助。
答案 0 :(得分:1)
您缺少标题信息。
vector
仅包含像素数据。您必须在某处保存标题数据并再次将其传递给mat
。
在以下示例中,标题数据直接从源图像中获取。您也可以将其保存在某些整数变量中,并再次将其传递给新mat
的标题。
Mat image = imread("c:\\cv\\abc.bmp");
std::vector<unsigned char> src_vec;
src_vec.assign(image.datastart, image.dataend);
cv::Mat dest(image.rows,image.cols,image.type());
dest.data = src_vec.data();
try {
imshow("sss", dest);
cv::waitKey();
//or show using imshow - nothing is shown
}
catch (runtime_error& ex) {
fprintf(stderr, "Exception saving the image: %s\n", ex.what());
return 1;
}
return 0;
P.S。尽量不要使用\\
它是Windows的东西。使用/
,它是跨平台的。