当前位置:   article > 正文

基于yolov5的deepsort目标追踪--deepsort源码讲解_yolov5 deepsort

yolov5 deepsort

多目标追踪的主要步骤

获取原始视频帧数

利用目标检测器对目标进行检测(此处用的为yolov5

将检测到的目标框进行特征提取,一般特征提取用的是ReID

计算前后两帧的目标匹配程度(利用匈牙利算法和级联匹配),为每个追踪到的目标匹配ID。

什么是ReID

行人重识别(Person Re-identification也称行人再识别,简称为ReID,是利用计算机视觉技术判断图像或者视频序列中是否存在特定行人的技术。广泛被认为是一个图像检索的子问题。给定一个监控行人图像,检索跨设备下的该行人图像。也就是看下一帧检测出的人是不是上一帧的人。在本项目中我们主要是训练一个ReID模型来对yolov5检测到的和track进行特征提取,提取出一个128维度的特征向量,进行比较。

一.sort与deepsort

deepsort是以sort为基础加入了deep也就是深度学习。主要体现在加入了级联匹配Matching Cascade(优先缺失帧数最小的进行匹配)和新轨迹confirmed的确认,其余的大体上还是sort的结构。deepsort相对于sort的优点在于,当物体发生遮挡时,不会将物体丢失。(加入了feature)

Harlek提供的SORT解析图

sort没有ReID等深度学习特征

 图片来自知乎Harlek

二.重要环节

1.匈牙利匹配(KM算法)

大白话:匈牙利算法可以告诉我们当前帧的某个目标,是否与前一帧的某个目标相同。

其实就是通过通过代价矩阵来解决分配问题。

当我们拿到一个代价矩阵,对其进行化简是一个问题,我们在化简时要遵循:如果代价矩阵的某一行或某一列同时加上或减去某个数,则这个新的代价矩阵的最优分配仍然是原代价矩阵的最优分配。这一原则。

具体算法步骤: 

  1. 对于矩阵的每一行,减去其中最小的元素
  2. 对于矩阵的每一列,减去其中最小的元素
  3. 用最少的水平线或垂直线覆盖矩阵中所有的0
  4. 如果线的数量等于N,则找到了最优分配,算法结束,否则进入步骤5
  5. 找到没有被任何线覆盖的最小元素,每个没被线覆盖的行减去这个元素,每个被线覆盖的列加上这个元素,返回步骤3

代码实现:

  1. def min_cost_matching(
  2. distance_metric, max_distance, tracks, detections, track_indices=None,
  3. detection_indices=None):
  4. """Solve linear assignment problem.
  5. Parameters
  6. ----------
  7. distance_metric : Callable[List[Track], List[Detection], List[int], List[int]) -> ndarray
  8. The distance metric is given a list of tracks and detections as well as
  9. a list of N track indices and M detection indices. The metric should
  10. return the NxM dimensional cost matrix, where element (i, j) is the
  11. association cost between the i-th track in the given track indices and
  12. the j-th detection in the given detection_indices.
  13. max_distance : float
  14. Gating threshold. Associations with cost larger than this value are
  15. disregarded.
  16. tracks : List[track.Track]
  17. A list of predicted tracks at the current time step.
  18. detections : List[detection.Detection]
  19. A list of detections at the current time step.
  20. track_indices : List[int]
  21. List of track indices that maps rows in `cost_matrix` to tracks in
  22. `tracks` (see description above).
  23. detection_indices : List[int]
  24. List of detection indices that maps columns in `cost_matrix` to
  25. detections in `detections` (see description above).
  26. Returns
  27. -------
  28. (List[(int, int)], List[int], List[int])
  29. Returns a tuple with the following three entries:
  30. * A list of matched track and detection indices.
  31. * A list of unmatched track indices.
  32. * A list of unmatched detection indices.
  33. """
  34. if track_indices is None:
  35. track_indices = np.arange(len(tracks))
  36. if detection_indices is None:
  37. detection_indices = np.arange(len(detections))
  38. if len(detection_indices) == 0 or len(track_indices) == 0:
  39. return [], track_indices, detection_indices # Nothing to match.
  40. # 计算成本矩阵
  41. cost_matrix = distance_metric(
  42. tracks, detections, track_indices, detection_indices)
  43. cost_matrix[cost_matrix > max_distance] = max_distance + 1e-5
  44. # 执行匈牙利算法,得到指派成功的索引对,行索引为tracks的索引,列索引为detections的索引
  45. row_indices, col_indices = linear_assignment(cost_matrix)
  46. matches, unmatched_tracks, unmatched_detections = [], [], []
  47. # 找出未匹配的detections
  48. for col, detection_idx in enumerate(detection_indices):
  49. if col not in col_indices:
  50. unmatched_detections.append(detection_idx)
  51. # 找出未匹配的tracks
  52. for row, track_idx in enumerate(track_indices):
  53. if row not in row_indices:
  54. unmatched_tracks.append(track_idx)
  55. # 遍历匹配的(track, detection)索引对
  56. for row, col in zip(row_indices, col_indices):
  57. track_idx = track_indices[row]
  58. detection_idx = detection_indices[col]
  59. # 如果相应的cost大于阈值max_distance,也视为未匹配成功
  60. if cost_matrix[row, col] > max_distance:
  61. unmatched_tracks.append(track_idx)
  62. unmatched_detections.append(detection_idx)
  63. else:
  64. matches.append((track_idx, detection_idx))
  65. return matches, unmatched_tracks, unmatched_detections

2.卡尔曼滤波 

在目标跟踪中,需要估计track的以下两个状态:

  • 均值(Mean):表示目标的位置信息,由bbox的中心坐标 (cx, cy),宽高比r,高h,以及各自的速度变化值组成,由8维向量表示为 x = [cx, cy, r, h, vx, vy, vr, vh],各个速度值初始化为0。
  • 协方差(Covariance ):表示目标位置信息的不确定性,由8x8的对角矩阵表示,矩阵中数字越大则表明不确定性越大,可以以任意值初始化。

卡尔曼滤波分为两个阶段:(1) 预测track在下一时刻的位置,(2) 基于detection来更新预测的位置。 

(1)预测 

基于track在t-1时刻的状态来预测其在t时刻的状态。

x'=Fx        (1)

P'=FPF^T+Q        (2)

在公式1中,x为track在t-1时刻的均值,F称为状态转移矩阵,该公式预测t时刻的x' 

矩阵F中的dt是当前帧和前一帧之间的差,将等号右边的矩阵乘法展开,可以得到cx'=cx+dt*vx,cy'=cy+dt*vy...,所以这里的卡尔曼滤波是一个匀速模型(Constant Velocity Model)。

在公式2中,P为track在t-1时刻的协方差,Q为系统的噪声矩阵,代表整个系统的可靠程度,一般初始化为很小的值,该公式预测t时刻的P'

代码实现:

  1. def predict(self, mean, covariance):
  2. """Run Kalman filter prediction step.
  3. Parameters
  4. ----------
  5. mean : ndarray
  6. The 8 dimensional mean vector of the object state at the previous
  7. time step.
  8. covariance : ndarray
  9. The 8x8 dimensional covariance matrix of the object state at the
  10. previous time step.
  11. Returns
  12. -------
  13. (ndarray, ndarray)
  14. Returns the mean vector and covariance matrix of the predicted
  15. state. Unobserved velocities are initialized to 0 mean.
  16. """
  17. #卡尔曼滤波器由目标上一时刻的均值和协方差进行预测。
  18. std_pos = [
  19. self._std_weight_position * mean[3],
  20. self._std_weight_position * mean[3],
  21. 1e-2,
  22. self._std_weight_position * mean[3]]
  23. std_vel = [
  24. self._std_weight_velocity * mean[3],
  25. self._std_weight_velocity * mean[3],
  26. 1e-5,
  27. self._std_weight_velocity * mean[3]]
  28. # 初始化噪声矩阵Q;np.r_ 按列连接两个矩阵
  29. # motion_cov是过程噪声 W_k的 协方差矩阵Qk
  30. motion_cov = np.diag(np.square(np.r_[std_pos, std_vel]))
  31. # Update time state x' = Fx (1)
  32. # x为track在t-1时刻的均值,F称为状态转移矩阵,该公式预测t时刻的x'
  33. # self._motion_mat为F_k是作用在 x_{k-1}上的状态变换模型
  34. mean = np.dot(self._motion_mat, mean)
  35. # Calculate error covariance P' = FPF^T+Q (2)
  36. # P为track在t-1时刻的协方差,Q为系统的噪声矩阵,代表整个系统的可靠程度,一般初始化为很小的值,
  37. # 该公式预测t时刻的P'
  38. # covariance为P_{k|k} ,后验估计误差协方差矩阵,度量估计值的精确程度
  39. covariance = np.linalg.multi_dot((
  40. self._motion_mat, covariance, self._motion_mat.T)) + motion_cov
  41. return mean, covariance

(2)更新 

基于t时刻检测到的detection,校正与其关联的track的状态,得到一个更精确的结果。

y=z-Hx'         (3)

S=HP'H^T+R        (4)

K=P'H^TS^{-1}        (5)

x=x'+Ky        (6)

P=(I-KH)P'        (7)

在公式3中,z为detection的均值向量,不包含速度变化值,即z=[cx, cy, r, h]H称为测量矩阵,它将track的均值向量x'映射到检测空间,该公式计算detection和track的均值误差;

在公式4中,R为检测器的噪声矩阵,它是一个4x4的对角矩阵,对角线上的值分别为中心点两个坐标以及宽高的噪声,以任意值初始化,一般设置宽高的噪声大于中心点的噪声,该公式先将协方差矩阵P'映射到检测空间,然后再加上噪声矩阵R;

公式5计算卡尔曼增益K,卡尔曼增益用于估计误差的重要程度;

公式6和公式7得到更新后的均值向量x和协方差矩阵P。

源码:

  1. def project(self, mean, covariance):
  2. """Project state distribution to measurement space.
  3. 投影状态分布到测量空间
  4. Parameters
  5. ----------
  6. mean : ndarray
  7. The state's mean vector (8 dimensional array).
  8. covariance : ndarray
  9. The state's covariance matrix (8x8 dimensional).
  10. mean:ndarray,状态的平均向量(8维数组)。
  11. covariance:ndarray,状态的协方差矩阵(8x8维)。
  12. Returns
  13. -------
  14. (ndarray, ndarray)
  15. Returns the projected mean and covariance matrix of the given state
  16. estimate.
  17. 返回(ndarray,ndarray),返回给定状态估计的投影平均值和协方差矩阵
  18. """
  19. # 在公式4中,R为检测器的噪声矩阵,它是一个4x4的对角矩阵,
  20. # 对角线上的值分别为中心点两个坐标以及宽高的噪声,
  21. # 以任意值初始化,一般设置宽高的噪声大于中心点的噪声,
  22. # 该公式先将协方差矩阵P'映射到检测空间,然后再加上噪声矩阵R;
  23. std = [
  24. self._std_weight_position * mean[3],
  25. self._std_weight_position * mean[3],
  26. 1e-1,
  27. self._std_weight_position * mean[3]]
  28. # R为测量过程中噪声的协方差;初始化噪声矩阵R
  29. innovation_cov = np.diag(np.square(std))
  30. # 将均值向量映射到检测空间,即 Hx'
  31. mean = np.dot(self._update_mat, mean)
  32. # 将协方差矩阵映射到检测空间,即 HP'H^T
  33. covariance = np.linalg.multi_dot((
  34. self._update_mat, covariance, self._update_mat.T))
  35. return mean, covariance + innovation_cov # 公式(4)
  36. def update(self, mean, covariance, measurement):
  37. """Run Kalman filter correction step.
  38. 通过估计值和观测值估计最新结果
  39. Parameters
  40. ----------
  41. mean : ndarray
  42. The predicted state's mean vector (8 dimensional).
  43. covariance : ndarray
  44. The state's covariance matrix (8x8 dimensional).
  45. measurement : ndarray
  46. The 4 dimensional measurement vector (x, y, a, h), where (x, y)
  47. is the center position, a the aspect ratio, and h the height of the
  48. bounding box.
  49. Returns
  50. -------
  51. (ndarray, ndarray)
  52. Returns the measurement-corrected state distribution.
  53. """
  54. # 将均值和协方差映射到检测空间,得到 Hx'和S
  55. projected_mean, projected_cov = self.project(mean, covariance)
  56. # 矩阵分解
  57. chol_factor, lower = scipy.linalg.cho_factor(
  58. projected_cov, lower=True, check_finite=False)
  59. # 计算卡尔曼增益K;相当于求解公式(5)
  60. # 公式5计算卡尔曼增益K,卡尔曼增益用于估计误差的重要程度
  61. # 求解卡尔曼滤波增益K 用到了cholesky矩阵分解加快求解;
  62. # 公式5的右边有一个S的逆,如果S矩阵很大,S的逆求解消耗时间太大,
  63. # 所以代码中把公式两边同时乘上S,右边的S*S的逆变成了单位矩阵,转化成AX=B形式求解。
  64. kalman_gain = scipy.linalg.cho_solve(
  65. (chol_factor, lower), np.dot(covariance, self._update_mat.T).T,
  66. check_finite=False).T
  67. # y = z - Hx' (3)
  68. # 在公式3中,z为detection的均值向量,不包含速度变化值,即z=[cx, cy, r, h],
  69. # H称为测量矩阵,它将track的均值向量x'映射到检测空间,该公式计算detection和track的均值误差
  70. innovation = measurement - projected_mean
  71. # 更新后的均值向量 x = x' + Ky (6)
  72. new_mean = mean + np.dot(innovation, kalman_gain.T)
  73. # 更新后的协方差矩阵 P = (I - KH)P' (7)
  74. new_covariance = covariance - np.linalg.multi_dot((
  75. kalman_gain, projected_cov, kalman_gain.T))
  76. return new_mean, new_covariance

参考 目标跟踪初探(DeepSORT) - 知乎 (zhihu.com)

三.deepsort部分的源码解析

1.sort源码分析

(1)detection.py用来保存通过目标检测后的检测框

  1. import numpy as np
  2. class Detection(object):
  3. def __init__(self, tlwh, confidence, feature):
  4. self.tlwh = np.asarray(tlwh, dtype=np.float)
  5. self.confidence = float(confidence)
  6. self.feature = np.asarray(feature, dtype=np.float32)
  7. def to_tlbr(self):
  8. """Convert bounding box to format `(min x, min y, max x, max y)`, i.e.,
  9. `(top left, bottom right)`.
  10. """
  11. ret = self.tlwh.copy()
  12. ret[2:] += ret[:2]
  13. return ret
  14. def to_xyah(self):
  15. """Convert bounding box to format `(center x, center y, aspect ratio,
  16. height)`, where the aspect ratio is `width / height`.
  17. """
  18. ret = self.tlwh.copy()
  19. ret[:2] += ret[2:] / 2
  20. ret[2] /= ret[3]
  21. return ret
  • tlwh: 代表左上角坐标+宽高
  • tlbr: 代表左上角坐标+右下角坐标
  • xyah: 代表中心坐标+宽高比+高

 (2)track类

  1. class Track:
  2. """
  3. A single target track with state space `(x, y, a, h)` and associated
  4. velocities, where `(x, y)` is the center of the bounding box, `a` is the
  5. aspect ratio and `h` is the height.
  6. 具有状态空间(x,y,a,h)并关联速度的单个目标轨迹(track),
  7. 其中(x,y)是边界框的中心,a是宽高比,h是高度。
  8. Parameters
  9. ----------
  10. mean : ndarray
  11. Mean vector of the initial state distribution.
  12. 初始状态分布的均值向量
  13. covariance : ndarray
  14. Covariance matrix of the initial state distribution.
  15. 初始状态分布的协方差矩阵
  16. track_id : int
  17. A unique track identifier.
  18. 唯一的track标识符
  19. n_init : int
  20. Number of consecutive detections before the track is confirmed. The
  21. track state is set to `Deleted` if a miss occurs within the first
  22. `n_init` frames.
  23. 确认track之前的连续检测次数。 在第一个n_init帧中
  24. 第一个未命中的情况下将跟踪状态设置为“Deleted”
  25. max_age : int
  26. The maximum number of consecutive misses before the track state is
  27. set to `Deleted`.
  28. 跟踪状态设置为Deleted之前的最大连续未命中数;代表一个track的存活期限
  29. feature : Optional[ndarray]
  30. Feature vector of the detection this track originates from. If not None,
  31. this feature is added to the `features` cache.
  32. 此track所源自的检测的特征向量。 如果不是None,此feature已添加到feature缓存中。
  33. Attributes
  34. ----------
  35. mean : ndarray
  36. Mean vector of the initial state distribution.
  37. 初始状态分布的均值向量
  38. covariance : ndarray
  39. Covariance matrix of the initial state distribution.
  40. 初始状态分布的协方差矩阵
  41. track_id : int
  42. A unique track identifier.
  43. hits : int
  44. Total number of measurement updates.
  45. 测量更新总数
  46. age : int
  47. Total number of frames since first occurence.
  48. 自第一次出现以来的总帧数
  49. time_since_update : int
  50. Total number of frames since last measurement update.
  51. 自上次测量更新以来的总帧数
  52. state : TrackState
  53. The current track state.
  54. features : List[ndarray]
  55. A cache of features. On each measurement update, the associated feature
  56. vector is added to this list.
  57. feature缓存。每次测量更新时,相关feature向量添加到此列表中
  58. """
  59. def __init__(self, mean, covariance, track_id, n_init, max_age,
  60. feature=None):
  61. self.mean = mean
  62. self.covariance = covariance
  63. self.track_id = track_id
  64. # hits代表匹配上了多少次,匹配次数超过n_init,设置Confirmed状态
  65. # hits每次调用update函数的时候+1
  66. self.hits = 1
  67. self.age = 1 # 和time_since_update功能重复
  68. # 每次调用predict函数的时候就会+1; 每次调用update函数的时候就会设置为0
  69. self.time_since_update = 0
  70. self.state = TrackState.Tentative # 初始化一个Track的时设置Tentative状态
  71. # 每个track对应多个features, 每次更新都会将最新的feature添加到列表中
  72. self.features = []
  73. if feature is not None:
  74. self.features.append(feature)
  75. self._n_init = n_init
  76. self._max_age = max_age

 state代表框的状态,在deepsort里面有三种confirmed,unconfirmed(tentative),deleted。

 

(3)计算欧氏距离

什么是欧氏距离?

它是在m维空间中两个点之间的真实距离。

代码实现

  1. def _pdist(a, b):
  2. """Compute pair-wise squared distance between points in `a` and `b`.
  3. Parameters
  4. ----------
  5. a : array_like
  6. An NxM matrix of N samples of dimensionality M.
  7. b : array_like
  8. An LxM matrix of L samples of dimensionality M.
  9. Returns
  10. -------
  11. ndarray
  12. Returns a matrix of size len(a), len(b) such that element (i, j)
  13. contains the squared distance between `a[i]` and `b[j]`.
  14. 用于计算成对点之间的平方距离
  15. a :NxM 矩阵,代表 N 个样本,每个样本 M 个数值
  16. b :LxM 矩阵,代表 L 个样本,每个样本有 M 个数值
  17. 返回的是 NxL 的矩阵,比如 dist[i][j] 代表 a[i] 和 b[j] 之间的平方和距离
  18. 参考:https://blog.csdn.net/frankzd/article/details/80251042
  19. """
  20. a, b = np.asarray(a), np.asarray(b)
  21. if len(a) == 0 or len(b) == 0:
  22. return np.zeros((len(a), len(b)))
  23. a2, b2 = np.square(a).sum(axis=1), np.square(b).sum(axis=1)
  24. r2 = -2. * np.dot(a, b.T) + a2[:, None] + b2[None, :]
  25. r2 = np.clip(r2, 0., float(np.inf))
  26. return r2

(4)计算余弦距离 

什么是余弦距离?

 用向量空间中两个向量夹角的余弦值作为衡量两个个体间差异的大小的度量。要确定两个向量方向是否一致,这就要用到余弦定理计算向量的夹角。

代码实现

  1. def _cosine_distance(a, b, data_is_normalized=False):
  2. """Compute pair-wise cosine distance between points in `a` and `b`.
  3. Parameters
  4. ----------
  5. a : array_like
  6. An NxM matrix of N samples of dimensionality M.
  7. b : array_like
  8. An LxM matrix of L samples of dimensionality M.
  9. data_is_normalized : Optional[bool]
  10. If True, assumes rows in a and b are unit length vectors.
  11. Otherwise, a and b are explicitly normalized to lenght 1.
  12. Returns
  13. -------
  14. ndarray
  15. Returns a matrix of size len(a), len(b) such that eleement (i, j)
  16. contains the squared distance between `a[i]` and `b[j]`.
  17. 用于计算成对点之间的余弦距离
  18. a :NxM 矩阵,代表 N 个样本,每个样本 M 个数值
  19. b :LxM 矩阵,代表 L 个样本,每个样本有 M 个数值
  20. 返回的是 NxL 的矩阵,比如 c[i][j] 代表 a[i] 和 b[j] 之间的余弦距离
  21. 参考:
  22. https://blog.csdn.net/u013749540/article/details/51813922
  23. """
  24. if not data_is_normalized:
  25. # np.linalg.norm 求向量的范式,默认是 L2 范式
  26. a = np.asarray(a) / np.linalg.norm(a, axis=1, keepdims=True)
  27. b = np.asarray(b) / np.linalg.norm(b, axis=1, keepdims=True)
  28. return 1. - np.dot(a, b.T) # 余弦距离 = 1 - 余弦相似度

(5)最近邻距离度量类

对于每个目标,返回最近邻距的距离度量,即与目前为止已观察到的任何样本的最接近距离。

利用上述的欧氏距离和余弦距离来得出结论。

  1. class NearestNeighborDistanceMetric(object):
  2. # 对于每个目标,返回一个最近的距离
  3. def __init__(self, metric, matching_threshold, budget=None):
  4. # 默认matching_threshold = 0.2 budge = 100
  5. if metric == "euclidean":
  6. # 使用最近邻欧氏距离
  7. self._metric = _nn_euclidean_distance
  8. elif metric == "cosine":
  9. # 使用最近邻余弦距离
  10. self._metric = _nn_cosine_distance
  11. else:
  12. raise ValueError("Invalid metric; must be either 'euclidean' or 'cosine'")
  13. self.matching_threshold = matching_threshold
  14. # 在级联匹配的函数中调用
  15. self.budget = budget
  16. # budge 预算,控制feature的多少
  17. self.samples = {}
  18. # samples是一个字典{id->feature list}
  19. def partial_fit(self, features, targets, active_targets):
  20. # 作用:部分拟合,用新的数据更新测量距离
  21. # 调用:在特征集更新模块部分调用,tracker.update()中
  22. for feature, target in zip(features, targets):
  23. self.samples.setdefault(target, []).append(feature)
  24. # 对应目标下添加新的feature,更新feature集合
  25. # 目标id : feature list
  26. if self.budget is not None:
  27. self.samples[target] = self.samples[target][-self.budget:]
  28. # 设置预算,每个类最多多少个目标,超过直接忽略
  29. # 筛选激活的目标
  30. self.samples = {k: self.samples[k] for k in active_targets}
  31. def distance(self, features, targets):
  32. # 作用:比较feature和targets之间的距离,返回一个代价矩阵
  33. # 调用:在匹配阶段,将distance封装为gated_metric,
  34. # 进行外观信息(reid得到的深度特征)+
  35. # 运动信息(马氏距离用于度量两个分布相似程度)
  36. cost_matrix = np.zeros((len(targets), len(features)))
  37. for i, target in enumerate(targets):
  38. cost_matrix[i, :] = self._metric(self.samples[target], features)
  39. return cost_matrix

(6)tracker类

tracker集合了多个track,里面包含卡尔曼滤波的更新和预测和匈牙利匹配,iou匹配等等重要任务。

  1. class Tracker:
  2. # 是一个多目标tracker,保存了很多个track轨迹
  3. # 负责调用卡尔曼滤波来预测track的新状态+进行匹配工作+初始化第一帧
  4. # Tracker调用update或predict的时候,其中的每个track也会各自调用自己的update或predict
  5. """
  6. This is the multi-target tracker.
  7. """
  8. def __init__(self, metric, max_iou_distance=0.7, max_age=70, n_init=3):
  9. # 调用的时候,后边的参数全部是默认的
  10. self.metric = metric
  11. # metric是一个类,用于计算距离(余弦距离或马氏距离)
  12. self.max_iou_distance = max_iou_distance
  13. # 最大iou,iou匹配的时候使用
  14. self.max_age = max_age
  15. # 直接指定级联匹配的cascade_depth参数,也就是删除轨迹前的最大未命中数
  16. self.n_init = n_init
  17. # n_init代表需要n_init次数的update才会将track状态设置为confirmed
  18. self.kf = kalman_filter.KalmanFilter()# 卡尔曼滤波器
  19. self.tracks = [] # 保存一系列轨迹
  20. self._next_id = 1 # 下一个分配的轨迹id
  21. def predict(self):
  22. # 遍历每个track都进行一次预测,将跟踪状态分布向前传播一步
  23. """Propagate track state distributions one time step forward.
  24. This function should be called once every time step, before `update`.
  25. """
  26. for track in self.tracks:
  27. track.predict(self.kf)

tracker里还有两大重要的函数,是update和match。

update的代码如下:

  1. def update(self, detections):
  2. """Perform measurement update and track management.
  3. 执行测量更新和轨迹管理
  4. Parameters
  5. ----------
  6. detections : List[deep_sort.detection.Detection]
  7. A list of detections at the current time step.
  8. """
  9. # Run matching cascade.
  10. matches, unmatched_tracks, unmatched_detections = \
  11. self._match(detections)
  12. # Update track set.
  13. # 1. 针对匹配上的结果
  14. for track_idx, detection_idx in matches:
  15. # 更新tracks中相应的detection
  16. self.tracks[track_idx].update(
  17. self.kf, detections[detection_idx])
  18. # 2. 针对未匹配的track, 调用mark_missed进行标记
  19. # track失配时,若Tantative则删除;若update时间很久也删除
  20. # max age是一个存活期限,默认为70帧
  21. for track_idx in unmatched_tracks:
  22. self.tracks[track_idx].mark_missed()
  23. # 3. 针对未匹配的detection, detection失配,进行初始化
  24. for detection_idx in unmatched_detections:
  25. self._initiate_track(detections[detection_idx])
  26. # 得到最新的tracks列表,保存的是标记为Confirmed和Tentative的track
  27. self.tracks = [t for t in self.tracks if not t.is_deleted()]
  28. # Update distance metric.
  29. active_targets = [t.track_id for t in self.tracks if t.is_confirmed()]
  30. features, targets = [], []
  31. for track in self.tracks:
  32. # 获取所有Confirmed状态的track id
  33. if not track.is_confirmed():
  34. continue
  35. features += track.features # 将Confirmed状态的track的features添加到features列表
  36. # 获取每个feature对应的trackid
  37. targets += [track.track_id for _ in track.features]
  38. track.features = []
  39. # 距离度量中的特征集更新
  40. self.metric.partial_fit(
  41. np.asarray(features), np.asarray(targets), active_targets)

match函数

  1. def _match(self, detections):
  2. # 主要功能是进行匹配,找到匹配的,未匹配的部分
  3. def gated_metric(tracks, dets, track_indices, detection_indices):
  4. # 功能: 用于计算track和detection之间的距离,代价函数
  5. # 需要使用在KM算法之前
  6. # 调用:
  7. # cost_matrix = distance_metric(tracks, detections,
  8. # track_indices, detection_indices)
  9. features = np.array([dets[i].feature for i in detection_indices])
  10. targets = np.array([tracks[i].track_id for i in track_indices])
  11. # 1. 通过最近邻计算出代价矩阵 cosine distance
  12. cost_matrix = self.metric.distance(features, targets)
  13. # 2. 计算马氏距离,得到新的状态矩阵
  14. cost_matrix = linear_assignment.gate_cost_matrix(
  15. self.kf, cost_matrix, tracks, dets, track_indices,
  16. detection_indices)
  17. return cost_matrix
  18. # Split track set into confirmed and unconfirmed tracks.
  19. # 划分不同轨迹的状态
  20. confirmed_tracks = [
  21. i for i, t in enumerate(self.tracks) if t.is_confirmed()
  22. ]
  23. unconfirmed_tracks = [
  24. i for i, t in enumerate(self.tracks) if not t.is_confirmed()
  25. ]
  26. # 进行级联匹配,得到匹配的track、不匹配的track、不匹配的detection
  27. '''
  28. !!!!!!!!!!!
  29. 级联匹配
  30. !!!!!!!!!!!
  31. '''
  32. # gated_metric->cosine distance
  33. # 仅仅对确定态的轨迹进行级联匹配
  34. matches_a, unmatched_tracks_a, unmatched_detections = \
  35. linear_assignment.matching_cascade(
  36. gated_metric,
  37. self.metric.matching_threshold,
  38. self.max_age,
  39. self.tracks,
  40. detections,
  41. confirmed_tracks)
  42. # 将所有状态为未确定态的轨迹和刚刚没有匹配上的轨迹组合为iou_track_candidates,
  43. # 进行IoU的匹配
  44. iou_track_candidates = unconfirmed_tracks + [
  45. k for k in unmatched_tracks_a
  46. if self.tracks[k].time_since_update == 1 # 刚刚没有匹配上
  47. ]
  48. # 未匹配
  49. unmatched_tracks_a = [
  50. k for k in unmatched_tracks_a
  51. if self.tracks[k].time_since_update != 1 # 已经很久没有匹配上
  52. ]
  53. '''
  54. !!!!!!!!!!!
  55. IOU 匹配
  56. 对级联匹配中还没有匹配成功的目标再进行IoU匹配
  57. !!!!!!!!!!!
  58. '''
  59. # 虽然和级联匹配中使用的都是min_cost_matching作为核心,
  60. # 这里使用的metric是iou cost和以上不同
  61. matches_b, unmatched_tracks_b, unmatched_detections = \
  62. linear_assignment.min_cost_matching(
  63. iou_matching.iou_cost,
  64. self.max_iou_distance,
  65. self.tracks,
  66. detections,
  67. iou_track_candidates,
  68. unmatched_detections)
  69. matches = matches_a + matches_b # 组合两部分match得到的结果
  70. unmatched_tracks = list(set(unmatched_tracks_a + unmatched_tracks_b))
  71. return matches, unmatched_tracks, unmatched_detections

(7)级联匹配

  1. def matching_cascade(
  2. distance_metric, max_distance, cascade_depth, tracks, detections,
  3. track_indices=None, detection_indices=None):
  4. """Run matching cascade.
  5. Parameters
  6. ----------
  7. distance_metric : Callable[List[Track], List[Detection], List[int], List[int]) -> ndarray
  8. The distance metric is given a list of tracks and detections as well as
  9. a list of N track indices and M detection indices. The metric should
  10. return the NxM dimensional cost matrix, where element (i, j) is the
  11. association cost between the i-th track in the given track indices and
  12. the j-th detection in the given detection indices.
  13. 距离度量:
  14. 输入:一个轨迹和检测列表,以及一个N个轨迹索引和M个检测索引的列表。
  15. 返回:NxM维的代价矩阵,其中元素(i,j)是给定轨迹索引中第i个轨迹与
  16. 给定检测索引中第j个检测之间的关联成本。
  17. max_distance : float
  18. Gating threshold. Associations with cost larger than this value are
  19. disregarded.
  20. 门控阈值。成本大于此值的关联将被忽略。
  21. cascade_depth: int
  22. The cascade depth, should be se to the maximum track age.
  23. 级联深度应设置为最大轨迹寿命。
  24. tracks : List[track.Track]
  25. A list of predicted tracks at the current time step.
  26. 当前时间步的预测轨迹列表。
  27. detections : List[detection.Detection]
  28. A list of detections at the current time step.
  29. 当前时间步的检测列表。
  30. track_indices : Optional[List[int]]
  31. List of track indices that maps rows in `cost_matrix` to tracks in
  32. `tracks` (see description above). Defaults to all tracks.
  33. 轨迹索引列表,用于将 cost_matrix中的行映射到tracks的
  34. 轨迹(请参见上面的说明)。 默认为所有轨迹。
  35. detection_indices : Optional[List[int]]
  36. List of detection indices that maps columns in `cost_matrix` to
  37. detections in `detections` (see description above). Defaults to all
  38. detections.
  39. 将 cost_matrix中的列映射到的检测索引列表
  40. detections中的检测(请参见上面的说明)。 默认为全部检测。
  41. Returns
  42. -------
  43. (List[(int, int)], List[int], List[int])
  44. Returns a tuple with the following three entries:
  45. * A list of matched track and detection indices.
  46. * A list of unmatched track indices.
  47. * A list of unmatched detection indices.
  48. 返回包含以下三个条目的元组:
  49. 匹配的跟踪和检测的索引列表,
  50. 不匹配的轨迹索引的列表,
  51. 未匹配的检测索引的列表。
  52. """
  53. # 分配track_indices和detection_indices两个列表
  54. if track_indices is None:
  55. track_indices = list(range(len(tracks)))
  56. if detection_indices is None:
  57. detection_indices = list(range(len(detections)))
  58. # 初始化匹配集matches M ← ∅
  59. # 未匹配检测集unmatched_detections U ← D
  60. unmatched_detections = detection_indices
  61. matches = []
  62. # 由小到大依次对每个level的tracks做匹配
  63. for level in range(cascade_depth):
  64. # 如果没有detections,退出循环
  65. if len(unmatched_detections) == 0: # No detections left
  66. break
  67. # 当前level的所有tracks索引
  68. # 步骤6:Select tracks by age
  69. track_indices_l = [
  70. k for k in track_indices
  71. if tracks[k].time_since_update == 1 + level
  72. ]
  73. # 如果当前level没有track,继续
  74. if len(track_indices_l) == 0: # Nothing to match at this level
  75. continue
  76. # 步骤7:调用min_cost_matching函数进行匹配
  77. matches_l, _, unmatched_detections = \
  78. min_cost_matching(
  79. distance_metric, max_distance, tracks, detections,
  80. track_indices_l, unmatched_detections)
  81. matches += matches_l # 步骤8
  82. unmatched_tracks = list(set(track_indices) - set(k for k, _ in matches)) # 步骤9
  83. return matches, unmatched_tracks, unmatched_detections

(8)门控矩阵


门控成本矩阵:通过计算卡尔曼滤波的状态分布和测量值之间的距离对成本矩阵进行限制,
成本矩阵中的距离是track和detection之间的外观相似度。
如果一个轨迹要去匹配两个外观特征非常相似的 detection,很容易出错;
分别让两个detection计算与这个轨迹的马氏距离,并使用一个阈值gating_threshold进行限制,
就可以将马氏距离较远的那个detection区分开,从而减少错误的匹配。
代码:

  1. def gate_cost_matrix(
  2. kf, cost_matrix, tracks, detections, track_indices, detection_indices,
  3. gated_cost=INFTY_COST, only_position=False):
  4. """Invalidate infeasible entries in cost matrix based on the state
  5. distributions obtained by Kalman filtering.
  6. Parameters
  7. ----------
  8. kf : The Kalman filter.
  9. cost_matrix : ndarray
  10. The NxM dimensional cost matrix, where N is the number of track indices
  11. and M is the number of detection indices, such that entry (i, j) is the
  12. association cost between `tracks[track_indices[i]]` and
  13. `detections[detection_indices[j]]`.
  14. tracks : List[track.Track]
  15. A list of predicted tracks at the current time step.
  16. detections : List[detection.Detection]
  17. A list of detections at the current time step.
  18. track_indices : List[int]
  19. List of track indices that maps rows in `cost_matrix` to tracks in
  20. `tracks` (see description above).
  21. detection_indices : List[int]
  22. List of detection indices that maps columns in `cost_matrix` to
  23. detections in `detections` (see description above).
  24. gated_cost : Optional[float]
  25. Entries in the cost matrix corresponding to infeasible associations are
  26. set this value. Defaults to a very large value.
  27. 代价矩阵中与不可行关联相对应的条目设置此值。 默认为一个很大的值。
  28. only_position : Optional[bool]
  29. If True, only the x, y position of the state distribution is considered
  30. during gating. Defaults to False.
  31. 如果为True,则在门控期间仅考虑状态分布的x,y位置。默认为False。
  32. Returns
  33. -------
  34. ndarray
  35. Returns the modified cost matrix.
  36. """
  37. # 根据通过卡尔曼滤波获得的状态分布,使成本矩阵中的不可行条目无效。
  38. gating_dim = 2 if only_position else 4 # 测量空间维度
  39. # 马氏距离通过测算检测与平均轨迹位置的距离超过多少标准差来考虑状态估计的不确定性。
  40. # 通过从逆chi^2分布计算95%置信区间的阈值,排除可能性小的关联。
  41. # 四维测量空间对应的马氏阈值为9.4877
  42. gating_threshold = kalman_filter.chi2inv95[gating_dim]
  43. measurements = np.asarray(
  44. [detections[i].to_xyah() for i in detection_indices])
  45. for row, track_idx in enumerate(track_indices):
  46. track = tracks[track_idx]
  47. #KalmanFilter.gating_distance 计算状态分布和测量之间的选通距离
  48. gating_distance = kf.gating_distance(track.mean, track.covariance, measurements, only_position)
  49. cost_matrix[row, gating_distance > gating_threshold] = gated_cost
  50. return cost_matrix

四.总结

以上就是Deep SORT算法代码部分的解析,核心在于类图和流程图,理解Deep SORT实现的过程。其余内容以后慢慢补充,感谢观看。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/313019
推荐阅读
相关标签
  

闽ICP备14008679号