center_tracker.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. This code is based on https://github.com/xingyizhou/CenterTrack/blob/master/src/lib/utils/tracker.py
  16. """
  17. import copy
  18. import numpy as np
  19. import sklearn
  20. __all__ = ['CenterTracker']
  21. class CenterTracker(object):
  22. __shared__ = ['num_classes']
  23. def __init__(self,
  24. num_classes=1,
  25. min_box_area=0,
  26. vertical_ratio=-1,
  27. track_thresh=0.4,
  28. pre_thresh=0.5,
  29. new_thresh=0.4,
  30. out_thresh=0.4,
  31. hungarian=False):
  32. self.num_classes = num_classes
  33. self.min_box_area = min_box_area
  34. self.vertical_ratio = vertical_ratio
  35. self.track_thresh = track_thresh
  36. self.pre_thresh = max(track_thresh, pre_thresh)
  37. self.new_thresh = max(track_thresh, new_thresh)
  38. self.out_thresh = max(track_thresh, out_thresh)
  39. self.hungarian = hungarian
  40. self.reset()
  41. def init_track(self, results):
  42. print('Initialize tracking!')
  43. for item in results:
  44. if item['score'] > self.new_thresh:
  45. self.id_count += 1
  46. item['tracking_id'] = self.id_count
  47. if not ('ct' in item):
  48. bbox = item['bbox']
  49. item['ct'] = [(bbox[0] + bbox[2]) / 2,
  50. (bbox[1] + bbox[3]) / 2]
  51. self.tracks.append(item)
  52. def reset(self):
  53. self.id_count = 0
  54. self.tracks = []
  55. def update(self, results, public_det=None):
  56. N = len(results)
  57. M = len(self.tracks)
  58. dets = np.array([det['ct'] + det['tracking'] for det in results],
  59. np.float32) # N x 2
  60. track_size = np.array([((track['bbox'][2] - track['bbox'][0]) * \
  61. (track['bbox'][3] - track['bbox'][1])) \
  62. for track in self.tracks], np.float32) # M
  63. track_cat = np.array([track['class'] for track in self.tracks],
  64. np.int32) # M
  65. item_size = np.array([((item['bbox'][2] - item['bbox'][0]) * \
  66. (item['bbox'][3] - item['bbox'][1])) \
  67. for item in results], np.float32) # N
  68. item_cat = np.array([item['class'] for item in results], np.int32) # N
  69. tracks = np.array([pre_det['ct'] for pre_det in self.tracks],
  70. np.float32) # M x 2
  71. dist = (((tracks.reshape(1, -1, 2) - \
  72. dets.reshape(-1, 1, 2)) ** 2).sum(axis=2)) # N x M
  73. invalid = ((dist > track_size.reshape(1, M)) + \
  74. (dist > item_size.reshape(N, 1)) + \
  75. (item_cat.reshape(N, 1) != track_cat.reshape(1, M))) > 0
  76. dist = dist + invalid * 1e18
  77. if self.hungarian:
  78. item_score = np.array([item['score'] for item in results],
  79. np.float32)
  80. dist[dist > 1e18] = 1e18
  81. from sklearn.utils.linear_assignment_ import linear_assignment
  82. matched_indices = linear_assignment(dist)
  83. else:
  84. matched_indices = greedy_assignment(copy.deepcopy(dist))
  85. unmatched_dets = [d for d in range(dets.shape[0]) \
  86. if not (d in matched_indices[:, 0])]
  87. unmatched_tracks = [d for d in range(tracks.shape[0]) \
  88. if not (d in matched_indices[:, 1])]
  89. if self.hungarian:
  90. matches = []
  91. for m in matched_indices:
  92. if dist[m[0], m[1]] > 1e16:
  93. unmatched_dets.append(m[0])
  94. unmatched_tracks.append(m[1])
  95. else:
  96. matches.append(m)
  97. matches = np.array(matches).reshape(-1, 2)
  98. else:
  99. matches = matched_indices
  100. ret = []
  101. for m in matches:
  102. track = results[m[0]]
  103. track['tracking_id'] = self.tracks[m[1]]['tracking_id']
  104. ret.append(track)
  105. # Private detection: create tracks for all un-matched detections
  106. for i in unmatched_dets:
  107. track = results[i]
  108. if track['score'] > self.new_thresh:
  109. self.id_count += 1
  110. track['tracking_id'] = self.id_count
  111. ret.append(track)
  112. self.tracks = ret
  113. return ret
  114. def greedy_assignment(dist):
  115. matched_indices = []
  116. if dist.shape[1] == 0:
  117. return np.array(matched_indices, np.int32).reshape(-1, 2)
  118. for i in range(dist.shape[0]):
  119. j = dist[i].argmin()
  120. if dist[i][j] < 1e16:
  121. dist[:, j] = 1e18
  122. matched_indices.append([i, j])
  123. return np.array(matched_indices, np.int32).reshape(-1, 2)