Repository navigation
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
Conversation
…ing, fast contours, and matplotlib-free font lookup
Codecov Report❌ Patch coverage is 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:
|
Contributor
There was a problem hiding this comment.
🟡 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

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_weightedpromoted two full 1080puint8frames tofloat64(457 MiB peak per blend). It now builds and caches a tiny256×256uint8lookup table using the exact fused float32 rounding formula and indexes it in 64-row strips._box_blur_uint8allocated full-frameint32/int64cumulative arrays; it now processes 128-row horizontal strips with exact reflect-101 vertical padding._rectangle,_ellipse, and thick_polylinesallocated 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_contoursnow crops to the tight non-zero bounding box, traces borders over flatbyteswith precomputed direction offsets, and vectorizesCHAIN_APPROX_SIMPLEcollinear compression._text._resolve_dejavu_font_pathnow usesimportlib.util.find_spec("matplotlib")to locateDejaVuSans.ttfon disk instead of importingmatplotlibat runtime.Motivation and Context
Since
opencv-pythonis no longer a default dependency, out-of-the-box installs usesupervision._cv2for blending, annotators, blurring, contours, and text drawing. Measured on 1080p frames (Python 3.12, NumPy 2.3.1, median wall-time &tracemallocpeak MiB):develop)_cv2.addWeighted(1080p)_cv2.blur(1080p)BoxAnnotator(100 boxes, 1080p)LabelAnnotator(100 labels, 1080p)PolygonAnnotator(25 masks, 1080p)Changes Made
src/supervision/_cv2/_image.py: Cached256×256exactuint8LUT + 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_imagein_rectangle; window-local masks for_ellipseand thick_polylines.src/supervision/_cv2/_contours.py: Tight-bbox foreground crop, flat-bytesborder tracing (_follow_border_fast), and vectorized collinear compression in_compress_contour.src/supervision/_cv2/_text.py: Locate Matplotlib's bundled DejaVu fonts viaimportlib.util.find_spec("matplotlib")without importing Matplotlib._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 skippedWith 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, andmypy— 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
256×256LUT evaluates the exact same fused float32 blend equation on every(a, b)pair, preserving all existing midpoint tie-breaking tests.