A car's sensors report dots, not names. A tracker must say which dot is which object, ten times a second. Pick the wrong rule and two names swap the moment two paths cross.
Watch the car and the cyclist cross. Switch the rule from nearest neighbour to global nearest neighbour, and see whether the names on the trails stay put. Then raise the noise and the clutter until even the better rule breaks. Then we build the whole tracker, piece by piece.
You need a Kalman filter, met once (Chapter 1 re-teaches it) and 2D vectors. We build the rest from zero.
Press Replay to run the crossing.
Toy scene: a 60 m by 30 m patch of road, 10 frames a second, each object detected 92% of the time, seeded noise. Every rule sees exactly the same detections, so any difference comes from the rule. The default draw is one where greedy swaps. Over 300 seeded runs at these settings, greedy averages 0.51 identity switches a run, JPDA 0.27 and global nearest neighbour 0.13. GNN does not make swaps impossible: raise the noise and it swaps too.
Chapter 0
See how two paths that cross make a tracker lose track of who is who
A car waits at a junction. Ahead, another car drifts left to pass a cyclist, and the cyclist drifts right. A pedestrian waits at the kerb. Your car's camera and radar see all three.
Ten times a second, the perception model hands your software a short list of dots. Each dot is a detection: one measured position, from one sensor, at one moment. The list has no names on it. It does not say "this dot is the cyclist". The order of the list means nothing.
Yet everything downstream needs names. The planner asks "is the cyclist speeding up?" The braking function asks "how fast is that car closing on us?" Both questions need the same object followed across many frames. A track is that: the software's running estimate of one object, with an identity that lasts.
So the job splits in two. Keep a good estimate of each object. And, every frame, decide which detection belongs to which track. The second job is called data association, and it is where trackers break.
Two objects cross. Each frame shows two unnamed detections. The simple rule gives each track the detection nearest to it. Step through the frames, then reveal the truth and count the frames where the rule got the names wrong.
Toy: two objects on straight lines, the closest approach about 0.8 m, seeded Gaussian noise. "Predicted" moves each track by its last step before it looks for the nearest detection.
Try it with the noise at 0.45 m. Close to the crossing, the two detections land a metre or less apart. Noise of about half a metre is enough to put the cyclist's detection nearer to the car's track. Then the car's track takes it, and the names swap.
How likely is that? Work it on one axis. Two objects sit 1.0 m apart. Each detection has noise with a standard deviation of 0.6 m. The rule goes wrong when the two detections land in the wrong order. The difference of two such noises has a standard deviation of 0.6 × √2 = 0.85 m. So a swap needs that difference to exceed 1.0 m, which is 1.0 / 0.85 = 1.18 standard deviations.
P(swap in one frame) = P(Z > 1.18) = 0.12 · over 10 close frames: 1 − 0.8810 = 0.72
A 12% chance per frame looks small. But a crossing lasts many frames, and one wrong frame is enough. Over ten close frames, a swap is more likely than not. Now add a third object, false detections from rain, and frames where a detection is simply missing. The problem gets much harder.
Here is the same number in Python, worked two ways: by the formula and by brute simulation.
import math, random def swap_prob_formula(sep, sigma): """Two objects sep metres apart on one axis, each detection with noise sigma. A nearest-match rule swaps the names when the detections land in the wrong order.""" z = sep / (sigma * math.sqrt(2)) # the difference of two noises has sd sigma * sqrt(2) return 0.5 * math.erfc(z / math.sqrt(2)) # P(Z > z) for a standard normal Z def swap_prob_sim(sep, sigma, trials=200_000, seed=1): rng = random.Random(seed) wrong = 0 for _ in range(trials): a = 0.0 + rng.gauss(0, sigma) # detection of object A, which sits at 0 b = sep + rng.gauss(0, sigma) # detection of object B, which sits at sep wrong += a > b # order flipped: the names swap return wrong / trials p = swap_prob_formula(1.0, 0.6) print(round(p, 3), round(swap_prob_sim(1.0, 0.6), 3)) # 0.119 and about 0.12 print(round(1 - (1 - p) ** 10, 2)) # 0.72 over ten close frames
Notice one thing the device teaches already. The rule that uses velocity does better. If you know where each object is going, you know where to look for it next. That is the Kalman filter's job, and Chapter 1 starts there.
This matters most in the software that sits beside a learned perception model in a car or a robot. A perception onboard software lead at a robotics or vehicle company owns that layer. It must run on time every cycle, with fixed memory, and it must keep the names straight. Here is the road.
Chapter 1
Rebuild the Kalman filter in five lines and meet the number that drives every later chapter
Forget the crowd for a moment. Follow one cyclist. Each frame, you get one noisy detection of where she is. You want a smooth estimate of her position and her velocity, and an honest number for how sure you are.
The Kalman filter does this in two moves. First it predicts: it pushes the last estimate forward in time with a motion model. Then it corrects: it nudges the prediction toward the new detection. How far it nudges depends on which of the two it trusts more.
The filter keeps two things. The state x is the estimate: here position and velocity, [px, py, vx, vy]. The covariance P is the uncertainty of that estimate, as a matrix. Its diagonal holds the variance of each part; the rest says how the errors move together.
If the cyclist keeps her velocity for one frame of length Δt, her new position is the old one plus velocity times Δt. That is the constant velocity model. A matrix F writes it once for all four numbers. The uncertainty grows, because the model is never exact.
Now the detection z arrives. The filter compares it with where it expected to see it. The difference is the innovation ν: the part of the detection that the prediction did not explain. H picks out the position from the state, because the sensor measures position only.
S is the star of this lesson. It adds two uncertainties: where the track might be (H P⁻ HT) and how noisy the sensor is (R). If the filter is honest, real innovations should usually be about the size S says. An innovation far bigger than S predicts is a warning: this detection probably came from something else.
Those are the five lines: predict x, predict P, form ν and S, compute K, correct x and P. Everything else in this lesson wraps around them.
The warm ellipse is where the filter expects the cyclist. Press Step to move through one frame in three parts: predict, see the detection, correct. The dashed ellipse is S, the size of innovation the filter expects.
A real constant-velocity Kalman filter, with one frame every 0.3 s so each move is easy to see. The cyclist rides a gentle curve that the model does not know about. Ellipses are drawn at one standard deviation.
Take one axis to keep the arithmetic short. The predicted position is p⁻ = 10.5 m with variance P⁻ = 0.16 m² (a standard deviation of 0.4 m). The sensor noise is R = 0.36 m² (0.6 m). The detection says z = 11.1 m.
ν = 11.1 − 10.5 = 0.6 m · S = 0.16 + 0.36 = 0.52 m², so √S = 0.72 m
K = 0.16 / 0.52 = 0.31 · p = 10.5 + 0.31 × 0.6 = 10.68 m · P = (1 − 0.31) × 0.16 = 0.11 m²
Read the middle number twice. The innovation is 0.6 m and S says to expect about 0.72 m. So this detection is 0.6 / 0.72 = 0.83 standard deviations from the prediction. That is ordinary. If it had been 3 m away, it would be 4.2 standard deviations: almost certainly not this cyclist. Chapter 2 turns that idea into a test.
Here are the five lines in C++, written the way onboard code often is: fixed-size arrays, no heap, and a closed-form 2 by 2 inverse. The state is 4 numbers and the detection is 2, so every size is known at compile time.
// One constant-velocity track: state [px, py, vx, vy], detection [px, py]. // Fixed sizes, no heap: this runs every cycle for every track. struct Track { float x[4]; float P[4][4]; }; void predict(Track& t, float dt, float q) { t.x[0] += dt * t.x[2]; t.x[1] += dt * t.x[3]; // x- = F x float (&P)[4][4] = t.P; for (int i = 0; i < 4; ++i) { P[i][0] += dt * P[i][2]; P[i][1] += dt * P[i][3]; } // F P for (int j = 0; j < 4; ++j) { P[0][j] += dt * P[2][j]; P[1][j] += dt * P[3][j]; } // (F P) F^T const float a = q*dt*dt*dt/3, b = q*dt*dt/2, c = q*dt; // white-acceleration Q P[0][0] += a; P[1][1] += a; P[2][2] += c; P[3][3] += c; P[0][2] += b; P[2][0] += b; P[1][3] += b; P[3][1] += b; } // Innovation covariance S = H P H^T + R, and its inverse (2 by 2, closed form). struct Innov { float S[2][2], Si[2][2], det; }; Innov innovation(const Track& t, float r2) { Innov n; n.S[0][0] = t.P[0][0] + r2; n.S[0][1] = t.P[0][1]; n.S[1][0] = t.P[1][0]; n.S[1][1] = t.P[1][1] + r2; n.det = n.S[0][0]*n.S[1][1] - n.S[0][1]*n.S[1][0]; n.Si[0][0] = n.S[1][1]/n.det; n.Si[0][1] = -n.S[0][1]/n.det; n.Si[1][0] = -n.S[1][0]/n.det; n.Si[1][1] = n.S[0][0]/n.det; return n; } void correct(Track& t, const Innov& n, float zx, float zy) { const float v0 = zx - t.x[0], v1 = zy - t.x[1]; // innovation float K[4][2]; // K = P H^T S^-1 for (int i = 0; i < 4; ++i) { K[i][0] = t.P[i][0]*n.Si[0][0] + t.P[i][1]*n.Si[1][0]; K[i][1] = t.P[i][0]*n.Si[0][1] + t.P[i][1]*n.Si[1][1]; } for (int i = 0; i < 4; ++i) t.x[i] += K[i][0]*v0 + K[i][1]*v1; float HP[2][4]; // P = P - K (H P) for (int j = 0; j < 4; ++j) { HP[0][j] = t.P[0][j]; HP[1][j] = t.P[1][j]; } for (int i = 0; i < 4; ++i) for (int j = 0; j < 4; ++j) t.P[i][j] -= K[i][0]*HP[0][j] + K[i][1]*HP[1][j]; }
Failure mode: a filter that is too sure of itself. Set the process noise q very low in the device. The ellipse shrinks to a dot, the gain falls, and the track lags the curve. Its innovations grow far beyond S. In a multi-target tracker this is worse than lag: Chapter 2's gate is built from S, so the track starts to reject its own object.
How to diagnose it: log the normalised innovation squared (NIS), νT S−1 ν, for every accepted detection. For a 2D detection its long-run average should be close to 2. An average of 8 says S is far too small. The EKF lesson covers the same filter when the motion or the sensor is curved.
Chapter 2
Measure distance in standard deviations, then draw a gate that keeps the right detection 99% of the time
A car drives along the road at an uncertain speed. You know its lane well, but you are not sure how far along the lane it has got. Two detections arrive, each about 3 m from the prediction. One lies ahead along the lane. The other lies across it, on the pavement. Which is more likely to be the car?
The one along the lane, clearly. The track's uncertainty is long and thin, stretched along the direction of travel. A 3 m error along the lane is ordinary; a 3 m error sideways is not. Plain distance in metres misses this. We need a distance that counts in standard deviations, in the right direction.
In one dimension the answer is easy: divide the innovation by its standard deviation. In Chapter 1, 0.6 m against √S = 0.72 m gave 0.83 standard deviations. Square it and you get ν²/S. The 2D version does the same with the matrix S.
Why this form? Picture S as an ellipse. S−1 squashes and rotates space until that ellipse becomes a circle of radius 1. In the squashed space, ordinary distance is the count of standard deviations. So d² is just the squared length of the innovation, measured after you make the uncertainty round.
The warm dot is the predicted position of a car driving right. The warm ellipse is its gate. Drag the three detections A, B and C. Each shows its distance in metres and its d². Turn on the circle to compare with a plain distance gate.
S = diag(u², 1 m²): u along the road from the slider, 1 m across it. The gate is the set of points with d² ≤ γ. A real S is usually tilted; the maths is the same.
Let S = [[4, 0], [0, 1]] m²: a standard deviation of 2 m along the road (x) and 1 m across it (y). Then S−1 = [[1/4, 0], [0, 1]], and d² = νx²/4 + νy².
A and C are both about 3 m away. Yet A scores 2.50 and C scores 10.24. A sits along the uncertain direction, so it is easy to explain. C sits across the road, where the track is sure, so it is hard to explain. B, the nearest in metres, lands in between.
A gate is a threshold γ on d². A detection with d² ≤ γ is in the gate: it could belong to this track. Everything outside is ruled out for this track. How should we pick γ?
Suppose the detection truly came from this track and the filter is honest. Then ν is Gaussian with covariance S. After S−1 makes it round, its two parts are independent standard normals, and d² is the sum of their squares. A sum of k squared standard normals has a chi-square distribution with k degrees of freedom. Here k = 2.
For k = 2 the chi-square has a neat closed form. The chance that d² stays inside γ is:
PG = 0.99: γ = −2 ln(0.01) = 2 × 4.605 = 9.21 · 0.95: 5.99 · 0.999: 13.82
So with a 99% gate, A (2.50) and B (6.25) pass and C (10.24) fails. With a 95% gate, B fails too. With a 3D detection (say x, y and range rate) you would use 3 degrees of freedom and a chi-square table; the idea is the same.
One more number for later. The gate is an ellipse with area V = π γ √det S. For this S and a 99% gate, V = π × 9.21 × √4 = 57.9 m². Chapter 5 counts how many false detections land in that area.
Gating is cheap and it does two jobs. It throws out impossible pairs before the expensive assignment step. And it splits a crowded scene into small independent groups, which Chapter 10 uses to bound the run time. Here is the test in C++, plus the threshold in Python.
// Gate test for one track against every detection this frame. // Uses the Innov struct from Chapter 1 (S and its inverse Si). constexpr int kMaxDets = 128; constexpr float kGate99 = 9.21f; // chi-square, 2 degrees of freedom, P_G = 0.99 struct Det { float x, y; }; // Writes d2 for every detection; returns how many fall inside the gate. int gate(const Track& t, const Innov& n, const Det* dets, int nDets, float* d2Out, bool* inGate) { int count = 0; for (int k = 0; k < nDets; ++k) { // fixed order: same input, same output const float a = dets[k].x - t.x[0]; const float b = dets[k].y - t.x[1]; const float d2 = a * (n.Si[0][0]*a + n.Si[0][1]*b) + b * (n.Si[1][0]*a + n.Si[1][1]*b); d2Out[k] = d2; inGate[k] = d2 <= kGate99; count += inGate[k]; } return count; }
import math def chi2_gate_2d(p_gate): """Threshold on d^2 for a 2D detection: P(d^2 <= g) = 1 - exp(-g/2).""" return -2.0 * math.log(1.0 - p_gate) def mahalanobis2(nu, S): (a, b), ((s00, s01), (s10, s11)) = nu, S det = s00 * s11 - s01 * s10 inv = ((s11 / det, -s01 / det), (-s10 / det, s00 / det)) return a * (inv[0][0] * a + inv[0][1] * b) + b * (inv[1][0] * a + inv[1][1] * b) S = ((4.0, 0.0), (0.0, 1.0)) for name, nu in [("A", (3.0, 0.5)), ("B", (0.0, 2.5)), ("C", (0.0, 3.2))]: d2 = mahalanobis2(nu, S) print(name, round(d2, 2), "in" if d2 <= chi2_gate_2d(0.99) else "out") # A 2.5 in / B 6.25 in / C 10.24 out print(round(chi2_gate_2d(0.99), 2), round(math.pi * chi2_gate_2d(0.99) * 2.0, 1)) # 9.21, 57.9 m^2
Failure mode: a gate built on a wrong S. If S is too small (an overconfident filter), the track's own detection falls outside during a turn. The track coasts, a new track is born on the same object, and the identity changes. If S is too big, clutter walks in. Both look like "bad association" in a log, yet the cause is the filter.
How to diagnose it: histogram d² of the detections the tracker accepted. For an honest filter it should look like a chi-square with 2 degrees of freedom: mean about 2, about 1% above 9.21. A pile-up just under the gate means the gate is clipping real detections.
Chapter 3
Pair tracks with detections so the total cost is smallest, and see why the greedy shortcut fails
Gating leaves a smaller question, but still a real one. Near the crossing, the car's gate holds two detections and so does the cyclist's. Each detection can feed at most one track. Each track takes at most one detection. Which pairing is right?
Write the question as a table. Rows are tracks, columns are detections, and each cell holds a cost: how unlikely that pairing is. This table is the cost matrix. Pairing tracks with detections, one to one, so the total cost is smallest, is the assignment problem.
The natural cost is the negative log of the likelihood that this detection came from this track. For a Gaussian innovation that is, up to a constant:
Why the log term? A brand new track has a huge S. Every detection looks close to it in d², because its ellipse is enormous. Without a penalty, that vague track would steal detections from steady tracks nearby. The ln det S term is the price of vagueness. Pairs outside the gate get an infinite cost: they are not allowed.
The obvious rule is greedy assignment: take the cheapest cell, lock that pair, cross out its row and column, and repeat. It is fast and easy to code. It is also wrong in a way that matters exactly at crossings. Here is the smallest case.
Greedy grabbed the single best cell and forced T2 into a terrible pairing. The optimal answer gives up a little on T1 to save a lot on T2. At a crossing, "a little worse for one track, much better for the other" is exactly the trade that keeps both names right.
Rows are tracks, columns are detections. Tap a cell to raise its cost by 1. Pick a method; for the Hungarian method press Step to walk it one move at a time. Warm rings mark the chosen pairs.
Costs are whole numbers to keep the arithmetic readable. The Hungarian steps shown are the classic textbook form: reduce rows, reduce columns, cover zeros, adjust. Production code uses a faster form of the same method.
Trying every pairing works for 3 tracks (3! = 6 pairings) and dies quickly after that: 10 tracks have 3,628,800. The Hungarian method (Kuhn, 1955) finds the optimal pairing in time that grows like n³. Its key fact is simple. Subtracting a constant from a whole row or column does not change which pairing is best. Every pairing uses exactly one cell from each row and each column, so every total drops by the same amount.
So we subtract until zeros appear, and look for a full set of zeros, one per row and column. Take this matrix of costs (d² values, rounded).
Hungarian: T1-D2 + T2-D1 + T3-D3 = 1 + 2 + 2 = 5 · greedy: T2-D2 (0), T3-D3 (2), T1-D1 (4) = 6
Check it by brute force: the six pairings cost 6, 11, 5, 9, 7 and 6. The minimum is 5. Greedy took the free-looking zero at T2-D2 and paid for it later.
Real matrices are not square, and not every track should get a detection. A track's object may be hidden; a detection may be clutter or a new object. The standard fix is to augment the matrix with dummy rows and columns.
Giving track i its "miss" column costs c_miss; giving detection j its "new" row costs c_new. A real pair is chosen only when cij < c_miss + c_new. Set c_miss from the gate (γ plus track i's ln det S). Then a pair inside the gate is always worth taking, unless it blocks a better pair. The matrix is (n + m) square, so the Hungarian method still applies.
Run the optimal assignment every frame and you have global nearest neighbour (GNN). It is global because it optimises all pairs together, and nearest because it still commits to one best answer. The hero's second rule is exactly this. SORT, a well-known tracker for camera boxes, uses the same structure with box overlap as the cost.
Here is the Hungarian method in its compact potentials form, written for onboard use: fixed maximum size, no heap, deterministic tie-breaks by index. It is the same algorithm the hero runs in your browser.
// Optimal assignment, O(n^3), Hungarian method in its potentials form. // a is n x m with n <= m (pad with dummy rows/columns first). 1-based inside. constexpr int kN = 256; // fixed capacity: bounded memory, bounded time constexpr float kInf = 1e30f; // rowToCol[i] receives the column given to row i (0-based). void hungarian(const float a[kN][kN], int n, int m, int rowToCol[kN]) { static float u[kN + 1], v[kN + 1], minv[kN + 1]; // static: no allocation per call static int p[kN + 1], way[kN + 1]; static bool used[kN + 1]; for (int j = 0; j <= m; ++j) { v[j] = 0; p[j] = 0; } for (int i = 0; i <= n; ++i) u[i] = 0; for (int i = 1; i <= n; ++i) { p[0] = i; int j0 = 0; for (int j = 0; j <= m; ++j) { minv[j] = kInf; used[j] = false; } do { // grow a shortest augmenting path used[j0] = true; const int i0 = p[j0]; float delta = kInf; int j1 = 0; for (int j = 1; j <= m; ++j) if (!used[j]) { const float cur = a[i0 - 1][j - 1] - u[i0] - v[j]; // reduced cost if (cur < minv[j]) { minv[j] = cur; way[j] = j0; } if (minv[j] < delta) { delta = minv[j]; j1 = j; } // ties: lowest j wins } for (int j = 0; j <= m; ++j) if (used[j]) { u[p[j]] += delta; v[j] -= delta; } else minv[j] -= delta; j0 = j1; } while (p[j0] != 0); do { const int j1 = way[j0]; p[j0] = p[j1]; j0 = j1; } while (j0); // flip the path } for (int i = 0; i < n; ++i) rowToCol[i] = -1; for (int j = 1; j <= m; ++j) if (p[j]) rowToCol[p[j] - 1] = j - 1; }
Failure mode: costs on different scales. A team adds an appearance score (0 to 1) to a d² (0 to 9.21) with no weight. The d² term drowns the appearance term, or the reverse, and swaps rise after the "improvement". Another classic: a tie-break that depends on hash-map order, so the same log replays to a different answer.
How to diagnose it: replay one crossing from a log and print the full cost matrix for the frame where the identity changed. Check each term's range. Then replay it twice and diff the outputs: any difference means non-deterministic iteration somewhere.
Chapter 4
Decide when a run of detections becomes a track, and when a silent track should die
A pedestrian steps out from behind a parked van. On the first frame there is one detection with no track near it. Is it a person, or a puff of spray that the radar mistook for one? Start a full track at once and every puff of spray becomes a phantom pedestrian. Wait too long and you brake late.
Later, a bus passes between you and the pedestrian. For a second there are no detections of her. Delete her track at once and she comes back with a new name. Keep it forever and a ghost walks on after she has gone.
A tracker handles both with a small state machine: a fixed set of states and rules for moving between them. Most trackers use four states.
Press Hit or Miss to feed the track one frame. The row of boxes is the frame history; the dashed frame marks the last N. Or let a real object (detected 90% of the time) or a clutter point (5% of the time) feed it, and watch which one confirms.
The 90% and 5% are illustrative. A real detection probability depends on range, weather and occlusion; a clutter rate depends on the sensor and the gate size.
The usual rule is M-of-N logic: confirm a tentative track when it has at least M hits in its last N frames. A hit means some detection was assigned to the track this frame; a miss means none was. Real objects hit often. Clutter is scattered at random, so it rarely lands in the same small gate twice in a row.
Work 2 of 3. Let a real object be detected with probability pD = 0.9 each frame. Let a clutter point land in a given gate with probability 0.05 each frame. The chance of at least 2 hits in 3 frames is "exactly 2" plus "all 3":
real, p = 0.9: 3 × 0.81 × 0.1 + 0.729 = 0.972 · clutter, p = 0.05: 3 × 0.0025 × 0.95 + 0.000125 = 0.0073
So 2 of 3 confirms a real object 97% of the time and a clutter seed less than 1% of the time. Move to 3 of 4 and clutter drops to 0.00048, while the real object drops to 0.948. Every step toward strictness buys fewer false tracks and pays in two ways: more missed objects, and a later confirmation. At 10 frames a second, 3 of 4 means a track can appear no earlier than 300 ms after the first detection.
A confirmed track that misses K frames in a row is deleted. The chance that a real object detected 90% of the time misses 3 in a row is 0.1³ = 0.001 per window. That sounds rare, but a car tracks dozens of objects for hours. And occlusion is not random: a bus hides a person for many frames in a row. So K is a trade between keeping names through occlusions and killing ghosts fast.
That last point leads to a practical rule the hero uses. Associate confirmed tracks first, then give the leftover detections to tentative tracks. Otherwise a vague tentative track born from a stray detection can steal detections from a confirmed neighbour. DeepSORT, a camera tracker, takes this further with a matching cascade that serves recently seen tracks first.
In C++ the whole history fits in one byte. Shift in a 1 for a hit and a 0 for a miss, then count the bits.
#include <cstdint> #include <bit> // std::popcount, C++20 enum class TrackState : uint8_t { Tentative, Confirmed, Coasting, Deleted }; struct Life { TrackState state = TrackState::Tentative; uint8_t hist = 1; // bit 0 = this frame; born on a hit uint8_t age = 1; // frames since birth (saturates) uint8_t misses = 0; // consecutive misses }; struct LifeParams { int M = 2, N = 3, deleteAfter = 3; }; void stepLife(Life& L, bool hit, const LifeParams& p) { L.hist = static_cast<uint8_t>((L.hist << 1) | (hit ? 1u : 0u)); L.age = L.age < 255 ? L.age + 1 : 255; L.misses = hit ? 0 : static_cast<uint8_t>(L.misses + 1); const unsigned window = (1u << p.N) - 1u; // the last N frames const int hits = std::popcount(static_cast<unsigned>(L.hist) & window); switch (L.state) { case TrackState::Tentative: if (hits >= p.M) L.state = TrackState::Confirmed; else if (L.age >= p.N) L.state = TrackState::Deleted; // cannot reach M any more break; case TrackState::Confirmed: case TrackState::Coasting: if (L.misses >= p.deleteAfter) L.state = TrackState::Deleted; else L.state = hit ? TrackState::Confirmed : TrackState::Coasting; break; case TrackState::Deleted: break; } }
Failure mode: ghost tracks in rain, or late tracks for a child. One team tunes confirmation on dry-weather logs and ships 2 of 3. In heavy rain, spray makes clusters of false detections that repeat for a few frames, and phantom objects appear. Another team chooses 4 of 6 to stop that, and now a child who steps out is confirmed 400 ms late.
How to diagnose it: count false tracks per hour and confirmation latency, split by weather and by object class. If the numbers move together when you change M and N, you are on the trade curve. If false tracks come in bursts at one place, the cause is a sensor artefact, and the fix belongs upstream.
Chapter 5
Count how many false detections land in a gate, and see why a hard choice must sometimes be wrong
Drive into heavy rain. The radar sees spray thrown up by the truck ahead. A guard rail reflects radar energy and returns a phantom car. The camera model fires on a puddle that mirrors a headlight. Meanwhile, the real cyclist ahead is missed on one frame in ten, because the rain hides her.
Two numbers describe this. The probability of detection pD is the chance that a real object yields a detection on a given frame. The clutter density λ is how many false detections appear per square metre per frame. Rain, multipath and reflections raise λ. Range, occlusion and darkness lower pD.
If false detections fall at random with density λ, the expected number inside a gate is λ times the gate's area. From Chapter 2, the area is V = π γ √det S.
The second formula assumes false detections are scattered independently, so their count in the gate is a Poisson count with mean λV. That is the usual model; real clutter is often clumpier.
Take the hero's road: 60 m by 30 m, 1,800 m². A steady track has S = diag(0.5, 0.5) m², so √det S = 0.5 and V = π × 9.21 × 0.5 = 14.5 m².
The third line is the trap. A track that coasts for a few frames grows a big S, so its gate swells. In rain, a swollen gate almost always holds some false detection. Hard association will take it, because "a detection in the gate" always beats "no detection" under a GNN cost.
One track and its gate. Each frame brings the object's detection (when it is not missed) and some clutter. The nearest detection in d² is circled. Press Run 200 frames and read how often the pick was wrong.
Monte Carlo with Poisson clutter, uniform over the area, and Gaussian detection noise matched to S. The object's own detection is drawn from the track's S, so the filter here is honest by construction.
With the default rain and a coasting track, the pick is wrong often. Notice where the wrong picks come from. Some frames miss the object (10% at pD 0.9); then any clutter point in the gate wins. Other frames have the object, yet a clutter point lands closer in d². Both are invisible to a hard rule. It always picks something, and it never says how unsure it was.
Here is the Monte Carlo in Python. It checks the λV formula and measures how often nearest-neighbour picks clutter, for the three cases above.
import math, random def wrong_pick_rate(lam, S_diag, pd, gate=9.21, frames=100_000, seed=0): rng = random.Random(seed) sx, sy = math.sqrt(S_diag[0]), math.sqrt(S_diag[1]) rx, ry = sx * math.sqrt(gate), sy * math.sqrt(gate) # gate ellipse half-axes box = 4 * rx * ry # sample clutter in a box around it in_gate_total, wrong = 0, 0 for _ in range(frames): cands = [] # (d2, is_clutter) if rng.random() < pd: x, y = rng.gauss(0, sx), rng.gauss(0, sy) cands.append((x * x / S_diag[0] + y * y / S_diag[1], False)) n = 0; L = math.exp(-lam * box); p = rng.random() # Poisson count in the box while p > L: n += 1; p *= rng.random() for _ in range(n): x, y = rng.uniform(-rx, rx), rng.uniform(-ry, ry) d2 = x * x / S_diag[0] + y * y / S_diag[1] if d2 <= gate: cands.append((d2, True)); in_gate_total += 1 cands = [c for c in cands if c[0] <= gate] if cands and min(cands)[1]: wrong += 1 # nearest in d2 is clutter return in_gate_total / frames, wrong / frames for name, lam, S in [("dry", 1.5/1800, (0.5, 0.5)), ("rain", 30/1800, (0.5, 0.5)), ("rain, coasting", 30/1800, (4, 4))]: mean_in_gate, wrong = wrong_pick_rate(lam, S, pd=0.9) print(f"{name:15s} clutter in gate {mean_in_gate:.3f} wrong pick {wrong:.1%}")
It prints clutter counts of 0.013, 0.24 and 1.91 per gate, matching λV. The wrong-pick rates are about 0.4% dry, 7% in rain, and 35% in rain for a coasting track. One frame in three, the coasting track feeds its filter a false detection.
Failure mode: a track that follows a guard rail. A car changes lanes away from a crash barrier. Its track coasts one frame, its gate swells, and a stationary radar return from the barrier is the only detection inside it. The track takes it, its velocity drops, and next frame the barrier returns fit even better. The track has wandered off the car and onto the barrier.
How to diagnose it: plot the track's speed and the speed of the detections it accepted. A moving track that suddenly accepts stationary detections is a red flag. Remedies include a cap on gate size, a separate stationary-clutter map, and using radar range rate as a third gate dimension.
Chapter 6
Weigh every possible pairing by its probability instead of betting on one
Two pedestrians walk side by side, half a metre apart. Each frame brings two detections, and the noise is bigger than the gap. Any hard rule will sometimes pick the wrong pairing, and then feed a filter a detection from the wrong person. What if a track did not have to choose?
That is the idea of probabilistic data association. Instead of one detection, a track takes a weighted blend of every detection in its gate. The weights are the probabilities that each detection is the track's own. When the choice is clear, one weight is near 1 and nothing changes. When the choice is unclear, the track hedges.
With several tracks, the weights must respect the rule that one detection comes from at most one object. Joint probabilistic data association (JPDA) handles that. It scores every joint event: a complete, legal story of which detection came from which track, with the rest called clutter.
For one joint event θ, multiply one factor per track. A track that takes detection j contributes how well j fits, relative to clutter. A track that takes nothing contributes the chance of a miss.
Normalise over all events. Then the association probability βij is the total probability of the events that give detection j to track i. And βi0 is the probability that track i got nothing.
Two tracks, two detections, both in both gates. Let pD = 0.9 and λ = 0.02 per m². The likelihoods (per m²) are g11 = 0.10, g12 = 0.05, g21 = 0.04, g22 = 0.08. First form a = pD g / λ = 45 g for each pair.
β11 = (0.45 + 16.2) / 21.475 = 0.775 · β12 = (0.225 + 4.05) / 21.475 = 0.199 · β10 = 0.026
β21 = (0.18 + 4.05) / 21.475 = 0.197 · β22 = (0.36 + 16.2) / 21.475 = 0.771 · β20 = 0.032
GNN would pick the top event and treat it as certain. JPDA says the same pairing is most likely, at 75%, yet keeps a 19% chance that the two are crossed. Each row of β sums to 1.
Track i now forms one combined innovation, νi = ∑j βij νij, and corrects with it. Its covariance grows to admit the doubt. With Pc = P⁻ − K S KT, the standard Kalman result:
The last term is the spread of the candidate innovations. If two candidates pull in different directions, the track becomes less sure along that line. That is honest: the filter really does not know which one was right.
Two predicted tracks (warm) and three detections. Drag the detections. Line thickness shows β. The hollow dots are where each track lands after its update. Switch between hard and soft, and watch the event list on the right.
Real JPDA arithmetic with pD = 0.9 and S = 0.36 m² on each axis for both tracks. "Walk them side by side" runs two real JPDA tracks on two people 0.8 m apart for 4 s, to show coalescence.
Run "Walk them side by side". Two people walk in parallel, close together. Each track gives some weight to the other person's detection, so each estimate is pulled toward the middle. Next frame the estimates are closer, so the weights are even more mixed. The two tracks slide together until they sit on top of each other. This is track coalescence.
When the people later part, the two merged tracks may both follow one person, and the other loses its track. JPDA trades identity swaps for this. Variants exist that reduce it, for example by pruning the joint events that would merge tracks.
The cost is the number of joint events. With 2 tracks and 2 detections there are 7. It grows roughly factorially with the number of tracks and detections in one cluster. Gating keeps clusters small, so in practice JPDA runs on groups of a few tracks at a time. Here is the enumeration in Python, on the worked example.
from itertools import product def jpda_betas(a, pd): """a[i][j] = pD * g_ij / lambda for track i, detection j (0 if outside the gate). Returns beta[i][j] for j = 0..m-1 and beta[i][m] = P(track i got nothing).""" n, m = len(a), len(a[0]) beta = [[0.0] * (m + 1) for _ in range(n)] total = 0.0 for choice in product(range(-1, m), repeat=n): # -1 means "missed" used = [j for j in choice if j >= 0] if len(used) != len(set(used)): # one detection, one track continue w = 1.0 for i, j in enumerate(choice): w *= (1 - pd) if j < 0 else a[i][j] if w == 0.0: continue total += w for i, j in enumerate(choice): beta[i][m if j < 0 else j] += w return [[b / total for b in row] for row in beta], total pd, lam = 0.9, 0.02 g = [[0.10, 0.05], [0.04, 0.08]] a = [[pd * gij / lam for gij in row] for row in g] betas, total = jpda_betas(a, pd) print(round(total, 3)) # 21.475 for i, row in enumerate(betas): print(f"T{i+1}", [round(b, 3) for b in row]) # T1 [0.775, 0.199, 0.026] # T2 [0.197, 0.771, 0.032]
Failure mode: a burst of run time in a crowd. A bus unloads 30 people at a stop. Their gates overlap into one big cluster, and the number of joint events explodes. The tracker misses its cycle deadline. Separately, two people who walk together for minutes coalesce into one track.
How to diagnose it: log cluster sizes and the event count per cycle, as a histogram, not an average. Cap the cluster size and fall back to GNN (or an approximate JPDA) above the cap. For coalescence, count frames where two confirmed tracks sit closer than their objects could physically be.
Chapter 7
Delay a hard choice until later frames settle it, and pay for the delay in memory and time
Two cyclists pass close together. On the frame where they are closest, the detections are a coin toss: the crossed pairing scores slightly higher than the straight one. One frame later, the evidence is clear. Their speeds and headings say they never crossed. GNN already committed on the coin toss. JPDA hedged, then forgot. What if you could keep both stories until the next frame decides?
That is multiple hypothesis tracking (MHT). A hypothesis is one complete story of every association so far. Each frame, every hypothesis branches into all the legal joint events for that frame. The tracker scores each branch and keeps the best ones. It decides late, once later frames have spoken.
The score of a hypothesis is the product of its joint-event weights over all frames (the same weights as JPDA), or the sum of their logs. A wrong choice two frames ago keeps costing, because the track's velocity was spoiled by it. So the tree rewards stories that stay consistent.
Take two tracks and two detections per frame, so 7 joint events per frame, as in Chapter 6. Frame 2 is the coin toss: the straight pairing scores 2.0 × 2.0 = 4.0, the crossed one 2.2 × 2.2 = 4.84. Frame 3 depends on the history. After a straight frame 2, the straight pairing scores 6 × 6 = 36. After a crossed frame 2, both tracks have bent velocities, and the best pairing scores only 0.8 × 0.8 = 0.64.
straight, then straight: 4.0 × 36 = 144 · crossed, then best: 4.84 × 0.64 = 3.1
GNN picked "crossed" at frame 2 (4.84 beats 4.0) and the names swapped. MHT kept both stories. At frame 3 the straight story wins by a factor of 46, and MHT reports no swap.
Each column is a frame; each dot is a hypothesis that survived pruning. The warm path is the current best story. Press Next frame. Frame 2 is the coin toss. Change how many frames MHT may wait before it must commit.
Scripted scores from the worked example. Frame 1 is clear; frame 2 is a coin toss that favours the wrong pairing. Frames 3 and 4 score each story by whether it stayed consistent. The branching (7 events per frame) is real.
Without pruning, 7 events per frame give 7, 49, 343 and 2,401 hypotheses after four frames, for just two tracks. Real scenes have dozens. Three tools keep it bounded.
N is the important knob. With N = 0 the tracker commits at once, and MHT collapses to GNN. With N = 1 it waits one frame, which is enough for this crossing. Each extra frame of waiting adds latency to the final answer and multiplies the work.
A last family deserves one sentence. Random finite set methods, such as the PHD filter, treat the whole set of objects as one random variable. They avoid explicit association, but they do not keep identities by default. Here is N-scan pruning as a sketch in Python.
def prune(hyps, K, N, t): """hyps: list of (score, choices) where choices[k] is the joint event at frame k. Keep the K best, then keep only those that agree with the best on frame t - N.""" hyps = sorted(hyps, key=lambda h: -h[0])[:K] # K-best k = t - N # the frame we must decide now if k >= 0: decided = hyps[0][1][k] # the best story's choice there hyps = [h for h in hyps if h[1][k] == decided] return hyps def grow(hyps, events_for, t): """Branch every hypothesis into every legal joint event at frame t.""" out = [] for score, choices in hyps: for event, weight in events_for(choices, t): # weight depends on the history if weight > 0: out.append((score * weight, choices + [event])) return out def run_mht(events_for, frames, K=6, N=1): hyps = [(1.0, [])] for t in range(frames): hyps = prune(grow(hyps, events_for, t), K, N, t) return hyps[0] # best surviving story
Failure mode: the true story pruned early. In a dense scene, K is too small for the number of plausible stories. The true one falls below the cut on the ambiguous frame, before the evidence arrives. MHT then behaves like a slow GNN.
How to diagnose it: on labelled logs, record the rank of the true hypothesis on every frame before pruning. If it often sits just below K, raise K or improve the scores. Also log the time spent per frame; MHT's worst case, not its mean, sets the deadline.
Chapter 8
Match the prediction to how the object moves, and switch models when it starts to turn
A van drives straight along the far lane, then turns hard into a side street. On the straight, a calm motion model gives a smooth, accurate track. In the turn, the same calm model keeps predicting "straight on". Its prediction drifts away from the van, its innovations grow, and the van's detections start to fall outside the gate.
Every chapter so far used the constant velocity (CV) model. Its process noise q decides how much the object may surprise it. A small q gives a smooth track that lags a turn. A large q follows the turn but jitters on the straight. One number cannot be right for both.
For CTRV, one step moves the position along an arc. In one step, x grows by (v/ω)(sin(ψ + ωΔt) − sin ψ), y by (v/ω)(cos ψ − cos(ψ + ωΔt)), and the heading by ωΔt. When ω is near zero you switch to the straight-line form to avoid dividing by zero.
The interacting multiple model (IMM) filter runs several filters at once, one per motion model, and keeps a probability for each. A mode probability μj is the filter's belief that the object currently moves like model j. Each frame has four moves.
The switching is a Markov chain with transition probabilities pij: the chance of moving from model i to model j in one frame. The mixing weights follow from Bayes' rule.
Two models: quiet CV and manoeuvring CV (a large q). Let p11 = p22 = 0.95, so a switch has a 5% chance per frame. The van has driven straight, so μ = [0.9, 0.1].
c̄1 = 0.95 × 0.9 + 0.05 × 0.1 = 0.86 · c̄2 = 0.05 × 0.9 + 0.95 × 0.1 = 0.14
μ1|1 = 0.855 / 0.86 = 0.994 · μ1|2 = 0.045 / 0.14 = 0.32, μ2|2 = 0.68
So the quiet filter starts almost purely from itself, while the manoeuvre filter borrows a third of the quiet filter's estimate. Now the turn begins. The quiet filter's innovation is large, Λ1 = 0.02; the manoeuvre filter fits better, Λ2 = 0.10.
μ1′ ∝ 0.02 × 0.86 = 0.0172 · μ2′ ∝ 0.10 × 0.14 = 0.014 → μ = [0.55, 0.45]
One frame of turning moved the manoeuvre model from 10% to 45%. One more such frame puts it in charge. When the van straightens, the quiet model wins back control just as fast.
The green van drives straight, then turns. The warm trail is the track. The lower strip plots position error over time; with IMM it also shows the manoeuvre model's probability. Try each model, then raise the turn rate.
A real two-model IMM (p11 = 0.96, p22 = 0.92) on a toy van at 7 m/s with 0.4 m detection noise. Both models are CV with different q; production systems often pair CV with a turn model instead.
So far each object made one detection. A lidar sees a nearby car as hundreds of points; a radar may return several reflections from one truck. That is an extended object. The simple route is to cluster the points into one detection per object before tracking, which works when objects are apart. Extended-object trackers instead estimate the shape too, for example as a box or an ellipse, and let many detections update one track.
Here is the IMM mixing step in C++, for two models. It reuses the Track struct from Chapter 1.
// IMM mixing for r = 2 models. Each model keeps its own Track (x, P). constexpr int kR = 2; struct Imm { Track m[kR]; float mu[kR]; float cbar[kR]; }; constexpr float kTrans[kR][kR] = { {0.96f, 0.04f}, // p_ij: from model i to model j {0.08f, 0.92f} }; void immMix(Imm& f) { for (int j = 0; j < kR; ++j) { // predicted mode probabilities f.cbar[j] = 0.f; for (int i = 0; i < kR; ++i) f.cbar[j] += kTrans[i][j] * f.mu[i]; } Track mixed[kR]; for (int j = 0; j < kR; ++j) { float w[kR]; // mixing weights mu_{i|j} for (int i = 0; i < kR; ++i) w[i] = kTrans[i][j] * f.mu[i] / f.cbar[j]; for (int a = 0; a < 4; ++a) { // mixed mean mixed[j].x[a] = 0.f; for (int i = 0; i < kR; ++i) mixed[j].x[a] += w[i] * f.m[i].x[a]; } for (int a = 0; a < 4; ++a) // mixed covariance + spread of means for (int b = 0; b < 4; ++b) { float s = 0.f; for (int i = 0; i < kR; ++i) { const float da = f.m[i].x[a] - mixed[j].x[a], db = f.m[i].x[b] - mixed[j].x[b]; s += w[i] * (f.m[i].P[a][b] + da * db); } mixed[j].P[a][b] = s; } } for (int j = 0; j < kR; ++j) f.m[j] = mixed[j]; // then predict + correct each model } void immReweight(Imm& f, const float lik[kR]) { // lik[j] = N(nu_j; 0, S_j) float sum = 0.f; for (int j = 0; j < kR; ++j) { f.mu[j] = lik[j] * f.cbar[j]; sum += f.mu[j]; } for (int j = 0; j < kR; ++j) f.mu[j] = sum > 0.f ? f.mu[j] / sum : f.cbar[j]; }
Failure mode: lost in the turn. A tracker with a single quiet CV model drops vehicles at junctions. In each case the car turned, the prediction ran straight on, the detection fell outside the 99% gate, and a new track was born. The log shows an identity change, but the cause is the motion model.
How to diagnose it: plot NIS against time around junctions and roundabouts. A spike at every turn means the model, not the association, is wrong. IMM mode probabilities in the log also make good labels: they show where manoeuvres happen.
Chapter 9
Learn what each tracking metric sees, and which errors it hides
Two trackers run on the same hour of driving. Tracker A misses a few frames here and there. Tracker B never misses. But at one junction it swaps the names of the car and the cyclist, and keeps them swapped to the end of the clip. Which is better? It depends on the metric, and the metrics disagree more than you might expect.
Every metric starts the same way. On each frame, match the tracker's confirmed tracks to the true objects, usually with the Hungarian method and a distance limit. Then count four kinds of error.
MOTA comes from the CLEAR MOT metrics (2008). Its weakness is plain in the formula: a swap counts once per object, on one frame. Misses count on every frame. So a tracker that swaps names and keeps them swapped looks almost perfect.
IDF1 (2016) finds the best one-to-one mapping between whole tracks and whole objects, for the entire clip. Then it counts frames where an object is covered by its mapped track (IDTP), and the frames that are not (IDFN, IDFP).
Two objects, 20 frames, every frame detected. At frame 11, the two tracks swap names and keep them swapped. So GT = 40, FN = 0, FP = 0, and IDSW = 2 (one per object).
MOTA = 1 − 2 / 40 = 0.95 · IDF1: best mapping covers 10 + 10 = 20 frames, so 2 × 20 / (40 + 20 + 20) = 0.50
MOTA barely notices. IDF1 halves. For a planner that predicts each object's future from its history, IDF1 tells the truer story: half the time, each history belongs to the wrong object.
HOTA (2021) splits the score in two. DetA asks: were the objects detected? AssA asks: for each correct match, how much of that object's life and that track's life line up? HOTA is their geometric mean, so neither half can hide the other.
one swap at half time: DetA = 40 / 40 = 1 · each TP: 10 / (10 + 10 + 10) = 1/3, so AssA = 1/3 · HOTA = √(1/3) = 0.58
Radar and estimation people often use a different idea: a distance between the set of true objects and the set of tracks, on each frame. OSPA pairs them optimally and charges a cutoff c for every unpaired one. GOSPA (with its usual setting α = 2) splits that cleanly into localisation error, misses and false tracks.
c = 2 m; two tracks 0.3 m and 0.4 m off, plus one false track: (0.09 + 0.16 + 4/2)1/2 = √2.25 = 1.5 m
GOSPA as written ignores identity: it scores each frame alone. That makes it a good companion to IDF1 rather than a rival.
Two objects over 20 frames. Each bar shows which track covered the object on each frame. Switch on errors one at a time and watch the four scores move. Which metric barely notices the swap?
Exact MOTA, IDF1 and single-threshold HOTA on this toy clip. GOSPA uses c = 2 m and assumes every matched track sits 0.3 m off its object; it is averaged over frames.
Here is MOTA and IDF1 from per-frame matches, in Python. The input is, for each frame, a map from object to the track that covered it, plus the false track frames.
from itertools import permutations def mota(frames, false_frames): """frames: list of {object: track or None}; false_frames: number of FP track-frames.""" gt = fn = idsw = 0 last = {} for f in frames: for obj, trk in f.items(): gt += 1 if trk is None: fn += 1 continue if obj in last and last[obj] != trk: idsw += 1 # matched track changed last[obj] = trk return 1 - (fn + false_frames + idsw) / gt def idf1(frames, false_frames): objs = sorted({o for f in frames for o in f}) trks = sorted({t for f in frames for t in f.values() if t is not None}) gt = sum(len(f) for f in frames) pred = sum(1 for f in frames for t in f.values() if t is not None) + false_frames best = 0 for perm in permutations(trks + [None] * len(objs), len(objs)): # small: brute force idtp = sum(1 for f in frames for o, t in f.items() if t is not None and perm[objs.index(o)] == t) best = max(best, idtp) return 2 * best / (gt + pred) # = 2 IDTP / (2 IDTP + IDFP + IDFN) swap = [{"car": 1, "cyclist": 2}] * 10 + [{"car": 2, "cyclist": 1}] * 10 print(round(mota(swap, 0), 3), round(idf1(swap, 0), 3)) # 0.95 0.5
Failure mode: a metric that rewards the wrong fix. A team tunes for MOTA alone. Lowering the confirmation threshold cuts misses on every frame, so MOTA rises. Swaps and short false tracks rise too, but MOTA charges them lightly. The planner team then reports more erratic predictions after a "better" tracker shipped.
How to diagnose it: always report IDF1 or AssA next to MOTA, and the raw counts (FN, FP, IDSW, fragmentations) behind every score. Look at the worst clips, not just the average: a single swap during a crossing can matter more than a thousand clean frames.
Chapter 10
Bound the memory, the work and the order of everything, so the tracker finishes on time every cycle
A car pulls into a busy car park. Fifty parked cars, a dozen people, trolleys, a barrier. The detection list triples. On a laptop, the tracker takes a little longer and nobody cares. On the car, the tracker has a fixed slice of a fixed cycle. If it overruns, the braking function gets stale tracks, or none.
Onboard tracking code is judged on its worst case, not its average. Three rules follow. Bound the memory: no allocation after start-up. Bound the work: every loop has a known maximum. Bound the order: the same input gives the same output, bit for bit, every time. The driving fusion lesson shows where this tracker sits in a full stack.
Pick a capacity at design time: say 128 tracks and 256 detections per cycle. Store tracks in a fixed array with a free list of empty slots. Creating a track takes a slot; deleting one returns it. Nothing calls the heap in the cycle, so there is no allocator lock, no fragmentation, and no surprise pause.
What happens when the scene exceeds capacity? Decide it up front. A common rule is to keep the detections nearest the vehicle, or with the highest confidence, and drop the rest in a fixed, logged way. Silent overflow is the bug; designed overflow is a feature.
The Hungarian method on an augmented matrix of n tracks and m detections costs about (n + m)³ steps. Work it out at illustrative sizes, with an illustrative 1 ns per inner step.
The fix is the gate from Chapter 2. Tracks that share no gated detections cannot affect each other, so you can split the problem into clusters and solve each one alone. Cost now depends on the biggest cluster, not on the whole scene. Then you bound the biggest cluster too: cap its size, and above the cap fall back to a cheaper method.
The bar is one tracker cycle. Each colour block is a stage. The dashed line is the tracker's budget. Add tracks and detections, then switch from one full matrix to gated clusters. Try the crowd.
Illustrative cost model, not a measurement: 1 ns per Hungarian inner step, 0.2 µs to predict a track, 20 ns per gate test, 0.3 µs per update. A 5 ms tracker budget inside a 100 ms cycle is also illustrative. Measure your own code on your own target.
Determinism means that replaying the same log gives the same tracks, the same identities and the same numbers. You need it to reproduce a field failure, to run regression tests, and to argue safety. Four habits give it.
Here is a fixed-capacity track table: a free list, slot-order iteration and counter IDs. No call in it allocates.
#include <array> #include <cstdint> constexpr int kMaxTracks = 128; struct TrackSlot { Track kf; // Chapter 1: x[4], P[4][4] Life life; // Chapter 4: state, hit history uint32_t id = 0; // stable identity from a counter, never reused bool used = false; }; class TrackTable { public: TrackTable() { for (int i = 0; i < kMaxTracks; ++i) free_[i] = kMaxTracks - 1 - i; nFree_ = kMaxTracks; } // Returns the new slot, or -1 when full. The caller logs the overflow; nothing allocates. int create(float zx, float zy, float r2) { if (nFree_ == 0) return -1; const int s = free_[--nFree_]; TrackSlot& t = slots_[s]; t = TrackSlot{}; t.kf.x[0] = zx; t.kf.x[1] = zy; // velocity starts at zero, uncertain t.kf.P[0][0] = r2; t.kf.P[1][1] = r2; t.kf.P[2][2] = 25.f; t.kf.P[3][3] = 25.f; t.id = nextId_++; t.used = true; return s; } void destroy(int s) { slots_[s].used = false; free_[nFree_++] = s; } // Deterministic: always slot 0, 1, 2, ... whatever the creation order was. template <class F> void forEach(F&& f) { for (int s = 0; s < kMaxTracks; ++s) if (slots_[s].used) f(s, slots_[s]); } int size() const { return kMaxTracks - nFree_; } private: std::array<TrackSlot, kMaxTracks> slots_{}; std::array<int16_t, kMaxTracks> free_{}; int nFree_ = 0; uint32_t nextId_ = 1; };
And here is the cycle, with every stage bounded. The clusters come from a union-find over the gate table, which is itself a fixed-size array.
constexpr int kMaxDets = 256, kMaxCluster = 12; struct CycleStats { int nDets, droppedDets, maxCluster, fallbacks; }; CycleStats trackerCycle(TrackTable& tt, Det* dets, int nDets, float dt) { CycleStats st{nDets, 0, 0, 0}; if (nDets > kMaxDets) { // designed overflow: keep the nearest sortByRange(dets, nDets); // deterministic sort, ties by index st.droppedDets = nDets - kMaxDets; nDets = kMaxDets; } tt.forEach([&](int, TrackSlot& t) { predict(t.kf, dt, kQ); }); // O(n) buildGateTable(tt, dets, nDets); // O(n m), fixed arrays const int nClusters = clusterByUnionFind(); // tracks sharing gated detections for (int c = 0; c < nClusters; ++c) { const int size = clusterSize(c); st.maxCluster = size > st.maxCluster ? size : st.maxCluster; if (size <= kMaxCluster) solveClusterHungarian(c); // optimal, bounded else { solveClusterGreedy(c); ++st.fallbacks; } // bounded fallback, logged } updateAssigned(tt, dets); // Chapter 1 correct, per track manageLifeCycle(tt, dets, nDets); // Chapter 4: confirm, coast, delete, birth return st; // every cycle reports its own worst case }
Failure mode: a deadline miss that only happens on Tuesdays. The tracker passes every test, then overruns in one city's car parks. The cause is one big cluster in a dense scene, solved with a full O(n³) step. A second team finds that two replays of the same log give different IDs: an unordered map changed its iteration order after a library update.
How to diagnose it: log the per-cycle stats (detection count, biggest cluster, fallbacks, stage times) on the vehicle, and plot their maxima per drive. Add a replay test that runs every log twice and fails on any difference. The data association lesson in the sensor fusion series goes deeper on cluster methods.
Chapter 11
Run the whole tracker with every knob in reach, then break it on purpose
Here is everything at once: a crossing car and cyclist, a pedestrian, and a green van that turns across the scene. The tracker has every part you built: Kalman prediction, a chi-square gate, three association rules, M-of-N confirmation, coasting and deletion, and an optional IMM. The scoreboard uses the Chapter 9 counts.
Press Run. Change any knob and the scene restarts with the same detections. Red rings mark identity switches; red labels mark false tracks.
The same toy engine as the hero, 10 s at 10 frames a second. The averages quoted below come from 50 seeded runs of this bench in Node, with the other knobs at their defaults.
Each experiment changes one knob from the defaults (GNN, CV q = 2, noise 0.6 m, clutter 1.5, pD 0.92, 3 of 4, delete after 5). The numbers are averages over 50 seeded runs of this bench; your single run will vary.
One honest surprise: in this toy, JPDA swaps a little more often than GNN at the default settings (0.68 against 0.30 switches a run). The car and the cyclist pass within 1.5 m, and their JPDA tracks drift together, which is the coalescence of Chapter 6. Soft association is a tool for heavy ambiguity, not a free upgrade.
Here is the frame loop the bench runs, in C++ outline, using the pieces from every chapter. The order of stages is the order of the chapters.
// One frame of the full tracker, in chapter order. All storage is fixed-size. void frame(TrackTable& tt, const Det* dets, int nDets, const Params& p) { // Ch 1: predict every track (or run IMM mixing first, Ch 8) tt.forEach([&](int, TrackSlot& t) { p.imm ? immPredict(t, p.dt) : predict(t.kf, p.dt, p.q); }); // Ch 2: innovation covariance and gate for every track and detection static float d2[kMaxTracks][kMaxDets]; static bool inGate[kMaxTracks][kMaxDets]; tt.forEach([&](int s, TrackSlot& t) { const Innov n = innovation(t.kf, p.r2); gate(t.kf, n, dets, nDets, d2[s], inGate[s]); }); // Ch 4: confirmed tracks choose first, tentative tracks take what is left static int asg[kMaxTracks]; associate(tt, d2, inGate, nDets, p.rule, /*confirmedOnly=*/true, asg); // Ch 3 or Ch 6 associate(tt, d2, inGate, nDets, p.rule, /*confirmedOnly=*/false, asg); // Ch 1 again: correct with the chosen detection (or the JPDA blend) tt.forEach([&](int s, TrackSlot& t) { if (asg[s] >= 0) correct(t.kf, innovation(t.kf, p.r2), dets[asg[s]].x, dets[asg[s]].y); }); // Ch 4: hits, misses, confirm, coast, delete; births from ungated detections tt.forEach([&](int s, TrackSlot& t) { stepLife(t.life, asg[s] >= 0, p.life); if (t.life.state == TrackState::Deleted) tt.destroy(s); }); for (int k = 0; k < nDets; ++k) if (!gatedByAnyTrack(inGate, k)) tt.create(dets[k].x, dets[k].y, p.r2); }
Chapter 12
Gather the numbers, the design frames, the drills and the debugging stories in one place
Here is the lesson in one paragraph. Detections carry no names, so a tracker must decide each frame which detection belongs to which track. A Kalman filter per object predicts where to look and says how surprised to be, through S. The Mahalanobis distance and a chi-square gate rule out impossible pairs. An optimal assignment (GNN) beats greedy at crossings.
A small state machine with M-of-N logic decides when tracks are born and die. Clutter and misses make hard choices wrong sometimes; JPDA hedges and MHT waits, each at a price. IMM matches the motion model to the manoeuvre. Metrics disagree, so report several. And onboard, all of it runs with fixed memory, bounded work and a deterministic order.
Pick a symptom from a field report. The pipeline lights the stages to check first, in order, and the read-out says what to log.
A study aid: real incidents can have several causes. Always confirm with a replay of the logged frames.
| Idea | One line | Number to remember |
|---|---|---|
| Innovation covariance | S = H P⁻ HT + R, the expected size of detection minus prediction | NIS averages 2 for a 2D detection |
| Mahalanobis gate | d² = νTS−1ν ≤ γ | γ = 9.21 for 99% in 2D; 5.99 for 95% |
| Gate area | V = π γ √det S | clutter in gate = λV |
| Assignment cost | d² + ln det S; ∞ outside the gate | Hungarian is O(n³); 10! = 3.6 million by brute force |
| Greedy trap | cheapest pair first can force a bad pair elsewhere | [[1, 2], [2.5, 8]]: 9.0 against 4.5 |
| M-of-N | confirm with M hits in the last N frames | 2 of 3: real 0.972, clutter 0.0073 |
| Deletion | delete after K misses in a row | (1 − pD)K: 0.001 for 0.9 and K = 3 |
| JPDA | βij from joint events, weighted update | 2 tracks, 2 detections: 7 joint events |
| MHT | keep the K best stories, decide N frames late | 74 = 2,401 stories after 4 frames, unpruned |
| IMM | mix, filter, re-weight, combine | μ 0.10 → 0.45 in one turning frame (worked) |
| MOTA vs IDF1 | MOTA counts errors; IDF1 maps whole tracks | one swap at half time: 0.95 against 0.50 |
| Real time | fixed capacity, gated clusters, ties by index | (n + m)³ at 160 is 4.1 million steps |
Camera and radar detections arrive at about 20 Hz (illustrative), up to 64 objects, a 5 ms tracker budget, and the output feeds automatic emergency braking.
A lidar sees crowds at close range, people walk in groups, occlusion is constant, and the robot moves at walking pace.
bool inGate(const float nu[2], const float S[2][2], float gamma) with a closed-form inverse. Test it on A, B and C from Chapter 2, and on a singular S (return false, do not divide by zero).Here is one answer to the first drill. The point an interviewer looks for is the singular case.
// Drill 1, one answer: a gate test that never divides by zero. #include <cmath> bool inGate(const float nu[2], const float S[2][2], float gamma) { const float det = S[0][0] * S[1][1] - S[0][1] * S[1][0]; if (!(det > 1e-9f) || !std::isfinite(det)) return false; // singular or NaN: reject, and count it const float i00 = S[1][1] / det, i01 = -S[0][1] / det; const float i10 = -S[1][0] / det, i11 = S[0][0] / det; const float d2 = nu[0] * (i00 * nu[0] + i01 * nu[1]) + nu[1] * (i10 * nu[0] + i11 * nu[1]); return d2 <= gamma; } // Tests from Chapter 2, with S = diag(4, 1) and gamma = 9.21: // A {3.0, 0.5} -> d2 2.50 -> true // B {0.0, 2.5} -> d2 6.25 -> true // C {0.0, 3.2} -> d2 10.24 -> false // S = {{1, 1}, {1, 1}}, det 0 -> false, and never a crash
| Classical (this lesson) | Learned | |
|---|---|---|
| Association | Hungarian or JPDA on Mahalanobis costs | learned affinities, attention between track queries and detections |
| Motion | Kalman, IMM, explicit models | learned motion priors, often still a Kalman filter underneath |
| Identity cues | position, velocity, gate | appearance embeddings (DeepSORT), learned features |
| Worst case | bounded and analysable | harder to bound; depends on model size and input |
| Behaviour off the data | degrades by known rules | can fail in ways the training set never showed |
| Data needs | noise models and tuning logs | large labelled tracking datasets |
The frontier, briefly and honestly. Camera trackers such as SORT (Kalman plus Hungarian on box overlap) and DeepSORT (adds an appearance embedding) showed how far simple structure goes. ByteTrack added a second association pass for low-confidence detections, which recovers occluded objects. AB3DMOT applied a 3D Kalman filter with the Hungarian method to lidar and found that this simple baseline was competitive. Learned end-to-end trackers now associate with attention, and point trackers such as CoTracker3 follow thousands of pixels; optical flow is their dense cousin. In many onboard stacks, a learned detector feeds a classical, checkable tracker like the one you built.
Now press Present or Teach and explain, from memory, why greedy association swaps the names at a crossing and GNN keeps them. Say what S has to do with it. Then go back to the crossing, raise the noise, and find the point where even GNN swaps.