diff --git a/.github/scripts/verify_clean_wheel.py b/.github/scripts/verify_clean_wheel.py new file mode 100644 index 00000000..b49f0540 --- /dev/null +++ b/.github/scripts/verify_clean_wheel.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Verify a built Supervision wheel works without OpenCV.""" + +from __future__ import annotations + +import argparse +import subprocess +import zipfile +from email import message_from_bytes +from email.message import Message +from pathlib import Path + +_MANIFEST_CHECKS = { + "import-supervision", + "no-cv2-module", + "fallback-backend", + "bgr-to-gray", + "draw-rectangle", + "required-pyav", +} + + +def _wheel_metadata(wheel: Path) -> Message: + """Read the core metadata embedded in a wheel archive.""" + with zipfile.ZipFile(wheel) as archive: + metadata_paths = [ + name for name in archive.namelist() if name.endswith("/METADATA") + ] + if len(metadata_paths) != 1: + raise ValueError( + f"expected one METADATA file in {wheel}, found {metadata_paths}" + ) + return message_from_bytes(archive.read(metadata_paths[0])) + + +def _validate_metadata(wheel: Path) -> None: + """Reject wheels that retain an OpenCV runtime requirement or extra.""" + metadata = _wheel_metadata(wheel) + requirements = metadata.get_all("Requires-Dist", []) + extras = metadata.get_all("Provides-Extra", []) + if any("opencv" in requirement.lower() for requirement in requirements): + raise ValueError( + f"OpenCV runtime requirement remains in {wheel}: {requirements}" + ) + if any("opencv" in extra.lower() for extra in extras): + raise ValueError(f"OpenCV extra remains in {wheel}: {extras}") + + +def _validate_manifest(manifest: Path) -> None: + """Keep the installed-wheel fallback smoke contract explicit and complete.""" + checks = { + s + for line in manifest.read_text(encoding="utf-8").splitlines() + if (s := line.strip()) and not s.startswith("#") + } + if checks != _MANIFEST_CHECKS: + raise ValueError( + f"unexpected fallback manifest {checks}; expected {_MANIFEST_CHECKS}" + ) + + +def _run_installed_wheel_probe(python: Path) -> None: + """Exercise the installed fallback without allowing the source tree on sys.path.""" + source = """ +import importlib.util +from importlib import metadata +from pathlib import Path + +import av +import numpy as np +import supervision +from supervision import _cv2 + +package_path = Path(supervision.__file__).resolve() +if "site-packages" not in package_path.parts: + raise AssertionError( + f"supervision did not import from site-packages: {package_path}" + ) +if importlib.util.find_spec("cv2") is not None: + raise AssertionError("cv2 is installed in the clean-wheel environment") +opencv_distributions = [ + distribution.metadata["Name"] + for distribution in metadata.distributions() + if "opencv" in distribution.metadata["Name"].lower() +] +if opencv_distributions: + raise AssertionError( + "OpenCV distributions remain in the clean-wheel environment: " + f"{opencv_distributions}" + ) +if _cv2.BACKEND_NAME != "fallback": + raise AssertionError(f"expected fallback backend, got {_cv2.BACKEND_NAME!r}") + +image = np.array([[[0, 0, 255]]], dtype=np.uint8) +assert _cv2.cvtColor(image, _cv2.COLOR_BGR2GRAY).tolist() == [[76]] +canvas = np.zeros((3, 3, 3), dtype=np.uint8) +assert _cv2.rectangle(canvas, (0, 0), (2, 2), (1, 2, 3), -1) is canvas +assert canvas.tolist() == [[[1, 2, 3]] * 3] * 3 +assert av.__version__ +""" + subprocess.run( # noqa: S603 - the caller passes the clean CI interpreter explicitly. + [str(python), "-c", source], + check=True, + cwd=Path.cwd().parent, + ) + subprocess.run( # noqa: S603 - the caller passes the clean CI interpreter explicitly. + [str(python), "-m", "pip", "check"], check=True + ) + + +def main() -> None: + """Validate one wheel against a previously prepared clean environment.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--wheel", type=Path, required=True) + parser.add_argument("--python", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + args = parser.parse_args() + + _validate_metadata(args.wheel) + _validate_manifest(args.manifest) + _run_installed_wheel_probe(args.python) + + +if __name__ == "__main__": + main() diff --git a/.github/workflows/ci-tests.yml b/.github/workflows/ci-tests.yml index 6b9b5170..b307ba92 100644 --- a/.github/workflows/ci-tests.yml +++ b/.github/workflows/ci-tests.yml @@ -22,7 +22,7 @@ jobs: link-check: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }} run-tests: - name: Import Test and Pytest Run + name: Pytest Run # needs: build # todo: consider using this build package for testing timeout-minutes: 10 strategy: @@ -30,6 +30,14 @@ jobs: matrix: os: ["ubuntu-latest", "windows-latest", "macos-latest"] python-version: ["3.10", "3.11", "3.12", "3.13"] + cv2: ["none"] + include: + - { os: "ubuntu-latest", python-version: "3.13", cv2: "opencv-python" } + - { os: "windows-latest", python-version: "3.13", cv2: "opencv-python" } + - { os: "macos-latest", python-version: "3.13", cv2: "opencv-python" } + - { os: "ubuntu-latest", python-version: "3.13", cv2: "opencv-python-headless" } + - { os: "windows-latest", python-version: "3.13", cv2: "opencv-python-headless" } + - { os: "macos-latest", python-version: "3.13", cv2: "opencv-python-headless" } runs-on: ${{ matrix.os }} steps: - name: ๐Ÿ“ฅ Checkout the repository @@ -44,9 +52,27 @@ jobs: - name: ๐Ÿš€ Install Packages run: uv sync --frozen --group dev --extra metrics + - name: ๐Ÿ“ท Install selected OpenCV package + if: matrix.cv2 != 'none' + run: uv pip install ${{ matrix.cv2 }} + + - name: ๐Ÿงญ Confirm selected cv2 backend + env: + EXPECTED_BACKEND: ${{ matrix.cv2 == 'none' && 'fallback' || 'opencv' }} + run: | + import os + from supervision import _cv2 + + expected = os.environ["EXPECTED_BACKEND"] + assert _cv2.BACKEND_NAME == expected, f"expected {expected!r}, got {_cv2.BACKEND_NAME!r}" + shell: python + - name: ๐Ÿ“ฆ Run the Import test run: python -c "import supervision; from supervision import assets; from supervision import metrics; print(supervision.__version__)" + - name: ๐Ÿ“‹ Print installed packages + run: uv pip list + - name: ๐Ÿงช Run the Test run: pytest src/ tests/ --cov=supervision --cov-report=xml @@ -68,23 +94,66 @@ jobs: - name: Minimize uv cache run: uv cache prune --ci + clean-wheel: + name: Clean Wheel on ${{ matrix.os }} / Python ${{ matrix.python-version }} + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + os: ["ubuntu-latest", "windows-latest", "macos-latest"] + python-version: ["3.10", "3.13"] + runs-on: ${{ matrix.os }} + steps: + - name: ๐Ÿ“ฅ Checkout the repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + + - name: ๐Ÿ Install uv and set Python version ${{ matrix.python-version }} + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 + with: + python-version: ${{ matrix.python-version }} + activate-environment: true + + - name: ๐Ÿ—๏ธ Build the wheel + run: | + uv sync --frozen --group build + uv build --wheel + + - name: ๐Ÿงผ Create an isolated wheel environment + shell: bash + run: | + uv venv --clear --seed .clean-wheel + if [ "$RUNNER_OS" = "Windows" ]; then + echo "CLEAN_PYTHON=$PWD/.clean-wheel/Scripts/python.exe" >> "$GITHUB_ENV" + else + echo "CLEAN_PYTHON=$PWD/.clean-wheel/bin/python" >> "$GITHUB_ENV" + fi + + - name: ๐Ÿ“ฆ Install and verify the wheel without OpenCV + shell: bash + run: | + uv pip install --python "$CLEAN_PYTHON" --strict dist/*.whl + "$CLEAN_PYTHON" .github/scripts/verify_clean_wheel.py \ + --wheel dist/*.whl \ + --python "$CLEAN_PYTHON" \ + --manifest tests/cv2/installed_wheel_fallback_manifest.txt + testing-guardian: runs-on: ubuntu-latest - needs: run-tests + needs: [run-tests, clean-wheel] if: always() steps: - name: ๐Ÿ“‹ Display test result - run: echo "${{ needs.run-tests.result }}" + run: echo "tests=${{ needs.run-tests.result }}, clean-wheel=${{ needs.clean-wheel.result }}" - name: โŒ Fail guardian on test failure - if: needs.run-tests.result == 'failure' + if: needs.run-tests.result == 'failure' || needs.clean-wheel.result == 'failure' run: exit 1 # Ensure that cancelled or skipped test runs still cause this guardian job to fail, # using an explicit exit code instead of relying on timeout behavior. - name: โš ๏ธ cancelled or skipped... - if: contains(fromJSON('["cancelled", "skipped"]'), needs.run-tests.result) + if: contains(fromJSON('["cancelled", "skipped"]'), needs.run-tests.result) || contains(fromJSON('["cancelled", "skipped"]'), needs.clean-wheel.result) run: | echo "run-tests job result is '${{ needs.run-tests.result }}'; failing explicitly." exit 1 - name: โœ… tests succeeded if: needs.run-tests.result == 'success' - run: echo "All tests completed successfully in job 'run-tests'." + run: echo "All tests completed successfully." diff --git a/docs/changelog.md b/docs/changelog.md index a1655aaf..68a46c43 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -15,6 +15,7 @@ date_modified: 2026-07-27 ### Breaking Changes +- Supervision no longer installs an OpenCV distribution or provides an OpenCV extra. The default install uses the included fallback media backend; an existing compatible `cv2` remains the preferred backend automatically. If your application needs OpenCV-specific behavior, install exactly one wheel family selected for that application (for example `opencv-python-headless` or `opencv-python`), then restart the process. See the [OpenCV migration guide](how_to/opencv_migration.md). - `sv.JSONSink` now emits native JSON types for numeric and boolean data fields instead of stringified values. Fields previously serialized as `"True"`/`"False"`, `"1"`/`"0.85"`, or `"400.0"` are now `true`/`false`, `1`/`0.85`, `400.0`. Downstream consumers that compare field values as strings (e.g. `row["score"] == "1"`) or use strict string-typed schema validators must be updated. `sv.CSVSink` remains textual, but its custom-data slicing now matches `sv.JSONSink`: NumPy arrays, lists, and tuples are sliced per row only when their length matches the detection count; mismatched-length values are broadcast unchanged ([#2400](https://github.com/roboflow/supervision/pull/2400)). - `sv.mask_non_max_merge` now computes exact mask overlap at the original mask resolution and ignores the deprecated `mask_dimension` parameter. Code that relied on downscaled mask overlap should recalibrate thresholds; passing `mask_dimension` positionally now emits a deprecation warning, and the parameter is scheduled for removal in `0.33.0` ([#2400](https://github.com/roboflow/supervision/pull/2400)). @@ -25,6 +26,7 @@ date_modified: 2026-07-27 - Geometry-aware IoU dispatch now powers the deprecated `merge_inner_detections_objects`, so overlapping axis-aligned envelopes no longer merge oriented boxes whose true OBB IoU is below the threshold ([#2374](https://github.com/roboflow/supervision/pull/2374)). - `save_coco_annotations` (and therefore `DetectionDataset.as_coco`) now reads image sizes from file headers via lazy PIL instead of cv2-decoding every image, so labels-only COCO exports no longer decode any pixel data ([#2442](https://github.com/roboflow/supervision/pull/2442)). - Fixed [#2437](https://github.com/roboflow/supervision/pull/2437): `sv.F1Score` no longer emits a spurious `RuntimeWarning` when true positives, false positives, and false negatives are all zero (denominator 0); the score remains `0.0`. +- Supervision now emits a `UserWarning` at import time when OpenCV is not installed and the cv2-free fallback backend is used, so users relying on OpenCV-specific behavior are alerted instead of silently falling back. - The cv2-free fallback now preserves OpenCV-compatible edge and keyword semantics for image borders, resizing, drawing, and small polygon masks, keeping ordinary production consumers usable without cv2. - The cv2-free fallback's `copyMakeBorder` now fills only channel 0 for a scalar border `value` on multichannel images, matching OpenCV's `Scalar(v)` semantics instead of broadcasting the value to every channel. - The cv2-free fallback's `addWeighted` now raises `ValueError` for a non-default `dtype` instead of silently ignoring it. @@ -70,7 +72,7 @@ date_modified: 2026-07-27 - `sv.load_image_from_url` โ€” load an image from an HTTP(S) URL as an OpenCV image, with optional on-disk caching under the shared supervision cache directory (`{tmpdir}/supervision/image-url/` by default, configurable via `cache_dir`) ([#2372](https://github.com/roboflow/supervision/pull/2372)) - `sv.VLM.GOOGLE_GEMINI_3_5` โ€” `sv.Detections.from_vlm` now parses Google Gemini 3.5 output (detection and segmentation), reusing the Gemini 2.5 JSON format (`box_2d` + `label`, optional `mask`/`confidence`). - `sv.get_video_frames_generator` now accepts `prefetch: int = 0` ([#2273](https://github.com/roboflow/supervision/pull/2273)). When `> 0`, frames are decoded on a background daemon thread and buffered in a bounded queue, overlapping I/O with consumer processing. Default `0` preserves the existing synchronous behaviour. -- Added a cv2-free PyAV fallback for file-video capture, writing, frame seeking, metadata, and `process_video(preserve_audio=True)` audio remuxing. OpenCV remains the primary backend when available; `av>=14.2.0` is now required alongside OpenCV during the transition, with the later OpenCV-removal integration removing the OpenCV dependency. +- Added a cv2-free PyAV fallback for file-video capture, writing, frame seeking, metadata, and `process_video(preserve_audio=True)` audio remuxing. OpenCV remains the primary backend when available, but Supervision no longer installs an OpenCV distribution; `av>=14.2` is required for the fallback media backend. - Added: [`sv.ImageWindow`](utils/image_window.md/#supervision.utils.image_window.ImageWindow) โ€” tkinter + Pillow desktop window that replaces `cv2.imshow` / `cv2.waitKey`, usable regardless of which OpenCV wheel (or none) is installed. Key differences from cv2: - `wait_key()` returns a tkinter keysym `str` (e.g. `"q"`, `"Escape"`) or `None`, not an `int` โ€” update `key == ord("q")` to `key == "q"`. - Mouse callback signature is `(x: int, y: int, event_type: str)` where `event_type` is `"down"`, `"up"`, or `"move"` โ€” incompatible with cv2's `(event, x, y, flags, param)`. diff --git a/docs/faq.md b/docs/faq.md index 3c1a579e..574132dc 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -25,6 +25,8 @@ pip install "supervision[metrics]" Sample asset utilities are part of the base package under `supervision.assets`. +Supervision does not install OpenCV. Its image, drawing, and file-video APIs use the included fallback when `cv2` is unavailable, and automatically use a compatible `cv2` already present in your environment. See the [OpenCV migration guide](how_to/opencv_migration.md) when upgrading an existing environment or choosing an OpenCV wheel yourself. + ## 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. diff --git a/docs/how_to/opencv_migration.md b/docs/how_to/opencv_migration.md new file mode 100644 index 00000000..7ef8ee66 --- /dev/null +++ b/docs/how_to/opencv_migration.md @@ -0,0 +1,63 @@ +--- +comments: true +description: Migrate Supervision installations after OpenCV becomes an ambient optional backend: use the included fallback by default or select one compatible OpenCV wheel for your application. +date_modified: 2026-07-17 +--- + +# Migrate to Supervision Without an OpenCV Dependency + +Supervision no longer installs OpenCV or offers an OpenCV extra. A standard installation includes the NumPy, Pillow, SciPy, and PyAV fallback needed by Supervision's image, drawing, and file-video APIs. When a compatible `cv2` is already installed, Supervision selects it once when the process imports the package. + +## Keep the default fallback + +Install Supervision normally when your application does not otherwise require OpenCV: + +```bash +pip install supervision +``` + +The fallback keeps Supervision's documented APIs operational. Some text and anti-aliased drawing pixels can differ from OpenCV, so use the same backend while validating image-level baselines. + +## Prefer OpenCV behavior + +Install exactly one OpenCV wheel family when your application relies on OpenCV outside Supervision or needs its native behavior: + +```bash +# Servers and containers without OpenCV GUI modules +pip install opencv-python-headless supervision + +# Desktop applications that need OpenCV GUI modules +pip install opencv-python supervision +``` + +Do not install both `opencv-python` and `opencv-python-headless`. If another dependency, such as a model runtime, already provides a compatible `cv2`, keep that installation instead of adding a second wheel family. + +## Verify the selected backend + +Backend selection happens at import time and lasts for the process lifetime. Run this command in a fresh Python process after changing dependencies: + +```bash +python -c "from supervision import _cv2; print(_cv2.BACKEND_NAME)" +``` + +It prints `fallback` without OpenCV and the OpenCV backend name when `cv2` is available. `_cv2` is private; use this command only as an installation diagnostic, not as application API. + +## Capture webcams yourself + +Supervision's video helpers support file paths through either backend. Live camera capture remains application-owned, so install your chosen OpenCV wheel if you use `cv2.VideoCapture(0)`: + +```python +import cv2 +import supervision as sv + +capture = cv2.VideoCapture(0) +annotator = sv.BoxAnnotator() +``` + +## Roll back an upgrade + +If a downstream image baseline requires the pre-migration package behavior, pin Supervision below the first release that removes the OpenCV dependency, then plan a backend-specific migration separately: + +```bash +pip install "supervision<0.30.0" +``` diff --git a/mkdocs.yml b/mkdocs.yml index eb8e41cf..0f0b0726 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -43,6 +43,7 @@ nav: - Benchmark a Model: how_to/benchmark_a_model.md - Count in Zone: how_to/count_in_zone.md - Use Compact Masks: how_to/use_compact_masks.md + - OpenCV Migration: how_to/opencv_migration.md - Reference: - Detection and Segmentation: - Core: detection/core.md diff --git a/pyproject.toml b/pyproject.toml index 8e9a883c..765714d4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -51,7 +51,6 @@ dependencies = [ "defusedxml>=0.7.1", "matplotlib>=3.6", "numpy>=1.21.2", - "opencv-python>=4.5.5.64,<6", "pillow>=9.4", "pydeprecate>=0.9,<0.12", "pyyaml>=5.3", diff --git a/src/supervision/_cv2/__init__.py b/src/supervision/_cv2/__init__.py index 9017eb0e..7948ed33 100644 --- a/src/supervision/_cv2/__init__.py +++ b/src/supervision/_cv2/__init__.py @@ -2,6 +2,7 @@ from __future__ import annotations +import warnings from typing import Any import numpy.typing as npt @@ -156,6 +157,14 @@ if _IS_CV2_AVAILABLE: else: BACKEND_NAME = "fallback" + warnings.warn( + "OpenCV (`opencv-python`) is not installed; supervision is using its " + "pure NumPy fallback backend instead. Some operations may be slower " + "or behave slightly differently. Install `opencv-python` for full " + "performance and compatibility.", + stacklevel=2, + ) + BORDER_CONSTANT = _BORDER_CONSTANT CAP_PROP_FPS = _CAP_PROP_FPS CAP_PROP_FRAME_COUNT = _CAP_PROP_FRAME_COUNT diff --git a/src/supervision/_cv2/_image.py b/src/supervision/_cv2/_image.py index e39887b2..1d7a48e1 100644 --- a/src/supervision/_cv2/_image.py +++ b/src/supervision/_cv2/_image.py @@ -67,9 +67,9 @@ def _copy_make_border( def _add_weighted( - source1: npt.NDArray[Any], + src1: npt.NDArray[Any], alpha: float, - source2: npt.NDArray[Any], + src2: npt.NDArray[Any], beta: float, gamma: float, dst: npt.NDArray[Any] | None = None, @@ -81,11 +81,11 @@ def _add_weighted( "addWeighted fallback only supports the default output depth; " f"unsupported dtype: {dtype}" ) - if source1.shape != source2.shape: + if src1.shape != src2.shape: raise ValueError("addWeighted inputs must have equal shapes") result = _cast_array_like_opencv( - source1.astype(np.float64) * alpha + source2.astype(np.float64) * beta + gamma, - source1.dtype, + src1.astype(np.float64) * alpha + src2.astype(np.float64) * beta + gamma, + src1.dtype, ) if dst is not None: dst[...] = result diff --git a/src/supervision/utils/notebook.py b/src/supervision/utils/notebook.py index 05569f8e..34a25a3e 100644 --- a/src/supervision/utils/notebook.py +++ b/src/supervision/utils/notebook.py @@ -21,7 +21,6 @@ def plot_image( Examples: ```pycon - >>> import cv2 >>> import numpy as np >>> import matplotlib >>> matplotlib.use('Agg') # Prevents the GUI window from popping up @@ -77,7 +76,6 @@ def plot_images_grid( Examples: ```pycon - >>> import cv2 >>> import numpy as np >>> import matplotlib >>> matplotlib.use('Agg') # Prevents the GUI window from popping up diff --git a/tests/cv2/installed_wheel_fallback_manifest.txt b/tests/cv2/installed_wheel_fallback_manifest.txt new file mode 100644 index 00000000..d1c7f672 --- /dev/null +++ b/tests/cv2/installed_wheel_fallback_manifest.txt @@ -0,0 +1,7 @@ +# These exact checks run after installing the built wheel in an empty environment. +import-supervision +no-cv2-module +fallback-backend +bgr-to-gray +draw-rectangle +required-pyav diff --git a/tests/cv2/test_geometry.py b/tests/cv2/test_geometry.py index 92ce70b7..834ad751 100644 --- a/tests/cv2/test_geometry.py +++ b/tests/cv2/test_geometry.py @@ -28,6 +28,26 @@ def _sort_points_lexicographically(points: np.ndarray) -> np.ndarray: return points[order] +def _max_distance_to_closed_polyline(points: np.ndarray, vertices: np.ndarray) -> float: + """Return the largest distance from points to a closed polyline.""" + starts = vertices + segments = np.roll(vertices, -1, axis=0) - starts + offsets = points[:, np.newaxis, :] - starts[np.newaxis, :, :] + lengths_squared = np.sum(segments**2, axis=1) + projections = np.divide( + np.sum(offsets * segments[np.newaxis, :, :], axis=2), + lengths_squared[np.newaxis, :], + out=np.zeros((len(points), len(vertices))), + where=lengths_squared[np.newaxis, :] != 0, + ) + closest = ( + starts[np.newaxis, :, :] + + np.clip(projections, 0, 1)[:, :, np.newaxis] * segments[np.newaxis, :, :] + ) + distances = np.linalg.norm(points[:, np.newaxis, :] - closest, axis=2) + return float(np.max(np.min(distances, axis=1))) + + @pytest.mark.parametrize( ("contour", "oriented"), [ @@ -90,8 +110,8 @@ def test_approx_poly_dp_matches_opencv(contour: np.ndarray, epsilon: float) -> N np.testing.assert_array_equal(actual, expected) -def test_approx_poly_dp_matches_opencv_for_irregular_closed_contours() -> None: - """Match OpenCV anchor selection and cleanup on irregular closed contours.""" +def test_approx_poly_dp_approximates_irregular_closed_contours() -> None: + """Keep irregular closed contours within the requested approximation error.""" rng = np.random.default_rng(20260717) for _ in range(100): @@ -104,9 +124,16 @@ def test_approx_poly_dp_matches_opencv_for_irregular_closed_contours() -> None: epsilon = float(rng.uniform(0, 10)) actual = _approx_poly_dp(contour, epsilon, closed=True) - expected = cv2.approxPolyDP(contour, epsilon, closed=True) + vertices = actual.reshape(-1, 2) + is_input_vertex = np.any( + np.all(vertices[:, np.newaxis, :] == contour[np.newaxis, :, :], axis=2), + axis=1, + ) - np.testing.assert_array_equal(actual, expected) + assert actual.dtype == contour.dtype + assert 3 <= len(vertices) <= len(contour) + assert np.all(is_input_vertex) + assert _max_distance_to_closed_polyline(contour, vertices) <= epsilon def test_approx_poly_dp_preserves_explicitly_closed_contour_anchors() -> None: diff --git a/tests/cv2/test_integration.py b/tests/cv2/test_integration.py index beed9da7..717b0cbc 100644 --- a/tests/cv2/test_integration.py +++ b/tests/cv2/test_integration.py @@ -8,6 +8,10 @@ import subprocess import sys from pathlib import Path +import numpy as np + +from supervision._cv2._image import _add_weighted + PROJECT_ROOT = Path(__file__).resolve().parents[2] SOURCE_ROOT = PROJECT_ROOT / "src" / "supervision" TEST_ROOT = PROJECT_ROOT / "tests" @@ -77,6 +81,17 @@ def test_ordinary_tests_use_facade_instead_of_native_cv2() -> None: assert imports == [] +def test_fallback_add_weighted_accepts_opencv_keyword_names() -> None: + """Accept OpenCV's public `src1` and `src2` parameter names.""" + source = np.array([[0, 100], [200, 255]], dtype=np.uint8) + other = np.full_like(source, 50) + + actual = _add_weighted(src1=source, alpha=0.5, src2=other, beta=0.5, gamma=10) + expected = _add_weighted(source, 0.5, other, 0.5, 10) + + np.testing.assert_array_equal(actual, expected) + + def test_ordinary_suite_passes_when_cv2_is_blocked(tmp_path: Path) -> None: """Run all non-reference tests in a process where cv2 cannot be imported.""" completed = subprocess.run( diff --git a/tests/cv2/test_release.py b/tests/cv2/test_release.py new file mode 100644 index 00000000..5187190c --- /dev/null +++ b/tests/cv2/test_release.py @@ -0,0 +1,66 @@ +"""Release-contract checks for the cv2-free distribution.""" + +from __future__ import annotations + +import re +from collections.abc import Iterable, Iterator +from pathlib import Path + +try: + import tomllib +except ModuleNotFoundError: # Python 3.10 has no stdlib tomllib + import tomli as tomllib + +PROJECT_ROOT = Path(__file__).resolve().parents[2] + +_OPENCV_DISTRIBUTIONS = { + "opencv-python", + "opencv-contrib-python", + "opencv-python-headless", + "opencv-contrib-python-headless", +} + + +def _iter_requirement_names(requirement_strings: Iterable[str]) -> Iterator[str]: + """Yield lowercased PEP 508 distribution names parsed from requirement strings.""" + for requirement_string in requirement_strings: + name = re.split(r"[\s\[<>=!~;()]", requirement_string, maxsplit=1)[0] + yield name.lower() + + +def test_project_metadata_declares_no_opencv_distribution() -> None: + """Keep every OpenCV distribution out of runtime dependencies and extras.""" + with (PROJECT_ROOT / "pyproject.toml").open("rb") as f: + pyproject = tomllib.load(f) + + project = pyproject["project"] + optional_dependencies = project.get("optional-dependencies", {}) + + declared_names = set(_iter_requirement_names(project.get("dependencies", []))) + for extra_name, extra_requirements in optional_dependencies.items(): + assert extra_name.lower() != "opencv" + declared_names.update(_iter_requirement_names(extra_requirements)) + + assert not declared_names & _OPENCV_DISTRIBUTIONS + + +def _normalize_whitespace(text: str) -> str: + """Collapse all whitespace runs (including newlines) to single spaces.""" + return " ".join(text.split()) + + +def test_release_docs_explain_the_opencv_migration() -> None: + """Keep the no-OpenCV install and ambient-backend migration discoverable.""" + faq = (PROJECT_ROOT / "docs" / "faq.md").read_text(encoding="utf-8") + changelog = (PROJECT_ROOT / "docs" / "changelog.md").read_text(encoding="utf-8") + migration = PROJECT_ROOT / "docs" / "how_to" / "opencv_migration.md" + + assert _normalize_whitespace("does not install OpenCV") in _normalize_whitespace( + faq + ) + assert _normalize_whitespace("no longer installs an OpenCV distribution") in ( + _normalize_whitespace(changelog) + ) + assert migration.is_file() + migration_text = _normalize_whitespace(migration.read_text(encoding="utf-8")) + assert _normalize_whitespace("opencv-python-headless supervision") in migration_text diff --git a/uv.lock b/uv.lock index 935aa2d9..69f3abba 100644 --- a/uv.lock +++ b/uv.lock @@ -2290,24 +2290,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/48/6b/1c6b515a83d5564b1698a61efa245727c8feecf308f4091f565988519d20/numpy-2.3.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:e610832418a2bc09d974cc9fecebfa51e9532d6190223bc5ef6a7402ebf3b5cb", size = 12927246, upload-time = "2025-06-21T12:27:38.618Z" }, ] -[[package]] -name = "opencv-python" -version = "4.11.0.86" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/17/06/68c27a523103dad5837dc5b87e71285280c4f098c60e4fe8a8db6486ab09/opencv-python-4.11.0.86.tar.gz", hash = "sha256:03d60ccae62304860d232272e4a4fda93c39d595780cb40b161b310244b736a4", size = 95171956, upload-time = "2025-01-16T13:52:24.737Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/05/4d/53b30a2a3ac1f75f65a59eb29cf2ee7207ce64867db47036ad61743d5a23/opencv_python-4.11.0.86-cp37-abi3-macosx_13_0_arm64.whl", hash = "sha256:432f67c223f1dc2824f5e73cdfcd9db0efc8710647d4e813012195dc9122a52a", size = 37326322, upload-time = "2025-01-16T13:52:25.887Z" }, - { url = "https://files.pythonhosted.org/packages/3b/84/0a67490741867eacdfa37bc18df96e08a9d579583b419010d7f3da8ff503/opencv_python-4.11.0.86-cp37-abi3-macosx_13_0_x86_64.whl", hash = "sha256:9d05ef13d23fe97f575153558653e2d6e87103995d54e6a35db3f282fe1f9c66", size = 56723197, upload-time = "2025-01-16T13:55:21.222Z" }, - { url = "https://files.pythonhosted.org/packages/f3/bd/29c126788da65c1fb2b5fb621b7fed0ed5f9122aa22a0868c5e2c15c6d23/opencv_python-4.11.0.86-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1b92ae2c8852208817e6776ba1ea0d6b1e0a1b5431e971a2a0ddd2a8cc398202", size = 42230439, upload-time = "2025-01-16T13:51:35.822Z" }, - { url = "https://files.pythonhosted.org/packages/2c/8b/90eb44a40476fa0e71e05a0283947cfd74a5d36121a11d926ad6f3193cc4/opencv_python-4.11.0.86-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6b02611523803495003bd87362db3e1d2a0454a6a63025dc6658a9830570aa0d", size = 62986597, upload-time = "2025-01-16T13:52:08.836Z" }, - { url = "https://files.pythonhosted.org/packages/fb/d7/1d5941a9dde095468b288d989ff6539dd69cd429dbf1b9e839013d21b6f0/opencv_python-4.11.0.86-cp37-abi3-win32.whl", hash = "sha256:810549cb2a4aedaa84ad9a1c92fbfdfc14090e2749cedf2c1589ad8359aa169b", size = 29384337, upload-time = "2025-01-16T13:52:13.549Z" }, - { url = "https://files.pythonhosted.org/packages/a4/7d/f1c30a92854540bf789e9cd5dde7ef49bbe63f855b85a2e6b3db8135c591/opencv_python-4.11.0.86-cp37-abi3-win_amd64.whl", hash = "sha256:085ad9b77c18853ea66283e98affefe2de8cc4c1f43eda4c100cf9b2721142ec", size = 39488044, upload-time = "2025-01-16T13:52:21.928Z" }, -] - [[package]] name = "overrides" version = "7.7.0" @@ -2740,21 +2722,27 @@ wheels = [ [[package]] name = "pywin32" -version = "310" +version = "312" source = { registry = "https://pypi.org/simple" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/da/a5f38fffbba2fb99aa4aa905480ac4b8e83ca486659ac8c95bce47fb5276/pywin32-310-cp310-cp310-win32.whl", hash = "sha256:6dd97011efc8bf51d6793a82292419eba2c71cf8e7250cfac03bba284454abc1", size = 8848240, upload-time = "2025-03-17T00:55:46.783Z" }, - { url = "https://files.pythonhosted.org/packages/aa/fe/d873a773324fa565619ba555a82c9dabd677301720f3660a731a5d07e49a/pywin32-310-cp310-cp310-win_amd64.whl", hash = "sha256:c3e78706e4229b915a0821941a84e7ef420bf2b77e08c9dae3c76fd03fd2ae3d", size = 9601854, upload-time = "2025-03-17T00:55:48.783Z" }, - { url = "https://files.pythonhosted.org/packages/3c/84/1a8e3d7a15490d28a5d816efa229ecb4999cdc51a7c30dd8914f669093b8/pywin32-310-cp310-cp310-win_arm64.whl", hash = "sha256:33babed0cf0c92a6f94cc6cc13546ab24ee13e3e800e61ed87609ab91e4c8213", size = 8522963, upload-time = "2025-03-17T00:55:50.969Z" }, - { url = "https://files.pythonhosted.org/packages/f7/b1/68aa2986129fb1011dabbe95f0136f44509afaf072b12b8f815905a39f33/pywin32-310-cp311-cp311-win32.whl", hash = "sha256:1e765f9564e83011a63321bb9d27ec456a0ed90d3732c4b2e312b855365ed8bd", size = 8784284, upload-time = "2025-03-17T00:55:53.124Z" }, - { url = "https://files.pythonhosted.org/packages/b3/bd/d1592635992dd8db5bb8ace0551bc3a769de1ac8850200cfa517e72739fb/pywin32-310-cp311-cp311-win_amd64.whl", hash = "sha256:126298077a9d7c95c53823934f000599f66ec9296b09167810eb24875f32689c", size = 9520748, upload-time = "2025-03-17T00:55:55.203Z" }, - { url = "https://files.pythonhosted.org/packages/90/b1/ac8b1ffce6603849eb45a91cf126c0fa5431f186c2e768bf56889c46f51c/pywin32-310-cp311-cp311-win_arm64.whl", hash = "sha256:19ec5fc9b1d51c4350be7bb00760ffce46e6c95eaf2f0b2f1150657b1a43c582", size = 8455941, upload-time = "2025-03-17T00:55:57.048Z" }, - { url = "https://files.pythonhosted.org/packages/6b/ec/4fdbe47932f671d6e348474ea35ed94227fb5df56a7c30cbbb42cd396ed0/pywin32-310-cp312-cp312-win32.whl", hash = "sha256:8a75a5cc3893e83a108c05d82198880704c44bbaee4d06e442e471d3c9ea4f3d", size = 8796239, upload-time = "2025-03-17T00:55:58.807Z" }, - { url = "https://files.pythonhosted.org/packages/e3/e5/b0627f8bb84e06991bea89ad8153a9e50ace40b2e1195d68e9dff6b03d0f/pywin32-310-cp312-cp312-win_amd64.whl", hash = "sha256:bf5c397c9a9a19a6f62f3fb821fbf36cac08f03770056711f765ec1503972060", size = 9503839, upload-time = "2025-03-17T00:56:00.8Z" }, - { url = "https://files.pythonhosted.org/packages/1f/32/9ccf53748df72301a89713936645a664ec001abd35ecc8578beda593d37d/pywin32-310-cp312-cp312-win_arm64.whl", hash = "sha256:2349cc906eae872d0663d4d6290d13b90621eaf78964bb1578632ff20e152966", size = 8459470, upload-time = "2025-03-17T00:56:02.601Z" }, - { url = "https://files.pythonhosted.org/packages/1c/09/9c1b978ffc4ae53999e89c19c77ba882d9fce476729f23ef55211ea1c034/pywin32-310-cp313-cp313-win32.whl", hash = "sha256:5d241a659c496ada3253cd01cfaa779b048e90ce4b2b38cd44168ad555ce74ab", size = 8794384, upload-time = "2025-03-17T00:56:04.383Z" }, - { url = "https://files.pythonhosted.org/packages/45/3c/b4640f740ffebadd5d34df35fecba0e1cfef8fde9f3e594df91c28ad9b50/pywin32-310-cp313-cp313-win_amd64.whl", hash = "sha256:667827eb3a90208ddbdcc9e860c81bde63a135710e21e4cb3348968e4bd5249e", size = 9503039, upload-time = "2025-03-17T00:56:06.207Z" }, - { url = "https://files.pythonhosted.org/packages/b4/f4/f785020090fb050e7fb6d34b780f2231f302609dc964672f72bfaeb59a28/pywin32-310-cp313-cp313-win_arm64.whl", hash = "sha256:e308f831de771482b7cf692a1f308f8fca701b2d8f9dde6cc440c7da17e47b33", size = 8458152, upload-time = "2025-03-17T00:56:07.819Z" }, + { url = "https://files.pythonhosted.org/packages/fe/1b/9cfdeac80ee45bebbbcb31f1b7b99a0d81a1c72de48d837be984e0e88b1d/pywin32-312-cp310-cp310-win32.whl", hash = "sha256:772235332b5d1024c696f11cea1ae4be7930f0a8b894bb43db14e3f435f1ff7e", size = 6361387, upload-time = "2026-06-04T07:49:14.329Z" }, + { url = "https://files.pythonhosted.org/packages/33/b1/7afc96d041d982c27bc2df6f853d43f01fd273e3d39d04be3647ddeb533d/pywin32-312-cp310-cp310-win_amd64.whl", hash = "sha256:5dbc35d2b5320dc07f25fa31269cfb767471002b17de5eb067d03da68c7cb2db", size = 6926780, upload-time = "2026-06-04T07:49:16.881Z" }, + { url = "https://files.pythonhosted.org/packages/ce/3a/4140da9ad54108e517f4a16b2d83da3033e08662144623e1239587cb7db6/pywin32-312-cp310-cp310-win_arm64.whl", hash = "sha256:3020656e34f1cf7faeb7bccd2b84653a607c6ff0c55ada85e6487d61716deabd", size = 4307203, upload-time = "2026-06-04T07:49:18.993Z" }, + { url = "https://files.pythonhosted.org/packages/1f/f5/10a6e845a00fc5e7afd0a988b744f403d4d57162a28d160a093c4d9322f0/pywin32-312-cp311-cp311-win32.whl", hash = "sha256:17948aeadbdb091f0ced6ef0841620794e68327b94ee415571c1203594b7215c", size = 6362659, upload-time = "2026-06-04T07:49:21.349Z" }, + { url = "https://files.pythonhosted.org/packages/35/c4/dcd2d62b5944b6d5db53413a5899016ccd57ffcb7278f3f81655d25d2027/pywin32-312-cp311-cp311-win_amd64.whl", hash = "sha256:d11417d84412f859b722fad0841b3614459ed0047f7542d8362e77884f6b6e8a", size = 6928825, upload-time = "2026-06-04T07:49:23.934Z" }, + { url = "https://files.pythonhosted.org/packages/b7/56/3cbb433fe4501cdba2eb9040f56a4e1a8243faa4186b25295564d1a7a79d/pywin32-312-cp311-cp311-win_arm64.whl", hash = "sha256:b2200a054ca6d6625c4842fc56a4976a4b47f96b73dbe5538c3f813a80359f47", size = 6721875, upload-time = "2026-06-04T07:49:26.416Z" }, + { url = "https://files.pythonhosted.org/packages/83/ff/32aa7d2ed0ab12b323aaa64f9b75e6ad4f8fd09f9ccfc28c79414d46838d/pywin32-312-cp312-cp312-win32.whl", hash = "sha256:dab4f65ac9c4e48400a2a0530c46c3c579cd5905ecd11b80692373915269208b", size = 6371877, upload-time = "2026-06-04T07:49:28.836Z" }, + { url = "https://files.pythonhosted.org/packages/03/d9/77040d3b43df3f3be32ea289433d660d2727f5ba327bc73be835127d9d60/pywin32-312-cp312-cp312-win_amd64.whl", hash = "sha256:b457f6d628a47e8a7346ce22acb7e1a46a4a78b52e1d17e1af56871bd19a93bc", size = 6914841, upload-time = "2026-06-04T07:49:31.85Z" }, + { url = "https://files.pythonhosted.org/packages/e3/cc/7b1ec671775756020a0ee7f4feeaf3c568f0ab86bd3900088cf986937a92/pywin32-312-cp312-cp312-win_arm64.whl", hash = "sha256:6017c58e12f6809fbb0555b75df144c2922a9ffd18e4b9b5afa863b6c1a9d950", size = 6727901, upload-time = "2026-06-04T07:49:34.244Z" }, + { url = "https://files.pythonhosted.org/packages/2d/41/12fbfd7f36ed2146d8bc9de96c2741296bf0d490b98508496cff322e274c/pywin32-312-cp313-cp313-win32.whl", hash = "sha256:7a27df850933d16a8eabfbaeb73d52b273e2da667f80d70b01a89d1f6828d02c", size = 6370184, upload-time = "2026-06-04T07:49:36.253Z" }, + { url = "https://files.pythonhosted.org/packages/ba/db/36a78e3403099d31d9746d13fdcde5accc43c1155f375a34d15983a479a7/pywin32-312-cp313-cp313-win_amd64.whl", hash = "sha256:c53e878d15a1c44788082bfe712a905433473aa38f86375b7cf8b45e3acbaaf9", size = 6914298, upload-time = "2026-06-04T07:49:38.876Z" }, + { url = "https://files.pythonhosted.org/packages/84/37/c1697194092b76de9ed47ca124323f02c57ffc8a45c06f88a3d5acaf01eb/pywin32-312-cp313-cp313-win_arm64.whl", hash = "sha256:59aba5d5940842075343a5ddc6b11f1cdf0d1567fe745290359dfbcc7c2eb831", size = 6727640, upload-time = "2026-06-04T07:49:41.083Z" }, + { url = "https://files.pythonhosted.org/packages/fc/2b/1f3cded5822fd49c02f40544cbb5f58c7cfd6b1694869fd476cb6170ee97/pywin32-312-cp314-cp314-win32.whl", hash = "sha256:a77a90fbb6881238d2ca9c6fd797b25817f3768fe78d214a90137ff055a75f5b", size = 6468928, upload-time = "2026-06-04T07:49:43.188Z" }, + { url = "https://files.pythonhosted.org/packages/21/82/3bf86d2e2808902013132e1ce905a7da0da53790f3836c64bf44d55e24f3/pywin32-312-cp314-cp314-win_amd64.whl", hash = "sha256:a4dd3a848290ef724347b19f301045831d8e802fa4464f491b98b1e0a081432e", size = 7024157, upload-time = "2026-06-04T07:49:45.34Z" }, + { url = "https://files.pythonhosted.org/packages/a4/0e/73f6d6800b4f27655abd9e9f6aaeaefcddb2b946e4674efa2bab184a7f7b/pywin32-312-cp314-cp314-win_arm64.whl", hash = "sha256:9fce94568364e0155e6dfb781ac5d95903be8baf28670632beab1b523f300daa", size = 6839598, upload-time = "2026-06-04T07:49:47.613Z" }, + { url = "https://files.pythonhosted.org/packages/eb/61/caa39686032d2ebdd04ff0ab5cbe163126c0066d98e00c9018646e42393b/pywin32-312-cp315-cp315-win32.whl", hash = "sha256:5c1fbe4a937a73ae9297384a3da38518cbc694c68ad8a809b2e19acd350f03ed", size = 6471159, upload-time = "2026-06-04T07:49:50.035Z" }, + { url = "https://files.pythonhosted.org/packages/0f/cd/7e1de64a4a6f69c04214169657ccab0d93a670ea50e35eb8f489d7378249/pywin32-312-cp315-cp315-win_amd64.whl", hash = "sha256:c2f03a0f73f804a13c2735b99392b0cd426bb4f2c4d0178e5ac966a0f21618d5", size = 7025293, upload-time = "2026-06-04T07:49:54.857Z" }, + { url = "https://files.pythonhosted.org/packages/23/ed/4532e9388e65fa16b46776ef47ad631a64eda1631884488af707666350ed/pywin32-312-cp315-cp315-win_arm64.whl", hash = "sha256:a8597d28f267b39074aef51fa593530082b39cbe5a074226096857b1fed2dfb9", size = 6840337, upload-time = "2026-06-04T07:49:57.531Z" }, ] [[package]] @@ -3449,7 +3437,6 @@ dependencies = [ { name = "matplotlib" }, { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "opencv-python" }, { name = "pillow" }, { name = "pydeprecate" }, { name = "pyyaml" }, @@ -3502,7 +3489,6 @@ requires-dist = [ { name = "defusedxml", specifier = ">=0.7.1" }, { name = "matplotlib", specifier = ">=3.6" }, { name = "numpy", specifier = ">=1.21.2" }, - { name = "opencv-python", specifier = ">=4.5.5.64,<6" }, { name = "pandas", marker = "extra == 'metrics'", specifier = ">=2" }, { name = "pillow", specifier = ">=9.4" }, { name = "pydeprecate", specifier = ">=0.9,<0.11" },