byte_tracker.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. import numpy as np
  2. from collections import deque
  3. import os
  4. import os.path as osp
  5. import copy
  6. import torch
  7. import torch.nn.functional as F
  8. from dev.src.utils.used_time import get_time
  9. from .kalman_filter import KalmanFilter
  10. from dependence.ByteTrack.yolox.tracker import matching
  11. from .basetrack import BaseTrack, TrackState
  12. class STrack(BaseTrack):
  13. shared_kalman = KalmanFilter()
  14. def __init__(self, tlwh, score, cls, tracker_max_id):
  15. super(STrack, self).__init__(tracker_max_id)
  16. # wait activate
  17. self._tlwh = np.asarray(tlwh, dtype=np.float64)
  18. self.kalman_filter = None
  19. self.mean, self.covariance = None, None
  20. self.is_activated = False
  21. self.score = score
  22. self.cls = cls
  23. self.tracklet_len = 0
  24. def predict(self):
  25. mean_state = self.mean.copy()
  26. if self.state != TrackState.Tracked:
  27. mean_state[7] = 0
  28. self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance)
  29. @staticmethod
  30. def multi_predict(stracks):
  31. if len(stracks) > 0:
  32. multi_mean = np.asarray([st.mean.copy() for st in stracks])
  33. multi_covariance = np.asarray([st.covariance for st in stracks])
  34. for i, st in enumerate(stracks):
  35. if st.state != TrackState.Tracked:
  36. multi_mean[i][7] = 0
  37. multi_mean, multi_covariance = STrack.shared_kalman.multi_predict(multi_mean, multi_covariance)
  38. for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):
  39. stracks[i].mean = mean
  40. stracks[i].covariance = cov
  41. def activate(self, kalman_filter, frame_id):
  42. """Start a new tracklet"""
  43. self.kalman_filter = kalman_filter
  44. self.track_id = self.next_id()
  45. self.mean, self.covariance = self.kalman_filter.initiate(self.tlwh_to_xyah(self._tlwh))
  46. self.tracklet_len = 0
  47. self.state = TrackState.Tracked
  48. if frame_id == 1:
  49. self.is_activated = True
  50. self.frame_id = frame_id
  51. self.start_frame = frame_id
  52. def re_activate(self, new_track, frame_id, new_id=False):
  53. self.mean, self.covariance = self.kalman_filter.update(
  54. self.mean, self.covariance, self.tlwh_to_xyah(new_track.tlwh)
  55. )
  56. self.tracklet_len = 0
  57. self.state = TrackState.Tracked
  58. self.is_activated = True
  59. self.frame_id = frame_id
  60. if new_id:
  61. self.track_id = self.next_id()
  62. self.score = new_track.score
  63. self.cls = new_track.cls
  64. def update(self, new_track, frame_id):
  65. """
  66. Update a matched track
  67. :type new_track: STrack
  68. :type frame_id: int
  69. :type update_feature: bool
  70. :return:
  71. """
  72. self.frame_id = frame_id
  73. self.tracklet_len += 1
  74. new_tlwh = new_track.tlwh
  75. self.mean, self.covariance = self.kalman_filter.update(
  76. self.mean, self.covariance, self.tlwh_to_xyah(new_tlwh))
  77. self.state = TrackState.Tracked
  78. self.is_activated = True
  79. self.score = new_track.score
  80. self.cls = new_track.cls
  81. @property
  82. # @jit(nopython=True)
  83. def tlwh(self):
  84. """Get current position in bounding box format `(top left x, top left y,
  85. width, height)`.
  86. """
  87. if self.mean is None:
  88. return self._tlwh.copy()
  89. ret = self.mean[:4].copy()
  90. ret[2] *= ret[3]
  91. ret[:2] -= ret[2:] / 2
  92. return ret
  93. @property
  94. # @jit(nopython=True)
  95. def tlbr(self):
  96. """Convert bounding box to format `(min x, min y, max x, max y)`, i.e.,
  97. `(top left, bottom right)`.
  98. """
  99. ret = self.tlwh.copy()
  100. ret[2:] += ret[:2]
  101. return ret
  102. @staticmethod
  103. # @jit(nopython=True)
  104. def tlwh_to_xyah(tlwh):
  105. """Convert bounding box to format `(center x, center y, aspect ratio,
  106. height)`, where the aspect ratio is `width / height`.
  107. """
  108. ret = np.asarray(tlwh).copy()
  109. ret[:2] += ret[2:] / 2
  110. ret[2] /= ret[3]
  111. return ret
  112. def to_xyah(self):
  113. return self.tlwh_to_xyah(self.tlwh)
  114. @staticmethod
  115. # @jit(nopython=True)
  116. def tlbr_to_tlwh(tlbr):
  117. ret = np.asarray(tlbr).copy()
  118. ret[2:] -= ret[:2]
  119. return ret
  120. @staticmethod
  121. # @jit(nopython=True)
  122. def tlwh_to_tlbr(tlwh):
  123. ret = np.asarray(tlwh).copy()
  124. ret[2:] += ret[:2]
  125. return ret
  126. def __repr__(self):
  127. return 'OT_{}_({}-{})'.format(self.track_id, self.start_frame, self.end_frame)
  128. class BYTETracker(object):
  129. """
  130. This class is used for mulit-object tracking, we use this model named Bytetracker because of high precision and
  131. high efficiency. The authority code website: https://github.com/ifzhang/ByteTrack
  132. """
  133. def __init__(self, args, frame_rate=30):
  134. self.tracked_stracks = [] # type: list[STrack]
  135. self.lost_stracks = [] # type: list[STrack]
  136. self.removed_stracks = [] # type: list[STrack]
  137. self.frame_id = 0
  138. self.args = args
  139. self.tracker_max_id = args.tracker_max_id
  140. # self.det_thresh = args.track_thresh
  141. self.det_thresh = args.track_thresh + 0.1
  142. self.buffer_size = int(frame_rate / 30.0 * args.track_buffer)
  143. self.max_time_lost = self.buffer_size
  144. self.kalman_filter = KalmanFilter()
  145. @get_time
  146. def update(self, output_results, img_info, img_size):
  147. self.frame_id += 1
  148. activated_starcks = []
  149. refind_stracks = []
  150. lost_stracks = []
  151. removed_stracks = []
  152. if output_results.shape[1] == 5:
  153. output_results = output_results.cpu().numpy()
  154. scores = output_results[:, 4]
  155. bboxes = output_results[:, :4]
  156. cls = np.zeros_like(scores)
  157. else:
  158. output_results = output_results.cpu().numpy()
  159. scores = output_results[:, 4]
  160. bboxes = output_results[:, :4] # x1y1x2y2
  161. cls = output_results[:, 5]
  162. remain_inds = scores > self.args.track_thresh
  163. inds_low = scores > 0.1
  164. inds_high = scores < self.args.track_thresh
  165. inds_second = np.logical_and(inds_low, inds_high)
  166. dets = bboxes[remain_inds]
  167. clss = cls[remain_inds]
  168. scores_keep = scores[remain_inds]
  169. scores_second = scores[inds_second]
  170. clss_second = cls[inds_second]
  171. dets_second = bboxes[inds_second]
  172. if len(dets) > 0:
  173. '''Detections'''
  174. detections = [STrack(STrack.tlbr_to_tlwh(tlbr), s, c, self.tracker_max_id) for
  175. (tlbr, s, c) in zip(dets, scores_keep, clss)]
  176. else:
  177. detections = []
  178. ''' Add newly detected tracklets to tracked_stracks'''
  179. unconfirmed = []
  180. tracked_stracks = [] # type: list[STrack]
  181. for track in self.tracked_stracks:
  182. if not track.is_activated:
  183. unconfirmed.append(track)
  184. else:
  185. tracked_stracks.append(track)
  186. ''' Step 2: First association, with high score detection boxes'''
  187. strack_pool = joint_stracks(tracked_stracks, self.lost_stracks)
  188. # Predict the current location with KF
  189. STrack.multi_predict(strack_pool)
  190. dists = matching.iou_distance(strack_pool, detections)
  191. if not self.args.mot20:
  192. dists = matching.fuse_score(dists, detections)
  193. matches, u_track, u_detection = matching.linear_assignment(dists, thresh=self.args.match_thresh)
  194. for itracked, idet in matches:
  195. track = strack_pool[itracked]
  196. det = detections[idet]
  197. if track.state == TrackState.Tracked:
  198. track.update(detections[idet], self.frame_id)
  199. activated_starcks.append(track)
  200. else:
  201. track.re_activate(det, self.frame_id, new_id=False)
  202. refind_stracks.append(track)
  203. ''' Step 3: Second association, with low score detection boxes'''
  204. # association the untrack to the low score detections
  205. if len(dets_second) > 0:
  206. '''Detections'''
  207. detections_second = [STrack(STrack.tlbr_to_tlwh(tlbr), s, c, self.tracker_max_id) for
  208. (tlbr, s, c) in zip(dets_second, scores_second, clss_second)]
  209. else:
  210. detections_second = []
  211. r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
  212. dists = matching.iou_distance(r_tracked_stracks, detections_second)
  213. matches, u_track, u_detection_second = matching.linear_assignment(dists, thresh=0.5)
  214. for itracked, idet in matches:
  215. track = r_tracked_stracks[itracked]
  216. det = detections_second[idet]
  217. if track.state == TrackState.Tracked:
  218. track.update(det, self.frame_id)
  219. activated_starcks.append(track)
  220. else:
  221. track.re_activate(det, self.frame_id, new_id=False)
  222. refind_stracks.append(track)
  223. for it in u_track:
  224. track = r_tracked_stracks[it]
  225. if not track.state == TrackState.Lost:
  226. track.mark_lost()
  227. lost_stracks.append(track)
  228. '''Deal with unconfirmed tracks, usually tracks with only one beginning frame'''
  229. detections = [detections[i] for i in u_detection]
  230. dists = matching.iou_distance(unconfirmed, detections)
  231. if not self.args.mot20:
  232. dists = matching.fuse_score(dists, detections)
  233. matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
  234. for itracked, idet in matches:
  235. unconfirmed[itracked].update(detections[idet], self.frame_id)
  236. activated_starcks.append(unconfirmed[itracked])
  237. for it in u_unconfirmed:
  238. track = unconfirmed[it]
  239. track.mark_removed()
  240. removed_stracks.append(track)
  241. """ Step 4: Init new stracks"""
  242. for inew in u_detection:
  243. track = detections[inew]
  244. if track.score < self.det_thresh:
  245. continue
  246. track.activate(self.kalman_filter, self.frame_id)
  247. activated_starcks.append(track)
  248. """ Step 5: Update state"""
  249. for track in self.lost_stracks:
  250. if self.frame_id - track.end_frame > self.max_time_lost:
  251. track.mark_removed()
  252. removed_stracks.append(track)
  253. self.tracked_stracks = [t for t in self.tracked_stracks if t.state == TrackState.Tracked]
  254. self.tracked_stracks = joint_stracks(self.tracked_stracks, activated_starcks)
  255. self.tracked_stracks = joint_stracks(self.tracked_stracks, refind_stracks)
  256. self.lost_stracks = sub_stracks(self.lost_stracks, self.tracked_stracks)
  257. self.lost_stracks.extend(lost_stracks)
  258. self.lost_stracks = sub_stracks(self.lost_stracks, self.removed_stracks)
  259. self.removed_stracks.extend(removed_stracks)
  260. self.tracked_stracks, self.lost_stracks = remove_duplicate_stracks(self.tracked_stracks, self.lost_stracks)
  261. # get scores of lost tracks
  262. output_stracks = [track for track in self.tracked_stracks if track.is_activated]
  263. return output_stracks
  264. def joint_stracks(tlista, tlistb):
  265. exists = {}
  266. res = []
  267. for t in tlista:
  268. exists[t.track_id] = 1
  269. res.append(t)
  270. for t in tlistb:
  271. tid = t.track_id
  272. if not exists.get(tid, 0):
  273. exists[tid] = 1
  274. res.append(t)
  275. return res
  276. def sub_stracks(tlista, tlistb):
  277. stracks = {}
  278. for t in tlista:
  279. stracks[t.track_id] = t
  280. for t in tlistb:
  281. tid = t.track_id
  282. if stracks.get(tid, 0):
  283. del stracks[tid]
  284. return list(stracks.values())
  285. def remove_duplicate_stracks(stracksa, stracksb):
  286. pdist = matching.iou_distance(stracksa, stracksb)
  287. pairs = np.where(pdist < 0.15)
  288. dupa, dupb = list(), list()
  289. for p, q in zip(*pairs):
  290. timep = stracksa[p].frame_id - stracksa[p].start_frame
  291. timeq = stracksb[q].frame_id - stracksb[q].start_frame
  292. if timep > timeq:
  293. dupb.append(q)
  294. else:
  295. dupa.append(p)
  296. resa = [t for i, t in enumerate(stracksa) if not i in dupa]
  297. resb = [t for i, t in enumerate(stracksb) if not i in dupb]
  298. return resa, resb