Skip to content

feat(cv2): complete fallback integration#2439

Open
Borda wants to merge 7 commits into
developfrom
cv2/7
Open

feat(cv2): complete fallback integration#2439
Borda wants to merge 7 commits into
developfrom
cv2/7

Conversation

@Borda

@Borda Borda commented Jul 16, 2026

Copy link
Copy Markdown
Member

This pull request improves the cv2-free fallback implementation to ensure that image border handling, resizing, drawing, and small polygon masks behave consistently with OpenCV, making the library more robust for users without cv2 installed. It also introduces integration tests that enforce the correct use of the OpenCV compatibility layer, and refactors tests and code to consistently use the supervision._cv2 facade instead of direct cv2 imports. Several bug fixes and improvements are made to the fallback image processing routines to match OpenCV’s semantics more closely.

OpenCV compatibility and fallback improvements:

  • The cv2-free fallback now preserves OpenCV-compatible edge and keyword semantics for image borders, resizing, drawing, and small polygon masks, ensuring ordinary production consumers remain usable without cv2.
  • Fixed and enhanced fallback implementations in _drawing.py and _image.py for color handling, rectangle drawing, polylines, polygon filling, border copying, weighted addition, and resizing to closely match OpenCV behavior. [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

Testing and enforcement:

  • Added tests/cv2/test_integration.py to ensure that native OpenCV imports are only allowed through the supervision._cv2 facade and that the test suite passes without cv2 installed.
  • Refactored tests to use from supervision import _cv2 as cv2 instead of direct cv2 imports, ensuring all code paths go through the compatibility layer. [1] [2] [3] [4] [5]

Codebase cleanup:

  • Removed unnecessary or duplicate imports of cv2 within test cases, further enforcing the use of the compatibility layer. [1] [2] [3] [4] [5]
  • Minor test cleanup, such as removing unused files from test directories.

Geometry fallback improvements:

  • Improved fallback implementations for polygon simplification and approximation to better match OpenCV’s results. [1] [2] [3]

These changes make the library more robust for users in environments without OpenCV, provide better test coverage for the compatibility boundary, and enforce best practices for OpenCV usage in the codebase.

Route ordinary fixtures through _cv2 and add cv2-blocked integration coverage.

Co-authored-by: Codex <codex@openai.com>
@codecov

codecov Bot commented Jul 16, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 68.18182% with 14 lines in your changes missing coverage. Please review.
✅ Project coverage is 86%. Comparing base (20b7c08) to head (a363371).

Additional details and impacted files
@@           Coverage Diff           @@
##           develop   #2439   +/-   ##
=======================================
- Coverage       86%     86%   -0%     
=======================================
  Files           84      84           
  Lines        11890   11914   +24     
=======================================
+ Hits         10261   10276   +15     
- Misses        1629    1638    +9     
🚀 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.

Pull request overview

This PR strengthens supervision._cv2 as the single OpenCV compatibility boundary by improving fallback implementations (drawing, geometry, image ops) to better match OpenCV semantics, and by refactoring tests to route all OpenCV usage through the facade so the suite can run without cv2 installed.

Changes:

  • Improved fallback behavior in src/supervision/_cv2/ for borders/resizing/blending, drawing primitives, and polygon approximation.
  • Refactored tests to import from supervision import _cv2 as cv2 (or _cv2) instead of importing native cv2 directly.
  • Added an integration test to enforce the “no direct cv2 imports outside the facade” rule and to validate that the non-reference suite passes when cv2 is blocked.

Review scores (n/5):

  • Code quality: 4/5
  • Testing: 3/5
  • Docs: 4/5

Reviewed changes

Copilot reviewed 16 out of 16 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
tests/utils/conftest.py Switches fixtures to use the _cv2 facade instead of importing native cv2.
tests/metrics/test_detection.py Routes OpenCV usage through supervision._cv2.
tests/key_points/test_annotators.py Adjusts image-similarity thresholds based on backend (opencv vs fallback).
tests/helpers.py Uses _cv2 facade in dataset helper instead of native cv2.
tests/draw/test_utils.py Updates drawing tests to use _cv2 facade.
tests/detection/utils/test_internal.py Updates detection utility tests to use _cv2 facade.
tests/detection/test_compact_mask.py Removes local cv2 imports and relies on _cv2 facade.
tests/dataset/test_progress.py Updates dataset progress tests to use _cv2 facade.
tests/dataset/test_core.py Uses _cv2 facade and removes macOS-specific .DS_Store clutter setup.
tests/dataset/formats/test_pascal_voc.py Updates Pascal VOC tests to use _cv2 facade.
tests/dataset/formats/test_coco.py Updates COCO tests to use _cv2 facade.
tests/cv2/test_integration.py Adds boundary enforcement + “suite passes with cv2 blocked” integration check.
src/supervision/_cv2/_image.py Refines border fill semantics, updates resize signature/behavior, tweaks imread handling, and extends addWeighted signature.
src/supervision/_cv2/_geometry.py Updates approxPolyDP fallback logic to better match OpenCV for closed polygons.
src/supervision/_cv2/_drawing.py Improves fallback drawing for rectangle point ordering, polylines, and tiny polygons.
docs/changelog.md Documents the user-visible fallback compatibility improvements.

Comment thread tests/cv2/test_integration.py Outdated
Comment thread src/supervision/_cv2/_image.py Outdated
dtype: int | None = None,
) -> npt.NDArray[Any]:
"""Blend two arrays with OpenCV-compatible saturation and optional mutation."""
del dtype
Comment thread src/supervision/_cv2/_geometry.py Outdated
Comment on lines +113 to +115
deltas = points[:, np.newaxis] - points[np.newaxis, :]
distances = np.sum(deltas.astype(np.float64) ** 2, axis=2)
start, end = np.unravel_index(int(np.argmax(distances)), distances.shape)
Comment thread src/supervision/_cv2/_image.py Outdated
Comment on lines +54 to +58
values = np.asarray(value, dtype=image.dtype).reshape(-1)
if image.ndim == 2:
raise ValueError("Sequence border value requires a multi-channel image")
fill = np.asarray(value, dtype=image.dtype)
if fill.shape != (image.shape[2],):
raise ValueError("Border value must match the number of channels")
fill_value = fill.reshape((1, 1, -1))
fill_value = values[0] if values.size else 0
else:
fill = np.zeros(image.shape[2], dtype=image.dtype)
Borda and others added 5 commits July 17, 2026 00:27
…nchor seeding

[resolve group] PR #2439 — items 2 3

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: OpenAI Codex <codex@openai.com>
…ssert; fix Windows path separator in boundary check

[resolve group] PR #2439 — items 1 4 5

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: OpenAI Codex <codex@openai.com>
---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
…annel images

[resolve] PR #2439 — QA gate finding (blocking)

Scalar `value` bypassed the Sequence branch entirely and was broadcast to
every channel via np.full(); OpenCV's Scalar(v) semantics fills only
channel 0 and zero-pads the rest. Verified against installed cv2 4.11.0.
Pre-existing bug in the original PR, surfaced by copyMakeBorder parity
tests added in this resolve pass. Also reverts a lint-expert regression
in _geometry.py that dropped the `# type: ignore[redundant-cast]` the PR
author deliberately kept (see `warn_unused_ignores = false` override for
`supervision._cv2` in pyproject.toml — the ignore is needed under
pre-commit's isolated mypy env even though the project's own uv-managed
mypy env reports it as unused, a numpy-stub version skew between the two
environments).

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants