Color tracking using webcam, OpenCV and Python

In this post, a simple method to obtain continuous video from a standard webcam is described. It also provides code to track a certain color from the camera feed. For this purpose, we make use of OpenCV functions in python.

To test if you are able to capture the live video feed, use the code snippet provided below.

# import the necessary packages
import cv2
#Declare variables for window
vc = cv2.VideoCapture(0)
# try to get the first frame
if vc.isOpened():
rval, frame =
rval = False
while rval:
cv2.imshow("preview", frame)
rval, frame =
key = cv2.waitKey(20)
if key == 27: # Exit when ESC key is pressed
vc.release() #To unlock camera on windows OS

If you are unable to close the window, simply press ‘Esc’. It has been assigned as the exit key in the code.

Now, to verify color tracking using HSV values, use the following code:

#Import necesessary packages
import cv2
import numpy as np
#Declare variables for window
vc = cv2.VideoCapture(0)
# Take each frame
ret, frame =
# Convert BGR to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# define range of blue color in HSV
lower_blue = np.array([50, 100, 100], dtype=np.uint8)#[110,50,50]
upper_blue = np.array([70,255,255], dtype=np.uint8)#[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)
k = cv2.waitKey(5) & 0xFF
if k == 27: #Exit when ESC key is pressed

If you would like to determine HSV values for any color, please use the example below:

>> green = np.uint8([[[0,255,0]]])
>> hsv_green = cv2.cvtColor(green,cv2.COLOR_BGR2HSV)
>> print hsv_green

Now the value obtained (here, [[[60 255 255]]]) offers the base to set the range of colors to determine. Use [H-10, 100, 100] as lower bound and [H+10, 255, 255] as upper bound.

Hope this helps.