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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/272586.html
標籤:其他
上一篇:第41節 C程式結構/陳述句小節
