YUV to RGB and RGB to YUV Conversions

Posted: September 10, 2009 in C, C++, Programming Tips, VC++
Tags: , , ,

Y = Luminance, the weighted average of R G B components. (0=black 255=white)
U = Cb = Blue component (0=green 128=grey 255=blue)
V = Cr = Red component  (0=green 128=grey 255=red)

R = Red Component
G = Green Component
B = Blue Component

RGB to YUV Conversion

unsigned char Y = (unsigned char) (( 0.299 * R + 0.587 * G + 0.114 * B) * 219 / 255) + 16;
unsigned char U = (unsigned char) ((-0.299 * R - 0.587 * G + 0.886 * B) * 224 / 1.772 / 255) + 128;
unsigned char V = (unsigned char) (( 0.701 * R - 0.587 * G - 0.114 * B) * 224 / 1.402 / 255) + 128;

YUV to RGB Conversion

#define YUV2RGB(y, u, v, r, g, b)\
 r = y + ((v * 1436) >> 10);\
 g = y - ((u * 352 + v * 731) >> 10);\
 b = y + ((u * 1814) >> 10);\
 r = ( r > 255 )? 255 : (( r < 0 )? 0 : r);\
 g = ( g > 255 )? 255 : (( g < 0 )? 0 : g);\
 b = ( b > 255 )? 255 : (( b < 0 )? 0 : b)

The more well defined and accurate equation for the YUV to RGB conversion is given below

byRTemp = (BYTE)((255/219*(byY2Temp - 16))                                           + (255/224*1.402*(byVTemp - 128)));
byGTemp = (BYTE)((255/219*(byY2Temp - 16)) - (0.19421*1.772*255/224*(byVTemp - 128)) - (0.50937*1.402*255/224*(byUTemp - 128)));
byBTemp = (BYTE)((255/219*(byY2Temp - 16)) + (1.772*255/224*(byUTemp - 128)));

Another practical equation

 r = (int)((y - 16) + (1.370705 * (v - 128)));
 g = (int)((y - 16) - (0.698001 * (v - 128)) - (0.337633 * (u - 128)));
 b = (int)((y - 16) + (1.732446 * (u - 128)));

 if(r > 255) r = 255;
 if(g > 255) g = 255;
 if(b > 255) b = 255;
 if(r < 0) r = 0;
 if(g < 0) g = 0;
 if(b < 0) b = 0;

 pixel[0] = (BYTE)(r * 220 / 256);
 pixel[1] = (BYTE)(g * 220 / 256);
 pixel[2] = (BYTE)(b * 220 / 256);

R G B take values in the range 0-255
Y U V Should take the values from 16 to 235

NB: If any one has a correct conversion equation for YUV to RGB, then please post this as your comment here.

Comments
  1. anonymous says:

    thanks, the last one really helped me out. PAL/NTSC really isn’t made for integer arithmetics…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s