Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): keep RandomPerspective finite on a size-1 axis (#4985)

Mohansree Vijayakumar7a3f03d07852
diff --git a/changelog.d/4985.fixed.md b/changelog.d/4985.fixed.md
new file mode 100644
index 000000000..62d4d1856
--- /dev/null
+++ b/changelog.d/4985.fixed.md
@@ -0,0 +1 @@
+`RandomPerspective` no longer returns a NaN transform matrix and output for an image with a spatial dimension of 1. That axis now gets a unit source extent and no corner offset, so its single row or column maps onto itself and only the other axis is warped; at `distortion_scale=0` the warp is the identity. Images larger than one pixel along both axes draw and warp exactly as before.
diff --git a/kornia/augmentation/_2d/geometric/perspective.py b/kornia/augmentation/_2d/geometric/perspective.py
index 934da75f0..07a133b46 100644
--- a/kornia/augmentation/_2d/geometric/perspective.py
+++ b/kornia/augmentation/_2d/geometric/perspective.py
@@ -54,8 +54,10 @@ class RandomPerspective(GeometricAugmentationBase2D):
- ``basic`` samples each corner inward by at most ``distortion_scale * (W, H) / 2``. ``area_preserving``
samples each coordinate in both directions over the same extent.
- with ``distortion_scale=0`` and ``H > 1``, ``W > 1``, the warp is an identity up to numerical precision
- for either ``align_corners``. If either spatial dimension is 1, the coincident source corners give a NaN
- matrix and output even at zero distortion (`#4787 <https://github.com/kornia/kornia/issues/4787>`_).
+ for either ``align_corners``.
+ - a spatial dimension of 1 is not distorted: its source corners span a unit extent instead of ``0`` and
+ its offsets are zero, so the single row or column maps onto itself and only the other axis is warped.
+ At ``distortion_scale=0`` this is the identity.
.. note::
This function internally uses :func:`kornia.geometry.transform.warp_perspective`.
diff --git a/kornia/augmentation/random_generator/_2d/perspective.py b/kornia/augmentation/random_generator/_2d/perspective.py
index 74a90dac7..bf30571c1 100644
--- a/kornia/augmentation/random_generator/_2d/perspective.py
+++ b/kornia/augmentation/random_generator/_2d/perspective.py
@@ -80,18 +80,25 @@ class PerspectiveGenerator(RandomGeneratorBase):
_check_positive_int_or_traced(height, "height")
_check_positive_int_or_traced(width, "width")
+ # A size-1 axis would make two source corners coincide and the homography singular. Give it a
+ # unit extent and no offset instead: the single row or column then maps onto itself.
+ flat_x = isinstance(width, int) and width == 1
+ flat_y = isinstance(height, int) and height == 1
+ x_end = 1 if flat_x else width - 1
+ y_end = 1 if flat_y else height - 1
+
# Subtract before casting: bbox_generator subtracts in the tensor dtype,
# which changes large half-precision image coordinates.
start_points = _constant_tensor(
- [[[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]],
+ [[[0, 0], [x_end, 0], [x_end, y_end], [0, y_end]]],
device=_device,
dtype=_dtype,
)
start_points = start_points.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
+ fx = self._distortion_scale * (0 if flat_x else width) / 2
+ fy = self._distortion_scale * (0 if flat_y else height) / 2
factor = torch.stack([fx, fy], dim=0).view(-1, 1, 2).to(device=_device, dtype=_dtype)
diff --git a/tests/augmentation/test_conventions_geometric_matrix.py b/tests/augmentation/test_conventions_geometric_matrix.py
index 87cafd622..1714ce707 100644
--- a/tests/augmentation/test_conventions_geometric_matrix.py
+++ b/tests/augmentation/test_conventions_geometric_matrix.py
@@ -147,16 +147,47 @@ class TestConventionGeometricMatrices(BaseTester):
@pytest.mark.parametrize("size", [(1, 7), (5, 1), (1, 1)])
@pytest.mark.parametrize("align_corners", [False, True])
- def test_wart_random_perspective_singleton_dimensions_4787(self, device, dtype, size, align_corners):
+ def test_convention_random_perspective_singleton_dimensions_4787(self, device, dtype, size, align_corners):
+ # #4787: a size-1 axis gets a unit source extent and no offset, so the solve is not degenerate and
+ # zero distortion is the identity.
height, width = size
image = torch.arange(height * width, device=device, dtype=dtype).reshape(1, 1, height, width)
augmentation = K.RandomPerspective(0.0, align_corners=align_corners, p=1.0)
output = augmentation(image)
- # Coincident source corners make the perspective solve degenerate, even without distortion.
- assert torch.isnan(augmentation.transform_matrix).all()
- assert torch.isnan(output).all()
+ assert torch.isfinite(augmentation.transform_matrix).all()
+ self.assert_close(output, image, low_tolerance=True)
+
+ @pytest.mark.parametrize("sampling_method", ["basic", "area_preserving"])
+ @pytest.mark.parametrize("size", [(1, 7), (5, 1)])
+ def test_convention_random_perspective_does_not_distort_a_singleton_axis_4787(
+ self, device, dtype, size, sampling_method
+ ):
+ height, width = size
+ torch.manual_seed(0)
+ image = torch.rand(4, 1, height, width, device=device, dtype=dtype)
+ augmentation = K.RandomPerspective(1.0, p=1.0, sampling_method=sampling_method)
+
+ output = augmentation(image)
+
+ assert torch.isfinite(output).all()
+ # The singleton axis spans a unit source extent (the other axis keeps its inclusive corners).
+ start = augmentation._params["start_points"]
+ x_end, y_end = (width - 1, 1) if height == 1 else (1, height - 1)
+ expected = torch.tensor([[0, 0], [x_end, 0], [x_end, y_end], [0, y_end]]).to(start).expand_as(start)
+ assert torch.equal(start, expected)
+ matrix = augmentation.transform_matrix.to(torch.float32)
+ assert torch.isfinite(matrix).all()
+ # The singleton row (or column) maps onto itself, while the other axis is still warped.
+ axis = 1 if height == 1 else 0
+ extent = width if height == 1 else height
+ points = torch.zeros(4, extent, 2, device=device)
+ points[..., 1 - axis] = torch.arange(extent, device=device, dtype=torch.float32)
+ homogeneous = torch.cat([points, torch.ones_like(points[..., :1])], dim=-1) @ matrix.transpose(-1, -2)
+ mapped = homogeneous[..., :2] / homogeneous[..., 2:]
+ self.assert_close(mapped[..., axis], torch.zeros_like(mapped[..., axis]), low_tolerance=True)
+ assert not torch.allclose(mapped[..., 1 - axis], points[..., 1 - axis], atol=1e-2)
def test_wart_random_affine_rotation_sign_4408(self, device, dtype):
x = torch.zeros(1, 1, 7, 7, device=device, dtype=dtype)