Sub topic 2
Detections as the tracker's input
This chapter assumes you can read basic Python and NumPy, and that you know what an object detector and a bounding box are. Everything a tracking-by-detection system knows about the world arrives through the detector. This chapter covers what a detection contains, how its fields behave, and how to clean it up before the tracker uses it.
What a detection is
A detector processes one frame and returns a list of detections. Each detection usually has three parts:
- A bounding box, which is an axis-aligned rectangle around the object.
- A confidence score between 0 and 1, which is the detector's estimate that the box holds a real object of the predicted class.
- A class label, such as person, car, or bicycle.
The tracker does not see pixels, and it has no memory of earlier frames beyond its own tracks. Each frame it receives a fresh, unordered list. Nothing says which detection in frame 10 is the same object as which detection in frame 9. Establishing that link is the tracker's whole job.
Detections are also unlabeled with respect to identity. If the detector returns three people, the order of the three rows can change from frame to frame. Never rely on list position as an identity.
Box formats
Detectors disagree on how to write a box. Mixing formats is one of the most common bugs in a tracking pipeline, because the code still runs and the results are quietly wrong.
| Format | Fields | Typical source |
|---|---|---|
| xyxy | left, top, right, bottom | Many PyTorch detectors, the IoU code in this tutorial |
| xywh | left, top, width, height | MOTChallenge files, COCO annotations |
| cxcywh | center x, center y, width, height | YOLO-style outputs, Kalman filter state |
Some detectors also output normalized coordinates, where values lie between 0 and 1 relative to the image size. Multiply by the frame width and height before use.
Pick one internal format and convert at the boundary. This tutorial uses xyxy for matching and cxcywh for the Kalman filter state, so conversion helpers are worth writing once and testing.
The confidence score
The score is not a calibrated probability. A detector that outputs 0.9 does not mean the object is real nine times out of ten. Scores differ between models and even between training runs, so a threshold that works for one detector may not suit another.
The score matters to trackers in three ways:
- Thresholding. Detections below a threshold are discarded. A low threshold admits false positives, which spawn short-lived junk tracks. A high threshold drops true objects, which causes missed detections and fragmented tracks.
- Track initialization. Many trackers only start a new track from a high-confidence detection, since a new track is a commitment to a new identity.
- Association priority. Some trackers weight or order matches by score. ByteTrack, covered later in this tutorial, uses the score to split detections into a high group and a low group instead of discarding the low group.
A reasonable default is a threshold around 0.4 to 0.6 for a first experiment, then tuning on a validation sequence. Tune it together with the tracker's other parameters, because they interact.
How detector errors reach the tracker
The tracker cannot distinguish a detector mistake from a real scene change. It just sees boxes. The errors fall into a few types.
| Detector error | What the tracker sees | Typical consequence |
|---|---|---|
| Missed detection (false negative) | A track has no match for one or more frames | Track coasts on prediction, may be deleted, may get a new ID later |
| False positive | A box with no real object | A spurious new track, often short-lived |
| Duplicate boxes | Two overlapping boxes on one object | Two tracks for one object, or one track and one stray |
| Loose or jittery box | Box size and position vary frame to frame | Noisy IoU, unstable Kalman velocity estimates |
| Merged boxes | One box around two nearby objects | One track steals the match, the other goes unmatched |
| Wrong class | Same object flips between labels | Track loses its match if you filter by class |
Two of these deserve extra attention.
Duplicates. Detectors normally apply non-maximum suppression (NMS) internally, which removes boxes that overlap too much with a higher-scoring box. Its threshold is a trade-off. If it is too loose, duplicates survive. If it is too tight, two people standing close together get merged into one detection. In crowds, a tracker often performs better with a slightly looser detector NMS threshold, because a missing detection is harder to recover from than a duplicate.
Jitter. A box whose edges move a few pixels each frame is harmless for IoU matching, because overlap stays high. It hurts the motion model. The Kalman filter treats frame-to-frame position changes as evidence of velocity, so noisy boxes produce noisy velocity estimates. This is why the filter has a measurement noise parameter, which you will meet in a later chapter.
Preparing detections
Between the detector and the tracker sits a small cleaning step. It does four things: converts to one format, clips boxes to the frame, filters by class and score, and removes degenerate boxes. Order matters. Clip before measuring size, because a box that sticks far outside the frame may be tiny once clipped.
import numpy as np
def to_xyxy(boxes, fmt):
"""Convert an (N, 4) array of boxes in `fmt` to [x1, y1, x2, y2]."""
b = np.asarray(boxes, dtype=float).reshape(-1, 4)
if fmt == "xyxy":
return b.copy()
if fmt == "xywh": # top-left corner, width, height
return np.stack([b[:, 0], b[:, 1], b[:, 0] + b[:, 2], b[:, 1] + b[:, 3]], axis=1)
if fmt == "cxcywh": # center, width, height
return np.stack([b[:, 0] - b[:, 2] / 2, b[:, 1] - b[:, 3] / 2,
b[:, 0] + b[:, 2] / 2, b[:, 1] + b[:, 3] / 2], axis=1)
raise ValueError(f"unknown box format: {fmt}")
def prepare_detections(raw, fmt, frame_w, frame_h,
min_score=0.5, keep_classes=(0,), min_side=4.0):
"""raw is an (N, 6) array: four box values, score, class id.
Returns (boxes_xyxy, scores) for the detections the tracker should see."""
raw = np.asarray(raw, dtype=float).reshape(-1, 6)
boxes = to_xyxy(raw[:, :4], fmt)
scores = raw[:, 4]
classes = raw[:, 5].astype(int)
boxes[:, [0, 2]] = np.clip(boxes[:, [0, 2]], 0, frame_w)
boxes[:, [1, 3]] = np.clip(boxes[:, [1, 3]], 0, frame_h)
w = boxes[:, 2] - boxes[:, 0]
h = boxes[:, 3] - boxes[:, 1]
keep = (
(scores >= min_score)
& np.isin(classes, keep_classes)
& (w >= min_side)
& (h >= min_side)
)
return boxes[keep], scores[keep]
raw = [
[100, 50, 40, 80, 0.92, 0], # clear person
[102, 52, 40, 80, 0.60, 0], # near-duplicate with lower score
[300, 200, 30, 60, 0.35, 0], # low confidence, dropped
[610, 400, 60, 90, 0.88, 0], # sticks out of the frame, clipped
[10, 10, 3, 4, 0.95, 0], # too small, dropped
[200, 100, 50, 50, 0.90, 2], # wrong class, dropped
]
boxes, scores = prepare_detections(raw, "xywh", frame_w=640, frame_h=480)
print(boxes)
print(scores)Three detections survive. The near-duplicate in row two is still there, because this step does not run NMS. Detector-level NMS or a tracker-level rule has to handle it.
If you plan to use ByteTrack later, do not throw away the low-score detections here. Return both groups with two thresholds instead, for example a high threshold of 0.5 and a low threshold of 0.1.
Timing and frame rate
A detector gives a result per frame, but frames are not always evenly spaced in time.
- Dropped frames. If the detector cannot keep up, a real-time pipeline may skip frames. The tracker then sees a larger jump between observations. A constant-velocity motion model should be told the true time step instead of assuming one frame equals one unit.
- Frame skipping on purpose. Running the detector on every second or third frame saves compute. Objects move farther between observations, so IoU overlap between consecutive boxes drops. Fast objects and low frame rates are where IoU-only matching begins to fail.
- Detector latency. In a live system, the detection for frame t arrives some milliseconds after the frame was captured. If you display tracks on the newest frame, they lag slightly behind the objects.
Keep a timestamp with each detection list, and let the tracker compute its time step from it instead of counting frames.
Edge cases to handle
- Empty frames. A frame with zero detections is valid input. The tracker must still run its predict step and update miss counters. A common bug is returning early when the list is empty, which freezes all tracks.
- Truncated objects at the border. A person walking out of the frame produces a box that shrinks as it is clipped. The box center moves differently from the real body center, which can disturb velocity estimates.
- Zero-area boxes. After clipping, a box can have zero width or height. Dividing by its area in an IoU computation gives NaN or infinity unless you guard against it, as the IoU code in this tutorial does with a small floor on the union.
- Mixed classes. If you track people and cars together, decide whether a person box may match a car track. Most pipelines match only within a class, which means running association once per class or adding a large cost to cross-class pairs.
- Public detections versus your own. Benchmarks such as MOTChallenge sometimes supply a fixed set of detections, so every method sees the same input. When comparing trackers, check that they use the same detector. A better detector can improve scores more than a better tracker.
Exercise
Your tracker starts producing many short tracks that last two or three frames each, and the scene is a quiet street with few people. You are using a detector confidence threshold of 0.1. Name the most likely cause and one fix.
Show answer
The low threshold lets false positives through, and each one starts a new track that is deleted a few frames later. Raise the threshold to something like 0.4 to 0.6, or keep low-confidence boxes but only start new tracks from high-confidence ones. Tune the value on a validation sequence.
Exercise
A detector returns the box [320, 240, 60, 100] in cxcywh format. Convert it to xyxy and say what goes wrong if you pass the unconverted values to code expecting xyxy.
Show answer
In xyxy it is [290, 190, 350, 290], because x1 = 320 - 30, y1 = 240 - 50, x2 = 320 + 30, y2 = 240 + 50. Passed as is, the code reads it as x1=320, y1=240, x2=60, y2=100, a box with negative width and height. Intersections come out as zero or nonsense, so IoU is near zero and no detection matches any track.