Skip to content

perf(annotators,smoother): ROI-only mask/color/heatmap blending, strip halo, zero-mask-copy trace, and bounded smoother masks - #3039

Open
Acedia11 wants to merge 6 commits into
roboflow:developfrom
Acedia11:perf/annotators-and-smoother
Open

Acedia11 wants to merge 6 commits into
roboflow:developfrom
Acedia11:perf/annotators-and-smoother

Conversation

@Acedia11

Copy link
Copy Markdown

Description

Eliminates redundant full-frame allocations, blends, mask copies, and spline recomputations across high-traffic annotators and DetectionsSmoother, preserving exact pixel outputs and smoothing behavior on both OpenCV and pure-NumPy fallback backends:

  • _paint_masks_by_area scanned entire (H, W) frames per dense mask instead of each mask's tight bounding box; MaskAnnotator made a redundant scene_roi.copy(); ColorAnnotator cloned and blended the full scene instead of the detections' union ROI.
  • HaloAnnotator allocated full-frame float32 blend buffers even on rows with zero halo pixels.
  • HeatMapAnnotator allocated full-frame float64 masks, ran full-frame HSV→BGR conversions, and blended every frame pixel instead of active heatmap pixels.
  • TraceAnnotator copied full detection masks into track history even when position != Position.CENTER_OF_MASS, and recomputed splines on every frame.
  • DetectionsSmoother retained full dense masks on every historical entry in each track deque (even though only the latest entry's mask is emitted) and ran copy.deepcopy per track.

Motivation and Context

Measured standalone against develop (without OpenCV installed; Python 3.12, NumPy 2.3.1, median wall-time & tracemalloc peak MiB):

Workload Before (develop) After Speedup Peak RAM
HeatMapAnnotator (50 dets, 1080p) 889.1 ms 137.4 ms 6.5× 502.3 MiB → 69.0 MiB (7.3× less)
TraceAnnotator w/ masks (50 dets, 1080p) 59.4 ms 24.4 ms 2.4× 203.7 MiB → 7.94 MiB (25.7× less)
MaskAnnotator (50 masks, 1080p) 751.8 ms 325.0 ms 2.3× 442.8 MiB → 437.2 MiB
ColorAnnotator (50 boxes, 1080p) 804.6 ms 426.7 ms 1.9× 468.7 MiB → 437.3 MiB
HaloAnnotator (50 masks, 1080p) 424.7 ms 220.2 ms 1.9× 174.0 MiB → 133.4 MiB
DetectionsSmoother w/ masks (30 tracks, 480p) 6.8 ms 3.4 ms 2.0× 26.4 MiB → 17.6 MiB (5× fewer retained masks)

Changes Made

  • src/supervision/annotators/core.py:
    • Tight-bbox dense mask painting in _paint_masks_by_area; removed redundant scene_roi.copy() in MaskAnnotator.
    • Union-ROI copy and blend in ColorAnnotator.
    • 64-row strip blending (skipping zero-halo strips) in HaloAnnotator for both BGR and BGRA scenes.
    • Skip mask copies in TraceAnnotator when position != Position.CENTER_OF_MASS and cache per-track smooth splines.
    • uint8 ROI accumulation, cached 256-entry exact HSV(h, 255, 255)→BGR LUT via active cv2.cvtColor, and active-pixel ROI blending in HeatMapAnnotator.
  • src/supervision/detection/tools/smoother.py:
    • Release superseded historical masks when appending a newer detection for the same track (retaining only the latest mask) and avoid per-track deepcopy of Detections.
  • Added unit tests in tests/annotators/test_core.py and tests/detection/tools/test_smoother.py.

Testing

  • Without OpenCV: pytest tests/annotators tests/detection/tools/test_smoother.py --doctest-modules src/supervision/annotators/core.py src/supervision/detection/tools/smoother.py — 512 passed

  • With OpenCV (opencv-python-headless): pytest tests/annotators/test_core.py tests/detection/tools/test_smoother.py — 381 passed

  • ruff check, ruff format, codespell, check_doctest_fences.py, and mypy — all passed cleanly on changed lines.

  • Added/updated tests, and the full suite passes locally

  • Updated docs (docstrings / mkdocs entry) for new or changed public API

  • Added a changelog entry at the top of docs/changelog.md (skip for lint/type/format-only or pure doc changes)

Additional Notes

  • _heatmap_hsv_to_bgr_lut() runs the active cv2.cvtColor once on a 256-pixel strip so outputs remain bit-for-bit aligned with both OpenCV and fallback backends.

…p halo, zero-mask-copy trace, and bounded smoother masks
@Acedia11
Acedia11 requested a review from SkalskiP as a code owner November 21, 2026 01:12
@CLAassistant

CLAassistant commented Nov 21, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@Borda
Borda requested a balanced review from Copilot November 21, 2026 22:33
@Borda Borda added the enhancement New feature or request label Nov 21, 2026
@codecov

codecov Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.17834% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 95%. Comparing base (f9f5ee6) to head (1e68d8b).

Additional details and impacted files
@@           Coverage Diff           @@
##           develop   #3039   +/-   ##
=======================================
  Coverage       95%     95%           
=======================================
  Files           84      84           
  Lines        15503   15602   +99     
=======================================
+ Hits         14772   14867   +95     
- Misses         731     735    +4     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved findings identify annotation-output regressions, unbounded trace-cache growth, and shared mutable smoother data that can corrupt retained history.

6 open issues
What changed in this PR

This PR reduces allocation and processing costs in Supervision’s annotators and detection smoother, aiming to preserve rendering and smoothing behavior.

Changes:

  • Restricts mask painting and blending to relevant regions or non-empty strips.
  • Caches heatmap colors and trace splines, skips unused mask copies, and releases superseded smoother masks.
  • Adds focused regression tests and a changelog entry.
File Description
tests/​detection/​tools/​test_smoother.py Tests historical mask release and dense output-mask isolation.
tests/​annotators/​test_core.py Tests halo strips, trace updates, heatmap lookup colors, and offscreen anchors.
src/​supervision/​detection/​tools/​smoother.py Limits retained masks and replaces per-track deep copies with selective copying.
src/​supervision/​annotators/​core.py Adds region-based blending, strip processing, and heatmap and spline caches.
docs/​changelog.md Documents the performance optimizations.

Review effort: Balanced

if detections.class_id is not None
else None
),
tracker_id=detections.tracker_id[is_confirmed],
spline_points = unique_xy.astype(np.int32)
else:
spline_points = unique_xy.astype(np.int32)
spline_cache[tracker_id] = (xy_key, spline_points)
Comment thread src/supervision/annotators/core.py Outdated
Comment on lines +2819 to +2820
hue_scale = (self.low_hue - self.top_hue) / max_val
heat_hue = (self.low_hue - heat_mask * hue_scale).astype(np.uint8)
Comment thread src/supervision/annotators/core.py Outdated
Comment on lines +2827 to +2830
# Colorize and blend only the tight bounding ROI of nonzero heat via the
# cached 256-entry HSV(h, 255, 255) -> BGR table.
lut = _heatmap_hsv_to_bgr_lut()
heat_bgr_roi = lut[heat_hue[hy1:hy2, hx1:hx2]]
confidence = np.mean(np.array(confidences), axis=0) if confidences else None

data = {
key: value.copy() if isinstance(value, np.ndarray) else deepcopy(value)
Comment on lines +285 to +286
if copy_mask and isinstance(mask, np.ndarray):
mask = mask.copy()

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants