Changing Color Spaces
Changing color spaces is necessary in image processing. You can change your image in number of color-spaces but the two most importing thing to convert from BGR to gray and HSV. HSV stands for Hue saturation and value which has a different bit range than BGR. Generally the ranges are Hue [0,179], Saturation [0,255], Value [0,255]. For color conversion the simplest way is to use cv2.cvtColor() method. This method takes two input where one is the input image and other the mode of conversion you want. For our two modes of conversion we can use cv2.COLOR_BGR2GRAY and cv2.COLOR_BGR2HSV.
You can do object tracking by changing the color spaces from BGR to HSV. Let’s do a blue object tracing. The sample code is given below;
import cv2 import numpy as np cap = cv2.VideoCapture(0) while(1): # Take each frame _, frame = cap.read() # Convert BGR to HSV hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # setting up range for blue color you want to track lower_blue = np.array([110,50,50]) upper_blue = np.array([130,255,255]) # Threshold the HSV image to get only blue colors mask = cv2.inRange(hsv, lower_blue, upper_blue) # Bitwise-AND mask and original image res = cv2.bitwise_and(frame,frame, mask= mask) cv2.imshow('Window frame',frame) cv2.imshow('mask',mask) cv2.imshow('res',res) k = cv2.waitKey(5) & 0xFF if k == 27: break cv2.destroyAllWindows()
The code is simple. First you are creating the VideoCapture object to capture video from your camera just like we did earlier. Then in the loop we are converting our BGR video image to HSV for our convenience of tracking the blue object. Then we declared to array defining the range of blue color in HSV color spaces. Then we have done bitwise operation to find out the blue objects.
We can find the range of color in HSV color spaces using the following codes in the command terminal
green = np.uint8([[[0,255,0 ]]]) hsv_green = cv2.cvtColor(green,cv2.COLOR_BGR2HSV) print hsv_green [[[ 60 255 255]]]