Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from YUV colour space to RGB using OpenCV

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.

like image 393
d1xlord Avatar asked Sep 04 '14 12:09

d1xlord


1 Answers

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.

like image 82
Bull Avatar answered Oct 02 '22 14:10

Bull