In computer vision and image processing, color space refers to a specific way of organizing colors. A color space is actually a combination of two things: a color model and a mapping function. The reason we want color models is because it helps us in representing pixel values using tuples. The mapping function maps the color model to the set of all possible colors that can be represented.
There are many different color spaces that are useful. Some of the more popular color spaces are RGB, YUV, HSV, Lab, and so on. Different color spaces provide different advantages. We just need to pick the color space that's right for the given problem. Let's take a couple of color spaces and see what information they provide:
Converting between color spaces
Considering all the color spaces, there are around 190 conversion options available in OpenCV. If you want to see a list of all available flags, go to the Python shell and type the following:
You will see a list of options available in OpenCV for converting from one color space to another. We can pretty much convert any color space into any other color space. Let's see how we can convert a color image into a grayscale image:
We use the function cvtColor
to convert between color spaces. The first argument is the input image and the second argument specifies the color space conversion. You can convert to YUV by using the following flag:
The image will look something like the following one:
This may look like a deteriorated version of the original image, but it's not. Let's separate out the three channels:
Since yuv_img
is a numPy array, we can separate out the three channels by slicing it. If you look at yuv_img.shape
, you will see that it is a 3D array whose dimensions are NUM_ROWS x NUM_COLUMNS x NUM_CHANNELS
. So once you run the preceding piece of code, you will see three different images. Following is the Y
channel:
The Y
channel is basically the grayscale image. Next is the U
channel:
And lastly, the V
channel:
As we can see here, the Y
channel is the same as the grayscale image. It represents the intensity values. The U
and V
channels represent the color information.
Let's convert to HSV and see what happens:
Again, let's separate the channels:
If you run the preceding piece of code, you will see three different images. Take a look at the H
channel:
Next is the S
channel:
Following is the V
channel:
This should give you a basic idea of how to convert between color spaces. You can play around with more color spaces to see what the images look like. We will discuss the relevant color spaces as and when we encounter them during subsequent chapters.