0

I am using cvtColor to convert an image from YUYV format to RGB24. The output is fine as far as color is concerned but half of the image is cut. The image is 640x480 YUYV image buffer without any headers. I am using the following code:

 FILE* fd = fopen("imgdump", "r+b");

 char buffer[640*480*2]; // Each pixel takes two bytes in YUYV

 if (fd != NULL)
 {
     fread(buffer, sizeof(char), 640*480*2, fd);
     fclose(fd);
 }

 Mat s_sImageMat = Mat(640, 480, CV_8UC2);  
 Mat s_sConvertedImageMat;

 cout << "before conversion\n";
 s_sImageMat.data = (uchar*) buffer;
 cvtColor(s_sImageMat, s_sConvertedImageMat, CV_YUV2RGB_YUYV);
 cout << "after conversion\n";

 FILE* fw = fopen("converted", "w+b");

 if (fw != NULL)
 {
     fwrite((char*)s_sConvertedImageMat.data, sizeof(char), 640*480*2, fw);
     fclose(fw);
 }

Original Converted

Original file: https://drive.google.com/file/d/0B0YG1rjiNkBUQ0ZuaWN6Y1E2LUU/view?usp=sharing

Additional info: I am using opencv 3.2

Daniyal Yasin
  • 142
  • 1
  • 14
  • 1
    `s_sImageMat.data = (uchar*) buffer;` -- yikes, you're swapping the buffer without the owner's knowledge, and leaking the old one? Why don't you use an appropriate [`cv::Mat` constructor](http://docs.opencv.org/3.1.0/d3/d63/classcv_1_1Mat.html#a51615ebf17a64c968df0bf49b4de6a3a) instead? – Dan Mašek Mar 20 '17 at 02:29
  • I'm aware that it won't make a difference on the conversion, but that's not an excuse for doing something that causes a memory leak. Don't get into habit of writing code like this. – Dan Mašek Mar 20 '17 at 02:36
  • Anyway, there seems to be a significant part missing from the code you show. Can you please attach a full [MCVE](https://stackoverflow.com/help/mcve), along with an input that will allow us to reproduce this issue? – Dan Mašek Mar 20 '17 at 02:43
  • Image file and a full MCVE given now. – Daniyal Yasin Mar 20 '17 at 03:53

1 Answers1

1

The issue seems to be in the following line :

fwrite((char*)s_sConvertedImageMat.data, sizeof(char), 640*480*2, fw);

For RGB24, it should be be :

fwrite((char*)s_sConvertedImageMat.data, sizeof(char), 640*480*3, fw);

Each pixel is 3 bytes in RGB24

Jeru Luke
  • 20,118
  • 13
  • 80
  • 87