Tuesday, 1 July 2014

Identifying Coloured Objects Using OpenCv

Hey everyone , in this blog we will be learning how to create a mask for a particular colour  and extract the particular coloured object from an image.

Algorithm used:

1) Read the BGR image
2) Convert the image into HSV color space
3) Create a color mask by setting the upper and lower thresholds from the hsv image
4) Filter the original BGR  image using the color mask

Sample Code :

import cv2
import numpy as np

img = cv2.imread("tomato.jpg",-1)
cv2.imshow("orginal",img)

blur=cv2.GaussianBlur(img,(5,5),0)
cv2.imshow("blurred image",blur)
hsv=cv2.cvtColor(blur,cv2.COLOR_BGR2HSV)

lower=np.array([0,100,100])
upper=np.array([20,255,255])
mask=cv2.inRange(hsv,lower,upper)
cv2.imshow("mask",mask)
out=cv2.bitwise_and(img,img,mask=mask)
cv2.imshow("masked image",out)

cv2.waitKey(0)

Explanation:

The sample code above separates all the red coloured objects from your image.

import cv2
import numpy as np

img = cv2.imread("tomato.jpg",-1)
cv2.imshow("orginal",img)

The above lines are for reading the original image with the name tomato.jpg stored in the working directory.In case the image is stored in some other directory you have to give the complete path.

blur=cv2.GaussianBlur(img,(5,5),0)
cv2.imshow("blurred image",blur)
hsv=cv2.cvtColor(blur,cv2.COLOR_BGR2HSV)

The first two lines removes the noise in the image using a gaussian filter and displays the blurred image. Next line converts the image into into hsv color space.For more details of the conversion visit my blog.

lower=np.array([0,100,100])
upper=np.array([20,255,255])
mask=cv2.inRange(hsv,lower,upper)
cv2.imshow("mask",mask)

The lines #1,#2 sets the lower and upper threshold for the mask.The hue value is selected to be in between 0-20 since we want to get the red objects.If we want to select some other colour you can do it by just changing the hue value here.The value for saturation and value are set to be 100-255 to include all tones and shades of red.The line #3 creates a mask from the hsv image.Line #4 displays the mask.

out=cv2.bitwise_and(img,img,mask=mask)
cv2.imshow("masked image",out)
cv2.waitKey(0)

The line 1 use a bitwise 'and' operation to filter the original BGR image using the mask and return a masked image in which only the red objects will be shown.

Original Image
Blurred Image
Masked Image
Mask

 Hoping the blog was helpful.Take care & Continue Hacking ;-)


No comments:

Post a Comment