0
0
Computer Visionml~5 mins

Object tracking basics in Computer Vision

Choose your learning style9 modes available
Introduction

Object tracking helps computers follow moving things in videos or live camera feeds. It makes machines understand where objects go over time.

Tracking a ball in a sports game to analyze player performance.
Following a car in traffic videos for safety monitoring.
Monitoring people in a store for customer behavior analysis.
Keeping track of animals in wildlife videos for research.
Detecting and following drones or robots in a controlled area.
Syntax
Computer Vision
tracker = cv2.TrackerCSRT_create()
tracker.init(frame, bounding_box)
success, box = tracker.update(new_frame)

This example uses OpenCV's CSRT tracker, which is good for accuracy.

You first create a tracker, then initialize it with the first frame and the object's position, then update it for each new frame.

Examples
KCF tracker is faster but less accurate than CSRT.
Computer Vision
tracker = cv2.TrackerKCF_create()
tracker.init(frame, bbox)
success, box = tracker.update(new_frame)
MOSSE tracker is very fast and good for simple objects.
Computer Vision
tracker = cv2.TrackerMOSSE_create()
tracker.init(frame, bbox)
success, box = tracker.update(new_frame)
Sample Model

This program opens a video, lets you select an object to track, then follows it frame by frame using the CSRT tracker. It draws a green box around the object and shows if tracking is successful or lost.

Computer Vision
import cv2

# Load a video file
video = cv2.VideoCapture('video.mp4')

# Read the first frame
ret, frame = video.read()
if not ret:
    print('Cannot read video')
    exit()

# Select the object to track (manually select bounding box)
bbox = cv2.selectROI('Frame', frame, False)
cv2.destroyWindow('Frame')

# Create CSRT tracker
tracker = cv2.TrackerCSRT_create()
tracker.init(frame, bbox)

frame_count = 0
while True:
    ret, frame = video.read()
    if not ret:
        break

    success, box = tracker.update(frame)

    if success:
        x, y, w, h = map(int, box)
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        status = 'Tracking'
    else:
        status = 'Lost'

    cv2.putText(frame, status, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

    # Show frame
    cv2.imshow('Tracking', frame)

    if cv2.waitKey(30) & 0xFF == 27:  # ESC key to stop
        break

    frame_count += 1

video.release()
cv2.destroyAllWindows()
print(f'Tracked {frame_count} frames successfully.')
OutputSuccess
Important Notes

Object tracking needs a good initial position to work well.

Different trackers balance speed and accuracy differently.

Lighting changes and fast movement can make tracking harder.

Summary

Object tracking follows moving objects in videos over time.

Start by selecting the object, then update its position in each new frame.

Use different trackers depending on your need for speed or accuracy.