Conversion from RGB to other color spaces

The color of an image may also be modified by changing the color space. In OpenCV, six color models are available and it is possible to convert from one to another by using the cvtColor function.

Note

The default color format in OpenCV is often referred to as RGB but it is actually BGR (the channels are reversed).

The function void cvtColor(InputArray src, OutputArray dst, int code, int dstCn=0) has the input and output images as the first and second parameters. The third parameter is the color space conversion code and the last parameter is the number of channels in the output image; if this parameter is 0, the number of channels is obtained automatically from the input image.

The following color_channels example shows how to convert from RGB to HSV, Luv, Lab, YCrCb, and XYZ color spaces:

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

using namespace cv;
using namespace std;

int main( ){
    Mat image, HSV, Luv, Lab, YCrCb, XYZ;

    //Read image
    image = imread("HappyFish.jpg", CV_LOAD_IMAGE_COLOR);

    //Convert RGB image to different color spaces
    cvtColor(image, HSV, CV_RGB2HSV);
    cvtColor(image, Luv, CV_RGB2Luv);
    cvtColor(image, Lab, CV_RGB2Lab);
    cvtColor(image, YCrCb, CV_RGB2YCrCb);
    cvtColor(image, XYZ, CV_RGB2XYZ);

    //Create windows and display results
    namedWindow( "Source Image", 0 );
    namedWindow( "Result HSV Image", 0 );
    namedWindow( "Result Luv Image", 0 );
    namedWindow( "Result Lab Image", 0 );
    namedWindow( "Result YCrCb Image", 0 );
    namedWindow( "Result XYZ Image", 0 );

    imshow( "Source Image", image );
    imshow( "Result HSV Image",  HSV );
    imshow( "Result Luv Image", Luv );
    imshow( "Result Lab Image", Lab);
    imshow( "Result YCrCb Image", YCrCb );
    imshow( "Result XYZ Image", XYZ );

    waitKey(); //Wait for key press
    return 0;  //End the program
}

The code explanation is given here: the first example reads the original image and makes the conversion into five different color models. The original image in RGB and the results are then displayed. The following screenshot shows the output of the sample:

Conversion from RGB to other color spaces

Output of the different color spaces

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset