π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(geometry): Convention blocks for bbox/boxes (batch 4b: geometry operations) (#4245)
Dmytro Mishkin1eea5835bcfc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7cfc3cbc6..a345dbba3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+* Documented bbox/Boxes geometry-operation conventions and added executable pins for transforms,+ NMS, padding, clipping, and area filtering, including known unbatched-input limitations. (#4245)+* Documentation pages now provide search-specific titles and descriptions, canonical tutorial links, and acanonicalized redirect from the retired highlighted-features page. (#4226)diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.pyindex ee681385d..5a9f1e676 100644--- a/kornia/geometry/bbox.py+++ b/kornia/geometry/bbox.py@@ -538,21 +538,26 @@ def transform_bbox() -> torch.Tensor:r"""Apply a transformation matrix to a box or batch of boxes.+ Convention:+ ``xyxy`` and ``xywh`` inputs are transformed through endpoint pairs. Coordinate+ restoration sorts their endpoints after a flip; polygon vertices retain their+ transformed cyclic order.+Args:- trans_mat: The transformation matrix to be applied with a shape of :math:`(3, 3)`- or batched as :math:`(B, 3, 3)`.+ trans_mat: The transformation matrix to be applied, with supported shape :math:`(B, 3, 3)`.+ For boxes shaped :math:`(N, 4)`, ``B`` is one or ``N``. For boxes shaped+ :math:`(B, N, 4)` or :math:`(B, N, 4, 2)`, it is one or the boxes' ``B``.boxes: The boxes to be transformed with a common shape of :math:`(N, 4)` or batched as :math:`(B, N, 4)`, thepolygon shape of :math:`(B, N, 4, 2)` is also supported.mode: The format in which the boxes are provided. If set to 'xyxy' the boxes are assumed to be in the format``xmin, ymin, xmax, ymax``. If set to 'xywh' the boxes are assumed to be in the format``xmin, ymin, width, height``- restore_coordinates: In case the boxes are flipped, adding a post processing step to restore the- coordinates to a valid bounding box. Enabled by default (``None`` behaves as ``True``); pass- ``False`` to keep the raw transformed corners (the pre-2022 behavior, which yields invalid- boxes under flips).+ restore_coordinates: Reorder endpoints after a flipped ``xyxy`` or ``xywh`` transform.+ Enabled by default (``None`` behaves as ``True``); pass ``False`` to preserve raw+ transformed endpoints. Polygon vertices retain their transformed order.Returns:- The set of transformed points in the specified mode+ The transformed boxes in the specified mode."""if not isinstance(mode, str):@@ -589,13 +594,24 @@ def transform_bbox(def nms(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float) -> torch.Tensor:"""Perform non-maxima suppression (NMS) on tensor of bounding boxes according to the intersection-over-union (IoU).+ Convention:+ Boxes use exclusive ``xyxy`` coordinates. IoU area is+ ``(x_2 - x_1) * (y_2 - y_1)`` and the result contains kept indices rather+ than a boolean mask.+Args:- boxes: tensor containing the encoded bounding boxes with the shape :math:`(N, (x_1, y_1, x_2, y_2))`.+ boxes: tensor containing exclusive ``xyxy`` bounding boxes with shape+ :math:`(N, 4)`, ordered as ``(x_1, y_1, x_2, y_2)``.scores: tensor containing the scores associated to each bounding box with shape :math:`(N,)`.- iou_threshold: the throshold to discard the overlapping boxes.+ iou_threshold: the threshold to discard the overlapping boxes.- Return:- A tensor mask with the indices to keep from the input set of boxes and scores.+ Returns:+ Indices of the boxes kept from the input set, ordered by descending score.++ .. warning::+ This differs from the inclusive coordinate arithmetic used by several other+ :mod:`kornia.geometry.bbox` operations and is documented in+ `#4008 <https://github.com/kornia/kornia/issues/4008>`_.Example:>>> boxes = torch.tensor([diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.pyindex 0f9c5b2ae..f56f4531b 100644--- a/kornia/geometry/boxes.py+++ b/kornia/geometry/boxes.py@@ -263,6 +263,10 @@ class Boxes:`#4012 <https://github.com/kornia/kornia/issues/4012>`_. With ``validate_boxes=True``, vertex modes remainunvalidated, and ``'vertices'`` also subtracts one from fixed vertex positions, potentially deforming theinput rather than rejecting it; this is tracked in `#4177 <https://github.com/kornia/kornia/issues/4177>`_.+ The unimplemented ``trim``, ``translate(method='fast')``, and tuple-bound ``clamp`` paths are tracked in+ `#4017 <https://github.com/kornia/kornia/issues/4017>`_. The pad, unpad, and clamp operations fail for+ unbatched containers even though the class accepts :math:`(N, 4, 2)` data; this is tracked in+ `#4244 <https://github.com/kornia/kornia/issues/4244>`_."""@@ -443,10 +447,22 @@ class Boxes:return objdef pad(self, padding_size: torch.Tensor) -> Boxes:- """Pad a bounding box.+ """Pad every box in place.++ See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.++ ``padding_size`` is ordered as ``(left, right, top, bottom)``. Only+ ``left`` and ``top`` change the coordinate origin; this method returns+ ``self`` after adding those two values to every vertex. This operation+ supports only batched :math:`(B, N, 4, 2)` containers.++ Note:+ Padded :class:`~kornia.augmentation.RandomCrop` uses this method+ and therefore requires batched boxes.Args:- padding_size: (B, 4)+ padding_size: Per-batch padding in ``(left, right, top, bottom)``+ order, shaped :math:`(B, 4)`."""if not (len(padding_size.shape) == 2 and padding_size.size(1) == 4):@@ -456,10 +472,18 @@ class Boxes:return selfdef unpad(self, padding_size: torch.Tensor) -> Boxes:- """Pad a bounding box.+ """Undo :meth:`pad` in place.++ See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.++ ``padding_size`` is ordered as ``(left, right, top, bottom)``. Only+ ``left`` and ``top`` change the coordinate origin; this method returns+ ``self`` after subtracting those two values from every vertex. This+ operation supports only batched :math:`(B, N, 4, 2)` containers.Args:- padding_size: (B, 4)+ padding_size: Per-batch padding in ``(left, right, top, bottom)``+ order, shaped :math:`(B, 4)`."""if not (len(padding_size.shape) == 2 and padding_size.size(1) == 4):@@ -476,10 +500,18 @@ class Boxes:) -> Boxes:"""Clamp every box vertex inside per-image coordinate limits.+ See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.++ Convention:+ Bounds must be tensors with one ``(x, y)`` pair per batch element.+ Every vertex is clamped independently, so a box wholly outside the+ bounds collapses onto the nearest boundary instead of being removed.+ This operation supports only batched :math:`(B, N, 4, 2)` containers.+Coordinates below ``topleft`` are raised to the lower bound andcoordinates above ``botright`` are lowered to the upper bound. The- implementation expects tensor bounds with one ``(x, y)`` pair per batch- element.+ implementation accepts only tensor bounds with one ``(x, y)`` pair per+ batch element.Args:topleft: Tensor of shape :math:`(B, 2)` containing the minimum@@ -518,44 +550,32 @@ class Boxes:return objdef trim(self, correspondence_preserve: bool = False, inplace: bool = False) -> Boxes:- """Trim out zero padded boxes.-- Given box arrangements of shape :math:`(4, 4, Box)`:+ """Raise because trimming padded boxes is not implemented.- == === == === == === == === ==- -- Box -- Box -- Box -- Box --- -- 0 -- 0 -- Box -- Box --- -- 0 -- Box -- 0 -- 0 --- -- 0 -- 0 -- 0 -- 0 --- == === == === == === == === ==-- Nothing will change if correspondence_preserve is True. Only pure zero layers will be removed, resulting in- shape :math:`(4, 3, Box)`:+ See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.- == === == === == === == === ==- -- Box -- Box -- Box -- Box --- -- 0 -- 0 -- Box -- Box --- -- 0 -- Box -- 0 -- 0 --- == === == === == === == === ==+ Args:+ correspondence_preserve: Reserved for a future implementation.+ inplace: Reserved for a future implementation.- Otherwise, you will get :math:`(4, 2, Box)`:+ Raises:+ NotImplementedError: Always.- == === == === == === == === ==- -- Box -- Box -- Box -- Box --- -- 0 -- Box -- Box -- Box --- == === == === == === == === =="""raise NotImplementedErrordef filter_boxes_by_area(self, min_area: Optional[float] = None, max_area: Optional[float] = None, inplace: bool = False) -> Boxes:- """Remove boxes whose polygon area is outside the requested range.+ """Zero boxes whose polygon area is outside the requested range.++ See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.The box area is computed from its four vertices. Boxes smaller than``min_area`` or larger than ``max_area`` are not dropped from thetensor; their coordinates are replaced with zeros so the original batch- and box dimensions stay unchanged.+ and box dimensions stay unchanged. See :meth:`compute_area` for the+ area convention used by the thresholds.Args:min_area: Optional lower inclusive area threshold. Boxes with area@@ -586,7 +606,24 @@ class Boxes:return objdef compute_area(self) -> torch.Tensor:- """Return :math:`(B, N)`."""+ """Compute polygon area with the shoelace formula.++ See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.++ Convention:+ For axis-aligned boxes, the shoelace result over stored inclusive+ vertices is ``(width - 1) * (height - 1)``, while the inclusive+ terms from :meth:`get_boxes_shape` multiply to ``width * height``.+ Rotated or otherwise non-axis-aligned quadrilaterals use their+ polygon area instead.++ .. warning::+ The differing area conventions are tracked in+ `#4010 <https://github.com/kornia/kornia/issues/4010>`_.++ Returns:+ Area for each box, shaped :math:`(N,)` or :math:`(B, N)`.+ """coords = self._data.view((-1, 4, 2)) if self._data.ndim == 4 else self._data# calculate centroid of the boxcentroid = coords.mean(dim=1, keepdim=True)@@ -834,6 +871,8 @@ class Boxes:def transform_boxes(self, M: torch.Tensor, inplace: bool = False) -> Boxes:r"""Apply a transformation matrix to the 2D boxes.+ See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.+Args:M: The transformation matrix to be applied, shape of :math:`(3, 3)` or :math:`(B, 3, 3)`.inplace: do transform in-place and return self.@@ -855,12 +894,31 @@ class Boxes:return objdef transform_boxes_(self, M: torch.Tensor) -> Boxes:- """Inplace version of :func:`Boxes.transform_boxes`."""+ """Apply :meth:`transform_boxes` in place and return ``self``.++ See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.++ Convention:+ The in-place operation rebinds this object's internal tensor to a+ transformed result for nonempty containers. A tensor reference+ obtained from :attr:`data` before that call therefore remains+ unchanged and no longer aliases the container's data. Empty+ containers retain their original tensor reference.++ Returns:+ This :class:`Boxes` object after the transformation.+ """return self.transform_boxes(M, inplace=True)def translate(self, size: torch.Tensor, method: str = "warp", inplace: bool = False) -> Boxes:"""Translate boxes by the provided size.+ See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.++ ``size`` supplies one ``(x, y)`` translation per batch item. Only the+ ``"warp"`` method is implemented; ``"fast"`` raises+ :class:`NotImplementedError`.+Args:size: translate size for x, y direction, shape of :math:`(B, 2)`.method: "warp" or "fast".diff --git a/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.pyindex 296c86250..f4a8fdae8 100644--- a/tests/geometry/test_bbox.py+++ b/tests/geometry/test_bbox.py@@ -225,6 +225,21 @@ class TestBbox2D(BaseTester):class TestTransformBoxes2D(BaseTester):+ def test_convention_transform_bbox_restores_vector_endpoints(self, device, dtype):+ # Under a horizontal flip, restoration sorts xyxy coordinates while+ # polygon vertices retain their transformed cyclic order.+ matrix = torch.tensor([[[-1.0, 0.0, 10.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ vector = torch.tensor([[1.0, 1.0, 3.0, 2.0]], device=device, dtype=dtype)+ polygon = torch.tensor([[[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]]], device=device, dtype=dtype)++ self.assert_close(+ transform_bbox(matrix, vector), torch.tensor([[7.0, 1.0, 9.0, 2.0]], device=device, dtype=dtype)+ )+ self.assert_close(+ transform_bbox(matrix, polygon),+ torch.tensor([[[[9.0, 1.0], [7.0, 1.0], [7.0, 2.0], [9.0, 2.0]]]], device=device, dtype=dtype),+ )+def test_transform_boxes(self, device, dtype):boxes = torch.tensor([[139.2640, 103.0150, 397.3120, 410.5225]], device=device, dtype=dtype)@@ -434,6 +449,16 @@ class TestBbox3D(BaseTester):class TestNMS(BaseTester):+ def test_convention_nms_uses_exclusive_xyxy_iou_4008(self, device, dtype):+ # The boxes overlap by 1 / 4 under exclusive xyxy arithmetic. At 0.3, NMS+ # keeps both; inclusive corner arithmetic would compute 4 / 9 and suppress+ # the lower-scored box. The literal also pins descending-score index order.+ boxes = torch.tensor([[0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 2.0, 2.0]], device=device, dtype=dtype)+ scores = torch.tensor([0.8, 0.9], device=device, dtype=dtype)++ actual = nms(boxes, scores, iou_threshold=0.3)+ self.assert_close(actual, torch.tensor([1, 0], device=device, dtype=torch.long), atol=0.0, rtol=0.0)+def test_empty(self, device):boxes = torch.empty((0, 4), device=device)scores = torch.empty((0,), device=device)diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.pyindex dd49e15ed..22a42f073 100644--- a/tests/geometry/test_boxes.py+++ b/tests/geometry/test_boxes.py@@ -27,6 +27,17 @@ from kornia.geometry.boxes import Boxes, Boxes3D, VideoBoxesfrom testing.base import BaseTester+def _unbatched_geometry_data(device: torch.device, dtype: torch.dtype) -> torch.Tensor:+ return torch.tensor(+ [+ [[1.0, 2.0], [4.0, 2.0], [4.0, 5.0], [1.0, 5.0]],+ [[8.0, 0.0], [10.0, 0.0], [10.0, 1.0], [8.0, 1.0]],+ ],+ device=device,+ dtype=dtype,+ )++class TestBoxes2D(BaseTester):def test_convention_from_tensor_xyxy_stores_inclusive_vertices_in_tl_tr_br_bl_order(self, device, dtype):# Convention pin: Boxes stores four inclusive (x, y) vertices in clockwise@@ -584,7 +595,6 @@ class TestBoxes2D(BaseTester):self.assert_close(actual, expected)def test_compute_area(self):-# Rectanglebox_1 = [[0.0, 0.0], [100.0, 0.0], [100.0, 50.0], [0.0, 50.0]]# Trapezoid@@ -621,6 +631,212 @@ class TestBoxes2D(BaseTester):for computed_area, expected_area in zip(flattened_computed_areas_w_batch, expected_values))+ def test_wart_compute_area_is_shoelace_of_inclusive_vertices_4010(self, device, dtype):+ # Wart pin for kornia#4010: compute_area applies shoelace to the stored+ # inclusive vertices. A valid exclusive 2-by-1 box collapses to a line,+ # and a raw four-by-three rectangle has area six rather than the twelve+ # reported by get_boxes_shape. These are current values, not a contract.+ two_by_one = Boxes.from_tensor(torch.tensor([[[1.0, 1.0, 3.0, 2.0]]], device=device, dtype=dtype), mode="xyxy")+ four_by_three = Boxes(+ torch.tensor([[[1.0, 1.0], [4.0, 1.0], [4.0, 3.0], [1.0, 3.0]]], device=device, dtype=dtype)+ )+ self.assert_close(+ two_by_one.compute_area(), torch.tensor([[0.0]], device=device, dtype=dtype), atol=0.0, rtol=0.0+ )+ self.assert_close(+ four_by_three.compute_area(), torch.tensor([6.0], device=device, dtype=dtype), atol=0.0, rtol=0.0+ )++ @pytest.mark.xfail(strict=True, reason="kornia#4010: compute_area disagrees with get_boxes_shape")+ def test_convention_compute_area_matches_get_boxes_shape_product_4010(self, device, dtype):+ # The intended contract is that area agrees with the container's own+ # height and width terms. A repair must XPASS this strict xfail.+ boxes = Boxes.from_tensor(torch.tensor([[[1.0, 1.0, 3.0, 2.0]]], device=device, dtype=dtype), mode="xyxy")+ heights, widths = boxes.get_boxes_shape()+ self.assert_close(boxes.compute_area(), heights * widths)++ def test_convention_pad_and_unpad_use_left_right_top_bottom_in_place(self, device, dtype):+ boxes = Boxes.from_tensor(torch.tensor([[[1.0, 2.0, 5.0, 4.0]]], device=device, dtype=dtype), mode="xyxy")+ original = boxes.data.clone()+ padding = torch.tensor([[10.0, 99.0, 20.0, 88.0]], device=device, dtype=dtype)+ result = boxes.pad(padding)+ assert result is boxes+ expected = original + torch.tensor([10.0, 20.0], device=device, dtype=dtype)+ self.assert_close(boxes.data, expected, atol=0.0, rtol=0.0)+ assert boxes.unpad(padding) is boxes+ self.assert_close(boxes.data, original, atol=0.0, rtol=0.0)++ def test_wart_clamp_tuple_bounds_and_outside_box_behavior_4017(self, device, dtype):+ # Wart pin for kornia#4017: tuple bounds are advertised but unsupported;+ # tensor bounds clamp every vertex, collapsing a wholly outside box.+ boxes = Boxes.from_tensor(+ torch.tensor([[[8.0, 9.0, 10.0, 11.0]]], device=device, dtype=dtype),+ mode="xyxy",+ )+ with pytest.raises(NotImplementedError):+ boxes.clamp((0, 0), (5, 5))+ clamped = boxes.clamp(+ torch.tensor([[0.0, 0.0]], device=device, dtype=dtype),+ torch.tensor([[5.0, 5.0]], device=device, dtype=dtype),+ )+ expected = torch.full((1, 1, 4, 2), 5.0, device=device, dtype=dtype)+ self.assert_close(clamped.data, expected, atol=0.0, rtol=0.0)+ self.assert_close(+ boxes.data,+ Boxes.from_tensor(torch.tensor([[[8.0, 9.0, 10.0, 11.0]]], device=device, dtype=dtype), mode="xyxy").data,+ atol=0.0,+ rtol=0.0,+ )++ def test_wart_trim_and_fast_translate_are_unimplemented_4017(self, device, dtype):+ # Wart pin for kornia#4017: both documented entry points raise instead+ # of implementing their advertised operations.+ boxes = Boxes.from_tensor(torch.tensor([[[1.0, 2.0, 5.0, 4.0]]], device=device, dtype=dtype), mode="xyxy")+ with pytest.raises(NotImplementedError):+ boxes.trim()+ with pytest.raises(NotImplementedError):+ boxes.translate(torch.tensor([[1.0, 2.0]], device=device, dtype=dtype), method="fast")++ def test_convention_transform_boxes_in_place_rebinds_data(self, device, dtype):+ # transform_boxes leaves its input unchanged by default. Its in-place+ # twin returns self but rebinds storage, leaving prior data references stale.+ boxes = Boxes.from_tensor(torch.tensor([[[1.0, 2.0, 5.0, 4.0]]], device=device, dtype=dtype), mode="xyxy")+ original = boxes.data+ matrix = torch.tensor([[[1.0, 0.0, 10.0], [0.0, 1.0, 20.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ transformed = boxes.transform_boxes(matrix)+ assert transformed is not boxes+ self.assert_close(transformed.data, original + torch.tensor([10.0, 20.0], device=device, dtype=dtype))+ self.assert_close(boxes.data, original, atol=0.0, rtol=0.0)+ assert boxes.transform_boxes_(matrix) is boxes+ assert boxes.data.data_ptr() != original.data_ptr()+ self.assert_close(+ original,+ Boxes.from_tensor(torch.tensor([[[1.0, 2.0, 5.0, 4.0]]], device=device, dtype=dtype), mode="xyxy").data,+ atol=0.0,+ rtol=0.0,+ )++ def test_convention_translate_warp_uses_batched_xy_displacements(self, device, dtype):+ # Convention pin: each row of size supplies an (x, y) displacement for+ # its batch item. Asymmetric values catch an accidental axis swap.+ boxes = Boxes.from_tensor(+ torch.tensor([[[1.0, 2.0, 5.0, 4.0]], [[10.0, 20.0, 14.0, 23.0]]], device=device, dtype=dtype),+ mode="xyxy",+ )+ translated = boxes.translate(torch.tensor([[3.0, -7.0], [-5.0, 11.0]], device=device, dtype=dtype))+ expected = torch.tensor(+ [+ [[[4.0, -5.0], [7.0, -5.0], [7.0, -4.0], [4.0, -4.0]]],+ [[[5.0, 31.0], [8.0, 31.0], [8.0, 33.0], [5.0, 33.0]]],+ ],+ device=device,+ dtype=dtype,+ )+ self.assert_close(translated.data, expected, atol=0.0, rtol=0.0)+ assert translated is not boxes++ def test_wart_filter_boxes_by_area_zeroes_small_boxes_4010(self, device, dtype):+ # Wart pin for kornia#4010: filtering acts on compute_area, so the+ # valid two-by-one box with shoelace area zero is zeroed, not removed.+ boxes = Boxes.from_tensor(torch.tensor([[[1.0, 1.0, 3.0, 2.0]]], device=device, dtype=dtype), mode="xyxy")+ filtered = boxes.filter_boxes_by_area(min_area=1.0)+ assert filtered is not boxes+ self.assert_close(filtered.data, torch.zeros_like(boxes.data), atol=0.0, rtol=0.0)+ assert filtered.data.shape == boxes.data.shape+ assert not torch.equal(boxes.data, torch.zeros_like(boxes.data))++ def test_convention_filter_boxes_by_area_maximum_zeroes_in_place(self, device, dtype):+ # The shoelace areas are 2 and 8. Equal lower/upper bounds retain the+ # first box, pinning both inclusive endpoints; the larger box is zeroed.+ # In-place filtering returns the original wrapper and keeps its shape.+ boxes = Boxes(+ torch.tensor(+ [+ [+ [[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]],+ [[1.0, 1.0], [5.0, 1.0], [5.0, 3.0], [1.0, 3.0]],+ ]+ ],+ device=device,+ dtype=dtype,+ )+ )+ first = boxes.data[:, :1].clone()+ assert boxes.filter_boxes_by_area(min_area=2.0, max_area=2.0, inplace=True) is boxes+ self.assert_close(boxes.data[:, :1], first, atol=0.0, rtol=0.0)+ self.assert_close(boxes.data[:, 1:], torch.zeros_like(boxes.data[:, 1:]), atol=0.0, rtol=0.0)++ @pytest.mark.parametrize("operation, inplace", [("pad", None), ("unpad", None), ("clamp", False), ("clamp", True)])+ @pytest.mark.parametrize("num_boxes", [1, 2])+ def test_wart_unbatched_geometry_operations_raise_4244(self, operation, inplace, num_boxes, device, dtype):+ # Wart pin for kornia#4244: the documented unbatched (N, 4, 2) form+ # fails although its singleton-batched counterpart works. Clamp reaches+ # indexing failure for one box and broadcasting failure for two boxes.+ boxes = Boxes(_unbatched_geometry_data(device, dtype)[:num_boxes])+ if operation == "clamp":+ with pytest.raises((RuntimeError, IndexError)):+ boxes.clamp(+ torch.tensor([[2.0, 3.0]], device=device, dtype=dtype),+ torch.tensor([[6.0, 7.0]], device=device, dtype=dtype),+ inplace=inplace,+ )+ else:+ with pytest.raises((RuntimeError, IndexError)):+ getattr(boxes, operation)(torch.tensor([[10.0, 99.0, 20.0, 88.0]], device=device, dtype=dtype))++ @pytest.mark.parametrize("operation, inplace", [("pad", None), ("unpad", None), ("clamp", False), ("clamp", True)])+ @pytest.mark.parametrize("num_boxes", [1, 2])+ @pytest.mark.xfail(+ strict=True,+ raises=(RuntimeError, IndexError),+ reason="kornia#4244: unbatched geometry operations do not match singleton batches",+ )+ def test_convention_unbatched_geometry_operations_match_singleton_batch_4244(+ self, operation, inplace, num_boxes, device, dtype+ ):+ data = _unbatched_geometry_data(device, dtype)[:num_boxes]+ batched = Boxes(data[None].clone())+ unbatched = Boxes(data.clone())+ if operation == "clamp":+ limits = (+ torch.tensor([[2.0, 3.0]], device=device, dtype=dtype),+ torch.tensor([[6.0, 7.0]], device=device, dtype=dtype),+ )+ try:+ expected = batched.clamp(*limits, inplace=inplace)+ except (RuntimeError, IndexError) as error:+ raise AssertionError("The supported singleton-batch reference must succeed") from error+ assert (expected is batched) is inplace+ actual = unbatched.clamp(*limits, inplace=inplace)+ assert (actual is unbatched) is inplace+ if not inplace:+ self.assert_close(unbatched.data, data, atol=0.0, rtol=0.0)+ else:+ padding = torch.tensor([[10.0, 99.0, 20.0, 88.0]], device=device, dtype=dtype)+ try:+ expected = getattr(batched, operation)(padding)+ except (RuntimeError, IndexError) as error:+ raise AssertionError("The supported singleton-batch reference must succeed") from error+ assert expected is batched+ actual = getattr(unbatched, operation)(padding)+ assert actual is unbatched+ self.assert_close(actual.data, expected.data.squeeze(0), atol=0.0, rtol=0.0)++ @pytest.mark.parametrize("batched", [False, True])+ @pytest.mark.parametrize("inplace", [False, True])+ def test_wart_transform_boxes_empty_copy_aliases_input_4020(self, batched, inplace, device, dtype):+ # Wart pin for tracking issue #4020: transforming an empty container+ # preserves its tensor storage. The non-inplace wrapper is new but+ # aliases the input data; the in-place wrapper remains self.+ data = torch.empty((1, 0, 4, 2) if batched else (0, 4, 2), device=device, dtype=dtype)+ boxes = Boxes(data)+ original = boxes.data+ matrix = torch.eye(3, device=device, dtype=dtype)+ transformed = boxes.transform_boxes_(matrix) if inplace else boxes.transform_boxes(matrix)+ assert (transformed is boxes) is inplace+ assert transformed.data is original+ assert transformed.data.shape == original.shape+class TestTransformBoxes2D(BaseTester):def test_transform_boxes(self, device, dtype):