Object Tracking Concept
Object tracking follows a specific object across multiple video frames. Once an object is detected in one frame, tracking keeps following it without re-running full detection on every frame.
8 min•By Priygop Team•Updated 2026
Object Tracking with OpenCV
Object Tracking with OpenCV
import cv2
def track_object(video_path, initial_bbox=None):
"""
Track an object across video frames using CSRT tracker.
initial_bbox: (x, y, w, h) of the object in the first frame.
If None, user can select the object interactively.
"""
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print("Could not open video")
return
ret, first_frame = cap.read()
if not ret:
return
# Initialise tracker
# Available trackers: CSRT (accurate), KCF (fast), MOSSE (fastest)
tracker = cv2.TrackerCSRT_create()
if initial_bbox is None:
# Let user select the region to track
print("Select object to track, press ENTER when done")
initial_bbox = cv2.selectROI("Select Object", first_frame, fromCenter=False)
cv2.destroyWindow("Select Object")
# Initialise tracker with first frame and bounding box
tracker.init(first_frame, initial_bbox)
print(f"Tracking started: initial box = {initial_bbox}")
frame_count = 0
success_count = 0
while frame_count < 500:
ret, frame = cap.read()
if not ret:
break
# Update tracker
success, bbox = tracker.update(frame)
if success:
x, y, w, h = [int(v) for v in bbox]
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.putText(frame, "Tracking", (x, y-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
success_count += 1
else:
cv2.putText(frame, "Tracking lost", (50, 50),
cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 2)
frame_count += 1
cap.release()
success_rate = success_count / frame_count * 100 if frame_count > 0 else 0
print(f"Tracking success rate: {success_rate:.1f}% ({success_count}/{frame_count})")
track_object("video.mp4", initial_bbox=(100, 50, 80, 120))Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment