From 25e879ec053753f9934ba32b7d53ec17c6d3ec13 Mon Sep 17 00:00:00 2001 From: Matt Van Horn Date: Tue, 21 Jul 2026 03:37:20 -0700 Subject: [PATCH] refactor: centralize geometry-aware dispatch for detection_area and detection_iou (#2374) * refactor: centralize geometry-aware dispatch for detection_area and detection_iou * fix(detection): centralize geometry-aware merge IoU * docs(detection): add code examples to geometry calculation docstrings * code: reuse count_mask_pixels; relocate geometry dispatch out of utils/ * docs: fix changelog framing and filter_detections.md wording * test: add edge-case coverage for geometry dispatch and merge chains * fix(tests): repair syntax-broken docstrings in geometry dispatch/merge tests * refactor(detection): make geometry dispatch module private --------- Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: jirka <6035284+Borda@users.noreply.github.com> Co-authored-by: Codex Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- docs/changelog.md | 1 + docs/how_to/filter_detections.md | 2 +- .../detection/_geometry_dispatch.py | 132 +++++++ src/supervision/detection/core.py | 26 +- tests/detection/test_core.py | 51 ++- tests/detection/test_geometry_dispatch.py | 361 ++++++++++++++++++ 6 files changed, 548 insertions(+), 25 deletions(-) create mode 100644 src/supervision/detection/_geometry_dispatch.py create mode 100644 tests/detection/test_geometry_dispatch.py diff --git a/docs/changelog.md b/docs/changelog.md index 8c333793..5d4f07fd 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -18,6 +18,7 @@ date_modified: 2026-07-17 - `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)). ### Fixed +- 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`. - 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. diff --git a/docs/how_to/filter_detections.md b/docs/how_to/filter_detections.md index 5eed784f..a8da8b3b 100644 --- a/docs/how_to/filter_detections.md +++ b/docs/how_to/filter_detections.md @@ -320,7 +320,7 @@ Use NumPy-style boolean indexing: `detections[detections.class_id == 0]` for cla ### How do I filter by bounding box area? -`detections[detections.area > 1000]` filters by pixel area. If masks are present, `detections.area` uses mask area; otherwise it uses bounding box area from `xyxy`. Use `detections.box_area` when you specifically need bounding box area. +`detections[detections.area > 1000]` filters by pixel area. If masks are present, `detections.area` uses mask area; otherwise, if oriented-box coordinates are present, it uses oriented polygon area; all remaining detections use bounding box area from `xyxy`. Use `detections.box_area` when you specifically need axis-aligned bounding box area. ### Can I filter by box aspect ratio or dimensions? diff --git a/src/supervision/detection/_geometry_dispatch.py b/src/supervision/detection/_geometry_dispatch.py new file mode 100644 index 00000000..b44303b1 --- /dev/null +++ b/src/supervision/detection/_geometry_dispatch.py @@ -0,0 +1,132 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, cast + +import numpy as np +import numpy.typing as npt + +from supervision.config import ORIENTED_BOX_COORDINATES +from supervision.detection.compact_mask import CompactMask +from supervision.detection.utils.boxes import obb_polygon_area +from supervision.detection.utils.iou_and_nms import ( + OverlapMetric, + box_iou_batch, + mask_iou_batch, + oriented_box_iou_batch, +) +from supervision.detection.utils.masks import count_mask_pixels + +if TYPE_CHECKING: + from supervision.detection.core import Detections + + +def detection_area(detections: Detections) -> npt.NDArray[np.generic]: + """ + Calculate detection areas using the richest geometry present. + + Selection order: + + 1. If ``mask`` is set, return the area of each mask. + 2. Else, if ``data[ORIENTED_BOX_COORDINATES]`` is set, return the area of + each oriented box. + 3. Otherwise, return the axis-aligned box area. + + Args: + detections: Detections whose geometry should be measured. + + Returns: + A 1-D array containing the area of each detection. + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.detection.core import Detections + >>> detections = Detections( + ... xyxy=np.array([[0, 0, 2, 3]], dtype=np.float32) + ... ) + >>> detection_area(detections) # doctest: +ELLIPSIS + array([6.], dtype=float32) + + ``` + """ + if detections.mask is not None: + if isinstance(detections.mask, CompactMask): + return detections.mask.area + return count_mask_pixels(detections.mask) + if ORIENTED_BOX_COORDINATES in detections.data: + return obb_polygon_area( + cast(npt.NDArray[np.number], detections.data[ORIENTED_BOX_COORDINATES]) + ) + return detections.box_area + + +def detection_iou( + detections_a: Detections, + detections_b: Detections, + overlap_metric: OverlapMetric | str = OverlapMetric.IOU, +) -> npt.NDArray[np.floating]: + """ + Calculate pairwise IoU using the richest geometry both operands share. + + Selection order: + + 1. If both operands have masks, use mask IoU. + 2. Else, if both operands have oriented-box coordinates, use OBB IoU. + 3. Otherwise, use axis-aligned box IoU. + + This is a **shared**-geometry dispatch, unlike `detection_area`'s + per-operand dispatch: if the two operands carry different kinds of + richer geometry (e.g. one has only a mask, the other only oriented-box + coordinates), neither is used and the axis-aligned box IoU is computed + instead. + + Args: + detections_a: First set of detections. + detections_b: Second set of detections. + overlap_metric: Metric used to compute the degree of overlap. + + Returns: + A matrix of pairwise overlaps with shape + ``(len(detections_a), len(detections_b))``. + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.detection.core import Detections + >>> detections = Detections( + ... xyxy=np.array([[0, 0, 2, 2]], dtype=np.float32) + ... ) + >>> detection_iou(detections, detections) # doctest: +ELLIPSIS + array([[1.]], dtype=float32) + + ``` + """ + overlap_metric = OverlapMetric.from_value(overlap_metric) + if detections_a.mask is not None and detections_b.mask is not None: + return mask_iou_batch( + detections_a.mask, + detections_b.mask, + overlap_metric=overlap_metric, + ) + + if ( + ORIENTED_BOX_COORDINATES in detections_a.data + and ORIENTED_BOX_COORDINATES in detections_b.data + ): + return oriented_box_iou_batch( + cast( + npt.NDArray[np.number], + detections_a.data[ORIENTED_BOX_COORDINATES], + ), + cast( + npt.NDArray[np.number], + detections_b.data[ORIENTED_BOX_COORDINATES], + ), + overlap_metric=overlap_metric, + ) + + return box_iou_batch( + detections_a.xyxy, + detections_b.xyxy, + overlap_metric=overlap_metric, + ) diff --git a/src/supervision/detection/core.py b/src/supervision/detection/core.py index 2e2df10a..75321ade 100644 --- a/src/supervision/detection/core.py +++ b/src/supervision/detection/core.py @@ -14,6 +14,7 @@ from supervision.config import ( CLASS_NAME_DATA_FIELD, ORIENTED_BOX_COORDINATES, ) +from supervision.detection._geometry_dispatch import detection_area, detection_iou from supervision.detection.compact_mask import CompactMask from supervision.detection.tools.transformers import ( process_transformers_detection_result, @@ -27,7 +28,6 @@ from supervision.detection.utils._typing import ( ) from supervision.detection.utils.boxes import ( _oriented_box_anchors, - obb_polygon_area, xyxyxyxy_to_xyxy, ) from supervision.detection.utils.converters import ( @@ -47,11 +47,9 @@ from supervision.detection.utils.internal import ( ) from supervision.detection.utils.iou_and_nms import ( OverlapMetric, - box_iou_batch, box_non_max_merge, box_non_max_suppression, box_soft_non_max_suppression, - mask_iou_batch, mask_non_max_merge, mask_non_max_suppression, mask_soft_non_max_suppression, @@ -60,7 +58,6 @@ from supervision.detection.utils.iou_and_nms import ( ) from supervision.detection.utils.masks import ( calculate_masks_centroids, - count_mask_pixels, ) from supervision.detection.vlm import ( LMM, @@ -2852,15 +2849,7 @@ class Detections: ``` """ - if self.mask is not None: - if isinstance(self.mask, CompactMask): - return self.mask.area - return count_mask_pixels(self.mask) - if ORIENTED_BOX_COORDINATES in self.data: - return obb_polygon_area( - cast(npt.NDArray[np.number], self.data[ORIENTED_BOX_COORDINATES]) - ) - return self.box_area + return detection_area(self) @property def box_area(self) -> npt.NDArray[np.generic]: @@ -3490,16 +3479,7 @@ def merge_inner_detections_objects( """ detections_1 = detections[0] for detections_2 in detections[1:]: - if detections_1.mask is not None and detections_2.mask is not None: - iou = mask_iou_batch(detections_1.mask, detections_2.mask, overlap_metric)[ - 0 - ] - else: - iou = box_iou_batch( - detections_1.xyxy, - detections_2.xyxy, - overlap_metric, - )[0] + iou = detection_iou(detections_1, detections_2, overlap_metric)[0] if iou < threshold: break detections_1 = merge_inner_detection_object_pair(detections_1, detections_2) diff --git a/tests/detection/test_core.py b/tests/detection/test_core.py index 858a1cee..9c43ff7b 100644 --- a/tests/detection/test_core.py +++ b/tests/detection/test_core.py @@ -11,9 +11,14 @@ from supervision.detection.core import ( _merge_detection_group, _merge_obb_corners, merge_inner_detection_object_pair, + merge_inner_detections_objects, ) from supervision.detection.utils.boxes import xyxyxyxy_to_xyxy -from supervision.detection.utils.iou_and_nms import OverlapMetric +from supervision.detection.utils.iou_and_nms import ( + OverlapMetric, + box_iou_batch, + oriented_box_iou_batch, +) from supervision.geometry.core import Position from supervision.utils.internal import SupervisionWarnings from tests.helpers import _create_detections @@ -1611,6 +1616,50 @@ class TestDetectionsObbDispatch: assert len(result) == 2 + def test_deprecated_merge_uses_obb_iou_before_merging(self) -> None: + """Deprecated inner merge keeps separated OBBs despite overlapping envelopes.""" + quad_a = _rotated_rect(50, 50, 100, 10, 45) + quad_b = _rotated_rect(58, 50, 100, 10, -45) + detections_a = _make_obb_detections([quad_a], [0.9], [0]) + detections_b = _make_obb_detections([quad_b], [0.8], [0]) + + obb_iou = oriented_box_iou_batch( + detections_a.data[ORIENTED_BOX_COORDINATES], + detections_b.data[ORIENTED_BOX_COORDINATES], + )[0, 0] + aabb_iou = box_iou_batch(detections_a.xyxy, detections_b.xyxy)[0, 0] + + assert obb_iou < 0.5 + assert aabb_iou > 0.5 + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = merge_inner_detections_objects( + [detections_a, detections_b], threshold=0.5 + ) + + np.testing.assert_array_equal(result.xyxy, detections_a.xyxy) + + def test_deprecated_merge_chain_across_three_with_changing_geometry(self) -> None: + """N>2 chain: merge OBB pair, fall back to box IoU for AABB-only detection.""" + quad_a = _rotated_rect(50, 50, 20, 10, 10) + quad_b = _rotated_rect(52, 50, 20, 10, -10) + detections_a = _make_obb_detections([quad_a], [0.9], [0]) + detections_b = _make_obb_detections([quad_b], [0.85], [0]) + detections_c = Detections( + xyxy=np.array([[35, 40, 65, 60]], dtype=np.float32), + confidence=np.array([0.7], dtype=np.float32), + class_id=np.array([0], dtype=int), + ) + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = merge_inner_detections_objects( + [detections_a, detections_b, detections_c], threshold=0.3 + ) + + assert len(result) == 1 + np.testing.assert_array_equal(result.class_id, np.array([0])) + @pytest.mark.parametrize( "method", [ diff --git a/tests/detection/test_geometry_dispatch.py b/tests/detection/test_geometry_dispatch.py new file mode 100644 index 00000000..5fed80a4 --- /dev/null +++ b/tests/detection/test_geometry_dispatch.py @@ -0,0 +1,361 @@ +from __future__ import annotations + +import numpy as np +import numpy.typing as npt +import pytest + +from supervision.config import ORIENTED_BOX_COORDINATES +from supervision.detection._geometry_dispatch import detection_area, detection_iou +from supervision.detection.compact_mask import CompactMask +from supervision.detection.core import Detections +from supervision.detection.utils.boxes import xyxyxyxy_to_xyxy +from supervision.detection.utils.iou_and_nms import ( + OverlapMetric, + box_iou_batch, + mask_iou_batch, + oriented_box_iou_batch, +) +from supervision.detection.utils.masks import count_mask_pixels + + +def _rotated_rect( + center_x: float, center_y: float, width: float, height: float, angle_deg: float +) -> npt.NDArray[np.float32]: + """Return four corners of a rotated rectangle in clockwise order.""" + half_w = width / 2.0 + half_h = height / 2.0 + corners = np.array( + [ + [-half_w, -half_h], + [half_w, -half_h], + [half_w, half_h], + [-half_w, half_h], + ], + dtype=np.float32, + ) + angle = np.deg2rad(angle_deg) + rotation = np.array( + [[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]], + dtype=np.float32, + ) + center = np.array([center_x, center_y], dtype=np.float32) + return (corners @ rotation.T + center).astype(np.float32) + + +def _detections_from_quads( + quads: list[npt.NDArray[np.float32]], + xyxy: npt.NDArray[np.float32] | None = None, +) -> Detections: + """Build Detections carrying OBB coordinates.""" + corners = np.stack(quads).astype(np.float32) + if xyxy is None: + xyxy = xyxyxyxy_to_xyxy(corners).astype(np.float32) + return Detections( + xyxy=xyxy, + data={ORIENTED_BOX_COORDINATES: corners}, + ) + + +def _full_image_xyxy( + count: int, image_shape: tuple[int, int] +) -> npt.NDArray[np.float32]: + """Return full-image xyxy boxes for CompactMask construction.""" + image_height, image_width = image_shape + xyxy = np.array([0, 0, image_width - 1, image_height - 1], dtype=np.float32) + return np.tile(xyxy, (count, 1)) + + +class TestDetectionArea: + """Tests for geometry-aware area dispatch.""" + + def test_returns_mask_pixel_area(self) -> None: + """Masks take precedence over OBBs and AABB envelopes.""" + mask = np.zeros((1, 20, 20), dtype=bool) + mask[0, 2:5, 3:8] = True + quad = _rotated_rect(10, 10, 12, 6, 30) + detections = Detections( + xyxy=np.array([[0, 0, 20, 20]], dtype=np.float32), + mask=mask, + data={ORIENTED_BOX_COORDINATES: quad[np.newaxis]}, + ) + + area = detection_area(detections) + + np.testing.assert_array_equal(area, np.array([15], dtype=np.int64)) + + def test_dense_mask_branch_reuses_count_mask_pixels(self) -> None: + """Dense-mask area delegates to count_mask_pixels for the shared fast path.""" + mask = np.zeros((3, 10, 10), dtype=bool) + mask[0, :2, :2] = True + mask[1, :3, :3] = True + detections = Detections( + xyxy=np.tile(np.array([[0, 0, 9, 9]], dtype=np.float32), (3, 1)), + mask=mask, + ) + + area = detection_area(detections) + + np.testing.assert_array_equal(area, count_mask_pixels(mask)) + assert area.dtype == np.int64 + + def test_returns_compact_mask_area(self) -> None: + """CompactMask inputs use CompactMask.area without dense materialisation.""" + masks = np.zeros((2, 12, 12), dtype=bool) + masks[0, 1:4, 2:7] = True + masks[1, 4:9, 4:10] = True + compact_mask = CompactMask.from_dense( + masks=masks, + xyxy=_full_image_xyxy(len(masks), masks.shape[1:]), + image_shape=masks.shape[1:], + ) + detections = Detections( + xyxy=_full_image_xyxy(len(masks), masks.shape[1:]), + mask=compact_mask, + ) + + area = detection_area(detections) + + np.testing.assert_array_equal(area, compact_mask.area) + + def test_returns_oriented_box_area_when_present(self) -> None: + """OBB area is used instead of the larger rotated AABB envelope.""" + quad = _rotated_rect(50, 50, 20, 10, 45) + detections = _detections_from_quads([quad]) + + area = detection_area(detections) + + np.testing.assert_allclose(area, np.array([200.0])) + assert detections.box_area[0] > area[0] + + def test_returns_box_area_when_no_richer_geometry_is_present(self) -> None: + """AABB area is the fallback when masks and OBB corners are absent.""" + detections = Detections( + xyxy=np.array([[0, 0, 20, 10], [3, 4, 8, 12]], dtype=np.float32) + ) + + area = detection_area(detections) + + np.testing.assert_array_equal(area, detections.box_area) + + @pytest.mark.parametrize( + "detections", + [ + pytest.param( + Detections(xyxy=np.empty((0, 4), dtype=np.float32)), + id="empty-aabb", + ), + pytest.param( + Detections( + xyxy=np.empty((0, 4), dtype=np.float32), + mask=np.empty((0, 8, 8), dtype=bool), + ), + id="empty-mask", + ), + pytest.param( + Detections( + xyxy=np.empty((0, 4), dtype=np.float32), + data={ + ORIENTED_BOX_COORDINATES: np.empty((0, 4, 2), dtype=np.float32) + }, + ), + id="empty-obb", + ), + pytest.param( + Detections( + xyxy=np.empty((0, 4), dtype=np.float32), + mask=CompactMask.from_dense( + masks=np.empty((0, 8, 8), dtype=bool), + xyxy=np.empty((0, 4), dtype=np.float32), + image_shape=(8, 8), + ), + ), + id="empty-compact-mask", + ), + ], + ) + def test_returns_empty_array_for_empty_detections( + self, detections: Detections + ) -> None: + """Empty Detections return an empty area array for every geometry branch.""" + area = detection_area(detections) + + assert area.shape == (0,) + + @pytest.mark.parametrize( + "detections", + [ + pytest.param( + Detections( + xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32), + mask=np.ones((1, 3, 4), dtype=bool), + ), + id="mask", + ), + pytest.param( + _detections_from_quads([_rotated_rect(50, 50, 20, 10, 30)]), + id="obb", + ), + pytest.param( + Detections(xyxy=np.array([[0, 0, 10, 5]], dtype=np.float32)), + id="aabb", + ), + ], + ) + def test_matches_detections_area_property(self, detections: Detections) -> None: + """Detections.area delegates to the shared geometry dispatch helper.""" + area = detection_area(detections) + + np.testing.assert_array_equal(area, detections.area) + + def test_keeps_oriented_area_invariant_when_envelope_changes(self) -> None: + """Rotating an OBB preserves exact OBB area while changing envelope area.""" + axis_aligned = _detections_from_quads([_rotated_rect(30, 30, 20, 10, 0)]) + rotated = _detections_from_quads([_rotated_rect(30, 30, 20, 10, 45)]) + + areas = np.concatenate([detection_area(axis_aligned), detection_area(rotated)]) + + np.testing.assert_allclose(areas, np.array([200.0, 200.0])) + assert axis_aligned.box_area[0] != pytest.approx(rotated.box_area[0]) + + def test_mask_area_handles_rotated_arrays(self) -> None: + """Mask area counts true pixels consistently after array rotation.""" + mask = np.zeros((80, 80), dtype=bool) + mask[30:50, 25:55] = 1 + rotated_mask = np.rot90(mask) + detections = Detections( + xyxy=np.array([[0, 0, 79, 79], [0, 0, 79, 79]], dtype=np.float32), + mask=np.stack([mask, rotated_mask]), + ) + + area = detection_area(detections) + + np.testing.assert_array_equal(area, np.array([600, 600], dtype=np.int64)) + + def test_degenerate_collinear_obb_has_zero_area(self) -> None: + """A collinear (zero-area) OBB reports 0 rather than a well-formed area.""" + collinear = np.array([[0, 0], [5, 0], [10, 0], [15, 0]], dtype=np.float32) + detections = _detections_from_quads([collinear]) + + area = detection_area(detections) + + np.testing.assert_allclose(area, np.array([0.0])) + + +class TestDetectionIou: + """Tests for geometry-aware IoU dispatch.""" + + def test_returns_mask_iou_when_both_operands_have_masks(self) -> None: + """Mask IoU is used when both operands carry masks.""" + masks_a = np.zeros((1, 16, 16), dtype=bool) + masks_b = np.zeros((1, 16, 16), dtype=bool) + masks_a[0, 2:10, 2:10] = True + masks_b[0, 6:14, 6:14] = True + detections_a = Detections( + xyxy=np.array([[0, 0, 16, 16]], dtype=np.float32), + mask=masks_a, + ) + detections_b = Detections( + xyxy=np.array([[0, 0, 16, 16]], dtype=np.float32), + mask=masks_b, + ) + + iou = detection_iou(detections_a, detections_b) + + np.testing.assert_allclose(iou, mask_iou_batch(masks_a, masks_b)) + + def test_returns_oriented_box_iou_when_both_operands_have_obbs(self) -> None: + """OBB IoU is used even when AABB envelopes are identical.""" + square = np.array([[0, 0], [10, 0], [10, 10], [0, 10]], dtype=np.float32) + diamond = np.array([[5, 0], [10, 5], [5, 10], [0, 5]], dtype=np.float32) + shared_xyxy = np.array([[0, 0, 10, 10]], dtype=np.float32) + detections_a = _detections_from_quads([square], xyxy=shared_xyxy) + detections_b = _detections_from_quads([diamond], xyxy=shared_xyxy) + + iou = detection_iou(detections_a, detections_b) + + np.testing.assert_allclose( + iou, + oriented_box_iou_batch(square[np.newaxis], diamond[np.newaxis]), + ) + assert iou[0, 0] < box_iou_batch(shared_xyxy, shared_xyxy)[0, 0] + + def test_degenerate_collinear_obb_yields_zero_iou_without_error(self) -> None: + """A zero-area (collinear) OBB denominator yields 0 IoU, not NaN or a crash.""" + collinear = np.array([[0, 0], [5, 0], [10, 0], [15, 0]], dtype=np.float32) + square = np.array([[0, 0], [10, 0], [10, 10], [0, 10]], dtype=np.float32) + detections_a = _detections_from_quads([collinear]) + detections_b = _detections_from_quads([square]) + + iou = detection_iou(detections_a, detections_b) + + assert not np.isnan(iou).any() + np.testing.assert_allclose(iou, np.array([[0.0]])) + + def test_returns_box_iou_when_no_richer_geometry_is_present(self) -> None: + """AABB IoU is the fallback when neither operand carries richer geometry.""" + detections_a = Detections( + xyxy=np.array([[0, 0, 10, 10], [20, 20, 30, 30]], dtype=np.float32) + ) + detections_b = Detections(xyxy=np.array([[5, 5, 15, 15]], dtype=np.float32)) + + iou = detection_iou(detections_a, detections_b, OverlapMetric.IOS) + + np.testing.assert_allclose( + iou, + box_iou_batch(detections_a.xyxy, detections_b.xyxy, OverlapMetric.IOS), + ) + + def test_returns_empty_matrix_for_empty_detections(self) -> None: + """Empty Detections return an empty pairwise IoU matrix.""" + empty = Detections(xyxy=np.empty((0, 4), dtype=np.float32)) + non_empty = Detections(xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32)) + + iou = detection_iou(empty, non_empty) + + assert iou.shape == (0, 1) + + @pytest.mark.parametrize( + ("left_kind", "right_kind", "expected_geometry"), + [ + pytest.param("mask", "obb", "box", id="mask-vs-obb-falls-back-to-box"), + pytest.param("mask", "aabb", "box", id="mask-vs-aabb-falls-back-to-box"), + pytest.param("obb", "aabb", "box", id="obb-vs-aabb-falls-back-to-box"), + pytest.param("compact", "mask", "mask", id="compact-vs-dense-uses-mask"), + pytest.param( + "compact", "compact", "mask", id="compact-vs-compact-uses-mask" + ), + ], + ) + def test_mixed_geometry_dispatch_uses_shared_geometry_only_when_available( + self, left_kind: str, right_kind: str, expected_geometry: str + ) -> None: + """Mixed geometry uses AABB fallback unless both operands carry masks.""" + image_shape = (16, 16) + mask = np.zeros((1, *image_shape), dtype=bool) + mask[0, 2:10, 2:10] = True + xyxy = _full_image_xyxy(1, image_shape) + compact_mask = CompactMask.from_dense( + masks=mask, xyxy=xyxy, image_shape=image_shape + ) + obb = _detections_from_quads( + [np.array([[0, 0], [15, 0], [15, 15], [0, 15]], dtype=np.float32)], + xyxy=xyxy, + ) + detections_by_kind = { + "mask": Detections(xyxy=xyxy, mask=mask), + "compact": Detections(xyxy=xyxy, mask=compact_mask), + "obb": obb, + "aabb": Detections(xyxy=xyxy), + } + detections_left = detections_by_kind[left_kind] + detections_right = detections_by_kind[right_kind] + + result = detection_iou(detections_left, detections_right) + + if expected_geometry == "mask": + assert detections_left.mask is not None + assert detections_right.mask is not None + expected = mask_iou_batch(detections_left.mask, detections_right.mask) + else: + expected = box_iou_batch(detections_left.xyxy, detections_right.xyxy) + np.testing.assert_allclose(result, expected)