byte_tracker.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import numpy as np
  3. from .basetrack import BaseTrack, TrackState
  4. from .utils import matching
  5. from .utils.kalman_filter import KalmanFilterXYAH
  6. class STrack(BaseTrack):
  7. shared_kalman = KalmanFilterXYAH()
  8. def __init__(self, tlwh, score, cls):
  9. """wait activate."""
  10. self._tlwh = np.asarray(self.tlbr_to_tlwh(tlwh[:-1]), dtype=np.float32)
  11. self.kalman_filter = None
  12. self.mean, self.covariance = None, None
  13. self.is_activated = False
  14. self.score = score
  15. self.tracklet_len = 0
  16. self.cls = cls
  17. self.idx = tlwh[-1]
  18. def predict(self):
  19. """Predicts mean and covariance using Kalman filter."""
  20. mean_state = self.mean.copy()
  21. if self.state != TrackState.Tracked:
  22. mean_state[7] = 0
  23. self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance)
  24. @staticmethod
  25. def multi_predict(stracks):
  26. """Perform multi-object predictive tracking using Kalman filter for given stracks."""
  27. if len(stracks) <= 0:
  28. return
  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. @staticmethod
  39. def multi_gmc(stracks, H=np.eye(2, 3)):
  40. """Update state tracks positions and covariances using a homography matrix."""
  41. if len(stracks) > 0:
  42. multi_mean = np.asarray([st.mean.copy() for st in stracks])
  43. multi_covariance = np.asarray([st.covariance for st in stracks])
  44. R = H[:2, :2]
  45. R8x8 = np.kron(np.eye(4, dtype=float), R)
  46. t = H[:2, 2]
  47. for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):
  48. mean = R8x8.dot(mean)
  49. mean[:2] += t
  50. cov = R8x8.dot(cov).dot(R8x8.transpose())
  51. stracks[i].mean = mean
  52. stracks[i].covariance = cov
  53. def activate(self, kalman_filter, frame_id):
  54. """Start a new tracklet."""
  55. self.kalman_filter = kalman_filter
  56. self.track_id = self.next_id()
  57. self.mean, self.covariance = self.kalman_filter.initiate(self.convert_coords(self._tlwh))
  58. self.tracklet_len = 0
  59. self.state = TrackState.Tracked
  60. if frame_id == 1:
  61. self.is_activated = True
  62. self.frame_id = frame_id
  63. self.start_frame = frame_id
  64. def re_activate(self, new_track, frame_id, new_id=False):
  65. """Reactivates a previously lost track with a new detection."""
  66. self.mean, self.covariance = self.kalman_filter.update(self.mean, self.covariance,
  67. self.convert_coords(new_track.tlwh))
  68. self.tracklet_len = 0
  69. self.state = TrackState.Tracked
  70. self.is_activated = True
  71. self.frame_id = frame_id
  72. if new_id:
  73. self.track_id = self.next_id()
  74. self.score = new_track.score
  75. self.cls = new_track.cls
  76. self.idx = new_track.idx
  77. def update(self, new_track, frame_id):
  78. """
  79. Update a matched track
  80. :type new_track: STrack
  81. :type frame_id: int
  82. :return:
  83. """
  84. self.frame_id = frame_id
  85. self.tracklet_len += 1
  86. new_tlwh = new_track.tlwh
  87. self.mean, self.covariance = self.kalman_filter.update(self.mean, self.covariance,
  88. self.convert_coords(new_tlwh))
  89. self.state = TrackState.Tracked
  90. self.is_activated = True
  91. self.score = new_track.score
  92. self.cls = new_track.cls
  93. self.idx = new_track.idx
  94. def convert_coords(self, tlwh):
  95. """Convert a bounding box's top-left-width-height format to its x-y-angle-height equivalent."""
  96. return self.tlwh_to_xyah(tlwh)
  97. @property
  98. def tlwh(self):
  99. """Get current position in bounding box format `(top left x, top left y,
  100. width, height)`.
  101. """
  102. if self.mean is None:
  103. return self._tlwh.copy()
  104. ret = self.mean[:4].copy()
  105. ret[2] *= ret[3]
  106. ret[:2] -= ret[2:] / 2
  107. return ret
  108. @property
  109. def tlbr(self):
  110. """Convert bounding box to format `(min x, min y, max x, max y)`, i.e.,
  111. `(top left, bottom right)`.
  112. """
  113. ret = self.tlwh.copy()
  114. ret[2:] += ret[:2]
  115. return ret
  116. @staticmethod
  117. def tlwh_to_xyah(tlwh):
  118. """Convert bounding box to format `(center x, center y, aspect ratio,
  119. height)`, where the aspect ratio is `width / height`.
  120. """
  121. ret = np.asarray(tlwh).copy()
  122. ret[:2] += ret[2:] / 2
  123. ret[2] /= ret[3]
  124. return ret
  125. @staticmethod
  126. def tlbr_to_tlwh(tlbr):
  127. """Converts top-left bottom-right format to top-left width height format."""
  128. ret = np.asarray(tlbr).copy()
  129. ret[2:] -= ret[:2]
  130. return ret
  131. @staticmethod
  132. def tlwh_to_tlbr(tlwh):
  133. """Converts tlwh bounding box format to tlbr format."""
  134. ret = np.asarray(tlwh).copy()
  135. ret[2:] += ret[:2]
  136. return ret
  137. def __repr__(self):
  138. """Return a string representation of the BYTETracker object with start and end frames and track ID."""
  139. return f'OT_{self.track_id}_({self.start_frame}-{self.end_frame})'
  140. class BYTETracker:
  141. def __init__(self, args, frame_rate=30):
  142. """Initialize a YOLOv8 object to track objects with given arguments and frame rate."""
  143. self.tracked_stracks = [] # type: list[STrack]
  144. self.lost_stracks = [] # type: list[STrack]
  145. self.removed_stracks = [] # type: list[STrack]
  146. self.frame_id = 0
  147. self.args = args
  148. self.max_time_lost = int(frame_rate / 30.0 * args.track_buffer)
  149. self.kalman_filter = self.get_kalmanfilter()
  150. self.reset_id()
  151. def update(self, results, img=None):
  152. """Updates object tracker with new detections and returns tracked object bounding boxes."""
  153. self.frame_id += 1
  154. activated_stracks = []
  155. refind_stracks = []
  156. lost_stracks = []
  157. removed_stracks = []
  158. scores = results.conf
  159. bboxes = results.xyxy
  160. # Add index
  161. bboxes = np.concatenate([bboxes, np.arange(len(bboxes)).reshape(-1, 1)], axis=-1)
  162. cls = results.cls
  163. remain_inds = scores > self.args.track_high_thresh
  164. inds_low = scores > self.args.track_low_thresh
  165. inds_high = scores < self.args.track_high_thresh
  166. inds_second = np.logical_and(inds_low, inds_high)
  167. dets_second = bboxes[inds_second]
  168. dets = bboxes[remain_inds]
  169. scores_keep = scores[remain_inds]
  170. scores_second = scores[inds_second]
  171. cls_keep = cls[remain_inds]
  172. cls_second = cls[inds_second]
  173. detections = self.init_track(dets, scores_keep, cls_keep, img)
  174. # Add newly detected tracklets to tracked_stracks
  175. unconfirmed = []
  176. tracked_stracks = [] # type: list[STrack]
  177. for track in self.tracked_stracks:
  178. if not track.is_activated:
  179. unconfirmed.append(track)
  180. else:
  181. tracked_stracks.append(track)
  182. # Step 2: First association, with high score detection boxes
  183. strack_pool = self.joint_stracks(tracked_stracks, self.lost_stracks)
  184. # Predict the current location with KF
  185. self.multi_predict(strack_pool)
  186. if hasattr(self, 'gmc') and img is not None:
  187. warp = self.gmc.apply(img, dets)
  188. STrack.multi_gmc(strack_pool, warp)
  189. STrack.multi_gmc(unconfirmed, warp)
  190. dists = self.get_dists(strack_pool, detections)
  191. matches, u_track, u_detection = matching.linear_assignment(dists, thresh=self.args.match_thresh)
  192. for itracked, idet in matches:
  193. track = strack_pool[itracked]
  194. det = detections[idet]
  195. if track.state == TrackState.Tracked:
  196. track.update(det, self.frame_id)
  197. activated_stracks.append(track)
  198. else:
  199. track.re_activate(det, self.frame_id, new_id=False)
  200. refind_stracks.append(track)
  201. # Step 3: Second association, with low score detection boxes
  202. # association the untrack to the low score detections
  203. detections_second = self.init_track(dets_second, scores_second, cls_second, img)
  204. r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
  205. # TODO
  206. dists = matching.iou_distance(r_tracked_stracks, detections_second)
  207. matches, u_track, u_detection_second = matching.linear_assignment(dists, thresh=0.5)
  208. for itracked, idet in matches:
  209. track = r_tracked_stracks[itracked]
  210. det = detections_second[idet]
  211. if track.state == TrackState.Tracked:
  212. track.update(det, self.frame_id)
  213. activated_stracks.append(track)
  214. else:
  215. track.re_activate(det, self.frame_id, new_id=False)
  216. refind_stracks.append(track)
  217. for it in u_track:
  218. track = r_tracked_stracks[it]
  219. if track.state != TrackState.Lost:
  220. track.mark_lost()
  221. lost_stracks.append(track)
  222. # Deal with unconfirmed tracks, usually tracks with only one beginning frame
  223. detections = [detections[i] for i in u_detection]
  224. dists = self.get_dists(unconfirmed, detections)
  225. matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
  226. for itracked, idet in matches:
  227. unconfirmed[itracked].update(detections[idet], self.frame_id)
  228. activated_stracks.append(unconfirmed[itracked])
  229. for it in u_unconfirmed:
  230. track = unconfirmed[it]
  231. track.mark_removed()
  232. removed_stracks.append(track)
  233. # Step 4: Init new stracks
  234. for inew in u_detection:
  235. track = detections[inew]
  236. if track.score < self.args.new_track_thresh:
  237. continue
  238. track.activate(self.kalman_filter, self.frame_id)
  239. activated_stracks.append(track)
  240. # Step 5: Update state
  241. for track in self.lost_stracks:
  242. if self.frame_id - track.end_frame > self.max_time_lost:
  243. track.mark_removed()
  244. removed_stracks.append(track)
  245. self.tracked_stracks = [t for t in self.tracked_stracks if t.state == TrackState.Tracked]
  246. self.tracked_stracks = self.joint_stracks(self.tracked_stracks, activated_stracks)
  247. self.tracked_stracks = self.joint_stracks(self.tracked_stracks, refind_stracks)
  248. self.lost_stracks = self.sub_stracks(self.lost_stracks, self.tracked_stracks)
  249. self.lost_stracks.extend(lost_stracks)
  250. self.lost_stracks = self.sub_stracks(self.lost_stracks, self.removed_stracks)
  251. self.tracked_stracks, self.lost_stracks = self.remove_duplicate_stracks(self.tracked_stracks, self.lost_stracks)
  252. self.removed_stracks.extend(removed_stracks)
  253. if len(self.removed_stracks) > 1000:
  254. self.removed_stracks = self.removed_stracks[-999:] # clip remove stracks to 1000 maximum
  255. return np.asarray(
  256. [x.tlbr.tolist() + [x.track_id, x.score, x.cls, x.idx] for x in self.tracked_stracks if x.is_activated],
  257. dtype=np.float32)
  258. def get_kalmanfilter(self):
  259. """Returns a Kalman filter object for tracking bounding boxes."""
  260. return KalmanFilterXYAH()
  261. def init_track(self, dets, scores, cls, img=None):
  262. """Initialize object tracking with detections and scores using STrack algorithm."""
  263. return [STrack(xyxy, s, c) for (xyxy, s, c) in zip(dets, scores, cls)] if len(dets) else [] # detections
  264. def get_dists(self, tracks, detections):
  265. """Calculates the distance between tracks and detections using IOU and fuses scores."""
  266. dists = matching.iou_distance(tracks, detections)
  267. # TODO: mot20
  268. # if not self.args.mot20:
  269. dists = matching.fuse_score(dists, detections)
  270. return dists
  271. def multi_predict(self, tracks):
  272. """Returns the predicted tracks using the YOLOv8 network."""
  273. STrack.multi_predict(tracks)
  274. def reset_id(self):
  275. """Resets the ID counter of STrack."""
  276. STrack.reset_id()
  277. @staticmethod
  278. def joint_stracks(tlista, tlistb):
  279. """Combine two lists of stracks into a single one."""
  280. exists = {}
  281. res = []
  282. for t in tlista:
  283. exists[t.track_id] = 1
  284. res.append(t)
  285. for t in tlistb:
  286. tid = t.track_id
  287. if not exists.get(tid, 0):
  288. exists[tid] = 1
  289. res.append(t)
  290. return res
  291. @staticmethod
  292. def sub_stracks(tlista, tlistb):
  293. """DEPRECATED CODE in https://github.com/ultralytics/ultralytics/pull/1890/
  294. stracks = {t.track_id: t for t in tlista}
  295. for t in tlistb:
  296. tid = t.track_id
  297. if stracks.get(tid, 0):
  298. del stracks[tid]
  299. return list(stracks.values())
  300. """
  301. track_ids_b = {t.track_id for t in tlistb}
  302. return [t for t in tlista if t.track_id not in track_ids_b]
  303. @staticmethod
  304. def remove_duplicate_stracks(stracksa, stracksb):
  305. """Remove duplicate stracks with non-maximum IOU distance."""
  306. pdist = matching.iou_distance(stracksa, stracksb)
  307. pairs = np.where(pdist < 0.15)
  308. dupa, dupb = [], []
  309. for p, q in zip(*pairs):
  310. timep = stracksa[p].frame_id - stracksa[p].start_frame
  311. timeq = stracksb[q].frame_id - stracksb[q].start_frame
  312. if timep > timeq:
  313. dupb.append(q)
  314. else:
  315. dupa.append(p)
  316. resa = [t for i, t in enumerate(stracksa) if i not in dupa]
  317. resb = [t for i, t in enumerate(stracksb) if i not in dupb]
  318. return resa, resb