第一个公式是RGB转YUV(范围0-255)时用的,第二个公式是用在YUV转换RGB(范围0-255)时用的。
1.
Y = 0.257 * R + 0.504 * G + 0.098 * B + 16; U = -0.148 * R - 0.291 * G + 0.439 * B + 128; V = 0.439 * R - 0.368 * G - 0.071 * B + 128;
黑色:Y=16 ,U= V =128
红色:Y=82 ,U=90,V=240
绿色:Y=145,U=54,V=34
蓝色:Y=41 ,U=240,V=110
黄色:Y=210,U=16, V=146
暗红:Y=58, U=104,V=192
: Y=132,U=99, V=203
:Y=103,U=203,V=108
2.
B = 1.164 * (Y - 16) + 2.018 * (U - 128); G = 1.164 * (Y - 16) - 0.391 * (U - 128) - 0.813 * (V - 128); R = 1.164 * (Y - 16) + 1.596 * (V - 128);
一个简单的RGB转换YUV的小程序(仅仅是方便计算颜色值)
1 #include <iostream> 2 #include <stdio.h> 3 using namespace std; 4 5 int main() 6 { 7 int R,G,B; 8 int Y,U,V; 9 cout << "Please input the R,G,B:(eg:255 0 0)" << endl; 10 cin>>R>>G>>B; 11 Y = 0.257 * R + 0.504 * G + 0.098 * B + 16 +0.5; 12 U = -0.148 * R - 0.291 * G + 0.439 * B + 128 +0.5; 13 V = 0.439 * R - 0.368 * G - 0.071 * B + 128 +0.5;//加上0.5是为了四舍五入 14 cout<<"R,G,B: "<<R<<" "<<G<<" "<<B<<endl; 15 cout<<"Y,U,V: "<<Y<<" "<<U<<" "<<V<<endl; 16 getchar(); getchar(); return 0; 17 }
参考网址:
http://blog.sina.com.cn/s/blog_5713096b0100059i.html
http://www.fourcc.org/fccyvrgb.php
http://en.wikipedia.org/wiki/YUV
另附UYVY数据转换成OpenCV中的BGR代码一段:)
这里的尺寸是720x576
void YUV2BGR(unsigned char *srcData, unsigned char *destData) { int R,G,B; int Y,U,V; for (int height=0; height<576; height++) { for (int width=0; width<720; width++) { Y = srcData[height*720*2 + width*2 + 1]; U = (width%2==0) ? srcData[height*720*2 + width*2 + 0] : srcData[height*720*2 + width*2 + 2]; V = (width%2==1) ? srcData[height*720*2 + width*2 + 0] : srcData[height*720*2 + width*2 - 2]; B = (1164 * (Y - 16) + 2018 * (U - 128))/1000; G = (1164 * (Y - 16) - 391 * (U - 128) - 813 * (V - 128))/1000; R = (1164 * (Y - 16) + 1596 * (V - 128))/1000; if (R>255) R=255; if(R<0) R=0; if (G>255) G=255; if(G<0) G=0; if (B>255) B=255; if(B<0) B=0; destData[height * 720 * 3 + width*3 + 0] = (unsigned char)B; destData[height * 720 * 3 + width*3 + 1] = (unsigned char)G; destData[height * 720 * 3 + width*3 + 2] = (unsigned char)R; } } }