π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(geometry): Convention blocks for bbox/boxes (batch 4a: representation core) (#4060)
Dmytro Mishkinee6b713f6224
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.pyindex 21caf4b93..f30ac0f1b 100644--- a/kornia/geometry/bbox.py+++ b/kornia/geometry/bbox.py@@ -38,12 +38,33 @@ __all__ = [def validate_bbox(boxes: torch.Tensor) -> bool:- """Validate if a 2D bounding box usable or not. This function checks if the boxes are rectangular or not.+ """Validate whether a 2D box has matching top and bottom edge vectors.++ Convention:+ Vertices use inclusive coordinates in clockwise top-left, top-right, bottom-right, bottom-left order.+ The function accepts :math:`(B, 4, 2)` tensors and :math:`(B, N, 4, 2)` tensors. It returns ``False`` for an+ invalid shape or when corresponding components of the top and bottom edge vectors differ by more than+ ``1e-4``; it does not raise for those inputs. It does not check right angles, positive area, or clockwise+ direction. A parallelogram whose+ vertices follow a cyclic order passes, including cyclic rotations, either direction, rotated rectangles,+ and zero-area boxes; other vertex relabelings can fail. The inclusive ``+1`` terms, tracked in+ `#3934 <https://github.com/kornia/kornia/issues/3934>`_, cancel in exact arithmetic, but finite-precision+ rounding can make the result differ from exclusive arithmetic, particularly for low-precision dtypes.++ .. warning::+ Rank-4 input is flattened with ``view``. A stride layout whose leading dimensions cannot be flattened this+ way raises ``RuntimeError`` instead of returning a boolean. This wart is tracked in+ `#4174 <https://github.com/kornia/kornia/issues/4174>`_.++ .. warning::+ :func:`validate_bbox3d` raises ``AssertionError`` where this function returns ``False``. That+ inconsistency is tracked in `#4013 <https://github.com/kornia/kornia/issues/4013>`_.Args:boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape- of Bx4x2, where each box is defined in the following ``clockwise`` order: top-left, top-right, bottom-right,- bottom-left. The coordinates must be in the x, y order.+ of :math:`(B, 4, 2)` or view-compatible :math:`(B, N, 4, 2)`, where each box is defined in the+ following ``clockwise`` order: top-left, top-right, bottom-right, bottom-left. The coordinates must be in+ the x, y order."""if not (len(boxes.shape) in [3, 4] and boxes.shape[-2:] == torch.Size([4, 2])):@@ -112,14 +133,35 @@ def validate_bbox3d(boxes: torch.Tensor) -> bool:def infer_bbox_shape(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:r"""Auto-infer the output sizes for the given 2D bounding boxes.+ Convention:+ Vertices use inclusive coordinates in clockwise top-left, top-right, bottom-right, bottom-left order.+ The returned tuple is ``(heights, widths)``, in that order. Both extents are read from fixed vertex+ indices, as ``width = boxes[:, 1, 0] - boxes[:, 0, 0] + 1`` and+ ``height = boxes[:, 2, 1] - boxes[:, 0, 1] + 1``, rather than from a ``maximum - minimum`` reduction.+ The two agree for an axis-aligned box in the documented order; for any other vertex order, including the+ rotated quadrilaterals that :func:`transform_bbox` produces for polygon input, they can diverge and the+ result can be negative.+ :meth:`kornia.geometry.boxes.Boxes.get_boxes_shape` is reduction based and does not share that behavior.+ The fixed-index reading also lets zero-width boxes emitted by :func:`bbox_generator` report width ``0``+ rather than ``2`` under a reduction; :class:`~kornia.augmentation.RandomCutMixV2` relies on that behavior.++ .. warning::+ The inclusive ``+1`` arithmetic differs from torchvision, COCO, and albumentations and is tracked in+ `#3934 <https://github.com/kornia/kornia/issues/3934>`_.++ .. warning::+ Rank-4 input is not validated. The fixed indices then read boxes instead of vertices, so fewer than three+ boxes per batch raise ``IndexError`` and three or more return wrongly shaped values. This wart is tracked+ in `#4180 <https://github.com/kornia/kornia/issues/4180>`_.+Args:- boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape- of Bx4x2, where each box is defined in the following ``clockwise`` order: top-left, top-right, bottom-right,- bottom-left. The coordinates must be in the x, y order.+ boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have shape+ :math:`(N, 4, 2)`, where each box is defined in the following ``clockwise`` order: top-left, top-right,+ bottom-right, bottom-left. The coordinates must be in the x, y order.Returns:- - Bounding box heights, shape of :math:`(B,)`.- - Boundingbox widths, shape of :math:`(B,)`.+ - Bounding box heights, shape of :math:`(N,)`.+ - Bounding box widths, shape of :math:`(N,)`.Example:>>> boxes = torch.tensor([[diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.pyindex 65b5c963e..c2d511f9a 100644--- a/kornia/geometry/boxes.py+++ b/kornia/geometry/boxes.py@@ -192,14 +192,78 @@ class Boxes:raise_if_not_floating_point: flag to control floating point casting behaviour when `boxes` is not afloating point tensor. True to raise an error when `boxes` isn't a floating point tensor, Falseto cast to float.- mode: the box format of the input boxes.-- Note:- **2D boxes format** is defined as a floating data type tensor of shape ``Nx4x2`` or ``BxNx4x2``- where each box is a `quadrilateral <https://en.wikipedia.org/wiki/Quadrilateral>`_ defined by it's- 4 vertices coordinates (A, B, C, D). Coordinates must be in ``x, y`` order. The height and width of- a box is defined as ``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``. Examples of- `quadrilaterals <https://en.wikipedia.org/wiki/Quadrilateral>`_ are rectangles, rhombus and trapezoids.+ mode: Representation label reused as the default output mode by :meth:`to_tensor`. The constructor does not+ convert ``boxes``; use :meth:`from_tensor` to import another representation.++ Convention:+ - A box is a quadrilateral of four floating-point ``(x, y)`` vertices, stored as :math:`(N, 4, 2)` or+ :math:`(B, N, 4, 2)` data. Axis-aligned boxes are built in clockwise top-left, top-right,+ bottom-right, bottom-left order, but the vertices stay arbitrary: :meth:`transform_boxes` produces+ rotated quadrilaterals. :meth:`compute_area` sorts vertices by angle about their arithmetic centroid+ before applying the shoelace formula, so it assumes a convex quadrilateral and uses an exclusive area+ convention that can disagree with :meth:`get_boxes_shape` and :meth:`to_mask`.+ - The stored form is inclusive (``'vertices_plus'``): ``width = xmax - xmin + 1``. The exclusive+ ``'xyxy'``, ``'xywh'``, and ``'vertices'`` modes convert to this form in :meth:`from_tensor` and back+ in :meth:`to_tensor`. The constructor converts nothing and stores ``mode`` as a label. For exclusive+ vertex data ``d``, ``Boxes(d, mode='vertices').to_tensor()`` applies export offsets to unconverted data,+ while ``Boxes.from_tensor(d, mode='vertices')`` imports it before export; the round-trip conditions and+ limitations are described next.+ - An axis-aligned box in the documented vertex order whose extent is at least one unit per axis+ round-trips exactly in its own mode when every intermediate conversion result is exactly representable+ in the tensor dtype. A sub-unit extent does not: the inclusive ``- 1`` inverts the stored quadrilateral,+ so normalized ``[0, 1]`` boxes with a sub-unit span on either axis are silently corrupted by the three+ converting modes.+ The ``'xyxy_plus'`` mode is unaffected because its ``+ 1`` cancels the ``- 1``;+ ``'vertices_plus'`` applies no offset at all.+ - :meth:`to_tensor` reduces the stored vertices with ``amin``/``amax``, so every export is an+ axis-aligned bounding box. It is lossy for rotated boxes, and ``to_tensor('vertices_plus')`` is+ therefore not the identity on :attr:`data`.+ - :meth:`get_boxes_shape` returns ``(heights, widths)`` in that order, with exactly the values from+ ``to_tensor('xywh', as_padded_sequence=True)``. For a list-backed object this includes its padding+ entries, which report as 1-by-1 boxes under the inclusive ``+1`` convention even though an ordinary+ :meth:`to_tensor` export trims them.+ - :func:`~kornia.geometry.bbox.infer_bbox_shape`, :func:`~kornia.geometry.bbox.bbox_to_mask`,+ :func:`~kornia.geometry.bbox.validate_bbox`, and :func:`~kornia.geometry.bbox.nms` have no mode argument,+ but the module does not use one convention throughout. :func:`~kornia.geometry.bbox.infer_bbox_shape`+ adds one per axis and+ :func:`~kornia.geometry.bbox.bbox_to_mask` fills through the bottom-right vertex's row and column, so+ both read their input as inclusive: pass them the ``'vertices_plus'`` export rather than+ ``'vertices'``, which they read as one pixel larger per axis. Both consumers take unbatched+ :math:`(N, 4, 2)` input and neither detects a batched one, so index or flatten a batched+ :math:`(B, N, 4, 2)` export before passing it; see+ `#4180 <https://github.com/kornia/kornia/issues/4180>`_.+ :func:`~kornia.geometry.bbox.validate_bbox` is invariant in exact arithmetic, because its ``+1``+ terms cancel;+ :func:`~kornia.geometry.bbox.nms` computes exclusive areas, and+ :func:`~kornia.geometry.bbox.transform_bbox` converts ``'xywh'`` with the exclusive+ ``xmax = xmin + width``.+ - With ``validate_boxes=True``, the ``'xy*'`` modes reject non-positive extents measured in that mode's+ convention.+ - The constructor rejects an integer tensor unless ``raise_if_not_floating_point=False``. A list input is+ padded into a tensor of its *first* element's dtype before that check, so a mixed-dtype list is accepted+ or rejected by its first box alone and the remaining boxes are cast to that dtype. For a single tensor,+ :meth:`from_tensor` silently casts integer input to ``float32``. For a list, it converts each element+ independently and then pads into the first converted element's dtype, recasting the remaining elements.+ - :meth:`merge` concatenates batched boxes along the box axis, while :meth:`index_put` replaces selected+ coordinates. Both methods are non-mutating by default. :meth:`merge` is currently unsafe for unbatched+ and list-backed objects because it respectively concatenates vertices and preserves stale padding metadata.++ .. warning::+ The inclusive ``+1`` arithmetic differs from torchvision, COCO, and albumentations and is tracked as a+ coordinated repair in `#3934 <https://github.com/kornia/kornia/issues/3934>`_. The sub-unit conversion+ corruption is `#4061 <https://github.com/kornia/kornia/issues/4061>`_, the cross-module export trap is+ `#4009 <https://github.com/kornia/kornia/issues/4009>`_, the exclusive :meth:`compute_area` convention is+ `#4010 <https://github.com/kornia/kornia/issues/4010>`_, and the exclusive+ :func:`~kornia.geometry.bbox.nms` convention is+ `#4008 <https://github.com/kornia/kornia/issues/4008>`_. The differing ``width``/``height`` argument order+ of :func:`~kornia.geometry.bbox.bbox_to_mask` and :meth:`to_mask` is tracked in+ `#4014 <https://github.com/kornia/kornia/issues/4014>`_. Unbatched and list-backed :meth:`merge` are tracked+ in `#4168 <https://github.com/kornia/kornia/issues/4168>`_ and+ `#4175 <https://github.com/kornia/kornia/issues/4175>`_, respectively. The integer-input policy split+ between the constructor and :meth:`from_tensor` is+ `#4012 <https://github.com/kornia/kornia/issues/4012>`_. With ``validate_boxes=True``, vertex modes remain+ unvalidated, and ``'vertices'`` also subtracts one from fixed vertex positions, potentially deforming the+ input rather than rejecting it; this is tracked in `#4177 <https://github.com/kornia/kornia/issues/4177>`_."""@@ -259,6 +323,8 @@ class Boxes:def get_boxes_shape(self) -> tuple[torch.Tensor, torch.Tensor]:r"""Compute boxes heights and widths.+ See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.+Returns:- Boxes heights, shape of :math:`(N,)` or :math:`(B,N)`.- Boxes widths, shape of :math:`(N,)` or :math:`(B,N)`.@@ -277,6 +343,8 @@ class Boxes:def merge(self, boxes: Boxes, inplace: bool = False) -> Boxes:"""Merge boxes.+ See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.+Say, current instance holds :math:`(B, N, 4, 2)` and the incoming boxes holds :math:`(B, M, 4, 2)`,the merge results in :math:`(B, N + M, 4, 2)`.@@ -302,6 +370,8 @@ class Boxes:) -> Boxes:"""Write box coordinates at selected tensor indices.+ See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.+This mirrors :meth:`torch.Tensor.index_put_` for the internalquadrilateral tensor. It is useful when a subset of boxes in a batchmust be replaced while keeping the :class:`Boxes` wrapper and metadata.@@ -501,31 +571,30 @@ class Boxes:) -> Boxes:r"""Create :class:`Boxes` from boxes stored in another format.- Args:- boxes: 2D boxes, shape of :math:`(N, 4)`, :math:`(B, N, 4)`, :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`.- mode: The format in which the boxes are provided.- validate_boxes: Check if boxes are valid. Default is True.+ See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.- * 'xyxy': boxes are assumed to be in the format ``xmin, ymin, xmax, ymax`` where ``width = xmax - xmin``- and ``height = ymax - ymin``. With shape :math:`(N, 4)`, :math:`(B, N, 4)`.- * 'xyxy_plus': similar to 'xyxy' mode but where box width and length are defined as- ``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``.- With shape :math:`(N, 4)`, :math:`(B, N, 4)`.- * 'xywh': boxes are assumed to be in the format ``xmin, ymin, width, height`` where- ``width = xmax - xmin`` and ``height = ymax - ymin``. With shape :math:`(N, 4)`, :math:`(B, N, 4)`.+ Args:+ boxes: 2D boxes, shape of :math:`(N, 4)`, :math:`(B, N, 4)`, :math:`(N, 4, 2)` or+ :math:`(B, N, 4, 2)`, or a list of :math:`(N, 4)` or :math:`(N, 4, 2)` tensors matching ``mode``.+ mode: The format in which the boxes are provided:++ * 'xyxy': ``xmin, ymin, xmax, ymax`` with exclusive extent. With shape :math:`(N, 4)`,+ :math:`(B, N, 4)`.+ * 'xyxy_plus': ``xmin, ymin, xmax, ymax`` with inclusive extent. With shape :math:`(N, 4)`,+ :math:`(B, N, 4)`.+ * 'xywh': ``xmin, ymin, width, height`` with exclusive extent. With shape :math:`(N, 4)`,+ :math:`(B, N, 4)`.* 'vertices': boxes are defined by their vertices points in the following ``clockwise`` order:- *top-left, top-right, bottom-right, bottom-left*. Vertices coordinates are in (x,y) order. Finally,- box width and height are defined as ``width = xmax - xmin`` and ``height = ymax - ymin``.- With shape :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`.- * 'vertices_plus': similar to 'vertices' mode but where box width and length are defined as- ``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``. ymin + 1``.- With shape :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`.+ *top-left, top-right, bottom-right, bottom-left*. Vertices coordinates are in (x,y) order. This is+ the exclusive input form. With shape :math:`(N, 4, 2)`, :math:`(B, N, 4, 2)`.+ * 'vertices_plus': the inclusive stored vertex form. With shape :math:`(N, 4, 2)`,+ :math:`(B, N, 4, 2)`.- validate_boxes: check if boxes are valid rectangles or not. Valid rectangles are those with width- and height >= 1 (>= 2 when mode ends with '_plus' suffix).+ validate_boxes: Check extents for the ``'xy*'`` modes in each mode's convention. This flag has no+ validation effect for vertex modes; see the warning on :class:`~kornia.geometry.boxes.Boxes`.Returns:- :class:`Boxes` class containing the original `boxes` in the format specified by ``mode``.+ :class:`Boxes` containing the converted inclusive vertex representation.Examples:>>> boxes_xyxy = torch.as_tensor([[0, 3, 1, 4], [5, 1, 8, 4]])@@ -555,29 +624,38 @@ class Boxes:) -> torch.Tensor | list[torch.Tensor]:r"""Cast :class:`Boxes` to a tensor.- ``mode`` controls which 2D boxes format should be use to represent boxes in the tensor.+ See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.++ ``mode`` selects the output representation. ``'xyxy'``, ``'xywh'``, and ``'vertices'`` are exclusive+ exports; the ``'_plus'`` variants are inclusive. Every mode exports the axis-aligned bounds of the+ stored vertices, reduced with ``amin``/``amax``, so the export is lossy for rotated boxes:+ ``to_tensor('vertices_plus')`` does not return :attr:`data` unchanged after a :meth:`transform_boxes`+ call that rotates, shears, or otherwise reorders the vertices. A quarter turn keeps the box+ axis-aligned and still yields an export that differs from :attr:`data`, because the reduction+ re-canonicalizes the vertex order.Args:- mode: the output box format. It could be:+ mode: the output box format, or ``None`` to reuse :attr:`mode`. That attribute depends on the+ construction path: the constructor defaults to ``'vertices_plus'``, while :meth:`from_tensor`+ records the mode its input was given in. It could be:- * 'xyxy': boxes are defined as ``xmin, ymin, xmax, ymax`` where ``width = xmax - xmin`` and- ``height = ymax - ymin``.- * 'xyxy_plus': similar to 'xyxy' mode but where box width and length are defined as- ``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``.- * 'xywh': boxes are defined as ``xmin, ymin, width, height`` where ``width = xmax - xmin``- and ``height = ymax - ymin``.+ * 'xyxy': ``xmin, ymin, xmax, ymax`` with exclusive extent.+ * 'xyxy_plus': ``xmin, ymin, xmax, ymax`` with inclusive extent.+ * 'xywh': ``xmin, ymin, width, height`` with exclusive extent.* 'vertices': boxes are defined by their vertices points in the following ``clockwise`` order:- *top-left, top-right, bottom-right, bottom-left*. Vertices coordinates are in (x,y) order. Finally,- box width and height are defined as ``width = xmax - xmin`` and ``height = ymax - ymin``.- * 'vertices_plus': similar to 'vertices' mode but where box width and length are defined as- ``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``. ymin + 1``.- as_padded_sequence: whether to keep the pads for a list of boxes. This parameter is only valid- if the boxes are from a box list whilst `from_tensor`.+ *top-left, top-right, bottom-right, bottom-left*. Vertices coordinates are in (x,y) order. This is+ the exclusive export form.+ * 'vertices_plus': the inclusive stored vertex form.+ as_padded_sequence: If this object was created from a list, return its padded tensor rather than a list+ of tensors trimmed to their original lengths. The padded values follow the selected output mode.+ Indexing with ``[]`` drops the list metadata, so a sliced object always returns the padded tensor;+ see `#4179 <https://github.com/kornia/kornia/issues/4179>`_.Returns:- Boxes tensor in the ``mode`` format. The shape depends with the ``mode`` value:+ Boxes tensor in the ``mode`` format, or a list of tensors when the object was created from a list and+ ``as_padded_sequence=False``. The tensor shape depends on the ``mode`` value:- * 'vertices' or 'verticies_plus': :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`.+ * 'vertices' or 'vertices_plus': :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`.* Any other value: :math:`(N, 4)` or :math:`(B, N, 4)`.Examples:@@ -1102,12 +1180,12 @@ class Boxes3D:Returns:3D Boxes tensor in the ``mode`` format. The shape depends with the ``mode`` value:- * 'vertices' or 'verticies_plus': :math:`(N, 8, 3)` or :math:`(B, N, 8, 3)`.+ * 'vertices' or 'vertices_plus': :math:`(N, 8, 3)` or :math:`(B, N, 8, 3)`.* Any other value: :math:`(N, 6)` or :math:`(B, N, 6)`.Note:It is currently non-differentiable due to a bug. See github issue- `#1304 <https://github.com/kornia/kornia/issues/1396>`_.+ `#1396 <https://github.com/kornia/kornia/issues/1396>`_.Examples:>>> boxes_xyzxyz = torch.as_tensor([[0, 3, 6, 1, 4, 8], [5, 1, 3, 8, 4, 9]])diff --git a/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.pyindex a7dc066f6..7aaf635b3 100644--- a/tests/geometry/test_bbox.py+++ b/tests/geometry/test_bbox.py@@ -20,6 +20,7 @@ import torchimport korniafrom kornia.geometry.bbox import (+ bbox_generator,bbox_generator3d,infer_bbox_shape,infer_bbox_shape3d,@@ -33,6 +34,119 @@ from testing.base import BaseTesterclass TestBbox2D(BaseTester):+ def test_wart_infer_bbox_shape_is_inclusive_3934(self, device, dtype):+ # Wart pin for kornia#3934: a raw box spanning x=1..4 and y=1..2 reports+ # (height, width) = (2, 4) because infer_bbox_shape adds one on both axes.+ # The non-square extents also pin the (heights, widths) return order.+ boxes = torch.tensor([[[1.0, 1.0], [4.0, 1.0], [4.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)+ height, width = infer_bbox_shape(boxes)+ self.assert_close(height, torch.tensor([2.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)+ self.assert_close(width, torch.tensor([4.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)++ def test_convention_infer_bbox_shape_reads_fixed_vertex_indices(self, device, dtype):+ # Convention pin: the extents come from fixed vertex indices, not from a+ # maximum - minimum reduction. Swapping the top-left and top-right vertices in+ # x therefore yields a negative width, where max - min + 1 would give 5.+ # The -3 is 1 - 5 + 1; the inclusive offset is tracked in kornia#3934.+ boxes = torch.tensor([[[5.0, 2.0], [1.0, 2.0], [1.0, 3.0], [5.0, 3.0]]], device=device, dtype=dtype)+ height, width = infer_bbox_shape(boxes)+ self.assert_close(height, torch.tensor([2.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)+ self.assert_close(width, torch.tensor([-3.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)++ def test_convention_infer_bbox_shape_preserves_generated_zero_extent(self, device, dtype):+ # bbox_generator represents a zero width by placing the top-right vertex one+ # unit left of the top-left vertex. RandomCutMixV2 relies on the fixed-index+ # reading recovering width 0; a maximum - minimum reduction would return 2.+ # The recovered zero depends on the inclusive +1 tracked in kornia#3934.+ x_start = torch.tensor([3.0], device=device, dtype=dtype)+ y_start = torch.tensor([4.0], device=device, dtype=dtype)+ boxes = bbox_generator(x_start, y_start, torch.zeros_like(x_start), torch.full_like(y_start, 5.0))+ height, width = infer_bbox_shape(boxes)+ self.assert_close(height, torch.tensor([5.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)+ self.assert_close(width, torch.tensor([0.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)++ def test_wart_infer_bbox_shape_rank4_is_not_validated_4180(self, device, dtype):+ # Wart pin for kornia#4180: rank-4 input is read at fixed box indices instead+ # of vertex indices. Fewer than three boxes raise, while three or more return+ # extents of shape (B, 2) built from the wrong vertices.+ with pytest.raises(IndexError):+ infer_bbox_shape(torch.zeros(1, 2, 4, 2, device=device, dtype=dtype))++ boxes = torch.arange(24, device=device, dtype=dtype).reshape(1, 3, 4, 2)+ height, width = infer_bbox_shape(boxes)+ self.assert_close(height, torch.tensor([[17.0, 17.0]], device=device, dtype=dtype), atol=0.0, rtol=0.0)+ self.assert_close(width, torch.tensor([[9.0, 9.0]], device=device, dtype=dtype), atol=0.0, rtol=0.0)++ def test_convention_validate_bbox_checks_parallelograms_and_accepts_contiguous_batched_boxes(self, device, dtype):+ # The validator only compares the top and bottom edge vectors at fixed vertex+ # indices. A cyclically ordered sheared parallelogram and rotated rectangle+ # both return True, while the trapezoid fails. The leading dimensions also+ # pin contiguous rank-4 input.+ sheared_parallelogram = torch.tensor(+ [[[[0.0, 0.0], [2.0, 0.0], [3.0, 1.0], [1.0, 1.0]]]], device=device, dtype=dtype+ )+ assert validate_bbox(sheared_parallelogram) is True++ rotated_rectangle = torch.tensor(+ [[[[0.0, 0.0], [3.0, 4.0], [-1.0, 7.0], [-4.0, 3.0]]]], device=device, dtype=dtype+ )+ assert validate_bbox(rotated_rectangle) is True++ relabeled_rectangle = torch.tensor(+ [[[[0.0, 0.0], [3.0, 0.0], [0.0, 2.0], [3.0, 2.0]]]], device=device, dtype=dtype+ )+ assert validate_bbox(relabeled_rectangle) is False++ trapezoid = torch.tensor([[[[0.0, 0.0], [10.0, 0.0], [10.0, 5.0], [3.0, 5.0]]]], device=device, dtype=dtype)+ assert validate_bbox(trapezoid) is False++ def test_wart_validate_bbox_rank4_view_layout_4174(self, device, dtype):+ # Wart pin for kornia#4174: rank-4 input is flattened with view, so an+ # incompatible leading-dimension stride raises instead of returning a boolean.+ boxes = torch.zeros(2, 3, 4, 2, device=device, dtype=dtype).transpose(0, 1)+ assert not boxes.is_contiguous()+ with pytest.raises(RuntimeError):+ validate_bbox(boxes)++ def test_convention_validate_bbox_invariance_is_exact_arithmetic_only(self, device):+ # In float16 the inclusive +1 rounds distinct sub-unit spans to the same+ # value, although the exclusive span difference exceeds the 1e-4 threshold.+ # The True below holds only with the +1 tracked in kornia#3934.+ boxes = torch.tensor(+ [[[0.0, 0.0], [0.0005, 0.0], [0.001, 0.001], [0.0, 0.001]]], device=device, dtype=torch.float16+ )+ assert validate_bbox(boxes) is True+ top_span = boxes[..., 1, 0] - boxes[..., 0, 0]+ bottom_span = boxes[..., 2, 0] - boxes[..., 3, 0]+ assert torch.all(torch.abs(top_span - bottom_span) > 1e-4)++ def test_wart_validate_bbox_returns_false_where_validate_bbox3d_raises_4013(self, device, dtype):+ # Wart pin for kornia#4013: for the same invalid shape, the 2D validator+ # returns False while the 3D validator raises.+ invalid_shape = torch.rand(1, 3, 3, device=device, dtype=dtype)+ assert validate_bbox(invalid_shape) is False+ with pytest.raises(AssertionError):+ validate_bbox3d(invalid_shape)++ non_cube = torch.tensor(+ [+ [+ [0.0, 0.0, 0.0],+ [1.0, 0.0, 0.0],+ [1.0, 1.0, 0.0],+ [0.0, 1.0, 0.0],+ [0.0, 0.0, 1.0],+ [2.0, 0.0, 1.0],+ [2.0, 1.0, 1.0],+ [0.0, 1.0, 1.0],+ ]+ ],+ device=device,+ dtype=dtype,+ )+ with pytest.raises(AssertionError):+ validate_bbox3d(non_cube)+def test_smoke(self, device, dtype):# Sample two points of the rectanglepoints = torch.rand(1, 4, device=device, dtype=dtype)@@ -89,9 +203,9 @@ class TestBbox2D(BaseTester):# Test with valid boxself.assert_close(scripted_fn(boxes), validate_bbox(boxes))- # Test with non-rectangular box- boxes_invalid = torch.tensor([[[0.0, 0.0], [2.0, 0.0], [3.0, 1.0], [1.0, 1.0]]], device=device, dtype=dtype)- self.assert_close(scripted_fn(boxes_invalid), validate_bbox(boxes_invalid))+ # Test with a valid sheared parallelogram+ boxes_sheared = torch.tensor([[[0.0, 0.0], [2.0, 0.0], [3.0, 1.0], [1.0, 1.0]]], device=device, dtype=dtype)+ self.assert_close(scripted_fn(boxes_sheared), validate_bbox(boxes_sheared))# Test with invalid shapeboxes_wrong_shape = torch.rand(1, 3, 2, device=device, dtype=dtype)diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.pyindex 3bb6db81a..f50d4be2f 100644--- a/tests/geometry/test_boxes.py+++ b/tests/geometry/test_boxes.py@@ -21,12 +21,205 @@ import pytestimport torchfrom kornia.geometry import boxes as boxes_module+from kornia.geometry.bbox import infer_bbox_shapefrom kornia.geometry.boxes import Boxes, Boxes3D, VideoBoxesfrom testing.base import BaseTesterclass 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+ # top-left, top-right, bottom-right, bottom-left order. The asymmetric+ # exclusive xyxy input makes both the coordinate order and the +1 conversion+ # observable. The expected data carries the -1 tracked in kornia#3934.+ boxes = Boxes.from_tensor(torch.tensor([[[1.0, 2.0, 5.0, 4.0]]], device=device, dtype=dtype), mode="xyxy")+ expected = torch.tensor([[[[1.0, 2.0], [4.0, 2.0], [4.0, 3.0], [1.0, 3.0]]]], device=device, dtype=dtype)+ self.assert_close(boxes.data, expected, atol=0.0, rtol=0.0)++ @pytest.mark.parametrize("mode", ["xyxy", "xyxy_plus", "xywh", "vertices", "vertices_plus"])+ def test_convention_axis_aligned_box_round_trips_in_each_mode(self, mode, device, dtype):+ # Convention pin: an axis-aligned rectangle whose extent is at least one unit+ # per axis round-trips in each mode. The source values describe the same+ # asymmetric box with exclusive extent (4, 2). Sub-unit extents are the+ # documented boundary of this guarantee and are pinned separately below.+ source_by_mode = {+ "xyxy": [1.0, 2.0, 5.0, 4.0],+ "xyxy_plus": [1.0, 2.0, 4.0, 3.0],+ "xywh": [1.0, 2.0, 4.0, 2.0],+ "vertices": [[1.0, 2.0], [5.0, 2.0], [5.0, 4.0], [1.0, 4.0]],+ "vertices_plus": [[1.0, 2.0], [4.0, 2.0], [4.0, 3.0], [1.0, 3.0]],+ }+ source = torch.tensor([source_by_mode[mode]], device=device, dtype=dtype)+ output = Boxes.from_tensor(source, mode=mode).to_tensor(mode=mode)+ self.assert_close(output, source, atol=0.0, rtol=0.0)++ @pytest.mark.parametrize(+ ("box_dtype", "source_values", "expected_values"),+ [+ (torch.bfloat16, [256.0, 256.0, 258.0, 258.0], [256.0, 256.0, 256.0, 256.0]),+ (torch.float16, [-385.25, 0.0, 400.0, 2.0], [-385.25, 0.0, 399.75, 2.0]),+ ],+ )+ def test_convention_round_trip_requires_exact_intermediate_arithmetic(+ self, device, box_dtype, source_values, expected_values+ ):+ # bfloat16 cannot represent the +/-1 intermediate at 256. The float16+ # case can represent its offsets, but rounds the cross-zero width first.+ # Both discrepancies exist only because of the +/-1 offsets tracked in kornia#3934.+ source = torch.tensor([source_values], device=device, dtype=box_dtype)+ output = Boxes.from_tensor(source, mode="xyxy").to_tensor("xyxy")+ expected = torch.tensor([expected_values], device=device, dtype=box_dtype)+ self.assert_close(output, expected, atol=0.0, rtol=0.0)+ assert not torch.equal(output, source)++ @pytest.mark.parametrize("mode", ["xyxy", "xyxy_plus", "xywh", "vertices", "vertices_plus"])+ def test_wart_sub_unit_extent_round_trip_boundary_4061(self, mode, device, dtype):+ # Wart pin for kornia#4061: the three converting modes place the top-right+ # vertex at ``xmin + width - 1``, which lands left of the top-left vertex when+ # the extent is below one unit. The stored quadrilateral is inverted on both+ # axes and to_tensor recovers a larger box. 'xyxy_plus' cancels the -1,+ # while 'vertices_plus' bypasses offset conversion.+ source_by_mode = {+ "xyxy": [0.1, 0.1, 0.6, 0.9],+ "xyxy_plus": [0.1, 0.1, 0.6, 0.9],+ "xywh": [0.1, 0.1, 0.5, 0.8],+ "vertices": [[0.1, 0.1], [0.6, 0.1], [0.6, 0.9], [0.1, 0.9]],+ "vertices_plus": [[0.1, 0.1], [0.6, 0.1], [0.6, 0.9], [0.1, 0.9]],+ }+ expected_by_mode = {+ "xyxy": [-0.4, -0.1, 1.1, 1.1],+ "xyxy_plus": [0.1, 0.1, 0.6, 0.9],+ "xywh": [-0.4, -0.1, 1.5, 1.2],+ "vertices": [[-0.4, -0.1], [1.1, -0.1], [1.1, 1.1], [-0.4, 1.1]],+ "vertices_plus": [[0.1, 0.1], [0.6, 0.1], [0.6, 0.9], [0.1, 0.9]],+ }+ source = torch.tensor([source_by_mode[mode]], device=device, dtype=dtype)+ expected = torch.tensor([expected_by_mode[mode]], device=device, dtype=dtype)+ # validate_boxes=True does not reject the input: the extents are positive.+ # Half-precision converting modes use dtype-aware tolerance because their+ # expected decimal results are not all exactly representable.+ output = Boxes.from_tensor(source, mode=mode, validate_boxes=True).to_tensor(mode=mode)+ self.assert_close(output, expected)++ def test_wart_get_boxes_shape_uses_inclusive_extent_3934(self, device, dtype):+ # Wart pin for kornia#3934: raw inclusive vertices spanning x=1..4 and+ # y=2..3 report (height, width) = (2, 4) because both axes add one.+ vertices = torch.tensor([[[1.0, 2.0], [4.0, 2.0], [4.0, 3.0], [1.0, 3.0]]], device=device, dtype=dtype)+ heights, widths = Boxes(vertices).get_boxes_shape()+ self.assert_close(heights, torch.tensor([2.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)+ self.assert_close(widths, torch.tensor([4.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)++ def test_convention_get_boxes_shape_includes_list_padding(self, device, dtype):+ # get_boxes_shape uses the padded xywh export, so padding entries appear as+ # 1-by-1 boxes even though an ordinary to_tensor export trims them. The 1-by-1+ # value depends on the inclusive +1 tracked in kornia#3934.+ first = torch.tensor([[[1.0, 2.0], [4.0, 2.0], [4.0, 3.0], [1.0, 3.0]]], device=device, dtype=dtype)+ second = torch.cat([first, first])+ boxes = Boxes([first, second])+ exported = boxes.to_tensor("xywh")+ assert isinstance(exported, list)+ assert [item.shape for item in exported] == [(1, 4), (2, 4)]++ heights, widths = boxes.get_boxes_shape()+ expected_heights = torch.tensor([[2.0, 1.0], [2.0, 2.0]], device=device, dtype=dtype)+ expected_widths = torch.tensor([[4.0, 1.0], [4.0, 4.0]], device=device, dtype=dtype)+ self.assert_close(heights, expected_heights, atol=0.0, rtol=0.0)+ self.assert_close(widths, expected_widths, atol=0.0, rtol=0.0)++ def test_wart_vertices_export_is_exclusive_for_inclusive_bbox_consumers_4009(self, device, dtype):+ # Wart pin for kornia#4009: vertices is an exclusive export, while+ # infer_bbox_shape reads vertices as inclusive and therefore adds one per axis.+ boxes = Boxes.from_tensor(torch.tensor([[1.0, 2.0, 5.0, 4.0]], device=device, dtype=dtype), mode="xyxy")+ heights, widths = infer_bbox_shape(boxes.to_tensor("vertices"))+ self.assert_close(heights, torch.tensor([3.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)+ self.assert_close(widths, torch.tensor([5.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)++ @pytest.mark.parametrize("mode", ["vertices", "vertices_plus"])+ def test_wart_vertices_import_is_not_validated_4177(self, mode, device, dtype):+ # Wart pin for kornia#4177: neither vertex mode is validated. The exclusive+ # 'vertices' import also subtracts one from fixed positions, so a non-rectangular+ # quadrilateral is silently reshaped instead of rejected with validate_boxes=True.+ # The -1 deformation is the inclusive offset tracked in kornia#3934.+ quadrilateral = torch.tensor([[[0.0, 0.0], [9.0, 0.0], [3.0, 7.0], [0.0, 1.0]]], device=device, dtype=dtype)+ boxes = Boxes.from_tensor(quadrilateral, mode=mode, validate_boxes=True)+ expected = quadrilateral.clone()+ if mode == "vertices":+ expected = torch.tensor([[[0.0, 0.0], [8.0, 0.0], [2.0, 6.0], [0.0, 0.0]]], device=device, dtype=dtype)+ self.assert_close(boxes.data, expected, atol=0.0, rtol=0.0)++ def test_convention_constructor_mode_is_only_an_export_label(self, device, dtype):+ vertices = torch.tensor([[[1.0, 2.0], [5.0, 2.0], [5.0, 4.0], [1.0, 4.0]]], device=device, dtype=dtype)+ constructed = Boxes(vertices, mode="vertices").to_tensor()+ imported = Boxes.from_tensor(vertices, mode="vertices").to_tensor()+ expected_constructed = torch.tensor(+ [[[1.0, 2.0], [6.0, 2.0], [6.0, 5.0], [1.0, 5.0]]], device=device, dtype=dtype+ )+ self.assert_close(constructed, expected_constructed, atol=0.0, rtol=0.0)+ self.assert_close(imported, vertices, atol=0.0, rtol=0.0)++ def test_convention_to_tensor_exports_axis_aligned_bounds_of_a_rotated_box(self, device, dtype):+ # Convention pin: to_tensor reduces the stored vertices with amin/amax, so it+ # exports axis-aligned bounds. After a shear the export is lossy and+ # to_tensor('vertices_plus') is not the identity on data.+ boxes = Boxes(torch.tensor([[[1.0, 2.0], [4.0, 2.0], [4.0, 3.0], [1.0, 3.0]]], device=device, dtype=dtype))+ shear = torch.tensor([[[1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ sheared = boxes.transform_boxes(shear)+ expected_data = torch.tensor([[[3.0, 2.0], [6.0, 2.0], [7.0, 3.0], [4.0, 3.0]]], device=device, dtype=dtype)+ self.assert_close(sheared.data, expected_data, atol=0.0, rtol=0.0)+ expected_export = torch.tensor([[[3.0, 2.0], [7.0, 2.0], [7.0, 3.0], [3.0, 3.0]]], device=device, dtype=dtype)+ self.assert_close(sheared.to_tensor("vertices_plus"), expected_export, atol=0.0, rtol=0.0)++ def test_wart_constructor_and_from_tensor_have_different_integer_policies_4012(self, device):+ # Wart pin for kornia#4012: the constructor rejects integer coordinates,+ # while from_tensor silently casts them to float32.+ vertices = torch.tensor([[[1, 2], [4, 2], [4, 3], [1, 3]]], device=device)+ with pytest.raises(ValueError, match="floating point"):+ Boxes(vertices)+ coordinates = torch.tensor([[1, 2, 5, 4]], device=device)+ assert Boxes.from_tensor(coordinates, mode="xyxy").dtype == torch.float32++ # A list is padded into a tensor of its first element's dtype before the+ # check, so a mixed-dtype list is judged by its first box alone.+ floating = vertices.to(torch.float32)+ assert Boxes([floating, vertices]).dtype == torch.float32+ with pytest.raises(ValueError, match="floating point"):+ Boxes([vertices, floating])++ # from_tensor converts each list element independently before the same+ # first-element dtype merge, so reversing mixed float16/integer inputs+ # changes the output dtype.+ half = vertices.to(torch.float16)+ assert Boxes.from_tensor([half, vertices], mode="vertices_plus").dtype == torch.float16+ assert Boxes.from_tensor([vertices, half], mode="vertices_plus").dtype == torch.float32++ def test_convention_merge_concatenates_batched_boxes_without_mutating_by_default(self, device, dtype):+ first = Boxes.from_tensor(torch.tensor([[[1.0, 2.0, 5.0, 4.0]]], device=device, dtype=dtype))+ second = Boxes.from_tensor(torch.tensor([[[6.0, 3.0, 9.0, 8.0]]], device=device, dtype=dtype))+ first_before = first.data.clone()+ second_before = second.data.clone()+ merged = first.merge(second)+ assert merged is not first+ assert merged.data.shape == (1, 2, 4, 2)+ self.assert_close(merged.data[:, 0], first_before[:, 0], atol=0.0, rtol=0.0)+ self.assert_close(merged.data[:, 1], second_before[:, 0], atol=0.0, rtol=0.0)+ self.assert_close(first.data, first_before, atol=0.0, rtol=0.0)+ self.assert_close(second.data, second_before, atol=0.0, rtol=0.0)++ def test_convention_index_put_replaces_coordinates_without_mutating_by_default(self, device, dtype):+ boxes = Boxes.from_tensor(+ torch.tensor([[[1.0, 2.0, 5.0, 4.0], [6.0, 3.0, 9.0, 8.0]]], device=device, dtype=dtype)+ )+ replacement = Boxes.from_tensor(torch.tensor([[10.0, 20.0, 14.0, 23.0]], device=device, dtype=dtype))+ boxes_before = boxes.data.clone()+ replacement_before = replacement.data.clone()+ updated = boxes.index_put((torch.tensor([0], device=device), torch.tensor([1], device=device)), replacement)+ assert updated is not boxes+ self.assert_close(updated.data[:, 0], boxes_before[:, 0], atol=0.0, rtol=0.0)+ self.assert_close(updated.data[:, 1], replacement_before, atol=0.0, rtol=0.0)+ self.assert_close(boxes.data, boxes_before, atol=0.0, rtol=0.0)+ self.assert_close(replacement.data, replacement_before, atol=0.0, rtol=0.0)+def test_smoke(self, device, dtype):def _create_tensor_box():# Sample two points of the rectangle@@ -186,21 +379,18 @@ class TestBoxes2D(BaseTester):@pytest.mark.parametrize("mode", ["xyxy", "xyxy_plus", "xywh", "vertices", "vertices_plus"])def test_boxes_list_to_tensor_list(self, mode, device, dtype):- src_1 = [- torch.as_tensor([[[1, 2], [1, 3], [2, 2], [2, 3]]], device=device, dtype=dtype),- torch.as_tensor(- [[[1, 2], [1, 3], [2, 2], [2, 3]], [[1, 2], [1, 3], [2, 2], [2, 3]]], device=device, dtype=dtype- ),- ]- src_2 = [- torch.as_tensor([[1, 1, 5, 5]], device=device, dtype=dtype),- torch.as_tensor([[1, 1, 5, 5], [1, 1, 5, 5]], device=device, dtype=dtype),- ]- src = src_1 if mode in ["vertices", "vertices_plus"] else src_2+ if mode == "vertices":+ item = torch.as_tensor([[[1, 2], [3, 2], [3, 4], [1, 4]]], device=device, dtype=dtype)+ elif mode == "vertices_plus":+ item = torch.as_tensor([[[1, 2], [2, 2], [2, 3], [1, 3]]], device=device, dtype=dtype)+ else:+ item = torch.as_tensor([[1, 1, 5, 5]], device=device, dtype=dtype)+ src = [item, torch.cat([item, item])]box = Boxes.from_tensor(src, mode=mode)out = box.to_tensor(mode)- assert out[0].shape == src[0].shape- assert out[1].shape == src[1].shape+ assert isinstance(out, list)+ self.assert_close(out[0], src[0], atol=0.0, rtol=0.0)+ self.assert_close(out[1], src[1], atol=0.0, rtol=0.0)def test_boxes_to_mask(self, device, dtype):t_box1 = torch.tensor(