Algorithmresearch
Deep SORT
Also called DeepSORT.
SORT with an appearance embedding per detection and a matching cascade that combines Mahalanobis motion gating with cosine appearance distance.
- Solves
- Multi-object tracking
- Time
- O(N (n m (n + m + L d) + A)) worst
- Space
- O(n L d + n m) extra
- Where
- A = the largest track age; L = the gallery size of a track; N = the number of frames; d = the embedding dimension; m = the number of detections in a frame; n = the number of tracks
- Model
- Real RAM
- Properties
- deterministicnot exactnot iterativeonline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Nicolai Wojke, Alex Bewley, Dietrich Paulus, 2017
Deep SORT is the SORT tracker with an appearance score. Each detection comes with an embedding, a vector that a neural network computes from the image inside the box, so that boxes of the same person give close vectors. The network and its training are outside this page: here the embeddings are input data, and the page covers only the tracker that uses them. Deep SORT keeps for each track the embeddings of its last detections, gates pairs by the Mahalanobis distance of the Kalman filter, and scores them by the smallest cosine distance to the stored embeddings. It then matches tracks in a cascade, the most recently seen tracks first, and runs a SORT-like IoU stage on the rest. Compared with SORT, it keeps a lost track for 30 frames instead of 1, so a person who comes back after an occlusion can get the old identity. Compared with ByteTrack, it adds appearance but uses only the detections above the detector threshold.
In plain words
SORT only looks at where boxes are. When a person walks behind a tree and comes out a second later, SORT has already forgotten them and gives a new number. Deep SORT also looks at what a box looks like. A separate network turns each box into a list of numbers, and two boxes of the same person give similar lists. Each track remembers the lists of its last boxes. When new boxes come, a box can go to a track only if it is near where the track should be and if it looks like the track. Tracks that were seen most recently choose first, and tracks that have been missing longer choose later. A track that is missing is kept for a while, so the person gets the old number back.
The problem
The input and output are those of the SORT tracker, and the problem is multi-object tracking. The only change in the input is that detection of a frame is a pair of a box and an embedding .
The state. A track holds a Kalman filter on : the center of the box, the aspect ratio , the height , and their velocities, with a constant velocity model. It also holds a gallery of the embeddings of its last detections, with in the paper, a count of hits, and the count of frames since its last update. A new track is tentative. It becomes confirmed at its third detection in a row.
The two distances. For track with predicted measurement and covariance , and detection with measurement ,
A pair is admissible if and . The gate is the 95 percent point of the chi-square distribution with 4 degrees of freedom, so a correct measurement passes it with probability 0.95 under the Kalman model. The paper sets on a separate training set; the released code uses . The cost of an admissible pair is . The paper uses in its experiments, so the motion term acts only through the gate.
The algorithm
DEEP-SORT-STEP(the tracks, the detections (d_j, e_j), A_max, t_1, t_2, λ)- 1
for each track i: Kalman predict; a_i ← a_i + 1 - 2
U ← all detections; for n = 1, 2, ..., A_max: T_n ← the confirmed tracks with a_i = n - 3
c_ij ← λ d_1(i, j) + (1 - λ) d_2(i, j), admissible only if d_1 ≤ t_1 and d_2 ≤ t_2 - 4
min-cost assignment of T_n to U; keep the admissible pairs; remove their detections from U - 5
C ← the tentative tracks and the unmatched tracks with a_i = 1; match C to U on 1 - IoU, keep pairs with IoU ≥ 0.3 - 6
for each matched pair (i, j): Kalman update with d_j; add e_j to G_i (keep the last L); a_i ← 0; confirm at 3 hits - 7
delete each unmatched tentative track and each track with a_i > A_max - 8
for each detection j left in U: a new tentative track with G = {e_j} - 9
output the confirmed tracks updated in this frame
Lines L2 to L4 are the matching cascade of Listing 1 of the paper. Each level is a separate assignment, solved by the Hungarian algorithm. In the released code, which the implementation follows, a pair that is not admissible gets a cost just above every admissible cost before the assignment and is removed after it. Line L5 is the IoU stage of the paper, with the IoU bound 0.3 of the released code (a largest IoU distance of 0.7). It helps with sudden changes of appearance and with new tracks that have only one embedding. The paper uses and .
The filter. The released code scales the noise by the height of the box. With and , the standard deviations are for the position part and for the velocity part of the motion noise, for the measurement, and for a new track.
Example
The gallery distance. A track has the gallery and a detection has the embedding . The cosine distances are and , so , and the pair passes . The gallery lets a track match a view of the person that it saw some frames ago.
Why the cascade. A track of a box 40 pixels high moved 2 pixels per frame for 5 frames. A detection lies 10 pixels right and 10 pixels below the predicted center, with the same size. The squared Mahalanobis distance is 15.0 if the track was updated one frame ago, 9.0 after two predictions without an update, and 1.0 after ten. The covariance grows with each prediction, so a track that has been missing for long accepts almost any detection near it, and it gets a smaller than a track that is sure of its position. Matching all tracks at once would let old, uncertain tracks take detections from fresh ones. The cascade gives fresh tracks the first choice.
What the cascade costs. Track 1 was updated one frame ago and track 2 two frames ago. There are detections and , with the costs , and , and the pair outside the gate. Level 1 matches track 1 alone and gives it , its cheaper detection. Level 2 offers only to track 2, which is not admissible. Track 2 has , so it is not in the IoU stage either, and starts a new track. One assignment over both tracks would match and , two pairs at a total of 0.17. So the cascade can match fewer pairs than a single assignment. The design accepts this to protect fresh tracks.
A short sequence. Two people with 8-dimensional embeddings walk for 40 frames. Person 0 walks behind person 1 and is not detected for 10 frames. Deep SORT gives person 0 the same identity before and after the occlusion. With , as in SORT, the track of person 0 is deleted during the occlusion and person 0 comes back with a new identity.
Correctness
Deep SORT is a heuristic tracker, and the claims below are about one frame and about the parts of the method. The proofs are in proofs/correctness.md.
- Theorem: the gate. If the measurement error is Gaussian with the covariance of the filter, then has the chi-square distribution with 4 degrees of freedom, and . For this is 0.95.
- Theorem: each stage. Each level of the cascade and the IoU stage return an assignment, all kept pairs are admissible, and no track or detection is matched twice over the whole frame.
- Theorem: priority. A detection that is admissible for a track of level and still free at that level is never taken by a track of a level above .
- Theorem: the cascade is not a global optimum. The example above shows a frame where the cascade keeps fewer pairs than one assignment over all tracks.
- Theorem: uncertainty widens the gate. If (that is, is positive semidefinite), then the Mahalanobis distance under is at most the distance under for every offset. This is why the cascade is needed.
- Not proved. That the embedding separates people is a property of the network and the data. The improvement on MOT16 is a benchmark result.
Proof: Why the Deep SORT gate has probability 0.95, why the cascade gives priority and matches nothing twice, why it is not a global optimum, and why uncertain tracks have a wider gatefull
Notation as on the page. In one frame there are tracks with predicted measurement , innovation covariance (positive definite), gallery and count of frames since the last update after line L1, and detections with measurement and embedding . A pair is admissible if and . The claims are about the algorithm in one frame. The quality of the embeddings is not part of any claim.
Claim 1: the probability of the gate
Let be Gaussian with mean 0 and covariance in . Then has the chi-square distribution with 4 degrees of freedom, and
Proof. Let with the Cholesky factor, and . Then has covariance , so are independent standard normal numbers, and . That is the chi-square distribution with 4 degrees of freedom, whose density is for . The function has derivative , so .
For , and , so the product is and the probability is . The claim needs the Gaussian model. The tests draw 4000 measurements from the projected distribution of a filter and find a fraction within 0.015 of 0.95.
Claim 2: each stage gives a matching, and the frame matches nothing twice
Each call of the minimum cost matching on rows and columns returns a set of pairs in in which no row and no column appears twice, and all pairs are admissible for that stage. Over the whole frame, no track and no detection is matched twice.
Proof. The routine solves a full assignment of the matrix on , in which a pair that is not admissible has a cost one above the largest admissible cost. By Claim 1 of the SORT proof on the Hungarian algorithm, the result is an assignment of least cost of that matrix, so it is a set of pairs with distinct rows and distinct columns. The routine then drops the pairs that are not admissible, and a subset of an assignment is an assignment.
The rows of the levels are the sets , which are disjoint for different . The rows of the IoU stage are the tentative tracks, which are in no , and the confirmed tracks that the cascade left unmatched. So no track takes part in two stages in which it is matched. The columns of each stage are the set of free detections, and every detection matched in a stage is removed from before the next stage. So no detection is matched twice.
Claim 3: priority of fresh tracks
The tracks of level choose among all detections that the levels did not take, and the tracks of the levels above see only the detections that level left free. In particular, if has one track and some free detection is admissible for , then gets its cheapest admissible free detection, whatever the tracks of higher levels would prefer.
Proof. The first sentence is the order of the loop of line L2 and the update of in line L4. For a single row, a full assignment picks one column. Every admissible column has a cost below the cost of every column that is not admissible, so the least cost column is the cheapest admissible one, and it is kept.
Claim 4: the cascade is not a global optimum
There is a frame where the cascade keeps fewer admissible pairs than one assignment over all confirmed tracks.
Example. Track 1 has and track 2 has . There are detections and with costs , , , all admissible, and not admissible. Level 1 is , and by Claim 3 track 1 takes . Level 2 is , and the only free detection is not admissible, so track 2 stays unmatched. Since , track 2 is not a candidate of the IoU stage. One pair is kept. A single assignment over both tracks can use , which has two admissible pairs and total cost , while any assignment that uses must give track 2 the detection , which is not admissible. So the single assignment keeps two pairs.
The tests check this example with the implementation.
Claim 5: a larger covariance gives a wider gate
Let and be positive definite with positive semidefinite. Then for every , . So every measurement inside the gate of is also inside the gate of .
Proof. Let be the symmetric positive definite square root of , and . Then is positive semidefinite, so every eigenvalue of the symmetric matrix is at least 1. The eigenvalues of are their inverses, at most 1, so is positive semidefinite. With ,
Each prediction without an update adds and spreads the position by the velocity variance, so the innovation covariance of a track usually grows while it is missing. In the example of the page, the first entry of grows from 13.3 after one prediction to 195 after ten, and the squared Mahalanobis distance of a fixed offset drops from 15.0 to 1.0. Claim 5 then says that a missing track accepts every detection that a fresh track at the same place would accept, and more. Without the cascade, such a track would win detections because its is small; the cascade of Claim 3 prevents that.
Claim 6: the filter
The prediction and the update are the Kalman recursion for the linear model of the page, and the implementation uses the Joseph form for the update. By Claim 6 of the SORT proof, the covariance stays symmetric and positive definite, since the motion noise and the measurement noise are positive definite for every height . This is what makes and well defined.
Complexity
Let be the number of tracks, the number of detections, the gallery size and the embedding dimension, in the real RAM model. The appearance costs need time, and the gate needs , since the filter has a fixed size. If level of the cascade has tracks, its assignment costs , and these add up to because . The IoU stage costs the same, and the levels add for the loop. One frame costs time, and a video of frames times that. The galleries take space and the cost matrices . The network that computes the embeddings is usually the most expensive part, and it is not counted here.
Properties
- Online. The output of a frame never changes later.
- Long memory. A confirmed track survives up to missed frames.
- Appearance needed. With , a pair is matched in the cascade only if the appearance distance is at most , so a bad embedding blocks a match even when the motion fits.
- Detections above a threshold. The tracker uses only the detections that the detector reports; it does not look at weak boxes as ByteTrack does.
Variants and improvements
- The combined cost. With , the motion distance also ranks the pairs. The paper reports that worked well when the camera moves a lot.
- Feature update by moving average. Later trackers replace the gallery by one embedding per track, updated as an exponential moving average, which takes less space and memory traffic.
- No cascade. Some later trackers match all tracks in one assignment and handle uncertainty in other ways, for example with a better motion model. The gains are benchmark results.
- ByteTrack. ByteTrack keeps the SORT structure and adds a second round with low-score detections. It can use appearance in its first round too.
When to use it
Use Deep SORT when objects are hidden for many frames and come back, and when an appearance network for the object class is available, as for pedestrians. It is a common baseline for tracking people. Do not use it when objects of the same class look alike (identical parts on a belt, players in the same jersey), since the appearance score then helps little and the stricter matching can lose tracks. Without a network, use SORT or ByteTrack.
Pitfalls
- Embeddings from another domain. A network trained on pedestrians gives poor embeddings for cars. The gate then rejects good pairs or accepts bad ones.
- Uncertain tracks winning. Without the cascade, old tracks with large covariance take detections from current tracks, because their Mahalanobis distance is small. Keep the cascade or bound the covariance.
- Mixing up the state. The state uses aspect ratio and height, not area and aspect ratio as SORT does. Copying the noise values of one filter into the other gives a badly tuned filter.
- Gallery size. A long gallery keeps old views, which helps after occlusions but also matches a different person who looks like an old view. The cost of the appearance term grows with .
- Counting identity switches only. Deep SORT trades some MOTA for fewer identity switches. Compare trackers with an identity measure such as IDF1 or HOTA as well as with the CLEAR MOT metrics.
Implementations
The Python file follows the paper and its released code: the 8-dimensional filter with noise scaled by the height, the gate 9.4877, a gallery of 100 embeddings, , , the cascade over 30 levels, and an IoU stage with bound 0.3. The embeddings are inputs. The tests check the gate probability by sampling from the filter, compare the assignment with brute force, check the cascade example and the Mahalanobis values above, and run the occlusion sequence.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/deep-sort/. The authors are listed in prov/Q69QVS.jsonl.
"""Deep SORT: SORT with a deep association metric (Wojke, Bewley and Paulus 2017).
The appearance network is not part of this file: each detection comes with
its embedding vector, as the output of some re-identification network.
Each track is a constant velocity Kalman filter on (u, v, a, h, du, dv, da, dh):
the box center, the aspect ratio a = width / height, the height, and their
velocities. The noise is scaled by the height, as in the released code.
A track keeps a gallery of the last `budget` embeddings of its detections.
One frame:
1. predict every track;
2. matching cascade: for n = 1, 2, ..., max_age, match the confirmed tracks
whose time since the last update is n with the detections still free,
by a minimum cost assignment on c = lam * d1 + (1 - lam) * d2, where d1 is
the squared Mahalanobis distance and d2 the smallest cosine distance to
the gallery; a pair is allowed only if d1 <= t1 and d2 <= t2;
3. IoU stage: tentative tracks and confirmed tracks missed only in this
frame are matched with the free detections on 1 - IoU, allowed if
1 - IoU <= max_iou_distance;
4. update the matched tracks, delete tentative tracks that miss, delete
confirmed tracks missed more than max_age frames, and start a tentative
track for each free detection.
Boxes are (x1, y1, x2, y2), area (x2 - x1)(y2 - y1). Matrices are lists of rows.
"""
import math
CHI2_95_4DOF = 9.4877 # 95 percent quantile of the chi-square law with 4 degrees of freedom
# ---------------------------------------------------------------- small linear algebra
def mat_mul(a, b):
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def transpose(a):
return [list(r) for r in zip(*a)]
def mat_add(a, b):
return [[x + y for x, y in zip(r, s)] for r, s in zip(a, b)]
def mat_sub(a, b):
return [[x - y for x, y in zip(r, s)] for r, s in zip(a, b)]
def mat_vec(a, x):
return [sum(p * q for p, q in zip(row, x)) for row in a]
def eye(n):
return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
def diag(values):
n = len(values)
return [[float(values[i]) if i == j else 0.0 for j in range(n)] for i in range(n)]
def inverse(a):
"""Inverse of a small nonsingular matrix by Gauss-Jordan elimination with partial pivoting."""
n = len(a)
m = [list(map(float, r)) + [1.0 if i == j else 0.0 for j in range(n)] for i, r in enumerate(a)]
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
if abs(m[p][c]) < 1e-300:
raise ValueError("singular matrix")
m[c], m[p] = m[p], m[c]
piv = m[c][c]
m[c] = [x / piv for x in m[c]]
for r in range(n):
if r != c and m[r][c] != 0.0:
f = m[r][c]
m[r] = [x - f * y for x, y in zip(m[r], m[c])]
return [r[n:] for r in m]
# ---------------------------------------------------------------- boxes and embeddings
def iou(a, b):
"""Intersection over union of two boxes (x1, y1, x2, y2). Exact on Fractions."""
w = min(a[2], b[2]) - max(a[0], b[0])
h = min(a[3], b[3]) - max(a[1], b[1])
if w <= 0 or h <= 0:
return 0 * w
inter = w * h
union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
return inter / union
def box_to_xyah(box):
w = box[2] - box[0]
h = box[3] - box[1]
return [box[0] + w / 2.0, box[1] + h / 2.0, w / float(h), float(h)]
def xyah_to_box(z):
w = z[2] * z[3]
return (z[0] - w / 2.0, z[1] - z[3] / 2.0, z[0] + w / 2.0, z[1] + z[3] / 2.0)
def cosine_distance(a, b):
"""1 - cos(angle between a and b)."""
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(x * x for x in b))
return 1.0 - sum(x * y for x, y in zip(a, b)) / (na * nb)
def gallery_distance(gallery, e):
"""d2: the smallest cosine distance from e to the embeddings of a track."""
return min(cosine_distance(g, e) for g in gallery)
# ---------------------------------------------------------------- Kalman filter on (u, v, a, h)
STD_POS = 1.0 / 20.0
STD_VEL = 1.0 / 160.0
F8 = [[1.0 if (i == j or j == i + 4) else 0.0 for j in range(8)] for i in range(8)]
H8 = [[1.0 if i == j else 0.0 for j in range(8)] for i in range(4)]
def kf_initiate(z):
h = z[3]
std = [2 * STD_POS * h, 2 * STD_POS * h, 1e-2, 2 * STD_POS * h,
10 * STD_VEL * h, 10 * STD_VEL * h, 1e-5, 10 * STD_VEL * h]
return list(z) + [0.0, 0.0, 0.0, 0.0], diag([s * s for s in std])
def kf_predict(mean, cov):
h = mean[3]
std = [STD_POS * h, STD_POS * h, 1e-2, STD_POS * h, STD_VEL * h, STD_VEL * h, 1e-5, STD_VEL * h]
q = diag([s * s for s in std])
return mat_vec(F8, mean), mat_add(mat_mul(mat_mul(F8, cov), transpose(F8)), q)
def kf_measurement_noise(mean):
h = mean[3]
std = [STD_POS * h, STD_POS * h, 1e-1, STD_POS * h]
return diag([s * s for s in std])
def kf_project(mean, cov):
"""Predicted measurement and its covariance S = H P H^T + R."""
s = mat_add(mat_mul(mat_mul(H8, cov), transpose(H8)), kf_measurement_noise(mean))
return mean[:4], s
def kf_update(mean, cov, z):
zp, s = kf_project(mean, cov)
ph = mat_mul(cov, transpose(H8))
k = mat_mul(ph, inverse(s))
mean = [a + b for a, b in zip(mean, mat_vec(k, [x - y for x, y in zip(z, zp)]))]
ikh = mat_sub(eye(8), mat_mul(k, H8))
r = kf_measurement_noise(zp)
cov = mat_add(mat_mul(mat_mul(ikh, cov), transpose(ikh)), mat_mul(mat_mul(k, r), transpose(k)))
return mean, cov
def mahalanobis_sq(mean, cov, z):
"""d1: squared Mahalanobis distance of a measurement z = (u, v, a, h) to the track."""
zp, s = kf_project(mean, cov)
d = [x - y for x, y in zip(z, zp)]
return sum(p * q for p, q in zip(d, mat_vec(inverse(s), d)))
# ---------------------------------------------------------------- assignment
def hungarian_min(cost):
"""Minimum cost assignment for a rectangular matrix of finite costs.
Returns the sorted list of pairs (row, column); its size is min(rows, columns).
"""
r = len(cost)
if r == 0 or len(cost[0]) == 0:
return []
c = len(cost[0])
flip = r > c
if flip:
cost = transpose(cost)
r, c = c, r
inf = float("inf")
u, v = [0.0] * (r + 1), [0.0] * (c + 1)
p, way = [0] * (c + 1), [0] * (c + 1)
for i in range(1, r + 1):
p[0], j0 = i, 0
minv, used = [inf] * (c + 1), [False] * (c + 1)
while True:
used[j0] = True
i0, delta, j1 = p[j0], inf, 0
for j in range(1, c + 1):
if not used[j]:
cur = cost[i0 - 1][j - 1] - u[i0] - v[j]
if cur < minv[j]:
minv[j], way[j] = cur, j0
if minv[j] < delta:
delta, j1 = minv[j], j
for j in range(c + 1):
if used[j]:
u[p[j]] += delta
v[j] -= delta
else:
minv[j] -= delta
j0 = j1
if p[j0] == 0:
break
while True:
j1 = way[j0]
p[j0] = p[j1]
j0 = j1
if j0 == 0:
break
pairs = [(p[j] - 1, j - 1) for j in range(1, c + 1) if p[j] != 0]
if flip:
pairs = [(b, a) for a, b in pairs]
return sorted(pairs)
def min_cost_matching(cost, allowed, rows, cols):
"""Minimum cost assignment of rows to cols that keeps only allowed pairs.
cost(i, j) and allowed(i, j) are functions. Pairs that are not allowed get
one cost above every allowed cost before the assignment, as in the released
code, and are removed after it. Returns (matches, free rows, free cols).
"""
if not rows or not cols:
return [], list(rows), list(cols)
vals = {(i, j): cost(i, j) for i in rows for j in cols if allowed(i, j)}
top = max(vals.values(), default=0.0) + 1.0
mat = [[vals.get((i, j), top) for j in cols] for i in rows]
matches = [(rows[a], cols[b]) for a, b in hungarian_min(mat) if (rows[a], cols[b]) in vals]
mr = {i for i, _ in matches}
mc = {j for _, j in matches}
return matches, [i for i in rows if i not in mr], [j for j in cols if j not in mc]
def matching_cascade(ages, cost, allowed, cols, max_age):
"""Lines L2 to L4. ages maps each confirmed track to its time since the last update."""
matches, free = [], list(cols)
for n in range(1, max_age + 1): # @line L2
level = [i for i in sorted(ages) if ages[i] == n]
if not level or not free:
continue
# @line L3 (the cost and the gate are the functions cost and allowed)
found, _, free = min_cost_matching(cost, allowed, level, free) # @line L4
matches += found
matched = {i for i, _ in matches}
return matches, [i for i in sorted(ages) if i not in matched], free
# ---------------------------------------------------------------- tracks and tracker
TENTATIVE, CONFIRMED, DELETED = 0, 1, 2
class Track:
def __init__(self, box, embedding, track_id):
self.mean, self.cov = kf_initiate(box_to_xyah(box))
self.id = track_id
self.hits = 1
self.age = 1
self.time_since_update = 0
self.state = TENTATIVE
self.gallery = [list(embedding)]
def box(self):
return xyah_to_box(self.mean[:4])
class DeepSortTracker:
"""Call step(detections) once per frame; a detection is (box, embedding)."""
def __init__(self, max_age=30, n_init=3, t1=CHI2_95_4DOF, t2=0.2, lam=0.0,
max_iou_distance=0.7, budget=100):
self.max_age = max_age
self.n_init = n_init
self.t1 = t1
self.t2 = t2
self.lam = lam
self.max_iou_distance = max_iou_distance
self.budget = budget
self.tracks = []
self.next_id = 1
def step(self, detections):
tr = self.tracks
for t in tr: # @line L1
t.mean, t.cov = kf_predict(t.mean, t.cov)
t.age += 1
t.time_since_update += 1
zs = [box_to_xyah(b) for b, _ in detections]
d1 = {}
d2 = {}
def dist(i, j):
if (i, j) not in d1:
d1[(i, j)] = mahalanobis_sq(tr[i].mean, tr[i].cov, zs[j])
d2[(i, j)] = gallery_distance(tr[i].gallery, detections[j][1])
return d1[(i, j)], d2[(i, j)]
def cost(i, j):
a, b = dist(i, j)
return self.lam * a + (1.0 - self.lam) * b
def allowed(i, j):
a, b = dist(i, j)
return a <= self.t1 and b <= self.t2
ages = {i: t.time_since_update for i, t in enumerate(tr) if t.state == CONFIRMED}
m_a, um_a, free = matching_cascade(ages, cost, allowed, list(range(len(detections))), self.max_age)
cand = [i for i, t in enumerate(tr) if t.state == TENTATIVE] # @line L5
cand += [i for i in um_a if tr[i].time_since_update == 1]
cand.sort()
boxes = [t.box() for t in tr]
m_b, _, free = min_cost_matching(
lambda i, j: 1.0 - iou(boxes[i], detections[j][0]),
lambda i, j: 1.0 - iou(boxes[i], detections[j][0]) <= self.max_iou_distance,
cand, free)
matched = set()
for i, j in m_a + m_b: # @line L6
t = tr[i]
t.mean, t.cov = kf_update(t.mean, t.cov, zs[j])
t.gallery = (t.gallery + [list(detections[j][1])])[-self.budget:]
t.hits += 1
t.time_since_update = 0
if t.state == TENTATIVE and t.hits >= self.n_init:
t.state = CONFIRMED
matched.add(i)
for i, t in enumerate(tr): # @line L7
if i not in matched and (t.state == TENTATIVE or t.time_since_update > self.max_age):
t.state = DELETED
for j in free: # @line L8
tr.append(Track(detections[j][0], detections[j][1], self.next_id))
self.next_id += 1
self.tracks = [t for t in tr if t.state != DELETED]
# @line L9
return [(t.id, t.box()) for t in self.tracks if t.state == CONFIRMED and t.time_since_update == 0]
test_deep_sort.py 224 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/deep-sort/. The authors are listed in prov/Q69QVS.jsonl.
import itertools
import math
import random
from fractions import Fraction
from deep_sort import (
CHI2_95_4DOF,
CONFIRMED,
DeepSortTracker,
box_to_xyah,
gallery_distance,
hungarian_min,
iou,
kf_initiate,
kf_predict,
kf_project,
kf_update,
mahalanobis_sq,
matching_cascade,
min_cost_matching,
xyah_to_box,
)
def cholesky(a):
n = len(a)
low = [[0.0] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1):
s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
low[i][j] = math.sqrt(s) if i == j else s / low[j][j]
return low
def test_chi_square_gate_value():
g = CHI2_95_4DOF
assert abs(1.0 - math.exp(-g / 2.0) * (1.0 + g / 2.0) - 0.95) < 1e-4
def test_gate_keeps_95_percent_of_model_measurements():
rng = random.Random(5)
mean, cov = kf_initiate(box_to_xyah((100.0, 50.0, 120.0, 90.0)))
for _ in range(3):
mean, cov = kf_predict(mean, cov)
zp, s = kf_project(mean, cov)
low = cholesky(s)
inside, trials = 0, 4000
for _ in range(trials):
w = [rng.gauss(0.0, 1.0) for _ in range(4)]
z = [zp[i] + sum(low[i][k] * w[k] for k in range(4)) for i in range(4)]
inside += mahalanobis_sq(mean, cov, z) <= CHI2_95_4DOF
assert abs(inside / trials - 0.95) < 0.015
def test_box_round_trip_and_iou_values():
b = (4.0, 0.0, 14.0, 20.0)
assert box_to_xyah(b) == [9.0, 10.0, 0.5, 20.0]
assert xyah_to_box(box_to_xyah(b)) == b
assert iou(tuple(map(Fraction, (0, 0, 2, 2))), tuple(map(Fraction, (1, 1, 3, 3)))) == Fraction(1, 7)
assert iou(tuple(map(Fraction, (0, 0, 10, 10))), tuple(map(Fraction, (5, 0, 15, 10)))) == Fraction(1, 3)
def test_gallery_distance_is_the_minimum():
gallery = [[1.0, 0.0], [0.0, 1.0]]
assert abs(gallery_distance(gallery, [0.6, 0.8]) - 0.2) < 1e-12
assert abs(gallery_distance(gallery, [12.0, 5.0]) - 1.0 / 13.0) < 1e-12
def brute_min_cost(cost, allowed, rows, cols):
"""The rule of min_cost_matching by search: a full assignment of least cost,
where a forbidden pair costs 1 more than the largest allowed cost."""
vals = {(i, j): cost(i, j) for i in rows for j in cols if allowed(i, j)}
top = max(vals.values(), default=0.0) + 1.0
k = min(len(rows), len(cols))
best = None
for rs in itertools.permutations(rows, k):
for cs in itertools.combinations(cols, k):
total = sum(vals.get((i, j), top) for i, j in zip(rs, cs))
if best is None or total < best:
best = total
return best, top
def test_min_cost_matching_against_brute_force():
rng = random.Random(9)
for _ in range(150):
n, m = rng.randint(1, 4), rng.randint(1, 4)
c = [[rng.random() for _ in range(m)] for _ in range(n)]
ok = [[rng.random() < 0.7 for _ in range(m)] for _ in range(n)]
rows, cols = list(range(n)), list(range(m))
matches, fr, fc = min_cost_matching(lambda i, j: c[i][j], lambda i, j: ok[i][j], rows, cols)
best, top = brute_min_cost(lambda i, j: c[i][j], lambda i, j: ok[i][j], rows, cols)
k = min(n, m)
got = sum(c[i][j] for i, j in matches) + top * (k - len(matches))
assert abs(got - best) < 1e-9
assert all(ok[i][j] for i, j in matches)
assert sorted(fr + [i for i, _ in matches]) == rows
assert sorted(fc + [j for _, j in matches]) == cols
def test_hungarian_against_brute_force():
rng = random.Random(2)
for _ in range(100):
n, m = rng.randint(1, 5), rng.randint(1, 5)
c = [[rng.random() for _ in range(m)] for _ in range(n)]
pairs = hungarian_min(c)
if n <= m:
best = min(sum(c[i][j] for i, j in enumerate(p)) for p in itertools.permutations(range(m), n))
else:
best = min(sum(c[i][j] for j, i in enumerate(p)) for p in itertools.permutations(range(n), m))
assert abs(sum(c[i][j] for i, j in pairs) - best) < 1e-9
def test_page_example_cascade_priority_and_lost_pair():
# Track 0 was updated one frame ago, track 1 two frames ago. Detections a = 0, b = 1.
c = {(0, 0): 0.10, (0, 1): 0.12, (1, 0): 0.05}
cost = lambda i, j: c[(i, j)] # noqa: E731
allowed = lambda i, j: (i, j) in c # noqa: E731
matches, um_tracks, free = matching_cascade({0: 1, 1: 2}, cost, allowed, [0, 1], 30)
assert matches == [(0, 0)] and um_tracks == [1] and free == [1]
# One assignment over both tracks keeps two pairs, at total cost 0.17.
flat, _, _ = min_cost_matching(cost, allowed, [0, 1], [0, 1])
assert sorted(flat) == [(0, 1), (1, 0)]
assert abs(sum(c[p] for p in flat) - 0.17) < 1e-12
def test_uncertain_track_has_a_wider_gate():
# The same offset has a smaller Mahalanobis distance for a track that was
# predicted more times without an update, which is why the cascade is needed.
mean, cov = kf_initiate(box_to_xyah((100.0, 50.0, 120.0, 90.0)))
for k in range(1, 6):
mean, cov = kf_predict(mean, cov)
mean, cov = kf_update(mean, cov, box_to_xyah((100.0 + 2 * k, 50.0, 120.0 + 2 * k, 90.0)))
dists = []
m2, c2 = mean, cov
for _ in range(10):
m2, c2 = kf_predict(m2, c2)
dists.append(mahalanobis_sq(m2, c2, [m2[0] + 10.0, m2[1] + 10.0, m2[2], m2[3]]))
assert all(a > b for a, b in zip(dists, dists[1:]))
# The page example: about 15.0 after one prediction, 9.0 after two, 1.0 after ten.
assert dists[0] > CHI2_95_4DOF > dists[1]
assert abs(dists[0] - 14.98) < 0.01 and abs(dists[1] - 8.99) < 0.01 and abs(dists[9] - 1.03) < 0.01
assert all(abs(cov[i][j] - cov[j][i]) < 1e-9 for i in range(8) for j in range(8))
def unit(v):
n = math.sqrt(sum(x * x for x in v))
return [x / n for x in v]
def make_sequence(seed, hide=range(10, 20)):
"""Two people, 20 by 40 boxes, 40 frames, 8-dim embeddings.
Person 0 walks right at 2 pixels per frame and is not detected in the frames
in `hide`. Person 1 stands at x = 60 to 80 and walks down slowly.
"""
rng = random.Random(seed)
base = [unit([rng.gauss(0, 1) for _ in range(8)]) for _ in range(2)]
frames, truth = [], []
for f in range(40):
gt = [(10.0 + 2 * f, 50.0, 30.0 + 2 * f, 90.0), (60.0, 52.0 + 0.2 * f, 80.0, 92.0 + 0.2 * f)]
dets = []
for k, b in enumerate(gt):
if k == 0 and f in hide:
continue
box = tuple(x + rng.gauss(0.0, 0.7) for x in b)
emb = unit([x + rng.gauss(0.0, 0.05) for x in base[k]])
dets.append((box, emb))
rng.shuffle(dets)
frames.append(dets)
truth.append(gt)
return frames, truth
def run(tracker, frames, truth):
ids = {0: set(), 1: set()}
for f, dets in enumerate(frames):
for tid, box in tracker.step(dets):
best = max(range(2), key=lambda k: iou(box, truth[f][k]))
assert iou(box, truth[f][best]) > 0.5
ids[best].add(tid)
return ids
def test_reidentifies_after_occlusion():
# Person 0 passes behind person 1 and is not detected for 10 frames.
frames, truth = make_sequence(4)
tr = DeepSortTracker()
ids = run(tr, frames, truth)
assert len(ids[0]) == 1 and len(ids[1]) == 1 and ids[0] != ids[1]
assert tr.next_id == 3
assert all(t.state == CONFIRMED for t in tr.tracks)
def test_short_memory_loses_the_identity():
# With max_age = 1, as in SORT, the same occlusion gives person 0 a new identity.
frames, truth = make_sequence(4)
ids = run(DeepSortTracker(max_age=1), frames, truth)
assert len(ids[0]) == 2 and len(ids[1]) == 1
def test_tentative_track_needs_n_init_hits():
tr = DeepSortTracker()
det = ((0.0, 0.0, 10.0, 20.0), [1.0, 0.0])
assert tr.step([det]) == []
assert tr.step([det]) == []
out = tr.step([det])
assert len(out) == 1 and out[0][0] == 1
# A tentative track that misses one frame is deleted.
tr2 = DeepSortTracker()
tr2.step([det])
tr2.step([])
assert tr2.tracks == []
def test_gallery_budget():
tr = DeepSortTracker(budget=5)
rng = random.Random(1)
for f in range(12):
tr.step([((f * 1.0, 0.0, f + 10.0, 20.0), unit([1.0, rng.uniform(-0.01, 0.01)]))])
assert len(tr.tracks) == 1 and len(tr.tracks[0].gallery) == 5
History
In 2017, Wojke, Bewley and Paulus extended SORT with a deep association metric. The network was a wide residual network that gives a 128-dimensional embedding, trained on the MARS person re-identification data, with over 1,100,000 images of 1,261 pedestrians. They reported on MOT16 that the identity switches fell from 1423 for SORT to 781, with MOTA 61.4 against 59.8 for SORT. The paper presents the matching cascade as a way to give priority to the objects seen more often. Deep SORT became the base of many later trackers, which keep its structure and change the detector, the network or the motion model.
References
- Nicolai Wojke, Alex Bewley and Dietrich Paulus, Simple online and realtime tracking with a deep association metric, IEEE International Conference on Image Processing (ICIP), 2017, 3645-3649 (arXiv:1703.07402), Section 2.1 (the state and track handling), Section 2.2 (the Mahalanobis gate, the gallery and the combined cost), Section 2.3 and Listing 1 (the matching cascade), Section 2.4 (the network), Section 3 (MOT16 results)
- Alex Bewley, Zongyuan Ge, Lionel Ott, Fabio Ramos and Ben Upcroft, Simple online and realtime tracking, ICIP 2016, 3464-3468 (arXiv:1602.00763), Section 3 (the SORT tracker that Deep SORT extends)
- R. E. Kalman, A new approach to linear filtering and prediction problems, Journal of Basic Engineering 82(1), 1960, 35-45, the recursive linear estimator used for each track
- Harold W. Kuhn, The Hungarian method for the assignment problem, Naval Research Logistics Quarterly 2(1-2), 1955, 83-97, the whole paper (the assignment in each stage)
- Anton Milan, Laura Leal-Taixe, Ian Reid, Stefan Roth and Konrad Schindler, MOT16: a benchmark for multi-object tracking, arXiv:1603.00831, 2016, the benchmark of the Deep SORT experiments
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag Q69QVS Edit this page History Report an error Markdown