Sub topic 4
The Tracking-by-Detection Pipeline
This chapter assumes you know what a detector outputs (boxes, class labels, confidence scores), can compute IoU between two boxes, and are comfortable with NumPy. Earlier chapters covered the tracking problem, detections as input, and IoU. Here you will see how those pieces fit into one per-frame loop. Later chapters cover the Hungarian algorithm, Kalman filters, and track lifecycles in detail.
The core idea
Tracking-by-detection splits multi-object tracking into two separate problems:
- Detection. A detector looks at one frame and returns boxes. It has no memory of earlier frames.
- Tracking. A tracker takes those boxes frame after frame and decides which box continues which trajectory.
The detector answers "what is in this frame?" The tracker answers "which of these is the same object as before?" The detector can be any model that outputs boxes, such as YOLO, Faster R-CNN, or DETR. The tracker only sees numbers: boxes, scores, and sometimes class labels.
This split has practical benefits. You can upgrade the detector without touching the tracker. You can train the detector on large image datasets that need no video labels. You can also debug each half separately.
It also has a cost. The tracker can only be as good as its detections. A missed detection leaves a gap in the trajectory, and a duplicate detection can create a second track for the same object.
The per-frame loop
Every online tracker in this family, including SORT, DeepSORT, and ByteTrack, runs the same loop on each frame. "Online" means the tracker uses only the current and past frames, never future ones.
The loop has six stages:
- Detect. Run the detector on frame t.
- Filter. Drop detections below a score threshold, and optionally apply non-maximum suppression (NMS) to remove duplicates.
- Predict. Move each existing track forward to where it should be in frame t.
- Associate. Compute a cost between every predicted track and every detection, then solve the assignment problem.
- Update. Matched tracks absorb their detection. Unmatched tracks accumulate a miss. Unmatched detections become new tracks.
- Prune and report. Delete tracks with too many misses and output the confirmed ones.
What each stage owns
| Stage | Question it answers | Typical implementation | Typical failure |
|---|---|---|---|
| Detect | Where are the objects in this frame? | Any box detector | Missed or duplicate boxes |
| Filter | Which boxes are trustworthy? | Score threshold, NMS | Threshold too high loses occluded objects |
| Predict | Where should each track be now? | Kalman filter, constant velocity | Wrong guess when an object turns or stops |
| Associate | Which detection is which track? | IoU or appearance cost, Hungarian algorithm | ID switch between nearby objects |
| Update | How do we correct the track? | Kalman update, replace box | Noisy boxes make trajectories jitter |
| Prune | When is a track really gone? | Max-miss counter | Deleted too early, ID lost on return |
Each stage has its own knobs, and they interact. Changing the score threshold in stage 2 changes how many unmatched detections reach stage 5, which changes how many tracks are born.
A minimal pipeline you can run
The code below is a small tracker with the whole loop in it. For readability it replaces the Kalman filter with a simple velocity estimate on the box. Chapter 6 replaces that with a proper Kalman filter. It needs only NumPy and SciPy.
import numpy as np
from scipy.optimize import linear_sum_assignment
def iou_matrix(boxes_a, boxes_b):
a = np.asarray(boxes_a, dtype=float).reshape(-1, 1, 4)
b = np.asarray(boxes_b, dtype=float).reshape(1, -1, 4)
x1 = np.maximum(a[..., 0], b[..., 0])
y1 = np.maximum(a[..., 1], b[..., 1])
x2 = np.minimum(a[..., 2], b[..., 2])
y2 = np.minimum(a[..., 3], b[..., 3])
inter = np.clip(x2 - x1, 0, None) * np.clip(y2 - y1, 0, None)
area_a = (a[..., 2] - a[..., 0]) * (a[..., 3] - a[..., 1])
area_b = (b[..., 2] - b[..., 0]) * (b[..., 3] - b[..., 1])
return inter / np.maximum(area_a + area_b - inter, 1e-9)
def associate(pred_boxes, det_boxes, iou_thresh):
if len(pred_boxes) == 0 or len(det_boxes) == 0:
return [], list(range(len(pred_boxes))), list(range(len(det_boxes)))
iou = iou_matrix(pred_boxes, det_boxes)
rows, cols = linear_sum_assignment(1.0 - iou)
matches = [(int(r), int(c)) for r, c in zip(rows, cols) if iou[r, c] >= iou_thresh]
mt = {r for r, _ in matches}
md = {c for _, c in matches}
return (matches,
[i for i in range(len(pred_boxes)) if i not in mt],
[j for j in range(len(det_boxes)) if j not in md])
class Track:
_next_id = 1
def __init__(self, box):
self.id = Track._next_id
Track._next_id += 1
self.last = np.asarray(box, dtype=float)
self.vel = np.zeros(4)
self.hits = 1
self.misses = 0
def predict(self):
# Extrapolate across any frames in which the track was not matched.
return self.last + self.vel * (self.misses + 1)
def update(self, box):
box = np.asarray(box, dtype=float)
step = (box - self.last) / (self.misses + 1)
self.vel = 0.5 * self.vel + 0.5 * step
self.last = box
self.hits += 1
self.misses = 0
class Tracker:
def __init__(self, det_thresh=0.5, iou_thresh=0.3, max_age=3, min_hits=2):
self.det_thresh = det_thresh
self.iou_thresh = iou_thresh
self.max_age = max_age
self.min_hits = min_hits
self.tracks = []
def update(self, detections):
"""detections: list of (box, score). Returns [(track_id, box), ...]."""
dets = [np.asarray(b, dtype=float) for b, s in detections if s >= self.det_thresh]
preds = [t.predict() for t in self.tracks]
matches, unmatched_t, unmatched_d = associate(preds, dets, self.iou_thresh)
for ti, di in matches:
self.tracks[ti].update(dets[di])
for ti in unmatched_t:
self.tracks[ti].misses += 1
for di in unmatched_d:
self.tracks.append(Track(dets[di]))
self.tracks = [t for t in self.tracks if t.misses <= self.max_age]
return [(t.id, t.last.tolist()) for t in self.tracks
if t.misses == 0 and t.hits >= self.min_hits]
frames = [
[([10, 10, 50, 50], 0.90), ([200, 200, 240, 240], 0.20)],
[([14, 10, 54, 50], 0.92)],
[],
[([22, 10, 62, 50], 0.88)],
[([26, 10, 66, 50], 0.91)],
]
tracker = Tracker()
for t, dets in enumerate(frames, start=1):
print(t, tracker.update(dets))Run it and check three things:
- Frame 1 prints an empty list. The low-score box is filtered out, and the first box has only one hit, so it is not yet confirmed.
- Frame 2 reports track 1, because it now has two hits.
- Frame 3 has no detections. The track survives with one miss and is not reported. In frame 4 it is matched again under the same ID, because its prediction was extrapolated across the gap.
Design decisions and edge cases
The score threshold
The threshold in stage 2 is the most influential parameter. A high value (0.6 or above) gives few false tracks but loses partially occluded objects, whose scores drop. A low value (0.1 to 0.3) keeps those objects but admits background clutter that spawns short, spurious tracks. ByteTrack, covered later, avoids this trade-off by using low-score boxes only to extend existing tracks.
Confirmation before output
The code reports a track only after min_hits matches. Without this, every false positive from the detector would appear as a one-frame track. The cost is a delay of min_hits - 1 frames before a real object gets an ID.
Prediction before association
Always predict first, then associate. If you compare detections with the previous frame's boxes, any fast-moving object has little overlap with its old position. This produces unmatched pairs and new IDs. At 30 fps a walking person moves a few pixels per frame, but a car or a low frame rate can move an object by more than its own width.
Frame rate and skipped frames
The velocity here is measured in pixels per frame. If you subsample a video, for example by processing every third frame, objects move three times as far between steps. Retune iou_thresh and max_age for the new rate, because max_age=3 now means 3 processed frames, not 3 video frames.
Detector errors propagate
The tracker cannot fix a wrong detection. It can only hide short gaps. Common cases:
- Split detections. One object is detected as two boxes. One wins the match and the other starts a new track.
- Merged detections. Two close objects become one box. One track is matched and the other coasts, then may drift onto the wrong object.
- Class flicker. A detector alternates between "car" and "truck". If you associate only within a class, the track breaks. Many trackers ignore class during matching and decide the label afterward.
Common errors
- Using the wrong box format.
iou_matrixexpects[x1, y1, x2, y2]. Many detectors output[x, y, width, height]or center format. IoU then comes out wrong, but without any error message. - Resetting IDs per frame. IDs must come from a counter that outlives the loop. A class-level counter, as above, or a single object that persists across frames, avoids this.
- Pruning inside the matching loop. Delete tracks only after updates and misses are applied. Removing during iteration shifts list indices and corrupts matches.
- Reporting coasting tracks. A track with
misses > 0has no current detection, so its box is a guess. Reporting it is a product decision. Make it deliberately.
Exercise
In the code above, a track is lost for two frames and then the object reappears. Why does the tracker still match it under the same ID, and which parameter would you change if the object could be hidden for ten frames?
Show answer
While unmatched, the track's miss counter rises but it stays in the list as long as misses <= maxage (3 by default). Its prediction is extrapolated using velocity times (misses + 1), so it should land near the object when it reappears, and IoU matching succeeds. For ten-frame gaps, raise maxage to at least 10. A larger max_age also keeps dead tracks alive longer, so they can steal detections and cause wrong matches, and the extrapolated box becomes less reliable the longer it runs.
Exercise
Your tracker produces many one- or two-frame tracks on a busy street, while real pedestrians keep their IDs. Name two changes in this pipeline that could reduce them, and the trade-off for each.
Show answer
Raise detthresh to filter low-confidence false positives (trade-off: occluded pedestrians with lower scores are dropped). Raise minhits so short tracks are never reported (trade-off: real objects get their ID later). Applying NMS or tightening detector duplicates is also valid.