supervision 完整教學

30 分鐘從安裝到能寫出「車流計數 / 區域進出告警 / 速度估計」這類 production 級 CV pipeline。


1. 專案定位

1.1 一句話總結

supervisionRoboflow 開源的 model-agnostic computer vision toolkit。把任何 detection / segmentation / classification model 的輸出 標準化 成統一資料結構(sv.Detections / sv.KeyPoints / sv.Classifications),然後用一套乾淨 API 做視覺化、ROI 計數、速度估算、tracking、dataset 轉換、metric 計算。

1.2 它解決什麼問題?

CV 應用工程師的痛點:

  1. 每換一個 model 就得重寫後處理:YOLOv8 / Ultralytics / MMDetection / Transformers 各家輸出格式都不一樣,畫框、計算 IoU、做 NMS 都要重寫
  2. OpenCV 畫圖難看且囉嗦cv2.rectangle + cv2.putText 寫一堆才畫得出像樣 annotation
  3. 「區域進出 / 跨線計數 / 軌跡平滑 / SAHI tile inference」自己 implement 慢且容易出錯
  4. Dataset 格式互轉:COCO ↔ YOLO ↔ Pascal VOC 三大格式,每換一次就要寫 parser
  5. Metrics 不統一:mAP / Precision / Recall / Confusion Matrix 各家算法細節不同,難 reproduce

supervision 的解法:

  • 統一資料結構 sv.Detections,所有 model 輸出 from_xxx() 都轉到同一個結構
  • 24+ 種 annotator,組合使用即可疊出任何視覺化
  • PolygonZone / LineZone / InferenceSlicer / DetectionsSmoother 是 first-class abstraction
  • COCO / YOLO / Pascal VOC 三大 format 互轉一行 code
  • sv.metrics 提供標準 mAP / Precision / Recall / Confusion Matrix

1.3 與類似工具的差異

工具定位supervision 差異
Ultralytics utilitiesYOLO 專用工具supervision 是 model-agnostic,YOLOv8 只是 supported sources 之一
OpenCV cv2 imgproclow-level 影像 APIsupervision 提供 high-level annotator + ROI 抽象
FiftyOnedataset 管理 + 視覺化FiftyOne 重在 dataset exploration UI;supervision 重在 production pipeline 程式 API
MMDetection / Detectron2訓練 + inference 框架supervision 不訓練 model,只負責 model 輸出後的處理
SAHItile inference 專用supervision 內建 InferenceSlicer 等同 SAHI,但同時提供其他工具
roboflow Inference (server)model serversupervision 是 client;兩者共生

1.4 適合誰

  • CV 應用工程師:要把 YOLO / DETR / SAM 等 model 接到實際應用
  • 零售 analytics / 智慧城市 / 工安 / 體育分析:要做區域進出 / 跨線計數 / 速度估計
  • 研究生 / 學者:要在論文中算 mAP / Precision / Recall / Confusion Matrix,且想要 reproducible 的 baseline
  • 要快速做 demo 的人:annotator 組合 + matplotlib / Jupyter integration 三行就能出視覺化結果
  • ⚠️ 要訓練自己 model 的人:supervision 不負責訓練;用 Ultralytics / MMDetection / HuggingFace Transformers 訓練後再接 supervision
  • ⚠️ 要做 tracking 的人:v0.28+ ByteTrack 已 deprecated,遷到 roboflow/trackers 獨立 repo

2. 安裝指南

2.1 環境前提

元件版本說明
Python>= 3.9
pip / uv / conda任一即可uv 速度最快
GPU非必要supervision 本身不跑 model;要跑 model 才需要 GPU

2.2 安裝步驟

 1# 方法 1:pip (最常用)
 2pip install supervision
 3
 4# 方法 2:uv (快)
 5uv pip install supervision
 6
 7# 方法 3:含 metrics extras (pandas)
 8pip install "supervision[metrics]"
 9
10# 方法 4:從 source 裝最新 dev 版
11pip install git+https://github.com/roboflow/supervision.git@develop

2.3 安裝後驗證

 1import supervision as sv
 2print(sv.__version__)  # 應為 0.28.0 或更新
 3
 4# 建一個假的 Detections 看 import 是否正常
 5import numpy as np
 6detections = sv.Detections(
 7    xyxy=np.array([[100, 100, 200, 200]]),
 8    confidence=np.array([0.95]),
 9    class_id=np.array([0]),
10)
11print(len(detections))  # 1

2.4 常見搭配

 1# YOLO 系列
 2pip install ultralytics            # YOLOv8 / v11
 3pip install rfdetr                 # Roboflow DETR
 4
 5# Transformers 系列 (DETR / OwlViT)
 6pip install transformers torch pillow
 7
 8# Roboflow Inference server (有 RF API key 的人)
 9pip install inference
10
11# Dataset 工具 (COCO / YOLO / VOC)
12pip install pycocotools

3. 核心架構解析

3.1 整體模組圖

 1                  ┌───────────────────────────────┐
 2                  │      Model (you choose)       │
 3                  │  YOLO / DETR / SAM / Owl /…   │
 4                  └──────────────┬────────────────┘
 5 6 7                  ┌───────────────────────────────┐
 8                  │  sv.Detections.from_xxx(...)  │ ── 統一輸入
 9                  │  sv.Detections.from_ultralytics
10                  │  sv.Detections.from_inference
11                  │  sv.Detections.from_transformers
12                  │  sv.Detections.from_lmm        │
13                  └──────────────┬────────────────┘
1415                ┌────────────────┴────────────────┐
16                ▼                                 ▼
17      ┌─────────────────┐              ┌─────────────────┐
18      │  Annotators     │              │  Tools / Logic  │
19      │  Box / Label /  │              │  PolygonZone    │
20      │  Mask / Halo /  │              │  LineZone       │
21      │  Heatmap /      │              │  InferenceSlicer│
22      │  Trace / …      │              │  Smoother       │
23      └─────────────────┘              │  CSVSink        │
24                                       └─────────────────┘
25                ▼                                 ▼
26      visualization                       business logic
27                                            (counts, etc)
282930                  ┌───────────────────────────────┐
31                  │  sv.metrics (mAP / P / R)     │
32                  └───────────────────────────────┘

3.2 核心資料結構:sv.Detections

1class Detections:
2    xyxy: np.ndarray         # (N, 4) bounding box [x1, y1, x2, y2]
3    mask: Optional[np.ndarray]      # (N, H, W) instance masks
4    confidence: Optional[np.ndarray]  # (N,) 信心
5    class_id: Optional[np.ndarray]    # (N,) 類別 id
6    tracker_id: Optional[np.ndarray]  # (N,) 追蹤 id (跑 tracker 後才有)
7    data: Dict[str, np.ndarray]       # 任意 extra 欄位 (如 keypoints, age, gender)
8    metadata: Dict[str, Any]          # frame-level metadata

為什麼這個設計重要? 它把「N 個 detection」當 column-oriented 的小 dataframe 而非 row-oriented list of dict。所有操作都 NumPy vectorized,比 Python loop 快數量級。

 1# Slicing
 2high_conf = detections[detections.confidence > 0.7]    # 過濾
 3person_only = detections[detections.class_id == 0]     # 類別過濾
 4detections.xyxy.shape  # (N, 4)
 5len(detections)        # N
 6
 7# Iteration(會慢,盡量避免)
 8for xyxy, mask, conf, cid, tid, data in detections:
 9    pass
10
11# 合併
12merged = sv.Detections.merge([dets_frame1, dets_frame2])

3.3 模組對照表

模組主要 class / function何時用
sv.annotatorsBoxAnnotator / LabelAnnotator / MaskAnnotator / HaloAnnotator / HeatMapAnnotator / TraceAnnotator / BlurAnnotator / IconAnnotator / PixelateAnnotator / OrientedBoxAnnotator / PercentageBarAnnotator 等 24 種視覺化
sv.detection.toolsPolygonZone / LineZone / InferenceSlicer / DetectionsSmoother / CSVSink / JSONSink業務邏輯
sv.datasetDetectionDataset / ClassificationDataset + from_coco / from_yolo / from_pascal_voc + as_*資料處理
sv.metricsMeanAveragePrecision / Precision / Recall / ConfusionMatrix評估
sv.trackerByteTrack (deprecated → trackers)追蹤
sv.drawColor / ColorPalette / draw_text / draw_polygon 等 primitive客製繪圖
sv.geometryPoint / Rect / Position座標處理
sv.detection.utilsbox_iou_batch / box_non_max_suppression / mask_to_polygons / polygon_to_mask / calculate_masks_centroids低階運算
sv.detection.vlmLMM / VLM adapter對接 GPT-4V / Claude / Gemini 等 VLM 輸出

3.4 Annotator 的組合哲學

每個 annotator 一致 API:annotate(scene, detections) -> scene。組合方式很自然:

 1import cv2, supervision as sv
 2
 3image = cv2.imread("frame.jpg")
 4detections = sv.Detections.from_ultralytics(yolo.predict(image)[0])
 5
 6box_annotator = sv.BoxAnnotator(thickness=2)
 7label_annotator = sv.LabelAnnotator(text_thickness=1, text_scale=0.5)
 8trace_annotator = sv.TraceAnnotator(trace_length=30)
 9
10annotated = image.copy()
11annotated = box_annotator.annotate(annotated, detections)
12annotated = label_annotator.annotate(annotated, detections, labels=[
13    f"{cls} {conf:.2f}" for cls, conf in zip(detections.class_id, detections.confidence)
14])
15annotated = trace_annotator.annotate(annotated, detections)

為什麼好用? 想加 / 拿掉 annotator 只是加 / 拿掉一行;不像 OpenCV 寫死的 cv2.rectangle + cv2.putText 改一次要重寫。

3.5 Tools 的職責

Tool功能典型場景
PolygonZone多邊形 ROI 進出計數「多少人進入這個店面區域?」
LineZone跨線進 / 出計數 (兩個方向)「車輛通過這條檢核線往哪邊去?」
InferenceSlicer圖片切 tile 後分別 inference 再合併 (= SAHI)衛星圖、4K 直播畫面找小目標
DetectionsSmoother多 frame 時域平滑抓拍框抖動緩解
CSVSink / JSONSink序列化 detections 到磁碟analytics pipeline 落地

3.6 Dataset 三大格式互轉

 1# 載入
 2ds = sv.DetectionDataset.from_coco(images_directory_path=..., annotations_path=...)
 3ds = sv.DetectionDataset.from_yolo(images_directory_path=..., annotations_directory_path=..., data_yaml_path=...)
 4ds = sv.DetectionDataset.from_pascal_voc(images_directory_path=..., annotations_directory_path=...)
 5
 6# 切分 / 合併
 7train, test = ds.split(split_ratio=0.7)
 8ds_merged = sv.DetectionDataset.merge([ds1, ds2])
 9
10# 存成另一個格式
11ds.as_yolo(images_directory_path=..., annotations_directory_path=..., data_yaml_path=...)
12ds.as_coco(images_directory_path=..., annotations_path=...)
13ds.as_pascal_voc(images_directory_path=..., annotations_directory_path=...)

3.7 Metrics 用法

 1from supervision.metrics import MeanAveragePrecision, MetricTarget
 2
 3predictions = [...]  # list of sv.Detections, one per image
 4targets = [...]      # list of sv.Detections (ground truth)
 5
 6map_metric = MeanAveragePrecision()
 7result = map_metric.update(predictions, targets).compute()
 8print(result.map50_95)  # COCO-style mAP @[0.5:0.95]
 9print(result.map50)     # mAP @ 0.5
10print(result.map75)     # mAP @ 0.75
11
12# Confusion Matrix
13from supervision.metrics import ConfusionMatrix
14cm = ConfusionMatrix(num_classes=80)
15cm.update(predictions, targets).compute().plot()  # matplotlib heatmap

4. CLI / Helper 詳細用法

Supervision 沒有 supervision CLI binary(純 library)。本節改為列「常用 helper function 速查表」。

4.1 Detections 的 from_*

Method來源 model
from_ultralytics(result)Ultralytics YOLO (v5/v8/v11)
from_inference(result)Roboflow Inference server
from_transformers(result)HuggingFace Transformers DETR / OwlViT
from_yolov5(result)舊版 YOLOv5
from_yolo_nas(result)YOLO-NAS
from_mmdetection(result)MMDetection
from_paddledet(result)PaddleDetection
from_sam(masks)Segment Anything
from_azure_analyze_image(result, class_map)Azure Cognitive Services
from_lmm(result, ...)通用 VLM (GPT-4V / Claude / Gemini)

4.2 IOU / NMS / 合併操作

 1from supervision.detection.utils import (
 2    box_iou_batch,                  # (N, 4) vs (M, 4) → (N, M) IoU 矩陣
 3    box_non_max_suppression,         # NMS, returns boolean mask
 4    box_non_max_merge,               # Non-Max Merge (合併重疊 box)
 5    mask_iou_batch, mask_non_max_suppression, mask_non_max_merge,
 6    oriented_box_iou_batch,          # OBB IoU
 7)
 8
 9# 直接在 Detections 上呼叫
10detections = detections.with_nms(threshold=0.5, class_agnostic=False)
11detections = detections.with_nmm(threshold=0.2, overlap_metric=sv.OverlapMetric.IOU)

4.3 Mask / Polygon / RLE 互轉

 1from supervision.detection.utils import (
 2    mask_to_polygons,    # (H, W) bool mask → list of (N, 2) polygons
 3    polygon_to_mask,     # (N, 2) polygon → (H, W) bool mask
 4    mask_to_xyxy,        # mask → bounding box
 5    mask_to_rle,         # mask → COCO RLE
 6    rle_to_mask,         # COCO RLE → mask
 7    polygon_to_xyxy,
 8    xyxy_to_mask,
 9    xyxy_to_polygons,
10)

4.4 Color / Drawing primitives

 1from supervision.draw.color import Color, ColorPalette
 2from supervision.draw.utils import draw_text, draw_polygon, draw_filled_rectangle
 3
 4# 色票
 5ColorPalette.LEGACY    # 舊版預設色
 6ColorPalette.ROBOFLOW  # Roboflow 品牌色
 7custom = ColorPalette.from_hex(["#FF0000", "#00FF00", "#0000FF"])
 8
 9# 取顏色
10color = custom.by_idx(0)            # 第 0 個
11color = Color.from_hex("#FF5733")   # 從 hex

4.5 Video 處理工具

 1import supervision as sv
 2
 3# 一個一個讀 frame (generator)
 4for frame in sv.get_video_frames_generator(source_path="input.mp4"):
 5    pass
 6
 7# 用 callback 處理整個 video,自動寫 output (含 trace 等)
 8def callback(frame, frame_index):
 9    detections = sv.Detections.from_ultralytics(yolo.predict(frame)[0])
10    return box_annotator.annotate(frame, detections)
11
12sv.process_video(
13    source_path="input.mp4",
14    target_path="output.mp4",
15    callback=callback,
16)
17
18# 取得 video metadata
19info = sv.VideoInfo.from_video_path("input.mp4")
20print(info.fps, info.width, info.height, info.total_frames)

5. 應用場景

5.1 Workflow A — 入店人流計數 (PolygonZone)

 1import cv2, numpy as np, supervision as sv
 2from ultralytics import YOLO
 3
 4model = YOLO("yolov8n.pt")
 5zone_polygon = np.array([[100, 100], [400, 100], [400, 400], [100, 400]])
 6zone = sv.PolygonZone(polygon=zone_polygon)
 7
 8box_annotator = sv.BoxAnnotator()
 9zone_annotator = sv.PolygonZoneAnnotator(zone=zone, color=sv.Color.GREEN, thickness=2)
10
11def callback(frame, _):
12    result = model(frame)[0]
13    detections = sv.Detections.from_ultralytics(result)
14    detections = detections[detections.class_id == 0]  # person
15    zone.trigger(detections=detections)
16    annotated = box_annotator.annotate(frame.copy(), detections)
17    annotated = zone_annotator.annotate(annotated)
18    return annotated
19
20sv.process_video("store_camera.mp4", "out.mp4", callback)
21print(f"Total people in zone (cumulative): {zone.current_count}")

5.2 Workflow B — 車輛跨線計數 (LineZone) + 方向判斷

 1line = sv.LineZone(start=sv.Point(0, 540), end=sv.Point(1920, 540))
 2line_annotator = sv.LineZoneAnnotator(thickness=4, text_thickness=2, text_scale=2)
 3
 4def callback(frame, _):
 5    result = model(frame)[0]
 6    dets = sv.Detections.from_ultralytics(result)
 7    dets = dets[np.isin(dets.class_id, [2, 3, 5, 7])]  # car/motor/bus/truck
 8    dets = byte_tracker.update_with_detections(dets)
 9    line.trigger(detections=dets)  # 自動判斷哪些 cross
10    annotated = box_annotator.annotate(frame.copy(), dets)
11    annotated = line_annotator.annotate(annotated, line_counter=line)
12    return annotated
13
14# line.in_count / line.out_count 兩個方向計數

5.3 Workflow C — 速度估計(透過 perspective transform)

examples/speed_estimation/ 完整可跑,核心想法:

  1. 攝影機畫面 4 角 + 真實世界 4 角 → 建 perspective transform
  2. tracker 提供每個物件 tracker_id
  3. 連續 frame 的中心點 → 真實世界座標 → 算位移 → 算速度(公里 / 小時)
  4. LabelAnnotator 把速度標到框上

5.4 Workflow D — 衛星 / 4K 找小目標 (SAHI 風格)

1from supervision import InferenceSlicer
2
3def callback(slice_image: np.ndarray) -> sv.Detections:
4    result = model(slice_image)[0]
5    return sv.Detections.from_ultralytics(result)
6
7slicer = InferenceSlicer(callback=callback, slice_wh=(640, 640), overlap_ratio_wh=(0.2, 0.2))
8detections = slicer(image=large_image)  # 自動 tile + inference + 合併 + NMS

5.5 Workflow E — 自家 dataset COCO ↔ YOLO 互轉

1# 把同事給的 COCO 格式 dataset 轉成 YOLO 給 Ultralytics 訓練
2ds = sv.DetectionDataset.from_coco(images_directory_path="data/coco/images",
3                                   annotations_path="data/coco/annotations.json")
4ds.as_yolo(images_directory_path="data/yolo/images",
5           annotations_directory_path="data/yolo/labels",
6           data_yaml_path="data/yolo/data.yaml")

6. 資安掃描報告

6.1 整體風險等級

🟢 低風險(可放心安裝、商業使用)

6.2 詳細掃描結果

風險面向掃描方法結果
任意 code execution (exec / eval / os.system / subprocess)grep src/ 全檔(唯一 match 是 model.eval() PyTorch 模型切 eval mode,與 Python eval() 無關)
Pickle deserializationgrep pickle\.load
Shell injectiongrep shell=True
Network requestsgrep src/0 個 production 路徑;僅 1 個 docstring 範例(from_azure_analyze_image 教如何 call Azure)
XML XXE 攻擊防護grep defusedxml vs xml.etree正確使用 defusedxml.ElementTree 解析 Pascal VOC,避開 stdlib XML library 的 XXE 風險
隱藏字元 / Unicode 攻擊grep -P
Hardcoded secretgrep API_KEY / password / token
Supply chainpyproject.toml depsnumpy / opencv / matplotlib / pillow / scipy / requests / pyyaml / tqdm / defusedxml / pydeprecate — 都是業界標準套件
Snyk advisorREADME badge持續 monitor,沒有已知 critical
CodecovREADME badge公開 coverage 追蹤

6.3 信任邊界

1[絕對信任]   supervision 純 Python library,無 hooks / 無 binary / 無外部 process
2[條件信任]   ↓
3            上游 model (YOLO / DETR / SAM 等):你自己選的,由你信任
4[條件信任]   ↓
5            COCO / YOLO / VOC dataset 檔案:解析 VOC XML 用 defusedxml 防 XXE
6[一般風險]   ↓
7            video / image 解碼依賴 OpenCV / Pillow,這兩者本身有歷史 CVE,建議套件保持最新

6.4 維護健康度

  • ⭐ 38.8k 星、3.5k forks、Roboflow 公司資源支持
  • 主要 maintainer 活躍:BordaSkalskiP
  • Dependabot 自動 PR 升級 (近期 commits 有 mistune / jupyter-server / AButler/upload-release-assets)
  • pre-commit chain 完整:ruff / codespell / mdformat / prettier / pyproject-fmt / 標準 hooks
  • AGENTS.md 文件清楚指引 AI agent 怎麼貢獻
  • 社群已開始討論 EU AI Act 合規(issue #2194)

6.5 唯一需要使用者注意的點

  • OpenCV / Pillow 是 image / video 解碼層:歷史上 CVE 多在這層 (CVE-2024-* / CVE-2025-* 等)。建議:
    1pip install --upgrade opencv-python pillow
    2pip-audit  # 定期跑
    
  • 跑外部 model checkpoint 要看來源:例如從不可信 source 下 .pt / .ckpt 檔案要小心 — Pickle 反序列化漏洞 (CVE-2025-32434 / 等) 可能造成 code execution。supervision 不負責這層;用 torch.load(weights_only=True)(PyTorch 2.6+)

7. FAQ

Q1:YOLO 結果怎麼轉成 supervision Detections? A:sv.Detections.from_ultralytics(result)(YOLOv8/v11);舊版用 from_yolov5;NAS 用 from_yolo_nas

Q2:可以畫多個 annotator 疊加嗎? A:可以,這就是 supervision 的核心設計。每個 annotator 簽名都是 annotate(scene, detections) -> scene,前一個的輸出當下一個的輸入即可。

Q3:ByteTrack 哪去了? A:v0.28+ 標 deprecated,遷到獨立 roboflow/trackers repo。短期還能用,長期建議改 from trackers import ByteTrackTracker

Q4:怎麼算 mAP @ 0.5:0.95? A:

1from supervision.metrics import MeanAveragePrecision
2result = MeanAveragePrecision().update(preds, targets).compute()
3print(result.map50_95)

Q5:可以用在 production / 商用嗎? A:可以,MIT License。實務上很多 Roboflow 客戶 + Fortune 500 都用。注意:

  • 商用要 self-audit OpenCV / Pillow 等 transitive deps
  • 若涉及歐盟使用者,注意 EU AI Act 合規(issue #2194)

Q6:supervision 跟 roboflow inference 差別? A:inference 是 model server (跑 model),supervision 是 client toolkit (處理結果)。兩者組合成完整 pipeline,但獨立可用 — 你可以只用 supervision + ultralytics 不用 inference。

Q7:怎麼加自家 model 的 from_xxx adapter? A:直接 import Detections 並用 constructor 建:

1detections = sv.Detections(
2    xyxy=my_model_boxes,
3    confidence=my_model_scores,
4    class_id=my_model_class_ids,
5)

不一定要寫 from_* method(那只是慣例)。要 PR 上游也歡迎,contributing guide 在 .github/CONTRIBUTING.md

Q8:跑大解析度直播 (4K / 8K) 會不會慢? A:annotator 用 OpenCV vectorized 操作,對單 frame (2160, 3840, 3) 還算快。瓶頸通常在 model inference 而非 supervision。要更快的 inference 可用 SAHI 風格的 InferenceSlicer + 並行。


8. 進階技巧

8.1 Detections 自訂欄位 (data dict)

sv.Detectionsdata: Dict[str, np.ndarray],可以塞任意 (N,) 或 (N, K) array。常見用法:keypoints / age / gender / 自家 ID。

1detections.data["age"] = np.array([25, 35, 18])
2detections.data["custom_id"] = np.array(["A1", "B2", "C3"])
3
4# slicing 會自動帶過去
5high_conf = detections[detections.confidence > 0.7]
6print(high_conf.data["age"])  # 自動篩選

8.2 自訂 ColorPalette 對應公司品牌色

1from supervision.draw.color import ColorPalette
2palette = ColorPalette.from_hex(["#1A73E8", "#34A853", "#FBBC05", "#EA4335"])
3box_annotator = sv.BoxAnnotator(color=palette)
4label_annotator = sv.LabelAnnotator(color=palette, text_color=sv.Color.WHITE)

8.3 用 process_video 一次跑完並寫檔

1sv.process_video(
2    source_path="in.mp4",
3    target_path="out.mp4",
4    callback=my_callback,
5    show_progress=True,
6)

注意:參數叫 show_progress 不是 progress(社群常見筆誤,issue #2244 也提到這點)。

8.4 把結果落地成 CSV / JSON

1csv_sink = sv.CSVSink(file_name="detections.csv")
2with csv_sink as sink:
3    for frame_idx, frame in enumerate(sv.get_video_frames_generator("video.mp4")):
4        dets = sv.Detections.from_ultralytics(model(frame)[0])
5        sink.append(dets, custom_data={"frame_index": frame_idx})

8.5 Smoothing tracker 抖動

1smoother = sv.DetectionsSmoother(length=5)
2for frame in frames:
3    dets = sv.Detections.from_ultralytics(model(frame)[0])
4    dets = byte_tracker.update_with_detections(dets)
5    dets = smoother.update_with_detections(dets)  # 5 frame 滑動平均

8.6 InferenceSlicer 對 4K 找小目標

1slicer = sv.InferenceSlicer(
2    callback=lambda img: sv.Detections.from_ultralytics(model(img)[0]),
3    slice_wh=(640, 640),
4    overlap_ratio_wh=(0.2, 0.2),
5    iou_threshold=0.5,    # 合併重疊 detections
6)
7detections = slicer(image=large_image)

9. 整合進其他工作流

9.1 與 Roboflow ecosystem

1roboflow Inference (server)  ─→  sv.Detections.from_inference  ─→  supervision tools
2roboflow datasets             ─→  sv.DetectionDataset.from_yolo / from_coco
3roboflow notebooks            ─→  Jupyter 教學整合
4roboflow trackers (new!)      ─→  ByteTrack / DeepSORT / SORT (從 supervision 拆出)
5autodistill                   ─→  用 foundation model 自動標註,產 dataset 給 supervision 處理
6multimodal-maestro            ─→  VLM prompting → sv.Detections.from_lmm

9.2 與 LangChain / 其他 LLM agent 框架

sv.Detections 結果轉 JSON 餵給 LLM:

1import json
2serialized = {
3    "boxes": detections.xyxy.tolist(),
4    "classes": detections.class_id.tolist(),
5    "scores": detections.confidence.tolist(),
6}
7prompt = f"Analyze this scene: {json.dumps(serialized)}. What's happening?"

9.3 與 Streamlit / Gradio Demo

HuggingFace Space 範例:Roboflow/Annotators。Gradio app 結構:

1import gradio as gr, supervision as sv
2def predict(image):
3    detections = sv.Detections.from_ultralytics(model(image)[0])
4    return box_annotator.annotate(image.copy(), detections)
5gr.Interface(predict, gr.Image(), gr.Image()).launch()

9.4 與 ai-knowledge-template 工作流

  • 想拿 supervision 當論文 / 報告的 baseline → 把本 tutorial md + gh-save md 整理進文獻
  • 想追蹤 Roboflow ecosystem 更新 → 訂閱 roboflow/notebooks / roboflow/inference / roboflow/trackers 三個 repo

10. 重點摘要 Checklist

  • supervision = model-agnostic computer vision toolkit(從 detection 結果 → 視覺化 → 業務邏輯)
  • 安裝:pip install supervision,Python >= 3.9
  • 核心抽象:sv.Detections(column-oriented NumPy struct,可 slicing / merge / NMS / NMM)
  • 24+ 種 annotator 組合使用:Box / Label / Mask / Halo / Heatmap / Trace / Blur / Pixelate / Icon / OrientedBox / PercentageBar…
  • 業務邏輯 first-class:PolygonZone / LineZone / InferenceSlicer / DetectionsSmoother
  • Dataset 三大格式互轉:COCO ↔ YOLO ↔ Pascal VOC
  • Metrics:mAP / Precision / Recall / Confusion Matrix
  • Tracker 已遷出:v0.28+ ByteTrack deprecated → roboflow/trackers
  • 🟢 資安:純 client library、無危險 pattern、Pascal VOC 用 defusedxml 防 XXE、無自有網路請求
  • 生態整合:Roboflow Inference / autodistill / maestro / notebooks 工具鏈完整
  • AI agent 友善:repo 含 AGENTS.md + CLAUDE.md 給 Copilot / Claude / Cursor 用

11. 進一步閱讀

官方

  • 主 repo:roboflow/supervision
  • 文件:https://supervision.roboflow.com(develop / latest)
  • Cheatsheet:https://roboflow.github.io/cheatsheet-supervision/
  • Demo Colab:https://colab.research.google.com/github/roboflow/supervision/blob/main/demo.ipynb
  • HuggingFace Space:https://huggingface.co/spaces/Roboflow/Annotators
  • Discord:https://discord.gg/GbfgXGJ8Bk

周邊 repo

周邊技術

  • Ultralytics YOLO:ultralytics/ultralytics
  • HuggingFace Transformers DETR:文件
  • SAHI (tile inference 原始 paper):obss/sahi
  • ByteTrack (paper):https://arxiv.org/abs/2110.06864
  • Pascal VOC XXE 防護:defusedxml docs

法規 / 合規

  • EU AI Act compliance for CV: supervision issue #2194

免責聲明:本教學由 AI Knowledge Template 自動產生,技術內容供研究與商業使用參考。實際 production 部署仍需依貴司資安規範自行 audit。如涉及歐盟使用者,請特別留意 EU AI Act Art. 9 / 12 / 14 條款。