图像RGB格式与YUV格式互转

时间:2022-08-24 21:09:28
 // rgb2yuv.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h" #define Level 256 //直方图bin数
#define SIZEX 176 //image列尺寸
#define SIZEY 256 //image列尺寸
#define READ 0
#define WRITE 1 unsigned char image_in[SIZEY*SIZEX*];
unsigned char image_out[SIZEY*SIZEX*];
float Y[SIZEX*SIZEY], U[SIZEX*SIZEY], V[SIZEX*SIZEY];
float Y_out[SIZEX*SIZEY]; void GetFileName(char *name , char *message)
{
if((NULL == name) || (NULL == message))
{
return ;
} printf("%s" , message);
scanf("%s" , name);
} FILE * FileOpen(char *fileName , int mode)
{
FILE *filePoint ;
char *option = "" ; if(mode == READ)
{
option = "r+b";
}
else if(mode == WRITE)
{
option = "w+b";
} if(NULL == (filePoint = fopen(fileName , option)))
{
printf("File Open Fail!\n");
} return filePoint ;
} void ReadImageData(FILE *filePoint)
{
if(filePoint == NULL)
{
return ;
} int y_count ;
unsigned char temp = ; for(y_count = ; y_count < SIZEX*SIZEY ; y_count++)
{
fscanf(filePoint , "%c" , &temp);
image_in[y_count] = temp ;
}
} void Histogram(long *hist)
{
int i , num ; for(num = ; num < Level ; num++)
{
hist[num] = ;
} for(i = ; i < SIZEX*SIZEY ; i++)
{
num = Y[i];
hist[num]++;
} for(num = ; num < Level ; num++)
{
printf("%d \n" , hist[num]);
}
} void Equalization(long *hist ,long *q)
{
int i,n;
long sum=; for(i=;i<;i++)
{
sum += hist[i]; /* find distribution */
q[i]=(int) (sum*Level/((float)SIZEY*SIZEX));
}
} void Calculate(long *q)
{
int i, y, data; for(i=;i<SIZEX*SIZEY;i++){
data = Y[SIZEX*SIZEY];
Y_out[SIZEX*SIZEY] = q[data];
}
} void WriteImageData(FILE *file_p)
{
int Y_Count; for(Y_Count = ; Y_Count < SIZEX*SIZEY*; Y_Count++)
{
fprintf(file_p, "%c", image_out[Y_Count]);
}
} int _tmain(int argc, _TCHAR* argv[])
{
FILE *in , *out; char source[],destin[];
char *message1="Input Data File Name : " ;
char *message2="Output Data File Name : " ; int i ;
long hist[Level] = {} ;
long q[Level] = {} ;
unsigned char Red[SIZEX*SIZEY] = {} ;
unsigned char Green[SIZEX*SIZEY] = {} ;
unsigned char Blue[SIZEX*SIZEY] = {} ; /*读取源文件名*/
GetFileName(source , message1);
GetFileName(destin , message2); /*打开源文件/目的文件*/
in = FileOpen(source , READ);
out = FileOpen(destin , WRITE); /*读取源文件数据*/
ReadImageData(in); /*RGB2YUV*/
for(i = ; i < SIZEX*SIZEY; i++)
{
/*Get RGB Data*/
Red[i] = image_in[i*] ;
Green[i] = image_in[i*+] ;
Blue[i] = image_in[i*+] ; /*RGB to YUV*/
Y[i] = 0.3*Red[i] + 0.59*Green[i] + 0.11*Blue[i] ;
U[i] = (Blue[i]-Y[i]) * 0.493;
V[i] = (Red[i]-Y[i]) * 0.877;
} /*直方图信息统计*/
Histogram(hist); /*直方图均衡*/
Equalization(hist , q); /*直方图计算*/
Calculate(q); for(i=; i < SIZEX*SIZEY; i++)
{
Red[i] = Y_out[i] + 0.956*U[i] + 0.621*V[i];
Green[i] = Y_out[i] + 0.272*U[i] + 0.647*V[i];
Blue[i] = Y_out[i] + 1.1061*U[i] + 1.703*V[i];
} for(i=; i < SIZEY*SIZEX; i++)
{ image_out[i*] = Red[i];
image_out[i*+] = Green[i];
image_out[i*+] = Blue[i];
} WriteImageData(out);
fcloseall(); return ;
}

示例图片:

sample.jpg:                     UV分量:

图像RGB格式与YUV格式互转   图像RGB格式与YUV格式互转