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

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