Tracker Module

Advanced object tracking and motion analysis capabilities

Overview

The Tracker module provides sophisticated object tracking and motion analysis capabilities. It enables robust object tracking across video frames, trajectory analysis, line crossing detection, and detailed motion pattern analysis.

Object Tracking

Robust multi-object tracking with automatic ID assignment

Line Crossing

Advanced line crossing detection with directional analysis

Motion Analysis

Track movement patterns and calculate trajectories

Visualization

Rich visualization tools for tracks and statistics

Installation

pip install yolozone

Initialization

from yolozone import ObjectTracker

# Initialize tracker
tracker = ObjectTracker()

# Tracking parameters can be customized:
tracker.max_track_length = 30  # Maximum track history length
tracker.max_inactive_frames = 30  # Frames before removing inactive tracks
tracker.min_detection_confidence = 0.3  # Minimum confidence for detection
tracker.min_track_hits = 3  # Minimum detections to confirm track

Configuration Parameters

Track Management

  • max_track_length: Maximum points in track history (default: 30)
  • max_inactive_frames: Frames before track removal (default: 30)
  • min_track_hits: Minimum detections to confirm track (default: 3)

Detection Parameters

  • min_detection_confidence: Minimum confidence threshold (default: 0.3)
  • max_movement_threshold: Maximum pixel movement between frames (default: 100)
  • max_size_change: Maximum allowed size change ratio (default: 0.5)

Matching Parameters

  • max_frames_to_match: Maximum frame difference for matching (default: 30)
  • iou_threshold: Minimum IOU for box matching (default: 0.3)

Methods

update(results, min_hits=3)

Update tracks with new detections

Parameters

  • results: Detection results from object detector
  • min_hits (int): Minimum detections to confirm track

Returns

  • dict: Dictionary of current tracks

Example

# Update tracks with new detections
current_tracks = tracker.update(detection_results)

draw_tracks(frame, tracks, draw_labels=True, draw_trails=True)

Visualize tracked objects and their trails

Parameters

  • frame: Input image/frame
  • tracks: Dictionary of current tracks
  • draw_labels (bool): Whether to draw labels
  • draw_trails (bool): Whether to draw motion trails

Returns

  • numpy.ndarray: Frame with visualizations

Example

# Draw tracks with trails and labels
frame = tracker.draw_tracks(
    frame,
    current_tracks,
    draw_labels=True,
    draw_trails=True
)

detect_line_crossing(line_start, line_end, track_info)

Detect if a track has crossed a defined line

Parameters

  • line_start (tuple): Start point of line (x, y)
  • line_end (tuple): End point of line (x, y)
  • track_info: Track information dictionary

Returns

  • tuple: (crossed: bool, direction: int)

Example

# Check if track crossed line
crossed, direction = tracker.detect_line_crossing(
    (100, 300), (500, 300),  # Line coordinates
    track_info
)

update_line_crossings(tracks, line_start, line_end)

Update and count line crossings by direction and class

Parameters

  • tracks: Dictionary of current tracks
  • line_start (tuple): Start point of line
  • line_end (tuple): End point of line

Returns

  • dict: Counts of crossings by direction and class

Example

# Get crossing statistics
crossings = tracker.update_line_crossings(
    tracks,
    (100, 300),  # Line start
    (500, 300)   # Line end
)
print(f"Up crossings: {crossings['up']}")
print(f"Down crossings: {crossings['down']}")

draw_counting_line(frame, line_start, line_end, counts)

Visualize counting line and crossing statistics

Parameters

  • frame: Input image/frame
  • line_start (tuple): Start point of line
  • line_end (tuple): End point of line
  • counts: Dictionary of crossing counts

Returns

  • numpy.ndarray: Frame with line and statistics

Example

# Draw counting line and statistics
frame = tracker.draw_counting_line(
    frame,
    (100, 300),
    (500, 300),
    crossing_counts
)

get_track_info(track_id)

Get detailed information about a specific track

Parameters

  • track_id: ID of the track

Returns

  • dict: Track information including history and statistics

Example

# Get track information
info = tracker.get_track_info(track_id)
print(f"Track length: {info['length']}")
print(f"Displacement: {info['displacement']}")

Complete Examples

Basic Object Tracking

from yolozone import ObjectDetector, ObjectTracker
import cv2

# Initialize detector and tracker
detector = ObjectDetector()
tracker = ObjectTracker()

# Process video
cap = cv2.VideoCapture('video.mp4')

while True:
    ret, frame = cap.read()
    if not ret:
        break
        
    # Detect objects with tracking enabled
    results = detector.detect_objects(
        frame,
        track=True,
        conf=0.35
    )
    
    # Update tracks
    current_tracks = tracker.update(results)
    
    # Draw tracks
    frame = tracker.draw_tracks(
        frame,
        current_tracks,
        draw_trails=True
    )
    
    cv2.imshow('Tracking', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

Line Crossing Detection

# Define counting line
line_start = (100, 300)
line_end = (500, 300)

while True:
    ret, frame = cap.read()
    if not ret:
        break
    
    # Detect and track objects
    results = detector.detect_objects(frame, track=True)
    current_tracks = tracker.update(results)
    
    # Update crossing counts
    counts = tracker.update_line_crossings(
        current_tracks,
        line_start,
        line_end
    )
    
    # Draw visualizations
    frame = tracker.draw_tracks(frame, current_tracks)
    frame = tracker.draw_counting_line(
        frame,
        line_start,
        line_end,
        counts
    )
    
    cv2.imshow('Line Crossing', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

Motion Analysis

# Process video and analyze motion
while True:
    ret, frame = cap.read()
    if not ret:
        break
    
    # Track objects
    results = detector.detect_objects(frame, track=True)
    current_tracks = tracker.update(results)
    
    # Analyze each track
    for track_id in current_tracks:
        info = tracker.get_track_info(track_id)
        
        # Print motion statistics
        print(f"Track {track_id}:")
        print(f"- Length: {info['length']} frames")
        print(f"- Total displacement: {info['displacement']:.2f}")
        print(f"- Class: {info['class']}")
        print(f"- Current position: {info['current_pos']}")
    
    # Visualize
    frame = tracker.draw_tracks(
        frame,
        current_tracks,
        draw_trails=True
    )
    
    cv2.imshow('Motion Analysis', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break