Showing color spaces

The RGB color space is an additive color space, where a specific color is represented by red, green, and blue values. Human vision works in a similar way, so this color space is an appropriate way to display computer graphics.

The CIELAB color space (also known as CIE L*a*b* or simply LAB) represents a specific color as three numerical values, where L* represents the lightness, a* represents the green-red components, and b* represents the blue-yellow components. This color space is also used in some image processing algorithms.

Hue, saturation, lightness (HSL) and hue, saturation, value (HSV) are two color spaces, where only one channel (H) is used to describe the color, making it very intuitive to specify the color. In these color models, the separation of the luminance component has some advantages when applying image processing techniques.

YCbCr is a family of color spaces used in video and digital photography systems, representing colors in terms of the chroma components (Y) and two chrominance components/chroma (Cb and Cr). This color space is very popular in image segmentation, based on the color model derived from the YCbCr image.

In the color_spaces.py script, an image is loaded in the BGR color space and converted into the aforementioned color spaces. In this script, the key function is cv2.cvtColor(), which converts an input image of one color space into another.

In the case of transformations to/from the RGB color space, the order of the channels should be specified explicitly (BGR or RGB). For example:

image = cv2.imread('color_spaces.png')

This image is loaded in the BGR color space. Therefore, if we want to convert it into the HSV color space, we must perform the following:

hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

Note that we have used cv2.COLOR_BGR2HSV and not cv2.COLOR_RGB2HSV.

The full code for this script can be seen in color_space.py. The output can be seen in the following screenshot:

As shown in the preceding screenshot, the BGR image is converted into the HSV, HLS, YCrCb, and L*a*b* color spaces. All the components (channels) for each color space are also shown.