Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): align 3D box sizes with 2D generator (#6088)

Devulapalli Naga Sri Vaishnavi74c7bd48cd64
diff --git a/changelog.d/6088.fixed.md b/changelog.d/6088.fixed.md
new file mode 100644
index 000000000..30f5dbd6c
--- /dev/null
+++ b/changelog.d/6088.fixed.md
@@ -0,0 +1 @@
+`kornia.geometry.bbox.bbox_generator3d` now places each far corner at `start + size - 1`, so `infer_bbox_shape3d` reads back the requested width, height and depth and `bbox_to_mask3d` covers `width * height * depth` voxels, as with `bbox_generator` and `Boxes3D.from_tensor(..., mode="xyzwhd")`. Before, the far corner was at `start + size`, and every box measured one voxel larger than requested on each axis. Code that passed `size - 1` to work around this now gets boxes one voxel smaller on each axis and should pass `size`. `CropGenerator3D` did this and now passes `size`, so `RandomCrop3D` and the generator's `src` and `dst` boxes are unchanged.
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
index ee392411d..081c699e7 100644
--- a/kornia/augmentation/random_generator/_3d/crop.py
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -129,7 +129,7 @@ class CropGenerator3D(RandomGeneratorBase):
z_start = _truncate_to_start(_adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch), z_diff)
crop_src = bbox_generator3d(
- x_start.view(-1), y_start.view(-1), z_start.view(-1), size[:, 2] - 1, size[:, 1] - 1, size[:, 0] - 1
+ x_start.view(-1), y_start.view(-1), z_start.view(-1), size[:, 2], size[:, 1], size[:, 0]
)
if self.resize_to is None:
@@ -137,9 +137,9 @@ class CropGenerator3D(RandomGeneratorBase):
torch.zeros(batch_size, device=_device, dtype=_dtype),
torch.zeros(batch_size, device=_device, dtype=_dtype),
torch.zeros(batch_size, device=_device, dtype=_dtype),
- size[:, 2] - 1,
- size[:, 1] - 1,
- size[:, 0] - 1,
+ size[:, 2],
+ size[:, 1],
+ size[:, 0],
)
else:
if not (
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index 3f57f9bcb..dbc96f178 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -154,8 +154,7 @@ def infer_bbox_shape(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
Convention:
Vertices are **inclusive**: a box covering pixels ``0..9`` has corners at ``0`` and ``9`` and width
- ``10``. The vertex-based helpers of this module share it, except :func:`bbox_generator3d`
- (`#4018 <https://github.com/kornia/kornia/issues/4018>`_); :func:`nms` takes exclusive ``xyxy`` and
+ ``10``. The vertex-based helpers of this module share it; :func:`nms` takes exclusive ``xyxy`` and
:func:`transform_bbox` converts ``'xywh'`` exclusively (``xmax = xmin + width``).
The order is clockwise top-left, top-right, bottom-right, bottom-left. The result is
``(heights, widths)``, read from fixed vertex indices, ``width = boxes[:, 1, 0] - boxes[:, 0, 0] + 1`` and
@@ -463,10 +462,6 @@ def bbox_generator(
the start. A scalar input gives a batch of one. The four tensors must share dtype and device, otherwise
``AssertionError``; the output keeps a gradient path.
- .. warning::
- :func:`bbox_generator3d` places its far corner at ``start + size`` instead:
- `#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,)`.
@@ -543,10 +538,8 @@ def bbox_generator3d(
The four front vertices precede the four back vertices. A scalar input gives a batch of one. The six
tensors must share dtype and device, otherwise ``AssertionError``; the output keeps a gradient path.
- .. warning::
- The far corner is at ``start + size``, one further than :func:`bbox_generator`, so
- :func:`infer_bbox_shape3d` reads back ``size + 1`` on every axis:
- `#4018 <https://github.com/kornia/kornia/issues/4018>`_.
+ The far corner is at ``start + size - 1`` (inclusive, see :func:`infer_bbox_shape3d`), so
+ :func:`infer_bbox_shape3d` reads back ``size`` on every axis, matching :func:`bbox_generator`.
Args:
x_start: a tensor containing the x coordinates of the bounding boxes to be extracted. Shape must be a scalar
@@ -571,22 +564,22 @@ def bbox_generator3d(
>>> depth = torch.tensor([30, 60])
>>> bbox_generator3d(x_start, y_start, z_start, width, height, depth)
tensor([[[ 0, 1, 2],
- [10, 1, 2],
- [10, 21, 2],
- [ 0, 21, 2],
- [ 0, 1, 32],
- [10, 1, 32],
- [10, 21, 32],
- [ 0, 21, 32]],
+ [ 9, 1, 2],
+ [ 9, 20, 2],
+ [ 0, 20, 2],
+ [ 0, 1, 31],
+ [ 9, 1, 31],
+ [ 9, 20, 31],
+ [ 0, 20, 31]],
<BLANKLINE>
[[ 3, 4, 5],
- [43, 4, 5],
- [43, 54, 5],
- [ 3, 54, 5],
- [ 3, 4, 65],
- [43, 4, 65],
- [43, 54, 65],
- [ 3, 54, 65]]])
+ [42, 4, 5],
+ [42, 53, 5],
+ [ 3, 53, 5],
+ [ 3, 4, 64],
+ [42, 4, 64],
+ [42, 53, 64],
+ [ 3, 53, 64]]])
"""
if not (x_start.shape == y_start.shape == z_start.shape and x_start.dim() in [0, 1]):
@@ -614,16 +607,14 @@ def bbox_generator3d(
bbox[:, :, 0] += x_start.view(-1, 1)
bbox[:, :, 1] += y_start.view(-1, 1)
bbox[:, :, 2] += z_start.view(-1, 1)
- # Far corner is at start + size, not start + size - 1: see the warning in this function's docstring (#4018).
- bbox[:, 1, 0] += width.view(-1)
- bbox[:, 2, 0] += width.view(-1)
- bbox[:, 2, 1] += height.view(-1)
- bbox[:, 3, 1] += height.view(-1)
+ bbox[:, 1, 0] += width.view(-1) - 1
+ bbox[:, 2, 0] += width.view(-1) - 1
+ bbox[:, 2, 1] += height.view(-1) - 1
+ bbox[:, 3, 1] += height.view(-1) - 1
# back
bbox_back = bbox.clone()
- # Far corner is at start + size, not start + size - 1: see the warning in this function's docstring (#4018).
- bbox_back[:, :, -1] += depth.view(-1, 1).expand(-1, 4)
+ bbox_back[:, :, -1] += (depth.view(-1, 1) - 1).expand(-1, 4)
return torch.cat([bbox, bbox_back], dim=1)
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 7094cc416..c74483aaf 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -1241,9 +1241,7 @@ class Boxes3D:
export trap `#4009 <https://github.com/kornia/kornia/issues/4009>`_. The integer-input split is
`#4012 <https://github.com/kornia/kornia/issues/4012>`_ and the validator split with
:func:`~kornia.geometry.bbox.validate_bbox` is `#4013 <https://github.com/kornia/kornia/issues/4013>`_.
- Boxes from :func:`~kornia.geometry.bbox.bbox_generator3d` measure one larger than requested:
- `#4018 <https://github.com/kornia/kornia/issues/4018>`_. The :meth:`to_tensor` default differs from
- :meth:`Boxes.to_tensor`, which defaults to the stored mode:
+ The :meth:`to_tensor` default differs from :meth:`Boxes.to_tensor`, which defaults to the stored mode:
`#4251 <https://github.com/kornia/kornia/issues/4251>`_.
"""
diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txt
index 52211377e..fe40d69b6 100644
--- a/testing/half_precision_xfails/cpu_bfloat16.txt
+++ b/testing/half_precision_xfails/cpu_bfloat16.txt
@@ -242,7 +242,6 @@ call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpP
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestGetRotationMatrix3d::test_rot90x[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestGetRotationMatrix3d::test_rot90y[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestGetRotationMatrix3d::test_rot90z[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestPerspectiveTransform3D::test_get_perspective_transform3d_2[cpu-bfloat16-1]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestWarpAffine3d::test_rotate_x[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestWarpAffine3d::test_rotate_y[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestWarpAffine3d::test_rotate_y_large[cpu-bfloat16]
diff --git a/tests/augmentation/test_random_generator_3d.py b/tests/augmentation/test_random_generator_3d.py
index 842086f9f..5ccf530f1 100644
--- a/tests/augmentation/test_random_generator_3d.py
+++ b/tests/augmentation/test_random_generator_3d.py
@@ -29,6 +29,7 @@ from kornia.augmentation.random_generator import (
RotationGenerator3D,
center_crop_generator3d,
)
+from kornia.geometry.bbox import infer_bbox_shape3d
from testing.base import assert_close
@@ -468,6 +469,17 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
resize_to=resize_to,
)(batch_shape=torch.Size((2, 1, *input_size)))
+ @pytest.mark.parametrize("resize_to", [None, (2, 3, 2)])
+ def test_boxes_measure_crop_and_output_size_4018(self, resize_to, device, dtype):
+ # kornia#4018: src measures the crop size and dst the output size, inclusively, with dst at the origin.
+ size = torch.tensor([[2, 3, 4], [1, 1, 1], [4, 5, 6]], device=device, dtype=dtype)
+ params = CropGenerator3D(size, resize_to)(torch.Size((3, 1, 4, 5, 6)))
+ output_size = size if resize_to is None else torch.tensor([resize_to] * 3, device=device, dtype=dtype)
+ for key, expected in (("src", size), ("dst", output_size)):
+ measured = torch.stack(infer_bbox_shape3d(params[key].to(dtype)), dim=-1)
+ assert_close(measured, expected, atol=0.0, rtol=0.0)
+ assert_close(params["dst"][:, 0], torch.zeros(3, 3, device=device, dtype=params["dst"].dtype))
+
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
param_gen = CropGenerator3D(
diff --git a/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.py
index 28a672e00..f5e76f5af 100644
--- a/tests/geometry/test_bbox.py
+++ b/tests/geometry/test_bbox.py
@@ -589,7 +589,7 @@ class TestBbox3D(BaseTester):
boxes = bbox_generator3d(*args)
assert boxes.shape == (1, 8, 3)
self.assert_close(boxes[0, 0], torch.tensor([1, 2, 3], device=device, dtype=dtype))
- self.assert_close(boxes[0, 6], torch.tensor([5, 7, 9], device=device, dtype=dtype))
+ self.assert_close(boxes[0, 6], torch.tensor([4, 6, 8], device=device, dtype=dtype))
def test_smoke(self, device, dtype):
# Sample two points of the 3d rect
@@ -757,25 +757,16 @@ class TestBbox3D(BaseTester):
with pytest.raises(ShapeError):
call()
- 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.
+ def test_bbox_generator3d_matches_bbox_generator_extent_4018(self, device, dtype):
+ # kornia#4018: 3D sizes are inclusive, just like the 2D generator. A size of 3 from x=1 spans x=1..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)
+ expected_x = torch.tensor([[1.0, 3.0, 3.0, 1.0, 1.0, 3.0, 3.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)):
+ for extent in infer_bbox_shape(bbox_generator(start, start, 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):
diff --git a/tests/geometry/transform/test_imgwarp3d.py b/tests/geometry/transform/test_imgwarp3d.py
index 56a1e154f..d5f753e0d 100644
--- a/tests/geometry/transform/test_imgwarp3d.py
+++ b/tests/geometry/transform/test_imgwarp3d.py
@@ -695,26 +695,26 @@ class TestPerspectiveTransform3D(BaseTester):
torch.randint_like(torch.ones(batch_size), 0, 50, dtype=dtype),
torch.randint_like(torch.ones(batch_size), 0, 50, dtype=dtype),
torch.randint_like(torch.ones(batch_size), 0, 50, dtype=dtype),
- torch.randint(0, 50, (1,), dtype=dtype).repeat(batch_size),
- torch.randint(0, 50, (1,), dtype=dtype).repeat(batch_size),
- torch.randint(0, 50, (1,), dtype=dtype).repeat(batch_size),
+ torch.randint(1, 50, (1,), dtype=dtype).repeat(batch_size),
+ torch.randint(1, 50, (1,), dtype=dtype).repeat(batch_size),
+ torch.randint(1, 50, (1,), dtype=dtype).repeat(batch_size),
).to(device=device, dtype=dtype)
dst = kornia.geometry.bbox.bbox_generator3d(
torch.randint_like(torch.ones(batch_size), 0, 50, dtype=dtype),
torch.randint_like(torch.ones(batch_size), 0, 50, dtype=dtype),
torch.randint_like(torch.ones(batch_size), 0, 50, dtype=dtype),
- torch.randint(0, 50, (1,), dtype=dtype).repeat(batch_size),
- torch.randint(0, 50, (1,), dtype=dtype).repeat(batch_size),
- torch.randint(0, 50, (1,), dtype=dtype).repeat(batch_size),
+ torch.randint(1, 50, (1,), dtype=dtype).repeat(batch_size),
+ torch.randint(1, 50, (1,), dtype=dtype).repeat(batch_size),
+ torch.randint(1, 50, (1,), dtype=dtype).repeat(batch_size),
).to(device=device, dtype=dtype)
out = kornia.geometry.transform.get_perspective_transform3d(src, dst)
if batch_size == 1:
expected = torch.tensor(
[
[
- [3.3000, 0.0000, 0.0000, -118.2000],
- [0.0000, 0.0769, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.5517, 28.7930],
+ [1.4348, 0.0000, 0.0000, -36.1304],
+ [0.0000, 1.0667, 0.0000, -38.6000],
+ [0.0000, 0.0000, 2.6250, -39.6250],
[0.0000, 0.0000, 0.0000, 1.0000],
]
],
@@ -725,15 +725,15 @@ class TestPerspectiveTransform3D(BaseTester):
expected = torch.tensor(
[
[
- [0.9630, 0.0000, 0.0000, -9.3702],
- [0.0000, 2.0000, 0.0000, -49.9999],
- [0.0000, 0.0000, 0.3830, 44.0213],
+ [0.0976, 0.0000, 0.0000, 28.7073],
+ [0.0000, 0.0889, 0.0000, 13.0667],
+ [0.0000, 0.0000, 11.0000, -94.0000],
[0.0000, 0.0000, 0.0000, 1.0000],
],
[
- [0.9630, 0.0000, 0.0000, -36.5555],
- [0.0000, 2.0000, 0.0000, -14.0000],
- [0.0000, 0.0000, 0.3830, 16.8940],
+ [0.0976, 0.0000, 0.0000, -2.8049],
+ [0.0000, 0.0889, 0.0000, 5.1111],
+ [0.0000, 0.0000, 11.0000, -291.0000],
[0.0000, 0.0000, 0.0000, 1.0000],
],
],