為什么YUYV格式要轉到RGB格式,視頻的顯示調用的多數API都是基於RGB格式,所以需要進行格式的轉換。
YUYV格式如下:
Y0U0Y1V0 Y2U1Y3V1..........
說明:一個Y代表一個像素,而一個Y和UV組合起來構成一個像素,所以第0個像素Y0和第一個像素Y1都是共用第0個像素的U0和V0。而每個分量Y,U,V都是占用一個字節的存儲空間。所以Y0U0Y1V0相當於兩個像素,占用了4個字節的存儲空間,平均一個像素占用兩個字節。
RGB格式:
R0G0B0 R1G1B1.........
說明:一個像素由三個分量構成,即一個像素占用三個字節。
YUV到RGB的轉換有如下公式:
R = 1.164*(Y-16) + 1.159*(V-128);
G = 1.164*(Y-16) - 0.380*(U-128)+ 0.813*(V-128);
B = 1.164*(Y-16) + 2.018*(U-128));
1 int yuvtorgb0(unsigned char *yuv, unsigned char *rgb, unsigned int width, unsigned int height) 2 { 3 unsigned int in, out; 4 int y0, u, y1, v; 5 unsigned int pixel24; 6 unsigned char *pixel = (unsigned char *)&pixel24; 7 unsigned int size = width*height*2; 8 9 for (in = 0, out = 0; in < size; in += 4, out += 6) 10 { 11 y0 = yuv[in+0]; 12 u = yuv[in+1]; 13 y1 = yuv[in+2]; 14 v = yuv[in+3]; 15 16 sign3 = true; 17 pixel24 = yuvtorgb(y0, u, v); 18 rgb[out+0] = pixel[0]; //for QT 19 rgb[out+1] = pixel[1]; 20 rgb[out+2] = pixel[2]; 21 //rgb[out+0] = pixel[2]; //for iplimage 22 //rgb[out+1] = pixel[1]; 23 //rgb[out+2] = pixel[0]; 24 25 //sign3 = true; 26 pixel24 = yuvtorgb(y1, u, v); 27 rgb[out+3] = pixel[0]; 28 rgb[out+4] = pixel[1]; 29 rgb[out+5] = pixel[2]; 30 //rgb[out+3] = pixel[2]; 31 //rgb[out+4] = pixel[1]; 32 //rgb[out+5] = pixel[0]; 33 } 34 return 0; 35 } 36 37 int yuvtorgb(int y, int u, int v) 38 { 39 unsigned int pixel24 = 0; 40 unsigned char *pixel = (unsigned char *)&pixel24; 41 int r, g, b; 42 static long int ruv, guv, buv; 43 44 if (sign3) 45 { 46 sign3 = false; 47 ruv = 1159*(v-128); 48 guv = 380*(u-128) + 813*(v-128); 49 buv = 2018*(u-128); 50 } 51 52 r = (1164*(y-16) + ruv) / 1000; 53 g = (1164*(y-16) - guv) / 1000; 54 b = (1164*(y-16) + buv) / 1000; 55 56 if (r > 255) r = 255; 57 if (g > 255) g = 255; 58 if (b > 255) b = 255; 59 if (r < 0) r = 0; 60 if (g < 0) g = 0; 61 if (b < 0) b = 0; 62 63 pixel[0] = r; 64 pixel[1] = g; 65 pixel[2] = b; 66 67 return pixel24; 68 }