Converting from YUV colour space to RGB using OpenCV

d1xlord picture d1xlord · Sep 4, 2014 · Viewed 16.9k times · Source

I am trying to convert a YUV image to RGB using OpenCV. I am a complete novice at this. I have created a function which takes a YUV image as source and converts it into RGB. It is like this :

void ConvertYUVtoRGBA(const unsigned char *src, unsigned char *dest, int width, int height)
{
    cv::Mat myuv(height + height/2, width, CV_8UC1, &src);
    cv::Mat mrgb(height, width, CV_8UC4, &dest);

    cv::cvtColor(myuv, mrgb, CV_YCrCb2RGB);
    return;
}

Should this work? Do I need to convert the Mat into char* again? I am in a loss and any help will be greatly appreciated.

Answer

Bull picture Bull · Sep 4, 2014

There is not enough detail in your question to give a certain answer but below is my best guess. I'll assume you want RGBA output (not RGB, BGR or BGRA) and that your YUV is yuv420sp (as this is what comes out of an Android camera, and it is consistent with your Mat sizes)

void ConvertYUVtoRGBA(const unsigned char *src, unsigned char *dest, int width, int height)
{
    //cv::Mat myuv(height + height/2, width, CV_8UC1, &src);
    cv::Mat myuv(height + height/2, width, CV_8UC1, src); // pass buffer pointer, not its address
    //cv::Mat mrgb(height, width, CV_8UC4, &dest);
    cv::Mat mrgb(height, width, CV_8UC4, dest);

    //cv::cvtColor(myuv, mrgb, CV_YCrCb2RGB);
    cv::cvtColor(myuv, mrgb, CV_YUV2RGBA_NV21);  // are you sure you don't want BGRA?
    return;
}

Do I need to convert the Mat into char again?*

No the Mat mrgb is a wrapper around dest and, the way you have arranged it, the RGBA data will written directly into the dest buffer.