在OpenCV中将RGB转换为YCbCr

时间:2015-04-17 01:12:40

标签: opencv

我目前正在使用OpenCV函数将图像从 RGB转换为YCrCb 格式 - cvtColor。我想用类似于

的方程式自己进行转换
 //equations for RGB to YUV conversion
 Y' = 0.299 R + 0.587 G + 0.114  B 
 U = -0.147 R - 0.289 G + 0.436  B
 V = 0.615  R - 0.515 G - 0.100  B.      

我无法理解OpenCV图像矩阵操作。我想从图像Mat访问RGB像素值,以便我可以自己执行转换。如何从图像中获取R,G,B值,然后如何应用转换?我目前的代码如下。

int main (int argc, char *argv[])
{   
    // Load in image 
    cv::Mat src = cv ::imread("C:\\openv2410\\frames\\frame_0.png",1);

    // Create a vector for the channels and split the original image into B G R colour channels.
    // Keep in mind that OpenCV uses BGR and not RGB images
    vector<cv::Mat> spl;
    split(src,spl);

    // Create an zero pixel image for filling purposes - will become clear later
    // Also create container images for B G R channels as colour images
    cv::Mat empty_image =  cv::Mat::zeros(src.rows, src.cols, CV_8UC1);
    cv::Mat empty_channel =  cv::Mat::zeros(src.rows, src.cols, CV_8UC1);

    cv::Mat result_blue(src.rows, src.cols, CV_8UC3); // notice the 3 channels here!
    cv::Mat result_green(src.rows, src.cols, CV_8UC3); // notice the 3 channels here!
    cv::Mat result_red(src.rows, src.cols, CV_8UC3); // notice the 3 channels here!

    // Create blue channel
    cv::Mat in1[] = { spl[0], empty_image, empty_image };
    int from_to1[] = { 0,0, 1,1, 2,2 };
    mixChannels( in1, 3, &result_blue, 1, from_to1, 3 );

    // Create green channel
    cv::Mat in2[] = { empty_channel, spl[1], empty_image };
    int from_to2[] = { 0,0, 1,1, 2,2 };
    mixChannels( in2, 3, &result_green, 1, from_to2, 3 ); 

    // Create red channel
    cv::Mat in3[] = { empty_channel, empty_channel, spl[2]};
    int from_to3[] = { 0,0, 1,1, 2,2 };
    mixChannels( in3, 3, &result_red, 1, from_to3, 3 );    

    imshow("blue channel",result_blue);
    imshow("green channel",result_green);
    imshow("red channel",result_red);  

    cv::waitKey(0);
    return 0;    
}    

1 个答案:

答案 0 :(得分:1)

从BGR转换为YCrCb的示例代码。源(1)。

//sample input and output
float data[3][1] = { 98,76,88 };
Mat input( 1, 1, CV_32FC3, data) ;
Mat output( 1, 1, CV_32FC3 );

//iterate over all pixels
for(int i = 0; i < input.rows; i++) {
    for(int j = 0; j < input.cols; j++) {
        //get bgr pixel 
        Vec3f bgrPixel = input.at<Vec3f>(i, j);

        float B = bgrPixel[0];
        float G = bgrPixel[1];
        float R = bgrPixel[2];          

        //actual conversion from BGR to YCrCb
        float delta = 0.5f; 
        float Y  = 0.299f * R + 0.587f * G + 0.114f * B;
        float Cb = (B - Y) * 0.564f + delta;
        float Cr = (R - Y) * 0.713f + delta;

        //store into result image
        Vec3f yCrCbPixel( Y, Cr, Cb );
        output.at<Vec3f>(i, j) = yCrCbPixel;
    }
}