byte_tracker.py 12 KB

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