Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): handle singleton axes in RandomPerspective3D (#5071)

Puttala Jeevan Kumarb59318173570
diff --git a/changelog.d/5071.fixed.md b/changelog.d/5071.fixed.md
new file mode 100644
index 000000000..7a090e402
--- /dev/null
+++ b/changelog.d/5071.fixed.md
@@ -0,0 +1 @@
+`RandomPerspective3D` now handles singleton spatial dimensions without a singular perspective solve. These axes get unit source extents and zero corner offsets, and their single slice, row or column maps onto itself. Zero distortion gives an identity transform (output identity still needs `align_corners=True` while #4503 is open). Non-singleton volumes and random draws are unchanged.
diff --git a/kornia/augmentation/_3d/geometric/perspective.py b/kornia/augmentation/_3d/geometric/perspective.py
index fe0e6fcc9..0fad0c1a9 100644
--- a/kornia/augmentation/_3d/geometric/perspective.py
+++ b/kornia/augmentation/_3d/geometric/perspective.py
@@ -53,6 +53,9 @@ class RandomPerspective3D(GeometricAugmentationBase3D):
``float64``. The false-setting normalization defect is tracked in
`#4503 <https://github.com/kornia/kornia/issues/4503>`_.
- the default interpolation is bilinear and the default ``align_corners`` is ``False``.
+ - a spatial dimension of 1 gets a unit source extent and no corner offset, so its single
+ slice, row or column maps onto itself. At ``distortion_scale=0`` the transform matrix is
+ the identity; output identity still requires ``align_corners=True`` as described above.
Examples:
>>> import torch
@@ -106,7 +109,13 @@ class RandomPerspective3D(GeometricAugmentationBase3D):
def compute_transformation(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
- return get_perspective_transform3d(params["start_points"], params["end_points"]).to(input)
+ start_points, end_points = params["start_points"], params["end_points"]
+ if isinstance(input.shape[-1], int) and input.shape[-1] == 1:
+ # The solver uses corners 0, 1, 2, 5, 7: only two lie on x=0. Swap the x/z or x/y
+ # corner ordering so three constrain each singleton plane to map onto itself.
+ order = [0, 4, 7, 3, 1, 5, 6, 2] if input.shape[-3] > 1 else [0, 3, 2, 1, 4, 7, 6, 5]
+ start_points, end_points = start_points[:, order], end_points[:, order]
+ return get_perspective_transform3d(start_points, end_points).to(input)
def apply_transform(
self,
diff --git a/kornia/augmentation/random_generator/_3d/perspective.py b/kornia/augmentation/random_generator/_3d/perspective.py
index 9685bad45..41b598d4f 100644
--- a/kornia/augmentation/random_generator/_3d/perspective.py
+++ b/kornia/augmentation/random_generator/_3d/perspective.py
@@ -72,17 +72,26 @@ class PerspectiveGenerator3D(RandomGeneratorBase):
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([self.distortion_scale])
+ # Coincident source corners make the perspective solve singular. Give singleton axes a
+ # unit extent and no offset, as in the 2D generator.
+ flat_x = isinstance(width, int) and width == 1
+ flat_y = isinstance(height, int) and height == 1
+ flat_z = isinstance(depth, int) and depth == 1
+ x_end = 1 if flat_x else width - 1
+ y_end = 1 if flat_y else height - 1
+ z_end = 1 if flat_z else depth - 1
+
start_points: torch.Tensor = _constant_tensor(
[
[
[0, 0, 0],
- [width - 1, 0, 0],
- [width - 1, height - 1, 0],
- [0, height - 1, 0],
- [0, 0, depth - 1],
- [width - 1, 0, depth - 1],
- [width - 1, height - 1, depth - 1],
- [0, height - 1, depth - 1],
+ [x_end, 0, 0],
+ [x_end, y_end, 0],
+ [0, y_end, 0],
+ [0, 0, z_end],
+ [x_end, 0, z_end],
+ [x_end, y_end, z_end],
+ [0, y_end, z_end],
]
],
device=_device,
@@ -90,9 +99,9 @@ class PerspectiveGenerator3D(RandomGeneratorBase):
).expand(batch_size, -1, -1)
# generate random offset not larger than half of the image
- fx = self._distortion_scale * width / 2
- fy = self._distortion_scale * height / 2
- fz = self._distortion_scale * depth / 2
+ fx = self._distortion_scale * (0 if flat_x else width) / 2
+ fy = self._distortion_scale * (0 if flat_y else height) / 2
+ fz = self._distortion_scale * (0 if flat_z else depth) / 2
factor = torch.stack([fx, fy, fz], 0).view(-1, 1, 3).to(device=_device, dtype=_dtype)
diff --git a/tests/augmentation/test_conventions_3d.py b/tests/augmentation/test_conventions_3d.py
index 615c7c7e5..5f6859f1e 100644
--- a/tests/augmentation/test_conventions_3d.py
+++ b/tests/augmentation/test_conventions_3d.py
@@ -174,6 +174,62 @@ class Test3DAugmentationConventions(BaseTester):
volume = torch.arange(60, device=device, dtype=dtype).reshape(1, 1, 3, 4, 5)
self.assert_close(K.RandomPerspective3D(0.0, p=1.0)(volume), volume)
+ @pytest.mark.parametrize("size", [(1, 4, 5), (4, 1, 5), (4, 5, 1), (1, 1, 5), (1, 4, 1), (4, 1, 1), (1, 1, 1)])
+ @pytest.mark.parametrize("align_corners", [False, True])
+ def test_convention_random_perspective3d_singleton_identity_5001(self, device, dtype, size, align_corners):
+ if not supports_bilinear_3d_grid_sample(device, dtype):
+ pytest.skip("bilinear 3D grid_sample is unavailable for this device and dtype")
+ volume = torch.linspace(0, 1, 2 * size[0] * size[1] * size[2], device=device, dtype=dtype).reshape(2, 1, *size)
+ augmentation = K.RandomPerspective3D(0.0, p=1.0, align_corners=align_corners)
+
+ output = augmentation(volume)
+
+ assert output.shape == volume.shape
+ assert output.device == volume.device and output.dtype == dtype
+ assert torch.isfinite(output).all()
+ matrix = augmentation.transform_matrix
+ assert torch.isfinite(matrix).all()
+ self.assert_close(matrix, torch.eye(4, device=device, dtype=dtype).expand(2, -1, -1))
+ # #4503 still affects output identity with align_corners=False, independently of the corner solve.
+ if align_corners:
+ self.assert_close(output, volume, low_tolerance=True)
+
+ @pytest.mark.parametrize("size", [(1, 4, 5), (4, 1, 5), (4, 5, 1), (1, 1, 5), (1, 4, 1), (4, 1, 1), (1, 1, 1)])
+ @pytest.mark.parametrize("align_corners", [False, True])
+ @pytest.mark.parametrize("same_on_batch", [False, True])
+ def test_convention_random_perspective3d_singleton_axis_stays_fixed_5001(
+ self, device, dtype, size, align_corners, same_on_batch
+ ):
+ if not supports_bilinear_3d_grid_sample(device, dtype):
+ pytest.skip("bilinear 3D grid_sample is unavailable for this device and dtype")
+ torch.manual_seed(0)
+ volume = torch.rand(2, 1, *size, device=device, dtype=dtype)
+ augmentation = K.RandomPerspective3D(0.5, p=1.0, align_corners=align_corners, same_on_batch=same_on_batch)
+
+ output = augmentation(volume)
+
+ assert torch.isfinite(output).all()
+ start, end = augmentation._params["start_points"], augmentation._params["end_points"]
+ x, y, z = (max(n - 1, 1) for n in reversed(size))
+ expected = start.new_tensor(
+ [[0, 0, 0], [x, 0, 0], [x, y, 0], [0, y, 0], [0, 0, z], [x, 0, z], [x, y, z], [0, y, z]]
+ ).expand_as(start)
+ assert torch.equal(start, expected)
+ if same_on_batch:
+ assert torch.equal(end[0], end[1])
+ matrix = augmentation.transform_matrix.to(torch.float32)
+ assert torch.isfinite(matrix).all()
+ zz, yy, xx = torch.meshgrid(*(torch.arange(n, device=device, dtype=torch.float32) for n in size), indexing="ij")
+ points = torch.stack([xx, yy, zz], dim=-1).reshape(1, -1, 3).expand(2, -1, -1)
+ homogeneous = torch.cat([points, torch.ones_like(points[..., :1])], dim=-1) @ matrix.transpose(-1, -2)
+ mapped = homogeneous[..., :3] / homogeneous[..., 3:]
+ for axis, extent in enumerate(reversed(size)):
+ if extent == 1:
+ assert torch.equal(start[..., axis], end[..., axis])
+ self.assert_close(mapped[..., axis], torch.zeros_like(mapped[..., axis]), low_tolerance=True)
+ else:
+ assert not torch.allclose(mapped[..., axis], points[..., axis], atol=1e-2)
+
@pytest.mark.device_agnostic
def test_wart_positive_roll_direction_splits_the_rotation_entry_points_4408(self):
# An off-centre marker in a 7 x 7 slice: a counter-clockwise quarter turn sends (row 1, col 4) to (2, 1),