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.

byte_tracker.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. from __future__ import absolute_import
  2. from __future__ import division
  3. from __future__ import print_function
  4. import numpy as np
  5. from sklearn.utils.linear_assignment_ import linear_assignment
  6. import copy
  7. from .mot_online.kalman_filter import KalmanFilter
  8. from .mot_online.basetrack import BaseTrack, TrackState
  9. from .mot_online import matching
  10. class STrack(BaseTrack):
  11. shared_kalman = KalmanFilter()
  12. def __init__(self, tlwh, score):
  13. # wait activate
  14. self._tlwh = np.asarray(tlwh, dtype=np.float)
  15. self.kalman_filter = None
  16. self.mean, self.covariance = None, None
  17. self.is_activated = False
  18. self.score = score
  19. self.tracklet_len = 0
  20. def predict(self):
  21. mean_state = self.mean.copy()
  22. if self.state != TrackState.Tracked:
  23. mean_state[7] = 0
  24. self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance)
  25. @staticmethod
  26. def multi_predict(stracks):
  27. if len(stracks) > 0:
  28. multi_mean = np.asarray([st.mean.copy() for st in stracks])
  29. multi_covariance = np.asarray([st.covariance for st in stracks])
  30. for i, st in enumerate(stracks):
  31. if st.state != TrackState.Tracked:
  32. multi_mean[i][7] = 0
  33. multi_mean, multi_covariance = STrack.shared_kalman.multi_predict(multi_mean, multi_covariance)
  34. for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):
  35. stracks[i].mean = mean
  36. stracks[i].covariance = cov
  37. def activate(self, kalman_filter, frame_id):
  38. """Start a new tracklet"""
  39. self.kalman_filter = kalman_filter
  40. self.track_id = self.next_id()
  41. self.mean, self.covariance = self.kalman_filter.initiate(self.tlwh_to_xyah(self._tlwh))
  42. self.tracklet_len = 0
  43. self.state = TrackState.Tracked
  44. if frame_id == 1:
  45. self.is_activated = True
  46. # self.is_activated = True
  47. self.frame_id = frame_id
  48. self.start_frame = frame_id
  49. def re_activate(self, new_track, frame_id, new_id=False):
  50. self.mean, self.covariance = self.kalman_filter.update(
  51. self.mean, self.covariance, self.tlwh_to_xyah(new_track.tlwh)
  52. )
  53. self.tracklet_len = 0
  54. self.state = TrackState.Tracked
  55. self.is_activated = True
  56. self.frame_id = frame_id
  57. if new_id:
  58. self.track_id = self.next_id()
  59. self.score = new_track.score
  60. def update(self, new_track, frame_id):
  61. """
  62. Update a matched track
  63. :type new_track: STrack
  64. :type frame_id: int
  65. :type update_feature: bool
  66. :return:
  67. """
  68. self.frame_id = frame_id
  69. self.tracklet_len += 1
  70. new_tlwh = new_track.tlwh
  71. self.mean, self.covariance = self.kalman_filter.update(
  72. self.mean, self.covariance, self.tlwh_to_xyah(new_tlwh))
  73. self.state = TrackState.Tracked
  74. self.is_activated = True
  75. self.score = new_track.score
  76. @property
  77. # @jit(nopython=True)
  78. def tlwh(self):
  79. """Get current position in bounding box format `(top left x, top left y,
  80. width, height)`.
  81. """
  82. if self.mean is None:
  83. return self._tlwh.copy()
  84. ret = self.mean[:4].copy()
  85. ret[2] *= ret[3]
  86. ret[:2] -= ret[2:] / 2
  87. return ret
  88. @property
  89. # @jit(nopython=True)
  90. def tlbr(self):
  91. """Convert bounding box to format `(min x, min y, max x, max y)`, i.e.,
  92. `(top left, bottom right)`.
  93. """
  94. ret = self.tlwh.copy()
  95. ret[2:] += ret[:2]
  96. return ret
  97. @staticmethod
  98. # @jit(nopython=True)
  99. def tlwh_to_xyah(tlwh):
  100. """Convert bounding box to format `(center x, center y, aspect ratio,
  101. height)`, where the aspect ratio is `width / height`.
  102. """
  103. ret = np.asarray(tlwh).copy()
  104. ret[:2] += ret[2:] / 2
  105. ret[2] /= ret[3]
  106. return ret
  107. def to_xyah(self):
  108. return self.tlwh_to_xyah(self.tlwh)
  109. @staticmethod
  110. # @jit(nopython=True)
  111. def tlbr_to_tlwh(tlbr):
  112. ret = np.asarray(tlbr).copy()
  113. ret[2:] -= ret[:2]
  114. return ret
  115. @staticmethod
  116. # @jit(nopython=True)
  117. def tlwh_to_tlbr(tlwh):
  118. ret = np.asarray(tlwh).copy()
  119. ret[2:] += ret[:2]
  120. return ret
  121. def __repr__(self):
  122. return 'OT_{}_({}-{})'.format(self.track_id, self.start_frame, self.end_frame)
  123. class BYTETracker(object):
  124. def __init__(self, args, frame_rate=30):
  125. self.args = args
  126. self.det_thresh = args.new_thresh
  127. self.buffer_size = int(frame_rate / 30.0 * args.track_buffer)
  128. self.max_time_lost = self.buffer_size
  129. self.reset()
  130. # below has no effect to final output, just to be compatible to codebase
  131. def init_track(self, results):
  132. for item in results:
  133. if item['score'] > self.opt.new_thresh and item['class'] == 1:
  134. self.id_count += 1
  135. item['active'] = 1
  136. item['age'] = 1
  137. item['tracking_id'] = self.id_count
  138. if not ('ct' in item):
  139. bbox = item['bbox']
  140. item['ct'] = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]
  141. self.tracks.append(item)
  142. def reset(self):
  143. self.frame_id = 0
  144. self.kalman_filter = KalmanFilter()
  145. self.tracked_stracks = [] # type: list[STrack]
  146. self.lost_stracks = [] # type: list[STrack]
  147. self.removed_stracks = [] # type: list[STrack]
  148. self.tracks = []
  149. # below has no effect to final output, just to be compatible to codebase
  150. self.id_count = 0
  151. def step(self, results, public_det=None):
  152. self.frame_id += 1
  153. activated_starcks = []
  154. refind_stracks = []
  155. lost_stracks = []
  156. removed_stracks = []
  157. detections = []
  158. detections_second = []
  159. scores = np.array([item['score'] for item in results if item['class'] == 1], np.float32)
  160. bboxes = np.vstack([item['bbox'] for item in results if item['class'] == 1]) # N x 4, x1y1x2y2
  161. remain_inds = scores >= self.args.track_thresh
  162. dets = bboxes[remain_inds]
  163. scores_keep = scores[remain_inds]
  164. inds_low = scores > self.args.out_thresh
  165. inds_high = scores < self.args.track_thresh
  166. inds_second = np.logical_and(inds_low, inds_high)
  167. dets_second = bboxes[inds_second]
  168. scores_second = scores[inds_second]
  169. if len(dets) > 0:
  170. '''Detections'''
  171. detections = [STrack(STrack.tlbr_to_tlwh(tlbr), s) for
  172. (tlbr, s) in zip(dets, scores_keep)]
  173. else:
  174. detections = []
  175. ''' Add newly detected tracklets to tracked_stracks'''
  176. unconfirmed = []
  177. tracked_stracks = [] # type: list[STrack]
  178. for track in self.tracked_stracks:
  179. if not track.is_activated:
  180. unconfirmed.append(track)
  181. else:
  182. tracked_stracks.append(track)
  183. ''' Step 2: First association, with Kalman and IOU'''
  184. strack_pool = joint_stracks(tracked_stracks, self.lost_stracks)
  185. # Predict the current location with KF
  186. STrack.multi_predict(strack_pool)
  187. dists = matching.iou_distance(strack_pool, detections)
  188. #dists = matching.fuse_motion(self.kalman_filter, dists, strack_pool, detections)
  189. matches, u_track, u_detection = matching.linear_assignment(dists, thresh=self.args.match_thresh)
  190. for itracked, idet in matches:
  191. track = strack_pool[itracked]
  192. det = detections[idet]
  193. if track.state == TrackState.Tracked:
  194. track.update(detections[idet], self.frame_id)
  195. activated_starcks.append(track)
  196. else:
  197. track.re_activate(det, self.frame_id, new_id=False)
  198. refind_stracks.append(track)
  199. ''' Step 3: Second association, association the untrack to the low score detections, with IOU'''
  200. if len(dets_second) > 0:
  201. '''Detections'''
  202. detections_second = [STrack(STrack.tlbr_to_tlwh(tlbr), s) 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. matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
  227. for itracked, idet in matches:
  228. unconfirmed[itracked].update(detections[idet], self.frame_id)
  229. activated_starcks.append(unconfirmed[itracked])
  230. for it in u_unconfirmed:
  231. track = unconfirmed[it]
  232. track.mark_removed()
  233. removed_stracks.append(track)
  234. """ Step 4: Init new stracks"""
  235. for inew in u_detection:
  236. track = detections[inew]
  237. if track.score < self.det_thresh:
  238. continue
  239. track.activate(self.kalman_filter, self.frame_id)
  240. activated_starcks.append(track)
  241. """ Step 5: Update state"""
  242. for track in self.lost_stracks:
  243. if self.frame_id - track.end_frame > self.max_time_lost:
  244. track.mark_removed()
  245. removed_stracks.append(track)
  246. self.tracked_stracks = [t for t in self.tracked_stracks if t.state == TrackState.Tracked]
  247. self.tracked_stracks = joint_stracks(self.tracked_stracks, activated_starcks)
  248. self.tracked_stracks = joint_stracks(self.tracked_stracks, refind_stracks)
  249. self.lost_stracks = sub_stracks(self.lost_stracks, self.tracked_stracks)
  250. self.lost_stracks.extend(lost_stracks)
  251. self.lost_stracks = sub_stracks(self.lost_stracks, self.removed_stracks)
  252. self.removed_stracks.extend(removed_stracks)
  253. self.tracked_stracks, self.lost_stracks = remove_duplicate_stracks(self.tracked_stracks, self.lost_stracks)
  254. output_stracks = [track for track in self.tracked_stracks if track.is_activated]
  255. ret = []
  256. for track in output_stracks:
  257. track_dict = {}
  258. track_dict['score'] = track.score
  259. track_dict['bbox'] = track.tlbr
  260. bbox = track_dict['bbox']
  261. track_dict['ct'] = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]
  262. track_dict['active'] = 1 if track.is_activated else 0
  263. track_dict['tracking_id'] = track.track_id
  264. track_dict['class'] = 1
  265. ret.append(track_dict)
  266. self.tracks = ret
  267. return ret
  268. def joint_stracks(tlista, tlistb):
  269. exists = {}
  270. res = []
  271. for t in tlista:
  272. exists[t.track_id] = 1
  273. res.append(t)
  274. for t in tlistb:
  275. tid = t.track_id
  276. if not exists.get(tid, 0):
  277. exists[tid] = 1
  278. res.append(t)
  279. return res
  280. def sub_stracks(tlista, tlistb):
  281. stracks = {}
  282. for t in tlista:
  283. stracks[t.track_id] = t
  284. for t in tlistb:
  285. tid = t.track_id
  286. if stracks.get(tid, 0):
  287. del stracks[tid]
  288. return list(stracks.values())
  289. def remove_duplicate_stracks(stracksa, stracksb):
  290. pdist = matching.iou_distance(stracksa, stracksb)
  291. pairs = np.where(pdist < 0.15)
  292. dupa, dupb = list(), list()
  293. for p, q in zip(*pairs):
  294. timep = stracksa[p].frame_id - stracksa[p].start_frame
  295. timeq = stracksb[q].frame_id - stracksb[q].start_frame
  296. if timep > timeq:
  297. dupb.append(q)
  298. else:
  299. dupa.append(p)
  300. resa = [t for i, t in enumerate(stracksa) if not i in dupa]
  301. resb = [t for i, t in enumerate(stracksb) if not i in dupb]
  302. return resa, resb
  303. def remove_fp_stracks(stracksa, n_frame=10):
  304. remain = []
  305. for t in stracksa:
  306. score_5 = t.score_list[-n_frame:]
  307. score_5 = np.array(score_5, dtype=np.float32)
  308. index = score_5 < 0.45
  309. num = np.sum(index)
  310. if num < n_frame:
  311. remain.append(t)
  312. return remain