Object Tracking Using OpenCV
Below, are the code of Object Tracking Using OpenCV:
Install Necessary Library
First, we need to install the numpy and cv2 libraries, which help us with object tracking. To install them, use the following command:
pip install numpy opencv-python
Complete Code
Below, code starts by capturing video and picking a specific area to focus on from the initial frame. Then, it analyzes that area to create a histogram and sets rules for when to stop tracking. Inside a loop, it continuously reads frames, figures out where the focused area is in each frame, and draws a rectangle around it. This loop keeps going until you press the escape key. Lastly, it stops capturing video and closes all open windows.
import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
ret, frame = cap.read()
bbox = cv.selectROI('select', frame, False)
x, y, w, h = bbox
roi = frame[y:y+h, x:x+w]
hsv_roi = cv.cvtColor(roi, cv.COLOR_BGR2HSV)
mask = cv.inRange(hsv_roi, np.array((0., 60., 32.)),
np.array((180., 255., 255.)))
roi_hist = cv.calcHist([hsv_roi], [0], mask, [180], [0, 180])
cv.normalize(roi_hist, roi_hist, 0, 255, cv.NORM_MINMAX)
term_crit = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 1)
while(1):
ret, frame = cap.read()
if ret == True:
hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
dst = cv.calcBackProject([hsv], [0], roi_hist, [0, 180], 1)
ret, track_window = cv.meanShift(dst, bbox, term_crit)
x, y, w, h = track_window
img2 = cv.rectangle(frame, (x, y), (x+w, y+h), 255, 2)
cv.imshow('gfg', img2)
k = cv.waitKey(30) & 0xff
if k == 27:
break
else:
break
cap.release()
cv.destroyAllWindows()
Output:
Getting Started With Object Tracking Using OpenCV
OpenCV, developed by Intel in the early 2000s, is a popular open-source computer vision library used for real-time tasks. It offers various features like image processing, face detection, object detection, and more. In this article, we explore object-tracking algorithms and how to implement them using OpenCV and Python to track objects in videos.