5/22/2018

single color value convert from RGB to YUV and YUV to RGB

Simple color convert code for a pixel value

example for :
RGB to YUV ,YUV to RGB


void rgbToyuv(int r, int g, int b, int& y, int& u, int& v)
{
    Mat img_in(1, 1, CV_8UC3);
    img_in.at<Vec3b>(0, 0)[0] = uint(b);
    img_in.at<Vec3b>(0, 0)[1] = uint(g);
    img_in.at<Vec3b>(0, 0)[2] = uint(r);


    Mat img_out;
    cvtColor(img_in, img_out, CV_BGR2YUV);

    y = uint(img_out.at< cv::Vec3b>(0, 0)[0]);
    u = uint(img_out.at< cv::Vec3b>(0, 0)[1]);
    v = uint(img_out.at< cv::Vec3b>(0, 0)[2]);
}

void yuvTorgb(int y, int u, int v, int& r, int& g, int& b)
{
    Mat img_in(1, 1, CV_8UC3);
    img_in.at<Vec3b>(0, 0)[0] = uint(y);
    img_in.at<Vec3b>(0, 0)[1] = uint(u);
    img_in.at<Vec3b>(0, 0)[2] = uint(v);


    Mat img_out;
    cvtColor(img_in, img_out, CV_YUV2BGR);

    b = uint(img_out.at< cv::Vec3b>(0, 0)[0]);
    g = uint(img_out.at< cv::Vec3b>(0, 0)[1]);
    r = uint(img_out.at< cv::Vec3b>(0, 0)[2]);
}


int main()
{

    int ored = 255;
    int ogreen = 0;
    int oblue = 0;
    int y2, u2, v2;
    printf("origin %d %d %d \n", oblue, ogreen, ored);

    rgbToyuv(ored, ogreen, oblue, y2, u2, v2);
    printf("origin -> yuv: %d %d %d \n", y2, u2, v2);

    int r3, g3, b3;
    yuvTorgb(y2, u2, v2, r3, g3, b3);
    printf("yuv -> rgb: %d %d %d \n", r3, g3, b3);
}




No comments:

Post a Comment