1

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.

Sam R.
  • 16,027
  • 12
  • 69
  • 122
flankechen
  • 1,225
  • 16
  • 31

1 Answers1

2

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:

Sam R.
  • 16,027
  • 12
  • 69
  • 122
berak
  • 39,159
  • 9
  • 91
  • 89
  • Thanks for the suggetion. the image is not right(much better than before),after I change it to wb, rb mood. I am wondering whether the image is really CV_8UC1 type. – flankechen Aug 11 '13 at 09:14
  • OMG, I get thins right after I change image(640,480,CV_8UC1,buffer); to image(480,640,CV_8UC1,buffer); it's rows then cols. what a mistake, thanks a lot! – flankechen Aug 11 '13 at 09:26