i have code to read YUV 4:2:0 file. I wanna convert the YUV to RGB color space. Below is my trial code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct _IMAGE_BUF
{
int width;
int height;
int Total;
unsigned char* buf;
}IMAGE_BUF;
int clamp(int val){
if(val>255) return 255;
if(val<0) return 0;
return val;
}
int main(){
FILE *f_img,*f_out;
FILE *f_y,*f_u,*f_v,*f_buff,*f_RGB;
int i, j;
IMAGE_BUF y,u,v,buff,RGB;
int frm, numfrm;
int face_num;
FILE *f_outy, *f_outu, *f_outv;
int width, height;
width = 416;
height = 240;
f_img=fopen("RaceHorses_416x240_30.yuv","rb");
f_RGB=fopen("RGB_416x240_30.rgb","wb");
f_buff=fopen("buff_416x240_30.yuv","wb");
fseek(f_img,0,SEEK_END);
numfrm = ftell(f_img);
numfrm /= ((width * height * 3)>> 1);
fseek(f_img,0,SEEK_SET);
buff.buf = (unsigned char*)malloc(width * height *1.5*sizeof(unsigned char));
RGB.buf = (unsigned char*)malloc(width * height *sizeof(unsigned char));
for(frm = 0 ; frm < numfrm ; frm++)
{
fread(buff.buf, sizeof(unsigned char), (width * height)*1.5, f_img);
for (int j=0;j<height;j++)
{
for (int i=0;i<width;i++)
{
unsigned int y=buff.buf[j*width+i];
unsigned int u=buff.buf[(j/2)*(width/2)+(i/2)+(width*height)];
unsigned int v=buff.buf[(j/2)*(width/2)+(i/2)+(width*height)+((width*height)/4)];
//printf("%d, %d,%d ", y,u,v);
//convert to RGB
unsigned int R=clamp(y + (1.370705 * (v-128)));
unsigned int G=clamp( y - (0.698001 * (v-128)) - (0.337633 * (u-128)));
unsigned int B=clamp(y + (1.732446 * (u-128)));
unsigned int RGBval= (0xFF << 24) | ((unsigned int) R << 16) | ((unsigned int) G << 8) | B;
RGB.buf[j*width+i]=RGBval;
}
}
fwrite(buff.buf,sizeof(unsigned char), (width * height)*1.5, f_buff);
fwrite(RGB.buf,sizeof(unsigned char), (width * height), f_RGB);
}
fclose(f_buff);
fclose(f_RGB);
free(buff.buf);
free(RGB.buf);
fclose(f_img);
return 0;
}
However,i get difference image between original and RGB video output. Probably, anyone know about my problem or any correction for the code above.Thanks