smartyfy.mrindigi.com

Python Master Course V2 — 168. Video Frames, Motion and Simple Object Tracking

Purpose and learning outcomes

Video adds time and identity to image analysis. Detecting an object in each frame does not establish that two detections belong to the same object. You will generate a short sequence of moving squares, track component centroids with a distance gate, and use known synthetic identities only for evaluation. A crossing and temporary merge expose the limits of nearest-neighbor tracking without requiring a codec, camera, or video download.

  • Treat video as ordered frames with timestamps
  • Estimate motion and associate detections across frames
  • Identify tracking failures from occlusion and ambiguous matches

Prerequisites

  • 078: timestamps
  • 162 and 167: boxes and detection

Environment and execution

Use a project-specific virtual environment with a currently supported Python 3 release compatible with the packages below. Python 3.11 or 3.12 is a practical starting point. Run shell commands in a terminal, then run the Python blocks in order in one script or notebook kernel. They use only included data and local CPU computation. No account, API key, camera, or external dataset is required. Record the installed package versions with python -m pip freeze when you save your results; a random seed does not guarantee identical numerical behavior across library versions.

python -m venv .venv
# macOS/Linux: source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install numpy scipy

Understand the model and its assumptions

A frame sequence should preserve capture order and timestamps. Frame number is not elapsed time unless the frame rate is fixed and no frames are dropped. Velocity is displacement divided by elapsed time, so irregular sampling changes its interpretation. Our generated frames use a declared ten frames per second and monotonically increasing timestamps.

Detection produces a set of positions within one frame. Association assigns those detections to existing tracks. A distance gate rejects pairings that require implausibly large motion between frames. Greedy nearest-pair assignment is simple: sort candidate distances, then accept pairs only if neither the track nor detection has been used. This is not globally optimal assignment and can fail when nearby objects cross.

A track needs lifecycle rules. New unmatched detections start tracks; unmatched existing tracks accumulate missed frames; tracks expire after a declared gap. Keeping a track alive briefly supports short occlusions, but its last position becomes stale. A constant-velocity model can improve prediction in some settings, while appearance features can help distinguish objects. Neither removes ambiguity when observations do not identify which object is which.

Evaluation must distinguish missed detections from identity switches. An identity switch occurs when the same true object is associated with a different track ID under the chosen protocol. The generated truth is available for evaluation only; feeding it into association would make the tracker appear magically reliable. When two identical squares overlap exactly, a component detector observes one region and cannot recover two separate identities from that frame alone.

Worked example: build it in stages

Generate thirteen frames in which two identical squares approach and cross. Detect connected-component centroids from each frame. The tracker uses only those centroids, a six-pixel gate, and a one-missed-frame lifetime. For auditing, each unambiguous detected center is matched to the nearest generated object center; tied truth distances are recorded as ambiguous rather than guessed. Track labels are ordinary counters, not real-world identities.

import numpy as np
from scipy import ndimage

frames, timestamps, truth_frames = [], [], []
for frame_number in range(13):
    truth = {"A": (8 + 4*frame_number, 15), "B": (56 - 4*frame_number, 15)}
    frame = np.zeros((32, 64), dtype=float)
    for x, y in truth.values():
        frame[y-1:y+2, x-1:x+2] = 1.0
    frames.append(frame)
    timestamps.append(frame_number / 10)
    truth_frames.append(truth)

def detections(frame):
    labels, count = ndimage.label(frame > 0.5)
    centers = ndimage.center_of_mass(frame > 0.5, labels, range(1, count+1))
    return [np.array([column, row]) for row, column in centers]

tracks, next_id = {}, 0
last_track_for_truth = {}
switches = ambiguous = 0
history = []
for frame, timestamp, truth in zip(frames, timestamps, truth_frames):
    observed = detections(frame)
    for track in tracks.values():
        track["missed"] += 1
    candidates = []
    for track_id, track in tracks.items():
        for j, point in enumerate(observed):
            distance = float(np.linalg.norm(track["point"]-point))
            if distance <= 6:
                candidates.append((distance, track_id, j))
    used_tracks, used_detections, assigned = set(), set(), {}
    for distance, track_id, j in sorted(candidates):
        if track_id in used_tracks or j in used_detections:
            continue
        tracks[track_id] = {"point": observed[j], "missed": 0}
        used_tracks.add(track_id)
        used_detections.add(j)
        assigned[j] = track_id
    for j, point in enumerate(observed):
        if j not in used_detections:
            tracks[next_id] = {"point": point, "missed": 0}
            assigned[j] = next_id
            next_id += 1
    tracks = {i: t for i, t in tracks.items() if t["missed"] <= 1}
    history.append((timestamp, dict(assigned)))
    for j, track_id in assigned.items():
        distances = sorted((float(np.linalg.norm(observed[j]-np.array(center))), name)
                           for name, center in truth.items())
        if len(distances) > 1 and np.isclose(distances[0][0], distances[1][0]):
            ambiguous += 1
            continue
        name = distances[0][1]
        if name in last_track_for_truth and last_track_for_truth[name] != track_id:
            switches += 1
        last_track_for_truth[name] = track_id

assert np.all(np.diff(timestamps) > 0)
print("frames:", len(frames), "tracks created:", next_id)
print("identity switches:", switches, "ambiguous observations:", ambiguous)
print("middle-frame detections:", len(detections(frames[6])))

What the output means

The sequence has thirteen frames, and the middle frame has one detected component because the two squares overlap exactly. Track count, identity switches, and ambiguous observations are computed by the declared association and audit rules. The identity-switch count is not a standardized multi-object-tracking benchmark score. It is a transparent diagnostic for this synthetic crossing, whose ground truth is known by construction.

Guided lab and acceptance checks

First run a no-crossing variant by placing the objects on different rows. Then compare it with the crossing sequence. Increase the distance gate and explain why fewer rejected matches can also mean more wrong associations. Delete one frame while keeping the original timestamps and inspect the longer motion interval.

Acceptance requires monotonic timestamps, explicit gate and expiry settings, no truth input to the tracker, and an audit of misses versus switches. Add a record of per-track positions so you can draw trajectories or inspect them numerically. An optional GIF can visualize the frames, but the core experiment must remain runnable without multimedia codecs.

Common mistakes and repairs

Do not sort frames lexicographically when filenames such as frame10 precede frame2. Do not use a fixed pixel gate across irregular time gaps without considering elapsed time. A reused track number is not proof of object identity. Avoid hiding merged detections by supplying the generator's true centers to the tracker; that bypasses the very observation problem being studied.

Questions and answers

Why is tracking harder than repeated detection?

Detection reports what is visible now. Tracking must connect observations across motion, missed frames, and occlusion while preserving identity. Multiple objects can generate equally plausible associations, especially when they look alike or cross.

Why does a distance gate need a time assumption?

A ten-pixel move may be implausible over one millisecond and ordinary over a second. A fixed gate is meaningful only relative to sampling interval and expected motion. Time-aware gates or motion models are needed when intervals vary.

Can nearest-neighbor tracking solve identical-object crossings?

Not reliably. At a crossing the closest continuation can belong to the other physical object, and a merged observation loses separation information. Additional motion history or appearance cues can help, but genuinely indistinguishable observations remain uncertain.

Why keep unmatched tracks briefly?

A detection may be missing for one frame because of noise or occlusion. Immediate deletion creates new IDs when the object returns. Retaining tracks helps continuity but also risks matching a stale track to a different object, so expiry is a tradeoff.

Why skip tied ground-truth attribution in the audit?

When one observed center is equally compatible with both true objects, assigning it arbitrarily would create a misleading identity claim. Recording ambiguity keeps the diagnostic honest. A formal benchmark may use a different specified matching protocol.

Exercises

1. Calculate speed from two positions and timestamps. 2. Reject zero or negative elapsed time. 3. Explain why deleting a frame should not compress the remaining timestamps to pretend no gap occurred.

Worked solutions and reasoning

Both intervals imply forty pixels per second. Compressing timestamps after a dropped frame would falsely double the inferred speed. Frame order and elapsed time are separate pieces of information and should both survive ingestion.

def speed(previous, current, t0, t1):
    if t1 <= t0:
        raise ValueError("timestamps must increase")
    return float(np.linalg.norm(np.array(current)-np.array(previous))/(t1-t0))
assert np.isclose(speed((8, 15), (12, 15), 0.0, 0.1), 40.0)
assert np.isclose(speed((8, 15), (16, 15), 0.0, 0.2), 40.0)

Recap

Tracking requires ordered observations, a motion assumption, one-to-one association, and explicit lifecycle rules. Synthetic video exposes identity ambiguity without needing real footage. Report uncertainty and failure modes rather than treating a persistent number on a moving shape as established identity.

Official references

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.