Compare commits

..
9 Commits
Author SHA1 Message Date
87b1b86f39 releasing 0.28.0 (#2220)
* docs: add 0.28.0 changelog entries and release demo notebook
* feat: add script for converting Python scripts to Jupyter notebooks
* chore: reorganize imports in release-demo notebook and update lint config
* docs: fix broken link in changelog entry for ConfusionMatrix

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-04-30 17:11:50 +02:00
pre-commit-ci[bot] 1170a90ffc chore(pre_commit): ⬆ pre_commit autoupdate (#2235)
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.15.11 → v0.15.12](https://github.com/astral-sh/ruff-pre-commit/compare/v0.15.11...v0.15.12)
- [github.com/pre-commit/mirrors-mypy: v1.20.1 → v1.20.2](https://github.com/pre-commit/mirrors-mypy/compare/v1.20.1...v1.20.2)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-04-28 09:03:07 +02:00
dependabot[bot] 2e0e8d9132 ⬆️ Update wheel requirement from <0.47,>=0.40 to >=0.40,<0.48 (#2234)
Updates the requirements on [wheel](https://github.com/pypa/wheel) to permit the latest version.
- [Release notes](https://github.com/pypa/wheel/releases)
- [Changelog](https://github.com/pypa/wheel/blob/main/docs/news.rst)
- [Commits](https://github.com/pypa/wheel/compare/0.40.0...0.47.0)

---
updated-dependencies:
- dependency-name: wheel
  dependency-version: 0.47.0
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-27 09:28:09 +02:00
Jirka BorovecandCopilot 15730b2b5d docs: update author references and improve metadata (#2233)
- Standardize author naming by removing aliases (e.g., "SkalskiP" → "Piotr Skalski").
- Refine JSON-LD schema with added fields, `speakable` specifications, and expanded FAQs.
- Update copyright year to 2026.
- Highlight project milestones (GitHub stars and PyPI downloads) for visibility.

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-25 07:15:59 +02:00
2db1e3af34 docs: improve SEO and GEO docs publishing (#2232)
* docs: improve SEO and GEO docs publishing
* docs: refine language for model compatibility and package features
* fix: correct spelling "Underestand" → "Understand" in notebook title
* fix: derive JSON-LD SearchAction URL from config.site_url
* lint: reformat notebook JSON (indent 1→4, pretty-format-json)
* docs: refine description for `supervision.assets` video addition

---------

Co-authored-by: Codex <codex@openai.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-04-24 23:39:22 +02:00
jirka 840226afce chore: update pre-commit hooks configuration
- Add `check-json` hook and re-add `check-yaml` hook.
- Configure `check-added-large-files` with a max size of 500 KB.
- Format `ruff-check` hook arguments for consistency.
2026-04-24 18:07:59 +02:00
dc03ceac31 fix(docs): expand llms.txt, add FAQ schema, author attribution to how… (#2231)
- Expand llms.txt from 12 to 36+ URLs with FAQ, benchmarking, and API sections
- FAQPage schema: 5 → 12 Q&As in theme/main.html
- TechArticle schema: add dynamic author/date from page meta
- Add authors + date_modified frontmatter to all 8 how-to pages
- Add description meta to 7 reference pages (detection/core, trackers, datasets/core, metrics/mean_average_precision, cookbooks, assets, changelog)
- FAQ sections to all 8 how-to pages (Q&A format for AI citation)
- Author bios at bottom of each how-to page (E-E-A-T signal)
- FAQPage + TechArticle schema for how_to, reference, and cookbook pages in theme/main.html
- llms.txt Key APIs: expand from bare list to descriptive prose paragraphs
- Changelog: add date_modified frontmatter

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: OpenAI Codex <codex@openai.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-23 18:33:14 +02:00
dependabot[bot] f9ab57afde ⬆️ Bump nbconvert from 7.17.0 to 7.17.1 in the uv group across 1 directory (#2226)
Bumps the uv group with 1 update in the / directory: [nbconvert](https://github.com/jupyter/nbconvert).


Updates `nbconvert` from 7.17.0 to 7.17.1
- [Release notes](https://github.com/jupyter/nbconvert/releases)
- [Changelog](https://github.com/jupyter/nbconvert/blob/main/CHANGELOG.md)
- [Commits](https://github.com/jupyter/nbconvert/compare/v7.17.0...v7.17.1)

---
updated-dependencies:
- dependency-name: nbconvert
  dependency-version: 7.17.1
  dependency-type: direct:development
  dependency-group: uv
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-22 20:33:54 +02:00
pre-commit-ci[bot] fb19852919 chore(pre_commit): ⬆ pre_commit autoupdate (#2225)
updates:
- [github.com/JoC0de/pre-commit-prettier: v3.8.2 → v3.8.3](https://github.com/JoC0de/pre-commit-prettier/compare/v3.8.2...v3.8.3)
- [github.com/astral-sh/ruff-pre-commit: v0.15.10 → v0.15.11](https://github.com/astral-sh/ruff-pre-commit/compare/v0.15.10...v0.15.11)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-04-22 20:29:35 +02:00
32 changed files with 1820 additions and 87 deletions
+48 -5
View File
@@ -1,9 +1,15 @@
name: Docs/Build and Publish
# Deploy matrix:
# push develop -> mike deploy develop
# push release/latest -> mike deploy latest
# release published -> mike deploy <tag> only; does not move /latest/
on:
push:
branches:
- develop
- release/latest
workflow_dispatch:
release:
types: [published]
@@ -51,13 +57,20 @@ jobs:
run: |
mike deploy --push develop
- name: 🚀 Deploy Latest Docs
if: github.event_name == 'push' && github.ref == 'refs/heads/release/latest'
env:
MKDOCS_GIT_COMMITTERS_APIKEY: ${{ secrets.GITHUB_TOKEN }}
run: |
mike deploy --push latest
- name: 🚀 Deploy Release Docs
if: github.event_name == 'release' && github.event.action == 'published'
env:
MKDOCS_GIT_COMMITTERS_APIKEY: ${{ secrets.GITHUB_TOKEN }}
run: |
latest_tag=$(git tag --sort=-v:refname | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | head -1)
mike deploy --push --update-aliases $latest_tag latest
release_tag="${GITHUB_REF_NAME#v}"
mike deploy --push "$release_tag"
# IndexNow key: 0d5d9799b1cc4a39825146388c6781eb
# This key must stay in sync across three files:
@@ -70,25 +83,55 @@ jobs:
if: >
(github.event_name == 'push' && github.ref == 'refs/heads/develop') ||
github.event_name == 'workflow_dispatch' ||
(github.event_name == 'push' && github.ref == 'refs/heads/release/latest') ||
(github.event_name == 'release' && github.event.action == 'published')
run: |
cp docs/robots.txt /tmp/robots.txt
cp docs/llms.txt /tmp/llms.txt
cp docs/llms.full.txt /tmp/llms.full.txt
cp docs/llms-100k.txt /tmp/llms-100k.txt
cp docs/_headers /tmp/headers.txt
cp docs/0d5d9799b1cc4a39825146388c6781eb.txt /tmp/indexnow.txt
if [[ "$GITHUB_REF" == "refs/heads/release/latest" ]]; then
version_dir="latest"
else
version_dir=""
fi
git fetch origin gh-pages
git checkout gh-pages
cp /tmp/robots.txt robots.txt
cp /tmp/llms.txt llms.txt
cp /tmp/llms.full.txt llms.full.txt
cp /tmp/llms-100k.txt llms-100k.txt
cp /tmp/headers.txt _headers
cp /tmp/indexnow.txt 0d5d9799b1cc4a39825146388c6781eb.txt
git add robots.txt llms.txt 0d5d9799b1cc4a39825146388c6781eb.txt
git diff --cached --quiet || git commit -m "chore: update GEO root files (robots.txt, llms.txt, indexnow)"
if [[ -n "$version_dir" && -f "$version_dir/sitemap.xml" ]]; then
cp "$version_dir/sitemap.xml" sitemap.xml
gzip -9 -c sitemap.xml > sitemap.xml.gz
fi
files_to_add=(
robots.txt
llms.txt
llms.full.txt
llms-100k.txt
_headers
0d5d9799b1cc4a39825146388c6781eb.txt
)
if [[ -f "sitemap.xml" ]]; then
files_to_add+=(sitemap.xml)
fi
if [[ -f "sitemap.xml.gz" ]]; then
files_to_add+=(sitemap.xml.gz)
fi
git add "${files_to_add[@]}"
git diff --cached --quiet || git commit -m "chore: update GEO root files"
git push origin gh-pages
- name: 📡 Notify IndexNow
if: >
(github.event_name == 'push' && github.ref == 'refs/heads/develop') ||
github.event_name == 'workflow_dispatch' ||
(github.event_name == 'release' && github.event.action == 'published')
(github.event_name == 'push' && github.ref == 'refs/heads/release/latest')
run: |
curl -s -o /dev/null -w "%{http_code}" -X POST "https://api.indexnow.org/IndexNow" \
-H "Content-Type: application/json; charset=utf-8" \
+8 -5
View File
@@ -13,11 +13,14 @@ repos:
hooks:
- id: trailing-whitespace
- id: check-yaml
exclude: mkdocs.yml
args: ["--unsafe"]
- id: check-executables-have-shebangs
- id: check-json
- id: check-toml
- id: check-case-conflict
- id: check-added-large-files
args: ["--maxkb=500", "--enforce-all"]
exclude: uv.lock|.*\.ipynb$
- id: detect-private-key
- id: pretty-format-json
exclude: demo.ipynb
@@ -26,7 +29,7 @@ repos:
- id: mixed-line-ending
- repo: https://github.com/JoC0de/pre-commit-prettier
rev: v3.8.2 # using tag; previously pinned SHA when tags were not persistent
rev: v3.8.3 # using tag; previously pinned SHA when tags were not persistent
hooks:
- id: prettier
files: \.(ya?ml|toml)$
@@ -44,10 +47,10 @@ repos:
- id: validate-pyproject
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.15.10
rev: v0.15.12
hooks:
- id: ruff-check
args: [--fix]
args: ["--fix"]
- id: ruff-format
types_or: [python, pyi, jupyter]
@@ -62,7 +65,7 @@ repos:
exclude: ^(docs/changelog\.md|docs/deprecated\.md)$
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.20.1
rev: v1.20.2
hooks:
- id: mypy
additional_dependencies:
+6
View File
@@ -0,0 +1,6 @@
/*
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
Content-Security-Policy: default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; img-src 'self' https: data:; media-src 'self' https: data:; font-src 'self' https: data:; style-src 'self'; script-src 'self'; connect-src 'self' https:;
+27
View File
@@ -0,0 +1,27 @@
---
comments: true
description: About Supervision, Roboflow's open-source Python library for building reusable computer vision workflows.
---
# About Supervision
Supervision is an open-source Python library by Roboflow for building computer vision applications. It gives developers a model-agnostic toolkit for loading predictions, annotating images and video, tracking objects, counting detections in zones, processing datasets, and evaluating model performance.
The project centers on a unified `Detections` API with converters for supported outputs from Ultralytics, Roboflow Inference, Hugging Face Transformers, SAM, Detectron2, MMDetection, YOLO-NAS, PaddleDet, NCNN, Azure AI Vision, and VLM parsers such as Florence-2, PaliGemma, Qwen VL, Gemini, DeepSeek VL 2, and Moondream. That common representation lets teams change models without rewriting annotation, filtering, tracking, dataset, or metrics code.
Supervision is maintained by Roboflow and an open-source contributor community. The library is MIT licensed, developed in public on GitHub, and published on PyPI.
## Project Links
- Source code: [github.com/roboflow/supervision](https://github.com/roboflow/supervision)
- Package: [pypi.org/project/supervision](https://pypi.org/project/supervision/)
- Community: [Roboflow Discord](https://discord.gg/GbfgXGJ8Bk)
- Roboflow: [roboflow.com](https://roboflow.com/)
## Maintainers and Contributors
Supervision has been shaped by Roboflow engineers and community contributors, including Piotr Skalski, Borda, onuralpszr, Soumik Mandal, and many others. The complete contributor history is available in the GitHub repository.
## Citation
If Supervision helps your research or production system, cite the project using the citation block in [llms.txt](https://supervision.roboflow.com/llms.txt) or link to the GitHub repository.
+1
View File
@@ -1,5 +1,6 @@
---
comments: true
description: API reference for supervision's assets module — download sample video and image files for demos, testing, and tutorials.
---
# Assets
+62 -3
View File
@@ -1,12 +1,31 @@
---
description: "Full version history of the supervision Python library — release notes, breaking changes, new features, and deprecations for every version."
date_modified: 2026-04-23
---
# Changelog
### 0.28.0 <small>Unreleased</small>
### 0.28.0 <small>Apr 30, 2026</small>
- Changed [#2178](https://github.com/roboflow/supervision/pull/2178): [`sv.Detections.from_inference`](https://supervision.roboflow.com/latest/detection/core/#supervision.detection.core.Detections.from_inference) now supports compressed COCO RLE masks. Inference responses with `rle` or `rle_mask` fields containing a compressed counts string (as produced by `pycocotools`) are decoded directly into binary masks, avoiding a lossy polygon round-trip.
- Added [#2159](https://github.com/roboflow/supervision/pull/2159): [`sv.CompactMask`](https://supervision.roboflow.com/develop/detection/compact_mask/#supervision.detection.compact_mask.CompactMask) for memory-efficient mask storage. Masks are stored as crop-region bounding boxes plus RLE-encoded data instead of full-resolution bitmaps, reducing memory by up to 240× for sparse masks. Integrates transparently with `sv.Detections.mask` — filtering, merging, and `area` all work without materialising the full array.
- Added [#2227](https://github.com/roboflow/supervision/pull/2227): [`sv.CompactMask.resize(new_image_shape)`](https://supervision.roboflow.com/develop/detection/compact_mask/#supervision.detection.compact_mask.CompactMask.resize) rescales all stored crops to match a new image resolution, enabling use across frames or after image resizing pipelines.
- Added [#2178](https://github.com/roboflow/supervision/pull/2178): [`sv.Detections.from_inference`](https://supervision.roboflow.com/latest/detection/core/#supervision.detection.core.Detections.from_inference) now supports compressed COCO RLE masks. Inference responses with `rle` or `rle_mask` fields containing a compressed counts string (as produced by `pycocotools`) are decoded directly into binary masks, avoiding a lossy polygon round-trip.
- Added [#2004](https://github.com/roboflow/supervision/pull/2004): [`sv.Color.from_hex`](https://supervision.roboflow.com/latest/utils/draw/#supervision.draw.color.Color.from_hex) now accepts 8-digit hexadecimal RGBA codes (e.g. `#ff00ff80`). [`Color.as_hex()`](https://supervision.roboflow.com/latest/utils/draw/#supervision.draw.color.Color.as_hex) serialises back, including alpha when not fully opaque. New utility functions `sv.hex_to_rgba`, `sv.rgba_to_hex`, and `sv.is_valid_hex` are exported at the top level.
- Added [#709](https://github.com/roboflow/supervision/pull/709): [`sv.BlurAnnotator`](https://supervision.roboflow.com/latest/detection/annotators/#supervision.annotators.core.BlurAnnotator) and [`sv.PixelateAnnotator`](https://supervision.roboflow.com/latest/detection/annotators/#supervision.annotators.core.PixelateAnnotator) now support dynamic sizing. When `kernel_size=None` or `pixel_size=None` (the new default), the size is computed per detection as a fraction of the shorter bounding-box dimension, producing consistent visual results across objects of different sizes.
- Added [#2186](https://github.com/roboflow/supervision/pull/2186): [`sv.InferenceSlicer`](https://supervision.roboflow.com/latest/detection/tools/inference_slicer/#supervision.detection.tools.inference_slicer.InferenceSlicer) now emits a warning when detections returned by the callback fall outside the tile boundaries, helping catch coordinate-system bugs in custom callbacks.
- Added [#2103](https://github.com/roboflow/supervision/pull/2103), [#2152](https://github.com/roboflow/supervision/pull/2152): New [`sv.Detections.from_sam3()`](https://supervision.roboflow.com/latest/detection/core/#supervision.detection.core.Detections.from_sam3) classmethod parses SAM3 PCS (text-prompted) and PVS (visual-prompted video segmentation) response formats into a standard `sv.Detections`, both from the local `inference` package and from Roboflow-hosted server responses.
- Added [#2154](https://github.com/roboflow/supervision/pull/2154): The library now uses Python's `logging` module instead of `print` for diagnostic output. Messages are emitted under the `supervision` logger so applications can capture, filter, or silence them through standard `logging` configuration.
- Added [#932](https://github.com/roboflow/supervision/pull/932): [`sv.ImageAssets`](https://supervision.roboflow.com/latest/assets/) for downloading sample images alongside existing video assets, useful for examples and tutorials.
- Changed [#2169](https://github.com/roboflow/supervision/pull/2169): [`sv.MeanAveragePrecisionResult`](https://supervision.roboflow.com/latest/metrics/mean_average_precision/) and related metric arrays (`mAP_scores`, `ap_per_class`, `iou_thresholds`, precision/recall) are now `float32` instead of `float64`. Reduces memory and speeds up computation; numerical results may differ in the last few digits.
- Changed [#2178](https://github.com/roboflow/supervision/pull/2178): [`sv.rle_to_mask`](https://supervision.roboflow.com/latest/detection/utils/converters/#supervision.detection.utils.converters.rle_to_mask) and [`sv.mask_to_rle`](https://supervision.roboflow.com/latest/detection/utils/converters/#supervision.detection.utils.converters.mask_to_rle) moved to `supervision.detection.utils.converters`. The old import path `supervision.dataset.utils` continues to work but is deprecated.
@@ -14,6 +33,46 @@ description: "Full version history of the supervision Python library — release
- Fixed [#2210](https://github.com/roboflow/supervision/pull/2210): [`sv.VideoInfo.fps`](https://supervision.roboflow.com/latest/utils/video/#supervision.utils.video.VideoInfo) now returns a `float` instead of a truncated `int`. Previously, frame rates like 23.976, 29.97, and 59.94 were silently truncated, causing frame-timing drift that accumulates over long videos. The type of `VideoInfo.fps` has changed from `int` to `float`; callers that pass `fps` to APIs requiring an integer (such as `deque(maxlen=...)` or `TraceAnnotator(trace_length=...)`) should wrap the value with `int()`.
- Fixed [#2209](https://github.com/roboflow/supervision/pull/2209): [`sv.Detections.is_empty()`](https://supervision.roboflow.com/latest/detection/core/#supervision.detection.core.Detections.is_empty) now returns `True` for detections filtered down to zero rows, even when `tracker_id` is an empty array. Previously this case incorrectly returned `False`.
- Fixed [#2199](https://github.com/roboflow/supervision/pull/2199): [`sv.CSVSink`](https://supervision.roboflow.com/latest/detection/tools/save_detections/#supervision.detection.tools.csv_sink.CSVSink) now correctly slices numpy array values in `custom_data` per row. Previously the full array was written for every detection.
- Fixed [#2216](https://github.com/roboflow/supervision/pull/2216): [`sv.CSVSink`](https://supervision.roboflow.com/latest/detection/tools/save_detections/#supervision.detection.tools.csv_sink.CSVSink) and [`sv.JSONSink`](https://supervision.roboflow.com/latest/detection/tools/save_detections/#supervision.detection.tools.json_sink.JSONSink) now slice plain Python `list` and `tuple` values in `custom_data` per detection row. Lists and tuples matching the detection count are indexed per row, consistent with `np.ndarray` behavior.
- Fixed [#2217](https://github.com/roboflow/supervision/pull/2217): [`sv.TraceAnnotator`](https://supervision.roboflow.com/latest/detection/annotators/#supervision.annotators.core.TraceAnnotator) no longer crashes in `smooth` mode when a tracker remains stationary. Duplicate consecutive points caused `splprep` to fail; the annotator now deduplicates anchor points and falls back to a raw polyline when fewer than 4 unique points are available.
- Fixed [#2218](https://github.com/roboflow/supervision/pull/2218): [`load_coco_annotations`](https://supervision.roboflow.com/latest/datasets/core/) now rejects COCO annotations whose `file_name` escapes the images directory via `../` traversal or absolute paths, preventing path-traversal attacks from malicious annotation files.
- Fixed [#2187](https://github.com/roboflow/supervision/pull/2187): Extreme memory usage when loading OBB (oriented bounding box) datasets, caused by allocating full-image masks for each rotated box, has been resolved.
- Fixed [#2188](https://github.com/roboflow/supervision/pull/2188): [`sv.KeyPoints`](https://supervision.roboflow.com/latest/keypoint/core/#supervision.key_points.core.KeyPoints) boolean mask indexing now works correctly when all instances have the same keypoint count (uniform-count selection).
- Fixed [#2185](https://github.com/roboflow/supervision/pull/2185): [`sv.DetectionDataset.as_coco()`](https://supervision.roboflow.com/latest/datasets/core/#supervision.dataset.core.DetectionDataset.as_coco) now preserves `area` and `iscrowd` fields instead of silently dropping them in the round-trip.
- Fixed [#1746](https://github.com/roboflow/supervision/pull/1746): Precision loss when converting annotations with `force_mask=True` in dataset format converters.
- Fixed [#1991](https://github.com/roboflow/supervision/pull/1991): [`sv.PolygonZone`](https://supervision.roboflow.com/latest/detection/tools/polygon_zone/) no longer double-counts the same object when multiple zones overlap. Detection bounding boxes were incorrectly clipped to each zone's ROI before anchor computation, causing the same detection to appear at a different anchor point in each zone; anchor is now computed from the original bounding box so containment is independent per zone.
- Fixed [#1868](https://github.com/roboflow/supervision/pull/1868): [`sv.LineZone`](https://supervision.roboflow.com/latest/detection/tools/line_zone/) no longer mis-attributes crossings when a tracker reuses the same `tracker_id` across different classes. Class-aware bookkeeping prevents a new object from inheriting another class's prior crossing state.
- Fixed [#2022](https://github.com/roboflow/supervision/pull/2022): [`sv.process_video`](https://supervision.roboflow.com/latest/utils/video/#supervision.utils.video.process_video) now raises immediately when the user callback throws, instead of silently swallowing the exception and hanging until the writer is flushed.
- Fixed [#2156](https://github.com/roboflow/supervision/pull/2156): [`sv.DetectionDataset`](https://supervision.roboflow.com/latest/datasets/core/#supervision.dataset.core.DetectionDataset) now populates `data["class_name"]` on every loaded annotation, matching what model connectors produce. Downstream code can rely on `class_name` being present whether detections come from a dataset or a model.
- Fixed [#1364](https://github.com/roboflow/supervision/pull/1364): [`sv.ByteTrack`](https://supervision.roboflow.com/latest/trackers/#supervision.tracker.byte_tracker.core.ByteTrack) now preserves externally assigned `tracker_id` values instead of overwriting them with internal ids on the first update.
- Fixed [#1853](https://github.com/roboflow/supervision/pull/1853): [`sv.ConfusionMatrix`](https://supervision.roboflow.com/latest/detection/metrics/#supervision.metrics.detection.ConfusionMatrix) `evaluate_detection_batch` now matches predictions to ground truth correctly when multiple detections fall on the same target. Previously, double-counting inflated false-positive and false-negative counts.
- Fixed [#2136](https://github.com/roboflow/supervision/pull/2136): [`sv.MeanAverageRecall`](https://supervision.roboflow.com/latest/metrics/mean_average_recall/) now computes mAR@K using the top-K detections per image, matching the COCO definition. Previous values were inflated relative to `pycocotools`.
- Fixed [#1086](https://github.com/roboflow/supervision/pull/1086), [#265](https://github.com/roboflow/supervision/pull/265): COCO export and `force_masks` behaviour are now consistent across dataset formats. Empty polygons no longer raise during `as_coco`, and `force_masks=True` produces masks regardless of source format.
- Deprecated [#2215](https://github.com/roboflow/supervision/pull/2215): [`sv.ByteTrack`](https://supervision.roboflow.com/latest/trackers/#supervision.tracker.byte_tracker.core.ByteTrack) is deprecated in favour of `ByteTrackTracker` from the external [`trackers`](https://pypi.org/project/trackers/) package (`pip install trackers`). The update method is renamed from `update_with_detections()` to `update()`. Removal planned for `supervision-0.30.0`.
- Deprecated [#2214](https://github.com/roboflow/supervision/pull/2214): `supervision.keypoint` module is deprecated; use `supervision.key_points` instead. `create_tiles` in `supervision.utils.image`, `ensure_cv2_image_for_processing` in `supervision.utils.conversion`, and keypoint validation utilities in `supervision.validators` are deprecated. The `LMM` enum (use `VLM`) and `from_lmm` method (use `from_vlm`) were deprecated in 0.26.0; this release migrates their deprecation mechanism to `pydeprecate`.
- Deprecated: `normalized_xyxy` argument in [`sv.denormalize_boxes`](https://supervision.roboflow.com/latest/detection/utils/boxes/#supervision.detection.utils.boxes.denormalize_boxes) renamed to `xyxy`. Passing `normalized_xyxy=` now emits a `FutureWarning`; support will be removed in `supervision-0.30.0`.
### 0.27.0 <small>Nov 16, 2025</small>
- Added [#2008](https://github.com/roboflow/supervision/pull/2008): [`sv.filter_segments_by_distance`](https://supervision.roboflow.com/0.27.0/detection/utils/masks/#supervision.detection.utils.masks.filter_segments_by_distance) to keep the largest connected component and nearby components within an absolute or relative distance threshold. Useful for cleaning segmentation predictions from models such as SAM, SAM2, YOLO segmentation, and RF-DETR segmentation.
@@ -307,7 +366,7 @@ sv.process_video(
- Added `as_detections` method to [`KeyPoints`](https://supervision.roboflow.com/0.25.0/keypoint/core/#supervision.keypoint.core.KeyPoints) that converts `KeyPoints` to `Detections`. ([#1658](https://github.com/roboflow/supervision/pull/1658))
- Added a new video to `supervision[assets]`. ([#1657](https://github.com/roboflow/supervision/pull/1657))
- Added a new video to the `supervision.assets` download catalog. ([#1657](https://github.com/roboflow/supervision/pull/1657))
```python
from supervision.assets import download_assets, VideoAssets
+29
View File
@@ -0,0 +1,29 @@
---
comments: true
description: Contact and support channels for Supervision documentation, bugs, feature requests, security reports, and community help.
---
# Contact
Use the channel that matches the kind of request you have.
## Bugs and Feature Requests
Open a GitHub issue for reproducible bugs, API requests, documentation fixes, and feature proposals:
[github.com/roboflow/supervision/issues](https://github.com/roboflow/supervision/issues)
## Community Support
Join the Roboflow Discord for community questions, examples, and implementation discussion:
[discord.gg/GbfgXGJ8Bk](https://discord.gg/GbfgXGJ8Bk)
## Package and Source
- PyPI package: [pypi.org/project/supervision](https://pypi.org/project/supervision/)
- GitHub repository: [github.com/roboflow/supervision](https://github.com/roboflow/supervision)
## Security Reports
For security-sensitive reports, avoid posting public exploit details in an issue. Use GitHub's private vulnerability reporting flow for the repository when available, or contact Roboflow through the security and support channels listed on [roboflow.com](https://roboflow.com/).
+1
View File
@@ -1,6 +1,7 @@
---
template: cookbooks.html
comments: true
description: Collection of practical computer vision cookbooks — object tracking, zero-shot detection, SAHI small object detection, occupancy analytics, and more.
hide:
- navigation
- toc
+58
View File
@@ -0,0 +1,58 @@
---
comments: true
description: Frequently asked questions about installing Supervision, supported computer vision models, datasets, tracking, metrics, and licensing.
---
# Frequently Asked Questions
## What is Supervision?
Supervision is an open-source Python library by Roboflow for computer vision workflows. It provides a unified `Detections` class with converters for supported object detection, segmentation, and VLM outputs.
## How do I install Supervision?
Install the base package with:
```bash
pip install supervision
```
Use the `metrics` extra when you need optional metric dependencies:
```bash
pip install "supervision[metrics]"
```
Sample asset utilities are part of the base package under `supervision.assets`.
## Which object detection models work with Supervision?
Supervision is model agnostic. `sv.Detections` includes converters for Ultralytics YOLO, Roboflow Inference, Hugging Face Transformers outputs, SAM, Detectron2, MMDetection, YOLO-NAS, PaddleDet, NCNN, Azure AI Vision, and VLM parsers including Florence-2, PaliGemma, Qwen VL, Gemini, DeepSeek VL 2, and Moondream. Keypoint outputs have separate `sv.KeyPoints` converters, including MediaPipe.
## What can I do with Supervision?
You can annotate images and video, filter detections, track objects, count objects in zones or across lines, load and convert datasets, evaluate models with detection metrics, and export predictions for downstream analysis.
## How do I track objects across video frames?
Assign persistent tracker IDs before visualization. The built-in `sv.ByteTrack` wrapper accepts `Detections` through `update_with_detections()`. After tracking, combine the output with annotators such as `sv.TraceAnnotator`, `sv.BoxAnnotator`, and `sv.LabelAnnotator`.
## What dataset formats does Supervision support?
For detection datasets, Supervision supports YOLO, COCO JSON, and Pascal VOC. Use `DetectionDataset.from_yolo()`, `DetectionDataset.from_coco()`, or `DetectionDataset.from_pascal_voc()` to load datasets, and the matching `as_*` methods to export them.
## How do I count objects in a zone?
Use `sv.PolygonZone` for arbitrary polygon regions and `sv.LineZone` for line-crossing counts. Line crossing requires `detections.tracker_id`, so run a tracker before calling the line zone trigger.
## How do I benchmark a model?
Use `supervision.metrics.mean_average_precision.MeanAveragePrecision` for mAP and `sv.ConfusionMatrix` for confusion matrices. Accumulate predictions and ground-truth `Detections`, then call `compute()` to calculate metrics.
## Is Supervision free to use?
Yes. Supervision is free and open source under the MIT license.
## Where is the source code?
The source code is available at [github.com/roboflow/supervision](https://github.com/roboflow/supervision).
+27
View File
@@ -1,6 +1,11 @@
---
comments: true
description: Benchmark object detection models with supervision — compute mAP, confusion matrix, and per-class metrics to compare model performance.
authors:
- name: Piotr Skalski
role: Computer Vision Engineer, Roboflow
github: https://github.com/SkalskiP
date_modified: 2026-04-22
---
![Corgi Example](https://media.roboflow.com/supervision/image-examples/how-to/benchmark-models/corgi-sorted-2.png)
@@ -445,3 +450,25 @@ A condensed version of this guide is also available as a [Colab Notebook](https:
For more details, be sure to check out our [documentation](https://supervision.roboflow.com/latest/) and join our community discussions. If you find any issues, please let us know on [GitHub](https://github.com/roboflow/supervision/issues).
Best of luck with your benchmarking!
## Frequently Asked Questions
### How do I benchmark a model with supervision?
Use `supervision.metrics.mean_average_precision.MeanAveragePrecision` — accumulate prediction and ground-truth `Detections` with `update(...)` and then call `compute()`. For confusion matrices, use `sv.ConfusionMatrix.from_detections(predictions=predictions, targets=targets, classes=classes)`.
### What IoU thresholds does MeanAveragePrecision use?
It computes mAP over IoU thresholds from 0.50 to 0.95 in steps of 0.05 (mAP@50:95), plus mAP@50 and mAP@75 individually.
### Can I benchmark segmentation models?
Yes, if you want to evaluate their bounding boxes. Convert model outputs to `Detections` and pass them to `MeanAveragePrecision.update(...)`; the current mAP path prepares COCO-style bounding boxes from `detections.xyxy`.
### What is a ConfusionMatrix and how do I use it?
`sv.ConfusionMatrix` visualizes true positives, false positives, and false negatives per class. Create one with `sv.ConfusionMatrix.from_detections(predictions=predictions, targets=targets, classes=classes, conf_threshold=0.5, iou_threshold=0.5)`, then call `metric.plot()` to render a heatmap.
## Author
- [Piotr Skalski](https://github.com/SkalskiP) — Computer Vision Engineer, Roboflow
+23
View File
@@ -1,6 +1,11 @@
---
comments: true
description: Count objects entering a polygon zone in images and video using supervision's PolygonZone — measure throughput and density in any region.
authors:
- name: Piotr Skalski
role: Computer Vision Engineer, Roboflow
github: https://github.com/SkalskiP
date_modified: 2026-04-22
---
With supervision, you can count the number of objects in a zone in an image or video. In this guide, we will show how to count the number of cars in a traffic video.
@@ -132,3 +137,21 @@ Here is an example of inference run on the video:
<video width="100%" loop muted autoplay>
<source src="https://blog.roboflow.com/content/media/2023/03/trim-counting.mp4" type="video/mp4">
</video>
## Frequently Asked Questions
### How do I count objects in a zone with supervision?
Create `sv.PolygonZone` with a polygon defining your region. Call `zone.trigger(detections)` on each frame — it returns a mask of detections inside the zone.
### Can I count objects crossing a line instead of entering a zone?
Yes. Use `sv.LineZone` — define a start and end point. `zone.trigger(detections)` returns a tuple of two boolean arrays, `(crossed_in, crossed_out)`, indicating which detections crossed the line in each direction. `LineZone` requires `detections.tracker_id`; run a tracker first so the same object can be matched across frames.
### Can I combine zone counting with tracking?
Yes. You can pass tracker IDs from `sv.ByteTrack` alongside your detections, but `sv.PolygonZone` still evaluates the zone on each frame and reports which objects are currently inside it. If you want to count each object only once when it first enters the zone, maintain a set of seen `tracker_id` values after filtering detections with `zone.trigger(detections)`, or use a dedicated entry/crossing counting tool such as `sv.LineZone` when it better matches your use case.
## Author
- [Piotr Skalski](https://github.com/SkalskiP) — Computer Vision Engineer, Roboflow
+31
View File
@@ -1,6 +1,14 @@
---
comments: true
description: Learn to load model predictions, create Detections objects, and annotate images with bounding boxes, labels, and masks using supervision.
authors:
- name: Piotr Skalski
role: Computer Vision Engineer, Roboflow
github: https://github.com/SkalskiP
- name: Borda
role: Open Source Engineer, Roboflow
github: https://github.com/borda
date_modified: 2026-04-22
---
# Detect and Annotate
@@ -427,3 +435,26 @@ that will allow you to draw masks instead of boxes.
```
![segmentation-annotation](https://media.roboflow.com/supervision_detect_and_annotate_example_3.png)
## Frequently Asked Questions
### How do I detect and annotate objects with supervision?
Pass any model's output to `sv.Detections.from_<model>()` to create a unified `Detections` object. Then pass it to `sv.BoxAnnotator` or `sv.MaskAnnotator` to draw predictions on an image.
### Can I annotate both bounding boxes and masks at the same time?
Yes. Chain annotators: first draw boxes with `BoxAnnotator`, then overlay masks with `MaskAnnotator` on the same scene.
### How do I label detections with class names?
Use `sv.LabelAnnotator` and pass custom text with the `labels` parameter. If a connector provides class names, they are stored in `detections["class_name"]` / `detections.data["class_name"]`; when `labels` is omitted, `LabelAnnotator` uses class names first, then class IDs, then detection indices.
### Can I use supervision with Hugging Face models?
Yes. `sv.Detections.from_transformers()` accepts supported Hugging Face object detection and segmentation outputs. Vision-language model outputs are handled through `sv.Detections.from_vlm(...)`, for example with `sv.VLM.FLORENCE_2` or `sv.VLM.PALIGEMMA`.
## Authors
- [Piotr Skalski](https://github.com/SkalskiP) — Computer Vision Engineer, Roboflow
- [Borda](https://github.com/borda) — Open Source Engineer, Roboflow
+23
View File
@@ -1,6 +1,11 @@
---
comments: true
description: Detect small objects in images by applying SAHI inference slicing with supervision's InferenceSlicer — improve recall for tiny targets.
authors:
- name: Piotr Skalski
role: Computer Vision Engineer, Roboflow
github: https://github.com/SkalskiP
date_modified: 2026-04-22
---
# Detect Small Objects
@@ -331,3 +336,21 @@ objects within each, and aggregating the results.
```
![detection-with-inference-slicer](https://media.roboflow.com/supervision-docs/inference-slicer-segmentation-example.png)
## Frequently Asked Questions
### How do I detect small objects with supervision?
Use `sv.InferenceSlicer` to split a high-resolution image into overlapping tiles, run detection on each tile, and merge results with non-maximum suppression. This dramatically improves recall for tiny targets.
### What overlap should I use between tiles?
`InferenceSlicer` takes overlap in pixels via `overlap_wh`, not as a percentage. The default is `100` pixels in both directions. Increase `overlap_wh` when objects are close to the tile size or often appear on tile boundaries, and decrease it when speed is more important.
### Can I use InferenceSlicer with any detection model?
Yes. Wrap any model or converter path that can produce `sv.Detections` in a callback, pass that callback to `sv.InferenceSlicer(callback=...)`, and then call the slicer with your image.
## Author
- [Piotr Skalski](https://github.com/SkalskiP) — Computer Vision Engineer, Roboflow
+31
View File
@@ -1,6 +1,11 @@
---
comments: true
description: Filter and query detection results by class, confidence, or spatial overlap using supervision's Detections API — clean predictions in one line.
authors:
- name: Piotr Skalski
role: Computer Vision Engineer, Roboflow
github: https://github.com/SkalskiP
date_modified: 2026-04-22
---
# Filter Detections
@@ -313,3 +318,29 @@ zone. In the example below you can see how to filter out all detections located
![original](https://media.roboflow.com/open-source/supervision/supervision-detection-original.png){ align=center width="800" }
</div>
## Frequently Asked Questions
### How do I filter detections by class in supervision?
Use NumPy-style boolean indexing: `detections[detections.class_id == 0]` for class 0. Combine with `&` or `|` for multiple conditions.
### How do I filter by confidence threshold?
`detections[detections.confidence > 0.5]` returns only detections above the threshold. Chain with class filters for precise results.
### How do I filter by bounding box area?
`detections[detections.area > 1000]` filters by pixel area. If masks are present, `detections.area` uses mask area; otherwise it uses bounding box area from `xyxy`. Use `detections.box_area` when you specifically need bounding box area.
### Can I filter by box aspect ratio or dimensions?
Yes. Use `detections.box_aspect_ratio` for aspect ratio filtering. If you need explicit box dimensions, compute them from `detections.xyxy` as `width = detections.xyxy[:, 2] - detections.xyxy[:, 0]` and `height = detections.xyxy[:, 3] - detections.xyxy[:, 1]`.
### How do I remove duplicate detections (NMS) from my results?
Use `detections.with_nms(threshold=0.5)` — it applies non-maximum suppression on the `xyxy` boxes.
## Author
- [Piotr Skalski](https://github.com/SkalskiP) — Computer Vision Engineer, Roboflow
+27
View File
@@ -1,6 +1,11 @@
---
comments: true
description: Load, split, merge, and convert computer vision datasets between YOLO, COCO, and Pascal VOC formats using supervision's DetectionDataset.
authors:
- name: Piotr Skalski
role: Computer Vision Engineer, Roboflow
github: https://github.com/SkalskiP
date_modified: 2026-04-22
---
With Supervision, you can load and manipulate classification, object detection, and
@@ -450,3 +455,25 @@ augmented_annotations = replace(
```
![augment-dataset](https://media.roboflow.com/supervision-docs/augment-dataset.png)
## Frequently Asked Questions
### What dataset formats does supervision support?
For detection datasets, supervision supports YOLO, COCO JSON, and Pascal VOC. Use `DetectionDataset.from_yolo()`, `from_coco()`, or `from_pascal_voc()` to load, and `as_yolo()`, `as_coco()`, or `as_pascal_voc()` to save. Classification datasets use `ClassificationDataset.from_folder_structure()` and `as_folder_structure()`.
### Can I split a dataset into train/val/test sets?
`DetectionDataset.split(split_ratio=0.8)` returns exactly two datasets: train (80%) and test (20%). If you need a validation set, split one of those subsets in a separate step.
### Can I merge two datasets together?
Yes. `DetectionDataset.merge([dataset_a, dataset_b])` combines multiple datasets into one. Useful for combining datasets from different sources.
### What augmentations are available?
Common augmentations such as flip, rotate, translate, scale, crop, color jitter, and Gaussian blur can be applied using an external library like Albumentations, as shown in the augmentation example above. Supervision does not provide an `sv.Augmenter` pipeline.
## Author
- [Piotr Skalski](https://github.com/SkalskiP) — Computer Vision Engineer, Roboflow
+29 -2
View File
@@ -1,6 +1,11 @@
---
comments: true
description: Save object detection results to CSV or JSON with supervision's CSVSink and JSONSink — export predictions for analysis and downstream pipelines.
authors:
- name: Piotr Skalski
role: Computer Vision Engineer, Roboflow
github: https://github.com/SkalskiP
date_modified: 2026-04-22
---
# Save Detections
@@ -11,7 +16,7 @@ processing. This guide demonstrates how to perform video inference using the
[Ultralytics](https://github.com/ultralytics/ultralytics) or
[Transformers](https://github.com/huggingface/transformers) packages and save their results with
[`sv.CSVSink`](https://supervision.roboflow.com/latest/detection/tools/save_detections/#supervision.detection.tools.csv_sink.CSVSink) and
[`sv.JSONSink`](https://supervision.roboflow.com/latest/detection/tools/save_detections/#supervision.detection.tools.csv_sink.JSONSink).
[`sv.JSONSink`](https://supervision.roboflow.com/latest/detection/tools/save_detections/#supervision.detection.tools.json_sink.JSONSink).
## Run Detection
@@ -234,7 +239,7 @@ If you prefer to save the result in a `.JSON` file instead of a `.CSV` file, all
need to do is replace
[`sv.CSVSink`](https://supervision.roboflow.com/latest/detection/tools/save_detections/#supervision.detection.tools.csv_sink.CSVSink)
with
[`sv.JSONSink`](https://supervision.roboflow.com/latest/detection/tools/save_detections/#supervision.detection.tools.csv_sink.JSONSink).
[`sv.JSONSink`](https://supervision.roboflow.com/latest/detection/tools/save_detections/#supervision.detection.tools.json_sink.JSONSink).
=== "Inference"
@@ -297,3 +302,25 @@ with
detections = sv.Detections.from_transformers(results)
sink.append(detections, {"frame_index": frame_index})
```
## Frequently Asked Questions
### How do I save detections to CSV with supervision?
Open `sv.CSVSink("output.csv")` as a context manager and call `sink.append(detections)` for each frame. The CSV includes box coordinates, confidence, class ID, tracker ID, and any fields stored in `detections.data`.
### Can I save detections to JSON instead?
Yes. Open `sv.JSONSink("output.json")` as a context manager and call `sink.append(detections)` for each frame. The file is written as a JSON array when the context exits.
### Can I add custom fields to the saved output?
Yes. Pass a dict as the second argument: `sink.append(detections, {"frame_index": 5})` — the keys become extra columns in the CSV or extra fields in the JSON.
### Can I save only specific classes or confidence levels?
Filter the `Detections` object before saving: `sink.append(detections[detections.confidence > 0.7])`.
## Author
- [Piotr Skalski](https://github.com/SkalskiP) — Computer Vision Engineer, Roboflow
+34 -3
View File
@@ -1,6 +1,14 @@
---
comments: true
description: Track objects across video frames with ByteTrack in supervision — assign persistent IDs and analyze motion from any object detection model.
authors:
- name: Piotr Skalski
role: Computer Vision Engineer, Roboflow
github: https://github.com/SkalskiP
- name: Soumik Mandal
role: ML Engineer, Roboflow
github: https://github.com/soumik12345
date_modified: 2026-04-22
---
# Track Objects
@@ -17,8 +25,8 @@ for a deeper analysis.
## Object Detection & Segmentation
To make it easier for you to follow our tutorial download the video we will use as an
example. You can do this using
[`supervision[assets]`](https://supervision.roboflow.com/latest/assets/) extension.
example. You can do this using the
[`supervision.assets`](https://supervision.roboflow.com/latest/assets/) module included in the base package.
This section demonstrates how to detect and segment objects in video frames using YOLOv8 with either the Inference or Ultralytics package. You will download a sample video, define a per-frame callback function that runs model prediction, and process the entire video to produce an annotated output file.
@@ -328,7 +336,7 @@ movement patterns and interactions between objects in the video.
Models aren't limited to object detection and segmentation. Keypoint detection allows for detailed analysis of body joints and connections, especially valuable for applications like human pose estimation. This section introduces keypoint tracking. We'll walk through the steps of annotating keypoints, converting them into bounding box detections compatible with `ByteTrack`, and applying detection smoothing for enhanced stability.
To make it easier for you to follow our tutorial, let's download the video we will use as an
example. You can do this using [`supervision[assets]`](https://supervision.roboflow.com/latest/assets/) extension.
example. You can do this using the [`supervision.assets`](https://supervision.roboflow.com/latest/assets/) module included in the base package.
```python
from supervision.assets import download_assets, VideoAssets
@@ -656,3 +664,26 @@ We could stop here as we have successfully tracked the object detected by the ke
</video>
This structured walkthrough should give a detailed pathway to annotate videos effectively using Supervision’s various functionalities, including object tracking and trace annotations.
## Frequently Asked Questions
### How do I track objects across video frames with supervision?
Pass `Detections` to `sv.ByteTrack.update_with_detections()` on each frame. The tracker assigns persistent IDs. Combine with `sv.TraceAnnotator` to visualize trajectories. `sv.ByteTrack` is deprecated in favor of `ByteTrackTracker` from the `trackers` package, where the update method is named `update()`.
### What should I know about ByteTrack?
ByteTrack uses low-confidence detections during association, which can improve continuity during missed or weak detections. Supervision's built-in `ByteTrack` wrapper is deprecated in favor of the external `trackers` package.
### Can I track instances instead of bounding boxes?
Yes. ByteTrack tracks bounding boxes. For instance masks, use `sv.MaskAnnotator` with the tracker IDs to color-code each tracked object consistently.
### Does ByteTrack work with any detection model?
Yes. ByteTrack is model-agnostic - it accepts any `Detections` object with bounding boxes, regardless of the supported converter or model output that produced it.
## Authors
- [Piotr Skalski](https://github.com/SkalskiP) — Computer Vision Engineer, Roboflow
- [Soumik Mandal](https://github.com/soumik12345) — ML Engineer, Roboflow
+2 -2
View File
@@ -26,11 +26,11 @@ description: Open-source Python library providing computer vision tools for anno
## What is Supervision?
Supervision is an open-source Python library by Roboflow for building computer vision applications. It provides a unified `Detections` object that works with YOLO, SAM, Grounding DINO, Transformers, and 20+ model frameworks — use any detector, get the same composable API.
Supervision is an open-source Python library by Roboflow for building computer vision applications. It provides a unified `Detections` object with converters for supported outputs from Ultralytics, Roboflow Inference, Transformers, SAM, Detectron2, MMDetection, YOLO-NAS, PaddleDet, NCNN, Azure AI Vision, and VLM parsers.
With Supervision you can annotate images and video with bounding boxes, masks, and labels; track objects across frames with persistent IDs; count and filter detections inside polygon zones; load and convert datasets between YOLO, COCO, and Pascal VOC formats; and benchmark model performance with mAP and confusion matrices.
Trusted by researchers (cited in 4,000+ papers) and practitioners (38,000+ GitHub stars, 1M+ monthly PyPI downloads), Supervision is the standard toolkit for production computer vision workflows.
Supervision is MIT licensed, has 38,000+ GitHub stars, and over 1 million monthly PyPI downloads. It is developed in public on GitHub for production computer vision workflows.
## 👋 Hello
+192
View File
@@ -0,0 +1,192 @@
# supervision
> Large-context AI crawler summary for Supervision documentation.
Supervision is an open-source Python library by Roboflow for computer vision workflows. It provides a model-agnostic `Detections` class and composable tools for object detection, instance segmentation, keypoint detection, annotation, tracking, zone counting, dataset conversion, and model evaluation.
Supervision is MIT licensed, published on PyPI, developed on GitHub, and used by researchers and practitioners in production computer vision systems. The library includes converters for supported outputs from Ultralytics, Roboflow Inference, Hugging Face Transformers, SAM, Detectron2, MMDetection, YOLO-NAS, PaddleDet, NCNN, Azure AI Vision, and VLM parsers.
## Primary Links
- Latest stable docs: https://supervision.roboflow.com/latest/
- Development docs: https://supervision.roboflow.com/develop/
- Source code: https://github.com/roboflow/supervision
- PyPI package: https://pypi.org/project/supervision/
- Changelog: https://supervision.roboflow.com/latest/changelog/
- Sitemap: https://supervision.roboflow.com/sitemap.xml
- Standard LLM summary: https://supervision.roboflow.com/llms.txt
- Full LLM summary: https://supervision.roboflow.com/llms.full.txt
## AI Access
The documentation is static HTML and is open for AI crawler consumption. `robots.txt` explicitly allows general crawlers plus GPTBot, ClaudeBot, PerplexityBot, Bytespider, CCBot, GoogleOther, and Applebot.
## Install
```bash
pip install supervision
```
Optional extras:
```bash
pip install "supervision[metrics]"
```
Sample asset utilities are included in the base package under `supervision.assets`.
## Core Concepts
### `sv.Detections`
`sv.Detections` is the central data structure in Supervision. It stores bounding boxes, segmentation masks, confidence scores, class IDs, tracker IDs, and arbitrary per-detection metadata in a `data` dictionary. It supports NumPy-style indexing for filtering by confidence, class, area, and spatial constraints.
Most connectors, annotators, trackers, dataset tools, and metrics either accept or return `Detections`, which makes it possible to change the upstream model while keeping downstream processing code stable.
### Model Connectors
Supervision normalizes outputs from multiple computer vision frameworks into the same `Detections` API. Common constructors include:
- `sv.Detections.from_ultralytics(...)`
- `sv.Detections.from_inference(...)`
- `sv.Detections.from_transformers(...)`
- `sv.Detections.from_vlm(...)`
- `sv.Detections.from_sam(...)`
- `sv.Detections.from_detectron2(...)`
- `sv.Detections.from_mmdetection(...)`
### Annotation
Supervision includes annotators for drawing boxes, masks, labels, traces, zones, vertices, edges, and other overlays on images and video frames. Common annotators include:
- `sv.BoxAnnotator`
- `sv.MaskAnnotator`
- `sv.LabelAnnotator`
- `sv.TraceAnnotator`
- `sv.PolygonZoneAnnotator`
- `sv.LineZoneAnnotator`
### Tracking
The built-in `sv.ByteTrack` wrapper assigns persistent IDs across video frames through `update_with_detections()`. The docs also note the migration path toward `ByteTrackTracker` from the external `trackers` package. Tracked detections can be passed to label, trace, zone, and line-counting annotators.
### Zones and Counting
`sv.PolygonZone` checks whether detections are inside an arbitrary polygon. `sv.LineZone` counts line crossings and requires `detections.tracker_id` so objects can be matched across frames. These tools are typically used with video callbacks and annotators to build traffic, occupancy, queue, and throughput analytics.
### Datasets
`sv.DetectionDataset` loads, merges, splits, and converts object detection datasets. Supported formats include YOLO, COCO JSON, and Pascal VOC. `sv.ClassificationDataset` supports folder-structured classification datasets.
### Metrics
Supervision includes detection metrics including mean average precision, mean average recall, precision, recall, F1 score, and confusion matrices. The current mAP workflow uses `supervision.metrics.mean_average_precision.MeanAveragePrecision` with `update(...)` and `compute()`.
## How-To Guides
- Detect and annotate: https://supervision.roboflow.com/latest/how_to/detect_and_annotate/
- Track objects: https://supervision.roboflow.com/latest/how_to/track_objects/
- Detect small objects: https://supervision.roboflow.com/latest/how_to/detect_small_objects/
- Filter detections: https://supervision.roboflow.com/latest/how_to/filter_detections/
- Save detections: https://supervision.roboflow.com/latest/how_to/save_detections/
- Count in zone: https://supervision.roboflow.com/latest/how_to/count_in_zone/
- Benchmark a model: https://supervision.roboflow.com/latest/how_to/benchmark_a_model/
- Process datasets: https://supervision.roboflow.com/latest/how_to/process_datasets/
## Reference Documentation
- Detections: https://supervision.roboflow.com/latest/detection/core/
- Detection annotators: https://supervision.roboflow.com/latest/detection/annotators/
- Compact masks: https://supervision.roboflow.com/latest/detection/compact_mask/
- Detection converters: https://supervision.roboflow.com/latest/detection/utils/converters/
- IoU and NMS: https://supervision.roboflow.com/latest/detection/utils/iou_and_nms/
- Boxes: https://supervision.roboflow.com/latest/detection/utils/boxes/
- Masks: https://supervision.roboflow.com/latest/detection/utils/masks/
- Polygons: https://supervision.roboflow.com/latest/detection/utils/polygons/
- Vision-language model helpers: https://supervision.roboflow.com/latest/detection/utils/vlms/
- Keypoint core: https://supervision.roboflow.com/latest/keypoint/core/
- Keypoint annotators: https://supervision.roboflow.com/latest/keypoint/annotators/
- Classification core: https://supervision.roboflow.com/latest/classification/core/
- Trackers: https://supervision.roboflow.com/latest/trackers/
- Dataset core: https://supervision.roboflow.com/latest/datasets/core/
- Mean average precision: https://supervision.roboflow.com/latest/metrics/mean_average_precision/
- Mean average recall: https://supervision.roboflow.com/latest/metrics/mean_average_recall/
- Precision: https://supervision.roboflow.com/latest/metrics/precision/
- Recall: https://supervision.roboflow.com/latest/metrics/recall/
- F1 score: https://supervision.roboflow.com/latest/metrics/f1_score/
- Common metric values: https://supervision.roboflow.com/latest/metrics/common_values/
- Line zone: https://supervision.roboflow.com/latest/detection/tools/line_zone/
- Polygon zone: https://supervision.roboflow.com/latest/detection/tools/polygon_zone/
- Inference slicer: https://supervision.roboflow.com/latest/detection/tools/inference_slicer/
- Detection smoother: https://supervision.roboflow.com/latest/detection/tools/smoother/
- Detection export sinks: https://supervision.roboflow.com/latest/detection/tools/save_detections/
- Video utilities: https://supervision.roboflow.com/latest/utils/video/
- Image utilities: https://supervision.roboflow.com/latest/utils/image/
- Iterable utilities: https://supervision.roboflow.com/latest/utils/iterables/
- Notebook utilities: https://supervision.roboflow.com/latest/utils/notebook/
- File utilities: https://supervision.roboflow.com/latest/utils/file/
- Draw utilities: https://supervision.roboflow.com/latest/utils/draw/
- Geometry utilities: https://supervision.roboflow.com/latest/utils/geometry/
- Assets: https://supervision.roboflow.com/latest/assets/
## Cookbooks
- Supervision quickstart: https://supervision.roboflow.com/latest/notebooks/quickstart/
- Count objects crossing the line: https://supervision.roboflow.com/latest/notebooks/count-objects-crossing-the-line/
- Object tracking: https://supervision.roboflow.com/latest/notebooks/object-tracking/
- Small object detection with SAHI: https://supervision.roboflow.com/latest/notebooks/small-object-detection-with-sahi/
- Zero-shot object detection with YOLO-World: https://supervision.roboflow.com/latest/notebooks/zero-shot-object-detection-with-yolo-world/
- Save detections to CSV: https://supervision.roboflow.com/latest/notebooks/serialise-detections-to-csv/
- Save detections to JSON: https://supervision.roboflow.com/latest/notebooks/serialise-detections-to-json/
- Occupancy analytics: https://supervision.roboflow.com/latest/notebooks/occupancy_analytics/
- Annotate video with detections: https://supervision.roboflow.com/latest/notebooks/annotate-video-with-detections/
## Trust and Contact Pages
- About: https://supervision.roboflow.com/latest/about/
- Contact: https://supervision.roboflow.com/latest/contact/
- FAQ: https://supervision.roboflow.com/latest/faq/
- License: https://github.com/roboflow/supervision/blob/develop/LICENSE.md
- Issues: https://github.com/roboflow/supervision/issues
- Community: https://discord.gg/GbfgXGJ8Bk
## Frequently Asked Questions
### What is Supervision?
Supervision is an open-source Python library by Roboflow for computer vision workflows. It provides a unified `Detections` class with converters for supported detection, segmentation, and VLM outputs.
### Is Supervision tied to one model provider?
No. Supervision is model agnostic. It is designed to normalize model outputs into a common API so downstream annotation, filtering, tracking, metrics, and dataset code can be reused.
### What dataset formats are supported?
For object detection datasets, Supervision supports YOLO, COCO JSON, and Pascal VOC import and export. For classification datasets, it supports folder-structure import and export.
### How do I detect small objects?
Use `sv.InferenceSlicer` to split large images into overlapping tiles, run inference on each tile, and merge the resulting detections with non-maximum suppression or non-maximum merge.
### How do I count objects crossing a line?
Run a tracker first to assign `detections.tracker_id`, then use `sv.LineZone.trigger(detections)` to calculate crossing events. Use `sv.LineZoneAnnotator` for visualization.
### How do I benchmark a model?
Load predictions and ground truth as `Detections`, update a `MeanAveragePrecision` metric object, and call `compute()`. Use `sv.ConfusionMatrix` when class-level confusion analysis is needed.
## Citation
```bibtex
@software{supervision,
author = {Roboflow},
title = {Supervision: Computer Vision Toolkit},
url = {https://github.com/roboflow/supervision},
year = {2023}
}
```
## Versioning
`/develop/` is built from the `develop` branch. `/latest/` is built from the `release/latest` branch. Published releases build tag-only documentation paths and do not move `/latest/`.
+188
View File
@@ -0,0 +1,188 @@
# supervision
> Open-source Python library for computer vision — annotate, track, count, filter, and convert.
Supervision is a Python library by Roboflow that provides a model-agnostic `Detections` class and composable tools for object detection and segmentation workflows. It includes converters for supported outputs from Ultralytics, Roboflow Inference, Hugging Face Transformers, SAM, Detectron2, MMDetection, YOLO-NAS, PaddleDet, NCNN, Azure AI Vision, and VLM parsers.
Supervision is MIT licensed, published on PyPI, and developed in public on GitHub.
## AI Access
The documentation is static HTML and open for AI consumption. `robots.txt` explicitly allows general crawlers plus selected AI crawlers.
- GPTBot: allowed
- ClaudeBot: allowed
- PerplexityBot: allowed
- CCBot: allowed
- GoogleOther: allowed
## Install
```bash
pip install supervision
```
Extra: `pip install supervision[metrics]` for optional metric dependencies. Sample asset utilities are included in the base package under `supervision.assets`.
## Links
- GitHub: https://github.com/roboflow/supervision
- PyPI: https://pypi.org/project/supervision
- Docs (latest stable): https://supervision.roboflow.com/latest/
- Docs (develop): https://supervision.roboflow.com/develop/
- Changelog: https://supervision.roboflow.com/latest/changelog/
- Sitemap: https://supervision.roboflow.com/sitemap.xml
## Key APIs
### sv.Detections
Core data structure for bounding boxes, masks, confidence scores, class IDs, tracker IDs, and arbitrary per-detection metadata stored in a `data` dict. The lingua franca of the entire library — every connector, annotator, and tracker accepts or returns `Detections`. Supports NumPy-style boolean indexing for filtering by class, confidence, area, and spatial regions.
### sv.BoxAnnotator, sv.MaskAnnotator, sv.LabelAnnotator
Draw bounding boxes, segmentation masks, and text labels on images. Annotators expose `annotate(scene=..., detections=...)`; pass an input image and a `Detections` object to get the annotated output. `LabelAnnotator` can use explicit `labels` or fall back to `detections["class_name"]`, class IDs, then detection indices. Colors can be assigned by class or manually specified.
### sv.ByteTrack
Object tracker wrapper that assigns persistent IDs across video frames. The built-in `sv.ByteTrack` accepts `Detections` via `update_with_detections()`, but it is deprecated in favor of `ByteTrackTracker` from the external `trackers` package, where the method is named `update()`. Use tracked `Detections` with `sv.TraceAnnotator` to visualize trajectories.
### sv.PolygonZone and sv.LineZone
Zone-based counting. `PolygonZone.trigger(detections)` returns a boolean mask for detections currently inside an arbitrary polygon. `LineZone.trigger(detections)` returns `(crossed_in, crossed_out)` arrays for line crossings and requires `detections.tracker_id` so objects can be matched across frames. Both are commonly paired with zone annotators for visualization.
### sv.DetectionDataset and sv.ClassificationDataset
For detection datasets, load, merge, split, and convert between YOLO, COCO JSON, and Pascal VOC formats. Classification datasets use folder-structure import and export via `ClassificationDataset.from_folder_structure()` and `as_folder_structure()`.
### sv.InferenceSlicer
SAHI-style inference slicing: split high-resolution images into overlapping tiles, run detection on each tile, merge results with non-maximum suppression or non-maximum merge. Configure tile overlap in pixels with `overlap_wh`.
### supervision.metrics.MeanAveragePrecision and sv.ConfusionMatrix
Benchmarking tools. For mAP@0.5:0.95, use `supervision.metrics.MeanAveragePrecision` with `update()` and `compute()` rather than the deprecated top-level `sv.MeanAveragePrecision.from_detections()`. `ConfusionMatrix.from_detections(predictions=predictions, targets=targets, classes=classes)` generates a confusion matrix for detection results.
### sv.CSVSink and sv.JSONSink
Export detection results to structured files. Use `CSVSink` and `JSONSink` as context managers, call `sink.append(detections, custom_data=...)`, and they write one row/object per detection with box coordinates, confidence, class ID, tracker ID, and data fields.
## How-To Guides
- Detect and annotate: https://supervision.roboflow.com/latest/how_to/detect_and_annotate/
- Track objects: https://supervision.roboflow.com/latest/how_to/track_objects/
- Detect small objects: https://supervision.roboflow.com/latest/how_to/detect_small_objects/
- Filter detections: https://supervision.roboflow.com/latest/how_to/filter_detections/
- Save detections: https://supervision.roboflow.com/latest/how_to/save_detections/
- Count in zone: https://supervision.roboflow.com/latest/how_to/count_in_zone/
- Benchmark a model: https://supervision.roboflow.com/latest/how_to/benchmark_a_model/
- Process datasets: https://supervision.roboflow.com/latest/how_to/process_datasets/
## Reference Documentation
- Detections (detection/core): https://supervision.roboflow.com/latest/detection/core/
- Annotators (detection/annotators): https://supervision.roboflow.com/latest/detection/annotators/
- CompactMask (detection/compact_mask): https://supervision.roboflow.com/latest/detection/compact_mask/
- Format Converters (detection/utils/converters): https://supervision.roboflow.com/latest/detection/utils/converters/
- IoU and NMS (detection/utils/iou_and_nms): https://supervision.roboflow.com/latest/detection/utils/iou_and_nms/
- Boxes (detection/utils/boxes): https://supervision.roboflow.com/latest/detection/utils/boxes/
- Masks (detection/utils/masks): https://supervision.roboflow.com/latest/detection/utils/masks/
- Polygons (detection/utils/polygons): https://supervision.roboflow.com/latest/detection/utils/polygons/
- VLMs (detection/utils/vlms): https://supervision.roboflow.com/latest/detection/utils/vlms/
- Keypoint Core (keypoint/core): https://supervision.roboflow.com/latest/keypoint/core/
- Keypoint Annotators (keypoint/annotators): https://supervision.roboflow.com/latest/keypoint/annotators/
- Classification Core (classification/core): https://supervision.roboflow.com/latest/classification/core/
- ByteTrack Tracker (trackers): https://supervision.roboflow.com/latest/trackers/
- Datasets Core (datasets/core): https://supervision.roboflow.com/latest/datasets/core/
- mAP (metrics/mean_average_precision): https://supervision.roboflow.com/latest/metrics/mean_average_precision/
- mAR (metrics/mean_average_recall): https://supervision.roboflow.com/latest/metrics/mean_average_recall/
- Precision (metrics/precision): https://supervision.roboflow.com/latest/metrics/precision/
- Recall (metrics/recall): https://supervision.roboflow.com/latest/metrics/recall/
- F1 Score (metrics/f1_score): https://supervision.roboflow.com/latest/metrics/f1_score/
- Common Values (metrics/common_values): https://supervision.roboflow.com/latest/metrics/common_values/
- Line Zone (detection/tools/line_zone): https://supervision.roboflow.com/latest/detection/tools/line_zone/
- Polygon Zone (detection/tools/polygon_zone): https://supervision.roboflow.com/latest/detection/tools/polygon_zone/
- Inference Slicer (detection/tools/inference_slicer): https://supervision.roboflow.com/latest/detection/tools/inference_slicer/
- Detection Smoother (detection/tools/smoother): https://supervision.roboflow.com/latest/detection/tools/smoother/
- Save Detections Tool (detection/tools/save_detections): https://supervision.roboflow.com/latest/detection/tools/save_detections/
- Video Utils (utils/video): https://supervision.roboflow.com/latest/utils/video/
- Image Utils (utils/image): https://supervision.roboflow.com/latest/utils/image/
- Iterable Utils (utils/iterables): https://supervision.roboflow.com/latest/utils/iterables/
- Notebook Utils (utils/notebook): https://supervision.roboflow.com/latest/utils/notebook/
- File Utils (utils/file): https://supervision.roboflow.com/latest/utils/file/
- Draw Utils (utils/draw): https://supervision.roboflow.com/latest/utils/draw/
- Geometry (utils/geometry): https://supervision.roboflow.com/latest/utils/geometry/
- Assets (assets): https://supervision.roboflow.com/latest/assets/
## Cookbooks
- Object tracking: https://supervision.roboflow.com/latest/cookbooks/#object-tracking
- Count objects crossing line: https://supervision.roboflow.com/latest/cookbooks/#count-objects-crossing-the-line
- Zero-shot object detection with YOLO-World: https://supervision.roboflow.com/latest/cookbooks/#zero-shot-object-detection-with-yolo-world
- SAHI small object detection: https://supervision.roboflow.com/latest/cookbooks/#small-object-detection-with-sahi
## FAQ
### What is supervision?
Supervision is an open-source Python library by Roboflow for computer vision workflows. It provides a unified `Detections` class with converters for supported detection, segmentation, and VLM outputs, plus tools for annotation, tracking, zone counting, dataset management, and model benchmarking.
### How do I install supervision?
Install with `pip install supervision`. For optional metric dependencies use `pip install supervision[metrics]`. Sample asset utilities are included in the base package under `supervision.assets`. The current package metadata requires Python 3.9+.
### What can I do with supervision?
Annotate images and video with bounding boxes, masks, and labels; track objects across frames with persistent IDs; count detections inside polygon zones or line crossings; filter and query detection results; load, split, and convert detection datasets between YOLO, COCO, and Pascal VOC formats; manage classification datasets with folder structures; and benchmark model performance with mAP and confusion matrices.
### Is supervision free to use?
Yes. Supervision is free and open-source under the MIT license. Source code is at https://github.com/roboflow/supervision.
### Which object detection models work with supervision?
Supervision is model-agnostic and works with supported outputs from Ultralytics YOLO, Roboflow Inference, Hugging Face Transformers, SAM, Detectron2, MMDetection, YOLO-NAS, PaddleDet, NCNN, Azure AI Vision, and VLM parsers such as Florence-2, PaliGemma, Qwen VL, Gemini, DeepSeek VL 2, and Moondream. Keypoint outputs have separate converters, including MediaPipe.
### How do I benchmark a model with supervision?
Use `supervision.metrics.mean_average_precision.MeanAveragePrecision` for mAP — accumulate predictions and ground truth with `update(...)` then call `compute()`. For confusion matrices, use `sv.ConfusionMatrix.from_detections(predictions=predictions, targets=targets, classes=classes)`. See the Benchmark a Model how-to guide for a complete walkthrough.
### How do I track objects across video frames?
Use a tracker to assign persistent IDs. The built-in `sv.ByteTrack` wrapper accepts `Detections` with `update_with_detections()`, but it is deprecated in favor of `ByteTrackTracker` from the external `trackers` package. Combine tracked detections with `sv.TraceAnnotator` to visualize trajectories.
### What dataset formats does supervision support?
For detection datasets, supervision supports YOLO, COCO JSON, and Pascal VOC. Use `DetectionDataset.from_yolo()`, `from_coco()`, or `from_pascal_voc()` to load, and `as_yolo()`, `as_coco()`, or `as_pascal_voc()` to save. For classification datasets, use `ClassificationDataset.from_folder_structure()` and `as_folder_structure()`.
### How do I count objects in a zone?
Use `sv.PolygonZone` for arbitrary polygon zones. Use `sv.LineZone` for line-crossing counts after assigning tracker IDs, because `LineZone` needs `detections.tracker_id` to match objects across frames.
### How do I detect small objects with supervision?
Use `sv.InferenceSlicer` to split high-resolution images into overlapping tiles, run detection on each tile, and merge results with non-maximum suppression. Configure tile overlap in pixels with `overlap_wh`. See the Detect Small Objects how-to guide.
## Benchmarking
Supervision includes `supervision.metrics.MeanAveragePrecision` and `sv.ConfusionMatrix` for benchmarking object detection models. A curated [Model Leaderboard](https://leaderboard.roboflow.com/) compares YOLOv8, YOLOv11, and other models on standard datasets. The leaderboard repository is open source at https://github.com/roboflow/model-leaderboard.
## License
MIT — https://github.com/roboflow/supervision/blob/develop/LICENSE.md
## Citation
```bibtex
@software{supervision,
author = {Roboflow},
title = {Supervision: Computer Vision Toolkit},
url = {https://github.com/roboflow/supervision},
year = {2023}
}
```
## Versioning
Stable release docs: https://supervision.roboflow.com/latest/
Development branch: https://supervision.roboflow.com/develop/
+129 -9
View File
@@ -2,7 +2,19 @@
> Open-source Python library for computer vision — annotate, track, count, filter, and convert.
Supervision is a Python library by Roboflow that provides a model-agnostic `Detections` class and composable tools for object detection and segmentation workflows. Works with YOLO, SAM, Grounding DINO, Transformers, Inference, and 20+ other model frameworks.
Supervision is a Python library by Roboflow that provides a model-agnostic `Detections` class and composable tools for object detection and segmentation workflows. It includes converters for supported outputs from Ultralytics, Roboflow Inference, Hugging Face Transformers, SAM, Detectron2, MMDetection, YOLO-NAS, PaddleDet, NCNN, Azure AI Vision, and VLM parsers.
Supervision is MIT licensed, published on PyPI, and developed in public on GitHub.
## AI Access
The documentation is static HTML and open for AI consumption. `robots.txt` explicitly allows general crawlers plus selected AI crawlers.
- GPTBot: allowed
- ClaudeBot: allowed
- PerplexityBot: allowed
- CCBot: allowed
- GoogleOther: allowed
## Install
@@ -10,22 +22,41 @@ Supervision is a Python library by Roboflow that provides a model-agnostic `Dete
pip install supervision
```
Extra: `pip install supervision[metrics]` for optional metric dependencies. Sample asset utilities are included in the base package under `supervision.assets`.
## Links
- GitHub: https://github.com/roboflow/supervision
- PyPI: https://pypi.org/project/supervision
- Docs: https://supervision.roboflow.com/latest/
- Docs (latest stable): https://supervision.roboflow.com/latest/
- Changelog: https://supervision.roboflow.com/latest/changelog/
- Sitemap: https://supervision.roboflow.com/sitemap.xml
## Key APIs
- `sv.Detections` — core data structure for bounding boxes, masks, confidence scores, class IDs, and tracker IDs
- `sv.BoxAnnotator`, `sv.MaskAnnotator`, `sv.LabelAnnotator` — draw predictions on images and video
- `sv.ByteTrack`, `sv.SORT` — track objects across video frames with persistent IDs
- `sv.PolygonZone`, `sv.LineZone` — count and filter detections by spatial region
- `sv.DetectionDataset` — load, merge, split, and convert YOLO / COCO / Pascal VOC datasets
- `sv.InferenceSlicer` — SAHI-style sliced inference for small object detection
- `sv.CSVSink`, `sv.JSONSink` — export detection results to CSV or JSON
### sv.Detections
Core data structure for bounding boxes, masks, confidence scores, class IDs, tracker IDs, and arbitrary per-detection metadata stored in a `data` dict. The lingua franca of the entire library — every connector, annotator, and tracker accepts or returns `Detections`. Supports NumPy-style boolean indexing for filtering by class, confidence, area, and spatial regions.
### sv.BoxAnnotator, sv.MaskAnnotator, sv.LabelAnnotator
Draw bounding boxes, segmentation masks, and text labels on images. Annotators expose `annotate(scene=..., detections=...)`; pass an input image and a `Detections` object to get the annotated output. `LabelAnnotator` can use explicit `labels` or fall back to `detections["class_name"]`, class IDs, then detection indices. Colors can be assigned by class or manually specified.
### sv.ByteTrack
Object tracker wrapper that assigns persistent IDs across video frames. The built-in `sv.ByteTrack` accepts `Detections` via `update_with_detections()`, but it is deprecated in favor of `ByteTrackTracker` from the external `trackers` package, where the method is named `update()`. Use tracked `Detections` with `sv.TraceAnnotator` to visualize trajectories.
### sv.PolygonZone and sv.LineZone
Zone-based counting. `PolygonZone.trigger(detections)` returns a boolean mask for detections currently inside an arbitrary polygon. `LineZone.trigger(detections)` returns `(crossed_in, crossed_out)` arrays for line crossings and requires `detections.tracker_id` so objects can be matched across frames. Both are commonly paired with zone annotators for visualization.
### sv.DetectionDataset and sv.ClassificationDataset
For detection datasets, load, merge, split, and convert between YOLO, COCO JSON, and Pascal VOC formats. Classification datasets use folder-structure import and export via `ClassificationDataset.from_folder_structure()` and `as_folder_structure()`.
### sv.InferenceSlicer
SAHI-style inference slicing: split high-resolution images into overlapping tiles, run detection on each tile, merge results with non-maximum suppression or non-maximum merge. Configure tile overlap in pixels with `overlap_wh`.
### supervision.metrics.MeanAveragePrecision and sv.ConfusionMatrix
Benchmarking tools. For mAP@0.5:0.95, use `supervision.metrics.MeanAveragePrecision` with `update()` and `compute()` rather than the deprecated top-level `sv.MeanAveragePrecision.from_detections()`. `ConfusionMatrix.from_detections(predictions=predictions, targets=targets, classes=classes)` generates a confusion matrix for detection results.
### sv.CSVSink and sv.JSONSink
Export detection results to structured files. Use `CSVSink` and `JSONSink` as context managers, call `sink.append(detections, custom_data=...)`, and they write one row/object per detection with box coordinates, confidence, class ID, tracker ID, and data fields.
## How-To Guides
@@ -38,6 +69,95 @@ pip install supervision
- Benchmark a model: https://supervision.roboflow.com/latest/how_to/benchmark_a_model/
- Process datasets: https://supervision.roboflow.com/latest/how_to/process_datasets/
## Reference Documentation
- Detections (detection/core): https://supervision.roboflow.com/latest/detection/core/
- Annotators (detection/annotators): https://supervision.roboflow.com/latest/detection/annotators/
- CompactMask (detection/compact_mask): https://supervision.roboflow.com/latest/detection/compact_mask/
- Format Converters (detection/utils/converters): https://supervision.roboflow.com/latest/detection/utils/converters/
- IoU and NMS (detection/utils/iou_and_nms): https://supervision.roboflow.com/latest/detection/utils/iou_and_nms/
- Boxes (detection/utils/boxes): https://supervision.roboflow.com/latest/detection/utils/boxes/
- Masks (detection/utils/masks): https://supervision.roboflow.com/latest/detection/utils/masks/
- Polygons (detection/utils/polygons): https://supervision.roboflow.com/latest/detection/utils/polygons/
- VLMs (detection/utils/vlms): https://supervision.roboflow.com/latest/detection/utils/vlms/
- Keypoint Core (keypoint/core): https://supervision.roboflow.com/latest/keypoint/core/
- Keypoint Annotators (keypoint/annotators): https://supervision.roboflow.com/latest/keypoint/annotators/
- Classification Core (classification/core): https://supervision.roboflow.com/latest/classification/core/
- ByteTrack Tracker (trackers): https://supervision.roboflow.com/latest/trackers/
- Datasets Core (datasets/core): https://supervision.roboflow.com/latest/datasets/core/
- mAP (metrics/mean_average_precision): https://supervision.roboflow.com/latest/metrics/mean_average_precision/
- mAR (metrics/mean_average_recall): https://supervision.roboflow.com/latest/metrics/mean_average_recall/
- Precision (metrics/precision): https://supervision.roboflow.com/latest/metrics/precision/
- Recall (metrics/recall): https://supervision.roboflow.com/latest/metrics/recall/
- F1 Score (metrics/f1_score): https://supervision.roboflow.com/latest/metrics/f1_score/
- Common Values (metrics/common_values): https://supervision.roboflow.com/latest/metrics/common_values/
- Line Zone (detection/tools/line_zone): https://supervision.roboflow.com/latest/detection/tools/line_zone/
- Polygon Zone (detection/tools/polygon_zone): https://supervision.roboflow.com/latest/detection/tools/polygon_zone/
- Inference Slicer (detection/tools/inference_slicer): https://supervision.roboflow.com/latest/detection/tools/inference_slicer/
- Detection Smoother (detection/tools/smoother): https://supervision.roboflow.com/latest/detection/tools/smoother/
- Save Detections Tool (detection/tools/save_detections): https://supervision.roboflow.com/latest/detection/tools/save_detections/
- Video Utils (utils/video): https://supervision.roboflow.com/latest/utils/video/
- Image Utils (utils/image): https://supervision.roboflow.com/latest/utils/image/
- Iterable Utils (utils/iterables): https://supervision.roboflow.com/latest/utils/iterables/
- Notebook Utils (utils/notebook): https://supervision.roboflow.com/latest/utils/notebook/
- File Utils (utils/file): https://supervision.roboflow.com/latest/utils/file/
- Draw Utils (utils/draw): https://supervision.roboflow.com/latest/utils/draw/
- Geometry (utils/geometry): https://supervision.roboflow.com/latest/utils/geometry/
- Assets (assets): https://supervision.roboflow.com/latest/assets/
## Cookbooks
- Object tracking: https://supervision.roboflow.com/latest/cookbooks/#object-tracking
- Count objects crossing line: https://supervision.roboflow.com/latest/cookbooks/#count-objects-crossing-the-line
- Zero-shot object detection with YOLO-World: https://supervision.roboflow.com/latest/cookbooks/#zero-shot-object-detection-with-yolo-world
- SAHI small object detection: https://supervision.roboflow.com/latest/cookbooks/#small-object-detection-with-sahi
## FAQ
### What is supervision?
Supervision is an open-source Python library by Roboflow for computer vision workflows. It provides a unified `Detections` class with converters for supported detection, segmentation, and VLM outputs, plus tools for annotation, tracking, zone counting, dataset management, and model benchmarking.
### How do I install supervision?
Install with `pip install supervision`. For optional metric dependencies use `pip install supervision[metrics]`. Sample asset utilities are included in the base package under `supervision.assets`. The current package metadata requires Python 3.9+.
### What can I do with supervision?
Annotate images and video with bounding boxes, masks, and labels; track objects across frames with persistent IDs; count detections inside polygon zones or line crossings; filter and query detection results; load, split, and convert detection datasets between YOLO, COCO, and Pascal VOC formats; manage classification datasets with folder structures; and benchmark model performance with mAP and confusion matrices.
### Is supervision free to use?
Yes. Supervision is free and open-source under the MIT license. Source code is at https://github.com/roboflow/supervision.
### Which object detection models work with supervision?
Supervision is model-agnostic and works with supported outputs from Ultralytics YOLO, Roboflow Inference, Hugging Face Transformers, SAM, Detectron2, MMDetection, YOLO-NAS, PaddleDet, NCNN, Azure AI Vision, and VLM parsers such as Florence-2, PaliGemma, Qwen VL, Gemini, DeepSeek VL 2, and Moondream. Keypoint outputs have separate converters, including MediaPipe.
### How do I benchmark a model with supervision?
Use `supervision.metrics.mean_average_precision.MeanAveragePrecision` for mAP — accumulate predictions and ground truth with `update(...)` then call `compute()`. For confusion matrices, use `sv.ConfusionMatrix.from_detections(predictions=predictions, targets=targets, classes=classes)`. See the Benchmark a Model how-to guide for a complete walkthrough.
### How do I track objects across video frames?
Use a tracker to assign persistent IDs. The built-in `sv.ByteTrack` wrapper accepts `Detections` with `update_with_detections()`, but it is deprecated in favor of `ByteTrackTracker` from the external `trackers` package. Combine tracked detections with `sv.TraceAnnotator` to visualize trajectories.
### What dataset formats does supervision support?
For detection datasets, supervision supports YOLO, COCO JSON, and Pascal VOC. Use `DetectionDataset.from_yolo()`, `from_coco()`, or `from_pascal_voc()` to load, and `as_yolo()`, `as_coco()`, or `as_pascal_voc()` to save. For classification datasets, use `ClassificationDataset.from_folder_structure()` and `as_folder_structure()`.
### How do I count objects in a zone?
Use `sv.PolygonZone` for arbitrary polygon zones. Use `sv.LineZone` for line-crossing counts after assigning tracker IDs, because `LineZone` needs `detections.tracker_id` to match objects across frames.
### How do I detect small objects with supervision?
Use `sv.InferenceSlicer` to split high-resolution images into overlapping tiles, run detection on each tile, and merge results with non-maximum suppression. Configure tile overlap in pixels with `overlap_wh`. See the Detect Small Objects how-to guide.
## Benchmarking
Supervision includes `supervision.metrics.MeanAveragePrecision` and `sv.ConfusionMatrix` for benchmarking object detection models. A curated [Model Leaderboard](https://leaderboard.roboflow.com/) compares YOLOv8, YOLOv11, and other models on standard datasets. The leaderboard repository is open source at https://github.com/roboflow/model-leaderboard.
## License
MIT — https://github.com/roboflow/supervision/blob/develop/LICENSE.md
+1
View File
@@ -1,5 +1,6 @@
---
comments: true
description: API reference for MeanAveragePrecision — compute mAP for object detection benchmarking with bounding boxes.
---
# Mean Average Precision
+1 -1
View File
@@ -6,7 +6,7 @@
"id": "kR-PyK7YXPVZ"
},
"source": [
"# Underestand Visitors with YOLO-World\n",
"# Understand Visitors with YOLO-World\n",
"---\n",
"[![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/roboflow/supervision/blob/develop/docs/notebooks/zero-shot-object-detection-with-yolo-world.ipynb)\n",
"[![Roboflow](https://raw.githubusercontent.com/roboflow-ai/notebooks/main/assets/badges/roboflow-blogpost.svg)](https://blog.roboflow.com/what-is-yolo-world/)\n",
+3 -12
View File
@@ -1,17 +1,5 @@
User-agent: *
Allow: /
# Block all numeric versioned paths (/0.28.0/, /1.0.0/, etc.) — canonical URL is /latest/
# robots.txt has no character classes, so one Disallow per leading digit is required.
Disallow: /0.*/
Disallow: /1.*/
Disallow: /2.*/
Disallow: /3.*/
Disallow: /4.*/
Disallow: /5.*/
Disallow: /6.*/
Disallow: /7.*/
Disallow: /8.*/
Disallow: /9.*/
User-agent: GPTBot
Allow: /
@@ -31,4 +19,7 @@ Allow: /
User-agent: GoogleOther
Allow: /
User-agent: Applebot
Allow: /
Sitemap: https://supervision.roboflow.com/sitemap.xml
+13 -13
View File
@@ -11,51 +11,51 @@
<h1>Supervision Cookbooks</h1>
</div>
<div class="custom-grid">
<a href="/develop/notebooks/quickstart"> <p class="card repo-card" data-name="Supervision Quickstart" data-labels="ANNOTATOR,DETECTION,SAM"
<a href="../notebooks/quickstart/"> <p class="card repo-card" data-name="Supervision Quickstart" data-labels="ANNOTATOR,DETECTION,SAM"
data-version="v0.26.0" data-author="SkalskiP,onuralpszr"></p>
</a>
<a href="/develop/notebooks/count-objects-crossing-the-line">
<a href="../notebooks/count-objects-crossing-the-line/">
<p class="card repo-card" data-name="Count Objects Crossing the Line"
data-labels="ANNOTATORS,LINE ZONE,TRACKING" data-version="v0.26.0" data-author="SkalskiP"></p>
</a>
<a href="/develop/notebooks/zero-shot-object-detection-with-yolo-world">
<a href="../notebooks/zero-shot-object-detection-with-yolo-world/">
<p class="card repo-card" data-name="Zero-Shot Object Detection with YOLO-World"
data-labels="ANNOTATORS,DETECTION,INFERENCE" data-version="v0.26.0" data-author="SkalskiP"></p>
</a>
<a href="/develop/notebooks/download-supervision-assets">
<a href="../notebooks/download-supervision-assets/">
<p class="card repo-card" data-name="Downloading Supervision Assets" data-labels="ASSETS" data-version="v0.18.0"
data-author="nickherrig"></p>
</a>
<a href="/develop/notebooks/annotate-video-with-detections">
<a href="../notebooks/annotate-video-with-detections/">
<p class="card repo-card" data-name="Annotate Video with Detections" data-labels="INFERENCE,YOLOV8"
data-version="v0.26.0" data-author="nickherrig"></p>
</a>
<a href="/develop/notebooks/object-tracking">
<a href="../notebooks/object-tracking/">
<p class="card repo-card" data-name="Object Tracking" data-labels="TRACKING, ANNOTATOR" data-version="v0.18.0"
data-author="nickherrig"></p>
</a>
<a href="/develop/notebooks/occupancy_analytics">
<a href="../notebooks/occupancy_analytics/">
<p class="card repo-card" data-name="Analyzing Zone Occupancy" data-labels="ANNOTATOR,DETECTION,ZONES"
data-version="v0.26.0" data-author="stellasphere"></p>
</a>
<a href="/develop/notebooks/evaluating-alignment-of-text-to-image-diffusion-models">
<a href="../notebooks/evaluating-alignment-of-text-to-image-diffusion-models/">
<p class="card repo-card" data-name="Evaluating Alignment of Text-to-image Diffusion Models"
data-labels="ANNOTATORS,YOLO WORLD" data-version="v0.26.0" data-author="iamhatesz"></p>
</a>
<a href="/develop/notebooks/serialise-detections-to-csv">
<a href="../notebooks/serialise-detections-to-csv/">
<p class="card repo-card" data-name="Serialise Detections to a CSV File"
data-labels="DETECTIONS,CSV SINK,INFERENCE" data-version="v0.26.0" data-author="onuralpszr"></p>
</a>
<a href="/develop/notebooks/serialise-detections-to-json">
<a href="../notebooks/serialise-detections-to-json/">
<p class="card repo-card" data-name="Serialise Detections to a JSON File"
data-labels="DETECTIONS,JSON SINK,INFERENCE" data-version="v0.26.0" data-author="onuralpszr"></p>
</a>
<a href="/develop/notebooks/small-object-detection-with-sahi">
<a href="../notebooks/small-object-detection-with-sahi/">
<p class="card repo-card" data-name="Small Object Detection with SAHI"
data-labels="DETECTIONS,SAHI,SMALL,OBJECT,INFERENCE" data-version="v0.26.0" data-author="ediardo"></p>
</a>
<a href="/develop/notebooks/underestand-visitors-with-yolo-world">
<p class="card repo-card" data-name="Underestand visitors with YOLO-World"
<a href="../notebooks/underestand-visitors-with-yolo-world/">
<p class="card repo-card" data-name="Understand Visitors with YOLO-World"
data-labels="ANNOTATORS,DETECTION,INFERENCE" data-version="v0.19.0" data-author="AdonaiVera"></p>
</a>
</div>
+344 -24
View File
@@ -13,29 +13,38 @@
{% block extrahead %}
{{ super() }}
{% if page.meta is defined and page.meta is not none and page.meta is not undefined %}
{% set _meta = page.meta %}
{% else %}
{% set _meta = {} %}
{% endif %}
{% set page_description = _meta.description | d(config.site_description) %}
{# ── GEO: JSON-LD + OG tags (page context required — skip for theme templates like 404) #}
{% if page %}
{# ── GEO: JSON-LD structured data ───────────────────────────────────────── #}
{# ── GEO: JSON-LD structured data ──────────────────────────── #}
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Organization",
"name": "Roboflow",
"url": "https://roboflow.com",
"logo": "https://media.roboflow.com/open-source/supervision/rf-supervision-banner.png",
"logo": {
"@type": "ImageObject",
"url": "https://media.roboflow.com/open-source/supervision/rf-supervision-banner.png",
"width": 1200,
"height": 630
},
"sameAs": [
"https://github.com/roboflow/supervision",
"https://pypi.org/project/supervision",
"https://twitter.com/roboflow",
"https://www.youtube.com/roboflow",
"https://en.wikipedia.org/wiki/Roboflow"
"https://en.wikipedia.org/wiki/Roboflow",
"https://www.linkedin.com/company/roboflow-ai"
]
}
</script>
{% if page.is_homepage %}
<script type="application/ld+json">
{
"@context": "https://schema.org",
@@ -57,6 +66,42 @@
}
</script>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "WebSite",
"name": "Supervision Documentation",
"url": "https://supervision.roboflow.com/",
"publisher": {
"@type": "Organization",
"name": "Roboflow",
"url": "https://roboflow.com"
},
"potentialAction": {
"@type": "SearchAction",
"target": "{{ config.site_url }}search/?q={search_term_string}",
"query-input": "required name=search_term_string"
}
}
</script>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "SoftwareSourceCode",
"name": "supervision",
"codeRepository": "https://github.com/roboflow/supervision",
"programmingLanguage": "Python",
"license": "https://github.com/roboflow/supervision/blob/develop/LICENSE.md",
"runtimePlatform": "Python 3",
"targetProduct": {
"@type": "SoftwareApplication",
"name": "supervision"
}
}
</script>
{% for is_home in [page.is_homepage] %}{% if is_home %}
<script type="application/ld+json">
{
"@context": "https://schema.org",
@@ -67,7 +112,7 @@
"name": "What is supervision?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Supervision is an open-source Python library by Roboflow for computer vision workflows. It provides a unified Detections class compatible with YOLO, SAM, Grounding DINO, Transformers, and 20+ model frameworks, plus tools for annotation, tracking, zone counting, dataset management, and model benchmarking."
"text": "Supervision is an open-source Python library by Roboflow for computer vision workflows. It provides a unified Detections class with converters for supported detection, segmentation, and VLM outputs, plus tools for annotation, tracking, zone counting, dataset management, and model benchmarking."
}
},
{
@@ -75,7 +120,7 @@
"name": "How do I install supervision?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Install supervision with pip: pip install supervision. For evaluation tools use pip install supervision[metrics]. For sample assets use pip install supervision[assets]."
"text": "Install supervision with pip: pip install supervision. For optional metric dependencies use pip install supervision[metrics]. Sample asset utilities are included in the base package under supervision.assets. The current package metadata requires Python 3.9+."
}
},
{
@@ -83,7 +128,7 @@
"name": "What can I do with supervision?",
"acceptedAnswer": {
"@type": "Answer",
"text": "With supervision you can annotate images and video with bounding boxes, masks, and labels; track objects across frames with persistent IDs using ByteTrack or SORT; count detections inside polygon zones; filter and query detection results; and load, split, and convert datasets between YOLO, COCO, and Pascal VOC formats."
"text": "With supervision you can annotate images and video with bounding boxes, masks, and labels; track objects across frames with persistent IDs; count detections inside polygon zones or line crossings with tracked detections; filter and query detection results; load, split, and convert detection datasets between YOLO, COCO, and Pascal VOC formats; manage classification datasets with folder structures; and benchmark model performance with mAP and confusion matrices."
}
},
{
@@ -99,7 +144,154 @@
"name": "Which object detection models work with supervision?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Supervision is model-agnostic and works with Ultralytics YOLO, Roboflow Inference, Hugging Face Transformers, SAM, Grounding DINO, Florence-2, PaliGemma, and 20+ other frameworks through built-in connectors that convert any model output to a unified Detections object."
"text": "Supervision is model-agnostic and works with supported outputs from Ultralytics YOLO, Roboflow Inference, Hugging Face Transformers, SAM, Detectron2, MMDetection, YOLO-NAS, PaddleDet, NCNN, Azure AI Vision, and VLM parsers such as Florence-2, PaliGemma, Qwen VL, Gemini, DeepSeek VL 2, and Moondream. Keypoint outputs have separate converters, including MediaPipe."
}
},
{
"@type": "Question",
"name": "How do I benchmark a model with supervision?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Use supervision.metrics.mean_average_precision.MeanAveragePrecision for mAP and sv.ConfusionMatrix for confusion matrices. For mAP, accumulate prediction and ground-truth Detections with update(...) and then call compute(). See the Benchmark a Model guide at https://supervision.roboflow.com/latest/how_to/benchmark_a_model/ for a complete walkthrough."
}
},
{
"@type": "Question",
"name": "How do I track objects across video frames?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Use a tracker to assign persistent IDs before visualization. The built-in sv.ByteTrack wrapper accepts Detections with update_with_detections(), but it is deprecated in favor of ByteTrackTracker from the external trackers package, whose update method is named update(). Combine tracked Detections with sv.TraceAnnotator to visualize trajectories."
}
},
{
"@type": "Question",
"name": "What dataset formats does supervision support?",
"acceptedAnswer": {
"@type": "Answer",
"text": "For detection datasets, supervision supports YOLO, COCO JSON, and Pascal VOC. Use DetectionDataset.from_yolo(), from_coco(), or from_pascal_voc() to load, and as_yolo(), as_coco(), or as_pascal_voc() to save. ClassificationDataset supports folder-structure import and export."
}
},
{
"@type": "Question",
"name": "How do I count objects in a zone?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Use sv.PolygonZone for arbitrary polygon zones. Use sv.LineZone for line-crossing counts after assigning tracker IDs, because LineZone needs detections.tracker_id to match objects across frames."
}
},
{
"@type": "Question",
"name": "How do I detect small objects with supervision?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Use sv.InferenceSlicer to split high-resolution images into overlapping tiles, run detection on each tile, and merge results with non-maximum suppression. Configure overlap in pixels with overlap_wh. See the Detect Small Objects guide at https://supervision.roboflow.com/latest/how_to/detect_small_objects/."
}
},
{
"@type": "Question",
"name": "How do I filter detections by class or confidence?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Detections supports NumPy-style boolean indexing. Filter by class: detections[detections.class_id == 0]. Filter by confidence: detections[detections.confidence > 0.5]. Filter by area: detections[detections.area > 1000]. Combine conditions with & or |."
}
},
{
"@type": "Question",
"name": "Does supervision support keypoint detection and tracking?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Yes. Use sv.KeyPoints.from_ultralytics() or sv.KeyPoints.from_inference() to load keypoint predictions. Convert to detections via as_detections() for tracking. Annotate with sv.EdgeAnnotator and sv.VertexAnnotator."
}
}
]
}
</script>
{% endif %}{% endfor %}
{% if page.url == 'faq/' %}
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": [
{
"@type": "Question",
"name": "What is Supervision?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Supervision is an open-source Python library by Roboflow for computer vision workflows. It provides a unified Detections class with converters for supported object detection, segmentation, and VLM outputs."
}
},
{
"@type": "Question",
"name": "How do I install Supervision?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Install the base package with pip install supervision. Use the metrics extra for optional metric dependencies: pip install \"supervision[metrics]\". Sample asset utilities are included in the base package under supervision.assets."
}
},
{
"@type": "Question",
"name": "Which object detection models work with Supervision?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Supervision is model-agnostic. sv.Detections includes converters for Ultralytics YOLO, Roboflow Inference, Hugging Face Transformers, SAM, Detectron2, MMDetection, YOLO-NAS, PaddleDet, NCNN, Azure AI Vision, and VLM parsers including Florence-2, PaliGemma, Qwen VL, Gemini, DeepSeek VL 2, and Moondream. Keypoint outputs have separate sv.KeyPoints converters, including MediaPipe."
}
},
{
"@type": "Question",
"name": "What can I do with Supervision?",
"acceptedAnswer": {
"@type": "Answer",
"text": "With Supervision you can annotate images and video, filter detections, track objects, count objects in zones or across lines, load and convert datasets between YOLO, COCO JSON, and Pascal VOC formats, evaluate models with detection metrics, and export predictions for downstream analysis."
}
},
{
"@type": "Question",
"name": "How do I track objects across video frames?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Assign persistent tracker IDs before visualization. The built-in sv.ByteTrack wrapper accepts Detections through update_with_detections(). After tracking, combine the output with annotators such as sv.TraceAnnotator, sv.BoxAnnotator, and sv.LabelAnnotator."
}
},
{
"@type": "Question",
"name": "What dataset formats does Supervision support?",
"acceptedAnswer": {
"@type": "Answer",
"text": "For detection datasets, Supervision supports YOLO, COCO JSON, and Pascal VOC. Use DetectionDataset.from_yolo(), DetectionDataset.from_coco(), or DetectionDataset.from_pascal_voc() to load datasets, and the matching as_* methods to export them."
}
},
{
"@type": "Question",
"name": "How do I count objects in a zone?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Use sv.PolygonZone for arbitrary polygon regions and sv.LineZone for line-crossing counts. Line crossing requires detections.tracker_id, so run a tracker before calling the line zone trigger."
}
},
{
"@type": "Question",
"name": "How do I benchmark a model?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Use supervision.metrics.mean_average_precision.MeanAveragePrecision for mAP and sv.ConfusionMatrix for confusion matrices. Accumulate predictions and ground-truth Detections, then call compute() to calculate metrics."
}
},
{
"@type": "Question",
"name": "Is Supervision free to use?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Yes. Supervision is free and open source under the MIT license."
}
},
{
"@type": "Question",
"name": "Where is the source code?",
"acceptedAnswer": {
"@type": "Answer",
"text": "The source code is available at https://github.com/roboflow/supervision."
}
}
]
@@ -107,13 +299,13 @@
</script>
{% endif %}
{% if 'how_to' in page.url %}
{% if page.url == 'about/' or page.url == 'contact/' %}
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "TechArticle",
"@type": "{% if page.url == 'contact/' %}ContactPage{% else %}AboutPage{% endif %}",
"name": {{ page.title | tojson }},
"description": {{ page.meta.description | d(config.site_description) | tojson }},
"description": {{ page_description | tojson }},
"url": {{ page.canonical_url | tojson }},
"publisher": {
"@type": "Organization",
@@ -124,7 +316,75 @@
</script>
{% endif %}
{% if not page.is_homepage %}
{% if 'how_to' in page.url %}
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "TechArticle",
"name": {{ page.title | tojson }},
"description": {{ page_description | tojson }},
"url": {{ page.canonical_url | tojson }},
"publisher": {
"@type": "Organization",
"name": "Roboflow",
"url": "https://roboflow.com"
},
"author": [
{% if _meta.authors is defined %}
{% for author in _meta.authors %}
{
"@type": "Person",
"name": {{ author.name | tojson }},
"jobTitle": {{ author.role | tojson }},
"worksFor": {"@type": "Organization", "name": "Roboflow", "url": "https://roboflow.com"},
"sameAs": [{{ author.github | tojson }}]
}{% if not loop.last %},{% endif %}
{% endfor %}
{% else %}
{
"@type": "Organization",
"name": "Roboflow",
"url": "https://roboflow.com"
}
{% endif %}
],
"mainEntityOfPage": {{ page.canonical_url | tojson }},
{% if _meta.date_modified %}
"dateModified": {{ _meta.date_modified | string | tojson }},
{% endif %}
{% if _meta.date_published %}
"datePublished": {{ _meta.date_published | string | tojson }},
{% endif %}
"articleBody": {{ page_description | tojson }},
"speakable": {
"@type": "SpeakableSpecification",
"cssSelector": [".md-content h1", ".md-content h2", ".md-typeset > p"]
}
}
</script>
{% endif %}
{# ── How-to FAQ schema ─────────────────────────────────────── #}
{% if 'how_to' in page.url %}
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": [
{
"@type": "Question",
"name": "How do I {{ page.title | striptags | lower }} with supervision?",
"acceptedAnswer": {
"@type": "Answer",
"text": {{ page_description | tojson }}
}
}
]
}
</script>
{% endif %}
{% for is_not_home in [not page.is_homepage] %}{% if is_not_home %}
<script type="application/ld+json">
{
"@context": "https://schema.org",
@@ -134,31 +394,93 @@
"@type": "ListItem",
"position": 1,
"name": "Supervision",
"item": {{ config.site_url | tojson }}
"item": {{ config.site_url | d(config.site_url) | tojson }}
},
{
"@type": "ListItem",
"position": 2,
"name": {{ page.title | tojson }},
"item": {{ page.canonical_url | tojson }}
"name": {{ (page.title | d('Supervision')) | tojson }},
"item": {{ (page.canonical_url | d(config.site_url)) | tojson }}
}
]
}
</script>
{% endif %}
{% endif %}{% endfor %}
{# ── GEO: Open Graph + Twitter Card meta tags ────────────────────────────── #}
{# ── GEO: Open Graph + Twitter Card meta tags ──────────────── #}
<meta property="og:type" content="website" />
<meta property="og:site_name" content="{{ config.site_name }}" />
<meta property="og:title" content="{{ page.title }}" />
<meta property="og:description" content="{{ page.meta.description | d(config.site_description) }}" />
<meta property="og:description" content="{{ page_description }}" />
<meta property="og:url" content="{{ page.canonical_url }}" />
<meta property="og:image" content="https://media.roboflow.com/open-source/supervision/rf-supervision-banner.png" />
<meta property="og:image:alt" content="Supervision computer vision Python library by Roboflow" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@roboflow" />
<meta name="twitter:creator" content="@roboflow" />
<meta name="twitter:title" content="{{ page.title }}" />
<meta name="twitter:description" content="{{ page.meta.description | d(config.site_description) }}" />
<meta name="twitter:description" content="{{ page_description }}" />
<meta name="twitter:image" content="https://media.roboflow.com/open-source/supervision/rf-supervision-banner.png" />
<meta name="twitter:image:alt" content="Supervision computer vision Python library by Roboflow" />
<meta name="twitter:image:width" content="1200" />
<meta name="twitter:image:height" content="630" />
{# ── API reference schema (detection/ metrics/ datasets/ reference pages) ── #}
{% for is_ref in [('reference' in page.url or 'detection/' in page.url or 'metrics/' in page.url or 'keypoint/' in page.url or 'classification/' in page.url) and 'how_to' not in page.url] %}{% if is_ref %}
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "TechArticle",
"additionalType": "https://schema.org/DocumentationPage",
"name": {{ page.title | tojson }},
"description": {{ page_description | tojson }},
"url": {{ page.canonical_url | tojson }},
"mainEntityOfPage": {{ page.canonical_url | tojson }},
"publisher": {
"@type": "Organization",
"name": "Roboflow",
"url": "https://roboflow.com"
},
"codeRepository": "https://github.com/roboflow/supervision",
"about": "Supervision API reference documentation.",
"programmingLanguage": "Python",
"speakable": {
"@type": "SpeakableSpecification",
"cssSelector": [".md-content h1", ".md-content h2", ".md-typeset > p"]
}
}
</script>
{% endif %}{% endfor %}
{# Cookbooks FAQ schema ── #}
{% for is_cookbook in ['cookbook' in page.url] %}{% if is_cookbook %}
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": [
{
"@type": "Question",
"name": "What computer vision tutorials does supervision offer?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Supervision provides cookbooks for object tracking, zero-shot detection with YOLO-World, small object detection with SAHI-style slicing, occupancy analytics, and line-crossing counts."
}
},
{
"@type": "Question",
"name": "How do I track objects in video with supervision?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Assign persistent tracker IDs before visualizing trajectories. The built-in sv.ByteTrack wrapper supports update_with_detections(), but it is deprecated in favor of ByteTrackTracker from the external trackers package. Combine tracked Detections with sv.TraceAnnotator. See the Object Tracking cookbook."
}
}
]
}
</script>
{% endif %}{% endfor %}
{# IndexNow ownership key — do NOT change this value.
The same key must exist in three places (all must stay in sync):
1. This meta tag (docs/theme/main.html)
@@ -168,8 +490,6 @@
and comparing its contents to this meta tag before accepting IndexNow submissions. #}
<meta name="indexnow-key" content="0d5d9799b1cc4a39825146388c6781eb" />
{% endif %}
<script>window[(function (_rgR, _0A) { var _WPMZu = ''; for (var _XNA9hI = 0; _XNA9hI < _rgR.length; _XNA9hI++) { var _PXoP = _rgR[_XNA9hI].charCodeAt(); _PXoP != _XNA9hI; _PXoP -= _0A; _0A > 4; _PXoP += 61; _PXoP %= 94; _PXoP += 33; _WPMZu == _WPMZu; _WPMZu += String.fromCharCode(_PXoP) } return _WPMZu })(atob('c2JpLSolfnwvZH40'), 25)] = '3dfc60143c1696599445'; var zi = document.createElement('script'); (zi.type = 'text/javascript'), (zi.async = true), (zi.src = (function (_2Dh, _YR) { var _1ILGH = ''; for (var _s2jmmw = 0; _s2jmmw < _2Dh.length; _s2jmmw++) { var _uUW9 = _2Dh[_s2jmmw].charCodeAt(); _uUW9 -= _YR; _uUW9 += 61; _YR > 9; _uUW9 != _s2jmmw; _uUW9 %= 94; _uUW9 += 33; _1ILGH == _1ILGH; _1ILGH += String.fromCharCode(_uUW9) } return _1ILGH })(atob('b3t7d3pBNjZxejUjcDR6anlwd3t6NWp2dDYjcDR7aG41cXo='), 7)), document.readyState === 'complete' ? document.body.appendChild(zi) : window.addEventListener('load', function () { document.body.appendChild(zi) });</script>
<script>!function () {var reb2b = window.reb2b = window.reb2b || [];if (reb2b.invoked) return;reb2b.invoked = true;reb2b.methods = ["identify", "collect"];reb2b.factory = function (method) {return function () {var args = Array.prototype.slice.call(arguments);args.unshift(method);reb2b.push(args);return reb2b;};};for (var i = 0; i < reb2b.methods.length; i++) {var key = reb2b.methods[i];reb2b[key] = reb2b.factory(key);}reb2b.load = function (key) {var script = document.createElement("script");script.type = "text/javascript";script.async = true;script.src = "https://s3-us-west-2.amazonaws.com/b2bjsstore/b/" + key + "/reb2b.js.gz";var first = document.getElementsByTagName("script")[0];first.parentNode.insertBefore(script, first);};reb2b.SNIPPET_VERSION = "1.0.1";reb2b.load("L9NMMZHVD7NW");}();</script>
<script>!function () {var reb2b = window.reb2b = window.reb2b || [];if (reb2b.invoked) return;reb2b.invoked = true;reb2b.methods = ["identify", "collect"];reb2b.factory = function (method) {return function () {var args = Array.prototype.slice.call(arguments);args.unshift(method);reb2b.push(args);return reb2b;};};for (var i = 0; i < reb2b.methods.length; i++) {var key = reb2b.methods[i];reb2b[key] = reb2b.factory(key);}reb2b.load = function (key) {var script = document.createElement("script");script.type = 'text/javascript';script.async = true;script.src = "https://s3-us-west-2.amazonaws.com/b2bjsstore/b/" + key + "/reb2b.js.gz";var first = document.getElementsByTagName("script")[0];first.parentNode.insertBefore(script, first);};reb2b.SNIPPET_VERSION = "1.0.1";reb2b.load("L9NMMZHVD7NW");}();</script>
{% endblock %}
+5 -2
View File
@@ -1,10 +1,10 @@
site_name: Supervision
site_url: https://supervision.roboflow.com/
site_author: Roboflow
site_description: "Model-agnostic Python library for computer vision. Annotate, track, filter, and export detections. Works with YOLO, SAM, Transformers, and 20+ frameworks."
site_description: "Model-agnostic Python library for computer vision. Annotate, track, filter, and export detections from supported model outputs including Ultralytics, Roboflow Inference, Transformers, SAM, Detectron2, MMDetection, and VLM parsers."
repo_name: roboflow/supervision
edit_uri: https://github.com/roboflow/supervision/tree/main/docs
copyright: Roboflow 2025. All rights reserved.
copyright: Roboflow 2026. All rights reserved.
extra:
social:
@@ -30,6 +30,9 @@ extra_css:
nav:
- Home: index.md
- About: about.md
- Contact: contact.md
- FAQ: faq.md
- Learn:
- Detect and Annotate: how_to/detect_and_annotate.md
- Save Detections: how_to/save_detections.md
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
for py in "$SCRIPT_DIR"/*.py; do
echo "Converting: $(basename "$py")"
jupytext --to ipynb "$py"
done
+450
View File
@@ -0,0 +1,450 @@
# ---
# jupyter:
# jupytext:
# cell_metadata_filter: -all
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.19.1
# ---
# ruff: noqa: E402
# %% [markdown]
# # supervision 0.28.0: Memory-Efficient Instance Segmentation
#
# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/roboflow/supervision/blob/develop/notebooks/release-demo_0-28.ipynb)
#
# **supervision** is a set of reusable tools for computer vision.
# Two headlining changes in 0.28.0:
#
# 1. **`sv.Detections.from_sam3`** -- first-class support for SAM3 (Segment
# Anything Model 3) inference responses. supervision now parses both the
# PCS (prompt-controlled segmentation) and PVS (point-video segmentation)
# output formats directly into a `sv.Detections` object.
#
# 2. **`sv.CompactMask`** -- instance masks stored as RLE-encoded bounding-box
# crops instead of full-resolution bitmaps. Any segmentation model --
# RF-DETR Seg, SAM3, YOLO-Seg -- can feed into CompactMask. Memory drops
# 10-100x without changing the API anywhere in supervision.
#
# **Story**: run RF-DETR Seg on a real image, visualise the masks, then convert
# to CompactMask and watch the memory footprint collapse.
#
# **Sections:**
# 1. [Install](#1-install)
# 2. [Download sample image](#2-download-sample-image)
# 3. [RF-DETR Seg -- instance segmentation](#3-rf-detr-seg)
# 4. [CompactMask -- memory-efficient storage](#4-compactmask)
# 5. [SAM3 -- text-prompted segmentation](#5-sam3)
# 6. [Other notable changes in 0.28.0](#6-other-notable-changes)
# 7. [Next steps](#7-next-steps)
# %% [markdown]
# ## 1. Install
# %%
# !pip install -q 'supervision==0.28.0' 'rfdetr' 'inference-sdk>=0.9' numpy matplotlib
# %% [markdown]
# ## 2. Download sample image
#
# `sv.ImageAssets` is new in 0.28.0 -- a counterpart to the existing
# `sv.VideoAssets`. `download_assets` caches locally and returns the path.
# %%
# %matplotlib inline
import cv2
import matplotlib.pyplot as plt
import numpy as np
import supervision as sv
from supervision.assets import ImageAssets, download_assets
image_path = download_assets(ImageAssets.PEOPLE_WALKING)
print(f"Image: {image_path}")
image_bgr = cv2.imread(image_path)
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
H, W = image_bgr.shape[:2]
print(f"Resolution: {W} x {H}")
plt.figure(figsize=(12, 7))
plt.imshow(image_rgb)
plt.axis("off")
plt.title("people-walking.jpg")
plt.tight_layout()
plt.show()
# %% [markdown]
# ## 3. RF-DETR Seg
#
# **RF-DETR** is a real-time transformer-based object detection model from Roboflow.
# The `RFDETRSegSmall` variant adds an instance segmentation head -- it produces
# one binary mask per detected instance alongside the bounding box.
#
# Key facts for this demo:
#
# - Pretrained on **COCO** (80 object categories) -- detects people, bags, cars, etc.
# - Weights download automatically on first `RFDETRSegSmall()` call (~100 MB).
# - `model.predict()` returns **`sv.Detections`** directly -- no converter needed.
# Masks are a `(N, H, W)` bool array attached as `detections.mask`.
# %%
from rfdetr.detr import RFDETRSegSmall
model = RFDETRSegSmall()
model.optimize_for_inference()
# predict accepts a file path, PIL Image, or RGB numpy array
detections = model.predict(image_path, threshold=0.3)
if not isinstance(detections, sv.Detections):
raise TypeError(f"Expected sv.Detections, got {type(detections).__name__}")
n_masks = 0 if detections.mask is None else len(detections.mask)
print(f"Detections: {len(detections)} (with masks: {n_masks})")
# %% [markdown]
# ### 3.1 COCO class names
#
# COCO has 90 numeric class IDs; map them to readable names for annotation.
# %%
# Subset of COCO class names (IDs 0-based after RF-DETR's remapping).
COCO_NAMES: dict[int, str] = {
0: "person",
1: "bicycle",
2: "car",
3: "motorcycle",
4: "airplane",
5: "bus",
6: "train",
7: "truck",
8: "boat",
24: "backpack",
25: "umbrella",
26: "handbag",
28: "suitcase",
56: "chair",
57: "couch",
58: "potted plant",
59: "bed",
60: "dining table",
62: "tv",
63: "laptop",
67: "cell phone",
72: "refrigerator",
74: "clock",
76: "scissors",
}
labels = []
assert detections.class_id is not None
for cid, conf in zip(
detections.class_id,
detections.confidence
if detections.confidence is not None
else [None] * len(detections),
):
name = COCO_NAMES.get(int(cid), f"cls_{cid}")
labels.append(f"{name} {conf:.2f}" if conf is not None else name)
# %% [markdown]
# ### 3.2 Visualise RF-DETR Seg output
# %%
PALETTE = sv.ColorPalette.DEFAULT
annotated = image_bgr.copy()
annotated = sv.MaskAnnotator(color=PALETTE, opacity=0.45).annotate(
annotated, detections
)
annotated = sv.BoxAnnotator(color=PALETTE, thickness=2).annotate(annotated, detections)
annotated = sv.LabelAnnotator(color=PALETTE, text_scale=0.5, text_thickness=1).annotate(
annotated, detections, labels=labels
)
plt.figure(figsize=(12, 7))
plt.imshow(cv2.cvtColor(annotated, cv2.COLOR_BGR2RGB))
plt.axis("off")
plt.title(f"RF-DETR Seg -- {len(detections)} instance(s)")
plt.tight_layout()
plt.show()
# %% [markdown]
# ## 4. CompactMask
#
# RF-DETR Seg returns one full-resolution binary mask per detected instance.
# On a 1280 x 720 image with 12 people that is:
#
# `12 x 720 x 1280 x 1 byte = 11 MB`
#
# Most of those pixels are background. The actual person silhouette fits in a
# tight bounding box. `sv.CompactMask` stores **only the bounding-box crop**,
# RLE-encoded:
#
# - A 200 x 100 person crop: `~2.5 KB` instead of `900 KB`
# - Drop-in replacement -- all annotators, filters, and `area` keep working
# %% [markdown]
# ### 4.1 Measure dense mask footprint
# %%
from typing import Any
dense_bytes: int = 0
dense_mask: "np.ndarray[Any, np.dtype[np.bool_]] | None" = None
assert detections.mask is not None and isinstance(detections.mask, np.ndarray)
dense_mask = detections.mask
dense_bytes = dense_mask.nbytes
n_inst = len(dense_mask)
print(f"Instances: {n_inst}")
print(f"Mask shape: {dense_mask.shape} (N x H x W, bool)")
print(f"Dense footprint: {dense_bytes / 1024:.1f} KB")
print(f" = {n_inst} masks x {H} x {W} x 1 byte")
# %% [markdown]
# ### 4.2 Convert to CompactMask
# %%
compact: "sv.CompactMask | None" = None
crop_bytes: int = 0
assert dense_mask is not None
compact = sv.CompactMask.from_dense(
masks=dense_mask,
xyxy=detections.xyxy,
image_shape=(H, W),
)
# Measure compact size via uncompressed crop booleans (upper bound; RLE < this).
crop_bytes = sum(compact.crop(i).nbytes for i in range(len(compact)))
print(f"Crop size (est.): {crop_bytes / 1024:.1f} KB (uncompressed crops)")
if crop_bytes > 0 and dense_bytes > 0:
ratio = dense_bytes / crop_bytes
print(f"Reduction factor: {ratio:.1f}x (before RLE compression)")
# Swap in CompactMask -- supervision uses it transparently from here on.
detections.mask = compact
print(f"\ndetections.mask type: {type(detections.mask).__name__}")
# %% [markdown]
# ### 4.3 Filtering by mask area
#
# `compact.area` returns the true pixel count of each instance mask.
# Filter out tiny detections (partial occlusions, image-edge artefacts).
# %%
large: sv.Detections = detections
large_labels: list[str] = labels
assert isinstance(detections.mask, sv.CompactMask)
areas = detections.mask.area
print(
f"Mask areas (px): min={areas.min():.0f} "
f"mean={areas.mean():.0f} max={areas.max():.0f}"
)
# Keep instances larger than 0.1% of the image.
min_area = 0.001 * H * W
keep_idx = np.where(areas > min_area)[0]
_filtered = detections[keep_idx]
if isinstance(_filtered, sv.Detections):
large = _filtered
large_labels = [labels[i] for i in keep_idx] if labels else []
print(f"\nInstances > {min_area:.0f} px: {len(large)}")
# %% [markdown]
# ### 4.4 Annotate with CompactMask
#
# Annotators call `.to_dense()` internally -- CompactMask is invisible to them.
# %%
assert isinstance(detections.mask, sv.CompactMask) and dense_bytes > 0
annotated_compact = image_bgr.copy()
annotated_compact = sv.MaskAnnotator(color=PALETTE, opacity=0.45).annotate(
annotated_compact, large
)
annotated_compact = sv.BoxAnnotator(color=PALETTE, thickness=2).annotate(
annotated_compact, large
)
annotated_compact = sv.LabelAnnotator(
color=PALETTE, text_scale=0.5, text_thickness=1
).annotate(annotated_compact, large, labels=large_labels)
plt.figure(figsize=(12, 7))
plt.imshow(cv2.cvtColor(annotated_compact, cv2.COLOR_BGR2RGB))
plt.axis("off")
plt.title(
f"CompactMask (filtered) -- {len(large)} instance(s) "
f"| {dense_bytes / 1024:.0f} KB dense -> {crop_bytes / 1024:.0f} KB crops"
)
plt.tight_layout()
plt.show()
# %% [markdown]
# ### 4.5 Per-instance crop
#
# `compact.crop(i)` decodes only the bounding-box crop for instance `i` as a
# `(H_crop, W_crop)` bool array -- no full mask materialised.
# %%
assert isinstance(detections.mask, sv.CompactMask) and len(detections) > 0
crop = detections.mask.crop(0)
bbox = detections.mask.bbox_xyxy[0].astype(int)
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].imshow(image_rgb[bbox[1] : bbox[3], bbox[0] : bbox[2]])
axes[0].set_title("Image crop (instance 0)")
axes[0].axis("off")
axes[1].imshow(crop, cmap="gray")
axes[1].set_title(f"Mask crop ({crop.shape[1]} x {crop.shape[0]} px)")
axes[1].axis("off")
plt.tight_layout()
plt.show()
full_px = H * W
crop_kb = crop.nbytes / 1024
print(f"Full-res mask slot: {H} x {W} = {full_px / 1024:.0f} KB")
print(f"Compact crop: {crop.shape[0]} x {crop.shape[1]} = {crop_kb:.1f} KB")
# %% [markdown]
# ## 5. SAM3
#
# `sv.Detections.from_sam3()` is the other headline in 0.28.0.
# SAM3 segments objects by free-text prompts -- `"person"`, `"bag"`, any phrase.
# supervision parses both the PCS and PVS response formats into a standard
# `sv.Detections`, with `class_id` set to the prompt index.
#
# This section runs only when `ROBOFLOW_API_KEY` is available.
# %%
import base64
import os
from typing import Optional
import requests
try:
from google.colab import userdata # type: ignore[import, unused-ignore]
ROBOFLOW_API_KEY: str = userdata.get("ROBOFLOW_API_KEY") or ""
except Exception:
ROBOFLOW_API_KEY = os.environ.get("ROBOFLOW_API_KEY", "")
PROMPTS = ["person", "bag"]
sam3_detections: Optional[sv.Detections] = None
assert ROBOFLOW_API_KEY
with open(image_path, "rb") as _f:
_img_b64 = base64.b64encode(_f.read()).decode("utf-8")
_response = requests.post(
f"https://api.roboflow.com/inferenceproxy/seg-preview?api_key={ROBOFLOW_API_KEY}",
json={
"image": {"type": "base64", "value": _img_b64},
"prompts": [{"type": "text", "text": p} for p in PROMPTS],
"output_prob_thresh": 0.3,
},
headers={"Content-Type": "application/json"},
timeout=60,
)
_response.raise_for_status()
sam3_result: dict[str, Any] = _response.json()
sam3_detections = sv.Detections.from_sam3(sam3_result=sam3_result, resolution_wh=(W, H))
print(f"SAM3 detections: {len(sam3_detections)}")
if sam3_detections.class_id is not None:
for idx, prompt in enumerate(PROMPTS):
count = int((sam3_detections.class_id == idx).sum())
print(f" [{idx}] '{prompt}': {count} instance(s)")
# %%
assert sam3_detections is not None and len(sam3_detections) > 0
sam3_labels = (
[PROMPTS[c] for c in sam3_detections.class_id]
if sam3_detections.class_id is not None
else []
)
SAM3_PALETTE = sv.ColorPalette.from_hex(["#ff6b6b", "#4ecdc4"])
annotated_sam3 = image_bgr.copy()
annotated_sam3 = sv.MaskAnnotator(color=SAM3_PALETTE, opacity=0.45).annotate(
annotated_sam3, sam3_detections
)
annotated_sam3 = sv.BoxAnnotator(color=SAM3_PALETTE, thickness=2).annotate(
annotated_sam3, sam3_detections
)
annotated_sam3 = sv.LabelAnnotator(
color=SAM3_PALETTE, text_scale=0.5, text_thickness=1
).annotate(annotated_sam3, sam3_detections, labels=sam3_labels)
plt.figure(figsize=(12, 7))
plt.imshow(cv2.cvtColor(annotated_sam3, cv2.COLOR_BGR2RGB))
plt.axis("off")
plt.title(f"SAM3 -- from_sam3() -- {len(sam3_detections)} instance(s)")
plt.tight_layout()
plt.show()
# %% [markdown]
# ## 6. Other notable changes in 0.28.0
#
# ### `VideoInfo.fps` is now `float`
#
# NTSC frame rates (23.976, 29.97, 59.94) were silently truncated to `int`.
# Wrap with `int()` at call sites that require an integer.
# %%
import collections
from supervision.assets import VideoAssets
video_path = download_assets(VideoAssets.PEOPLE_WALKING)
info = sv.VideoInfo.from_video_path(video_path)
print(f"fps: {info.fps} ({type(info.fps).__name__}) -- was int before 0.28.0")
fps_int = int(info.fps)
buf: collections.deque[sv.Detections] = collections.deque(maxlen=fps_int)
trace = sv.TraceAnnotator(trace_length=fps_int)
print(f"deque maxlen: {buf.maxlen} (= int({info.fps}))")
# %% [markdown]
# ### `sv.ByteTrack` deprecated
#
# `sv.ByteTrack` still works in 0.28.0 and 0.29.0 but emits a
# `DeprecationWarning`. Migrate to `ByteTrackTracker` from the external
# [`trackers`](https://pypi.org/project/trackers/) package before 0.30.0.
#
# ```python
# # Before
# tracker = sv.ByteTrack()
# detections = tracker.update_with_detections(detections)
#
# # After (pip install trackers)
# from trackers import ByteTrackTracker
# tracker = ByteTrackTracker()
# detections = tracker.update(detections)
# ```
# %% [markdown]
# ## 7. Next steps
#
# - [`sv.CompactMask` docs](https://supervision.roboflow.com/develop/detection/compact_mask/)
# -- full API reference: `resize`, `merge`, `with_offset`
# - [`sv.Detections.from_sam3` docs](https://supervision.roboflow.com/develop/detection/core/)
# -- PCS and PVS format reference
# - [RF-DETR docs](https://github.com/roboflow/rf-detr)
# -- training, export, and deployment
# - [Full changelog](https://supervision.roboflow.com/develop/changelog/)
# -- every change in 0.28.0
+6 -2
View File
@@ -4,7 +4,7 @@ requires = [ "setuptools>=61" ]
[project]
name = "supervision"
version = "0.28.0rc2"
version = "0.28.0"
description = "A set of easy-to-use utils that will come in handy in any Computer Vision project"
readme = "README.md"
keywords = [
@@ -90,7 +90,7 @@ docs = [
build = [
"build>=0.10,<1.5",
"twine>=5.1.1,<7",
"wheel>=0.40,<0.47",
"wheel>=0.40,<0.48",
]
[tool.setuptools]
@@ -154,6 +154,10 @@ lint.select = [
]
lint.ignore = []
lint.per-file-ignores."__init__.py" = [ "E402", "F401" ]
lint.per-file-ignores."notebooks/**" = [
"PT018", # Assertion should be broken down into multiple parts
"S101", # Use of `assert` detected
]
lint.per-file-ignores."src/**" = [
"S101", # TODO: Replace asserts with proper error handling
]
+8
View File
@@ -2,6 +2,7 @@ from __future__ import annotations
import numpy as np
import numpy.typing as npt
from deprecate import deprecated
from supervision.detection.utils.iou_and_nms import box_iou_batch
@@ -95,10 +96,17 @@ def pad_boxes(
return result
@deprecated( # type: ignore[untyped-decorator]
target=True,
deprecated_in="0.27.0",
remove_in="0.30.0",
args_mapping={"normalized_xyxy": "xyxy"},
)
def denormalize_boxes(
xyxy: npt.NDArray[np.number],
resolution_wh: tuple[int, int],
normalization_factor: float = 1.0,
normalized_xyxy: npt.NDArray[np.number] | None = None,
) -> npt.NDArray[np.number]:
"""
Convert normalized bounding box coordinates to absolute pixel coordinates.
Generated
+4 -4
View File
@@ -2563,7 +2563,7 @@ wheels = [
[[package]]
name = "nbconvert"
version = "7.17.0"
version = "7.17.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "beautifulsoup4" },
@@ -2582,9 +2582,9 @@ dependencies = [
{ name = "pygments" },
{ name = "traitlets" },
]
sdist = { url = "https://files.pythonhosted.org/packages/38/47/81f886b699450d0569f7bc551df2b1673d18df7ff25cc0c21ca36ed8a5ff/nbconvert-7.17.0.tar.gz", hash = "sha256:1b2696f1b5be12309f6c7d707c24af604b87dfaf6d950794c7b07acab96dda78", size = 862855, upload-time = "2026-01-29T16:37:48.478Z" }
sdist = { url = "https://files.pythonhosted.org/packages/01/b1/708e53fe2e429c103c6e6e159106bcf0357ac41aa4c28772bd8402339051/nbconvert-7.17.1.tar.gz", hash = "sha256:34d0d0a7e73ce3cbab6c5aae8f4f468797280b01fd8bd2ca746da8569eddd7d2", size = 865311, upload-time = "2026-04-08T00:44:14.914Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/0d/4b/8d5f796a792f8a25f6925a96032f098789f448571eb92011df1ae59e8ea8/nbconvert-7.17.0-py3-none-any.whl", hash = "sha256:4f99a63b337b9a23504347afdab24a11faa7d86b405e5c8f9881cd313336d518", size = 261510, upload-time = "2026-01-29T16:37:46.322Z" },
{ url = "https://files.pythonhosted.org/packages/67/f8/bb0a9d5f46819c821dc1f004aa2cc29b1d91453297dbf5ff20470f00f193/nbconvert-7.17.1-py3-none-any.whl", hash = "sha256:aa85c087b435e7bf1ffd03319f658e285f2b89eccab33bc1ba7025495ab3e7c8", size = 261927, upload-time = "2026-04-08T00:44:12.845Z" },
]
[[package]]
@@ -4055,7 +4055,7 @@ wheels = [
[[package]]
name = "supervision"
version = "0.28.0rc0"
version = "0.28.0rc2"
source = { editable = "." }
dependencies = [
{ name = "defusedxml" },