Encoding images in the RGB space

I am sure that you are already familiar with the RGB color space, which uses additive mixing of different shades of red, green, and blue to produce different composite colors. The RGB color space is useful in everyday life because it covers a large part of the color space that the human eye can see. This is why color television sets or color computer monitors only need to care about producing mixtures of red, green, and blue light.

In OpenCV, RGB images are supported straight out of the box. All you need to know, or need to be reminded of, is that color images are actually stored as BGR images in OpenCV; that is, the order of color channels is blue-green-red instead of red-green-blue. The reasons for this choice of format are mostly historical. OpenCV has stated that the choice of this format was due to its popularity among camera manufacturers and software providers when OpenCV was first created.

We can load a sample image in BGR format using cv2.imread:

In [1]: import cv2
... import matplotlib.pyplot as plt
... %matplotlib inline
In [2]: img_bgr = cv2.imread('data/lena.jpg')

If you have ever tried to display a BGR image using Matplotlib or similar libraries, you might have noticed a weird blue tint to the image. This is because Matplotlib expects an RGB image. To achieve this, we have to permute the color channels using cv2.cvtColor:

In [3]: img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)

For comparison, we can plot both img_bgr and img_rgb next to each other:

In [4]: plt.figure(figsize=(12, 6))
... plt.subplot(121)
... plt.imshow(img_bgr)
... plt.subplot(122)
... plt.imshow(img_rgb)
Out[4]: <matplotlib.image.AxesImage at 0x20f6d043198>

This code will lead to the following two images in the screenshot:

In case you were wondering, Lena is the name of a popular Playboy model (Lena Soderberg), and her picture is one of the most used images in computer history. The reason is that, back in the 1970s, people got tired of using the conventional stock of test images and instead wanted something glossy to ensure good output dynamic range. 

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

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