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.
67 lines
2.3 KiB
67 lines
2.3 KiB
2 years ago
|
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
||
2 years ago
|
|
||
2 years ago
|
from functools import partial
|
||
|
|
||
2 years ago
|
import torch
|
||
|
|
||
1 year ago
|
from ultralytics.utils import IterableSimpleNamespace, yaml_load
|
||
|
from ultralytics.utils.checks import check_yaml
|
||
2 years ago
|
|
||
1 year ago
|
from .bot_sort import BOTSORT
|
||
|
from .byte_tracker import BYTETracker
|
||
2 years ago
|
|
||
2 years ago
|
TRACKER_MAP = {'bytetrack': BYTETracker, 'botsort': BOTSORT}
|
||
2 years ago
|
|
||
|
|
||
2 years ago
|
def on_predict_start(predictor, persist=False):
|
||
|
"""
|
||
|
Initialize trackers for object tracking during prediction.
|
||
|
|
||
|
Args:
|
||
|
predictor (object): The predictor object to initialize trackers for.
|
||
|
persist (bool, optional): Whether to persist the trackers if they already exist. Defaults to False.
|
||
|
|
||
|
Raises:
|
||
|
AssertionError: If the tracker_type is not 'bytetrack' or 'botsort'.
|
||
|
"""
|
||
|
if hasattr(predictor, 'trackers') and persist:
|
||
|
return
|
||
2 years ago
|
tracker = check_yaml(predictor.args.tracker)
|
||
|
cfg = IterableSimpleNamespace(**yaml_load(tracker))
|
||
2 years ago
|
assert cfg.tracker_type in ['bytetrack', 'botsort'], \
|
||
2 years ago
|
f"Only support 'bytetrack' and 'botsort' for now, but got '{cfg.tracker_type}'"
|
||
2 years ago
|
trackers = []
|
||
|
for _ in range(predictor.dataset.bs):
|
||
|
tracker = TRACKER_MAP[cfg.tracker_type](args=cfg, frame_rate=30)
|
||
|
trackers.append(tracker)
|
||
|
predictor.trackers = trackers
|
||
|
|
||
|
|
||
|
def on_predict_postprocess_end(predictor):
|
||
2 years ago
|
"""Postprocess detected boxes and update with object tracking."""
|
||
2 years ago
|
bs = predictor.dataset.bs
|
||
2 years ago
|
im0s = predictor.batch[1]
|
||
2 years ago
|
for i in range(bs):
|
||
|
det = predictor.results[i].boxes.cpu().numpy()
|
||
|
if len(det) == 0:
|
||
|
continue
|
||
|
tracks = predictor.trackers[i].update(det, im0s[i])
|
||
|
if len(tracks) == 0:
|
||
|
continue
|
||
2 years ago
|
idx = tracks[:, -1].astype(int)
|
||
2 years ago
|
predictor.results[i] = predictor.results[i][idx]
|
||
2 years ago
|
predictor.results[i].update(boxes=torch.as_tensor(tracks[:, :-1]))
|
||
|
|
||
|
|
||
2 years ago
|
def register_tracker(model, persist):
|
||
|
"""
|
||
|
Register tracking callbacks to the model for object tracking during prediction.
|
||
|
|
||
|
Args:
|
||
|
model (object): The model object to register tracking callbacks for.
|
||
|
persist (bool): Whether to persist the trackers if they already exist.
|
||
|
|
||
|
"""
|
||
|
model.add_callback('on_predict_start', partial(on_predict_start, persist=persist))
|
||
2 years ago
|
model.add_callback('on_predict_postprocess_end', on_predict_postprocess_end)
|