RGB与YUV的互相转换

news/2025/3/6 6:42:13/

RGB与YUV的互相转换

一、实验目的:完成彩色空间的互相转换,即将.yuv图片转换为.rgb图片,将.rgb图片转换为.yuv文件。

先调试老师给出的.rgb文件转换至.yuv文件代码,理清思路,再写出.yuv文件转换至.rgb文件代码。
down.yuv
down.yuv(需转换的yuv文件)图片如上,其采样格式为4:2:0,分辨率为256×256.
down.rgb
down.rgb(需转换的rgb文件)图片如上,格式为RGB24,分辨率为256×256.

二、前导知识

1.转换公式
Y = 0.2990R + 0.5870G + 0.1140B;

U = -0.1684R - 0.3316G + 0.5B + 128;

V = 0.5R - 0.4187G - 0.083B + 128;

R = Y + 1.4075( V - 128);

G = Y - 0.3455( U - 128) - 0.7169( V - 128);

B = Y + 1.779( U - 128);
2.存储格式
.yuv文件先存y再存uv,.rgb文件bgr顺序存储(4:4:4)即bgrbgr…
3.采样
因为yuv文件采样格式为4:2:0,所以将.rgb文件转换为.yuv文件时要进行下采样,.yuv文件转换为.rgb文件时要进行上采样.

三、代码

1.rgbtoyuv
rgb2yuv.h

int RGB2YUV (int x_dim, int y_dim, void *bmp, void *y_out, void *u_out, void *v_out, int flip);void InitLookupTable();

main.cpp

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include "rgb2yuv.h"#define u_int8_t	unsigned __int8
#define u_int		unsigned __int32
#define u_int32_t	unsigned __int32
#define FALSE		false
#define TRUE		true/** rgb2yuv* required arg1 should be the input RAW RGB24 file* required arg2 should be the output RAW YUV12 file*/ 
int main(int argc, char** argv)
{/* variables controlable from command line */u_int frameWidth = 352;			/* --width=<uint> */u_int frameHeight = 240;		/* --height=<uint> */bool flip = TRUE;				/* --flip */unsigned int i;/* internal variables */char* rgbFileName = NULL;char* yuvFileName = NULL;FILE* rgbFile = NULL;FILE* yuvFile = NULL;u_int8_t* rgbBuf = NULL;u_int8_t* yBuf = NULL;u_int8_t* uBuf = NULL;u_int8_t* vBuf = NULL;u_int32_t videoFramesWritten = 0;/* begin process command line *//* point to the specified file names */rgbFileName = argv[1];yuvFileName = argv[2];frameWidth = atoi(argv[3]);frameHeight = atoi(argv[4]);/* open the RGB file */rgbFile = fopen(rgbFileName,"rb");if (rgbFile == NULL){printf("cannot find rgb file\n");exit(1);}else{printf("The input rgb file is %s\n", rgbFileName);}/* open the RAW file */yuvFile = fopen(yuvFileName, "wb");if (yuvFile == NULL){printf("cannot find yuv file\n");exit(1);}else{printf("The output yuv file is %s\n", yuvFileName);}/* get an input buffer for a frame */rgbBuf = (u_int8_t*)malloc(frameWidth * frameHeight * 3);/* get the output buffers for a frame */yBuf = (u_int8_t*)malloc(frameWidth * frameHeight);uBuf = (u_int8_t*)malloc((frameWidth * frameHeight) / 4);vBuf = (u_int8_t*)malloc((frameWidth * frameHeight) / 4);if (rgbBuf == NULL || yBuf == NULL || uBuf == NULL || vBuf == NULL){printf("no enought memory\n");exit(1);}while (fread(rgbBuf, 1, frameWidth * frameHeight * 3, rgbFile)) {if(RGB2YUV(frameWidth, frameHeight, rgbBuf, yBuf, uBuf, vBuf, flip)){printf("error");return 0;}for (i = 0; i < frameWidth*frameHeight; i++){if (yBuf[i] < 16) yBuf[i] = 16;if (yBuf[i] > 235) yBuf[i] = 235;}for (i = 0; i < frameWidth*frameHeight/4; i++){if (uBuf[i] < 16) uBuf[i] = 16;if (uBuf[i] > 240) uBuf[i] = 240;if (vBuf[i] < 16) vBuf[i] = 16;if (vBuf[i] > 240) vBuf[i] = 240;}fwrite(yBuf, 1, frameWidth * frameHeight, yuvFile);fwrite(uBuf, 1, (frameWidth * frameHeight) / 4, yuvFile);fwrite(vBuf, 1, (frameWidth * frameHeight) / 4, yuvFile);printf("\r...%d", ++videoFramesWritten);}printf("\n%u %ux%u video frames written\n", videoFramesWritten, frameWidth, frameHeight);/* cleanup */fclose(rgbFile);fclose(yuvFile);return(0);
}

rgb2yuv.cpp

/***************************************************************************                                                                        ** This code is developed by Adam Li.  This software is an                ** implementation of a part of one or more MPEG-4 Video tools as          ** specified in ISO/IEC 14496-2 standard.  Those intending to use this    ** software module in hardware or software products are advised that its  ** use may infringe existing patents or copyrights, and any such use      ** would be at such party's own risk.  The original developer of this     ** software module and his/her company, and subsequent editors and their  ** companies (including Project Mayo), will have no liability for use of  ** this software or modifications or derivatives thereof.                 **                                                                        ** Project Mayo gives users of the Codec a license to this software       ** module or modifications thereof for use in hardware or software        ** products claiming conformance to the MPEG-4 Video Standard as          ** described in the Open DivX license.                                    **                                                                        ** The complete Open DivX license can be found at                         ** http://www.projectmayo.com/opendivx/license.php .                      **                                                                        ***************************************************************************//****************************************************************************  rgb2yuv.c, 24-bit RGB bitmap to YUV converter**  Copyright (C) 2001  Project Mayo**  Adam Li**  DivX Advance Research Center <darc@projectmayo.com>***************************************************************************//* This file contains RGB to YUV transformation functions.                */#include "stdlib.h"
#include "rgb2yuv.h"static float RGBYUV02990[256], RGBYUV05870[256], RGBYUV01140[256];
static float RGBYUV01684[256], RGBYUV03316[256];
static float RGBYUV04187[256], RGBYUV00813[256];/**************************************************************************  int RGB2YUV (int x_dim, int y_dim, void *bmp, YUV *yuv)**	Purpose :	It takes a 24-bit RGB bitmap and convert it into*				YUV (4:2:0) format**  Input :		x_dim	the x dimension of the bitmap*				y_dim	the y dimension of the bitmap*				bmp		pointer to the buffer of the bitmap*				yuv		pointer to the YUV structure**  Output :	0		OK*				1		wrong dimension*				2		memory allocation error**	Side Effect :*				None**	Date :		09/28/2000**  Contacts:**  Adam Li**  DivX Advance Research Center <darc@projectmayo.com>*************************************************************************/int RGB2YUV (int x_dim, int y_dim, void *bmp, void *y_out, void *u_out, void *v_out, int flip)
{static int init_done = 0;long i, j, size;unsigned char *r, *g, *b;unsigned char *y, *u, *v;unsigned char *pu1, *pu2, *pv1, *pv2, *psu, *psv;unsigned char *y_buffer, *u_buffer, *v_buffer;unsigned char *sub_u_buf, *sub_v_buf;if (init_done == 0){InitLookupTable();init_done = 1;}// check to see if x_dim and y_dim are divisible by 2if ((x_dim % 2) || (y_dim % 2)) return 1;size = x_dim * y_dim;// allocate memoryy_buffer = (unsigned char *)y_out;sub_u_buf = (unsigned char *)u_out;sub_v_buf = (unsigned char *)v_out;u_buffer = (unsigned char *)malloc(size * sizeof(unsigned char));v_buffer = (unsigned char *)malloc(size * sizeof(unsigned char));if (!(u_buffer && v_buffer)){if (u_buffer) free(u_buffer);if (v_buffer) free(v_buffer);return 2;}b = (unsigned char *)bmp;y = y_buffer;u = u_buffer;v = v_buffer;// convert RGB to YUVif (!flip) {for (j = 0; j < y_dim; j ++){y = y_buffer + (y_dim - j - 1) * x_dim;u = u_buffer + (y_dim - j - 1) * x_dim;v = v_buffer + (y_dim - j - 1) * x_dim;for (i = 0; i < x_dim; i ++) {g = b + 1;r = b + 2;*y = (unsigned char)(  RGBYUV02990[*r] + RGBYUV05870[*g] + RGBYUV01140[*b]);*u = (unsigned char)(- RGBYUV01684[*r] - RGBYUV03316[*g] + (*b)/2          + 128);*v = (unsigned char)(  (*r)/2          - RGBYUV04187[*g] - RGBYUV00813[*b] + 128);b += 3;y ++;u ++;v ++;}}} else {for (i = 0; i < size; i++){g = b + 1;r = b + 2;*y = (unsigned char)(  RGBYUV02990[*r] + RGBYUV05870[*g] + RGBYUV01140[*b]);*u = (unsigned char)(- RGBYUV01684[*r] - RGBYUV03316[*g] + (*b)/2          + 128);*v = (unsigned char)(  (*r)/2          - RGBYUV04187[*g] - RGBYUV00813[*b] + 128);b += 3;y ++;u ++;v ++;}}// subsample UVfor (j = 0; j < y_dim/2; j ++){psu = sub_u_buf + j * x_dim / 2;psv = sub_v_buf + j * x_dim / 2;pu1 = u_buffer + 2 * j * x_dim;pu2 = u_buffer + (2 * j + 1) * x_dim;pv1 = v_buffer + 2 * j * x_dim;pv2 = v_buffer + (2 * j + 1) * x_dim;for (i = 0; i < x_dim/2; i ++){*psu = (*pu1 + *(pu1+1) + *pu2 + *(pu2+1)) / 4;*psv = (*pv1 + *(pv1+1) + *pv2 + *(pv2+1)) / 4;psu ++;psv ++;pu1 += 2;pu2 += 2;pv1 += 2;pv2 += 2;}}free(u_buffer);free(v_buffer);return 0;
}void InitLookupTable()
{int i;for (i = 0; i < 256; i++) RGBYUV02990[i] = (float)0.2990 * i;for (i = 0; i < 256; i++) RGBYUV05870[i] = (float)0.5870 * i;for (i = 0; i < 256; i++) RGBYUV01140[i] = (float)0.1140 * i;for (i = 0; i < 256; i++) RGBYUV01684[i] = (float)0.1684 * i;for (i = 0; i < 256; i++) RGBYUV03316[i] = (float)0.3316 * i;for (i = 0; i < 256; i++) RGBYUV04187[i] = (float)0.4187 * i;for (i = 0; i < 256; i++) RGBYUV00813[i] = (float)0.0813 * i;
}

在这里插入图片描述
2.yuvtorgb
yuv2rgb.h

int YUV2RGB (int x_dim, int y_dim, void *bmp, void *y_out, void *u_out, void *v_out, int flip);void InitLookupTable();

main.cpp

#include <stdio.h>
#include <stdlib.h>  
#include <malloc.h>
#include "yuv2rgb.h"#define u_int8_t	unsigned __int8  
#define u_int		unsigned __int32  
#define u_int32_t	unsigned __int32
#define FALSE		false
#define TRUE		trueint main(int argc, char* argv[])
{/* variables controlable from command line */u_int frameWidth = 352;			/* --width=<uint> */u_int frameHeight = 240;		/* --height=<uint> */bool flip = TRUE;				/* --flip */unsigned int i;/* internal variables */char* rgbFileName = NULL;char* yuvFileName = NULL;FILE* rgbFile = NULL;FILE* yuvFile = NULL;u_int8_t* rgbBuf = NULL;u_int8_t* yBuf = NULL;u_int8_t* uBuf = NULL;u_int8_t* vBuf = NULL;u_int32_t videoFramesWritten = 0;/* begin process command line *//* point to the specified file names */yuvFileName = argv[1];rgbFileName = argv[2];frameWidth = atoi(argv[3]);   frameHeight = atoi(argv[4]);/* open the YUV file */yuvFile = fopen(yuvFileName, "rb");if (yuvFile == NULL){printf("cannot find yuv file\n");exit(1);}else{printf("The input yuv file is %s\n", yuvFileName);}/* open the RGB file */rgbFile = fopen(rgbFileName, "wb");if (rgbFile == NULL){printf("cannot find rgb file\n");exit(1);}else{printf("The output rgb file is %s\n", rgbFileName);}/* get an output buffer for a frame */rgbBuf = (u_int8_t*)malloc(frameWidth * frameHeight * 3);  /* get the input buffers for a frame */yBuf = (u_int8_t*)malloc(frameWidth * frameHeight);uBuf = (u_int8_t*)malloc((frameWidth * frameHeight) / 4);vBuf = (u_int8_t*)malloc((frameWidth * frameHeight) / 4);if (rgbBuf == NULL || yBuf == NULL || uBuf == NULL || vBuf == NULL) {printf("no enought memory\n");exit(1);}while (fread(yBuf, 1, frameWidth * frameHeight, yuvFile)&& fread(uBuf, 1, frameWidth * frameHeight / 4, yuvFile)&& fread(vBuf, 1, frameWidth * frameHeight / 4, yuvFile)){if (YUV2RGB(frameWidth, frameHeight, rgbBuf, yBuf, uBuf, vBuf, flip)){printf("error");return 0;}fwrite(rgbBuf, 1, frameWidth * frameHeight * 3, rgbFile);printf("\r...%d", ++videoFramesWritten);}printf("\n%u %ux%u video frames written\n",videoFramesWritten, frameWidth, frameHeight);fclose(rgbFile);fclose(yuvFile);if (rgbBuf != NULL) free(rgbBuf);if (yBuf != NULL)free(yBuf);if (uBuf != NULL)free(uBuf);if (vBuf != NULL)free(vBuf);return(0);
}

yuv2rgb.cpp

#include "stdlib.h"
#include "yuv2rgb.h"static float YUVRGB14075[256];
static float YUVRGB03455[256], YUVRGB07169[256];
static float YUVRGB1779[256];int YUV2RGB(int width, int height, void* rgb_out, void* y_in, void* u_in, void* v_in, int flip)
{static int init_done = 0;long i, j, size;float tempr,tempg, tempb;unsigned char* bgr;unsigned char* y, * u, * v;unsigned char* y_buffer, * u_buffer, * v_buffer;unsigned char* sub_u_buf, * sub_v_buf;if (init_done == 0){InitLookupTable();init_done = 1;}if ((width % 2) || (height % 2)) return 1;size = width * height;y_buffer = (unsigned char*)y_in;u_buffer = (unsigned char*)u_in;v_buffer = (unsigned char*)v_in;bgr = (unsigned char*)rgb_out;sub_u_buf = (unsigned char*)malloc(size);sub_v_buf = (unsigned char*)malloc(size);//上采样for (i = 0; i < height; i++){for (j = 0; j < width; j++){*(sub_u_buf + i * width + j) = *(u_buffer + (i / 2) * (width / 2) + j / 2);*(sub_v_buf + i * width + j) = *(v_buffer + (i / 2) * (width / 2) + j / 2);}}y = y_buffer;u = sub_u_buf;v = sub_v_buf;for(i=0;i<size;i++){tempr = *y + YUVRGB14075[*v];tempg = *y - YUVRGB03455[*u] - YUVRGB07169[*v];tempb = *y + YUVRGB1779[*u];*bgr = ( (tempr > 255) ? 255 : ( tempr < 0 ? 0 : (unsigned char)tempr) );*(bgr+1) = ( (tempg > 255) ? 255 : ( tempg < 0 ? 0 : (unsigned char)tempg) );*(bgr+2) = ( (tempb > 255) ? 255 : ( tempb < 0 ? 0 : (unsigned char)tempb) );bgr=bgr+3;y++;u++;v++;}if (sub_u_buf != NULL) free(sub_u_buf);if (sub_v_buf != NULL) free(sub_v_buf);return 0;
}void InitLookupTable()
{int i;for (i = 0; i < 256; i++) YUVRGB14075[i] = (float)1.4075 * (i - 128);for (i = 0; i < 256; i++) YUVRGB03455[i] = (float)0.3455 * (i - 128);for (i = 0; i < 256; i++) YUVRGB07169[i] = (float)0.7169 * (i - 128);for (i = 0; i < 256; i++) YUVRGB1779[i] = (float)1.779 * (i - 128);}

在这里插入图片描述

四、结果

rgbtoyuv.yuv
rgbtoyuv.yuv(.rgb转换为.yuv结果)如上

yuvtorgb.rgb
yuvtorgb.rgb(.yuv转换为.rgb结果)如上

五、结果分析

将down.rgb与yuvtorgb.rgb进行对比,可以看出存在较大的误差,这是因为进行了上采样,存在一定误差。

文章来源:https://blog.csdn.net/weixin_45653303/article/details/115144364
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ppmy.cn/news/807473.html

相关文章

Linux 内核引导选项简介

概述 内核引导选项大体上可以分为两类&#xff1a;一类与设备无关、另一类与设备有关。与设备有关的引导选项多如牛毛&#xff0c;需要你自己阅读内核中的相应驱动程序源码以获取其能够接受的引导选项。比如&#xff0c;如果你想知道可以向 AHA1542 SCSI 驱动程序传递哪些引导…

图像增强算法总结

需要图像增强的原因: 1 图像噪点过大&#xff0c;影响感观、影响计算机对图像特征的提取 2 图像因为光线环境等造成整体对比度不足或局部过暗、过曝。细节损失 3 图像白平衡系数未校准造成图像偏色 4 图像因采集时镜头失焦等问题造成的模糊 5 图像由于运动速度过快 (采集一帧时…

图像重采样/插值原理与其在MRI脑影像分辨率修改中的应用——将尺寸为1mm标准模板修改成体素尺寸为3、6、8mm标准模板(FSL、SPM12、NIfTI_20140122、dpabi、nilearn)

| 图源 图像重采样这个词&#xff0c;可能许多人都会觉得陌生。但是图像放大&#xff0c;图像缩小&#xff0c;图像旋转&#xff0c;图像错切等这些我们熟悉操作背后&#xff0c;增多、减少和移位的像素点值的确定&#xff0c;其实都是通过重采样&#xff08;resample&#xff…

psv leapftp使用教程,psv leapftp使用教程图解

psv leapftp是一款功能强大&#xff0c;媲美Flshfxp、BulletProof FTP、FFFtp的FTP软件。但小编觉得&#xff0c;比起另外一款ftp工具来说&#xff0c;功能方面还是有些不足。那就是iis7服务器管理工具。 IIS7服务器管理工具支持批量操作&#xff0c;里面的ftp还可以实现定时同…

光场超分辨率论文笔记

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 一、二、LFT三、四、LFCNN五、LFSR六七八九十十一十二十三十四、An Epipolar Volume Autoencoder with Adversarial Loss for Deep Light Field Super-Resolution十…

MySql存储引擎介绍——InnoDB、MyISAM、Memory

文章目录 1.MySql体系结构2.存储引擎简介3.存储引擎的特点3.1 InnoDB存储引擎特点3.2 MyISAM存储引擎介绍3.3 Memory存储引擎介绍 4.三种存储引擎的特点5.存储引擎的选择6.小结 1.MySql体系结构 2.存储引擎简介 存储引擎就是存储数据、建立索引、更新/查询数据等技术的实现方式…

RabbitMQ - 单机部署(超详细)

RabbitMQ部署 1.单机部署 我们在Centos7虚拟机中使用Docker来安装。 1.1.下载镜像 方式一&#xff1a;在线拉取 docker pull rabbitmq:3-management方式二&#xff1a;从本地加载 也可以从网上搜索 RabbitMQ 的 tar 包下载下来 上传到虚拟机中后&#xff0c;使用命令加载…

神州无线AC、三层交换机、无线AP连接方法

配置命令如下&#xff1a; AC&#xff1a; User Access Verification Username: admin Password: Username: admin Password: DCWS-6028#conf DCWS-6028(config)#host AC AC(config)#int vlan 1 AC(config-if-vlan1)#ip add 10.1.1.1 255.255.255.0 AC(config-if-vl…