Roboflow Supervision:Python 计算机视觉标注工具包

Roboflow 出品的 Supervision 是一个全面的计算机视觉工具包,简化了 CV 标注、数据处理和模型评估。通过 pip install supervision 即可为你的项目获取可复用的计算机视觉工具。

  • 更新于 2026-06-10

📦 资源信息

📋 授权协议MIT

简介 #

计算机视觉已经成为机器学习最具影响力的应用之一,为从自动驾驶汽车、质量检测系统到医学影像和零售分析在内的一切提供动力。但要构建生产级的 CV 系统,需要的不仅仅是训练模型——还需要强大的数据标注、评估、可视化和调试工具。

Roboflow 出品的 Supervision 正是对这一需求的回应。它拥有 43,972 个 GitHub star,已成为需要可复用、设计精良的 Python 工具的计算机视觉从业者的首选工具包。他们的标语说明了一切:“我们为你编写可复用的计算机视觉工具。”

披露: 本文可能包含附属链接。如果你通过这些链接注册,我可能会赚取少量佣金,而无需你支付额外费用。披露政策

DigitalOcean - 为你的 CV 部署提供可靠的云基础设施。HTStack - 高性能服务器托管。WebShare - 面向 AI 数据管道的高级代理服务。

2026-06-11-supervision 架构图
架构概览(来源:dibi8.com)

Supervision 是什么? #

Supervision 是一个 Python 库,为计算机视觉任务提供了一整套全面的工具。它覆盖了整个 CV 流程——从标注训练数据、评估模型输出,到可视化检测结果和处理视频流。

这个库的构建围绕一个简单的理念:让最常见的 CV 操作变得极其简单,同时为自定义工作流保留空间。无论你是在为目标检测标注图像、评估分割模型的输出,还是在视频中可视化跟踪结果,Supervision 都能满足你的需求。

特色图片:

Supervision 库概览

核心功能 #

Supervision 在整个计算机视觉生命周期中提供工具:

数据标注 #

Supervision 提供了用于创建、操作和转换标注格式的实用工具。它支持 COCO、YOLO、Pascal VOC 以及自定义格式,让你可以轻松使用不同的机器学习框架和流程。

# Import supervision
from supervision import *

# Load existing annotations
annotations = load_annotations("annotations/coco_format.json")

# Convert between annotation formats
coco_to_yolo(
    input_path="annotations/coco_format.json",
    output_path="annotations/yolo_format.txt",
    class_map={"person": 0, "car": 1, "dog": 2}
)

# Inspect annotation statistics
stats = get_annotation_stats(annotations)
print(f"Total objects: {stats.total_objects}")
print(f"Classes: {stats.classes}")
print(f"Images: {stats.total_images}")

检测结果处理 #

Supervision 为处理检测模型的输出提供了强大的工具,包括置信度过滤、非极大值抑制以及结果可视化。

import supervision as sv
import cv2

# Load a detection model (works with YOLO, Detectron, etc.)
detections = sv.Detections.from_yolo_output(
    prediction,  # model output tensor
    original_image_size,  # image dimensions
    confidence_threshold=0.5,
    class_id=0  # filter by class
)

# Apply non-maximum suppression
detections = sv.NMS(detections, iou_threshold=0.45)

# Filter by confidence
detections = detections[detections.confidence > 0.6]

可视化与标注绘制 #

Supervision 的优势之一在于它的可视化工具包。在图像和视频帧上绘制边界框、分割掩膜、关键点和跟踪 ID 都非常简单:

# Create annotation context for drawing
annotation_context = sv.BoxAnnotator(
    thickness=2,
    color_lookup=sv.ColorLookup.INDEX
)

# Load image
image = cv2.imread("scene.jpg")

# Draw bounding boxes
annotated_image = annotation_context.annotate(
    scene=image,
    detections=detections
)

# Draw segmentation masks
mask_annotator = sv.MaskAnnotator(
    opacity=0.5,
    color_lookup=sv.ColorLookup.INDEX
)
annotated_image = mask_annotator.annotate(
    scene=annotated_image,
    detections=detections
)

# Draw class labels with confidence
label_annotator = sv.LabelAnnotator(
    text_scale=0.5,
    text_thickness=1,
    color_lookup=sv.ColorLookup.INDEX
)
annotated_image = label_annotator.annotate(
    scene=annotated_image,
    detections=detections
)

# Save result
cv2.imwrite("annotated_scene.jpg", annotated_image)

跟踪支持 #

Supervision 对目标跟踪提供一流的支持,内置了对主流跟踪算法的集成:

# Initialize a tracker
tracker = sv.Tracker(
    tracker_type="ocsort",  # or "bytetrack"
    max_age=30,
    min_hits=3,
    iou_threshold=0.3
)

# Track objects across video frames
video_path = "traffic_camera.mp4"
for frame_number, frame in enumerate(
    sv.VideoInfo.from_video_path(video_path).iter_frames()
):
    detections = detect_objects(frame)  # your detection model
    detections = tracker.update_with_detections(detections)
    
    # Annotated frame with tracking IDs
    annotated_frame = draw_tracking_ids(frame, detections)

指标计算 #

Supervision 提供了用于计算常见 CV 评估指标的工具:

# Compute confusion matrix
confusion_matrix = sv.ConfusionMatrix(
    num_classes=10,
    task="multiclass"
)
confusion_matrix.compute(
    predictions=predicted_labels,
    targets=ground_truth_labels
)

# Display the confusion matrix
confusion_matrix.plot(title="Model Performance")

# Get precision, recall, and F1 per class
for class_name, metrics in confusion_matrix.class_metrics().items():
    print(f"{class_name}: precision={metrics.precision:.3f}, recall={metrics.recall:.3f}, f1={metrics.f1:.3f}")

工作原理 #

Supervision 通过一个简洁、一致的 API 运行,遵循几种核心设计模式:

检测结果作为数据结构 #

Supervision 的核心是 Detections 类,它为所有类型的目标检测输出——边界框、分割掩膜、关键点和方向角——提供了统一的表示形式。

from supervision import Detections

# Create detections from scratch
detections = Detections(
    xyxy=np.array([  # bounding boxes [x1, y1, x2, y2]
        [100, 50, 300, 250],
        [400, 100, 600, 300]
    ]),
    confidence=np.array([0.95, 0.87]),
    class_id=np.array([0, 2]),
    mask=np.array([mask_1, mask_2]),  # optional segmentation masks
    keypoints=np.array([keypoints_1, keypoints_2])  # optional keypoints
)

# Filter detections
person_detections = detections[detections.class_id == 0]
high_confidence = detections[detections.confidence > 0.8]

# Compute IoU between two detection sets
ious = sv.match_iou(detections_a, detections_b, iou_threshold=0.5)

流水线组合 #

Supervision 鼓励将操作组合成流水线。每一步都接收一个 Detections 对象,并产出一个新的对象:

# Build a detection pipeline
pipeline = [
    {"operation": "filter_confidence", "threshold": 0.5},
    {"operation": "non_max_suppression", "iou_threshold": 0.45},
    {"operation": "filter_class", "class_ids": [0, 1, 2]},
    {"operation": "compute_metrics", "metric": "ap50"}
]

# Execute the pipeline
results = apply_pipeline(original_detections, pipeline)

安装 #

安装 Supervision 非常简单:

# Install via pip
pip install supervision

# Verify installation
python -c "import supervision as sv; print(sv.__version__)"

# Install with all optional dependencies for maximum compatibility
pip install supervision[all]

搭配 PyTorch 安装 #

对于深度学习工作流,可以搭配 PyTorch 一起安装:

# Install with PyTorch (CPU)
pip install supervision torch torchvision

# Install with PyTorch (CUDA 12.x)
pip install supervision torch torchvision --index-url https://download.pytorch.org/whl/cu121

Colab 演示 #

Roboflow 提供了一个交互式 Colab notebook,用于探索 Supervision 的功能:

# Open the interactive Colab demo
# https://colab.research.google.com/github/roboflow/supervision/blob/main/demo.ipynb

# Or run locally:
# Clone the repository to access the demo notebook
git clone https://github.com/roboflow/supervision.git
cd supervision
jupyter notebook demo.ipynb

集成模式 #

YOLO 集成 #

Supervision 与 YOLO 模型有一流的集成:

# Integration with YOLOv8 (Ultralytics)
from ultralytics import YOLO
import supervision as sv

# Load YOLOv8 model
model = YOLO("yolov8n.pt")

# Run inference
results = model.predict("image.jpg", conf=0.25)

# Convert YOLO results to Supervision detections
detections = sv.Detections.from_ultralytics(results[0])

# Visualize
annotator = sv.BoxAnnotator()
annotated_frame = annotator.annotate(
    scene=results[0].plot(),
    detections=detections
)

MediaPipe 集成 #

用于姿态估计和关键点检测:

import supervision as sv
from mediapipe import solutions

# Load MediaPipe pose model
pose = solutions.pose.Pose(static_image_mode=True)

# Run pose detection
results = pose.process(image)

# Convert to Supervision keypoint format
if results.pose_landmarks:
    keypoints = sv.KeyPoints.from_mediapipe(results.pose_landmarks)

ONNX Runtime 集成 #

用于优化推理:

import supervision as sv
from onnxruntime import InferenceSession

# Load ONNX model
session = InferenceSession("model.onnx")

# Run inference and convert to Supervision format
outputs = session.run(None, {session.get_inputs()[0].name: input_tensor})
detections = sv.Detections.from_onnx(outputs)

Supervision 流水线架构

基准测试与性能 #

评估速度 #

Supervision 的评估函数针对速度做了优化:

| Operation | Dataset Size | Time | Performance | |

💬 留言讨论