Sub topic 12
Occlusion, ID Switches, and Camera Motion
This chapter assumes you have read the earlier chapters on IoU, the Hungarian algorithm, the Kalman filter, and the track lifecycle. You should be comfortable with the match() and step() functions from those chapters. Here we look at the three situations where a tracker built from those parts goes wrong, how to recognize each failure, and which fix to pick.
Why trackers fail where detectors don't
A detector looks at one frame. A tracker must stay consistent across many frames, so its errors build up. One missed detection can end a track. A wrong match gives an object another object's ID, and the tracker keeps using that ID in later frames.
Most failures come from three causes:
- Occlusion: an object is hidden, fully or partly, by another object or by scenery.
- Identity confusion: two tracks come close, and the assignment step picks the wrong pairing.
- Camera motion: the camera moves, so every box shifts even if the objects are still.
Occlusion
What happens inside the tracker
When a pedestrian walks behind a pole, the detector may stop reporting them for a few frames. The track then goes through these steps:
- The track has no matched detection, so its miss counter goes up.
- The Kalman filter keeps running its predict step and skips the update step. The track "coasts" along its last estimated velocity.
- Each predict step adds process noise
Qto the covarianceP. The position uncertainty grows, so a gated or Mahalanobis-based matcher accepts detections farther from the prediction. - If a detection appears near the prediction before
max_missesis reached, the track resumes with the same ID. - If the limit passes first, the track is deleted. The reappearing object then starts a new track with a new ID.
Partial occlusion
Partial occlusion is harder to notice. The detector still fires, but the box covers only the visible part. The box center moves, its size shrinks, and IoU with the track's predicted box drops. The Kalman filter then reads this box shift as real motion and corrupts its velocity estimate.
Tuning `max_misses`
| Setting | Benefit | Cost |
|---|---|---|
| Small (2 to 5 frames) | Few ghost tracks; low compute | Short occlusions cause ID changes |
| Large (30+ frames) | Survives longer occlusions | Constant-velocity prediction drifts; ghost tracks pollute matching |
A constant-velocity model is reasonable for a few frames. Over a long gap the prediction drifts away from the real path, because people stop, turn, and accelerate. This is why long-term recovery usually needs appearance features and not motion alone, as in DeepSORT.
ID switches
Definitions
An ID switch is counted when a ground-truth object is matched to a different tracker ID than it was matched to previously. A fragmentation is a ground-truth trajectory that is interrupted: it is tracked, then lost, then tracked again. A single event can produce both. The common patterns are:
- Swap: two objects cross paths, and their IDs exchange.
- Rebirth: an occluded object returns after its track was deleted and gets a new ID.
- Hijack: a track jumps to a nearby object when its own target disappears.
- Duplicate: a detector fires twice on one object, and the tracker briefly holds two tracks for it.
Why IoU-only matching swaps IDs
Two people walk toward each other. As they overlap, each track's box has high IoU with both detections. The Hungarian algorithm minimizes total cost, so a small difference in IoU can flip the pairing. After they separate, each track follows the wrong person. Both tracks look healthy, which makes this failure hard to catch without ground truth.
Motion helps here, because velocity predicts which side each person should emerge on. Appearance helps more, because clothing differs even when positions are identical.
Counting switches
The function below counts switches from a per-frame mapping of ground-truth IDs to tracker IDs. Frames where an object is unmatched simply do not contain its key, and the last known match is kept.
def count_id_switches(frames):
"""frames: list of dicts {ground_truth_id: tracker_id} for matched objects."""
last = {}
switches = 0
for frame in frames:
for gt_id, track_id in frame.items():
if gt_id in last and last[gt_id] != track_id:
switches += 1
last[gt_id] = track_id
return switches
frames = [
{1: 5, 2: 6},
{1: 5, 2: 6},
{2: 6}, # object 1 is occluded
{1: 9, 2: 6}, # object 1 returns with a new tracker ID
]
print(count_id_switches(frames)) # 1Note that this counts the reappearance under ID 9 as a switch even though no frame had a wrong match. This is the metric's behavior, and it matters when you compare trackers (see the evaluation chapter).
The transitions that matter are summarized in the state diagram below.
Camera motion
The problem
Every earlier chapter assumed the camera is fixed or that object motion dominates. With a handheld, drone, or vehicle-mounted camera, the whole image shifts between frames. The Kalman filter predicts where the object would be if the camera had not moved. The detection appears at a shifted location, IoU falls, and matches fail even though nothing is occluded. A fast pan can break every track in one frame, and the tracker then spawns a fresh set of IDs.
Camera motion compensation
The standard fix is camera motion compensation (CMC), also called global motion compensation. The steps are:
- Estimate the transform between the previous and current frame from the background. Common methods are sparse optical flow on corner features with RANSAC to reject moving objects, feature matching such as ORB, or ECC image alignment.
- Fit a 2×3 affine matrix (or a homography for large perspective change).
- Warp the predicted track boxes into the current frame's coordinates before computing IoU.
Trackers such as BoT-SORT include this step. It is cheap compared with the detector, but it fails when most of the frame is covered by moving objects, because the background estimate is then wrong.
The example shows the effect on IoU for a stationary object when the camera pans.
import numpy as np
def iou(a, b):
x1, y1 = max(a[0], b[0]), max(a[1], b[1])
x2, y2 = min(a[2], b[2]), min(a[3], b[3])
inter = max(x2 - x1, 0) * max(y2 - y1, 0)
area_a = (a[2] - a[0]) * (a[3] - a[1])
area_b = (b[2] - b[0]) * (b[3] - b[1])
return inter / (area_a + area_b - inter)
def warp_box(box, affine):
"""Apply a 2x3 affine transform to the two corners of a box."""
p1 = affine @ np.array([box[0], box[1], 1.0])
p2 = affine @ np.array([box[2], box[3], 1.0])
return np.concatenate([p1, p2])
# The camera pans: static scene content moves 12 px left and 3 px down.
A = np.array([[1.0, 0.0, -12.0],
[0.0, 1.0, 3.0]])
track_box = np.array([100.0, 100.0, 140.0, 180.0]) # position in previous frame
detection = np.array([88.0, 103.0, 128.0, 183.0]) # same object, current frame
print(round(iou(track_box, detection), 2)) # 0.51 without CMC
print(round(iou(warp_box(track_box, A), detection), 2)) # 1.0 with CMCA pure affine warp of two corners is exact for translation and scale. With rotation, the warped corners no longer form an axis-aligned box of the right size, so real implementations warp all four corners and take the bounding rectangle, or warp the Kalman state and covariance.
Choosing a mitigation
| Failure | Symptom in the output | Typical mitigation | Trade-off |
|---|---|---|---|
| Short occlusion | Track survives; IDs stable | Coasting with `max_misses` | Ghost tracks if limit too high |
| Long occlusion | Rebirth under a new ID | Appearance embeddings, long track memory | Extra compute; embeddings can fail for similar clothing |
| Crossing objects | Swapped IDs | Motion plus appearance cost; gating | Needs a trained re-ID model |
| Low-confidence detections during occlusion | Early deletion | Use low-score detections in a second matching pass (ByteTrack) | More false matches if the threshold is too low |
| Camera pan or shake | Many tracks lost at once | Camera motion compensation | Fails if the background estimate is poor |
| Duplicate detections | Two tracks per object | Non-maximum suppression; track merging | May merge close real objects |
Debugging workflow
When you see bad IDs, work through these checks in order:
- Plot per-frame detection counts. If detections vanish, the cause is the detector, and tuning the tracker will not help.
- Plot the mean IoU of matched pairs per frame. A sudden fall across all tracks points to camera motion.
- Inspect single trajectories around the failure. A track that ends and a new one that begins within a few pixels is a rebirth, and you can fix it by raising
max_missesor adding appearance. - If two tracks exchange positions, check whether the gate or cost uses only IoU.
Summary of key points
- Occlusion usually shows up as missed detections. The track coasts and either recovers or is deleted.
- Constant-velocity coasting is reliable for a few frames and unreliable for many.
- ID switches come from rebirth after deletion and from wrong assignments between close objects.
- Camera motion breaks IoU and velocity for all tracks at once, so correct it globally before matching.
- Each fix costs something: longer memory adds ghosts, appearance adds compute, and compensation depends on a good background estimate.
Exercise
A tracker on a fixed camera shows stable IDs for most people, but whenever two people cross paths, their IDs swap. Detection counts per frame are steady. Name the most likely cause and two changes you could try.
Show answer
The association cost uses only IoU (and possibly position), so at the crossing both tracks overlap both detections almost equally and the Hungarian solution can flip. Detection quality is fine, since the counts are steady, and there is no camera motion. Two changes: add an appearance embedding term to the cost (the DeepSORT approach) so clothing differences decide the match, and use the Kalman velocity to gate or weight matches so each track prefers the detection on its predicted side.
Exercise
A drone-mounted tracker loses almost every track in the frame where the drone yaws sharply, and new IDs appear for all objects. Mean matched IoU drops from about 0.8 to about 0.1 in that frame. Is this occlusion, and what should you add?
Show answer
It is not occlusion. All tracks fail at once and matched IoU collapses, which indicates global camera motion. Add camera motion compensation: estimate an affine or homography transform from background features between consecutive frames, and warp the predicted track boxes (and ideally the Kalman state) into the current frame before computing IoU.
Exercise
Using countidswitches, what does it return for frames = [{1: 3}, {1: 3}, {1: 4}, {1: 3}]?
Show answer
It returns 2. Object 1 changes from tracker ID 3 to 4 (one switch), then from 4 back to 3 (a second switch).