Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(geometry): Convention blocks for bbox/boxes (batch 4c: masks, generators, 3D, video) (#4253)

Dmytro Mishkin92e5fe8df2cd
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index 5a9f1e676..b8c5ecfc0 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -96,13 +96,32 @@ def validate_bbox(boxes: torch.Tensor) -> bool:
def validate_bbox3d(boxes: torch.Tensor) -> bool:
- """Validate if a 3D bounding box usable or not. This function checks if the boxes are cube or not.
+ """Validate that a 3D box has equal inclusive edge extents along each axis, raising when it does not.
+
+ Convention:
+ Vertices use inclusive coordinates in the order front-top-left, front-top-right, front-bottom-right,
+ front-bottom-left, then the same four back vertices. The function accepts :math:`(B, 8, 3)` and
+ :math:`(B, N, 8, 3)` tensors and raises ``AssertionError`` for any other shape. It compares the inclusive
+ ``+1`` extents of the four edges parallel to each axis and raises ``AssertionError`` when they differ, so a
+ sheared parallelepiped with equal edge lengths and a zero-extent box both pass; it does not check right
+ angles or positive extent. Under graph capture the extent checks are skipped and the shape check alone
+ returns ``True``. The ``+1`` terms cancel in exact arithmetic and are tracked in
+ `#3934 <https://github.com/kornia/kornia/issues/3934>`_.
+
+ .. warning::
+ :func:`validate_bbox` returns ``False`` where this function raises; that inconsistency is tracked in
+ `#4013 <https://github.com/kornia/kornia/issues/4013>`_. Rank-4 input passes this check but breaks
+ :func:`infer_bbox_shape3d` and :func:`bbox_to_mask3d`, tracked in
+ `#4248 <https://github.com/kornia/kornia/issues/4248>`_.
Args:
boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape
- of Bx8x3, where each box is defined in the following ``clockwise`` order: front-top-left, front-top-right,
- front-bottom-right, front-bottom-left, back-top-left, back-top-right, back-bottom-right, back-bottom-left.
- The coordinates must be in the x, y, z order.
+ of :math:`(B, 8, 3)` or :math:`(B, N, 8, 3)`, where each box is defined in the following ``clockwise``
+ order: front-top-left, front-top-right, front-bottom-right, front-bottom-left, back-top-left,
+ back-top-right, back-bottom-right, back-bottom-left. The coordinates must be in the x, y, z order.
+
+ Returns:
+ ``True``. Invalid input raises instead of returning ``False``.
"""
if not (len(boxes.shape) in [3, 4] and boxes.shape[-2:] == torch.Size([8, 3])):
@@ -191,11 +210,28 @@ def infer_bbox_shape(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
def infer_bbox_shape3d(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
r"""Auto-infer the output sizes for the given 3D bounding boxes.
+ Convention:
+ Vertices use inclusive coordinates in the order front-top-left, front-top-right, front-bottom-right,
+ front-bottom-left, then the same four back vertices. The returned tuple is ``(depths, heights, widths)``,
+ in that order, each read as ``max - min + 1`` along one edge of the box after :func:`validate_bbox3d`
+ has established that the edges parallel to each axis have equal extent. Like :func:`infer_bbox_shape`,
+ the function adds one per axis, so pass the ``'vertices_plus'`` export of
+ :class:`~kornia.geometry.boxes.Boxes3D` rather than ``'vertices'``, which it reads as one larger per axis.
+
+ .. warning::
+ The inclusive ``+1`` arithmetic differs from torchvision, COCO, and albumentations and is tracked in
+ `#3934 <https://github.com/kornia/kornia/issues/3934>`_; the exclusive-export trap is
+ `#4009 <https://github.com/kornia/kornia/issues/4009>`_. Validation raises ``AssertionError`` rather than
+ returning ``False``, see `#4013 <https://github.com/kornia/kornia/issues/4013>`_. Batched :math:`(B, N, 8, 3)`
+ input passes validation but is then indexed as if the box axis were the vertex axis, which raises an
+ indexing error or returns wrong-shaped values depending on ``N``; flatten to :math:`(B \cdot N, 8, 3)`
+ first. Tracked in `#4248 <https://github.com/kornia/kornia/issues/4248>`_.
+
Args:
boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape
- of Bx8x3, where each box is defined in the following ``clockwise`` order: front-top-left, front-top-right,
- front-bottom-right, front-bottom-left, back-top-left, back-top-right, back-bottom-right, back-bottom-left.
- The coordinates must be in the x, y, z order.
+ of :math:`(B, 8, 3)`, where each box is defined in the following ``clockwise`` order: front-top-left,
+ front-top-right, front-bottom-right, front-bottom-left, back-top-left, back-top-right, back-bottom-right,
+ back-bottom-left. The coordinates must be in the x, y, z order.
Returns:
- Bounding box depths, shape of :math:`(B,)`.
@@ -240,15 +276,33 @@ def infer_bbox_shape3d(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor,
def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
"""Convert 2D bounding boxes to masks. Covered area is 1. and the remaining is 0.
+ Convention:
+ The image size is given as ``(width, height)`` while the mask comes back as :math:`(B, height, width)`;
+ :meth:`kornia.geometry.boxes.Boxes.to_mask` takes ``(height, width)`` for the same result. Only the top-left
+ (index 0) and bottom-right (index 2) vertices are read and the other two are ignored, so a non-rectangular
+ quadrilateral is masked by the axis-aligned box those two vertices span. A pixel is covered when its integer
+ coordinates satisfy ``xmin <= x <= xmax`` and ``ymin <= y <= ymax`` on the raw, unrounded values, which
+ reads the vertices as inclusive: pass the ``'vertices_plus'`` export of
+ :class:`~kornia.geometry.boxes.Boxes`, not ``'vertices'``. The mask has the input dtype, including integer
+ dtypes, and no gradient path. Input must be unbatched :math:`(B, 4, 2)`; :math:`(B, N, 4, 2)` raises
+ :class:`~kornia.core.exceptions.ShapeError`.
+
+ .. warning::
+ The ``(width, height)`` argument order is tracked in `#4014 <https://github.com/kornia/kornia/issues/4014>`_.
+ The inclusive raw-float comparison differs from the rounding in
+ :meth:`~kornia.geometry.boxes.Boxes.to_mask` and the truncation in :func:`bbox_to_mask3d` for fractional
+ coordinates and is tracked in `#4015 <https://github.com/kornia/kornia/issues/4015>`_; the exclusive-export
+ trap is `#4009 <https://github.com/kornia/kornia/issues/4009>`_.
+
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
- and bottom-left. The coordinates must be in the x, y order.
+ of :math:`(B, 4, 2)`, where each box is defined in the following ``clockwise`` order: top-left, top-right,
+ bottom-right and bottom-left. The coordinates must be in the x, y order.
width: width of the masked image.
height: height of the masked image.
Returns:
- the output mask tensor.
+ the output mask tensor, shape of :math:`(B, height, width)` and dtype of ``boxes``.
Raises:
ShapeError: if ``boxes`` does not have shape :math:`(B, 4, 2)`.
@@ -296,15 +350,38 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
def bbox_to_mask3d(boxes: torch.Tensor, size: tuple[int, int, int]) -> torch.Tensor:
"""Convert 3D bounding boxes to masks. Covered area is 1. and the remaining is 0.
+ Convention:
+ ``size`` is ``(depth, height, width)`` and the mask comes back as :math:`(B, 1, depth, height, width)` in
+ ``float32`` whatever the input dtype, unlike :func:`bbox_to_mask`, which keeps the input dtype and has no
+ channel axis, and :meth:`kornia.geometry.boxes.Boxes3D.to_mask`, which keeps the box dtype and returns
+ :math:`(N, depth, height, width)`. After :func:`validate_bbox3d`, which raises ``AssertionError`` for an
+ invalid box, the bounds are read from fixed vertex positions, truncated toward zero with ``.long()``, and
+ compared inclusively, which reads the vertices as inclusive: pass the ``'vertices_plus'`` export. The
+ intersection of the three axis ranges is recovered only when the box leaves at least one index uncovered
+ on every axis; see the warning. There is no gradient path.
+
+ .. warning::
+ A box that covers or overhangs a whole output axis fills the entire volume instead of the intersection:
+ the union-of-planes intermediate becomes all true and its reductions lose the other two bounds, where
+ :meth:`~kornia.geometry.boxes.Boxes3D.to_mask` fills the clamped region. Tracked in
+ `#4255 <https://github.com/kornia/kornia/issues/4255>`_. The truncation differs from the inclusive
+ raw-float comparison of :func:`bbox_to_mask` and the rounding of
+ :meth:`~kornia.geometry.boxes.Boxes3D.to_mask` for fractional coordinates and is tracked in
+ `#4015 <https://github.com/kornia/kornia/issues/4015>`_. The ``float32`` output with a channel axis is
+ tracked in `#4250 <https://github.com/kornia/kornia/issues/4250>`_. Validation raises rather than returning
+ ``False``, `#4013 <https://github.com/kornia/kornia/issues/4013>`_. Batched :math:`(B, N, 8, 3)` input passes
+ validation and then raises an indexing or broadcasting error; flatten it first. Tracked in
+ `#4248 <https://github.com/kornia/kornia/issues/4248>`_.
+
Args:
boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape
- of Bx8x3, where each box is defined in the following ``clockwise`` order: front-top-left, front-top-right,
- front-bottom-right, front-bottom-left, back-top-left, back-top-right, back-bottom-right, back-bottom-left.
- The coordinates must be in the x, y, z order.
+ of :math:`(B, 8, 3)`, where each box is defined in the following ``clockwise`` order: front-top-left,
+ front-top-right, front-bottom-right, front-bottom-left, back-top-left, back-top-right, back-bottom-right,
+ back-bottom-left. The coordinates must be in the x, y, z order.
size: depth, height and width of the masked image.
Returns:
- the output mask tensor.
+ the output mask tensor, shape of :math:`(B, 1, depth, height, width)` and dtype ``float32``.
Examples:
>>> boxes = torch.tensor([[
@@ -378,16 +455,28 @@ def bbox_generator(
) -> torch.Tensor:
"""Generate 2D bounding boxes according to the provided start coords, width and height.
+ Convention:
+ The far corner is placed at ``start + size - 1`` on each axis, so the generated box is inclusive:
+ :func:`infer_bbox_shape` reads back exactly ``width`` and ``height``, and a zero size places the far
+ corner one before the start. The vertex order is top-left, top-right, bottom-right, bottom-left. A scalar
+ input produces a batch of one. All four tensors must share dtype and device, otherwise ``AssertionError``
+ is raised; the output has that dtype and device and keeps a gradient path to the inputs.
+
+ .. warning::
+ The inclusive arithmetic is tracked in `#3934 <https://github.com/kornia/kornia/issues/3934>`_.
+ :func:`bbox_generator3d` places its far corner at ``start + size`` instead, see
+ `#4018 <https://github.com/kornia/kornia/issues/4018>`_.
+
Args:
x_start: a tensor containing the x coordinates of the bounding boxes to be extracted. Shape must be a scalar
tensor or :math:`(B,)`.
y_start: a tensor containing the y coordinates of the bounding boxes to be extracted. Shape must be a scalar
tensor or :math:`(B,)`.
- width: widths of the masked image. Shape must be a scalar tensor or :math:`(B,)`.
- height: heights of the masked image. Shape must be a scalar tensor or :math:`(B,)`.
+ width: widths of the bounding boxes. Shape must be a scalar tensor or :math:`(B,)`.
+ height: heights of the bounding boxes. Shape must be a scalar tensor or :math:`(B,)`.
Returns:
- the bounding box tensor.
+ the bounding box tensor, shape of :math:`(B, 4, 2)`.
Examples:
>>> x_start = torch.tensor([0, 1])
@@ -452,6 +541,18 @@ def bbox_generator3d(
) -> torch.Tensor:
"""Generate 3D bounding boxes according to the provided start coords, width, height and depth.
+ Convention:
+ The far corner is placed at ``start + size`` on each axis, one further than :func:`bbox_generator`, so
+ :func:`infer_bbox_shape3d` reads back ``size + 1`` on every axis; the example below shows it. The four
+ front vertices precede the four back vertices. A scalar input produces a batch of one. All six tensors
+ must share dtype and device, otherwise ``AssertionError`` is raised; the output has that dtype and device
+ and keeps a gradient path to the inputs.
+
+ .. warning::
+ The extra unit of extent relative to :func:`bbox_generator` and to the inclusive
+ :func:`infer_bbox_shape3d` is tracked as a coordinated repair in
+ `#4018 <https://github.com/kornia/kornia/issues/4018>`_ and is documented as it is.
+
Args:
x_start: a tensor containing the x coordinates of the bounding boxes to be extracted. Shape must be a scalar
tensor or :math:`(B,)`.
@@ -459,9 +560,9 @@ def bbox_generator3d(
tensor or :math:`(B,)`.
z_start: a tensor containing the z coordinates of the bounding boxes to be extracted. Shape must be a scalar
tensor or :math:`(B,)`.
- width: widths of the masked image. Shape must be a scalar tensor or :math:`(B,)`.
- height: heights of the masked image. Shape must be a scalar tensor or :math:`(B,)`.
- depth: depths of the masked image. Shape must be a scalar tensor or :math:`(B,)`.
+ width: widths of the bounding boxes. Shape must be a scalar tensor or :math:`(B,)`.
+ height: heights of the bounding boxes. Shape must be a scalar tensor or :math:`(B,)`.
+ depth: depths of the bounding boxes. Shape must be a scalar tensor or :math:`(B,)`.
Returns:
the 3d bounding box tensor :math:`(B, 8, 3)`.
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index f56f4531b..feb3f29f5 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -776,19 +776,40 @@ class Boxes:
def to_mask(self, height: int, width: int) -> torch.Tensor:
"""Convert 2D boxes to masks. Covered area is 1 and the remaining is 0.
+ See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.
+
+ Convention:
+ The size is ``(height, width)`` and the mask is :math:`(N, height, width)` or
+ :math:`(B, N, height, width)` in the box dtype; :func:`~kornia.geometry.bbox.bbox_to_mask` takes
+ ``(width, height)`` for the same result. The boxes are exported as exclusive ``'xyxy'`` bounds (the
+ axis-aligned bounding box of a rotated quadrilateral), clamped to ``[0, width]`` and ``[0, height]``,
+ rounded to the nearest integer, and filled over the half-open ranges ``[xmin, xmax)`` and
+ ``[ymin, ymax)``, so a box entirely outside the image fills nothing and a fractional box can fill a
+ different area than :func:`~kornia.geometry.bbox.bbox_to_mask` gives for the same vertices. A
+ list-backed object also fills a mask channel for each padding entry, whose zero row exports as a
+ one-pixel box at the origin. The loop taken on CPU and MPS and the vectorized path taken on CUDA and
+ under graph capture produce the same mask. A box tensor that requires grad is rejected with
+ ``RuntimeError``.
+
+ .. warning::
+ The argument-order split with :func:`~kornia.geometry.bbox.bbox_to_mask` is tracked in
+ `#4014 <https://github.com/kornia/kornia/issues/4014>`_ and the rounding split in
+ `#4015 <https://github.com/kornia/kornia/issues/4015>`_. The padding-entry pixel is tracked in
+ `#4252 <https://github.com/kornia/kornia/issues/4252>`_.
+
Args:
height: height of the masked image/images.
width: width of the masked image/images.
Returns:
- the output mask tensor, shape of :math:`(N, width, height)` or :math:`(B,N, width, height)` and dtype of
+ the output mask tensor, shape of :math:`(N, height, width)` or :math:`(B, N, height, width)` and dtype of
:func:`Boxes.dtype` (it can be any floating point dtype).
Note:
It is currently non-differentiable.
Examples:
- >>> boxes = Boxes(torch.tensor([[ # Equivalent to boxes = Boxes.from_tensor([[1,1,4,3]])
+ >>> boxes = Boxes(torch.tensor([[ # Equivalent to Boxes.from_tensor([[1, 1, 4, 3]], mode='xyxy_plus')
... [1., 1.],
... [4., 1.],
... [4., 3.],
@@ -1017,6 +1038,30 @@ class VideoBoxes(Boxes):
the pipeline contains a video sequential so that ``to_tensor`` restores the
temporal axis after geometric transforms.
+ See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.
+
+ Convention:
+ - :meth:`from_tensor` stores the :math:`(B, T, N, 4, 2)` input unchanged as batched
+ :math:`(B \cdot T, N, 4, 2)` ``'vertices_plus'`` data; there is no mode argument, no conversion and no
+ validation, and integer input is cast to ``float32``. Any other rank or last dimensions, and list input,
+ raise ``ValueError``.
+ - :meth:`to_tensor` accepts every :class:`Boxes` export mode and restores the temporal axis, so
+ ``to_tensor('xyxy')`` is :math:`(B, T, N, 4)`. Its default is the stored ``'vertices_plus'`` mode.
+ - A transformation matrix must carry one entry per flattened frame, :math:`(B \cdot T, 3, 3)`; a
+ :math:`(3, 3)` matrix raises ``ValueError``.
+ - Methods that copy through :meth:`clone`, among them :meth:`transform_boxes`, :meth:`translate`,
+ :meth:`clamp`, :meth:`filter_boxes_by_area` and :meth:`merge`, return a new :class:`VideoBoxes` with the
+ same :attr:`temporal_channel_size` and leave the source untouched. :meth:`pad`, :meth:`unpad`, :meth:`to`
+ and :meth:`type` update ``self`` in place and return it, so they keep the temporal size but change the
+ original coordinates or dtype.
+
+ .. warning::
+ :meth:`get_boxes_shape` and :meth:`to_mask` raise ``TypeError`` because the :meth:`to_tensor` override
+ does not accept the ``as_padded_sequence`` keyword they pass, and indexing returns a wrapper without
+ :attr:`temporal_channel_size`, so its :meth:`to_tensor` raises ``AttributeError``. Both are tracked in
+ `#4249 <https://github.com/kornia/kornia/issues/4249>`_. The inert ``validate_boxes`` flag is part of
+ `#4177 <https://github.com/kornia/kornia/issues/4177>`_.
+
Attributes:
temporal_channel_size: Number of frames :math:`T` stored with the boxes.
@@ -1033,7 +1078,8 @@ class VideoBoxes(Boxes):
Args:
boxes: Box corners with shape :math:`(B, T, N, 4, 2)` in
``vertices_plus`` order (top-left, top-right, bottom-right,
- bottom-left). Lists of tensors are not supported yet.
+ bottom-left), stored unchanged; integer input is cast to
+ ``float32``. Lists of tensors are not supported yet.
validate_boxes: Forwarded to ``_boxes_to_quadrilaterals``. The
``vertices_plus`` path used here builds corners directly and
performs no size check, so this flag currently has no effect.
@@ -1063,6 +1109,9 @@ class VideoBoxes(Boxes):
def to_tensor(self, mode: Optional[str] = None) -> torch.Tensor | list[torch.Tensor]: # type: ignore[override]
r"""Cast :class:`VideoBoxes` to a tensor with the temporal axis restored.
+ The ``as_padded_sequence`` keyword of :meth:`Boxes.to_tensor` is not
+ accepted; see the warning on the class.
+
Args:
mode: Output box format forwarded to :meth:`Boxes.to_tensor`. When
``None``, uses the stored mode (``vertices_plus`` by default).
@@ -1099,13 +1148,49 @@ class Boxes3D:
boxes: 3D boxes, shape of :math:`(N,8,3)` or :math:`(B,N,8,3)`. See below for more details.
raise_if_not_floating_point: flag to control floating point casting behaviour when `boxes` is not a floating
point tensor. True to raise an error when `boxes` isn't a floating point tensor, False to cast to float.
+ mode: Representation label reported by :attr:`mode`. The constructor does not convert ``boxes`` and
+ :meth:`to_tensor` does not consult the label; use :meth:`from_tensor` to import another representation.
- Note:
- **3D boxes format** is defined as a floating data type tensor of shape ``Nx8x3`` or ``BxNx8x3`` where each box
- is a `hexahedron <https://en.wikipedia.org/wiki/Hexahedron>`_ defined by it's 8 vertices coordinates.
- Coordinates must be in ``x, y, z`` order. The height, width and depth of a box is defined as
- ``width = xmax - xmin + 1``, ``height = ymax - ymin + 1`` and ``depth = zmax - zmin + 1``. Examples of
- `hexahedrons <https://en.wikipedia.org/wiki/Hexahedron>`_ are cubes and rhombohedrons.
+ Convention:
+ - A box is a `hexahedron <https://en.wikipedia.org/wiki/Hexahedron>`_ of eight floating-point
+ ``(x, y, z)`` vertices, stored as :math:`(N, 8, 3)` or :math:`(B, N, 8, 3)` data, in the order
+ front-top-left, front-top-right, front-bottom-right, front-bottom-left, then the same four back
+ vertices. The vertices stay arbitrary after :meth:`transform_boxes`.
+ - The stored form is inclusive: ``width = xmax - xmin + 1``, ``height = ymax - ymin + 1`` and
+ ``depth = zmax - zmin + 1``. The exclusive ``'xyzxyz'`` and ``'xyzwhd'`` modes subtract one from the
+ max corner in :meth:`from_tensor` and add it back in :meth:`to_tensor`; ``'xyzxyz_plus'`` is stored as
+ given. :meth:`from_tensor` accepts only :math:`(N, 6)` or :math:`(B, N, 6)` input in those three modes;
+ the vertex modes ``'vertices'`` (exclusive) and ``'vertices_plus'`` (the stored form) exist for
+ :meth:`to_tensor` only. Mode strings are lowercased before use.
+ - :meth:`to_tensor` reduces the stored vertices with ``amin``/``amax``, so every export is an axis-aligned
+ bounding box and ``to_tensor('vertices_plus')`` is not the identity on :attr:`data` for a rotated box.
+ Its default mode is ``'xyzxyz'`` whatever the stored label, unlike :meth:`Boxes.to_tensor`, which
+ defaults to the stored mode.
+ - :meth:`get_boxes_shape` returns ``(depths, heights, widths)`` in that order, in the inclusive terms.
+ - :func:`~kornia.geometry.bbox.validate_bbox3d`, :func:`~kornia.geometry.bbox.infer_bbox_shape3d` and
+ :func:`~kornia.geometry.bbox.bbox_to_mask3d` have no mode argument and read their input as inclusive:
+ pass them the ``'vertices_plus'`` export, never ``'vertices'``, which they read as one larger per axis.
+ The validator also accepts batched :math:`(B, N, 8, 3)` input, but the shape and mask helpers require
+ unbatched :math:`(N, 8, 3)` input; see their warnings.
+ - With ``validate_boxes=True``, :meth:`from_tensor` rejects extents that are not positive in the given
+ mode's convention, so ``xmax == xmin`` is rejected in ``'xyzxyz'`` and accepted in ``'xyzxyz_plus'``.
+ - The constructor rejects an integer tensor unless ``raise_if_not_floating_point=False``;
+ :meth:`from_tensor` silently casts integer input to ``float32``.
+ - :meth:`transform_boxes` leaves the source unchanged and returns a new object labelled
+ ``'xyzxyz_plus'``; :meth:`transform_boxes_` rebinds the internal tensor of ``self`` and keeps the label.
+
+ .. 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 exclusive-export trap is
+ `#4009 <https://github.com/kornia/kornia/issues/4009>`_, the integer-input policy split is
+ `#4012 <https://github.com/kornia/kornia/issues/4012>`_, the validator contract split with
+ :func:`~kornia.geometry.bbox.validate_bbox` is `#4013 <https://github.com/kornia/kornia/issues/4013>`_, and
+ boxes built by :func:`~kornia.geometry.bbox.bbox_generator3d` measure one larger than requested,
+ `#4018 <https://github.com/kornia/kornia/issues/4018>`_. The :meth:`to_tensor` default-mode split with
+ :class:`Boxes` is tracked in `#4251 <https://github.com/kornia/kornia/issues/4251>`_, and the rank-4 breakage
+ of the free functions in `#4248 <https://github.com/kornia/kornia/issues/4248>`_. :meth:`to_mask` rejects
+ boxes that require grad even though :meth:`to_tensor` is differentiable; see the note on
+ :meth:`to_tensor`.
"""
@@ -1154,7 +1239,9 @@ class Boxes3D:
return self.data.shape
def get_boxes_shape(self) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
- r"""Compute boxes heights and widths.
+ r"""Compute boxes depths, heights and widths.
+
+ See the Convention block on :class:`~kornia.geometry.boxes.Boxes3D`.
Returns:
- Boxes depths, shape of :math:`(N,)` or :math:`(B,N)`.
@@ -1176,9 +1263,11 @@ class Boxes3D:
def from_tensor(cls, boxes: torch.Tensor, mode: str = "xyzxyz", validate_boxes: bool = True) -> Boxes3D:
r"""Create :class:`Boxes3D` from 3D boxes stored in another format.
+ See the Convention block on :class:`~kornia.geometry.boxes.Boxes3D`.
+
Args:
- boxes: 3D boxes, shape of :math:`(N,6)` or :math:`(B,N,6)`.
- mode: The format in which the 3D boxes are provided.
+ boxes: 3D boxes, shape of :math:`(N,6)` or :math:`(B,N,6)`; integer input is cast to ``float32``.
+ mode: The format in which the 3D boxes are provided, matched case-insensitively.
* 'xyzxyz': boxes are assumed to be in the format ``xmin, ymin, zmin, xmax, ymax, zmax`` where
``width = xmax - xmin``, ``height = ymax - ymin`` and ``depth = zmax - zmin``.
@@ -1187,11 +1276,11 @@ class Boxes3D:
* 'xyzwhd': boxes are assumed to be in the format ``xmin, ymin, zmin, width, height, depth`` where
``width = xmax - xmin``, ``height = ymax - ymin`` and ``depth = zmax - zmin``.
- validate_boxes: check if boxes are valid rectangles or not. Valid rectangles are those with width, height
- and depth >= 1 (>= 2 when mode ends with '_plus' suffix).
+ validate_boxes: reject boxes whose width, height or depth is not positive when measured in the given
+ mode's convention, so ``xmax == xmin`` is rejected in ``'xyzxyz'`` and accepted in ``'xyzxyz_plus'``.
Returns:
- :class:`Boxes3D` class containing the original `boxes` in the format specified by ``mode``.
+ :class:`Boxes3D` containing the converted inclusive vertex representation, labelled with ``mode``.
Examples:
>>> boxes_xyzxyz = torch.as_tensor([[0, 3, 6, 1, 4, 8], [5, 1, 3, 8, 4, 9]])
@@ -1254,10 +1343,17 @@ class Boxes3D:
def to_tensor(self, mode: str = "xyzxyz") -> torch.Tensor:
r"""Cast :class:`Boxes3D` to a tensor.
- ``mode`` controls which 3D boxes format should be use to represent boxes in the tensor.
+ See the Convention block on :class:`~kornia.geometry.boxes.Boxes3D`.
+
+ Convention:
+ ``mode`` selects the export format and defaults to ``'xyzxyz'`` regardless of the label stored by
+ :meth:`from_tensor` or the constructor; :meth:`Boxes.to_tensor` defaults to its stored mode instead
+ (`#4251 <https://github.com/kornia/kornia/issues/4251>`_).
+ Every export starts from the ``amin``/``amax`` bounds of the stored vertices, so it is the
+ axis-aligned bounding box of a rotated hexahedron.
Args:
- mode: The format in which the boxes are provided.
+ mode: The format in which the boxes are provided, matched case-insensitively.
* 'xyzxyz': boxes are assumed to be in the format ``xmin, ymin, zmin, xmax, ymax, zmax`` where
``width = xmax - xmin``, ``height = ymax - ymin`` and ``depth = zmax - zmin``.
@@ -1270,8 +1366,9 @@ class Boxes3D:
back-top-right, back-bottom-right, back-bottom-left*. Vertices coordinates are in (x,y, z) order.
Finally, box width, height and depth are defined as ``width = xmax - xmin``, ``height = ymax - ymin``
and ``depth = zmax - zmin``.
- * 'vertices_plus': similar to 'vertices' mode but where box width, length and depth are defined as
- ``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``.
+ * 'vertices_plus': similar to 'vertices' mode but where box width, height and depth are defined as
+ ``width = xmax - xmin + 1``, ``height = ymax - ymin + 1`` and ``depth = zmax - zmin + 1``; this is
+ the stored form.
Returns:
3D Boxes tensor in the ``mode`` format. The shape depends with the ``mode`` value:
@@ -1335,7 +1432,25 @@ class Boxes3D:
return boxes
def to_mask(self, depth: int, height: int, width: int) -> torch.Tensor:
- """Convert Β·D boxes to masks. Covered area is 1 and the remaining is 0.
+ """Convert 3D boxes to masks. Covered area is 1 and the remaining is 0.
+
+ See the Convention block on :class:`~kornia.geometry.boxes.Boxes3D`.
+
+ Convention:
+ The size is ``(depth, height, width)`` and the mask is :math:`(N, depth, height, width)` or
+ :math:`(B, N, depth, height, width)` in the box dtype, where :func:`~kornia.geometry.bbox.bbox_to_mask3d`
+ returns ``float32`` with an extra channel axis. The boxes are exported as exclusive ``'xyzxyz'``
+ bounds, clamped to the volume, rounded to the nearest integer, and filled over half-open ranges, so a
+ box entirely outside the volume fills nothing and a fractional box can fill a different volume than
+ :func:`~kornia.geometry.bbox.bbox_to_mask3d`, which truncates. The loop and the grid comparison taken
+ under graph capture produce the same mask. A box tensor that requires grad is rejected with
+ ``RuntimeError``.
+
+ .. warning::
+ The rounding split with :func:`~kornia.geometry.bbox.bbox_to_mask3d` is tracked in
+ `#4015 <https://github.com/kornia/kornia/issues/4015>`_. That function also fills the whole volume for
+ a box that covers or overhangs a full axis, where this method fills the clamped region; tracked in
+ `#4255 <https://github.com/kornia/kornia/issues/4255>`_.
Args:
depth: depth of the masked image/images.
@@ -1343,14 +1458,14 @@ class Boxes3D:
width: width of the masked image/images.
Returns:
- the output mask tensor, shape of :math:`(N, depth, width, height)` or :math:`(B,N, depth, width, height)`
- and dtype of :func:`Boxes3D.dtype` (it can be any floating point dtype).
+ the output mask tensor, shape of :math:`(N, depth, height, width)` or :math:`(B, N, depth, height, width)`
+ and dtype of :func:`Boxes3D.dtype` (it can be any floating point dtype).
Note:
It is currently non-differentiable.
Examples:
- >>> boxes = Boxes3D(torch.tensor([[ # Equivalent to boxes = Boxes.3Dfrom_tensor([[1,1,1,3,3,2]])
+ >>> boxes = Boxes3D(torch.tensor([[ # Same as Boxes3D.from_tensor([[1, 1, 1, 3, 3, 2]], 'xyzxyz_plus')
... [1., 1., 1.],
... [3., 1., 1.],
... [3., 3., 1.],
@@ -1436,12 +1551,16 @@ class Boxes3D:
def transform_boxes(self, M: torch.Tensor, inplace: bool = False) -> Boxes3D:
r"""Apply a transformation matrix to the 3D boxes.
+ See the Convention block on :class:`~kornia.geometry.boxes.Boxes3D`.
+
Args:
- M: The transformation matrix to be applied, shape of :math:`(4, 4)` or :math:`(B, 4, 4)`.
+ M: The transformation matrix to be applied, shape of :math:`(4, 4)` or :math:`(B, 4, 4)`, where ``B``
+ must equal the box batch size and an unbatched box counts as one.
inplace: do transform in-place and return self.
Returns:
- The transformed boxes.
+ The transformed boxes: a new :class:`Boxes3D` labelled ``'xyzxyz_plus'`` when ``inplace`` is false,
+ otherwise ``self``.
"""
if not 2 <= M.ndim <= 3 or M.shape[-2:] != (4, 4):
@@ -1455,7 +1574,18 @@ class Boxes3D:
return Boxes3D(transformed_boxes, False, "xyzxyz_plus")
def transform_boxes_(self, M: torch.Tensor) -> Boxes3D:
- """Inplace version of :func:`Boxes3D.transform_boxes`."""
+ """Apply :meth:`transform_boxes` in place and return ``self``.
+
+ See the Convention block on :class:`~kornia.geometry.boxes.Boxes3D`.
+
+ Convention:
+ The in-place operation rebinds this object's internal tensor to the transformed result. A tensor
+ reference obtained from :attr:`data` before that call therefore remains unchanged and no longer
+ aliases the container's data. The stored mode label is kept.
+
+ Returns:
+ This :class:`Boxes3D` object after the transformation.
+ """
return self.transform_boxes(M, inplace=True)
@property
diff --git a/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.py
index f4a8fdae8..432ac0b38 100644
--- a/tests/geometry/test_bbox.py
+++ b/tests/geometry/test_bbox.py
@@ -20,10 +20,12 @@ import torch
import kornia
from kornia.core.exceptions import ShapeError
+from kornia.geometry import bbox as bbox_module
from kornia.geometry.bbox import (
bbox_generator,
bbox_generator3d,
bbox_to_mask,
+ bbox_to_mask3d,
infer_bbox_shape,
infer_bbox_shape3d,
nms,
@@ -31,6 +33,7 @@ from kornia.geometry.bbox import (
validate_bbox,
validate_bbox3d,
)
+from kornia.geometry.boxes import Boxes3D
from testing.base import BaseTester
@@ -223,6 +226,64 @@ class TestBbox2D(BaseTester):
boxes_wrong_shape = torch.rand(1, 3, 2, device=device, dtype=dtype)
self.assert_close(scripted_fn(boxes_wrong_shape), validate_bbox(boxes_wrong_shape))
+ def test_convention_bbox_to_mask_takes_width_then_height_and_reads_two_vertices_4014(self, device, dtype):
+ # Convention pin (kornia#4014 records the argument-order split with Boxes.to_mask):
+ # bbox_to_mask(boxes, width, height) returns (B, height, width), fills through the
+ # top-left (index 0) and bottom-right (index 2) vertices inclusively, ignores the two
+ # other vertices, keeps the input dtype, and carries no gradient path.
+ boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
+ mask = bbox_to_mask(boxes, 5, 3)
+ assert mask.shape == (1, 3, 5)
+ assert mask.dtype == dtype
+ expected = torch.tensor(
+ [[[0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 1.0, 0.0], [0.0, 1.0, 1.0, 1.0, 0.0]]],
+ device=device,
+ dtype=dtype,
+ )
+ self.assert_close(mask, expected, atol=0.0, rtol=0.0)
+ assert bbox_to_mask(boxes, 3, 5).shape == (1, 5, 3)
+
+ corrupted = boxes.clone()
+ corrupted[0, 1] = 9.0
+ corrupted[0, 3] = -9.0
+ self.assert_close(bbox_to_mask(corrupted, 5, 3), expected, atol=0.0, rtol=0.0)
+
+ assert bbox_to_mask(boxes.to(torch.int64), 5, 3).dtype == torch.int64
+ assert not bbox_to_mask(boxes.clone().requires_grad_(), 5, 3).requires_grad
+
+ def test_wart_bbox_to_mask_compares_raw_floats_inclusively_4015(self, device, dtype):
+ # Wart pin for kornia#4015: the fractional box [1.4, 3.0] x [2.0, 2.6] covers the integer
+ # columns 2..3 of row 2 under inclusive raw-float comparison, so the integer edges x=3 and
+ # y=2 are inside. The [1.4, 3.6] x [1.4, 2.6] box in test_boxes.py covers two pixels here
+ # and twelve under Boxes.to_mask's rounding of the exclusive export.
+ boxes = torch.tensor([[[1.4, 2.0], [3.0, 2.0], [3.0, 2.6], [1.4, 2.6]]], device=device, dtype=dtype)
+ expected = torch.zeros(1, 5, 6, device=device, dtype=dtype)
+ expected[0, 2, 2:4] = 1.0
+ self.assert_close(bbox_to_mask(boxes, 6, 5), expected, atol=0.0, rtol=0.0)
+ fractional = torch.tensor([[[1.4, 1.4], [3.6, 1.4], [3.6, 2.6], [1.4, 2.6]]], device=device, dtype=dtype)
+ assert bbox_to_mask(fractional, 6, 5).sum().item() == 2.0
+
+ def test_convention_bbox_generator_far_corner_is_start_plus_size_minus_one_3934(self, device, dtype):
+ # Convention pin (kornia#3934 tracks the inclusive arithmetic): width 3 from x=1 places
+ # the right edge at x=3, which infer_bbox_shape reads back as width 3. A scalar input is a
+ # batch of one, dtype and device are preserved, mixed dtypes raise, and the output keeps a
+ # gradient path to its inputs.
+ start = torch.tensor([1.0], device=device, dtype=dtype)
+ size = torch.tensor([3.0], device=device, dtype=dtype)
+ boxes = bbox_generator(start, start, size, size)
+ expected = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 3.0], [1.0, 3.0]]], device=device, dtype=dtype)
+ self.assert_close(boxes, expected, atol=0.0, rtol=0.0)
+ heights, widths = infer_bbox_shape(boxes)
+ self.assert_close(heights, size, atol=0.0, rtol=0.0)
+ self.assert_close(widths, size, atol=0.0, rtol=0.0)
+ assert boxes.device == start.device
+
+ self.assert_close(bbox_generator(start[0], start[0], size[0], size[0]), expected, atol=0.0, rtol=0.0)
+ assert bbox_generator(*(t.clone().requires_grad_() for t in (start, start, size, size))).requires_grad
+ other = torch.float32 if dtype == torch.float16 else torch.float16
+ with pytest.raises(AssertionError, match="same dtype"):
+ bbox_generator(start, start, size.to(other), size)
+
class TestTransformBoxes2D(BaseTester):
def test_convention_transform_bbox_restores_vector_endpoints(self, device, dtype):
@@ -447,6 +508,203 @@ class TestBbox3D(BaseTester):
expected = op(boxes)
self.assert_close(actual, expected)
+ @staticmethod
+ def _unit_cuboid(device, dtype) -> torch.Tensor:
+ # Inclusive vertices for x in 1..3, y in 1..3, z in 1..2: width 3, height 3, depth 2.
+ return torch.tensor(
+ [
+ [
+ [1.0, 1.0, 1.0],
+ [3.0, 1.0, 1.0],
+ [3.0, 3.0, 1.0],
+ [1.0, 3.0, 1.0],
+ [1.0, 1.0, 2.0],
+ [3.0, 1.0, 2.0],
+ [3.0, 3.0, 2.0],
+ [1.0, 3.0, 2.0],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ def test_wart_validate_bbox3d_checks_equal_edge_extents_not_cuboids_4013(self, device, dtype, monkeypatch):
+ # Wart pin for kornia#4013 (the 3D validator raises where the 2D one returns False): the
+ # check compares the inclusive extents of the four edges parallel to each axis, so a
+ # sheared parallelepiped and a zero-extent box pass, and only unequal edges raise. Under
+ # graph capture the extent check is skipped and the shape check alone returns True.
+ cuboid = self._unit_cuboid(device, dtype)
+ assert validate_bbox3d(cuboid) is True
+ assert validate_bbox3d(cuboid[None]) is True
+ assert validate_bbox3d(torch.zeros(1, 8, 3, device=device, dtype=dtype)) is True
+
+ sheared = cuboid.clone()
+ sheared[0, 4:, 0] += 1.0
+ assert validate_bbox3d(sheared) is True
+ for extent, expected in zip(infer_bbox_shape3d(sheared), (2.0, 3.0, 3.0)):
+ self.assert_close(extent, torch.tensor([expected], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+
+ unequal = cuboid.clone()
+ unequal[0, 1, 0] = 5.0
+ with pytest.raises(AssertionError, match="widths"):
+ validate_bbox3d(unequal)
+ with pytest.raises(AssertionError, match="shape"):
+ validate_bbox3d(cuboid[0])
+ monkeypatch.setattr(bbox_module, "is_exporting", lambda: True)
+ assert validate_bbox3d(unequal) is True
+ with pytest.raises(AssertionError, match="shape"):
+ validate_bbox3d(cuboid[0])
+
+ def test_convention_infer_bbox_shape3d_returns_depth_height_width_inclusive_3934(self, device, dtype):
+ # Convention pin (kornia#3934 tracks the inclusive arithmetic): the tuple order is
+ # (depths, heights, widths) and each extent is one larger than its coordinate span.
+ boxes = torch.tensor(
+ [
+ [
+ [1.0, 2.0, 3.0],
+ [4.0, 2.0, 3.0],
+ [4.0, 4.0, 3.0],
+ [1.0, 4.0, 3.0],
+ [1.0, 2.0, 7.0],
+ [4.0, 2.0, 7.0],
+ [4.0, 4.0, 7.0],
+ [1.0, 4.0, 7.0],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ depths, heights, widths = infer_bbox_shape3d(boxes)
+ self.assert_close(depths, torch.tensor([5.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(heights, torch.tensor([3.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)
+
+ @pytest.mark.parametrize("num_boxes", [1, 8])
+ def test_wart_rank4_input_passes_validate_bbox3d_then_breaks_the_3d_helpers_4248(self, device, dtype, num_boxes):
+ # Wart pin for kornia#4248: validate_bbox3d accepts (B, N, 8, 3), but infer_bbox_shape3d and bbox_to_mask3d
+ # then index the box axis as the vertex axis. With one box that raises out-of-bounds errors;
+ # with eight boxes infer_bbox_shape3d instead returns three (1, 3) tensors, one value per
+ # coordinate rather than per box. The 2D helpers had the same defect until kornia#4180.
+ boxes = self._unit_cuboid(device, dtype).expand(num_boxes, 8, 3)[None].contiguous()
+ assert validate_bbox3d(boxes) is True
+ if num_boxes == 8:
+ depths, heights, widths = infer_bbox_shape3d(boxes)
+ assert depths.shape == heights.shape == widths.shape == (1, 3)
+ with pytest.raises(RuntimeError):
+ bbox_to_mask3d(boxes, (4, 5, 5))
+ else:
+ with pytest.raises((RuntimeError, IndexError)):
+ infer_bbox_shape3d(boxes)
+ with pytest.raises((RuntimeError, IndexError)):
+ bbox_to_mask3d(boxes, (4, 5, 5))
+
+ @pytest.mark.parametrize("num_boxes", [1, 8])
+ @pytest.mark.xfail(
+ strict=True,
+ raises=AssertionError,
+ reason="kornia#4248: rank-4 3D input is not rejected with ShapeError as the 2D helpers do since kornia#4218",
+ )
+ def test_convention_rank4_input_is_rejected_by_the_3d_helpers_4248(self, device, dtype, num_boxes):
+ boxes = self._unit_cuboid(device, dtype).expand(num_boxes, 8, 3)[None].contiguous()
+ for call in (lambda: infer_bbox_shape3d(boxes), lambda: bbox_to_mask3d(boxes, (4, 5, 5))):
+ try:
+ call()
+ except ShapeError:
+ continue
+ except Exception as error:
+ raise AssertionError(f"expected ShapeError, got {type(error).__name__}") from error
+ raise AssertionError("expected ShapeError, the call returned")
+
+ def test_wart_bbox_generator3d_extent_is_one_larger_than_requested_4018(self, device, dtype):
+ # Wart pin for kornia#4018: the 3D generator places the far corner at start + size, so
+ # width 3 from x=1 spans x=1..4 and infer_bbox_shape3d reads 4 on every axis, where the
+ # 2D generator with the same arguments spans x=1..3 and reads 3.
+ start = torch.tensor([1.0], device=device, dtype=dtype)
+ size = torch.tensor([3.0], device=device, dtype=dtype)
+ boxes = bbox_generator3d(start, start, start, size, size, size)
+ expected_x = torch.tensor([[1.0, 4.0, 4.0, 1.0, 1.0, 4.0, 4.0, 1.0]], device=device, dtype=dtype)
+ self.assert_close(boxes[..., 0], expected_x, atol=0.0, rtol=0.0)
+ for extent in infer_bbox_shape3d(boxes):
+ self.assert_close(extent, size + 1, atol=0.0, rtol=0.0)
+ for extent in infer_bbox_shape(bbox_generator(start, start, size, size)):
+ self.assert_close(extent, size, atol=0.0, rtol=0.0)
+
+ @pytest.mark.xfail(strict=True, raises=AssertionError, reason="kornia#4018: bbox_generator3d extent is size + 1")
+ def test_convention_bbox_generator3d_matches_bbox_generator_extent_4018(self, device, dtype):
+ start = torch.tensor([1.0], device=device, dtype=dtype)
+ size = torch.tensor([3.0], device=device, dtype=dtype)
+ for extent in infer_bbox_shape3d(bbox_generator3d(start, start, start, size, size, size)):
+ self.assert_close(extent, size, atol=0.0, rtol=0.0)
+
+ def test_wart_bbox_to_mask3d_truncates_fractional_coordinates_4015(self, device, dtype):
+ # Wart pin for kornia#4015: x in [1.6, 3.4] truncates to 1..3 and y, z in [1.6, 2.4] to
+ # 1..2, filled inclusively: twelve voxels, where Boxes3D.to_mask fills two (test_boxes.py).
+ boxes = torch.tensor(
+ [
+ [
+ [1.6, 1.6, 1.6],
+ [3.4, 1.6, 1.6],
+ [3.4, 2.4, 1.6],
+ [1.6, 2.4, 1.6],
+ [1.6, 1.6, 2.4],
+ [3.4, 1.6, 2.4],
+ [3.4, 2.4, 2.4],
+ [1.6, 2.4, 2.4],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ expected = torch.zeros(1, 1, 5, 5, 6, device=device, dtype=torch.float32)
+ expected[0, 0, 1:3, 1:3, 1:4] = 1.0
+ self.assert_close(bbox_to_mask3d(boxes, (5, 5, 6)), expected, atol=0.0, rtol=0.0)
+
+ def test_wart_bbox_to_mask3d_returns_float32_with_a_channel_axis_4250(self, device, dtype):
+ # Wart pin for kornia#4250: the 3D free function returns float32 (B, 1, D, H, W) whatever the input dtype,
+ # while bbox_to_mask keeps the input dtype and returns (B, H, W). Neither carries a gradient.
+ cuboid = self._unit_cuboid(device, dtype)
+ mask = bbox_to_mask3d(cuboid, (4, 5, 6))
+ assert mask.shape == (1, 1, 4, 5, 6)
+ assert mask.dtype == torch.float32
+ assert bbox_to_mask3d(cuboid.repeat(2, 1, 1), (4, 5, 6)).shape == (2, 1, 4, 5, 6)
+ assert bbox_to_mask3d(cuboid.to(torch.int64), (4, 5, 6)).dtype == torch.float32
+ assert not bbox_to_mask3d(cuboid.clone().requires_grad_(), (4, 5, 6)).requires_grad
+ square = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
+ assert bbox_to_mask(square, 6, 5).dtype == dtype
+
+ @pytest.mark.parametrize("case", ["full_width", "full_height", "full_depth", "overhang"])
+ def test_wart_bbox_to_mask3d_fills_the_whole_volume_when_a_box_spans_an_axis_4255(self, device, dtype, case):
+ # Wart pin for kornia#4255: once one axis slab covers every index of the (4, 4, 5) volume, the
+ # union-of-planes intermediate is all true and its reductions lose the other two bounds, so all
+ # 80 voxels are filled where Boxes3D.to_mask fills the intersection. The interior box is unaffected.
+ xyzxyz_plus, intersection = {
+ "full_width": ([0.0, 1.0, 1.0, 4.0, 2.0, 2.0], 20.0),
+ "full_height": ([1.0, 0.0, 1.0, 2.0, 3.0, 2.0], 16.0),
+ "full_depth": ([1.0, 1.0, 0.0, 2.0, 2.0, 3.0], 16.0),
+ "overhang": ([-1.0, 1.0, 1.0, 5.0, 2.0, 2.0], 20.0),
+ }[case]
+ boxes = Boxes3D.from_tensor(torch.tensor([xyzxyz_plus], device=device, dtype=dtype), mode="xyzxyz_plus")
+ assert bbox_to_mask3d(boxes.data, (4, 4, 5)).sum().item() == 80.0
+ assert boxes.to_mask(4, 4, 5).sum().item() == intersection
+ interior = Boxes3D.from_tensor(
+ torch.tensor([[1.0, 1.0, 1.0, 2.0, 2.0, 2.0]], device=device, dtype=dtype), mode="xyzxyz_plus"
+ )
+ assert bbox_to_mask3d(interior.data, (4, 4, 5)).sum().item() == interior.to_mask(4, 4, 5).sum().item() == 8.0
+
+ @pytest.mark.xfail(
+ strict=True,
+ raises=AssertionError,
+ reason="kornia#4255: bbox_to_mask3d fills the whole volume for a full-axis box",
+ )
+ def test_convention_bbox_to_mask3d_intersects_the_axis_ranges_for_a_full_axis_box_4255(self, device, dtype):
+ # x spans the whole width 0..4, y and z cover 1..2: the intersection is 2 * 2 * 5 = 20 voxels.
+ boxes = Boxes3D.from_tensor(
+ torch.tensor([[0.0, 1.0, 1.0, 4.0, 2.0, 2.0]], device=device, dtype=dtype), mode="xyzxyz_plus"
+ )
+ expected = torch.zeros(1, 1, 4, 4, 5, device=device, dtype=torch.float32)
+ expected[0, 0, 1:3, 1:3, :] = 1.0
+ self.assert_close(bbox_to_mask3d(boxes.data, (4, 4, 5)), expected, atol=0.0, rtol=0.0)
+
class TestNMS(BaseTester):
def test_convention_nms_uses_exclusive_xyxy_iou_4008(self, device, dtype):
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index 22a42f073..1b42e42f4 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -21,7 +21,7 @@ import pytest
import torch
from kornia.geometry import boxes as boxes_module
-from kornia.geometry.bbox import infer_bbox_shape
+from kornia.geometry.bbox import bbox_to_mask, bbox_to_mask3d, infer_bbox_shape, infer_bbox_shape3d
from kornia.geometry.boxes import Boxes, Boxes3D, VideoBoxes
from testing.base import BaseTester
@@ -837,6 +837,65 @@ class TestBoxes2D(BaseTester):
assert transformed.data is original
assert transformed.data.shape == original.shape
+ def test_wart_to_mask_and_bbox_to_mask_take_opposite_size_orders_4014(self, device, dtype):
+ # Wart pin for kornia#4014: Boxes.to_mask(height, width) and bbox_to_mask(boxes, width, height)
+ # are the same call, and both return (N, height, width) in the box dtype.
+ vertices = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
+ method = Boxes(vertices).to_mask(3, 5)
+ assert method.shape == (1, 3, 5)
+ assert method.dtype == dtype
+ self.assert_close(method, bbox_to_mask(vertices, 5, 3), atol=0.0, rtol=0.0)
+ assert Boxes(vertices).to_mask(5, 3).shape == (1, 5, 3)
+ assert Boxes(vertices[None]).to_mask(3, 5).shape == (1, 1, 3, 5)
+
+ def test_wart_to_mask_rounds_the_exclusive_export_half_open_4015(self, device, dtype):
+ # Wart pin for kornia#4015: the fractional box [1.4, 3.6] x [1.4, 2.6] exports as xyxy
+ # [1.4, 1.4, 4.6, 3.6], rounds to [1, 1, 5, 4], and fills the half-open ranges: twelve pixels,
+ # where bbox_to_mask fills two (test_bbox.py). A box entirely outside the image is clamped
+ # onto the border and fills nothing, and a box that requires grad is rejected.
+ boxes = torch.tensor([[[1.4, 1.4], [3.6, 1.4], [3.6, 2.6], [1.4, 2.6]]], device=device, dtype=dtype)
+ expected = torch.zeros(1, 5, 6, device=device, dtype=dtype)
+ expected[0, 1:4, 1:5] = 1.0
+ self.assert_close(Boxes(boxes).to_mask(5, 6), expected, atol=0.0, rtol=0.0)
+ assert bbox_to_mask(boxes, 6, 5).sum().item() == 2.0
+
+ outside = torch.tensor([[[6.0, 6.0], [9.0, 6.0], [9.0, 9.0], [6.0, 9.0]]], device=device, dtype=dtype)
+ assert Boxes(outside).to_mask(5, 5).sum().item() == 0.0
+ with pytest.raises(RuntimeError, match="differentiable"):
+ Boxes(boxes.clone().requires_grad_()).to_mask(5, 6)
+
+ def test_wart_to_mask_fills_the_origin_pixel_for_list_padding_rows_4252(self, device, dtype):
+ # Wart pin for kornia#4252: a list-backed object exports its zero padding rows as the exclusive xyxy box
+ # [0, 0, 1, 1] (see the padding note on the class), so to_mask marks pixel (0, 0) in the
+ # mask channel of every padding entry instead of leaving it empty.
+ box = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
+ boxes = Boxes([box, torch.cat([box, box + 2.0])])
+ mask = boxes.to_mask(5, 5)
+ assert mask.shape == (2, 2, 5, 5)
+ expected_padding = torch.zeros(5, 5, device=device, dtype=dtype)
+ expected_padding[0, 0] = 1.0
+ self.assert_close(mask[0, 1], expected_padding, atol=0.0, rtol=0.0)
+ self.assert_close(mask[0, 0], mask[1, 0], atol=0.0, rtol=0.0)
+
+ @pytest.mark.parametrize("case", ["fractional", "outside", "negative", "rotated", "batched"])
+ def test_convention_to_mask_export_path_matches_loop_path(self, case, device, dtype, monkeypatch):
+ # Convention pin: the CPU/MPS loop path and the vectorized path taken on CUDA and under
+ # export produce the same mask. The vectorized branch is selected by patching the module's
+ # is_exporting predicate; on CUDA both calls already take it.
+ fractional = torch.tensor([[[1.4, 1.4], [3.6, 1.4], [3.6, 2.6], [1.4, 2.6]]], device=device, dtype=dtype)
+ data = {
+ "fractional": fractional,
+ "outside": torch.tensor([[[3.0, 3.0], [9.0, 3.0], [9.0, 9.0], [3.0, 9.0]]], device=device, dtype=dtype),
+ "negative": fractional - 3.0,
+ "rotated": torch.tensor([[[2.0, 0.0], [4.0, 2.0], [2.0, 4.0], [0.0, 2.0]]], device=device, dtype=dtype),
+ "batched": fractional.expand(2, 3, 4, 2).contiguous(),
+ }[case]
+ loop = Boxes(data).to_mask(5, 6)
+ monkeypatch.setattr(boxes_module, "is_exporting", lambda: True)
+ vectorized = Boxes(data).to_mask(5, 6)
+ assert loop.shape == vectorized.shape
+ self.assert_close(loop, vectorized, atol=0.0, rtol=0.0)
+
class TestTransformBoxes2D(BaseTester):
def test_transform_boxes(self, device, dtype):
@@ -1363,6 +1422,201 @@ class TestBbox3D(BaseTester):
expected_grad[0, tied_vertex, 0] = 0.25
self.assert_close(vertices.grad, expected_grad)
+ @staticmethod
+ def _asymmetric_xyzxyz(device, dtype) -> torch.Tensor:
+ # Exclusive corners: x in 1..5, y in 2..5, z in 3..8, so width 4, height 3, depth 5.
+ return torch.tensor([[1.0, 2.0, 3.0, 5.0, 5.0, 8.0]], device=device, dtype=dtype)
+
+ def test_convention_from_tensor_xyzxyz_stores_inclusive_front_then_back_vertices(self, device, dtype):
+ # Convention pin: the stored form is inclusive (each max corner is one less than the
+ # exclusive input) in front top-left, top-right, bottom-right, bottom-left order followed by
+ # the same four back vertices; get_boxes_shape returns (depths, heights, widths); every
+ # export mode derives from that stored form, and the mode string is lowercased.
+ xyzxyz = self._asymmetric_xyzxyz(device, dtype)
+ boxes = Boxes3D.from_tensor(xyzxyz, mode="XYZXYZ")
+ assert boxes.mode == "xyzxyz"
+ expected_data = torch.tensor(
+ [
+ [
+ [1.0, 2.0, 3.0],
+ [4.0, 2.0, 3.0],
+ [4.0, 4.0, 3.0],
+ [1.0, 4.0, 3.0],
+ [1.0, 2.0, 7.0],
+ [4.0, 2.0, 7.0],
+ [4.0, 4.0, 7.0],
+ [1.0, 4.0, 7.0],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ self.assert_close(boxes.data, expected_data, atol=0.0, rtol=0.0)
+ for extent, expected in zip(boxes.get_boxes_shape(), (5.0, 3.0, 4.0)):
+ self.assert_close(extent, torch.tensor([expected], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+
+ self.assert_close(boxes.to_tensor("xyzxyz"), xyzxyz, atol=0.0, rtol=0.0)
+ expected_plus = torch.tensor([[1.0, 2.0, 3.0, 4.0, 4.0, 7.0]], device=device, dtype=dtype)
+ self.assert_close(boxes.to_tensor("xyzxyz_plus"), expected_plus, atol=0.0, rtol=0.0)
+ expected_whd = torch.tensor([[1.0, 2.0, 3.0, 4.0, 3.0, 5.0]], device=device, dtype=dtype)
+ self.assert_close(boxes.to_tensor("xyzwhd"), expected_whd, atol=0.0, rtol=0.0)
+ self.assert_close(boxes.to_tensor("vertices_plus"), expected_data, atol=0.0, rtol=0.0)
+ offsets = 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]], device=device)
+ offsets = torch.cat([offsets, offsets + torch.tensor([0.0, 0.0, 1.0], device=device)]).to(dtype)
+ self.assert_close(boxes.to_tensor("vertices"), expected_data + offsets, atol=0.0, rtol=0.0)
+ with pytest.raises(ValueError, match="shape"):
+ Boxes3D.from_tensor(expected_data, mode="vertices")
+
+ def test_wart_vertices_export_is_exclusive_for_inclusive_bbox3d_consumers_4009(self, device, dtype):
+ # Wart pin for kornia#4009 (its 3D form): 'vertices' is an exclusive export, while
+ # infer_bbox_shape3d reads vertices as inclusive and therefore adds one per axis.
+ boxes = Boxes3D.from_tensor(self._asymmetric_xyzxyz(device, dtype), mode="xyzxyz")
+ for extent, expected in zip(infer_bbox_shape3d(boxes.to_tensor("vertices")), (6.0, 4.0, 5.0)):
+ self.assert_close(extent, torch.tensor([expected], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ for extent, expected in zip(infer_bbox_shape3d(boxes.to_tensor("vertices_plus")), (5.0, 3.0, 4.0)):
+ self.assert_close(extent, torch.tensor([expected], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+
+ def test_convention_from_tensor_rejects_non_positive_extents_in_mode_convention(self, device, dtype):
+ # Convention pin: validate_boxes=True rejects extents <= 0 measured in the given mode, so a
+ # zero-span 'xyzxyz_plus' box (inclusive extent one) passes where the same corners in
+ # 'xyzxyz' fail; each axis is checked; validate_boxes=False accepts everything.
+ def build(values, mode, validate_boxes=True):
+ return Boxes3D.from_tensor(torch.tensor([values], device=device, dtype=dtype), mode, validate_boxes)
+
+ with pytest.raises(ValueError, match="widths"):
+ build([1.0, 2.0, 3.0, 1.0, 6.0, 8.0], "xyzxyz")
+ assert build([1.0, 2.0, 3.0, 1.0, 6.0, 8.0], "xyzxyz_plus").data.shape == (1, 8, 3)
+ with pytest.raises(ValueError, match="widths"):
+ build([1.0, 2.0, 3.0, 0.0, 6.0, 8.0], "xyzxyz_plus")
+ with pytest.raises(ValueError, match="heights"):
+ build([1.0, 2.0, 3.0, 5.0, 2.0, 8.0], "xyzxyz")
+ with pytest.raises(ValueError, match="depths"):
+ build([1.0, 2.0, 3.0, 5.0, 6.0, 3.0], "xyzxyz")
+ with pytest.raises(ValueError, match="widths"):
+ build([1.0, 2.0, 3.0, 0.0, 4.0, 5.0], "xyzwhd")
+ assert build([1.0, 2.0, 3.0, 0.5, 4.0, 5.0], "xyzwhd").data.shape == (1, 8, 3)
+ assert build([1.0, 2.0, 3.0, 1.0, 6.0, 8.0], "xyzxyz", validate_boxes=False).data.shape == (1, 8, 3)
+
+ def test_wart_constructor_and_from_tensor_have_different_integer_policies_4012(self, device):
+ # Wart pin for kornia#4012 (its 3D form): the constructor rejects integer coordinates
+ # unless told to cast, while from_tensor silently casts them to float32.
+ vertices = torch.tensor([[[1, 2, 3]] * 8], device=device)
+ with pytest.raises(ValueError, match="floating point"):
+ Boxes3D(vertices)
+ assert Boxes3D(vertices, raise_if_not_floating_point=False).dtype == torch.float32
+ integer = torch.tensor([[1, 2, 3, 5, 5, 8]], device=device)
+ assert Boxes3D.from_tensor(integer, mode="xyzxyz").dtype == torch.float32
+ assert Boxes3D.from_tensor(integer.to(torch.float16), mode="xyzxyz").dtype == torch.float16
+
+ def test_wart_to_tensor_default_mode_ignores_the_stored_label_4251(self, device, dtype):
+ # Wart pin for kornia#4251: Boxes3D.to_tensor() defaults to 'xyzxyz' whatever mode the object was built in,
+ # while Boxes.to_tensor() defaults to the stored mode. The copy path of transform_boxes
+ # also resets the label to 'xyzxyz_plus' where the in-place path keeps it.
+ xyzwhd = torch.tensor([[1.0, 2.0, 3.0, 4.0, 3.0, 5.0]], device=device, dtype=dtype)
+ boxes = Boxes3D.from_tensor(xyzwhd, mode="xyzwhd")
+ assert boxes.mode == "xyzwhd"
+ self.assert_close(boxes.to_tensor(), self._asymmetric_xyzxyz(device, dtype), atol=0.0, rtol=0.0)
+ xywh = torch.tensor([[1.0, 2.0, 4.0, 3.0]], device=device, dtype=dtype)
+ self.assert_close(Boxes.from_tensor(xywh, mode="xywh").to_tensor(), xywh, atol=0.0, rtol=0.0)
+
+ identity = torch.eye(4, device=device, dtype=dtype)
+ assert boxes.transform_boxes(identity).mode == "xyzxyz_plus"
+ assert boxes.transform_boxes_(identity).mode == "xyzwhd"
+
+ @pytest.mark.xfail(
+ strict=True, raises=AssertionError, reason="kornia#4251: Boxes3D.to_tensor() ignores the stored mode label"
+ )
+ def test_convention_to_tensor_default_mode_is_the_stored_label_4251(self, device, dtype):
+ xyzwhd = torch.tensor([[1.0, 2.0, 3.0, 4.0, 3.0, 5.0]], device=device, dtype=dtype)
+ self.assert_close(Boxes3D.from_tensor(xyzwhd, mode="xyzwhd").to_tensor(), xyzwhd, atol=0.0, rtol=0.0)
+
+ @staticmethod
+ def _fractional_cuboid(device, dtype) -> torch.Tensor:
+ # x in [1.6, 3.4], y and z in [1.6, 2.4].
+ return torch.tensor(
+ [
+ [
+ [1.6, 1.6, 1.6],
+ [3.4, 1.6, 1.6],
+ [3.4, 2.4, 1.6],
+ [1.6, 2.4, 1.6],
+ [1.6, 1.6, 2.4],
+ [3.4, 1.6, 2.4],
+ [3.4, 2.4, 2.4],
+ [1.6, 2.4, 2.4],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ def test_convention_to_mask_takes_depth_height_width_and_matches_the_free_function(self, device, dtype):
+ # Convention pin: to_mask(depth, height, width) returns (N, depth, height, width) in the box
+ # dtype, equal to bbox_to_mask3d's channel on integer vertices; a box entirely outside the
+ # volume fills nothing, and a box that requires grad is rejected.
+ cuboid = Boxes3D.from_tensor(
+ torch.tensor([[1.0, 1.0, 1.0, 3.0, 3.0, 2.0]], device=device, dtype=dtype), mode="xyzxyz_plus"
+ )
+ mask = cuboid.to_mask(4, 5, 6)
+ assert mask.shape == (1, 4, 5, 6)
+ assert mask.dtype == dtype
+ self.assert_close(mask, bbox_to_mask3d(cuboid.data, (4, 5, 6))[:, 0].to(dtype), atol=0.0, rtol=0.0)
+ assert mask.sum().item() == 18.0
+ assert Boxes3D(cuboid.data[None]).to_mask(4, 5, 6).shape == (1, 1, 4, 5, 6)
+ assert Boxes3D(cuboid.data + 10.0).to_mask(4, 5, 6).sum().item() == 0.0
+ with pytest.raises(RuntimeError, match="differentiable"):
+ Boxes3D(cuboid.data.clone().requires_grad_()).to_mask(4, 5, 6)
+
+ def test_wart_to_mask_rounds_the_exclusive_export_half_open_4015(self, device, dtype):
+ # Wart pin for kornia#4015 (3D): the fractional cuboid exports as xyzxyz
+ # [1.6, 1.6, 1.6, 4.4, 3.4, 3.4], rounds to [2, 2, 2, 4, 3, 3], and fills the half-open
+ # ranges: two voxels, where bbox_to_mask3d truncates and fills twelve (test_bbox.py).
+ boxes = self._fractional_cuboid(device, dtype)
+ expected = torch.zeros(1, 5, 5, 6, device=device, dtype=dtype)
+ expected[0, 2, 2, 2:4] = 1.0
+ self.assert_close(Boxes3D(boxes).to_mask(5, 5, 6), expected, atol=0.0, rtol=0.0)
+ assert bbox_to_mask3d(boxes, (5, 5, 6)).sum().item() == 12.0
+
+ @pytest.mark.parametrize("case", ["fractional", "outside", "negative", "batched"])
+ def test_convention_to_mask_export_path_matches_loop_path(self, case, device, dtype, monkeypatch):
+ # Convention pin: the loop path and the grid-comparison path taken under export produce
+ # the same mask. The export branch is selected by patching the module's is_exporting predicate.
+ fractional = self._fractional_cuboid(device, dtype)
+ data = {
+ "fractional": fractional,
+ "outside": fractional + 10.0,
+ "negative": fractional - 2.0,
+ "batched": fractional.expand(2, 2, 8, 3).contiguous(),
+ }[case]
+ loop = Boxes3D(data).to_mask(5, 5, 6)
+ monkeypatch.setattr(boxes_module, "is_exporting", lambda: True)
+ vectorized = Boxes3D(data).to_mask(5, 5, 6)
+ assert loop.shape == vectorized.shape
+ self.assert_close(loop, vectorized, atol=0.0, rtol=0.0)
+
+ def test_convention_transform_boxes_in_place_rebinds_data(self, device, dtype):
+ # Convention pin: the copy path leaves the source untouched and returns a new object; the
+ # in-place path returns self but rebinds the internal tensor, so an earlier data reference
+ # is stale. A (3, 3) matrix is rejected and a (1, 4, 4) matrix applies to unbatched boxes.
+ source = Boxes3D.from_tensor(self._asymmetric_xyzxyz(device, dtype), mode="xyzxyz")
+ original = source.data
+ scale = torch.diag(torch.tensor([2.0, 3.0, 4.0, 1.0], device=device, dtype=dtype))
+ copied = source.transform_boxes(scale)
+ assert copied is not source
+ assert source.data is original
+ expected = torch.tensor([[2.0, 6.0, 12.0, 8.0, 12.0, 28.0]], device=device, dtype=dtype)
+ self.assert_close(copied.to_tensor("xyzxyz_plus"), expected, atol=0.0, rtol=0.0)
+ self.assert_close(source.transform_boxes(scale[None]).data, copied.data, atol=0.0, rtol=0.0)
+
+ result = source.transform_boxes_(scale)
+ assert result is source
+ assert source.data is not original
+ self.assert_close(source.data, copied.data, atol=0.0, rtol=0.0)
+ untouched = Boxes3D.from_tensor(self._asymmetric_xyzxyz(device, dtype)).data
+ self.assert_close(original, untouched, atol=0.0, rtol=0.0)
+ with pytest.raises(ValueError, match="4, 4"):
+ source.transform_boxes(torch.eye(3, device=device, dtype=dtype))
+
class TestTransformBoxes3D(BaseTester):
def test_transform_boxes(self, device, dtype):
@@ -1541,3 +1795,98 @@ class TestVideoBoxes(BaseTester):
return VideoBoxes.from_tensor(x).to_tensor() # type: ignore[return-value]
self.gradcheck(_wrap, (boxes,))
+
+ def test_convention_from_tensor_stores_vertices_plus_and_restores_the_temporal_axis(self, device, dtype):
+ # Convention pin: the (B, T, N, 4, 2) input is stored unchanged as (B * T, N, 4, 2) batched
+ # 'vertices_plus' data; every Boxes export mode is available and comes back with the
+ # temporal axis restored; integer input is cast to float32; a transformation matrix must
+ # carry the flattened batch of B * T matrices.
+ boxes = self._sample_video_boxes(device, dtype, batch=2, time=3, n_boxes=1)
+ video_boxes = VideoBoxes.from_tensor(boxes)
+ assert video_boxes.mode == "vertices_plus"
+ assert video_boxes.temporal_channel_size == 3
+ self.assert_close(video_boxes.data, boxes.reshape(6, 1, 4, 2), atol=0.0, rtol=0.0)
+
+ xyxy = video_boxes.to_tensor("xyxy")
+ assert isinstance(xyxy, torch.Tensor)
+ assert xyxy.shape == (2, 3, 1, 4)
+ expected_xyxy = torch.tensor([1.0, 1.0, 4.0, 4.0], device=device, dtype=dtype).expand(2, 3, 1, 4)
+ self.assert_close(xyxy, expected_xyxy, atol=0.0, rtol=0.0)
+ assert VideoBoxes.from_tensor(boxes.to(torch.int64)).dtype == torch.float32
+ with pytest.raises(ValueError, match="BxTxNx4x2"):
+ VideoBoxes.from_tensor(torch.zeros(2, 3, 1, 4, 3, device=device, dtype=dtype))
+
+ with pytest.raises(ValueError, match="Batch size mismatch"):
+ video_boxes.transform_boxes(torch.eye(3, device=device, dtype=dtype))
+ transformed = video_boxes.transform_boxes(torch.eye(3, device=device, dtype=dtype).expand(6, 3, 3))
+ assert isinstance(transformed, VideoBoxes)
+ assert transformed.temporal_channel_size == 3
+ self.assert_close(transformed.to_tensor(), boxes, atol=0.0, rtol=0.0)
+
+ def test_wart_inherited_methods_break_on_the_temporal_wrapper_4249(self, device, dtype):
+ # Wart pin for kornia#4249: the to_tensor override drops the as_padded_sequence keyword that
+ # the inherited get_boxes_shape and to_mask pass, and indexing builds a wrapper without the temporal size,
+ # so its to_tensor fails. The inherited methods keep the temporal size whether they copy or update in
+ # place; test_convention_inherited_methods_split_copies_from_in_place_updates pins which is which.
+ video_boxes = VideoBoxes.from_tensor(self._sample_video_boxes(device, dtype, batch=2, time=3, n_boxes=1))
+ with pytest.raises(TypeError, match="as_padded_sequence"):
+ video_boxes.get_boxes_shape()
+ with pytest.raises(TypeError, match="as_padded_sequence"):
+ video_boxes.to_mask(4, 5)
+ frame = video_boxes[0]
+ assert isinstance(frame, VideoBoxes)
+ with pytest.raises(AttributeError, match="temporal_channel_size"):
+ frame.to_tensor()
+ bounds = torch.zeros(6, 2, device=device, dtype=dtype)
+ assert video_boxes.clamp(bounds, bounds + 2.0).temporal_channel_size == 3
+ assert video_boxes.filter_boxes_by_area(1.0).temporal_channel_size == 3
+ assert video_boxes.translate(bounds + 1.0).temporal_channel_size == 3
+ assert video_boxes.pad(torch.ones(6, 4, device=device, dtype=dtype)).temporal_channel_size == 3
+ assert video_boxes.merge(video_boxes).temporal_channel_size == 3
+ assert video_boxes.to(dtype=torch.float32).temporal_channel_size == 3
+
+ def test_convention_inherited_methods_split_copies_from_in_place_updates(self, device, dtype):
+ # Convention pin: transform_boxes, translate, clamp, filter_boxes_by_area and merge copy through
+ # clone, so they return a new VideoBoxes carrying the temporal size and leave the source
+ # untouched; pad, unpad, to and type update self in place and return it.
+ video_boxes = VideoBoxes.from_tensor(self._sample_video_boxes(device, dtype, batch=2, time=3, n_boxes=1))
+ original = video_boxes.data.clone()
+ bounds = torch.zeros(6, 2, device=device, dtype=dtype)
+ copies = [
+ video_boxes.transform_boxes(torch.eye(3, device=device, dtype=dtype).expand(6, 3, 3)),
+ video_boxes.translate(bounds + 1.0),
+ video_boxes.clamp(bounds, bounds + 2.0),
+ video_boxes.filter_boxes_by_area(1.0),
+ video_boxes.merge(video_boxes),
+ ]
+ for copy in copies:
+ assert copy is not video_boxes
+ assert isinstance(copy, VideoBoxes)
+ assert copy.temporal_channel_size == 3
+ self.assert_close(video_boxes.data, original, atol=0.0, rtol=0.0)
+
+ padding = torch.ones(6, 4, device=device, dtype=dtype)
+ assert video_boxes.pad(padding) is video_boxes
+ self.assert_close(video_boxes.data, original + 1.0, atol=0.0, rtol=0.0)
+ assert video_boxes.unpad(padding) is video_boxes
+ self.assert_close(video_boxes.data, original, atol=0.0, rtol=0.0)
+ other = torch.float16 if dtype == torch.float32 else torch.float32
+ assert video_boxes.to(dtype=other) is video_boxes
+ assert video_boxes.dtype == other
+ assert video_boxes.type(dtype) is video_boxes
+ assert video_boxes.dtype == dtype
+ assert video_boxes.temporal_channel_size == 3
+
+ @pytest.mark.xfail(
+ strict=True, raises=AssertionError, reason="kornia#4249: VideoBoxes.get_boxes_shape and to_mask raise TypeError"
+ )
+ def test_convention_inherited_shape_and_mask_work_on_the_temporal_wrapper_4249(self, device, dtype):
+ video_boxes = VideoBoxes.from_tensor(self._sample_video_boxes(device, dtype, batch=2, time=3, n_boxes=1))
+ try:
+ heights, widths = video_boxes.get_boxes_shape()
+ mask = video_boxes.to_mask(4, 5)
+ except TypeError as error:
+ raise AssertionError(str(error)) from error
+ # One extent per box and one (4, 5) mask per box, whichever way the temporal axis is laid out.
+ assert heights.numel() == widths.numel() == 6
+ assert mask.shape[-2:] == (4, 5) and mask.numel() == 6 * 4 * 5