Skip to content

perf(cv2-fallback): LUT addWeighted, stripped blur, window-local drawing, fast contours, and matplotlib-free font lookup - #3038

Open
Acedia11 wants to merge 6 commits into
roboflow:developfrom
Acedia11:perf/cv2-fallback-blending-and-drawing
Open

Acedia11 wants to merge 6 commits into
roboflow:developfrom
Acedia11:perf/cv2-fallback-blending-and-drawing

Conversation

@Acedia11

Copy link
Copy Markdown

Description

Speeds up and reduces peak memory of Supervision's pure-NumPy OpenCV fallback backend (supervision._cv2) while preserving pixel-for-pixel OpenCV parity:

  • _add_weighted promoted two full 1080p uint8 frames to float64 (457 MiB peak per blend). It now builds and caches a tiny 256×256 uint8 lookup table using the exact fused float32 rounding formula and indexes it in 64-row strips.
  • _box_blur_uint8 allocated full-frame int32/int64 cumulative arrays; it now processes 128-row horizontal strips with exact reflect-101 vertical padding.
  • _rectangle, _ellipse, and thick _polylines allocated full-frame (H, W) coordinate grids/masks per shape. They now slice directly into ROIs and build masks only inside each shape's local bounding window.
  • _contours._find_contours now crops to the tight non-zero bounding box, traces borders over flat bytes with precomputed direction offsets, and vectorizes CHAIN_APPROX_SIMPLE collinear compression.
  • _text._resolve_dejavu_font_path now uses importlib.util.find_spec("matplotlib") to locate DejaVuSans.ttf on disk instead of importing matplotlib at runtime.

Motivation and Context

Since opencv-python is no longer a default dependency, out-of-the-box installs use supervision._cv2 for blending, annotators, blurring, contours, and text drawing. Measured on 1080p frames (Python 3.12, NumPy 2.3.1, median wall-time & tracemalloc peak MiB):

Workload Before (develop) After Speedup Peak RAM
_cv2.addWeighted (1080p) 732.1 ms 19.9 ms 36.8× 456.8 MiB → 6.41 MiB (71.2× less)
_cv2.blur (1080p) 220.6 ms 105.5 ms 2.1× 148.3 MiB → 32.6 MiB (4.6× less)
BoxAnnotator (100 boxes, 1080p) 293.0 ms 5.0 ms 58.7× 7.95 MiB → 5.95 MiB
LabelAnnotator (100 labels, 1080p) 342.3 ms 23.8 ms 14.4× 7.99 MiB → 6.02 MiB
PolygonAnnotator (25 masks, 1080p) 1,003.4 ms 234.3 ms 4.3× 23.8 MiB → 10.1 MiB (2.4× less)

Changes Made

  • src/supervision/_cv2/_image.py: Cached 256×256 exact uint8 LUT + 64-row strip blending in _add_weighted.
  • src/supervision/_cv2/_transform.py: 128-row horizontal strip processing in _box_blur_uint8.
  • src/supervision/_cv2/_drawing.py: Direct ROI slicing and _paint_disc_into_image in _rectangle; window-local masks for _ellipse and thick _polylines.
  • src/supervision/_cv2/_contours.py: Tight-bbox foreground crop, flat-bytes border tracing (_follow_border_fast), and vectorized collinear compression in _compress_contour.
  • src/supervision/_cv2/_text.py: Locate Matplotlib's bundled DejaVu fonts via importlib.util.find_spec("matplotlib") without importing Matplotlib.
  • Added unit tests for LUT multi-strip _add_weighted, strip _box_blur_uint8, tight-crop _find_contours, and Matplotlib-free font resolution.

Testing

  • Without OpenCV: pytest tests/cv2 tests/draw tests/annotators --doctest-modules src/supervision/_cv2 — 816 passed, 245 skipped

  • With OpenCV parity (opencv-python-headless): pytest tests/cv2/test_image.py tests/cv2/test_transform.py tests/cv2/test_drawing.py tests/cv2/test_contours.py tests/cv2/test_text.py — 602 passed (pixel-for-pixel parity verified against real OpenCV)

  • 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

  • The 256×256 LUT evaluates the exact same fused float32 blend equation on every (a, b) pair, preserving all existing midpoint tie-breaking tests.

…ing, fast contours, and matplotlib-free font lookup
@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:32
@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 98.45560% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 95%. Comparing base (f9f5ee6) to head (b344736).

Additional details and impacted files
@@           Coverage Diff            @@
##           develop   #3038    +/-   ##
========================================
- Coverage       95%     95%    -0%     
========================================
  Files           84      84            
  Lines        15503   15666   +163     
========================================
+ Hits         14772   14904   +132     
- Misses         731     762    +31     
🚀 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

Strip writes into a shifted, overlapping destination can overwrite source rows before they are read, producing incorrect output and requiring overlap-safe handling plus a regression test.

1 open issue
What changed in this PR

Optimizes Supervision’s NumPy-based OpenCV fallback to reduce runtime and peak memory for common image-processing and annotation operations.

Changes:

  • Adds cached lookup-table blending and strip-based box blurring.
  • Limits drawing masks to local windows and accelerates contour tracing.
  • Avoids importing Matplotlib during normal font lookup and adds focused regression tests.
File Description
tests/​cv2/​test_transform.py Checks strip blur against full-frame processing.
tests/​cv2/​test_text.py Checks text rendering without importing Matplotlib.
tests/​cv2/​test_image.py Tests lookup-table blending across strip boundaries.
tests/​cv2/​test_contours.py Checks cropped contour coordinates and holes.
src/​supervision/​_cv2/​_transform.py Processes uint8 blur in horizontal strips.
src/​supervision/​_cv2/​_text.py Locates bundled fonts through package metadata.
src/​supervision/​_cv2/​_image.py Adds cached uint8 blending tables and strip processing.
src/​supervision/​_cv2/​_drawing.py Uses direct slices and local drawing masks.
src/​supervision/​_cv2/​_contours.py Crops foreground bounds and accelerates border tracing and compression.
docs/​changelog.md Documents the fallback optimizations.

Review effort: Balanced

raise ValueError("addWeighted inputs must have equal shapes")
if src1.dtype in _FLOAT32_BLEND_DTYPES:

target = dst if dst is not None else np.empty(src1.shape, dtype=src1.dtype)

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