Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix rank-4 bbox input validation (#4218)

Hari Om Tiwarie4b266b16f49
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e50a6f0d2..051f17490 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -282,6 +282,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
instead of `view`, so a non-contiguous leading-dimension stride (a transpose, a slice that drops boxes, an
`expand`) returns a boolean as documented instead of raising `RuntimeError`. (#4174)
+* `infer_bbox_shape` and `bbox_to_mask` now reject rank-4 `(B, N, 4, 2)` inputs with `ShapeError`. Previously,
+ `N < 3` raised an incidental `IndexError`, while `N >= 3` silently returned `(B, 2)` extents computed from the
+ wrong vertices. (#4218)
+
* Constructing `ScaleSpaceDetector` with `compile_modules` no longer permanently mutates the process-global
`torch._dynamo.config.capture_dynamic_output_shape_ops` setting. (#4134)
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index 58f80d1c0..ee681385d 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -21,6 +21,7 @@ from typing import Optional
import torch
+from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.core.utils import is_exporting
from .linalg import transform_points
@@ -152,16 +153,14 @@ def infer_bbox_shape(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
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 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.
+ Raises:
+ ShapeError: if ``boxes`` does not have shape :math:`(N, 4, 2)`.
+
Returns:
- Bounding box heights, shape of :math:`(N,)`.
- Bounding box widths, shape of :math:`(N,)`.
@@ -182,6 +181,8 @@ def infer_bbox_shape(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
(tensor([2., 2.]), tensor([2., 3.]))
"""
+ KORNIA_CHECK_SHAPE(boxes, ["N", "4", "2"])
+
width: torch.Tensor = boxes[:, 1, 0] - boxes[:, 0, 0] + 1
height: torch.Tensor = boxes[:, 2, 1] - boxes[:, 0, 1] + 1
return height, width
@@ -249,6 +250,9 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
Returns:
the output mask tensor.
+ Raises:
+ ShapeError: if ``boxes`` does not have shape :math:`(B, 4, 2)`.
+
Note:
It is currently non-differentiable.
@@ -267,6 +271,8 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
[0., 0., 0., 0., 0.]]])
"""
+ KORNIA_CHECK_SHAPE(boxes, ["B", "4", "2"])
+
# NOTE: `validate_bbox`'s boolean result was previously computed here and discarded β€” it
# never raised, so it performed no validation while adding a data-dependent graph break
# (`torch.any(...)` -> Python `if`) that blocked torch.compile fullgraph (e.g. RandomErasing,
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index c08d8953e..0f9c5b2ae 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -230,10 +230,9 @@ class Boxes:
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>`_.
+ ``'vertices'``, which they read as one pixel larger per axis. Both consumers require unbatched
+ :math:`(N, 4, 2)` input and raise :class:`~kornia.core.exceptions.ShapeError` for a batched
+ :math:`(B, N, 4, 2)` export, so index or flatten it before passing it.
: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
diff --git a/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.py
index 6eb8749e3..296c86250 100644
--- a/tests/geometry/test_bbox.py
+++ b/tests/geometry/test_bbox.py
@@ -19,9 +19,11 @@ import pytest
import torch
import kornia
+from kornia.core.exceptions import ShapeError
from kornia.geometry.bbox import (
bbox_generator,
bbox_generator3d,
+ bbox_to_mask,
infer_bbox_shape,
infer_bbox_shape3d,
nms,
@@ -65,17 +67,19 @@ class TestBbox2D(BaseTester):
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))
+ @pytest.mark.parametrize("num_boxes", [2, 3])
+ def test_infer_bbox_shape_rejects_rank4_4180(self, device, dtype, num_boxes):
+ boxes = torch.zeros(1, num_boxes, 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)
+ with pytest.raises(ShapeError, match="expected 3 dimensions, got 4"):
+ infer_bbox_shape(boxes)
+
+ @pytest.mark.parametrize("num_boxes", [2, 3])
+ def test_bbox_to_mask_rejects_rank4_4180(self, device, dtype, num_boxes):
+ boxes = torch.zeros(1, num_boxes, 4, 2, device=device, dtype=dtype)
+
+ with pytest.raises(ShapeError, match="expected 3 dimensions, got 4"):
+ bbox_to_mask(boxes, width=5, height=5)
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