Tuesday, 1 July 2014

Colour Spaces and their conversions in opencv

In this blog we will be dealing with various color spaces and their conversions using opencv functions.

Introduction to Color spaces

According to definitions given in wikipedia the colorspace of an image is defined as: 
"Color space, also known as the color model (or color system), is an abstract mathematical model which simply describes the range of colors as tuples of numbers, typically as 3 or 4 values or color components "

For example in a RGB image every color is defined as a combination of three basic colors: red,green and blue.The color of a point changes as the value of red,green and blue component changes.(0,0,0) represents perfect black (255,255,255) represents white.One thing to be taken into account always is that in opencv the images are represented in the BGR format.So (0,0,255) represents perfect red and not blue as in a ordinary RGB image.

Another important color space used in image processing projects is HSV color space.Here the color value of each point is represented by three parameters Hue,Saturation and value.You can find more details here.Hue is the color component.In opencv it ranges from 0-180 unlike the normal image handling softwares such as Gimp or photoshop were the hsv value of hue varies from 0-360.So dont forget to divide the value by to before applying to opencv.

There are more than 150 color-space conversion methods available in OpenCV. But we will look into only two which are most widely used ones, BGR \leftrightarrow Gray and BGR \leftrightarrow HSV.
The syntax of the function used for color space conversion is :
cv2.cvtColor(input_image, flag) where flag determines the type of conversion.
For BGR \rightarrow Gray conversion we use the flags cv2.COLOR_BGR2GRAY. Similarly for BGR \rightarrow HSV, we use the flag cv2.COLOR_BGR2HSV
To get other flags, just run following commands in your Python terminal :
>>> import cv2
>>> flags = [i for i in dir(cv2) if i.startswith('COLOR_')]
>>> print flags

Example Code for BGR-> HSV conversion:

import cv2

img=cv2.imread('image.jpg')  # A BGR image is taken
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV) #image is converted to hsv color space

Example Code for BGR-> GRAY conversion:

import cv2

img=cv2.imread('image.jpg')    # A BGR image is taken
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)  #image is converted to gray sacle image

Similarly by changing the flags the image can be converted to various color spaces.Different color spaces have their own advantages and disadvantages.Each of them is selected according to their suitability to the application.

No comments:

Post a Comment