Reputation: 1255
When I try to fwrite an image data, captured from camera with OpenCV, and read them out, things are not getting right. I try them in many format like CV_8UC3 and CV_UC1 gray images.
Firstly, I captured an image(640*480) from the camera and save the data to a file
VideoCapture cap(0);
namedWindow("test",0);
namedWindow("gray",0);
FILE *f=fopen("data.txt","wt+");
while(1)
{
Mat frame;
cap>>frame;
imshow("test", frame);
//Mat temp(1, 1, CV_8UC3);
Mat gray;
if(waitKey(30) >= 0)
{
cvtColor(frame, gray, CV_BGR2GRAY);
imshow("gray", gray);
waitKey();
fwrite(gray.data, sizeof(unsigned char), 640*480,f);
break;
}
}
fclose(f);
return 0;
then in another program, I try to read them out like:
FILE *f = fopen("data.txt", "rt");
unsigned char* buffer;
size_t result;
buffer = (unsigned char*)malloc(sizeof(unsigned char)*640*480);
result = fread(buffer, sizeof(unsigned char), 640*480,f);
fclose(f);
Mat image(640, 480, CV_8UC1, buffer);
namedWindow("test", 0);
imshow("test", image);
waitKey();
image goes wrong then.
Thanks for any kind of suggestions.
Upvotes: 1
Views: 8028
Reputation: 39796
you can't save binary data in txt mode.
should be
FILE *f=fopen("data.txt","wb");
instead of :
FILE *f=fopen("data.txt","wt+");
// btw, what's the + for ? appending does not make any sense here
same for your read operation. ("rb" instead of "rt" )
but again, why all of this even? use the built-in stuff:
Upvotes: 2