YUV420转RGB888

YUV420转RGB888

yuv420的数据存储方式是planar,就是在一帧中先存y分量,存完y存u,接着v分量。而在yuv420中有y分量widthheight byte,uv分量各是widthheight1/4,一帧中总的数据是widthheight3/2(widthheight12/8).所以当时认为,yuv分量代入转换公式的话,uv分量是不是少了。其实不然,因为是每四个y分量共用一个u分量一个v分量,但也不是[YiYi+1Yi+2Yi+3]共用[Ui],[Vi],因为是一个22的窗口内的Y分量共用一个uv,所以[YiYi+1Yi+wYi+w+1],其中i是偶数。uv分量由于是分别按水平方向和垂直方向2:1采样,所以[U(i/2*w/2+j/2)],V分量同理。

#include <iostream>
#include <stdio.h>
#include<fstream>

using namespace std;

bool yuv420ToRgb(char *yuv, int w, int h, char *rgb)
{
    
    
	unsigned char *y = new unsigned char[w*h];
	unsigned char *u = new unsigned char[w*h / 4];
	unsigned char *v = new unsigned char[w*h / 4];

	memcpy(y, yuv, w*h);
	memcpy(u, yuv + w * h, w*h / 4);
	memcpy(v, yuv + w * h * 5 / 4, w*h / 4);

	for (int i = 0; i < h; i++)
	{
    
    
		for (int j = 0; j < w; j++)
		{
    
    
			rgb[i*w*3 + 3*j] = 1.164*(y[i*w+j] - 16) + 1.596*(v[i / 4 * w + j / 2] - 128);//R

			rgb[i*w*3 + 3*j+1] = 1.164*(y[i*w + j] - 16) - 0.392*(u[i / 4*w+j/2] - 128) - 0.813*(v[i / 4 * w + j / 2] - 128);//G

			rgb[i*w*3 + 3*j+2] = 1.164*(y[i*w + j] - 16) + 2.017*(u[i / 4 * w + j / 2] - 128);  //B
		}
	}
	free(y);
	free(u);
	free(v);
	return true;
}


int main(int argc, char* argv[])
{
    
    
	FILE *yuv, *out;	
	int len = 832 * 480 * 3 / 2;
	char  *yuvbuff = ( char *)malloc(len);
	char  *rgbbuff = ( char *)malloc(len*2);
	char  *buff = (char *)malloc(len * 2);
	yuv = fopen("D://movie player//BasketballDrill_832x480_50.yuv", "rb");
	out= fopen("D://movie player//rgb888.txt", "wb+");

	ifstream fl("D://movie player//BasketballDrill_832x480_50.yuv", ios::binary);
	fl.seekg(0, ios::end);
	int size = fl.tellg();
	int inFrameNum = (width*height * 3 / 2);
	int frameNum = size / inFrameNum;

	for (int i = 0; i <frameNum; i++) {
    
    
		fread(yuvbuff, 1, width*height * 3/2, yuv);
		yuv420ToRgb(yuvbuff, width, height, rgbbuff);
	    fwrite(rgbbuff, 1, width*height * 3 ,out);
	}
		return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44471761/article/details/115427748