Color tracking is fairly a simple activity in OpenCV and you may find a variety of articles in the Internet which describe different mechanisms and implementations. However the common steps involve the following.
- Convert the source frame into HSV color space.
- Define the upper bounds and lower bounds for the color you intend to track. In my example I mind the blue color and so the lower bound and upper bounds are respectively (100, 150, 0) and (140,255, 255) where the lower bound being the darker blue.
- Find the image mask that contain pixels which fall within the lower and upper bounds as mentioned above.
- Find contours in the mask image.
- Find the maximum contour in terms of the contour area. So that we can omit trivial contours and focus only on the most dominating blue color object in the scene.
- Approximate the maximum contour into a polygon.
- Find the bounding rectangle of the above polygon.
- Draw the rectangle from above step on the source image.
The code that follows the above series of steps is provided below.
#This is an exercise to track blue color from camera. import numpy as np import cv2 cap = cv2.VideoCapture(0) while(True): ret, source = cap.read() if(not ret): print('Error in video capture') break hsv = cv2.cvtColor(source, cv2.COLOR_BGR2HSV) lowerblue = np.array([100,150,0]) upperblue = np.array([140,255,255]) mask = cv2.inRange(hsv, lowerblue, upperblue) #find contours in the mask im, contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) maxContour = max(contours, key=cv2.contourArea) epsilon = 0.1*cv2.arcLength(maxContour, True) approxpoly = cv2.approxPolyDP(maxContour, epsilon, True) x,y,w,h = cv2.boundingRect(approxpoly) cv2.rectangle(source,(x,y),(x+w, y+h),(0,255,0), 2) cv2.imshow('original', source) if (cv2.waitKey(1) & 0xFF == 113): break cap.release() cv2.destroyAllWindows()
The demonstration is shown below.