matching.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. import numpy as np
  3. import scipy
  4. from scipy.spatial.distance import cdist
  5. from ultralytics.utils.metrics import batch_probiou, bbox_ioa
  6. try:
  7. import lap # for linear_assignment
  8. assert lap.__version__ # verify package is not directory
  9. except (ImportError, AssertionError, AttributeError):
  10. from ultralytics.utils.checks import check_requirements
  11. check_requirements("lap>=0.5.12") # https://github.com/gatagat/lap
  12. import lap
  13. def linear_assignment(cost_matrix: np.ndarray, thresh: float, use_lap: bool = True) -> tuple:
  14. """
  15. Perform linear assignment using either the scipy or lap.lapjv method.
  16. Args:
  17. cost_matrix (np.ndarray): The matrix containing cost values for assignments, with shape (N, M).
  18. thresh (float): Threshold for considering an assignment valid.
  19. use_lap (bool): Use lap.lapjv for the assignment. If False, scipy.optimize.linear_sum_assignment is used.
  20. Returns:
  21. matched_indices (np.ndarray): Array of matched indices of shape (K, 2), where K is the number of matches.
  22. unmatched_a (np.ndarray): Array of unmatched indices from the first set, with shape (L,).
  23. unmatched_b (np.ndarray): Array of unmatched indices from the second set, with shape (M,).
  24. Examples:
  25. >>> cost_matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  26. >>> thresh = 5.0
  27. >>> matched_indices, unmatched_a, unmatched_b = linear_assignment(cost_matrix, thresh, use_lap=True)
  28. """
  29. if cost_matrix.size == 0:
  30. return np.empty((0, 2), dtype=int), tuple(range(cost_matrix.shape[0])), tuple(range(cost_matrix.shape[1]))
  31. if use_lap:
  32. # Use lap.lapjv
  33. # https://github.com/gatagat/lap
  34. _, x, y = lap.lapjv(cost_matrix, extend_cost=True, cost_limit=thresh)
  35. matches = [[ix, mx] for ix, mx in enumerate(x) if mx >= 0]
  36. unmatched_a = np.where(x < 0)[0]
  37. unmatched_b = np.where(y < 0)[0]
  38. else:
  39. # Use scipy.optimize.linear_sum_assignment
  40. # https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linear_sum_assignment.html
  41. x, y = scipy.optimize.linear_sum_assignment(cost_matrix) # row x, col y
  42. matches = np.asarray([[x[i], y[i]] for i in range(len(x)) if cost_matrix[x[i], y[i]] <= thresh])
  43. if len(matches) == 0:
  44. unmatched_a = list(np.arange(cost_matrix.shape[0]))
  45. unmatched_b = list(np.arange(cost_matrix.shape[1]))
  46. else:
  47. unmatched_a = list(set(np.arange(cost_matrix.shape[0])) - set(matches[:, 0]))
  48. unmatched_b = list(set(np.arange(cost_matrix.shape[1])) - set(matches[:, 1]))
  49. return matches, unmatched_a, unmatched_b
  50. def iou_distance(atracks: list, btracks: list) -> np.ndarray:
  51. """
  52. Compute cost based on Intersection over Union (IoU) between tracks.
  53. Args:
  54. atracks (list[STrack] | list[np.ndarray]): List of tracks 'a' or bounding boxes.
  55. btracks (list[STrack] | list[np.ndarray]): List of tracks 'b' or bounding boxes.
  56. Returns:
  57. (np.ndarray): Cost matrix computed based on IoU.
  58. Examples:
  59. Compute IoU distance between two sets of tracks
  60. >>> atracks = [np.array([0, 0, 10, 10]), np.array([20, 20, 30, 30])]
  61. >>> btracks = [np.array([5, 5, 15, 15]), np.array([25, 25, 35, 35])]
  62. >>> cost_matrix = iou_distance(atracks, btracks)
  63. """
  64. if atracks and isinstance(atracks[0], np.ndarray) or btracks and isinstance(btracks[0], np.ndarray):
  65. atlbrs = atracks
  66. btlbrs = btracks
  67. else:
  68. atlbrs = [track.xywha if track.angle is not None else track.xyxy for track in atracks]
  69. btlbrs = [track.xywha if track.angle is not None else track.xyxy for track in btracks]
  70. ious = np.zeros((len(atlbrs), len(btlbrs)), dtype=np.float32)
  71. if len(atlbrs) and len(btlbrs):
  72. if len(atlbrs[0]) == 5 and len(btlbrs[0]) == 5:
  73. ious = batch_probiou(
  74. np.ascontiguousarray(atlbrs, dtype=np.float32),
  75. np.ascontiguousarray(btlbrs, dtype=np.float32),
  76. ).numpy()
  77. else:
  78. ious = bbox_ioa(
  79. np.ascontiguousarray(atlbrs, dtype=np.float32),
  80. np.ascontiguousarray(btlbrs, dtype=np.float32),
  81. iou=True,
  82. )
  83. return 1 - ious # cost matrix
  84. def embedding_distance(tracks: list, detections: list, metric: str = "cosine") -> np.ndarray:
  85. """
  86. Compute distance between tracks and detections based on embeddings.
  87. Args:
  88. tracks (list[STrack]): List of tracks, where each track contains embedding features.
  89. detections (list[BaseTrack]): List of detections, where each detection contains embedding features.
  90. metric (str): Metric for distance computation. Supported metrics include 'cosine', 'euclidean', etc.
  91. Returns:
  92. (np.ndarray): Cost matrix computed based on embeddings with shape (N, M), where N is the number of tracks
  93. and M is the number of detections.
  94. Examples:
  95. Compute the embedding distance between tracks and detections using cosine metric
  96. >>> tracks = [STrack(...), STrack(...)] # List of track objects with embedding features
  97. >>> detections = [BaseTrack(...), BaseTrack(...)] # List of detection objects with embedding features
  98. >>> cost_matrix = embedding_distance(tracks, detections, metric="cosine")
  99. """
  100. cost_matrix = np.zeros((len(tracks), len(detections)), dtype=np.float32)
  101. if cost_matrix.size == 0:
  102. return cost_matrix
  103. det_features = np.asarray([track.curr_feat for track in detections], dtype=np.float32)
  104. # for i, track in enumerate(tracks):
  105. # cost_matrix[i, :] = np.maximum(0.0, cdist(track.smooth_feat.reshape(1,-1), det_features, metric))
  106. track_features = np.asarray([track.smooth_feat for track in tracks], dtype=np.float32)
  107. cost_matrix = np.maximum(0.0, cdist(track_features, det_features, metric)) # Normalized features
  108. return cost_matrix
  109. def fuse_score(cost_matrix: np.ndarray, detections: list) -> np.ndarray:
  110. """
  111. Fuses cost matrix with detection scores to produce a single similarity matrix.
  112. Args:
  113. cost_matrix (np.ndarray): The matrix containing cost values for assignments, with shape (N, M).
  114. detections (list[BaseTrack]): List of detections, each containing a score attribute.
  115. Returns:
  116. (np.ndarray): Fused similarity matrix with shape (N, M).
  117. Examples:
  118. Fuse a cost matrix with detection scores
  119. >>> cost_matrix = np.random.rand(5, 10) # 5 tracks and 10 detections
  120. >>> detections = [BaseTrack(score=np.random.rand()) for _ in range(10)]
  121. >>> fused_matrix = fuse_score(cost_matrix, detections)
  122. """
  123. if cost_matrix.size == 0:
  124. return cost_matrix
  125. iou_sim = 1 - cost_matrix
  126. det_scores = np.array([det.score for det in detections])
  127. det_scores = np.expand_dims(det_scores, axis=0).repeat(cost_matrix.shape[0], axis=0)
  128. fuse_sim = iou_sim * det_scores
  129. return 1 - fuse_sim # fuse_cost