AI Wiki中文/EN

Object tracking: keep the identity, not just the box

目标跟踪

Build a small tracker with Kalman prediction, global assignment and low-score recovery; compare identity metrics and inspect cyclic kernel correlation.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The boxes are right. Are the identities right?

Imagine a four-frame video with two people. Every predicted box fits perfectly. Halfway through, the tracker exchanges their labels: the person called 1 becomes 2, and the person called 2 becomes 1. A detector could receive full credit for those boxes. A system counting how long each person waited would produce the wrong histories.

Object tracking estimates an object’s changing location while preserving the intended correspondence through time. An identity here is a label within a tracking task; it need not identify a named person. The input and output contracts matter:

TaskGiven informationRequired result
Single-object trackingAn initial target, often a first-frame boxThat target’s later locations, with the task’s absence policy
Multiple-object trackingA video and target classes or detectionsLocations and persistent IDs, including births and departures
Point trackingQueried image pointsTheir trajectories and, where supported, visibility
Video object segmentationAn object prompt or other specified supervisionA changing mask, with correspondence across frames

A point is not a whole object, and a segmentation mask does not by itself define the benchmark’s identity policy. CoTracker, for example, jointly reasons about point trajectories rather than returning a set of person detection boxes. Point-tracking task

A useful starting baseline needs no learned tracker: compare a template with image patches, or associate supplied detections by overlap. These baselines expose different failures. A repeated texture produces multiple plausible template matches. Two objects passing each other can confuse an overlap-only association. An object that disappears cannot be located from a missing measurement alone.

Below, we build a complete small tracker from supplied detections and keep its failures visible. A separate template example works on raw pixels. The tracker includes motion uncertainty, global assignment, score thresholds and lifetimes; it does not contain a hidden detector or pretrained appearance network. Its identity example is synthetic, not a benchmark result.

Computed identity swaps, a missed low-score observation and cyclic alignment. Synthetic inputs; not benchmark performance.
Computed identity swaps, a missed low-score observation and cyclic alignment. Synthetic inputs; not benchmark performance.

From a patch to a persistent track

Single-object tracking: what should count as similar?

For a template z and a candidate patch x_u at offset u, zero-mean normalized correlation removes each patch’s mean and divides by its contrast:

r(u)=⟨z−zˉ, xu−xˉu⟩∥z−zˉ∥2 ∥xu−xˉu∥2.r(u)=\frac{\langle z-\bar z,\ x_u-\bar x_u\rangle} {\|z-\bar z\|_2\,\|x_u-\bar x_u\|_2}.

The denominator uses Euclidean norms. Positive changes of scale and additive brightness shifts leave this score unchanged when neither centered patch is zero. A constant template has no contrast to normalize; our function rejects it. Constant search patches receive zero. A score of 1 means perfect normalized agreement, not proof that this is the same physical object.

KCF takes a discriminative route. It trains kernel ridge regression using circular shifts of a template as training examples, with a desired response for each shift. Circular shifts wrap the boundary: content leaving one edge returns at the other. This is a computational model, not what every moving object does. The paper discusses padding and windows to reduce that artifact. Cyclic samples and regression

Let P shift a length-n signal by one position. A kernel that is invariant under simultaneously permuting both inputs preserves the circulant structure of these samples. For the Gaussian kernel, our one-dimensional implementation forms a kernel correlation over all shifts and solves the regression in the Fourier domain:

κ(x,z)=exp⁡ ⁣(−∥x−z∥22σ2),k(x,z)j=κ(x,Pjz),α^=y^k(x,x)^+λ,f=F−1 ⁣(α^⊙k(x,z)^).\begin{aligned} \kappa(x,z)&=\exp\!\left(-\frac{\|x-z\|_2^2}{\sigma^2}\right),& k(x,z)_j&=\kappa(x,P^jz),\\ \widehat\alpha&=\frac{\widehat y}{\widehat{k(x,x)}+\lambda},& f&=\mathcal F^{-1}\!\left(\widehat\alpha\odot\widehat{k(x,z)}\right). \end{aligned}

Here k(x,z)_j compares x with P^j z; hats denote the discrete Fourier transform, and all spectral products and divisions are elementwise. For the real Gaussian self-kernel, the training kernel matrix is symmetric, so this expression gives the usual real dual coefficients after the inverse transform. The output at j scores the candidate P^j z. If z was created by shifting x right by two places in a length-eight signal, the best alignment is j=6, not j=2. Our tests compare the entire FFT response with an independently constructed dense kernel matrix, including arbitrary regression targets.

The speedup comes from structure: an n×n kernel system becomes transforms and elementwise operations, O(n log n) time and O(n) working storage for this single-channel core. It is not a claim that every kernel permits a fast kernel correlation, or that a full image tracker costs only this operation. Our example omits image cropping, spatial windows, scale search and online model updates. Kernel conditions and fast correlation

SiamFC instead learns a shared embedding on pairs of video crops. A cross-correlation between template and search feature maps produces a grid of scores. With labels y_u equal to −1 or +1, the basic score-map objective is:

su=[ϕ(z)⋆ϕ(x)]u+b,L=1∣D∣∑u∈Dlog⁡ ⁣(1+e−yusu).s_u=[\phi(z)\star\phi(x)]_u+b,\qquad L=\frac1{|D|}\sum_{u\in D}\log\!\left(1+e^{-y_us_u}\right).

The paper also balances positive and negative examples. Its fully convolutional property concerns translations in the valid output region, with the network stride taken into account. In the described tracker, the learned model is not updated online and no appearance-history memory is maintained. Our normalized raw-pixel matcher is therefore a baseline with a different representation, not a tiny reproduction of SiamFC training. Shared features, loss and tracking procedure

Multiple objects: predict before looking for a match

SORT combines detections, a constant-velocity Kalman model, IoU association and track creation/deletion. Its seven-dimensional state models box center, area, aspect ratio and three velocities. Deep SORT uses an eight-dimensional center/aspect/height state and the corresponding velocities. These representations are not interchangeable coordinate labels. SORT state Deep SORT state

To inspect the calculation, our smaller state contains only center position and velocity. Width and height come from the latest matched box. For elapsed time Δt, define:

x=[cxcyvxvy] ⁣T,F=[I2ΔtI20I2],H=[I20].x=\begin{bmatrix}c_x&c_y&v_x&v_y\end{bmatrix}^{\!T},\quad F=\begin{bmatrix}I_2&\Delta t I_2\\0&I_2\end{bmatrix},\quad H=\begin{bmatrix}I_2&0\end{bmatrix}.

The state mean has four components; P is its 4×4 covariance. A linear Gaussian model assumes additive, zero-mean process and observation noise, with their specified covariances. Assuming independence of the new process noise and the previous state gives the prediction:

μ−=Fμ,P−=FPFT+Q,Q=qGGT,G=[12Δt2I2ΔtI2].\mu^-=F\mu,\qquad P^-=FPF^T+Q,\qquad Q=qGG^T,\quad G=\begin{bmatrix}\tfrac12\Delta t^2 I_2\\\Delta t I_2\end{bmatrix}.

Our Q assumes one independent constant random acceleration per axis during the interval, with variance q. It is not the continuous-white-noise spectral-density formula, which has different powers of Δt. Larger gaps increase position uncertainty. This does not make a constant-velocity mean accurate during a turn or camera jump.

For a center measurement z, innovation covariance S includes both predicted uncertainty and measurement noise R. The Kalman gain weights the innovation. The covariance update uses the Joseph form:

S=HP−HT+R,K=P−HTS−1,μ+=μ−+K(z−Hμ−),P+=(I−KH)P−(I−KH)T+KRKT.\begin{aligned} S&=HP^-H^T+R,&K&=P^-H^TS^{-1},\\ \mu^+&=\mu^-+K(z-H\mu^-),\\ P^+&=(I-KH)P^-(I-KH)^T+KRK^T. \end{aligned}

The mean update corrects both position and velocity because prediction creates their cross-covariance. Setting R to zero would treat the measurement as exact; our implementation requires a positive scalar measurement variance. Tests compare this update with an independently computed Gaussian posterior in information form. The code uses linear solves, not an explicit inverse for its gain. The fixed Deep SORT implementation instead uses an eight-dimensional model with noise scales tied to box height; our parameters do not reproduce its filter. Actual Deep SORT initialization

Similarity, gates and one-to-one assignment

IoU compares overlap with union area. A motion gate can additionally reject implausible measurements using squared Mahalanobis distance. Deep SORT combines motion information with a gallery of normalized appearance descriptors:

dmotion(i,j)=(zj−Hμi)TSi−1(zj−Hμi),dappearance(i,j)=min⁡g∈Gi(1−rjTg).d_{\rm motion}(i,j)=(z_j-H\mu_i)^TS_i^{-1}(z_j-H\mu_i),\qquad d_{\rm appearance}(i,j)=\min_{g\in\mathcal G_i}(1-r_j^Tg).

In this notation g is a unit descriptor stored for track i, and r_j is the new unit descriptor. The minimum cosine distance searches that track’s gallery. These features require a suitable learned representation; assigning an arbitrary vector does not create re-identification ability. Deep SORT’s four-dimensional observation gate uses 9.4877 for its stated 95% chi-square threshold. That value should not be pasted into our two-dimensional center model. Its experiments can set the motion weight in the association cost to zero while still retaining the motion gate. Appearance and motion gates

Association is a one-to-one decision. Picking each track’s favorite detection independently can assign two tracks to the same box. For eligible pairs E and binary decisions a_ij, our teaching tracker uses a lexicographic objective:

lexmax⁡a(∑ijaij, ∑ijaijsij),aij∈{0,1},∑jaij≤1,∑iaij≤1,aij=0 if (i,j)∉E.\operatorname{lexmax}_{a}\left(\sum_{ij}a_{ij},\ \sum_{ij}a_{ij}s_{ij}\right),\quad a_{ij}\in\{0,1\},\quad\sum_j a_{ij}\le1,\quad\sum_i a_{ij}\le1,\quad a_{ij}=0\text{ if }(i,j)\notin E.

It first maximizes the number of eligible matches, then their summed similarity. Unmatched tracks and detections are allowed. We implement this using dummy assignments and a match bonus larger than any possible change in total similarity, then solve a rectangular minimum-cost assignment by primal/dual augmenting paths. The solver costs O(min(n,m)^2 max(n,m)); padding for the gated problem gives an O((n+m)^3) bound.

This objective is a choice. With similarities [[0.9,0.6],[0.6,0.49]] and threshold 0.5, unrestricted maximum-sum matching chooses the diagonal, whose sum is 1.39. Rejecting the 0.49 pair afterward leaves one match. Gating first allows the two off-diagonal matches, totaling 1.2. One method cannot be substituted for the other without changing behavior.

Deep SORT also uses a cascade: more recently observed tracks get first access to detections. As uncertainty grows, Mahalanobis distance alone can favor an older, broader distribution. The cascade encodes a preference that a single global solve does not capture. A final IoU stage handles specified unmatched and unconfirmed tracks. Our small tracker does not implement that appearance cascade. Matching cascade

Low confidence is not the same as no evidence

ByteTrack associates high-score detections first, then uses low-score detections to recover remaining tracks. Unmatched low-score detections do not create new identities. Its paper argues for IoU in the second stage because appearance can be unreliable under occlusion or blur. It also explains lost-track retention and rebirth that the compact pseudocode omits. Two stages and lifetimes

Our example makes its own boundaries explicit: score at least 0.6 enters the first stage; scores from 0.1 inclusive to 0.6 exclusive enter the second. The low-score stage serves only tracks observed in the immediately previous frame. Tentative tracks require repeated hits, missing confirmed tracks are retained for a limited number of frames, and predictions without a matched detection are not emitted.

The pinned ByteTrack code uses different boundary rules: high scores are strictly greater than track_thresh, low scores are strictly greater than 0.1 and strictly less than track_thresh, and initializing a new track uses track_thresh+0.1. A score exactly equal to track_thresh therefore falls into neither of those two input groups in that version. These details matter when reproducing a method. Pinned threshold and lifecycle code

A detector followed by hand-designed association is not the only architecture. MOTR carries track queries between frames inside a Transformer and trains the tracking process with sequence supervision. Detection queries can introduce new instances while track queries carry existing ones. This moves correspondence into a learned state-update mechanism; it does not remove the need to define supervision, disappearance and identity evaluation. Track queries and sequence learning

Evaluate identities, not only visible boxes

After the specified matching procedure, let N_GT be the total number of ground-truth detections. MOTA penalizes false negatives, false positives and identity switches:

MOTA=1−FN+FP+IDSWNGT.\mathrm{MOTA}=1-\frac{\mathrm{FN}+\mathrm{FP}+\mathrm{IDSW}}{N_{\rm GT}}.

It can be negative. It is undefined when N_GT is zero; our function returns None then. Switch counting also has a memory convention: our evaluator remembers the last successful match across gaps, but resets the previous-frame preference every frame. The pinned CLEAR implementation’s early returns for wholly empty sides preserve some previous-frame state instead. Our function is not a drop-in replacement for that benchmark implementation. CLEAR matching and counters

IDF1 asks for a global one-to-one mapping between ground-truth and predicted identities. For each candidate identity pair, count simultaneous detections meeting the spatial threshold, before any per-frame one-to-one assignment. Choose a global mapping that maximizes the retained correct detections. With their count IDTP:

IDFN=NGT−IDTP,IDFP=Npred−IDTP,IDF1=2IDTP2IDTP+IDFN+IDFP.\mathrm{IDFN}=N_{\rm GT}-\mathrm{IDTP},\quad \mathrm{IDFP}=N_{\rm pred}-\mathrm{IDTP},\quad \mathrm{IDF1}=\frac{2\mathrm{IDTP}}{2\mathrm{IDTP}+\mathrm{IDFN}+\mathrm{IDFP}}.

For an entirely empty sequence, our IDF1 convention is zero. N_pred counts all predicted detections, so unmatched identities still contribute error. This is different from summing the matches chosen by a detector metric frame by frame. The paper derives the equivalent minimum-cost identity assignment; the reference implementation explicitly accumulates eligible pair counts before assigning identities. Global identification measure Reference identity implementation

HOTA combines detection and association. At one localization threshold α, let c_gp count matched detections for identity pair (g,p), and let n_g and n_p count all detections belonging to those two identities. Their association Jaccard score penalizes both fragmentation and merging:

Agp=cgpng+np−cgp,AssAα=∑gpcgpAgpTP,DetAα=TPTP+FN+FP,HOTAα=DetAαAssAα.\begin{aligned} A_{gp}&=\frac{c_{gp}}{n_g+n_p-c_{gp}},& \mathrm{AssA}_\alpha&=\frac{\sum_{gp}c_{gp}A_{gp}}{\mathrm{TP}},\\ \mathrm{DetA}_\alpha&=\frac{\mathrm{TP}}{\mathrm{TP}+\mathrm{FN}+\mathrm{FP}},& \mathrm{HOTA}_\alpha&=\sqrt{\mathrm{DetA}_\alpha\mathrm{AssA}_\alpha}. \end{aligned}

With no true positives, our implementation sets AssA and HOTA to zero. The average is weighted by matched detections, not equally by identity pairs. Unmatched detections remain in the trajectory counts and in detection error denominators. The final HOTA averages the per-threshold scores:

HOTA=119∑k=119HOTAk/20.\mathrm{HOTA}=\frac1{19}\sum_{k=1}^{19}\mathrm{HOTA}_{k/20}.

The paper’s matching description prioritizes eligible true positives, association and localization, separately at each threshold. The pinned TrackEval implementation instead computes a sequence-level soft alignment, multiplies it by each frame’s similarities, solves that frame’s assignment once, and filters those pairs at nineteen thresholds. Our HOTA calculation follows that pinned implementation convention. The common score formulas do not make the two matching descriptions identical. Association formulas and paper matching Actual HOTA matching

In the four-frame identity swap, all eight boxes match. There are two switches, giving MOTA=0.75. Any global identity mapping retains only four detections, giving IDF1=0.5. For each of the four occurring identity pairs, c_gp=2 and n_g=n_p=4, so its association score is 2/(4+4−2)=1/3. DetA is 1 and HOTA is about 0.57735. “75% tracking accuracy” would hide what these numbers mean.

Run the association and inspect the failures

The complete program uses Python 3.12.4 and NumPy 1.26.4. Boxes are continuous xyxy coordinates with positive width and height; touching edges have zero IoU. Inputs must be finite, timestamps strictly increase, and each frame maps an integer identity to at most one box. Scores and coordinates are supplied; there is no detector training. Covariance inputs to the standalone filter functions are assumed to be valid symmetric positive-semidefinite matrices.

The default tracker requires two hits to confirm an identity. The printed comparison explicitly uses one hit so that initialization delay does not obscure the effect of dropping the third frame. The low-score example has a missed output when filtered, but no identity switch: the retained motion track is recovered on the next high-score observation. Neither outcome is guaranteed on real videos.

"""Original NumPy teaching tracker and single-class sequence metrics.

Supplied detections, center-only constant velocity, no detector/Re-ID training.
HOTA matching follows the pinned TrackEval score convention, not paper Eq. 15.
No benchmark preprocessing, ignored regions, camera fusion, or class averaging.
"""
import json
from dataclasses import dataclass
import numpy as np


def array(value, shape=None):
    a = np.asarray(value, dtype=float)
    if not np.isfinite(a).all() or (shape is not None and a.shape != shape):
        raise ValueError('Expected finite data with the stated shape')
    return a


def boxes(value):
    b = array(value)
    if b.size == 0:
        return b.reshape(0, 4)
    if b.ndim != 2 or b.shape[1] != 4 or np.any(b[:, 2:] <= b[:, :2]):
        raise ValueError('Boxes require x2 > x1 and y2 > y1')
    return b


def iou(a, b):
    a, b = boxes(a), boxes(b)
    intersection = np.maximum(0, np.minimum(a[:, None, 2:], b[None, :, 2:]) -
                              np.maximum(a[:, None, :2], b[None, :, :2])).prod(2)
    area_a, area_b = (a[:, 2:] - a[:, :2]).prod(1), (b[:, 2:] - b[:, :2]).prod(1)
    return intersection / (area_a[:, None] + area_b[None, :] - intersection)


def assignment(cost):
    """Minimum-cost rectangular assignment; all rows of the smaller side match.

    Primal/dual augmenting paths, O(min(n,m)^2 max(n,m)); ties scan low indices.
    """
    c = array(cost)
    if c.ndim != 2:
        raise ValueError('Expected a cost matrix')
    if not min(c.shape):
        return []
    if c.shape[0] > c.shape[1]:
        return sorted((j, i) for i, j in assignment(c.T))
    n, m = c.shape
    u, v = np.zeros(n + 1), np.zeros(m + 1)
    owner = np.zeros(m + 1, dtype=int)
    for row in range(1, n + 1):
        owner[0] = row
        column = 0
        distance = np.full(m + 1, np.inf)
        parent = np.zeros(m + 1, dtype=int)
        visited = np.zeros(m + 1, dtype=bool)
        while True:
            visited[column] = True
            active = owner[column]
            step, next_column = np.inf, 0
            for j in range(1, m + 1):
                if not visited[j]:
                    reduced = c[active - 1, j - 1] - u[active] - v[j]
                    if reduced < distance[j]:
                        distance[j], parent[j] = reduced, column
                    if distance[j] < step:
                        step, next_column = distance[j], j
            for j in range(m + 1):
                if visited[j]:
                    u[owner[j]] += step
                    v[j] -= step
                else:
                    distance[j] -= step
            column = next_column
            if owner[column] == 0:
                break
        while column:
            previous = parent[column]
            owner[column] = owner[previous]
            column = previous
    return sorted((int(owner[j] - 1), j - 1) for j in range(1, m + 1) if owner[j])


def gated_matching(similarity, threshold):
    """Maximize eligible match count, then summed similarity; unmatched allowed."""
    s = array(similarity)
    if s.ndim != 2 or np.any((s < 0) | (s > 1)) or not 0 <= threshold <= 1:
        raise ValueError('Similarity and threshold must lie in [0,1]')
    n, m = s.shape
    reward = np.zeros((n + m, n + m))
    eligible = s >= threshold
    reward[:n, :m] = np.where(eligible, min(n, m) + 1 + s, -1)
    return [(i, j) for i, j in assignment(-reward) if i < n and j < m and eligible[i, j]]


def predict(mean, covariance, dt, acceleration_variance=0.05):
    mean, covariance = array(mean, (4,)), array(covariance, (4, 4))
    if not np.isfinite([dt, acceleration_variance]).all() or dt <= 0 or acceleration_variance < 0:
        raise ValueError('Positive elapsed time and nonnegative process variance required')
    f = np.eye(4)
    f[:2, 2:] = dt * np.eye(2)
    # One independent, constant random acceleration per axis during this interval.
    g = np.vstack((0.5 * dt * dt * np.eye(2), dt * np.eye(2)))
    return f @ mean, f @ covariance @ f.T + acceleration_variance * g @ g.T


def update(mean, covariance, measurement, measurement_variance=0.2):
    mean, covariance, z = array(mean, (4,)), array(covariance, (4, 4)), array(measurement, (2,))
    if not np.isfinite(measurement_variance) or measurement_variance <= 0:
        raise ValueError('Positive measurement variance required')
    innovation_cov = covariance[:2, :2] + measurement_variance * np.eye(2)
    gain = np.linalg.solve(innovation_cov, covariance[:2, :]).T
    corrected = mean + gain @ (z - mean[:2])
    # Joseph form includes measurement noise and preserves covariance structure.
    residual = np.eye(4)
    residual[:, :2] -= gain
    p = residual @ covariance @ residual.T + measurement_variance * gain @ gain.T
    return corrected, (p + p.T) / 2


@dataclass
class Track:
    identity: int
    mean: np.ndarray
    covariance: np.ndarray
    size: np.ndarray
    misses: int = 0
    hits: int = 1

    def box(self):
        return np.r_[self.mean[:2] - self.size / 2, self.mean[:2] + self.size / 2]


class Tracker:
    """Two score passes with explicit lifetimes; deliberately not full ByteTrack.

    High >= high_threshold; low <= score < high. Low boxes never start tracks.
    Low pass is only for tracks observed in the immediately previous frame.
    A missing track is retained for at most max_misses frames but never emitted.
    """
    def __init__(self, low=0.1, high=0.6, overlap=0.2, max_misses=2, min_hits=2):
        if not (0 <= low < high <= 1 and 0 <= overlap <= 1):
            raise ValueError('Invalid thresholds')
        if type(max_misses) is not int or max_misses < 0 or type(min_hits) is not int or min_hits < 1:
            raise ValueError('Invalid lifetime settings')
        self.low, self.high, self.overlap = low, high, overlap
        self.max_misses, self.min_hits = max_misses, min_hits
        self.tracks, self.next_id, self.time = [], 1, None

    def step(self, time, detections):
        d = array(detections)
        if d.size == 0:
            d = d.reshape(0, 5)
        if d.ndim != 2 or d.shape[1] != 5 or np.any((d[:, 4] < 0) | (d[:, 4] > 1)):
            raise ValueError('Detections are rows x1,y1,x2,y2,score')
        boxes(d[:, :4])
        if not np.isfinite(time) or (self.time is not None and time <= self.time):
            raise ValueError('Timestamps must increase')
        dt = 1.0 if self.time is None else time - self.time
        self.time = time
        for t in self.tracks:
            t.mean, t.covariance = predict(t.mean, t.covariance, dt)
            t.misses += 1
        high_ids = np.flatnonzero(d[:, 4] >= self.high).tolist()
        low_ids = np.flatnonzero((d[:, 4] >= self.low) & (d[:, 4] < self.high)).tolist()
        remaining = list(range(len(self.tracks)))
        def associate(track_ids, detection_ids):
            tb = [self.tracks[i].box() for i in track_ids]
            matches = gated_matching(iou(tb, d[detection_ids, :4]), self.overlap)
            used_t, used_d = set(), set()
            for a, b in matches:
                i, j = track_ids[a], detection_ids[b]
                t = self.tracks[i]
                t.mean, t.covariance = update(t.mean, t.covariance, (d[j, :2] + d[j, 2:4]) / 2)
                t.size, t.misses, t.hits = d[j, 2:4] - d[j, :2], 0, t.hits + 1
                used_t.add(i); used_d.add(j)
            return used_t, used_d
        used_t, used_d = associate(remaining, high_ids)
        remaining = [i for i in remaining if i not in used_t]
        associate([i for i in remaining if self.tracks[i].misses == 1], low_ids)
        for j in high_ids:
            if j not in used_d:
                center, size = (d[j, :2] + d[j, 2:4]) / 2, d[j, 2:4] - d[j, :2]
                self.tracks.append(Track(self.next_id, np.r_[center, 0., 0.], np.diag([1., 1., 10., 10.]), size))
                self.next_id += 1
        self.tracks = [t for t in self.tracks if t.misses <= self.max_misses and
                       not (t.hits < self.min_hits and t.misses)]
        return {t.identity: t.box().tolist() for t in self.tracks if t.misses == 0 and t.hits >= self.min_hits}


def template_scores(template, search):
    """Valid zero-mean normalized raw-pixel correlation, without learned features."""
    z, x = array(template), array(search)
    if z.ndim != 2 or x.ndim != 2 or min(z.shape) == 0 or np.any(np.array(x.shape) < z.shape):
        raise ValueError('Template must fit the two-dimensional search image')
    z = z - z.mean()
    norm = np.linalg.norm(z)
    if norm == 0:
        raise ValueError('Constant template has no normalized contrast')
    h, w = z.shape
    result = np.zeros((x.shape[0] - h + 1, x.shape[1] - w + 1))
    for i, j in np.ndindex(result.shape):
        patch = x[i:i+h, j:j+w]
        patch = patch - patch.mean()
        denom = norm * np.linalg.norm(patch)
        result[i, j] = (z * patch).sum() / denom if denom else 0
    return result



def kernel_shift_response(template, search, target, regularization=0.1, sigma=1.0):
    """Gaussian kernel ridge regression on all 1D circular shifts.

    Output j scores np.roll(search, j). This is a cyclic alignment core,
    not a full image KCF tracker with cropping, windows and model updates.
    """
    x, z, y = array(template), array(search), array(target)
    if x.ndim != 1 or not x.size or x.shape != z.shape or x.shape != y.shape:
        raise ValueError('Three equally sized, nonempty vectors required')
    if not np.isfinite([regularization,sigma]).all() or regularization <= 0 or sigma <= 0:
        raise ValueError('Positive ridge coefficient and kernel scale required')
    def kernel(a,b):
        products = np.fft.ifft(np.fft.fft(a)*np.fft.fft(b).conj()).real
        squared = np.maximum(0, a@a + b@b - 2*products)
        return np.exp(-squared/(sigma*sigma))
    spectrum = np.fft.fft(kernel(x,x))
    dual = np.fft.fft(y)/(spectrum + regularization)
    return np.fft.ifft(dual*np.fft.fft(kernel(x,z))).real


def sequence_data(truth, prediction):
    """One class, one sequence; frame dictionaries map integer identity to xyxy."""
    if len(truth) != len(prediction):
        raise ValueError('Frame counts must match')
    for frame in list(truth) + list(prediction):
        if any(type(k) is not int for k in frame):
            raise ValueError('Identity keys must be integers')
        boxes(list(frame.values()))
    gids = sorted(set().union(*(set(f) for f in truth)))
    pids = sorted(set().union(*(set(f) for f in prediction)))
    gi, pi = {k:i for i,k in enumerate(gids)}, {k:i for i,k in enumerate(pids)}
    frames, gc, pc = [], np.zeros(len(gids)), np.zeros(len(pids))
    for g, p in zip(truth, prediction):
        gs, ps = sorted(g), sorted(p)
        a, b = [gi[k] for k in gs], [pi[k] for k in ps]
        gc[a] += 1; pc[b] += 1
        frames.append((a, b, iou([g[k] for k in gs], [p[k] for k in ps])))
    return frames, gc, pc


def metrics(truth, prediction, threshold=0.5):
    """MOTA with previous-frame preference, global IDF1, TrackEval-style HOTA.

    MOTA is None with no ground truth; empty-sequence IDF1/HOTA are zero.
    Last observed match is kept for counting switches across gaps; frame preference
    is reset each frame. This explicit gap rule differs from some evaluators.
    """
    if not np.isfinite(threshold) or not 0 < threshold <= 1:
        raise ValueError('Threshold must lie in (0,1]')
    frames, gc, pc = sequence_data(truth, prediction)
    potential, soft = np.zeros((len(gc), len(pc))), np.zeros((len(gc), len(pc)))
    previous, last, tp, switches = {}, {}, 0, 0
    for a, b, s in frames:
        ix = np.ix_(a, b)
        potential[ix] += s >= threshold
        denominator = s.sum(1)[:, None] + s.sum(0)[None, :] - s
        soft[ix] += np.divide(s, denominator, out=np.zeros_like(s), where=denominator > np.finfo(float).eps)
        score = s.copy()
        for i, g in enumerate(a):
            for j, p in enumerate(b):
                score[i, j] += 1000 * (previous.get(g) == p)
        score[s < threshold] = 0
        current = {}
        for i, j in assignment(-score):
            if score[i, j] > 0:
                g, p = a[i], b[j]
                tp += 1
                switches += g in last and last[g] != p
                current[g] = p
                last[g] = p
        previous = current
    ng, npred = int(gc.sum()), int(pc.sum())
    idtp = int(sum(potential[i,j] for i,j in assignment(-potential)))
    alignment = np.divide(soft, gc[:,None] + pc[None,:] - soft,
                          out=np.zeros_like(soft), where=(gc[:,None]+pc[None,:]-soft) > 0)
    selected = []
    for a, b, s in frames:
        selected.append(assignment(-(alignment[np.ix_(a,b)] * s)))
    curve = []
    for alpha in np.arange(1,20) / 20:
        count = np.zeros_like(soft)
        for (a,b,s), pairs in zip(frames, selected):
            for i,j in pairs:
                if s[i,j] >= alpha - np.finfo(float).eps:
                    count[a[i],b[j]] += 1
        htp = float(count.sum())
        association = np.divide(count, gc[:,None]+pc[None,:]-count,
                                out=np.zeros_like(count), where=(gc[:,None]+pc[None,:]-count) > 0)
        assa = float((count*association).sum()/htp) if htp else 0.
        deta = htp / (ng+npred-htp) if ng+npred-htp else 0.
        curve.append({'alpha':float(alpha),'DetA':deta,'AssA':assa,'HOTA':float(np.sqrt(deta*assa))})
    return {'TP':tp,'FN':ng-tp,'FP':npred-tp,'IDSW':int(switches),
            'MOTA':1-(ng+npred-2*tp+switches)/ng if ng else None,
            'IDTP':idtp,'IDFN':ng-idtp,'IDFP':npred-idtp,
            'IDF1':2*idtp/(ng+npred) if ng+npred else 0.,
            'HOTA':float(np.mean([c['HOTA'] for c in curve])),'curve':curve}


def demo():
    z = np.array([[0.,1.],[2.,0.]])
    x = np.zeros((5,7)); x[2:4,3:5] = z
    response = template_scores(z,x)
    best = np.unravel_index(response.argmax(),response.shape)
    def box(cx): return [cx-1,0,cx+1,2]
    scores = [.9,.9,.3,.9]
    kept, discarded = Tracker(min_hits=1), Tracker(low=.6-1e-6,min_hits=1)
    sequences = [[],[]]
    for i,score in enumerate(scores):
        detection = [box(.3*i)+[score]]
        sequences[0].append(kept.step(float(i),detection))
        sequences[1].append(discarded.step(float(i),detection))
    truth = [{1:box(.3*i)} for i in range(4)]
    # Exact boxes throughout: identity swap is the only change.
    gt = [{1:box(0),2:box(5)} for _ in range(4)]
    swapped = [dict(f) if t<2 else {2:f[1],1:f[2]} for t,f in enumerate(gt)]
    mismatch = metrics(gt,swapped)
    summary = lambda result: {k:v for k,v in result.items() if k!='curve'}
    cyclic = np.array([0.,1.,.2,0.,0.,0.,0.,0.])
    cyclic_scores = kernel_shift_response(cyclic,np.roll(cyclic,2),np.eye(8)[0])
    return {'cyclic_alignment_roll':int(cyclic_scores.argmax()),
            'cyclic_alignment_peak':float(cyclic_scores.max()),'template_peak_yx':[int(v) for v in best], 'template_peak_score':float(response[best]),
            'scores':scores,'recovered_ids':[list(f) for f in sequences[0]],
            'discarded_ids':[list(f) for f in sequences[1]],
            'recovered_metrics':summary(metrics(truth,sequences[0])),
            'discarded_metrics':summary(metrics(truth,sequences[1])),
            'perfect_boxes_swapped_ids':summary(mismatch),
            'swap_at_half':mismatch['curve'][9],
            'gated_counterexample':gated_matching([[.9,.6],[.6,.49]],.5)}


if __name__ == '__main__':
    print(json.dumps(demo(),indent=2))

The actual output is:

{
  "cyclic_alignment_roll": 6,
  "cyclic_alignment_peak": 0.902043944174126,
  "template_peak_yx": [
    2,
    3
  ],
  "template_peak_score": 1.0,
  "scores": [
    0.9,
    0.9,
    0.3,
    0.9
  ],
  "recovered_ids": [
    [
      1
    ],
    [
      1
    ],
    [
      1
    ],
    [
      1
    ]
  ],
  "discarded_ids": [
    [
      1
    ],
    [
      1
    ],
    [],
    [
      1
    ]
  ],
  "recovered_metrics": {
    "TP": 4,
    "FN": 0,
    "FP": 0,
    "IDSW": 0,
    "MOTA": 1.0,
    "IDTP": 4,
    "IDFN": 0,
    "IDFP": 0,
    "IDF1": 1.0,
    "HOTA": 1.0
  },
  "discarded_metrics": {
    "TP": 3,
    "FN": 1,
    "FP": 0,
    "IDSW": 0,
    "MOTA": 0.75,
    "IDTP": 3,
    "IDFN": 1,
    "IDFP": 0,
    "IDF1": 0.8571428571428571,
    "HOTA": 0.75
  },
  "perfect_boxes_swapped_ids": {
    "TP": 8,
    "FN": 0,
    "FP": 0,
    "IDSW": 2,
    "MOTA": 0.75,
    "IDTP": 4,
    "IDFN": 4,
    "IDFP": 4,
    "IDF1": 0.5,
    "HOTA": 0.5773502691896258
  },
  "swap_at_half": {
    "alpha": 0.5,
    "DetA": 1.0,
    "AssA": 0.3333333333333333,
    "HOTA": 0.5773502691896257
  },
  "gated_counterexample": [
    [
      0,
      1
    ],
    [
      1,
      0
    ]
  ]
}

The test suite checks assignment against exhaustive permutations and partial matchings, Kalman updates against an information-form posterior, all sixteen two-ID swap sequences over four frames, empty inputs, lifecycle thresholds, camera-motion failure and the full localization curve. The cyclic kernel response is independently checked against dense kernel regression. These tests establish the small computations; they do not establish a detector’s accuracy or full compatibility with benchmark preprocessing.

Which failure matters for the application?

A tracking system can fail because the detector never proposed the object, the motion model excluded it, appearance was ambiguous, the assignment preferred a competitor, or the track was deleted too soon. Log those stages separately. Increasing max_misses preserves hypotheses longer but also retains wrong ones; it is not a free improvement.

A sudden camera movement invalidates a simple image-coordinate velocity prediction. A repeated uniform or texture can confuse appearance. A tracker trained for one category need not recognize unseen ones. Across cameras, time synchronization, geometry, appearance shifts and the required identity policy become additional assumptions. A box tracker also does not infer a complete 3D trajectory or what an actor intends.

For a benchmark, freeze detector weights, input resolution, score/NMS settings, split, visibility rules, ignored regions, label definitions and the evaluator version. Report detector and feature-extraction time as well as association time. Distinguish offline use of future frames from online latency. Our metrics operate on one class and one already-prepared sequence, without ignored regions or benchmark-specific filtering. The ByteTrack paper itself specifies training/validation choices and private-detection conditions; those conditions belong with any reproduction claim. Experimental protocol scope

For an application, add an error measure tied to its decision: a counting system may care about duplicate IDs, while a trajectory analysis may care about long gaps. Predicted boxes during an occlusion should be marked as predictions. A task-local track ID is not evidence of a person’s legal identity, and video containing people requires a deliberate access and retention policy.

Check the correspondence yourself

1. Understanding: can excellent detections give poor identities?

Every predicted box is exact, but a person receives a different ID in every frame. Is detector recall enough to claim successful tracking?

Answer: No. Recall only says the objects were found under the detection matching rule. Each short predicted identity can map globally to at most one fragment of the real trajectory, so identity measures expose a problem that recall misses. Inspect identity duration and fragmentation as well as boxes.

2. Calculation: the two-person swap

In the printed four-frame example, derive IDF1 and the association term without running the code.

Answer: There are eight true and eight predicted detections. Either global mapping retains four, so IDF1=2×4/(8+8)=0.5. Each matched identity pair occurs twice and has two four-detection trajectories, giving 2/(4+4−2)=1/3. Every TP has this value, so AssA=1/3, DetA=1 and HOTA=√(1/3). The boxes are exact at all nineteen thresholds.

3. Counterexample: gate before or after assignment?

Use [[0.9,0.6],[0.6,0.49]] with threshold 0.5. Why does rejecting invalid matches after the unrestricted optimum fail to maximize the number of valid matches?

Answer: The diagonal sum 1.39 beats 1.2, so the unrestricted optimizer picks it. Removing the 0.49 pair leaves one match. Both cross pairs satisfy the gate, so a cardinality-first feasible optimizer returns two. Changing the objective, not a numerical tolerance, changes the result.

4. Transfer: a low-score object behind an obstruction

A confirmed track has no high-score match but has a plausible low-score box. Should every low-score box create a track, and should an unmatched old prediction be reported as observed?

Answer: Neither follows. A gated second association can use the plausible box to maintain an existing track, while unmatched low-score boxes can remain rejected. If nothing matches, retain a bounded hypothesis according to the task and distinguish prediction from observation. In our example, old missing tracks cannot be revived by the low-score pass; another system may deliberately choose a different lifecycle rule and must evaluate it.

Different dates, different contributions

First preprintWorkWhat to follow in the original source
2014-04-30High-Speed Tracking with Kernelized Correlation FiltersCircular samples and fast kernel regression; an extension of earlier work, not the origin of all correlation tracking
2016-02-02SORTA compact tracking-by-detection pipeline
2016-06-30SiamFCShared offline-learned features and dense cross-correlation
2016-09-06Identity measuresGlobal identity assignment and IDF1
2017-03-21Deep SORTAppearance descriptors, gates and matching cascade
2020-09-16HOTADetection, association and localization in a decomposable metric
2021-10-13ByteTrackReusing low-score detections through a second association

These dates come from the individual submission histories. The read versions are recorded separately: SORT v2, KCF v2, SiamFC v2 and the identity paper v2 include later revisions; ByteTrack is read in its ECCV 2022 version. KCF history SORT history SiamFC history Identity history Deep SORT history HOTA history ByteTrack history

HOTA’s publisher distinguishes online publication on 8 October 2020 from its 2021 journal volume. Neither should replace its first-preprint date. Publisher metadata

MOTR’s 2022 conference method and CoTracker’s 2023 paper illustrate two further directions: learned persistent object queries and joint point trajectories. Their output contracts differ, so an improvement on one benchmark cannot be transferred to the other by name alone. Read them alongside the separate chapters on detection, optical flow, video understanding and segmentation. The implementation here supplies inspectable building blocks and counterexamples, not a ranking of all trackers available at the edition cutoff. MOTR scope CoTracker scope

Make a prediction, then check

Every box is exact, but two identities swap halfway through. What can you conclude?

Choose one answer

Learning objectives

  • Separate object, point and mask tracking contracts from framewise detection.
  • Derive motion uncertainty, global gated assignment and track lifetimes.
  • Verify cyclic kernel responses against dense regression and identify shift conventions.
  • Compute MOTA, global IDF1 and HOTA without hiding protocol differences.

Prerequisites & connections

Explore related knowledge →

References

  1. Simple Online and Realtime Tracking
    Alex Bewley; Zongyuan Ge; Lionel Ott; Fabio Ramos; Ben Upcroft · 2017
  2. Simple Online and Realtime Tracking with a Deep Association Metric
    Nicolai Wojke; Alex Bewley; Dietrich Paulus · 2017
  3. ByteTrack: Multi-Object Tracking by Associating Every Detection Box
    Yifu Zhang; Peize Sun; Yi Jiang; Dongdong Yu; Fucheng Weng; Zehuan Yuan; Ping Luo; Wenyu Liu; Xinggang Wang · 2022
  4. HOTA: A Higher Order Metric for Evaluating Multi-Object Tracking
    Jonathon Luiten; Aljosa Osep; Patrick Dendorfer; Philip Torr; Andreas Geiger; Laura Leal-Taixe; Bastian Leibe · 2020
  5. Fully-Convolutional Siamese Networks for Object Tracking
    Luca Bertinetto; Jack Valmadre; João F. Henriques; Andrea Vedaldi; Philip H. S. Torr · 2016
  6. High-Speed Tracking with Kernelized Correlation Filters
    João F. Henriques; Rui Caseiro; Pedro Martins; Jorge Batista · 2014
  7. Performance Measures and a Data Set for Multi-Target, Multi-Camera Tracking
    Ergys Ristani; Francesco Solera; Roger S. Zou; Rita Cucchiara; Carlo Tomasi · 2016
  8. TrackEval HOTA sequence evaluation (fixed commit)
    JonathonLuiten/TrackEval contributors · 2022
  9. TrackEval global identity evaluation (fixed commit)
    JonathonLuiten/TrackEval contributors · 2022
  10. TrackEval CLEAR sequence matching (fixed commit)
    JonathonLuiten/TrackEval contributors · 2022
  11. Deep SORT Kalman state and initialization (fixed commit)
    nwojke/deep_sort contributors · 2025
  12. ByteTrack score thresholds and track lifecycle (fixed commit)
    ifzhang/ByteTrack contributors · 2022
  13. Simple Online and Realtime Tracking — submission history
    Alex Bewley; Zongyuan Ge; Lionel Ott; Fabio Ramos; Ben Upcroft
  14. Simple Online and Realtime Tracking with a Deep Association Metric — submission history
    Nicolai Wojke; Alex Bewley; Dietrich Paulus
  15. ByteTrack: Multi-Object Tracking by Associating Every Detection Box — submission history
    Yifu Zhang; Peize Sun; Yi Jiang; Dongdong Yu; Fucheng Weng; Zehuan Yuan; Ping Luo; Wenyu Liu; Xinggang Wang
  16. HOTA: A Higher Order Metric for Evaluating Multi-Object Tracking — submission history
    Jonathon Luiten; Aljosa Osep; Patrick Dendorfer; Philip Torr; Andreas Geiger; Laura Leal-Taixe; Bastian Leibe
  17. Fully-Convolutional Siamese Networks for Object Tracking — submission history
    Luca Bertinetto; Jack Valmadre; João F. Henriques; Andrea Vedaldi; Philip H. S. Torr
  18. High-Speed Tracking with Kernelized Correlation Filters — submission history
    João F. Henriques; Rui Caseiro; Pedro Martins; Jorge Batista
  19. Performance Measures and a Data Set for Multi-Target, Multi-Camera Tracking — submission history
    Ergys Ristani; Francesco Solera; Roger S. Zou; Rita Cucchiara; Carlo Tomasi
  20. HOTA — online publication and journal volume metadata
    Springer Nature · 2020
  21. MOTR: End-to-End Multiple-Object Tracking with Transformer
    Fangao Zeng; Bin Dong; Yuang Zhang; Tiancai Wang; Xiangyu Zhang; Yichen Wei · 2022
  22. CoTracker: It is Better to Track Together
    Nikita Karaev; Ignacio Rocco; Benjamin Graham; Natalia Neverova; Andrea Vedaldi; Christian Rupprecht · 2023

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: scoped original tracking papers and fixed metric code; 28 tests including independent assignment, Kalman posterior, identity sequences and FFT/dense kernel comparisons; full bilingual claims, 12 equations, code/output and four explained exercises compared. Not human peer review or full benchmark reproduction.

  • 28 checks: 22 numeric and six bilingual/output/metadata/event/protocol/diagram checks. Assignment versus exhaustive permutations/partial matches; Kalman versus information-form posterior; all two-ID four-frame swap patterns; Gaussian FFT versus dense kernel regression.
  • Compared definitions, assumptions, 12 equations per language, complete 342-line code/output, four explained exercises and 22 sources. HOTA paper/code matching, CLEAR gap memory and ByteTrack thresholds remain explicitly distinguished. All visual data use synthetic inputs, not benchmark performance.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.