实验内容:1.编写RGB转化为YUV程序,重点掌握函数定义,部分查找表的初始化和调用,缓冲区
分配。将得到的RGB文件转换为YUV文件,用YUV Viewer播放器观看,验证是否正确。
2.编写将YUV转换为RGB的程序。将给定的实验数据用该程序转换为RGB文件。并与原
RGB文件进行比较,如果有误差,分析误差来自何处。
YUV与RGB空间的相互转换
由电视原理可知,亮度和色差信号的构成如下:
Y=0.2990R+0.5870G+0.1140B
U=-0.1684R-0.3316G+0.5B
V=0.5R-0.4187G-0.0813B
R=1.000Y+1.4020(V−128)
G=1.000Y−0.3441(U−128)−0.7139(V−128)
B=1.000Y+1.7718(U−128)−0.0013(V−128)
需要在项目属性中设置命令参数和工作目录
rgb2yuv.cpp
#include<stdio.h>
#include<stdlib.h>
const int width = 256;
const int height = 256;
int main(int argc,char *argv[])
{
FILE* rgb=NULL;
FILE* yuv=NULL;
//判断是否成功打开文件
if (fopen_s(&rgb, argv[1], "rb") != 0)
printf("file not opened\n");
else
printf("file opened\n");
if (fopen_s(&yuv, argv[2], "wb") != 0)
printf("file not opened\n");
else
printf("file opened\n");
//建立缓冲区
unsigned char* buffer_rgb = (unsigned char*)malloc(sizeof(unsigned char) * 3 * width * height);
unsigned char* buffer_y = (unsigned char*)malloc(sizeof(unsigned char) * width * height);
unsigned char* buffer_u = (unsigned char*)malloc(sizeof(unsigned char) * width * height / 4);
unsigned char* buffer_v = (unsigned char*)malloc(sizeof(unsigned char) * width * height / 4);
//读文件
fread(buffer_rgb, sizeof(unsigned char), 3 * width * height,rgb);
//计算y分量
for (int i = 0; i < width * height; i++)
{
buffer_y[i] = 0.299 * buffer_rgb[3 * i + 2] + 0.587 * buffer_rgb[3 * i + 1] + 0.114 * buffer_rgb[3 * i];
if (buffer_y[i] >