目标跟踪:框对了,身份为什么还会错?
Object tracking
实现包含Kalman预测、全局分配和低分框恢复的小跟踪器,比较身份指标,并核对循环核相关的真实计算。
object-tracking框都对了,身份也对吗?
设想一段只有四帧、两个人的合成视频。预测框每一帧都贴得很准,可到了后两帧,跟踪器把两人的编号交换了:原来的1号变成2号,2号变成1号。检测器可能凭这些框拿到满分;如果系统要统计每个人等了多久,它拼出的历史却是错的。
目标跟踪要估计对象的位置变化,并在时间上保持任务要求的对应关系。这里的身份是跟踪任务中的标签,不一定对应一个有姓名的人。输入、输出的约定很重要:
| 任务 | 已知信息 | 需要输出什么 |
|---|---|---|
| 单目标跟踪 | 初始目标,常由第一帧的框指定 | 后续位置,以及任务规定的目标缺席状态 |
| 多目标跟踪 | 视频与目标类别,或已有检测结果 | 位置、持续编号,以及新出现和离开的对象 |
| 点跟踪 | 指定的图像点 | 点的轨迹,以及方法支持时的可见性 |
| 视频目标分割 | 对象提示或其他明确监督 | 随时间变化的掩码,以及帧间对应 |
一个点不等于整个物体,分割掩码本身也没有定义基准的身份规则。例如CoTracker联合推断点的轨迹,输出契约不同于一组人物检测框。点跟踪任务
有用的起点不必先训练一个跟踪网络:可以在图像里寻找与模板相似的区域,也可以按重叠程度关联已有检测框。这两条基线会暴露不同问题。重复纹理让多个区域都像模板;两人交错经过时,单靠重叠可能接错对象;没有测量时,算法不能凭空知道被遮挡物体的位置。
下文从给定检测框出发构建一个完整小跟踪器,并保留它的失败情况。另一个模板例子直接处理原始像素。跟踪器包含运动不确定性、全局分配、分数门限和轨迹寿命,没有暗中调用检测器或预训练外观网络。身份交换例子是合成数据,不是基准成绩。
怎样把观察接成同一条轨迹?
单目标:什么才算相似?
设模板为z,偏移u处的候选图块为x_u。零均值归一化相关先分别减去均值,再按各自对比度归一化:
分母使用欧氏范数。只要中心化后两个图块都不是全零,正的尺度变化与亮度平移就不会改变分数。常数模板没有可以归一化的对比度,程序会拒绝它;常数候选图块的分数定为0。分数1表示归一化后完全相同,不能证明这是同一个物理对象。
KCF采用判别式思路:把模板的循环移位作为训练样本,为每种移位指定期望响应,再训练核岭回归。循环移位会把从一侧移出的内容绕回另一侧;这是计算模型,不是物体运动的一般规律。论文讨论了用填充和窗函数减轻这种边界伪影。循环样本与回归
设P把长度n的信号移动一格。如果一个核在同时置换两个输入时保持不变,这批样本的核矩阵就能保留循环结构。对高斯核,我们的一维程序计算所有移位的核相关,再在傅里叶域求解:
这里k(x,z)_j比较x与P^j z;帽号表示离散傅里叶变换,频域乘除都是逐元素进行。实值高斯自核对应的训练矩阵是对称的,因此这一写法经逆变换得到通常的实值对偶系数。索引j处的输出是在给P^j z这个候选打分。如果z是把长度8的x向右移2格得到的,最佳对齐应为j=6,不是j=2。测试用独立构造的稠密核矩阵核对整条FFT响应,也覆盖任意回归目标。
加速来自结构:n×n核方程变成变换与逐元素运算,这个单通道核心的时间为O(n log n),工作存储为O(n)。这不表示任何核都有快速核相关公式,也不表示完整图像跟踪器只需这一步。例子没有图像裁剪、空间窗、尺度搜索或在线模型更新。核的条件与快速相关
SiamFC则从视频图块对中学习共享嵌入。模板与搜索图的特征图做互相关,得到一个空间分数网格。令标签y_u取−1或+1,基本分数图目标为:
论文还会平衡正、负样本的损失。其全卷积性质讨论有效输出区域中的平移,并考虑网络步幅。所描述的跟踪器不在线更新学到的模型,也不维护过去外观的记忆。因此,下文的归一化原始像素匹配是表示方式不同的基线,不能称为小型SiamFC训练复现。共享特征、损失与跟踪流程
多目标:先预测,再找匹配
SORT把检测、匀速Kalman模型、IoU关联与轨迹创建、删除结合起来。它的七维状态包含框中心、面积、宽高比及三个速度。Deep SORT改用八维的中心、宽高比、高度及对应速度。这些不是可以随意互换的坐标名字。SORT状态 Deep SORT状态
为了看清计算,我们的小状态只包含中心位置和速度。宽、高来自最近一次匹配的框。对经过的时间Δt,定义:
状态均值有四个分量,P是4×4协方差。线性高斯模型假设过程噪声和观测噪声都是加性、零均值,并具有指定协方差。假设新增过程噪声与旧状态独立,就有预测步骤:
这里的Q假设每个间隔中,每个轴各有一个独立的常随机加速度,方差为q。它不是连续白噪声谱密度对应的公式;后者的Δt幂次不同。间隔越长,位置不确定性会增长,但这不会让匀速均值在转弯或相机突跳时自动变准。
观测到中心z后,创新协方差S同时包含预测不确定性与测量噪声R。Kalman增益决定如何利用创新量;协方差采用Joseph形式更新:
均值更新会同时修正位置和速度,因为预测已在两者之间建立互协方差。令R为零相当于把测量当成完全准确;程序要求标量测量方差为正。测试通过独立的信息形式高斯后验核对这一步。计算增益时使用线性方程求解,没有显式求逆。固定版本的Deep SORT代码使用八维模型,并按框高设置噪声尺度,我们的参数不复现它的滤波器。Deep SORT实际初始化
相似度、门控与一对一分配
IoU用交集与并集面积比较框。运动门控还可以根据平方Mahalanobis距离排除不合理测量。Deep SORT把运动信息与归一化外观描述子的图库结合:
g是轨迹i保存的一个单位描述子,r_j是新观察的单位描述子;最小余弦距离在这条轨迹的图库中搜索。这样的特征需要合适的学习表示,随手指定一个向量不会产生重识别能力。Deep SORT四维观测的95%卡方门限为9.4877,不能直接搬到我们的二维中心模型。其关联代价在实验中可以把运动项权重设为零,但运动门控仍然保留。外观与运动门控
关联是一对一决策。让每条轨迹各自挑最喜欢的检测,会把两条轨迹同时接到一个框上。设合格边集合为E,二元决策为a_ij,小跟踪器采用按顺序优化的目标:
先让合格匹配数量最多,再让这些匹配的相似度总和最大;允许轨迹和检测不匹配。程序加入虚拟分配,并给一次合格匹配加上大于相似度总和最大变化的奖励,然后用原始—对偶增广路求矩形最小代价分配。求解器时间为O(min(n,m)^2 max(n,m));门控问题填充后可用O((n+m)^3)作上界。
这是一个明确选择。相似度为[[0.9,0.6],[0.6,0.49]]、门限为0.5时,不加限制的最大总和匹配会选对角线,总和1.39;事后丢掉0.49那一对,就只剩一个匹配。先门控可以选两个交叉对,总和1.2。两种流程不能在不改变行为的情况下互相替换。
Deep SORT还采用cascade:最近观察到的轨迹优先接触检测。随着不确定性增长,单独使用Mahalanobis距离可能偏爱更旧、更宽的分布;cascade引入了单次全局求解中没有的优先规则。最后的IoU阶段再处理指定的未匹配或未确认轨迹。小程序没有实现这套外观cascade。匹配顺序
低置信度不等于没有证据
ByteTrack先关联高分检测,再用低分检测恢复剩余轨迹;未匹配的低分检测不创建新身份。论文主张第二阶段使用IoU,因为遮挡或模糊下的外观可能不可靠;正文也补充了精简伪代码省略的lost轨迹保留和恢复流程。两阶段与轨迹寿命
小例子的边界另作明示:分数大于等于0.6进入第一阶段;大于等于0.1、严格小于0.6进入第二阶段。低分阶段只服务上一帧仍被观察到的轨迹。临时轨迹需要重复命中才确认;已确认但丢失的轨迹保留有限帧数;没有匹配检测的预测不作为输出。
固定版本ByteTrack代码的边界不同:高分严格大于track_thresh,低分严格大于0.1且严格小于track_thresh,新轨迹初始化门限还使用track_thresh+0.1。因此,在该版本中,恰好等于track_thresh的分数没有进入这两个输入组。这些细节属于方法复现的一部分。固定阈值与生命周期代码
检测器加手工设计的关联并不是唯一架构。MOTR在Transformer中逐帧传递track query,并用序列监督训练跟踪过程;detect query可以引入新实例,track query携带已有实例。这把对应关系纳入学到的状态更新机制,但没有免除监督、目标消失和身份评测的定义。轨迹查询与序列学习
评测身份,而不只是框
按指定流程匹配后,令N_GT为所有真值检测的总数。MOTA对漏检、误检和身份切换计数:
它可以为负。N_GT为零时该式没有定义,程序返回None。切换计数也需要记忆约定:本例跨间隔记住上次成功匹配的身份,但每帧都会重置用于关联的上一帧偏好。固定CLEAR实现遇到整帧一侧为空时会提前返回该循环,因此保留部分上一帧状态。我们的函数不能直接替换该基准实现。CLEAR匹配与计数
IDF1寻找真值身份与预测身份之间的全局一对一映射。先对每一对候选身份统计同时出现、满足空间门限的检测;这一步发生在逐帧一对一分配之前。再选择全局映射,让保留下来的正确检测最多。将这个数记为IDTP:
完全空的序列在本例中约定IDF1为零。N_pred包含全部预测检测,因此未映射身份仍然产生错误。这与逐帧累加检测指标选中的匹配不同。论文推导了等价的最小代价身份分配,参考实现也明确先累计合格候选对,再分配身份。全局身份指标 身份指标参考实现
HOTA结合检测与关联。在一个定位门限α下,设c_gp为身份对(g,p)成功匹配的检测数,n_g和n_p为这两个身份各自的全部检测数。关联Jaccard分数同时惩罚轨迹拆散和合并:
没有真阳性时,程序把AssA和HOTA设为零。平均按匹配检测数加权,不是让每个身份对权重相同。没有匹配上的检测仍保留在轨迹长度和检测错误分母中。最终HOTA对各个门限的分数求平均:
论文的匹配描述依次优先考虑合格真阳性、关联和定位,并为每个门限分别匹配。固定TrackEval代码却先计算全序列软对齐,与逐帧相似度相乘,每帧只求一次分配,再用十九个门限过滤这些对。本例HOTA遵循这个固定实现的约定;使用相同计分公式,不意味着两种匹配描述就相同。关联公式与论文匹配 HOTA实际匹配
四帧身份交换中,八个框全部匹配,有两次切换,因此MOTA=0.75。无论选择哪一个全局身份映射,都只能保留四个检测,所以IDF1=0.5。四种出现过的身份对都有c_gp=2、n_g=n_p=4,关联分数为2/(4+4−2)=1/3。DetA为1,HOTA约0.57735。笼统说“跟踪准确率75%”,会掩盖这些数各自的含义。
运行关联过程,也检查失败
完整程序使用Python 3.12.4与NumPy 1.26.4。框采用连续xyxy坐标,宽高必须为正;边缘相接的IoU为零。输入必须有限,时间戳严格递增,每帧一个整数身份最多对应一个框。分数和坐标由输入提供,没有训练检测器。单独调用滤波函数时,输入协方差应是合法的对称半正定矩阵。
默认跟踪器需要命中两次才确认身份。打印的比较显式设为一次,避免初始化延迟掩盖第三帧被过滤的影响。低分例子过滤后有一次无输出,但没有发生身份切换:保留下来的运动轨迹在下一次高分观察时被找回。这两种结果在真实视频里都没有保证。
"""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))
实际输出为:
{
"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
]
]
}
测试将分配与穷举排列、部分匹配对照,将Kalman更新与信息形式后验对照,并检查四帧两身份的全部十六种交换序列、空输入、生命周期边界、相机运动失败和完整定位曲线。循环核响应还与稠密核回归独立比较。这些测试验证小规模计算,不证明检测器准确率,也不证明完整基准预处理兼容性。
应用真正承受哪一种错误?
跟踪系统可能因为检测器根本没提出目标、运动模型把它排除、外观有歧义、分配偏向竞争者,或者过早删除轨迹而失败。应分别记录这些阶段。增大max_misses会让假设保留更久,也会留下错误假设,不是没有代价的改进。
相机突动会破坏简单的图像坐标匀速预测;重复的制服或纹理会混淆外观;针对一种类别训练的跟踪器不一定认识未见过的类别。跨镜头时,时间同步、几何、外观变化和身份规则成为额外假设。框跟踪器也不会因此推断出完整三维轨迹或行动意图。
做基准实验时,要固定检测器权重、输入分辨率、分数/NMS设置、划分、可见性规则、忽略区域、标签定义和评测器版本。耗时应同时报告检测、外观提取与关联,区分离线使用未来帧和在线延迟。我们的指标只处理一个类别、一条已整理序列,没有忽略区域或基准特定过滤。ByteTrack论文自身就注明了训练、验证选择及private detection条件;复现结论必须带上这些条件。实验协议范围
应用还应补充与决策相关的错误量:计数系统可能在意重复身份,轨迹分析可能更在意长时间缺口。遮挡期间推算的框应标明是预测。任务内的编号不是一个人的法定身份凭据;含人物的视频也需要明确的访问和保留规则。
自己核对一次对应关系
1. 理解:检测很好,身份仍可能很差吗?
每个预测框都准确,但同一个人每一帧都获得新编号。检测召回率足以证明跟踪成功吗?
答案:不够。召回率只表示在检测匹配规则下找到了对象。每条很短的预测身份在全局映射中最多对应真实轨迹的一段,所以身份指标能暴露召回率漏掉的问题。除了框,还要看身份持续时间和轨迹碎片。
2. 手算:两人的身份交换
不用程序,推导输出中四帧例子的IDF1与关联项。
答案:真值与预测各有八个检测。任选一个全局映射,都只能保留四个,因此IDF1=2×4/(8+8)=0.5。每个匹配身份对出现两次,对应两条各四次检测的轨迹,得到2/(4+4−2)=1/3。每个TP的值都相同,所以AssA=1/3、DetA=1、HOTA=√(1/3)。框完全准确,在十九个门限下都成立。
3. 反例:先门控还是先分配?
使用[[0.9,0.6],[0.6,0.49]]、门限0.5。为什么先求无约束最优、再删除不合格对,不能最大化有效匹配数?
答案:对角线总和1.39高于1.2,无约束优化会选对角线。删掉0.49后只剩一对;两个交叉对却都合格,优先最大化可行匹配数的优化会返回两对。结果来自目标不同,不是浮点容差。
4. 迁移:遮挡后留下一个低分框
一条已确认轨迹找不到高分匹配,但有一个合理低分框。是否应让每个低分框创建轨迹?没匹配上的旧预测是否能当成实际观察报告?
答案:都不能由此推出。经过门控的第二次关联可以用合理低分框维护已有轨迹,未匹配低分框仍可拒绝。如果完全没有匹配,应按任务规则保留有限时间的假设,并区分预测和观察。本例不允许低分阶段复活已经缺失的旧轨迹;另一系统可以有意采用不同生命周期,但需要验证其后果。
不同日期,分别贡献了什么?
| 首个预印本 | 工作 | 原始资料中的重点 |
|---|---|---|
| 2014-04-30 | High-Speed Tracking with Kernelized Correlation Filters | 循环样本与快速核回归,是更早工作的扩展,不是所有相关跟踪的起源 |
| 2016-02-02 | SORT | 紧凑的检测后跟踪流程 |
| 2016-06-30 | SiamFC | 离线学习的共享特征与密集互相关 |
| 2016-09-06 | 身份指标 | 全局身份分配与IDF1 |
| 2017-03-21 | Deep SORT | 外观描述子、门控与匹配cascade |
| 2020-09-16 | HOTA | 可拆解的检测、关联与定位指标 |
| 2021-10-13 | ByteTrack | 通过第二次关联重新利用低分检测 |
日期来自每篇论文各自的提交历史。核读版本另行记录:SORT v2、KCF v2、SiamFC v2与身份论文v2包含后续修订,ByteTrack核读的是ECCV 2022版本。KCF历史 SORT历史 SiamFC历史 身份指标历史 Deep SORT历史 HOTA历史 ByteTrack历史
HOTA出版社把2020年10月8日的线上发表与2021年期刊卷分开列出,两者都不能替换首个预印本的日期。出版社元数据
MOTR的2022年会议方法与CoTracker的2023年论文展示了另两条方向:学到的持续对象查询,以及联合点轨迹。输出契约不同,不能凭名称把一种基准的改进转移到另一种任务。可结合检测、光流、视频理解和分割的独立章节阅读。这里的实现提供可检查的组成部分与反例,不是事实截点时所有跟踪器的排名。MOTR范围 CoTracker范围
先判断,再看解释
每个框都准确,但两个身份在中途交换了,能得出什么结论?
学习目标
- 区分对象、点和掩码跟踪的契约与逐帧检测。
- 推导运动不确定性、全局门控分配与轨迹生命周期。
- 用稠密回归核对循环核响应,辨明移位约定。
- 计算MOTA、全局IDF1与HOTA,并辨明协议差异。
先修与延伸
查看知识关联图 →参考文献
- Simple Online and Realtime Tracking
Alex Bewley; Zongyuan Ge; Lionel Ott; Fabio Ramos; Ben Upcroft · 2017 - Simple Online and Realtime Tracking with a Deep Association Metric
Nicolai Wojke; Alex Bewley; Dietrich Paulus · 2017 - 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 - 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 - Fully-Convolutional Siamese Networks for Object Tracking
Luca Bertinetto; Jack Valmadre; João F. Henriques; Andrea Vedaldi; Philip H. S. Torr · 2016 - High-Speed Tracking with Kernelized Correlation Filters
João F. Henriques; Rui Caseiro; Pedro Martins; Jorge Batista · 2014 - Performance Measures and a Data Set for Multi-Target, Multi-Camera Tracking
Ergys Ristani; Francesco Solera; Roger S. Zou; Rita Cucchiara; Carlo Tomasi · 2016 - TrackEval HOTA sequence evaluation (fixed commit)
JonathonLuiten/TrackEval contributors · 2022 - TrackEval global identity evaluation (fixed commit)
JonathonLuiten/TrackEval contributors · 2022 - TrackEval CLEAR sequence matching (fixed commit)
JonathonLuiten/TrackEval contributors · 2022 - Deep SORT Kalman state and initialization (fixed commit)
nwojke/deep_sort contributors · 2025 - ByteTrack score thresholds and track lifecycle (fixed commit)
ifzhang/ByteTrack contributors · 2022 - Simple Online and Realtime Tracking — submission history
Alex Bewley; Zongyuan Ge; Lionel Ott; Fabio Ramos; Ben Upcroft - Simple Online and Realtime Tracking with a Deep Association Metric — submission history
Nicolai Wojke; Alex Bewley; Dietrich Paulus - 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 - 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 - Fully-Convolutional Siamese Networks for Object Tracking — submission history
Luca Bertinetto; Jack Valmadre; João F. Henriques; Andrea Vedaldi; Philip H. S. Torr - High-Speed Tracking with Kernelized Correlation Filters — submission history
João F. Henriques; Rui Caseiro; Pedro Martins; Jorge Batista - 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 - HOTA — online publication and journal volume metadata
Springer Nature · 2020 - MOTR: End-to-End Multiple-Object Tracking with Transformer
Fangao Zeng; Bin Dong; Yuang Zhang; Tiancai Wang; Xiangyu Zhang; Yichen Wei · 2022 - CoTracker: It is Better to Track Together
Nikita Karaev; Ignacio Rocco; Benjamin Graham; Natalia Neverova; Andrea Vedaldi; Christian Rupprecht · 2023
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(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项:22数值及六项双语/输出/元数据/事件/协议/图示;分配穷举、Kalman信息形式后验、两ID四帧全部交换及FFT/稠密核独立对照。
- 逐项比较定义、假设、各语言12公式、342行完整程序/输出、四解释答案和22来源;HOTA论文/代码匹配、CLEAR缺帧记忆和ByteTrack阈值差别明确保留。图示为合成输入,不是基准成绩。
核对的来源位置:
- Simple Online and Realtime Tracking · Physical pages 2-3 fully read; page 1 lines 1-25. Method/state/association/lifetime; no performance claims adopted.
- Simple Online and Realtime Tracking with a Deep Association Metric · Physical pages 2-3 fully read; page 2 visually checked. Title/authors and opening abstract on page 1. Four-coordinate Mahalanobis gate, cosine gallery, cascade, final IoU pass; no speed or accuracy claim adopted.
- ByteTrack: Multi-Object Tracking by Associating Every Detection Box · ECCV 2022 physical pages 5-7 fully read, page 1 title/authors/opening abstract. Two passes, lost-track retention, new high-score tracks, evaluation split description. No reported scores adopted.
- HOTA: A Higher Order Metric for Evaluating Multi-Object Tracking · Physical pages 7-8 fully read; page 8 visually checked; page 1 title/authors/opening abstract. Association sets, Eq.13-16 and threshold average. Matching convention differs from pinned TrackEval code.
- Fully-Convolutional Siamese Networks for Object Tracking · Physical pages 3-4 fully read. Translation equivariance in valid region, cross-correlation, score-map logistic loss and sampling. Author/title independently checked in arXiv metadata; not full training section or implementation. Physical pages 5-6 fully read after initial record: positive radius and loss balancing, dataset curation/context/stride/no-padding; no model update or memory in the described tracker. Author claims of no overfitting are not adopted as guarantees.
- High-Speed Tracking with Kernelized Correlation Filters · Physical pages 3-4 fully read. Ridge regression, cyclic samples, wraparound, circulant diagonalization and earlier-work distinction. Title/authors/opening abstract checked; later kernel derivation not yet read. Physical pages 5-7 fully read after the initial scope record: Eq.8-30, kernel invariance condition, fast kernel training/detection, Gaussian and other kernels. Supplements initial readScope, does not erase it.
- Performance Measures and a Data Set for Multi-Target, Multi-Camera Tracking · Physical pages 8-9 fully read; title/authors/opening abstract on page 1. Binary spatiotemporal miss costs, global identity assignment and IDTP/IDFN/IDFP/IDF1.
- TrackEval HOTA sequence evaluation (fixed commit) · Lines 1-180; sequence scoring, global soft alignment, one assignment then 19 threshold filters, association denominators and final fields. Combining methods seen in this range, not otherwise independently validated. Fixed commit 12c8791b303e0a0b50f753af204249e622d0281a.
- TrackEval global identity evaluation (fixed commit) · Lines 1-145; potential eligible pair counts before global identity assignment, counts and formulas. Fixed commit 12c8791b303e0a0b50f753af204249e622d0281a.
- TrackEval CLEAR sequence matching (fixed commit) · Lines 45-150; previous-match preference, persistent IDSW memory and empty-frame branch behavior. Full benchmark preprocessing not read. Fixed commit 12c8791b303e0a0b50f753af204249e622d0281a.
- Deep SORT Kalman state and initialization (fixed commit) · Lines 23-90: 8D state, dt=1 transition, height-relative initialization. Predict/update bodies not yet read. Fixed commit f08cf1dc470eeb1cd2add1cbf077d95ac6c48aab.
- ByteTrack score thresholds and track lifecycle (fixed commit) · Lines 151-290: score split, high/low passes, lost-track reactivation, unconfirmed handling, new-track threshold, removal and output. Fixed commit d1bf0191adff59bc8fcfeaa0b33d3d1642552a99.
- Simple Online and Realtime Tracking — submission history · Submission history From: Alex Bewley [ view email ] [v1] Tue, 2 Feb 2016 01:39:28 UTC (66 KB) [v2] Fri, 7 Jul 2017 11:59:38 UTC (110 KB) Metadata/history only, not all revision contents.
- Simple Online and Realtime Tracking with a Deep Association Metric — submission history · Submission history From: Nicolai Wojke [ view email ] [v1] Tue, 21 Mar 2017 19:40:25 UTC (550 KB) Metadata/history only, not all revision contents.
- ByteTrack: Multi-Object Tracking by Associating Every Detection Box — submission history · Submission history From: Yifu Zhang [ view email ] [v1] Wed, 13 Oct 2021 17:01:26 UTC (5,057 KB) [v2] Thu, 14 Oct 2021 14:07:10 UTC (5,057 KB) [v3] Thu, 7 Apr 2022 16:36:24 UTC (7,166 KB) Metadata/history only, not all revision contents.
- HOTA: A Higher Order Metric for Evaluating Multi-Object Tracking — submission history · Submission history From: Jonathon Luiten [ view email ] [v1] Wed, 16 Sep 2020 15:11:30 UTC (1,695 KB) [v2] Tue, 29 Sep 2020 10:40:09 UTC (1,695 KB) Metadata/history only, not all revision contents.
- Fully-Convolutional Siamese Networks for Object Tracking — submission history · Submission history From: Andrea Vedaldi [ view email ] [v1] Thu, 30 Jun 2016 16:00:43 UTC (5,776 KB) [v2] Wed, 14 Sep 2016 11:48:29 UTC (7,230 KB) [v3] Wed, 1 Dec 2021 19:21:43 UTC (7,232 KB) Metadata/history only, not all revision contents.
- High-Speed Tracking with Kernelized Correlation Filters — submission history · Submission history From: João F. Henriques [ view email ] [v1] Wed, 30 Apr 2014 04:16:38 UTC (818 KB) [v2] Fri, 11 Jul 2014 23:04:01 UTC (969 KB) [v3] Wed, 5 Nov 2014 01:32:56 UTC (982 KB) Metadata/history only, not all revision contents.
- Performance Measures and a Data Set for Multi-Target, Multi-Camera Tracking — submission history · Submission history From: Ergys Ristani [ view email ] [v1] Tue, 6 Sep 2016 21:58:25 UTC (8,689 KB) [v2] Mon, 19 Sep 2016 17:27:19 UTC (9,563 KB) Metadata/history only, not all revision contents.
- HOTA — online publication and journal volume metadata · Publisher heading metadata: published 8 October 2020; volume 129, pages 548–578 (2021). Used for date distinction, not a claim of full journal-text review.
- MOTR: End-to-End Multiple-Object Tracking with Transformer · Physical pages 4-5 fully read; page 1 first 18 lines including title/authors/opening abstract. Detect/track queries, newborn-only and target-consistent training assignment. No reported performance or full model reproduction.
- CoTracker: It is Better to Track Together · v2 physical page 3 extracted text fully read, including task, coordinates/visibility and feature initialization; page 1 first 18 lines including authors/opening abstract. Figure encoding artifacts not interpreted as a visual inspection. No later variants or performance numbers adopted.
相关主题