Meta Byte Track
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

matching.py 7.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. from __future__ import absolute_import
  2. from __future__ import division
  3. from __future__ import print_function
  4. import lap
  5. import numpy as np
  6. import scipy
  7. from cython_bbox import bbox_overlaps as bbox_ious
  8. from scipy.spatial.distance import cdist
  9. chi2inv95 = {
  10. 1: 3.8415,
  11. 2: 5.9915,
  12. 3: 7.8147,
  13. 4: 9.4877,
  14. 5: 11.070,
  15. 6: 12.592,
  16. 7: 14.067,
  17. 8: 15.507,
  18. 9: 16.919}
  19. def merge_matches(m1, m2, shape):
  20. O,P,Q = shape
  21. m1 = np.asarray(m1)
  22. m2 = np.asarray(m2)
  23. M1 = scipy.sparse.coo_matrix((np.ones(len(m1)), (m1[:, 0], m1[:, 1])), shape=(O, P))
  24. M2 = scipy.sparse.coo_matrix((np.ones(len(m2)), (m2[:, 0], m2[:, 1])), shape=(P, Q))
  25. mask = M1*M2
  26. match = mask.nonzero()
  27. match = list(zip(match[0], match[1]))
  28. unmatched_O = tuple(set(range(O)) - set([i for i, j in match]))
  29. unmatched_Q = tuple(set(range(Q)) - set([j for i, j in match]))
  30. return match, unmatched_O, unmatched_Q
  31. def _indices_to_matches(cost_matrix, indices, thresh):
  32. matched_cost = cost_matrix[tuple(zip(*indices))]
  33. matched_mask = (matched_cost <= thresh)
  34. matches = indices[matched_mask]
  35. unmatched_a = tuple(set(range(cost_matrix.shape[0])) - set(matches[:, 0]))
  36. unmatched_b = tuple(set(range(cost_matrix.shape[1])) - set(matches[:, 1]))
  37. return matches, unmatched_a, unmatched_b
  38. def linear_assignment(cost_matrix, thresh):
  39. if cost_matrix.size == 0:
  40. return np.empty((0, 2), dtype=int), tuple(range(cost_matrix.shape[0])), tuple(range(cost_matrix.shape[1]))
  41. matches, unmatched_a, unmatched_b = [], [], []
  42. cost, x, y = lap.lapjv(cost_matrix, extend_cost=True, cost_limit=thresh)
  43. for ix, mx in enumerate(x):
  44. if mx >= 0:
  45. matches.append([ix, mx])
  46. unmatched_a = np.where(x < 0)[0]
  47. unmatched_b = np.where(y < 0)[0]
  48. matches = np.asarray(matches)
  49. return matches, unmatched_a, unmatched_b
  50. def ious(atlbrs, btlbrs):
  51. """
  52. Compute cost based on IoU
  53. :type atlbrs: list[tlbr] | np.ndarray
  54. :type atlbrs: list[tlbr] | np.ndarray
  55. :rtype ious np.ndarray
  56. """
  57. ious = np.zeros((len(atlbrs), len(btlbrs)), dtype=np.float)
  58. if ious.size == 0:
  59. return ious
  60. ious = bbox_ious(
  61. np.ascontiguousarray(atlbrs, dtype=np.float),
  62. np.ascontiguousarray(btlbrs, dtype=np.float)
  63. )
  64. return ious
  65. def iou_distance(atracks, btracks):
  66. """
  67. Compute cost based on IoU
  68. :type atracks: list[STrack]
  69. :type btracks: list[STrack]
  70. :rtype cost_matrix np.ndarray
  71. """
  72. if (len(atracks)>0 and isinstance(atracks[0], np.ndarray)) or (len(btracks) > 0 and isinstance(btracks[0], np.ndarray)):
  73. atlbrs = atracks
  74. btlbrs = btracks
  75. else:
  76. atlbrs = [track.tlbr for track in atracks]
  77. btlbrs = [track.tlbr for track in btracks]
  78. _ious = ious(atlbrs, btlbrs)
  79. cost_matrix = 1 - _ious
  80. return cost_matrix
  81. def embedding_distance(tracks, detections, metric='cosine'):
  82. """
  83. :param tracks: list[STrack]
  84. :param detections: list[BaseTrack]
  85. :param metric:
  86. :return: cost_matrix np.ndarray
  87. """
  88. cost_matrix = np.zeros((len(tracks), len(detections)), dtype=np.float)
  89. if cost_matrix.size == 0:
  90. return cost_matrix
  91. det_features = np.asarray([track.curr_feat for track in detections], dtype=np.float)
  92. #for i, track in enumerate(tracks):
  93. #cost_matrix[i, :] = np.maximum(0.0, cdist(track.smooth_feat.reshape(1,-1), det_features, metric))
  94. track_features = np.asarray([track.smooth_feat for track in tracks], dtype=np.float)
  95. cost_matrix = np.maximum(0.0, cdist(track_features, det_features, metric)) # Nomalized features
  96. return cost_matrix
  97. def embedding_distance2(tracks, detections, metric='cosine'):
  98. """
  99. :param tracks: list[STrack]
  100. :param detections: list[BaseTrack]
  101. :param metric:
  102. :return: cost_matrix np.ndarray
  103. """
  104. cost_matrix = np.zeros((len(tracks), len(detections)), dtype=np.float)
  105. if cost_matrix.size == 0:
  106. return cost_matrix
  107. det_features = np.asarray([track.curr_feat for track in detections], dtype=np.float)
  108. #for i, track in enumerate(tracks):
  109. #cost_matrix[i, :] = np.maximum(0.0, cdist(track.smooth_feat.reshape(1,-1), det_features, metric))
  110. track_features = np.asarray([track.smooth_feat for track in tracks], dtype=np.float)
  111. cost_matrix = np.maximum(0.0, cdist(track_features, det_features, metric)) # Nomalized features
  112. track_features = np.asarray([track.features[0] for track in tracks], dtype=np.float)
  113. cost_matrix2 = np.maximum(0.0, cdist(track_features, det_features, metric)) # Nomalized features
  114. track_features = np.asarray([track.features[len(track.features)-1] for track in tracks], dtype=np.float)
  115. cost_matrix3 = np.maximum(0.0, cdist(track_features, det_features, metric)) # Nomalized features
  116. for row in range(len(cost_matrix)):
  117. cost_matrix[row] = (cost_matrix[row]+cost_matrix2[row]+cost_matrix3[row])/3
  118. return cost_matrix
  119. def vis_id_feature_A_distance(tracks, detections, metric='cosine'):
  120. track_features = []
  121. det_features = []
  122. leg1 = len(tracks)
  123. leg2 = len(detections)
  124. cost_matrix = np.zeros((leg1, leg2), dtype=np.float)
  125. cost_matrix_det = np.zeros((leg1, leg2), dtype=np.float)
  126. cost_matrix_track = np.zeros((leg1, leg2), dtype=np.float)
  127. det_features = np.asarray([track.curr_feat for track in detections], dtype=np.float)
  128. track_features = np.asarray([track.smooth_feat for track in tracks], dtype=np.float)
  129. if leg2 != 0:
  130. cost_matrix_det = np.maximum(0.0, cdist(det_features, det_features, metric))
  131. if leg1 != 0:
  132. cost_matrix_track = np.maximum(0.0, cdist(track_features, track_features, metric))
  133. if cost_matrix.size == 0:
  134. return track_features, det_features, cost_matrix, cost_matrix_det, cost_matrix_track
  135. cost_matrix = np.maximum(0.0, cdist(track_features, det_features, metric))
  136. if leg1 > 10:
  137. leg1 = 10
  138. tracks = tracks[:10]
  139. if leg2 > 10:
  140. leg2 = 10
  141. detections = detections[:10]
  142. det_features = np.asarray([track.curr_feat for track in detections], dtype=np.float)
  143. track_features = np.asarray([track.smooth_feat for track in tracks], dtype=np.float)
  144. return track_features, det_features, cost_matrix, cost_matrix_det, cost_matrix_track
  145. def gate_cost_matrix(kf, cost_matrix, tracks, detections, only_position=False):
  146. if cost_matrix.size == 0:
  147. return cost_matrix
  148. gating_dim = 2 if only_position else 4
  149. gating_threshold = chi2inv95[gating_dim]
  150. measurements = np.asarray([det.to_xyah() for det in detections])
  151. for row, track in enumerate(tracks):
  152. gating_distance = kf.gating_distance(
  153. track.mean, track.covariance, measurements, only_position)
  154. cost_matrix[row, gating_distance > gating_threshold] = np.inf
  155. return cost_matrix
  156. def fuse_motion(kf, cost_matrix, tracks, detections, only_position=False, lambda_=0.98):
  157. if cost_matrix.size == 0:
  158. return cost_matrix
  159. gating_dim = 2 if only_position else 4
  160. gating_threshold = chi2inv95[gating_dim]
  161. measurements = np.asarray([det.to_xyah() for det in detections])
  162. for row, track in enumerate(tracks):
  163. gating_distance = kf.gating_distance(
  164. track.mean, track.covariance, measurements, only_position, metric='maha')
  165. cost_matrix[row, gating_distance > gating_threshold] = np.inf
  166. cost_matrix[row] = lambda_ * cost_matrix[row] + (1 - lambda_) * gating_distance
  167. return cost_matrix