一、转换代码
int yuv2bgr(unsigned char * yuv_img, unsigned char *rgb_img,int width, int height)
{
unsigned char * ydata = yuv_img;
unsigned char *uvdata = ydata + width * height;
int indexY, indexU, indexV;
unsigned char Y, U, V;
int B, G, R;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
indexY = i * width + j;
Y = ydata[indexY];
if (j % 2 == 0)
{
indexU = i / 2 * width + j;
indexV = indexU + 1;
U = uvdata[indexU];
V = uvdata[indexV];
}
else
{
indexV = i / 2 * width + j;
indexU = indexV - 1;
U = uvdata[indexU];
V = uvdata[indexV];
}
//nv21
R = (unsigned char)(Y + 1.4075 * (U - 128));
G = (unsigned char)(Y - 0.3455 * (V - 128) - 0.7169 * (U - 128));
B = (unsigned char)(Y + 1.779 * (V - 128));
//nv12
//R = (unsigned char)(Y + 1.4075 * (V - 128));
//G = (unsigned char)(Y - 0.3455 * (U - 128) - 0.7169 * (V - 128));
//B = (unsigned char)(Y + 1.779 * (U - 128));
rgb_img[indexY * 3 + 0] = clamp_g(B, 0, 255);
rgb_img[indexY * 3 + 1] = clamp_g(G, 0, 255);
rgb_img[indexY * 3 + 2] = clamp_g(R, 0, 255);
}
}
return 0;
}
二、优化代码
int yuv2bgr2(unsigned char * yuv_img, unsigned char *rgb_img, int width, int height)
{
unsigned char * ydata = yuv_img;
unsigned char *uvdata = ydata + width * height;
int indexY, indexU, indexV;
unsigned char Y, U, V;
int B, G, R;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j+=2)
{
indexY = i * width + j;
Y = ydata[indexY];
indexU = i / 2 * width + j;
indexV = indexU + 1;
U = uvdata[indexU];
V = uvdata[indexV];
/*first*/
//nv21
R = (int)(Y * 4096 + 5765 * (U - 128));
G = (int)(Y * 4096 - 1415 * (V - 128) - 2936 * (U - 128));
B = (int)(Y * 4096 + 7286 * (V - 128));
//nv12
//R = (unsigned char)(Y + 1.4075 * (V - 128));
//G = (unsigned char)(Y - 0.3455 * (U - 128) - 0.7169 * (V - 128));
//B = (unsigned char)(Y + 1.779 * (U - 128));
rgb_img[indexY * 3 + 0] = B >> 12;// clamp_g(B >> 12, 0, 255);
rgb_img[indexY * 3 + 1] = G >> 12;// clamp_g(G >> 12, 0, 255);
rgb_img[indexY * 3 + 2] = R >> 12;//clamp_g(R >> 12, 0, 255);
/*second*/
indexY = indexY + 1;
Y = ydata[indexY];
//nv21
R = (int)(Y * 4096 + 5765 * (U - 128));
G = (int)(Y * 4096 - 1415 * (V - 128) - 2936 * (U - 128));
B = (int)(Y * 4096 + 7286 * (V - 128));
rgb_img[indexY * 3 + 0] = B >> 12;// clamp_g(B >> 12, 0, 255);
rgb_img[indexY * 3 + 1] = G >> 12;// clamp_g(G >> 12, 0, 255);
rgb_img[indexY * 3 + 2] = R >> 12;//clamp_g(R >> 12, 0, 255);
}
}
return 0;
}
三、速度对比
nv21转bgr的平均时间(输入大小720p):
AveTime:13.7835ms
改进代码:
改进后平均时间:AveTime:5.52088ms
速度提升60%,结果完全一致。