Algorithm Search⌘K

Algorithmresearch

ByteTrack

Also called BYTE association.

Associate high-score detections to tracks first, then match the remaining tracks to low-score detections, recovering occluded objects that a threshold drops.

Time
O(N n m (n + m)) worst
Space
O(n m) extra
Where
N = the number of frames; m = the number of detections in a frame; n = the number of tracks
Properties
deterministicnot exactnot iterativeonline
Origin
Yifu Zhang, Peize Sun, Yi Jiang, Dongdong Yu, Fucheng Weng, Zehuan Yuan, Ping Luo, Wenyu Liu, Xinggang Wang, 2022

ByteTrack is a multi-object tracker of the tracking by detection kind, built on the SORT scheme of a Kalman filter per track and an IoU assignment per frame. Its association step, called BYTE, uses every detection box. Other trackers drop the boxes whose detector score is below a threshold, but an object that is partly hidden often gets exactly such a low score. BYTE first matches the tracks with the high-score boxes, then matches the tracks still unmatched with the low-score boxes, and treats the low boxes that match no track as background. A low box can keep a track alive but can never start one. Compared with Deep SORT, ByteTrack needs no appearance network and has no cascade; compared with SORT, it keeps lost tracks for 30 frames and adds the second round.

In plain words

A detector gives each box a score that says how sure it is. Most trackers throw away the boxes with a low score, because many of them are wrong. But when a person walks behind a car, the detector still sees part of the person and gives a box with a low score. ByteTrack keeps those boxes for a second look. First it pairs the tracks with the boxes it trusts. Then, for each track that found no box, it looks at the doubtful boxes and takes one only if it overlaps the predicted place well. A doubtful box that no track wants is thrown away and never starts a new track. In this way the hidden person keeps a track, and wrong boxes do not create false tracks.

The problem

The input is that of the SORT tracker, and each detection also has a score s∈[0,1]s \in [0, 1] from the detector. Boxes are (x1,y1,x2,y2)(x_1, y_1, x_2, y_2) with area (x2−x1)(y2−y1)(x_2 - x_1)(y_2 - y_1). The output of each frame is a list of (identity, box) pairs, and the tracker is online.

The split. With the threshold τ\tau, the high detections are Dhigh={d:s>τ}D_{\text{high}} = \{d : s > \tau\} and the low detections are Dlow={d:smin⁡<s≤τ}D_{\text{low}} = \{d : s_{\min} < s \le \tau\}. The paper uses τ=0.6\tau = 0.6. The released code drops boxes with s≤0.1s \le 0.1, so smin⁡=0.1s_{\min} = 0.1.

The tracks. A track holds a Kalman filter on center, aspect ratio and height with their velocities, the same filter as in Deep SORT. Its state is tracked if it was matched in the last frame, lost if not. A lost track is kept for 30 frames and then removed. A new track is unconfirmed until it is matched in the next frame.

The matching. Each association step on tracks RR and detections CC with an IoU bound β\beta returns a matching of largest total weight ∑(IoU(i,j)−β)\sum (\mathrm{IoU}(i, j) - \beta), using only pairs with IoU(i,j)≥β\mathrm{IoU}(i, j) \ge \beta. This is a maximum weight matching in a bipartite graph. The released code computes it with the Jonker-Volgenant algorithm with a cost limit of 1−β1 - \beta on the cost 1−IoU1 - \mathrm{IoU}. A cost limit is built by extending the matrix with dummy rows and columns, and that extension gives a matching of the same largest weight.

The algorithm

  1. BYTE-STEP(the tracks, the detections (d_j, s_j), τ, s_min)
  2. 1D_high ← {j : s_j > τ}; D_low ← {j : s_min < s_j ≤ τ}
  3. 2for each track: Kalman predict
  4. 3match the tracked and lost tracks with D_high by IoU, bound 0.2; update the matched tracks
  5. 4match the tracked tracks still unmatched with D_low by IoU, bound 0.5; update the matched tracks
  6. 5the tracked tracks still unmatched become lost; remove lost tracks older than 30 frames; drop the rest of D_low
  7. 6match the unconfirmed tracks with the rest of D_high by IoU, bound 0.3; remove the unconfirmed tracks that miss
  8. 7for each detection j left in D_high with s_j ≥ τ + 0.1: start an unconfirmed track
  9. 8output the confirmed tracks updated in this frame

Lines L1 to L5 and the start of new tracks from the unmatched high boxes are Algorithm 1 of the paper. The paper rejects a pair of the first round with IoU below 0.2 and keeps lost tracks for 30 frames. The bounds 0.5 and 0.3 of lines L4 and L6, the floor smin⁡=0.1s_{\min} = 0.1, the start threshold τ+0.1\tau + 0.1 and the unconfirmed state are from the released code. A track is confirmed at once in the first frame of a video. The paper allows an appearance similarity in the first round when the tracker has one, but it uses IoU only in the second round, because low boxes often show an occluded or blurred object whose appearance is not reliable.

Example

One frame. Two confirmed tracks predict the boxes A=(0,0,10,20)A = (0, 0, 10, 20) and B=(30,0,40,20)B = (30, 0, 40, 20). The detector gives three boxes:

box score set
(31,1,41,21)(31, 1, 41, 21) 0.9 high
(2,0,12,20)(2, 0, 12, 20) 0.4 low
(80,80,90,100)(80, 80, 90, 100) 0.15 low

In the first round, the only high box has IoU 171/229≈0.747171/229 \approx 0.747 with BB (an overlap of 9×19=1719 \times 19 = 171 and a union of 400−171=229400 - 171 = 229) and 0 with AA, so BB takes it. In the second round, track AA meets the low boxes. The box (2,0,12,20)(2, 0, 12, 20) has IoU 160/240=2/3≥0.5160/240 = 2/3 \ge 0.5 with AA, so AA takes it. The box at (80,80)(80, 80) matches nothing and is dropped, and it does not start a track. Both tracks are reported. A tracker that drops the low boxes, here the same code without line L4, reports only BB, and track AA becomes lost.

A short sequence. Two people walk for 40 frames. Person 0 is half hidden in frames 12 to 21, where the detector gives a correct box with score 0.3. Weak false boxes with score 0.2 appear now and then. ByteTrack reports both people in all 40 frames with one identity each. Without the second round, person 0 is not reported in the 10 hidden frames. In this case the lost track is found again in frame 22 by the first round, because it is kept for 30 frames, so the identity is the same; with a memory of 5 frames, person 0 gets a new identity. The false boxes never start a track in either version.

Correctness

ByteTrack is a heuristic tracker. The proved parts are about one frame. The proofs are in proofs/correctness.md.

  • Theorem: each round is a largest weight matching. The matching of each round has the largest total of IoU−β\mathrm{IoU} - \beta among all matchings that use only pairs with IoU≥β\mathrm{IoU} \ge \beta, and the method with a full assignment on the clipped weights computes it.
  • Theorem: the rounds are consistent. Over the frame, no track and no detection is matched twice.
  • Theorem: low boxes start nothing. A detection with score at most τ\tau never starts a track. So in a frame without high boxes the set of tracks can only shrink.
  • Theorem: BYTE only adds matches. For the same tracks and detections, the pairs of the first round are those of the same tracker without the second round, and the second round only adds pairs. So in one frame, the set of matched tracks of BYTE contains the set of the baseline.
  • Not proved. That a low box with a large IoU belongs to the object of the track, and not to a nearby object, is an assumption. The gains on MOT17 and MOT20 are benchmark results.
Proof: Why each BYTE round is a largest weight matching, why the rounds match nothing twice, why low boxes start no track, and why BYTE only adds matchesfull

Notation as on the page. In one frame, a round works on a set RR of tracks, a set CC of detections and a bound β∈(0,1)\beta \in (0, 1). Write IoU(i,j)\mathrm{IoU}(i, j) for the IoU between the predicted box of track ii and the box of detection jj, and wij=IoU(i,j)−βw_{ij} = \mathrm{IoU}(i, j) - \beta. A matching is a set of pairs in R×CR \times C in which no track and no detection appears twice. It is valid if every pair has wij≥0w_{ij} \ge 0. Its weight is W(M)=∑(i,j)∈MwijW(M) = \sum_{(i, j) \in M} w_{ij}. The claims are about the algorithm in one frame.

Claim 1: the computation of one round

Let σ\sigma be a full assignment of least total cost for the cost −max⁡(0,wij)-\max(0, w_{ij}) on R×CR \times C, and let M={(i,j)∈σ:wij≥0}M = \{(i, j) \in \sigma : w_{ij} \ge 0\}. Then MM is a valid matching of largest weight.

Proof. MM is a subset of an assignment, so it is a matching, and it is valid by its definition. Let wij+=max⁡(0,wij)w^+_{ij} = \max(0, w_{ij}). For any valid matching M′M', extend it to a full assignment τ\tau by adding pairs between the rows and columns it does not use; the added pairs have w+≥0w^+ \ge 0, so ∑τw+≥∑M′w+=W(M′)\sum_\tau w^+ \ge \sum_{M'} w^+ = W(M'), since w+=ww^+ = w on valid pairs. By the optimality of σ\sigma (Claim 1 of the SORT proof on the Hungarian algorithm), ∑σw+≥∑τw+≥W(M′)\sum_\sigma w^+ \ge \sum_\tau w^+ \ge W(M'). The pairs of σ\sigma with wij<0w_{ij} < 0 have w+=0w^+ = 0, so ∑σw+=∑Mw=W(M)\sum_\sigma w^+ = \sum_M w = W(M). Hence W(M)≥W(M′)W(M) \ge W(M'). □\square

The tests compare the result with a search over all valid matchings of up to 4 tracks and 4 detections, for β=0.2\beta = 0.2 and β=0.5\beta = 0.5.

Claim 2: the cost limit of the released code gives the same matching

Use the cost cij=1−IoU(i,j)c_{ij} = 1 - \mathrm{IoU}(i, j) and the limit ℓ=1−β\ell = 1 - \beta, and extend the ∣R∣×∣C∣|R| \times |C| matrix to a square matrix of size ∣R∣+∣C∣|R| + |C| with ∣C∣|C| new rows and ∣R∣|R| new columns. The entries of the new rows in real columns and of real rows in new columns are ℓ/2\ell / 2, and the block where new rows meet new columns is 0. A full assignment of this matrix that matches kk real pairs MM costs

∑(i,j)∈Mcij+ℓ2(∣R∣−k)+ℓ2(∣C∣−k)=ℓ2(∣R∣+∣C∣)−∑(i,j)∈M(ℓ−cij),\sum_{(i, j) \in M} c_{ij} + \frac{\ell}{2}(|R| - k) + \frac{\ell}{2}(|C| - k) = \frac{\ell}{2}(|R| + |C|) - \sum_{(i, j) \in M} (\ell - c_{ij}),

and ℓ−cij=IoU(i,j)−β=wij\ell - c_{ij} = \mathrm{IoU}(i, j) - \beta = w_{ij}. So a least cost assignment of the extended matrix gives a matching of largest ∑Mwij\sum_M w_{ij}. If such a matching has a pair with wij<0w_{ij} < 0, removing the pair raises the weight, so an optimal matching has only pairs with wij≥0w_{ij} \ge 0, and pairs with wij=0w_{ij} = 0 do not change the weight. The real pairs of the optimum are therefore a valid matching of largest weight, as in Claim 1.

Proof of the cost formula. Every real row is matched either to a real column or to a new column, at cost cijc_{ij} or ℓ/2\ell / 2. The ∣R∣−k|R| - k real rows not in MM pay ℓ/2\ell / 2 each. Every real column not in MM is taken by a new row, at cost ℓ/2\ell / 2, which gives (∣C∣−k) ℓ/2(|C| - k)\, \ell / 2. The other new rows and new columns meet in the zero block. □\square

A solver with a cost limit, as the released code calls through the Jonker-Volgenant solver, can be built by this extension. The two methods can differ only in the choice between matchings of the same weight.

Claim 3: no track and no detection is matched twice

Proof. Each round returns a matching by Claim 1. The rows of the rounds are disjoint: line L3 uses the confirmed tracks, line L4 only the confirmed tracks that line L3 left unmatched, and line L6 only the unconfirmed tracks. The detections of line L3 and line L6 are high, and line L6 uses only the high detections that line L3 left. The detections of line L4 are low, a set disjoint from the high ones by the split of line L1. □\square

Claim 4: a low box never starts a track

A detection with score s≤τs \le \tau never starts a track. If a frame has no detection with score above τ\tau, no track is created in it.

Proof. New tracks are created only in line L7, which iterates over detections left in DhighD_{\text{high}}, all with s>τs > \tau. A low detection is in DlowD_{\text{low}} or dropped in line L1, and line L5 drops the low detections that line L4 did not match. If DhighD_{\text{high}} is empty, line L7 does nothing. □\square

With the start threshold τ+0.1\tau + 0.1 of the released code, a high box with score in (τ,τ+0.1)(\tau, \tau + 0.1) also starts no track; it can only extend one.

Claim 5: BYTE only adds matches

Fix the tracks before line L3 and the detections of the frame. Let BB be the same procedure without line L4. Then the pairs of line L3 are the same in BYTE and in BB, and the set of tracks matched in the frame by BYTE contains the set matched by BB.

Proof. Line L3 depends only on the predicted tracks and on DhighD_{\text{high}}, which are the same in both, so (with the same tie rule of the solver) it returns the same pairs. In BB, line L6 uses the same unconfirmed tracks and the same high detections left by line L3, so it returns the same pairs as in BYTE, since line L4 uses neither unconfirmed tracks nor high detections. BYTE adds the pairs of line L4, which involve tracks that are unmatched in BB. □\square

The claim is about one frame. Over many frames the states of the two trackers differ, so the claim does not compare whole runs. The occlusion sequence of the page shows a case where BYTE reports the hidden person in 10 more frames.

Complexity

Let nn be the number of tracks and mm the number of detections, in the real RAM model. The IoU values cost O(nm)O(n m). Each round is an assignment of at most nn tracks and mm detections, which the Hungarian or Jonker-Volgenant method solves in O(nm(n+m))O(n m (n + m)) time. The Kalman steps cost O(n+m)O(n + m), since the filter has a fixed size. One frame costs O(nm(n+m))O(n m (n + m)) time and O(nm)O(n m) extra space, and NN frames cost NN times that. The paper reports 30 frames per second for the whole system on one V100 GPU, almost all of it in the detector; that is a benchmark result.

Properties

  • Online. The output of a frame never changes later.
  • No appearance needed. The benchmark version of the paper uses IoU in both rounds.
  • Asymmetric use of scores. Low boxes can extend tracks but cannot start them, so lowering τ\tau does not by itself create false tracks.
  • Detector dependent. The scores must be calibrated in the sense that the boxes of hidden objects get low but nonzero scores. The method helps less with a detector that suppresses such boxes.

Variants and improvements

  • Appearance in the first round. The paper shows that BYTE can replace the association of trackers with an appearance model, such as FairMOT, and keep their appearance score in the first round. It reports IDF1 gains of 1 to 10 points on nine trackers, which is a benchmark result.
  • Score fusion. The released code multiplies the IoU by the detection score in the first round on MOT17, so that strong boxes win ties.
  • Later trackers. BoT-SORT adds camera motion compensation and appearance, and OC-SORT changes the Kalman update after a lost period. Both keep the two rounds of BYTE.

When to use it

Use ByteTrack when the detector is strong but objects are often partly hidden, as in crowds, and when a fast tracker without an appearance network is wanted. It works best at high frame rates, where the IoU of an object with its own box in the next frame is large. Do not expect it to keep identities when objects are fully hidden for longer than the lost period, or when similar objects cross while hidden, since it has no appearance score by default. For long occlusions, add appearance, as in Deep SORT.

Pitfalls

  • Treating the thresholds as universal. The values 0.6, 0.2, 0.5, 0.3 and 0.1 are tuned for pedestrian benchmarks and one detector. A different detector has a different score scale.
  • Starting tracks from low boxes. That defeats the method: low boxes are mostly background, and only a match with an existing track makes them useful.
  • Using appearance in the second round. The appearance of a hidden or blurred object is not reliable, which is why the paper uses IoU there.
  • Low boxes from nearby objects. In a dense crowd a low box of one person can overlap the prediction of another. The bound 0.5 of the second round limits this but does not prevent it.
  • Comparing trackers with different detectors. Most of the score of a tracker on MOT17 comes from the detector. Compare association methods on the same detections, as the paper does in its ablations.

Implementations

The Python file follows Algorithm 1 of the paper with the values of the paper and of the released code. Each round is a largest weight matching computed by the Hungarian algorithm on the clipped weights. The tests compare the matching with a search over all matchings, check the frame of the example with exact IoU values, check that low boxes never start tracks, and compare BYTE with the same tracker without the second round on the occlusion sequence above.

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.

bytetrack.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bytetrack/. The authors are listed in prov/0E34WD.jsonl.
"""ByteTrack: the BYTE association of Zhang et al. (ECCV 2022), with IoU as the similarity.

A detection is (box, score). The detections of a frame are split by the
score threshold tau into high ones (score > tau) and low ones
(low_min < score <= tau); boxes with score <= low_min are dropped.

One frame:
  1. predict every track with a Kalman filter on (u, v, a, h) and velocities;
  2. first association: the confirmed tracks (tracked and lost) with the high
     detections, by IoU, rejecting pairs with IoU below 0.2;
  3. second association: the tracked tracks still unmatched with the low
     detections, by IoU, rejecting pairs with IoU below 0.5;
  4. tracked tracks still unmatched become lost; lost tracks older than
     max_lost frames are removed; low detections still unmatched are dropped;
  5. tracks started in the previous frame (unconfirmed) with the high
     detections left, IoU at least 0.3; unconfirmed tracks that miss are removed;
  6. each high detection left with score >= tau + 0.1 starts an unconfirmed track.

Each association is a largest weight matching with weight IoU - bound, which
is what the released code gets from lapjv with a cost limit. The thresholds
are the ones of the paper and its released code.
Boxes are (x1, y1, x2, y2), area (x2 - x1)(y2 - y1). Matrices are lists of rows.
"""

# ---------------------------------------------------------------- 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


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)


# ---------------------------------------------------------------- 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_update(mean, cov, z):
    h = mean[3]
    r = diag([s * s for s in (STD_POS * h, STD_POS * h, 1e-1, STD_POS * h)])
    ph = mat_mul(cov, transpose(H8))
    s = mat_add(mat_mul(H8, ph), r)
    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, mean[:4])]))]
    ikh = mat_sub(eye(8), mat_mul(k, H8))
    cov = mat_add(mat_mul(mat_mul(ikh, cov), transpose(ikh)), mat_mul(mat_mul(k, r), transpose(k)))
    return mean, cov


# ---------------------------------------------------------------- matching


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 iou_matching(boxes_a, boxes_b, rows, cols, iou_min):
    """A matching of rows to cols of largest total weight IoU - iou_min, using only
    pairs with IoU >= iou_min. Returns (matches, free rows, free cols)."""
    if not rows or not cols:
        return [], list(rows), list(cols)
    w = [[iou(boxes_a[i], boxes_b[j]) - iou_min for j in cols] for i in rows]
    picked = hungarian_min([[-max(0.0, x) for x in row] for row in w])
    matches = [(rows[a], cols[b]) for a, b in picked if w[a][b] >= 0]
    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]


# ---------------------------------------------------------------- tracks and tracker

NEW, TRACKED, LOST, REMOVED = 0, 1, 2, 3


class Track:
    def __init__(self, box, score, track_id, frame, confirmed):
        self.mean, self.cov = kf_initiate(box_to_xyah(box))
        self.id = track_id
        self.score = score
        self.state = TRACKED
        self.confirmed = confirmed
        self.last_frame = frame

    def box(self):
        return xyah_to_box(self.mean[:4])


class ByteTracker:
    """Call step(detections) once per frame; a detection is (box, score)."""

    def __init__(self, tau=0.6, low_min=0.1, iou_first=0.2, iou_second=0.5,
                 iou_unconfirmed=0.3, new_track_min=0.7, max_lost=30, use_low=True):
        self.tau = tau
        self.low_min = low_min
        self.iou_first = iou_first
        self.iou_second = iou_second
        self.iou_unconfirmed = iou_unconfirmed
        self.new_track_min = new_track_min
        self.max_lost = max_lost
        self.use_low = use_low  # False gives the baseline that drops the low boxes
        self.tracks = []
        self.frame = 0
        self.next_id = 1

    def _update(self, t, det):
        t.mean, t.cov = kf_update(t.mean, t.cov, box_to_xyah(det[0]))
        t.score = det[1]
        t.state = TRACKED
        t.confirmed = True
        t.last_frame = self.frame

    def step(self, detections):
        self.frame += 1
        tr = self.tracks
        boxes = [d[0] for d in detections]
        high = [j for j, d in enumerate(detections) if d[1] > self.tau]  # @line L1
        low = [j for j, d in enumerate(detections) if self.low_min < d[1] <= self.tau]
        for t in tr:  # @line L2
            if t.state != TRACKED:
                t.mean[7] = 0.0  # a lost track keeps its height, as in the released code
            t.mean, t.cov = kf_predict(t.mean, t.cov)
        pred = [t.box() for t in tr]
        pool = [i for i, t in enumerate(tr) if t.confirmed]
        m1, rest, high_left = iou_matching(pred, boxes, pool, high, self.iou_first)  # @line L3
        for i, j in m1:
            self._update(tr[i], detections[j])
        second = [i for i in rest if tr[i].state == TRACKED]
        m2 = []
        if self.use_low:
            m2, _, _ = iou_matching(pred, boxes, second, low, self.iou_second)  # @line L4
            for i, j in m2:
                self._update(tr[i], detections[j])
        done = {i for i, _ in m1 + m2}
        for i in second:  # @line L5
            if i not in done:
                tr[i].state = LOST
        for t in tr:
            if t.state == LOST and self.frame - t.last_frame > self.max_lost:
                t.state = REMOVED
        new = [i for i, t in enumerate(tr) if not t.confirmed]
        m3, miss, high_left = iou_matching(pred, boxes, new, high_left, self.iou_unconfirmed)  # @line L6
        for i, j in m3:
            self._update(tr[i], detections[j])
        for i in miss:
            tr[i].state = REMOVED
        for j in high_left:  # @line L7
            if detections[j][1] >= self.new_track_min:
                tr.append(Track(boxes[j], detections[j][1], self.next_id, self.frame, self.frame == 1))
                self.next_id += 1
        self.tracks = [t for t in tr if t.state != REMOVED]
        # @line L8
        return [(t.id, t.box()) for t in self.tracks if t.state == TRACKED and t.confirmed]
test_bytetrack.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bytetrack/. The authors are listed in prov/0E34WD.jsonl.

import itertools
import random
from fractions import Fraction

from bytetrack import ByteTracker, iou, iou_matching


def brute_best_weight(boxes_a, boxes_b, rows, cols, iou_min):
    """Largest total of IoU - iou_min over all matchings that use pairs with IoU >= iou_min."""
    best = 0.0
    for k in range(1, min(len(rows), len(cols)) + 1):
        for rs in itertools.combinations(rows, k):
            for cs in itertools.permutations(cols, k):
                ws = [iou(boxes_a[i], boxes_b[j]) - iou_min for i, j in zip(rs, cs)]
                if all(w >= 0 for w in ws):
                    best = max(best, sum(ws))
    return best


def test_iou_values():
    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_matching_against_brute_force():
    rng = random.Random(8)
    for _ in range(150):
        a = []
        for _ in range(rng.randint(1, 4)):
            x, y = rng.uniform(0, 30), rng.uniform(0, 30)
            a.append((x, y, x + 10, y + 10))
        b = []
        for _ in range(rng.randint(1, 4)):
            x, y = rng.uniform(0, 30), rng.uniform(0, 30)
            b.append((x, y, x + 10, y + 10))
        rows, cols = list(range(len(a))), list(range(len(b)))
        for bound in (0.2, 0.5):
            m, fr, fc = iou_matching(a, b, rows, cols, bound)
            assert all(iou(a[i], b[j]) >= bound for i, j in m)
            assert len({i for i, _ in m}) == len(m) == len({j for _, j in m})
            got = sum(iou(a[i], b[j]) - bound for i, j in m)
            assert abs(got - brute_best_weight(a, b, rows, cols, bound)) < 1e-9
            assert sorted(fr + [i for i, _ in m]) == rows and sorted(fc + [j for _, j in m]) == cols


def warm_up(tracker, boxes, frames=3):
    for _ in range(frames):
        tracker.step([(b, 0.9) for b in boxes])


def test_page_example_second_association():
    a_box, b_box = (0.0, 0.0, 10.0, 20.0), (30.0, 0.0, 40.0, 20.0)
    frame = [((31.0, 1.0, 41.0, 21.0), 0.9), ((2.0, 0.0, 12.0, 20.0), 0.4), ((80.0, 80.0, 90.0, 100.0), 0.15)]
    assert iou(tuple(map(Fraction, (0, 0, 10, 20))), tuple(map(Fraction, (2, 0, 12, 20)))) == Fraction(2, 3)
    assert iou(tuple(map(Fraction, (30, 0, 40, 20))), tuple(map(Fraction, (31, 1, 41, 21)))) == Fraction(171, 229)
    results = {}
    for use_low in (True, False):
        tr = ByteTracker(use_low=use_low)
        warm_up(tr, [a_box, b_box])
        out = tr.step(frame)
        results[use_low] = (sorted(tid for tid, _ in out), len(tr.tracks), tr.next_id)
    # BYTE keeps both tracks; the low box at (80, 80) starts nothing.
    assert results[True] == ([1, 2], 2, 3)
    # Without the second association, track 1 is lost and not reported.
    assert results[False] == ([2], 2, 3)


def test_low_boxes_never_start_tracks():
    rng = random.Random(3)
    tr = ByteTracker()
    for _ in range(20):
        dets = []
        for _ in range(rng.randint(0, 5)):
            x, y = rng.uniform(0, 500), rng.uniform(0, 500)
            dets.append(((x, y, x + 20, y + 40), rng.uniform(0.0, 0.6)))
        assert tr.step(dets) == []
    assert tr.tracks == [] and tr.next_id == 1


def make_occlusion(seed):
    """Two people, 20 by 40 boxes, 40 frames. Person 0 walks right at 2 pixels
    per frame and is half hidden in frames 12 to 21, where its score is 0.3."""
    rng = random.Random(seed)
    frames, truth = [], []
    for f in range(40):
        gt = [(10.0 + 2 * f, 50.0, 30.0 + 2 * f, 90.0), (200.0, 40.0 + 0.5 * f, 220.0, 80.0 + 0.5 * f)]
        dets = []
        for k, b in enumerate(gt):
            score = 0.3 if (k == 0 and 12 <= f <= 21) else rng.uniform(0.75, 0.95)
            dets.append((tuple(x + rng.gauss(0.0, 0.7) for x in b), score))
        if f % 7 == 3:
            x = rng.uniform(300, 400)
            dets.append(((x, 10.0, x + 20.0, 50.0), 0.2))  # a weak false box
        rng.shuffle(dets)
        frames.append(dets)
        truth.append(gt)
    return frames, truth


def run(tracker, frames, truth):
    ids = {0: set(), 1: set()}
    count = {0: 0, 1: 0}
    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)
            count[best] += 1
    return ids, count


def test_occlusion_low_scores_byte_against_baseline():
    frames, truth = make_occlusion(6)
    ids, count = run(ByteTracker(), frames, truth)
    assert ids == {0: {1}, 1: {2}}
    assert count == {0: 40, 1: 40}
    # The baseline that drops the low boxes misses person 0 for the 10 hidden frames.
    ids_b, count_b = run(ByteTracker(use_low=False), frames, truth)
    assert count_b == {0: 30, 1: 40}
    # The lost track is kept for 30 frames, so the first association finds it again.
    assert ids_b == {0: {1}, 1: {2}}


def test_lost_track_removed_after_max_lost():
    tr = ByteTracker(max_lost=5)
    warm_up(tr, [(0.0, 0.0, 10.0, 20.0)])
    for _ in range(5):
        tr.step([])
    assert len(tr.tracks) == 1
    tr.step([])
    assert tr.tracks == []

History

Trackers before ByteTrack, from SORT and Deep SORT on, kept only detections above a score threshold. In 2021 Zhang, Sun, Jiang, Yu, Weng, Yuan, Luo, Liu and Wang posted ByteTrack, published at ECCV 2022. They argued that low-score boxes hold the occluded objects and should be associated, not dropped. With the YOLOX detector, they reported 80.3 MOTA, 77.3 IDF1 and 63.1 HOTA on the MOT17 test set at 30 frames per second. The two rounds of BYTE were then taken up by many later trackers.

References

  1. Yifu Zhang, Peize Sun, Yi Jiang, Dongdong Yu, Fucheng Weng, Zehuan Yuan, Ping Luo, Wenyu Liu and Xinggang Wang, ByteTrack: multi-object tracking by associating every detection box, ECCV 2022, LNCS 13682, 1-21 (arXiv:2110.06864), Section 3 and Algorithm 1 (BYTE), Section 4.1 (the threshold 0.6, the IoU bound 0.2, lost tracks kept 30 frames), Section 4.2 (BYTE added to nine other trackers)
  2. 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 Kalman filter and IoU assignment that BYTE keeps)
  3. Nicolai Wojke, Alex Bewley and Dietrich Paulus, Simple online and realtime tracking with a deep association metric, ICIP 2017, 3645-3649 (arXiv:1703.07402), Section 2.1 (the Kalman filter on center, aspect ratio and height that the released ByteTrack code also uses)
  4. Roy Jonker and Anton Volgenant, A shortest augmenting path algorithm for dense and sparse linear assignment problems, Computing 38(4), 1987, 325-340, the whole paper (the assignment solver of the released code)
  5. 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 protocol used for MOT17 results

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example