OpenCV: Color-spaces and splitting channels
Posted by Hemprasad Y. Badgujar on July 18, 2015
Conversion between color-spaces
Our goal here is to visualize each of the three channels of these color-spaces: RGB, HSV, YCrCb and Lab. In general, none of them are absolute color-spaces and the last three (HSV, YCrCb and Lab) are ways of encoding RGB information. Our images will be read in BGR (Blue-Green-Red), because of OpenCV defaults. For each of these color-spaces there is a mapping function and they can be found at OpenCV cvtColor documentation.
One important point is: OpenCV imshow() function will always assume that the Mat shown is in BGR color-space. Which means, we will always need to convert back to see what we want. Let’s start.
While in BGR, an image is treated as an additive result of three base colors (blue, green and red), HSV stands for Hue, Saturation and Value (Brightness). We can say that HSV is a rearrangement of RGB in a cylindrical shape. The HSV ranges are:
- 0 > H > 360 ⇒ OpenCV range = H/2 (0 > H > 180)
- 0 > S > 1 ⇒ OpenCV range = 255*S (0 > S > 255)
- 0 > V > 1 ⇒ OpenCV range = 255*V (0 > V > 255)
YCrCb or YCbCr
It is used widely in video and image compression schemes. The YCrCb stands for Luminance (sometimes you can see Y’ as luma), Red-difference and Blue-difference chroma components. The YCrCb ranges are:
- 0 > Y > 255
- 0 > Cr > 255
- 0 > Cb > 255
In this color-opponent space, L stands for the Luminance dimension, while a and b are the color-opponent dimensions. The Lab ranges are:
- 0 > L > 100 ⇒ OpenCV range = L*255/100 (1 > L > 255)
- -127 > a > 127 ⇒ OpenCV range = a + 128 (1 > a > 255)
- -127 > b > 127 ⇒ OpenCV range = b + 128 (1 > b > 255)
All the color-spaces mentioned above were constructed using three channels (dimensions). It is a good exercise to visualize each of these channels and realize what they really store, because when I say that the third channel of HSV stores the brightness, what do you expect to see? Remember: a colored image is made of three-channels (in our cases) and when we see each of them separately, what do you think the output will be? If you said a grayscale image, you are correct! However, you might have seen these channels as colored images out there. So, how? For that, we need to choose a fixed value for the other two channels. Let’s do this!
To visualize each channel with color, I used the same values used on the Slides 53 to 65 from CS143, Lecture 03 from Brown University.
RGB or BGR
YCrCb or YCbCr
Lab or CIE Lab