Multi-Object Tracking: Kalman Filter, SORT and Metrics
A detector run on every frame of a video produces a pile of boxes with no memory: frame 7 has three cars, frame 8 has three cars, but which car in frame 8 is which car from frame 7? Tracking answers that question by giving each object an identity that persists over time. With identities you can count cars once instead of once per frame, measure their speed, notice that a person has stood in a doorway for ten minutes, or follow a player across a match. This lesson builds a complete multi-object tracker from scratch: single-object tracking first, then the Kalman filter for motion, the Hungarian algorithm for matching, the SORT tracker that combines them, and the MOTA and IDF1 metrics that score it.
Single-object tracking
The simplest tracker follows one object that a person marked in the first frame. Template matching cuts the object out of frame 0 and, in every later frame, slides the template over the image and takes the position with the highest normalised cross-correlation (cv2.matchTemplate with TM_CCOEFF_NORMED, a score in ). Learned single-object trackers such as OpenCV's MIL tracker (multiple instance learning, Babenko et al., 2009) instead train a small classifier online, object versus surroundings, and update it as the object's appearance changes. Both are run below on vehicle 1 of the course's synthetic traffic video (make_video, introduced in video and motion), with IoU against the true box:
import numpy as np, cv2
cv2.setLogLevel(0)
def make_video(rng, n_frames=30, h=90, w=160, n_objects=3):
"""Grey road scene with bright rectangles ("vehicles") moving at constant velocity.
Returns frames (T, h, w) uint8 and gt: list per frame of (track_id, [x1, y1, x2, y2])."""
objs = []
for k in range(n_objects):
bw, bh = int(rng.integers(14, 24)), int(rng.integers(8, 14))
x, y = float(rng.uniform(0, w - bw)), float(10 + 25 * k + rng.uniform(0, 8))
vx = float(rng.choice([-1, 1]) * rng.uniform(1.5, 3.5)); vy = float(rng.uniform(-0.3, 0.3))
objs.append([x, y, bw, bh, vx, vy, int(rng.integers(170, 250))])
frames, gt = [], []
for t in range(n_frames):
f = rng.normal(60, 6, (h, w))
boxes = []
for k, (x, y, bw, bh, vx, vy, g) in enumerate(objs):
x1, y1 = int(round(x + vx * t)), int(round(y + vy * t))
if x1 + bw <= 0 or x1 >= w:
continue # left the frame
f[max(y1, 0):y1 + bh, max(x1, 0):x1 + bw] = g
boxes.append((k, [max(x1, 0), max(y1, 0), min(x1 + bw, w), min(y1 + bh, h)]))
frames.append(f.clip(0, 255).astype(np.uint8)); gt.append(boxes)
return np.array(frames), gt
def iou(a, b):
ix = max(0, min(a[2], b[2]) - max(a[0], b[0])); iy = max(0, min(a[3], b[3]) - max(a[1], b[1]))
inter = ix * iy
return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)
frames, gt = make_video(np.random.default_rng(0))
x1, y1, x2, y2 = dict(gt[0])[1] # vehicle 1 in the first frame
w, h, m = x2 - x1, y2 - y1, 3
print("vehicle 1 at frame 0:", [x1, y1, x2, y2])
template = frames[0][y1 - m:y2 + m, x1 - m:x2 + m] # with a 3-pixel margin of road: a uniform patch has no texture
cv2.setRNGSeed(0) # MIL samples patches at random: fix its seed
mil = cv2.TrackerMIL_create()
mil.init(cv2.cvtColor(frames[0], cv2.COLOR_GRAY2BGR), (x1, y1, w, h))
rows = []
for t in range(1, 20):
g = dict(gt[t]).get(1)
if g is None:
print(f"frame {t}: vehicle 1 has left the picture"); break
score = cv2.matchTemplate(frames[t], template, cv2.TM_CCOEFF_NORMED)
_, best, _, (bx, by) = cv2.minMaxLoc(score)
tm = [bx + m, by + m, bx + m + w, by + m + h]
ok, (mx, my, mw, mh) = mil.update(cv2.cvtColor(frames[t], cv2.COLOR_GRAY2BGR))
if t in (1, 4, 8, 11, 12, 13, 15, 18):
print(f"frame {t:2d} truth {g} template IoU {iou(tm, g):.2f} (score {best:.2f}) MIL IoU {iou([mx, my, mx + mw, my + mh], g):.2f}")vehicle 1 at frame 0: [103, 39, 122, 50]
frame 1 truth [106, 39, 125, 50] template IoU 1.00 (score 1.00) MIL IoU 0.69
frame 4 truth [115, 38, 134, 49] template IoU 1.00 (score 1.00) MIL IoU 0.40
frame 8 truth [128, 37, 147, 48] template IoU 1.00 (score 1.00) MIL IoU 0.48
frame 11 truth [137, 36, 156, 47] template IoU 1.00 (score 1.00) MIL IoU 0.48
frame 12 truth [140, 36, 159, 47] template IoU 0.00 (score 0.85) MIL IoU 0.44
frame 13 truth [144, 35, 160, 46] template IoU 0.00 (score 0.74) MIL IoU 0.45
frame 15 truth [150, 35, 160, 46] template IoU 0.00 (score 0.74) MIL IoU 0.09
frame 18 truth [159, 34, 160, 45] template IoU 0.00 (score 0.74) MIL IoU 0.00
frame 19: vehicle 1 has left the picture
The template has a 3-pixel margin of road around the vehicle, because a perfectly uniform patch has zero variance and its normalised correlation is undefined. Until frame 11 template matching is exact (IoU 1.00, score 1.00): the synthetic vehicle never changes. At frame 12 the vehicle's front plus the margin reaches the right border of the picture, the template no longer fits around it, and the best match (score 0.85) jumps to a different place: IoU 0 from then on. MIL follows the vehicle more loosely (IoU around 0.5, its box lags behind), and as the vehicle leaves the picture its box stays behind and the IoU decays to 0.
Both failures are typical. Template matching cannot handle appearance changes, partial visibility or scale changes; online-learned trackers drift as they learn from their own slightly wrong boxes. Modern single-object trackers (Siamese networks such as SiamRPN, transformer trackers such as OSTrack; OpenCV's TrackerNano, TrackerVit and TrackerDaSiamRPN need ONNX model files that this course cannot load) are far more robust, but none of them knows when a new object appears. For many objects, the standard approach is different.
Tracking by detection
Tracking by detection runs a detector on every frame and solves a matching problem between frames. Every tracker of this family repeats four steps per frame:
The two parts that need explaining are the prediction (where should each track be now?) and the association (which detection belongs to which track?).
Predicting motion: the Kalman filter
A track's state is a vector, for a box centre moving at constant velocity , together with its uncertainty, a covariance matrix . The Kalman filter (1960) alternates two steps. Predict moves the state forward with the motion model and grows the uncertainty by the process noise (the motion is never exactly constant). Update blends the prediction with a measurement (the detected centre, with measurement noise ), weighting each by how certain it is:
For constant velocity with one frame per step, adds the velocity to the position, and picks the position out of the state:
The gain is large when the prediction is uncertain (trust the measurement) and small when the measurement is noisy (trust the motion model). When an object is not detected, the filter simply skips the update and keeps predicting, with growing uncertainty: that is how a tracker coasts through a missed detection or a short occlusion. All the quantities are Gaussian, and the update is Bayes' rule for Gaussians (multivariate Gaussian, Bayes' theorem).
import numpy as np
# A vehicle's centre moves at constant velocity; a detector measures it with noise and misses frames 12-15.
rng = np.random.default_rng(0)
T = 30
true = np.stack([20 + 2.5 * np.arange(T), 40 - 0.3 * np.arange(T)], 1) # (x, y) in pixels
z = true + rng.normal(0, 2.0, true.shape) # measurement noise sigma = 2 px
missing = set(range(12, 16))
F = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]], float) # x += vx, y += vy
H = np.array([[1, 0, 0, 0], [0, 1, 0, 0]], float) # we observe x, y
Q = np.diag([0.01, 0.01, 0.01, 0.01]) # process noise (small: smooth motion)
R = 2.0 ** 2 * np.eye(2) # measurement noise
x = np.array([z[0, 0], z[0, 1], 0.0, 0.0]); P = np.diag([4.0, 4.0, 25.0, 25.0])
est, sd = [x[:2].copy()], [np.sqrt(np.diag(P)[:2])]
for t in range(1, T):
x = F @ x; P = F @ P @ F.T + Q # predict
if t not in missing: # update
S = H @ P @ H.T + R
K = P @ H.T @ np.linalg.inv(S) # Kalman gain
x = x + K @ (z[t] - H @ x); P = (np.eye(4) - K @ H) @ P
est.append(x[:2].copy()); sd.append(np.sqrt(np.diag(P)[:2]))
est, sd = np.array(est), np.array(sd)
seen = [t for t in range(5, T) if t not in missing]
err = lambda a, idx: float(np.sqrt(np.mean(np.sum((a[idx] - true[idx]) ** 2, axis=1))))
print(f"position error (RMS, frames 5-29 with a measurement): raw {err(z, seen):.2f} px, filtered {err(est, seen):.2f} px")
print(f"during the gap 12-15 (prediction only): {err(est, sorted(missing)):.2f} px")
print(f"estimated velocity at frame 29: ({x[2]:.2f}, {x[3]:.2f}) px/frame, true (2.50, -0.30)")
for t in [11, 12, 15, 16]:
print(f"frame {t}: x std {sd[t, 0]:.2f} px" + (" (no measurement)" if t in missing else ""))position error (RMS, frames 5-29 with a measurement): raw 2.75 px, filtered 1.98 px
during the gap 12-15 (prediction only): 2.19 px
estimated velocity at frame 29: (2.36, -0.44) px/frame, true (2.50, -0.30)
frame 11: x std 1.13 px
frame 12: x std 1.33 px (no measurement)
frame 15: x std 2.06 px (no measurement)
frame 16: x std 1.52 px
The filter reduces the position error from 2.75 pixels (the raw detections, noise in each axis) to 1.98 pixels, and keeps the error at 2.19 pixels during the four frames without any measurement, because it has learned the velocity: (2.36, -0.44) pixels per frame against the true (2.50, -0.30). The standard deviation of the estimate shows the coasting: 1.13 pixels before the gap, rising to 2.06 after four predictions in a row, and falling to 1.52 as soon as a measurement arrives. The choice of and is the tuning knob: a larger follows turns and braking faster but smooths less.
Associating detections with tracks
Given the predicted boxes of tracks and new detections, build the IoU matrix and choose pairs. Choosing the best pair first, then the best of the rest (greedy), can block a better overall assignment. The Hungarian algorithm (Kuhn, 1955) finds the one-to-one assignment with the minimum total cost (cost ), in time in its later refined forms; SciPy has it as linear_sum_assignment. Pairs below an IoU threshold are rejected afterwards.
import numpy as np
from scipy.optimize import linear_sum_assignment
# IoU between 2 predicted track boxes (rows) and 2 new detections (columns)
iou = np.array([[0.60, 0.50],
[0.55, 0.00]])
thr = 0.3
# Greedy: take the best remaining pair, again and again
pairs, rows, cols = [], set(), set()
for i, j in sorted(np.ndindex(iou.shape), key=lambda ij: -iou[ij]):
if i not in rows and j not in cols and iou[i, j] >= thr:
pairs.append((i, j)); rows.add(i); cols.add(j)
print("greedy :", [(int(i), int(j)) for i, j in pairs], "total IoU", round(float(sum(iou[p] for p in pairs)), 2))
# Hungarian: the assignment with the largest total IoU (minimum total cost 1 - IoU)
r, c = linear_sum_assignment(1 - iou)
pairs = [(int(i), int(j)) for i, j in zip(r, c) if iou[i, j] >= thr]
print("Hungarian:", pairs, "total IoU", round(float(sum(iou[p] for p in pairs)), 2))greedy : [(0, 0)] total IoU 0.6
Hungarian: [(0, 1), (1, 0)] total IoU 1.05
Greedy takes the single best pair (track 0, detection 0, IoU 0.60), and track 1 is left with detection 1, IoU 0, below the threshold: one track loses its object and one detection starts a spurious new track. The Hungarian solution pairs track 0 with detection 1 and track 1 with detection 0, total IoU 1.05, and keeps both tracks. In crowded scenes this difference decides whether identities survive.
IoU as the cost works when objects move less than their own size per frame. For fast objects or low frame rates, the distance between centres (often the Mahalanobis distance under the Kalman covariance, which knows how far a track can plausibly have moved) is used instead, and appearance similarity is added when objects look different (DeepSORT, below).
SORT
SORT (Simple Online and Realtime Tracking, Bewley et al., 2016) is exactly the loop of the figure: Kalman prediction of each box (centre, size and velocity), IoU cost, Hungarian matching with a minimum IoU, and two counters per track. max_age is how many frames a track may go unmatched before it is deleted; min_hits is how many consecutive matches a new track needs before it is reported, which suppresses one-frame false alarms. It runs at hundreds of frames per second because it does nothing else.
The test below uses the three vehicles of make_video (68 true boxes in 30 frames) and a simulated detector: every true box is dropped with probability 0.15, the survivors have their corners jittered by 1 pixel, and on average 0.3 false boxes per frame appear at random. The baseline is an "IoU tracker" without memory: it matches each detection to the previous frame's boxes only, so a single missed frame ends a track.
The metrics come from the CLEAR MOT framework (Bernardin and Stiefelhagen, 2008). In each frame, true boxes and reported boxes are matched by IoU (at least 0.5, Hungarian); unmatched true boxes are false negatives (FN), unmatched reported boxes false positives (FP), and an identity switch (IDSW) is counted whenever a true object is matched to a different track id than the last time it was matched. Then
where is the number of true objects in frame . MOTA can be negative. It is dominated by detection errors (FN and FP are usually much larger than IDSW), so it says little about identity. IDF1 (Ristani et al., 2016) does the opposite: it matches whole true trajectories to whole tracks one to one (Hungarian on the number of frames they share), counts the frames where a true object is covered by its track (IDTP), and computes an score,
so a tracker that switches ids halfway through scores about half. HOTA (2020) balances the two and is the current benchmark headline; the idea is the same.
import numpy as np
def make_video(rng, n_frames=30, h=90, w=160, n_objects=3):
"""Grey road scene with bright rectangles ("vehicles") moving at constant velocity.
Returns frames (T, h, w) uint8 and gt: list per frame of (track_id, [x1, y1, x2, y2])."""
objs = []
for k in range(n_objects):
bw, bh = int(rng.integers(14, 24)), int(rng.integers(8, 14))
x, y = float(rng.uniform(0, w - bw)), float(10 + 25 * k + rng.uniform(0, 8))
vx = float(rng.choice([-1, 1]) * rng.uniform(1.5, 3.5)); vy = float(rng.uniform(-0.3, 0.3))
objs.append([x, y, bw, bh, vx, vy, int(rng.integers(170, 250))])
frames, gt = [], []
for t in range(n_frames):
f = rng.normal(60, 6, (h, w))
boxes = []
for k, (x, y, bw, bh, vx, vy, g) in enumerate(objs):
x1, y1 = int(round(x + vx * t)), int(round(y + vy * t))
if x1 + bw <= 0 or x1 >= w:
continue # left the frame
f[max(y1, 0):y1 + bh, max(x1, 0):x1 + bw] = g
boxes.append((k, [max(x1, 0), max(y1, 0), min(x1 + bw, w), min(y1 + bh, h)]))
frames.append(f.clip(0, 255).astype(np.uint8)); gt.append(boxes)
return np.array(frames), gt
from scipy.optimize import linear_sum_assignment
def iou_matrix(a, b):
a, b = np.asarray(a, float).reshape(-1, 4)[:, None], np.asarray(b, float).reshape(-1, 4)[None]
iw = np.clip(np.minimum(a[..., 2], b[..., 2]) - np.maximum(a[..., 0], b[..., 0]), 0, None)
ih = np.clip(np.minimum(a[..., 3], b[..., 3]) - np.maximum(a[..., 1], b[..., 1]), 0, None)
inter = iw * ih
area = lambda r: (r[..., 2] - r[..., 0]) * (r[..., 3] - r[..., 1])
return inter / (area(a) + area(b) - inter)
def noisy_detector(gt, rng, p_miss=0.15, jitter=1.0, false_rate=0.3, h=90, w=160):
"""Simulated detector: drops each object with p_miss, jitters box corners (sigma jitter px),
adds Poisson(false_rate) false boxes per frame. Returns a list of (n, 4) arrays, no ids."""
out = []
for boxes in gt:
d = [np.array(b, float) + rng.normal(0, jitter, 4) for _, b in boxes if rng.random() > p_miss]
for _ in range(rng.poisson(false_rate)):
x, y = rng.uniform(0, w - 18), rng.uniform(0, h - 10)
d.append(np.array([x, y, x + 18, y + 10]))
out.append(np.array(d).reshape(-1, 4))
return out
class KalmanBox:
"""Constant-velocity Kalman filter on the box centre; width and height as slowly varying states.
State x = [cx, cy, w, h, vx, vy]."""
def __init__(self, box, q=1.0, r=1.0):
cx, cy, w, h = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2, box[2] - box[0], box[3] - box[1]
self.x = np.array([cx, cy, w, h, 0.0, 0.0])
self.P = np.diag([r, r, r, r, 100.0, 100.0]) # velocity unknown at birth
self.F = np.eye(6); self.F[0, 4] = self.F[1, 5] = 1.0 # position += velocity (dt = 1 frame)
self.H = np.eye(4, 6) # we measure cx, cy, w, h
self.Q = np.diag([q, q, 0.1, 0.1, 0.1 * q, 0.1 * q]); self.R = r * np.eye(4)
def predict(self):
self.x = self.F @ self.x; self.P = self.F @ self.P @ self.F.T + self.Q
return self.box()
def update(self, box):
z = np.array([(box[0] + box[2]) / 2, (box[1] + box[3]) / 2, box[2] - box[0], box[3] - box[1]])
S = self.H @ self.P @ self.H.T + self.R
K = self.P @ self.H.T @ np.linalg.inv(S)
self.x = self.x + K @ (z - self.H @ self.x); self.P = (np.eye(6) - K @ self.H) @ self.P
def box(self):
cx, cy, w, h = self.x[:4]
return [cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2]
def sort_tracker(dets, iou_thr=0.3, max_age=3, min_hits=2, use_kalman=True):
"""SORT: predict every track, match predictions to detections by IoU with the Hungarian
algorithm, update matched tracks, start new tracks, delete tracks unseen for max_age frames.
Returns per frame a list of (track_id, box) for confirmed tracks updated in that frame."""
tracks, next_id, out = [], 1, []
for D in dets:
preds = [t["kf"].predict() if use_kalman else t["box"] for t in tracks]
matches, unmatched = [], set(range(len(D)))
if tracks and len(D):
cost = 1 - iou_matrix(preds, D)
for i, j in zip(*linear_sum_assignment(cost)):
if 1 - cost[i, j] >= iou_thr:
matches.append((i, j)); unmatched.discard(j)
matched_tracks = {i for i, _ in matches}
for i, j in matches:
t = tracks[i]; t["kf"].update(D[j]); t["box"] = list(D[j]); t["hits"] += 1; t["age"] = 0
for i, t in enumerate(tracks):
if i not in matched_tracks:
t["age"] += 1; t["hits"] = 0 # frames since the last match; the hit streak restarts
for j in sorted(unmatched):
tracks.append({"id": next_id, "kf": KalmanBox(D[j]), "box": list(D[j]), "hits": 1, "age": 0}); next_id += 1
tracks = [t for t in tracks if t["age"] <= max_age]
out.append([(t["id"], t["kf"].box() if use_kalman else t["box"]) for t in tracks
if t["age"] == 0 and t["hits"] >= min_hits])
return out
def mot_metrics(gt, hyp, thr=0.5):
"""CLEAR-MOT counts (FN, FP, ID switches, MOTA) and IDF1, from scratch."""
fn = fp = idsw = n_gt = 0
last = {} # gt id -> track id it was last matched to
pair_frames = {} # (gt id, track id) -> frames matched
for G, Hy in zip(gt, hyp):
n_gt += len(G)
if G and Hy:
iou = iou_matrix([b for _, b in G], [b for _, b in Hy])
rows, cols = linear_sum_assignment(-iou)
pairs = [(G[i][0], Hy[j][0]) for i, j in zip(rows, cols) if iou[i, j] >= thr]
else:
pairs = []
for g, h in pairs:
if g in last and last[g] != h:
idsw += 1
last[g] = h
pair_frames[(g, h)] = pair_frames.get((g, h), 0) + 1
fn += len(G) - len(pairs); fp += len(Hy) - len(pairs)
gids = sorted({g for G in gt for g, _ in G}); hids = sorted({h for Hy in hyp for h, _ in Hy})
M = np.zeros((len(gids), len(hids)))
for (g, h), n in pair_frames.items():
M[gids.index(g), hids.index(h)] = n
r, c = linear_sum_assignment(-M) if M.size else ([], [])
idtp = M[r, c].sum() if M.size else 0
n_hyp = sum(len(Hy) for Hy in hyp)
return {"FN": fn, "FP": fp, "IDSW": idsw, "MOTA": 1 - (fn + fp + idsw) / n_gt,
"IDF1": 2 * idtp / (n_gt + n_hyp), "tracks": len(hids)}
frames, gt = make_video(np.random.default_rng(0))
dets = noisy_detector(gt, np.random.default_rng(1))
print(f"{sum(len(g) for g in gt)} true boxes in 30 frames, {sum(len(d) for d in dets)} detections")
for name, kw in [("IoU tracker, no memory", dict(use_kalman=False, max_age=0, min_hits=1)),
("SORT (Kalman, max_age 3, min_hits 2)", dict())]:
m = mot_metrics(gt, sort_tracker(dets, **kw))
print(f"{name:37s} tracks {m['tracks']:2d} FN {m['FN']:2d} FP {m['FP']:2d} IDSW {m['IDSW']:2d} "
f"MOTA {m['MOTA']:.3f} IDF1 {m['IDF1']:.3f}")68 true boxes in 30 frames, 64 detections
IoU tracker, no memory tracks 20 FN 12 FP 8 IDSW 9 MOTA 0.574 IDF1 0.576
SORT (Kalman, max_age 3, min_hits 2) tracks 3 FN 24 FP 0 IDSW 0 MOTA 0.647 IDF1 0.786
The memoryless tracker reports 20 tracks for 3 vehicles: every missed detection ends a track and the next detection of the same vehicle starts a new one, which costs 9 identity switches, and every false alarm is reported (FP 8). SORT reports exactly 3 tracks with no switch and no false positive: the Kalman prediction carries a track over a missed frame (max_age 3), and min_hits 2 keeps one-frame false alarms out. IDF1 rises from 0.576 to 0.786. Its MOTA improves less (0.574 to 0.647) because SORT has more false negatives, 24 against 12: like the original SORT, it reports a track only in frames where it was matched, and after a miss it waits for two consecutive matches before reporting again. Whether to report coasting predictions is a design choice; Project 5 tunes these knobs and studies what happens when vehicles cross.
Beyond SORT
| Tracker | Adds to SORT | Helps with |
|---|---|---|
| DeepSORT (2017) | an appearance embedding per box (a small re-ID CNN), cosine distance combined with the Mahalanobis gate; matching cascade by track age | identity through occlusions and crossings |
| ByteTrack (2022) | a second association round with low-score detections for unmatched tracks | occluded objects whose detector score drops |
| OC-SORT, BoT-SORT (2022) | observation-centric re-updates, camera-motion compensation, re-ID features | non-linear motion, moving cameras |
| Joint detection and tracking (FairMOT, transformers) | one network outputs boxes and embeddings, or tracks directly | speed, end-to-end training |
The appearance embeddings of DeepSORT are the same idea as person re-identification: vectors that are close for the same object. Ultralytics wraps ByteTrack and BoT-SORT around its YOLO detectors. Its tracking API needs the lap package for the assignment, which is not installed in this course's image, so here it is shown without running:
# Not run here: Ultralytics' trackers need the "lap" package (pip install lap)
from ultralytics import YOLO
model = YOLO("yolo11n.pt")
for result in model.track(source="traffic.mp4", tracker="bytetrack.yaml", persist=True, conf=0.25, stream=True, verbose=False):
if result.boxes.id is not None:
for track_id, box, cls in zip(result.boxes.id.int().tolist(), result.boxes.xyxy.tolist(), result.boxes.cls.int().tolist()):
print(track_id, result.names[cls], [round(v) for v in box])
# bytetrack.yaml sets track_high_thresh, track_low_thresh, new_track_thresh, track_buffer (= max_age in frames), match_threshPitfalls
- Evaluating with the detector's mistakes hidden. A tracker can only be as good as its detections. Report the detector's precision and recall too, or test the tracker on the same detections as its competitors (benchmarks such as MOT17 provide public detections for exactly this reason).
- MOTA alone. It barely notices identity errors. Report IDF1 (or HOTA) and the IDSW count next to it.
max_ageand the frame rate.max_agecounts frames. At a lower frame rate the same occlusion lasts fewer frames, and objects move further per frame, so IoU association fails earlier. Retune after changing the sampling (video preparation).- Fragmentation versus switches. A track that ends and restarts with a new id on the same object (fragmentation) and a track that jumps to a different object (switch) are different errors with different fixes (memory versus appearance).
- Identity is personal data. A track of a person across cameras is a movement profile. Tracking people in public spaces needs a legal basis and often a data protection impact assessment; under the EU AI Act, real-time remote biometric identification in publicly accessible spaces for law enforcement is prohibited apart from narrow exceptions, and other remote biometric identification is high-risk. Prefer counting without storing identities, and read privacy, consent and licensing.
Practice
- A track's prediction has position variance 9 pixels squared, and the detector's measurement variance is 4. In one dimension, the Kalman gain is . Compute it and the updated variance, and say which source the filter trusts more.
Answer
, so the estimate moves 69 % of the way from the prediction towards the measurement: the measurement is trusted more because its variance is smaller. Updated variance , smaller than both 9 and 4: combining two uncertain estimates gives a better one.
- A sequence has 1,000 true boxes. A tracker has 120 FN, 80 FP and 15 identity switches. Compute MOTA. Then a second tracker has 100 FN, 70 FP and 60 switches: which has the better MOTA, and which would you expect to have the better IDF1?
Answer
Tracker 1: . Tracker 2: . Tracker 1 has the better MOTA by a little, but with a quarter of the switches it very likely has a clearly better IDF1, because every switch breaks a trajectory into pieces that IDF1 cannot all credit.
- Two pedestrians walk towards each other and cross. The detector sees both all the time. Why can SORT still swap their identities, and what does DeepSORT add?
Answer
At the crossing the two boxes overlap, so both predicted boxes have high IoU with both detections; the Kalman velocities help, but with noise the Hungarian assignment can pick the swapped pairing, and after that each track follows the wrong person. DeepSORT adds an appearance embedding per box: the cost combines motion and appearance distance, so two people in different clothes are not swapped even when their boxes overlap.
- In the SORT example, change
min_hitsto 1. What do you expect for FP and FN?
Answer
New tracks are reported from their first detection, so FN falls (no frame is lost waiting for the second match) but every false alarm is reported as a one-frame track, so FP rises towards the detector's false-alarm count. Run the example with dict(min_hits=1) to see the trade-off; Project 5 sweeps it.
Test yourself
What does the Kalman filter do in a tracker such as SORT?
- It detects the objects
- It predicts where each track's box will be in the next frame from its estimated velocity, and smooths the noisy detections; with no detection it keeps predicting
- It computes the IoU
- It removes false positives by itself
Why use the Hungarian algorithm rather than greedy matching to assign detections to tracks?
- It is faster
- It finds the one-to-one assignment with the best total cost, while greedy can take one good pair that leaves another track without a match
- It does not need IoU
- It handles more than two tracks only
A tracker never switches identities but misses many objects. Which metric shows the misses, and which shows that identities are kept?
- IDF1 shows misses, MOTA identities
- MOTA counts the misses (FN) heavily; IDF1 rewards keeping each object on its own track
- Both only count switches
- Neither
What does max_age control in SORT?
- The maximum speed of an object
- How many frames a track may go without a matched detection before it is deleted
- The minimum IoU for a match
- How old a video may be