YOLOv12 目标跟踪实战:BoT-SORT 与 ByteTrack 多目标跟踪器配置与源码解析

原创2026-10-14 17:20:281,725 阅读
文章标签:计算机视觉深度学习人工智能模型推理服务

YOLOv12 目标跟踪实战:BoT-SORT 与 ByteTrack 多目标跟踪器配置与源码解析

本文基于仓库中的 多目标跟踪文档,系统讲解在 Ultralytics YOLO(本项目即 YOLOv12 开源实现)中启用多目标跟踪的完整方法:如何调用 model.track() 与 yolo track 命令、如何通过 YAML 配置文件在 BoT-SORT 与 ByteTrack 之间切换、track_high_thresh/track_buffer/gmc_method 等核心参数的含义与底层实现,以及基于 persist=True 的逐帧跟踪、轨迹可视化和多路视频多线程跟踪的实战脚本。读完本文,你可以独立完成跟踪任务的部署调参,并能读懂 ultralytics/trackers 目录下的核心源码。

什么是视频多目标跟踪

在视频分析场景中,目标跟踪(Object Tracking)不仅要在每一帧中识别出对象的位置和类别,还要为每个被检测到的对象在整个视频过程中维持一个唯一 ID。典型应用包括安防监控、体育赛事实时分析等。

Ultralytics 跟踪器的输出与标准目标检测保持一致,额外增加了对象 ID 这一增量信息,因此可以很自然地用于视频流跟踪及后续分析。选择 Ultralytics YOLO 做跟踪的核心理由:

  • 高效(Efficiency):可在不牺牲精度的前提下实时处理视频流;
  • 灵活(Flexibility):支持多种跟踪算法与配置;
  • 易用(Ease of Use):提供简洁的 Python API 和 CLI 选项,便于快速集成部署;
  • 可定制(Customizability):可轻松搭配自定义训练的 YOLO 模型,集成到垂直领域应用中。

功能总览:

  • 实时跟踪:在高帧率视频中无缝跟踪对象;
  • 多跟踪器支持:可从多种成熟跟踪算法中选择;
  • 可定制配置:通过调整各项参数适配具体需求。

可用跟踪器与默认配置

Ultralytics YOLO 支持以下两种跟踪算法,通过传入对应的 YAML 配置文件启用(tracker=tracker_type.yaml):

跟踪器 配置文件 特点
BoT-SORT botsort.yaml 在 ByteTrack 基础上增加 GMC 全局运动补偿,是默认跟踪器
ByteTrack bytetrack.yaml 两级关联策略,充分利用低分检测框,推理更快

从源码看,track.py 中维护了一张类型到类的映射表:

TRACKER_MAP = {"bytetrack": BYTETracker, "botsort": BOTSORT}

而默认值定义在 default.yaml:

tracker: botsort.yaml # (str) tracker type, choices=[botsort.yaml, bytetrack.yaml]

也就是说,不显式传 tracker 参数时,跟踪走 BoT-SORT。

跟踪器配置文件全解

两份配置文件的完整内容和默认值如下,可直接作为调参起点。

botsort.yaml:

tracker_type: botsort # tracker type, ['botsort', 'bytetrack']
track_high_thresh: 0.25 # threshold for the first association
track_low_thresh: 0.1 # threshold for the second association
new_track_thresh: 0.25 # threshold for init new track if the detection does not match any tracks
track_buffer: 30 # buffer to calculate the time when to remove tracks
match_thresh: 0.8 # threshold for matching tracks
fuse_score: True # Whether to fuse confidence scores with the iou distances before matching
# min_box_area: 10  # threshold for min box areas(for tracker evaluation, not used for now)

# BoT-SORT settings
gmc_method: sparseOptFlow # method of global motion compensation
# ReID model related thresh (not supported yet)
proximity_thresh: 0.5
appearance_thresh: 0.25
with_reid: False

bytetrack.yaml 与上表相同,但没有 BoT-SORT 专属的 gmc_method/proximity_thresh/appearance_thresh/with_reid 四项。

各参数的源码级含义(均可在 byte_tracker.py 中找到对应逻辑):

  • tracker_type:跟踪器类型,只能取 botsort 或 bytetrack。track.py 中有强制校验,取其他值会抛出 AssertionError:

    if cfg.tracker_type not in {"bytetrack", "botsort"}:
        raise AssertionError(f"Only 'bytetrack' and 'botsort' are supported for now, but got '{cfg.tracker_type}'")
    
  • track_high_thresh(默认 0.25):第一级关联的检测框分数下限。BYTETracker.update() 中 scores >= track_high_thresh 的框参与第一级(主)关联。

  • track_low_thresh(默认 0.1):第二级关联的下限。分数落在 (track_low_thresh, track_high_thresh) 区间的“低分框”不参与第一级关联,而是专门用于和第二级关联去补救那些在第一级中未匹配上的已激活轨迹,这正是 ByteTrack 相比传统跟踪器更稳健的关键。

  • new_track_thresh(默认 0.25):新轨迹初始化的置信度阈值,未匹配检测框的分数低于该值则不会建立新轨迹。

  • track_buffer(默认 30):轨迹丢失后保留的缓冲帧数。BYTETracker.init() 中会换算为 max_time_lost = int(frame_rate / 30.0 * args.track_buffer),超过该帧数仍未匹配的轨迹被标记为 removed。帧率非 30 的视频中该换算尤为重要。

  • match_thresh(默认 0.8):第一级关联中 linear_assignment 的代价上限,IoU 距离超过该值视为不可匹配。

  • fuse_score(默认 True):是否在匹配前将检测分数融合进 IoU 代价矩阵。matching.py 的 fuse_score() 会按“分数越高、代价越小”的方式调整 cost matrix,使高分框更优先被匹配。

  • gmc_method(BoT-SORT 专属,默认 sparseOptFlow):全局运动补偿(GMC)算法。相机运动会使所有检测框整体平移,GMC 估计帧间单应矩阵并通过 STrack.multi_gmc() 同步校正所有轨迹的卡尔曼滤波状态,显著减少相机移动造成的 ID 切换。可选值在 gmc.py 中校验,支持 orb、sift、ecc、sparseOptFlow、none 五种:

    if self.method == "orb":
        self.detector = cv2.FastFeatureDetector_create(20)
        self.extractor = cv2.ORB_create()
    elif self.method == "sift":
        ...
    elif self.method == "ecc":
        self.warp_mode = cv2.MOTION_EUCLIDEAN
    elif self.method == "sparseOptFlow":
        self.feature_params = dict(maxCorners=1000, qualityLevel=0.01, minDistance=1, blockSize=3, ...)
    elif self.method in {"none", "None", None}:
        self.method = None
    

    各方法的取舍:orb/sift 基于特征点匹配,ecc 基于增强相关系数求欧氏单应,sparseOptFlow 基于稀疏光流,none 完全关闭 GMC(此时 BoT-SORT 退化为接近 ByteTrack 的行为)。

  • with_reid / proximity_thresh / appearance_thresh(BoT-SORT 专属):ReID 外观特征相关参数。配置文件注释与 bot_sort.py 中的实现都明确 ReID 尚未支持(with_reid: True 时 encoder 仍为 None,get_dists() 中不会计算 embedding 距离),当前版本中这两项阈值仅在未来启用 ReID 时生效。

启动跟踪:Python API 与 CLI

跟踪可以运行在 Detect、Segment、Pose 三类已训练模型上(如 yolo11n.pt、yolo11n-seg.pt、yolo11n-pose.pt),输入可以是本地视频文件、图片或网络流地址。

Python

from ultralytics import YOLO

# Load an official or custom model
model = YOLO("yolo11n.pt")  # Load an official Detect model
model = YOLO("yolo11n-seg.pt")  # Load an official Segment model
model = YOLO("yolo11n-pose.pt")  # Load an official Pose model
model = YOLO("path/to/best.pt")  # Load a custom trained model

# Perform tracking with the model
results = model.track(source="path/to/video.mp4", show=True)  # Tracking with default tracker
results = model.track(
    source="path/to/video.mp4", show=True, tracker="bytetrack.yaml"
)  # Tracking with ByteTrack tracker

CLI

# Perform tracking with various models using the command line interface
yolo track model=yolo11n.pt source="path/to/video.mp4"  # Official Detect model
yolo track model=yolo11n-seg.pt source="path/to/video.mp4"  # Official Segment model
yolo track model=yolo11n-pose.pt source="path/to/video.mp4"  # Official Pose model
yolo track model=path/to/best.pt source="path/to/video.mp4"  # Custom trained model

# Track using ByteTrack tracker
yolo track model=path/to/best.pt tracker="bytetrack.yaml"

如上所示,跟踪功能对视频或流式输入上的所有 Detect、Segment 与 Pose 模型均可用。

跟踪启动的底层调用链

从源码看,model.track() 并不是一个独立的推理流程,而是 model.py 中对 predict 的包装:

def track(self, source=None, stream: bool = False, persist: bool = False, **kwargs):
    if not hasattr(self.predictor, "trackers"):
        from ultralytics.trackers import register_tracker
        register_tracker(self, persist)
    kwargs["conf"] = kwargs.get("conf") or 0.1  # ByteTrack-based method needs low confidence predictions as input
    kwargs["batch"] = kwargs.get("batch") or 1  # batch-size 1 for tracking in videos
    kwargs["mode"] = "track"
    return self.predict(source=source, stream=stream, **kwargs)

这里有三个值得注意的实现细节:

  1. 默认 conf=0.1:ByteTrack 系算法需要保留更多低分检测框用于第二级关联,因此不显式指定时置信度阈值会被降为 0.1(与配置文件 track_low_thresh: 0.1 呼应)。如果你显式传入 conf=0.3,则以其为准。
  2. batch=1:视频跟踪强制批大小为 1。
  3. 回调注册:register_tracker(见 track.py)向模型挂载两个回调:
    • on_predict_start:通过 check_yaml() 定位并解析 tracker YAML,为数据集的每个 batch 创建一个跟踪器实例(流模式下每个视频源各一个),并校验 tracker_type;
    • on_predict_postprocess_end:把每帧检测框(xywh 或 OBB 的 xywha)送入 tracker.update(det, im0s[i]),拿到带 ID 的 tracks 后,将轨迹坐标和 ID 回写进 Results 对象——这就是你在 results[0].boxes.id 中读到跟踪 ID 的来源。

on_predict_postprocess_end 中还有一段轨迹状态管理逻辑(见 track.py):当视频路径发生变化且 persist=False 时,会调用 tracker.reset() 清空所有轨迹并重置 ID 计数器,保证不同视频之间 ID 不串号;persist=True 则跳过重置,让轨迹状态跨调用延续。

跟踪参数配置

跟踪配置与 Predict 模式共享 conf、iou、show 等参数。

Python

from ultralytics import YOLO

# Configure the tracking parameters and run the tracker
model = YOLO("yolo11n.pt")
results = model.track(source="path/to/video.mp4", conf=0.3, iou=0.5, show=True)

CLI

# Configure tracking parameters and run the tracker using the command line interface
yolo track model=yolo11n.pt source="path/to/video.mp4" conf=0.3 iou=0.5 show

自定义跟踪器配置文件

Ultralytics 允许使用修改后的跟踪器配置。做法很简单:从 ultralytics/cfg/trackers 复制一份配置文件(例如保存为 custom_tracker.yaml),按需求修改除 tracker_type 外的任意参数,然后传入 tracker 参数即可。

Python

from ultralytics import YOLO

# Load the model and run the tracker with a custom configuration file
model = YOLO("yolo11n.pt")
results = model.track(source="path/to/video.mp4", tracker="custom_tracker.yaml")

CLI

# Load the model and run the tracker with a custom configuration file using the command line interface
yolo track model=yolo11n.pt source="path/to/video.mp4" tracker='custom_tracker.yaml'

完整的跟踪参数清单可参考 ultralytics/cfg/trackers 下的两个 YAML 文件。

tracker 路径在 track.py 中通过 check_yaml() 解析:仓库内置路径会自动映射到 cfg/trackers/ 目录,本地绝对/相对路径则直接加载,因此 tracker="custom_tracker.yaml" 与 tracker="botsort.yaml" 的写法完全一致。

实战 Python 示例

以下三个示例脚本继承自跟踪文档,均假设已安装 opencv-python 与 ultralytics。

1. 逐帧持续跟踪(Persisting Tracks Loop)

persist=True 参数告知跟踪器:当前图像是序列中的下一帧,期望在当前帧中找到前一帧轨迹的延续。这适合你自行用 OpenCV 读帧、逐帧调用跟踪器的场景。

import cv2

from ultralytics import YOLO

# Load the YOLO11 model
model = YOLO("yolo11n.pt")

# Open the video file
video_path = "path/to/video.mp4"
cap = cv2.VideoCapture(video_path)

# Loop through the video frames
while cap.isOpened():
    # Read a frame from the video
    success, frame = cap.read()

    if success:
        # Run YOLO11 tracking on the frame, persisting tracks between frames
        results = model.track(frame, persist=True)

        # Visualize the results on the frame
        annotated_frame = results[0].plot()

        # Display the annotated frame
        cv2.imshow("YOLO11 Tracking", annotated_frame)

        # Break the loop if 'q' is pressed
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        # Break the loop if the end of the video is reached
        break

# Release the video capture object and close the display window
cap.release()
cv2.destroyAllWindows()

注意 model(frame) 与 model.track(frame) 的区别:后者才启用跟踪而不是单纯检测。该脚本对视频的每一帧运行跟踪器、可视化结果并在窗口中显示,按 q 退出循环。

2. 绘制轨迹路径(Plotting Tracks Over Time)

在连续帧上可视化对象轨迹可以直观反映检测对象的运动模式与行为。思路是:保留每个检测框的中心点历史,用折线把它们连起来,即为该对象的运动路径。

from collections import defaultdict

import cv2
import numpy as np

from ultralytics import YOLO

# Load the YOLO11 model
model = YOLO("yolo11n.pt")

# Open the video file
video_path = "path/to/video.mp4"
cap = cv2.VideoCapture(video_path)

# Store the track history
track_history = defaultdict(lambda: [])

# Loop through the video frames
while cap.isOpened():
    # Read a frame from the video
    success, frame = cap.read()

    if success:
        # Run YOLO11 tracking on the frame, persisting tracks between frames
        results = model.track(frame, persist=True)

        # Get the boxes and track IDs
        boxes = results[0].boxes.xywh.cpu()
        track_ids = results[0].boxes.id.int().cpu().tolist()

        # Visualize the results on the frame
        annotated_frame = results[0].plot()

        # Plot the tracks
        for box, track_id in zip(boxes, track_ids):
            x, y, w, h = box
            track = track_history[track_id]
            track.append((float(x), float(y)))  # x, y center point
            if len(track) > 30:  # retain 90 tracks for 90 frames
                track.pop(0)

            # Draw the tracking lines
            points = np.hstack(track).astype(np.int32).reshape((-1, 1, 2))
            cv2.polylines(
                annotated_frame,
                [points],
                isClosed=False,
                color=(230, 230, 230),
                thickness=10,
            )

        # Display the annotated frame
        cv2.imshow("YOLO11 Tracking", annotated_frame)

        # Break the loop if 'q' is pressed
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        # Break the loop if the end of the video is reached
        break

# Release the video capture object and close the display window
cap.release()
cv2.destroyAllWindows()

3. 多线程跟踪(Multithreaded Tracking)

多线程跟踪可以在多个视频流上同时运行目标跟踪,特别适合多路监控摄像头等并发输入场景。示例使用 Python 的 threading 模块:每个线程负责一个视频文件上的跟踪,通过 run_tracker_in_thread 函数封装读帧—跟踪—显示的完整循环;daemon=True 表示线程随主程序结束而关闭;start() 启动线程,join() 让主线程等待两个跟踪线程全部完成。

import threading

import cv2

from ultralytics import YOLO


def run_tracker_in_thread(filename, model):
    """Starts multi-thread tracking on video from `filename` using `model` and displays results frame by frame."""
    video = cv2.VideoCapture(filename)
    frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
    for _ in range(frames):
        ret, frame = video.read()
        if ret:
            results = model.track(source=frame, persist=True)
            res_plotted = results[0].plot()
            cv2.imshow("p", res_plotted)
            if cv2.waitKey(1) == ord("q"):
                break


# Load the models
model1 = YOLO("yolo11n.pt")
model2 = YOLO("yolo11n-seg.pt")

# Define the video files for the trackers
video_file1 = "path/to/video1.mp4"
video_file2 = "path/to/video2.mp4"

# Create the tracker threads
tracker_thread1 = threading.Thread(target=run_tracker_in_thread, args=(video_file1, model1), daemon=True)
tracker_thread2 = threading.Thread(target=run_tracker_in_thread, args=(video_file2, model2), daemon=True)

# Start the tracker threads
tracker_thread1.start()
tracker_thread2.start()

# Wait for the tracker threads to finish
tracker_thread1.join()
tracker_thread2.join()

# Clean up and close windows
cv2.destroyAllWindows()

该示例可轻松扩展到更多视频文件和模型:只需按同样方式创建更多线程即可。

跟踪器核心原理速览

结合源码,可以概括两个跟踪器的共同骨架(均以检测器输出为输入,核心循环在 BYTETracker.update() 中):

  1. 分数分组:按 track_high_thresh / track_low_thresh 把检测框分为高分组(第一级关联)和中间低分组(第二级关联);
  2. 状态预测:对所有已激活轨迹 + 丢失轨迹调用卡尔曼滤波批量预测当前位置。ByteTrack 使用 KalmanFilterXYAH(状态为 x, y, 宽高比, h),BoT-SORT 使用 KalmanFilterXYWH(状态为 x, y, w, h,见 bot_sort.py 的 get_kalmanfilter() 覆写);
  3. GMC 校正(仅 BoT-SORT):当传入当前帧图像时,gmc.apply(img, dets) 估计相机全局运动的单应矩阵,STrack.multi_gmc() 同步变换所有轨迹的滤波状态(见 byte_tracker.py);
  4. 两级关联:第一级用 iou_distance + 可选 fuse_score 计算代价矩阵,linear_assignment 以 match_thresh 求解最优匹配;第二级用剩余轨迹与低分框以固定阈值 0.5 再做一次 IoU 匹配;
  5. 未确认轨迹处理与新建轨迹:仅出现一帧的未激活轨迹阈值 0.7 再匹配一次,仍未匹配则删除;剩余检测框中分数不低于 new_track_thresh 的激活为新轨迹;
  6. 状态清理:丢失超过 max_time_lost 帧的轨迹标记移除,removed_stracks 上限裁剪为 1000 条;remove_duplicate_stracks 基于 IoU<0.15 去除 tracked/lost 之间的重复轨迹。

单条轨迹本身由 STrack 封装,维护 Tracked / Lost / Removed 状态、卡尔曼滤波 mean/covariance、类别 cls、分数 score 等信息;BoT-SORT 的 BOTrack 在其基础上预留了 ReID 特征平滑(alpha=0.9 的指数移动平均)与特征历史队列,待 ReID 编码器支持后启用。

测试用例如何验证跟踪能力

仓库的 test_python.py 中的 test_track_stream 对跟踪链路做了端到端验证:

def test_track_stream():
    video_url = "https://github.com/ultralytics/assets/releases/download/v0.0.0/decelera_portrait_min.mov"
    model = YOLO(MODEL)
    model.track(video_url, imgsz=160, tracker="bytetrack.yaml")
    model.track(video_url, imgsz=160, tracker="botsort.yaml", save_frames=True)  # test frame saving also

    # Test Global Motion Compensation (GMC) methods
    for gmc in "orb", "sift", "ecc":
        with open(ROOT / "cfg/trackers/botsort.yaml", encoding="utf-8") as f:
            data = yaml.safe_load(f)
        tracker = TMP / f"botsort-{gmc}.yaml"
        data["gmc_method"] = gmc
        with open(tracker, "w", encoding="utf-8") as f:
            yaml.safe_dump(data, f)
        model.track(video_url, imgsz=160, tracker=tracker)

该测试印证了前文的两点:tracker 参数既可传内置文件名,也可传自定义 YAML 路径;gmc_method 支持 orb/sift/ecc 等多种取值(测试中通过复制 botsort.yaml、改写 gmc_method 字段的方式逐一验证)。

贡献新的跟踪器

如果你熟悉多目标跟踪,并已用 Ultralytics YOLO 实现或适配过某种跟踪算法,可以将成果贡献到 ultralytics/cfg/trackers 目录,同时参考 track.py 中的 TRACKER_MAP 与 bot_sort.py 中 BoT-SORT 作为参考实现的写法:新增跟踪器需要实现 update()/reset() 接口并继承或兼容 STrack 状态模型,再在 cfg/trackers/ 下提供默认 YAML 配置文件。通过贡献新跟踪器,可以为整个 YOLO 生态的跟踪能力增添新的可用方案。

小结

  • 默认跟踪器为 BoT-SORT(botsort.yaml),可切换 ByteTrack(bytetrack.yaml)或任意自定义 YAML;
  • track() 底层是 predict 加两个回调:默认 conf=0.1、batch=1,轨迹 ID 通过 Results.boxes.id 暴露;
  • 调参重点是两级关联阈值(track_high/low_thresh)、匹配阈值 match_thresh、缓冲帧数 track_buffer 以及 BoT-SORT 的 gmc_method(orb/sift/ecc/sparseOptFlow/none);
  • 逐帧自控循环请使用 model.track(frame, persist=True),多路并发可用 threading + 每线程独立模型实例实现。
登录后查看全文
yolov12