Friday, May 24, 2013

Conversion between RGB and YUV

Microsoft's answer to Conversion between RGB and YUV

Converting RGB888 to YUV

The following formulas define the conversion from RGB to YUV:

Y = ( (  66 * R + 129 * G +  25 * B + 128) >> 8) +  16
U = ( ( -38 * R -  74 * G + 112 * B + 128) >> 8) + 128
V = ( ( 112 * R -  94 * G -  18 * B + 128) >> 8) + 128
These formulas produce 8-bit results using coefficients that require no more than 8 bits of (unsigned) precision. Intermediate results require up to 16 bits of precision.

Converting 8-bit YUV to RGB888

The following coefficients are used in conversion process:

C = Y - 16
D = U - 128
E = V - 128
Using the previous coefficients and noting that clip() denotes clipping a value to the range of 0 to 255, the following formulas provide the conversion from YUV to RGB:

R = clip(( 298 * C           + 409 * E + 128) >> 8)
G = clip(( 298 * C - 100 * D - 208 * E + 128) >> 8)
B = clip(( 298 * C + 516 * D           + 128) >> 8)