参考:点击打开链接
图像RGB数据转为YUV420程序:
void RGB24_To_YUV420(const unsigned char *img_r,const unsigned char *img_g, const unsigned char *img_b, int width, int height, unsigned char *img_yuv)
{
int i, j;
unsigned char *buf_y;
unsigned char *buf_u;
unsigned char *buf_v;
buf_y = img_yuv;
buf_u = img_yuv + (width * height);
buf_v = buf_u + ((width * height >> 2));
unsigned char pos;
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{
unsigned char B = img_b[i*width + j];
unsigned char G = img_g[i*width + j];
unsigned char R = img_r[i*width + j];
#ifdef DEBUG
if (i==0 && j==width-1)
printf("R=%x,G=%x,B=%x\n", R, G, B);
#endif
//rgb to yuv
unsigned char Y = (unsigned char)((66 * R + 129 * G + 25 * B + 128) >> 8) + 16;
*(buf_y++) = Clip_0_255(Y);
//down sample 1/2 U at even line
if (i%2 == 0 && j%2 == 0)
{
unsigned char U = (unsigned char)((-38 * R - 74 * G + 112 * B + 128) >> 8) + 128;
*(buf_u++) = Clip_0_255(U);
}
//down sample 1/2 V at odd line
else
{
if (j % 2 == 0)
{
unsigned char V = (unsigned char)((112 * R - 94 * G - 18 * B + 128) >> 8) + 128;
*(buf_v++) = Clip_0_255(V);
}
}
}
}
}