Search code examples
c#colorsyuv

Converting a NV12 (YUV4:2:0) Byte array to RGB byte Array


I have a stream of bytes captured from a webcam (using Aforge.Net Library). But the image captured is returned in NV12 or YUV

I need to convert it to RGB byte stream.In order can I achieve this transform, I need to know how to read / interpret the byte array.

I'm hoping to implement a function that does this

byte[] ConvertToRGB(byte[] YCbCrarray)
{

//Read the byte array and encode it in RGB format and return it as a byte array

    return rgbarray;


}

Solution

  • this is best done in C++ - you can use Microsoft's DirectXTex library for it (if you want tested code).

    You can also convert it yourself using formulas below:

    CLIP(X) ( (X) > 255 ? 255 : (X) < 0 ? 0 : X)
    // YCbCr -> RGB
    CYCbCr2R(Y, Cb, Cr) CLIP( Y + ( 91881 * Cr >> 16 ) - 179 )
    CYCbCr2G(Y, Cb, Cr) CLIP( Y - (( 22544 * Cb + 46793 * Cr ) >> 16) + 135)
    CYCbCr2B(Y, Cb, Cr) CLIP( Y + (116129 * Cb >> 16 ) - 226 )
    

    Note that you will need dimensions of the image, not just byte size. Y channel in NV12 is located first (1 byte per pixel), then UV (2bytes per 4 pixels) as explained here: http://www.fourcc.org/yuv.php#NV12