In this tutorial, we will learn how we can use color models for object tracking. You can use any color model. Here, I have used HSI because it is easier to represent a color using the HSI model (as it separates the color component from greyscale). Let’s see how to do this
Steps
- Open the camera using cv2.VideoCapture()
- Create 3 Trackbars of H, S, and I using cv2.createTrackbar()
- Read frame by frame
- Record the current trackbar position using cv2.getTrackbarPos()
- Convert from BGR to HSV using cv2.cvtColor()
- Threshold the HSV image based on current trackbar position using cv2.inRange()
- Extract the desired result
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import cv2 import numpy as np def nothing(x): pass cap = cv2.VideoCapture(0) # Create a window cv2.namedWindow('image',cv2.WINDOW_NORMAL) # create trackbars for color change cv2.createTrackbar('lowH','image',0,179,nothing) cv2.createTrackbar('highH','image',179,179,nothing) cv2.createTrackbar('lowS','image',0,255,nothing) cv2.createTrackbar('highS','image',255,255,nothing) cv2.createTrackbar('lowV','image',0,255,nothing) cv2.createTrackbar('highV','image',255,255,nothing) while(True): ret, frame = cap.read() # get current positions of the trackbars ilowH = cv2.getTrackbarPos('lowH', 'image') ihighH = cv2.getTrackbarPos('highH', 'image') ilowS = cv2.getTrackbarPos('lowS', 'image') ihighS = cv2.getTrackbarPos('highS', 'image') ilowV = cv2.getTrackbarPos('lowV', 'image') ihighV = cv2.getTrackbarPos('highV', 'image') hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) lower_hsv = np.array([ilowH, ilowS, ilowV]) higher_hsv = np.array([ihighH, ihighS, ihighV]) mask = cv2.inRange(hsv, lower_hsv, higher_hsv) frame = cv2.bitwise_and(frame, frame, mask=mask) cv2.imshow('image', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() |
Open in full screen and play with trackbar to get more intuition about HSI model. Hope you enjoy reading.
If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.