Writing cv::Mat data is failed
Hi, I'm trying to read and write the data array of a cv::Mat only as a binary file. I saved the array like below.
FILE *file = fopen(file_name, "wb");
fwrite(mat.data, sizeof(char), height * width * 3, file); // RGB image
fclose(file);
Then I read it like below.
FILE *file2 = fopen(file_name, "rb");
fread(data, sizeof(char), height * width * 3, file2);
fclose(file2);
cv::Mat image(height, width, CV_8UC3, data);
It's fine when I check the result like this.
std::cout << data[height * width * 3 - 1] << image.at<cv::Vec3b>(height - 1, width - 1) << std::endl;
The last value of the "data" array and the red value of the last pixel of the cv::Mat image was the same. (ex, 37[41, 32, 37]) However, after I write the cv::Mat image again, the some pixel values are...destoyed like below. (ex, [127, 0, 0])
cv::imwrite(path, image);
cv::Mat test = cv::imread(path);
std::cout << test.at<cv::Vec3b>((height - 1, width - 1)) << std::endl;
The most of the pixels are OK but usually some of the last pixels are destroyed. Did I something wrong? Also, I read the binary file and save it as a image file using python cv2, that was OK. What should I do in C++?
Wait, Your saving of the array is done using
fread
? I would say you needfwrite
for that?Oh, it was a typo, sorry. I did it using fwrite.
I am wondering if you write a 8bit 3 channel image with a char iterator, and then read it back using char iterator, don't we drop precision? That might be what is happening here, because of the clear zeros, something like value overflow...
I called cvtcolor (rgba to rgb) first before writing the binary file. Will it be a problem?
it is wrong :
it should be
see Creating a Mat object explicitly
Alright, another typo again, sorry.
i used before
matwrite
andmatread
functions implemented by Miki the code is hereIs there any way to read the data written already? I think it is not the problem of the written data because it has no problem on the python cv2.
what do you mean "data written already?".
matread
reads files written bymatwrite