Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): honor elastic transform padding modes (#5987)

NIKHILb2b2eafd766d
diff --git a/changelog.d/5987.breaking.md b/changelog.d/5987.breaking.md
new file mode 100644
index 000000000..7cda0902e
--- /dev/null
+++ b/changelog.d/5987.breaking.md
@@ -0,0 +1 @@
+`elastic_transform2d` and `RandomElasticTransform` no longer clamp the displaced sampling grid to `[-1, 1]` before `grid_sample`, so `padding_mode` now applies to coordinates displaced outside the image. Previously `"zeros"`, the default of both, and `"reflection"` repeated the edge pixel there (`"zeros"` at half intensity, a quarter in the corners, with the default `align_corners=False` and bilinear sampling); now those samples are zero-padded or reflected as requested. Default outputs therefore change near the image border wherever the displacement points outward, and so do the gradients through those samples. `"border"` output is unchanged. This correctness fix ships without a deprecation window.
diff --git a/kornia/augmentation/_2d/geometric/elastic_transform.py b/kornia/augmentation/_2d/geometric/elastic_transform.py
index 448714c63..de83f246b 100644
--- a/kornia/augmentation/_2d/geometric/elastic_transform.py
+++ b/kornia/augmentation/_2d/geometric/elastic_transform.py
@@ -35,10 +35,10 @@ class RandomElasticTransform(AugmentationBase2D):
containers have limitations (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).
Noise has shape ``(B, 2, H, W)`` with channels ``(x, y)``; ``alpha`` scales displacement in
normalized sampling coordinates, whereas ``kernel_size`` and ``sigma`` use ``(y, x)`` order.
- The displaced grid is clamped to ``[-1, 1]`` before sampling. Zero ``alpha`` is an identity warp up to
- interpolation roundoff for either ``align_corners``. Its defaults and the ``align_corners`` split across
- classes (`#4412 <https://github.com/kornia/kornia/issues/4412>`_) are listed on
- :class:`~kornia.augmentation.GeometricAugmentationBase2D`.
+ Coordinates displaced outside the image are filled by ``padding_mode`` as in ``grid_sample``. Zero
+ ``alpha`` is an identity warp up to interpolation roundoff for either ``align_corners``. Its defaults and
+ the ``align_corners`` split across classes (`#4412 <https://github.com/kornia/kornia/issues/4412>`_) are
+ listed on :class:`~kornia.augmentation.GeometricAugmentationBase2D`.
Args:
kernel_size: the size of the Gaussian kernel, in the y and x directions, respectively.
diff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.py
index 121167a0f..9d04a7637 100644
--- a/kornia/geometry/transform/elastic_transform.py
+++ b/kornia/geometry/transform/elastic_transform.py
@@ -50,6 +50,8 @@ def elastic_transform2d(
``sigma``) and scaled by ``alpha``
- align_corners: ``False`` by default (the matrix warps default to ``True``); zero
``noise`` is an identity under either setting
+ - coordinates displaced outside the image are filled by ``padding_mode`` as in ``grid_sample``:
+ zeros, the edge value, or the reflected image
Args:
image: Input image to be transformed with shape :math:`(B, C, H, W)`.
@@ -135,6 +137,4 @@ def elastic_transform2d(
identity = torch.eye(2, 3, device=image.device, dtype=grid_dtype).unsqueeze(0)
grid = F.affine_grid(identity, [1, 1, h, w], align_corners=align_corners)
grid = grid.to(image.dtype)
- return _torch_grid_sample(
- image, (grid + disp).clamp(-1, 1), align_corners=align_corners, mode=mode, padding_mode=padding_mode
- )
+ return _torch_grid_sample(image, grid + disp, align_corners=align_corners, mode=mode, padding_mode=padding_mode)
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 5377a89f7..35269a462 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -5333,6 +5333,24 @@ class TestRandomFisheye(BaseTester):
class TestRandomElasticTransform(BaseTester):
+ def test_zero_padding_with_replayed_noise(self, device, dtype):
+ image = torch.ones(1, 1, 5, 5, device=device, dtype=dtype)
+ noise = torch.zeros(1, 2, 5, 5, device=device, dtype=dtype)
+ noise[:, 0] = 1.0
+ params = {"noise": noise, "batch_prob": torch.ones(1, device=device, dtype=dtype)}
+ aug = RandomElasticTransform(
+ kernel_size=(1, 1),
+ sigma=(1.0, 1.0),
+ alpha=(0.8, 0.0),
+ resample="nearest",
+ padding_mode="zeros",
+ p=1.0,
+ )
+ expected = torch.ones_like(image)
+ expected[..., -2:] = 0.0
+ self.assert_close(aug(image, params=params), expected)
+ self.assert_close(aug(image, params=aug._params), expected)
+
def test_smoke(self, device, dtype):
img = torch.rand(1, 1, 2, 2, device=device, dtype=dtype)
aug = RandomElasticTransform(p=1.0)
diff --git a/tests/augmentation/test_conventions_geometric_dense.py b/tests/augmentation/test_conventions_geometric_dense.py
index cfd8524e7..18016b9dc 100644
--- a/tests/augmentation/test_conventions_geometric_dense.py
+++ b/tests/augmentation/test_conventions_geometric_dense.py
@@ -44,15 +44,20 @@ class TestDenseGeometricConventions(BaseTester):
assert K.RandomElasticTransform().flags["align_corners"] is False
@pytest.mark.parametrize("axis", [0, 1])
- def test_convention_elastic_normalized_xy_displacement_and_clamp(self, device, dtype, axis):
- image = torch.arange(35, device=device, dtype=dtype).reshape(1, 1, 5, 7)
+ def test_convention_elastic_normalized_xy_displacement_and_zero_padding(self, device, dtype, axis):
+ image = torch.arange(45, device=device, dtype=dtype).reshape(1, 1, 5, 9)
# With corner alignment, one input pixel is 2/(size - 1) normalized units.
- alpha = (2 / 6, 0.0) if axis == 0 else (0.0, 2 / 4)
+ # These dimensions keep both the identity grid and displacement exact in half precision.
+ alpha = (2 / 8, 0.0) if axis == 0 else (0.0, 2 / 4)
aug = K.RandomElasticTransform(kernel_size=(1, 1), alpha=alpha, align_corners=True, p=1)
params = aug.forward_parameters(image.shape)
- assert params["noise"].shape == (1, 2, 5, 7)
- params["noise"] = torch.ones(1, 2, 5, 7, device=device, dtype=dtype)
- expected = image[..., [1, 2, 3, 4, 5, 6, 6]] if axis == 0 else image[..., [1, 2, 3, 4, 4], :]
+ assert params["noise"].shape == (1, 2, 5, 9)
+ params["noise"] = torch.ones(1, 2, 5, 9, device=device, dtype=dtype)
+ expected = torch.zeros_like(image)
+ if axis == 0:
+ expected[..., :-1] = image[..., 1:]
+ else:
+ expected[..., :-1, :] = image[..., 1:, :]
self.assert_close(aug(image, params=params), expected)
@pytest.mark.parametrize("kernel_size", [(3, 1), (1, 3)])
diff --git a/tests/geometry/transform/test_elastic_transform.py b/tests/geometry/transform/test_elastic_transform.py
index 99a62442c..ab98a2ff7 100644
--- a/tests/geometry/transform/test_elastic_transform.py
+++ b/tests/geometry/transform/test_elastic_transform.py
@@ -34,6 +34,85 @@ def _row_spread_std(out: torch.Tensor, reference: torch.Tensor) -> torch.Tensor:
class TestElasticTransform(BaseTester):
+ @pytest.mark.parametrize("padding_mode", ["zeros", "border", "reflection"])
+ @pytest.mark.parametrize("align_corners", [False, True])
+ @pytest.mark.parametrize("mode", ["bilinear", "nearest"])
+ @pytest.mark.parametrize("axis", [0, 1])
+ @pytest.mark.parametrize("direction", [-1, 1])
+ def test_displacement_outside_image(self, device, dtype, padding_mode, align_corners, mode, axis, direction):
+ if padding_mode == "border" and not supports_2d_border_padding(device):
+ pytest.skip("MPS 2D grid_sample lacks 'border' padding")
+ image = torch.arange(1, 6, device=device, dtype=dtype).view(1, 1, 1, 5).expand(2, 2, 5, 5).clone()
+ rows = {
+ "zeros": [3.0, 4.0, 5.0, 0.0, 0.0],
+ "border": [3.0, 4.0, 5.0, 5.0, 5.0],
+ "reflection": [3.0, 4.0, 5.0, 4.0, 3.0] if align_corners else [3.0, 4.0, 5.0, 5.0, 4.0],
+ }
+ expected = torch.tensor(rows[padding_mode], device=device, dtype=dtype).view(1, 1, 1, 5).expand_as(image)
+ if direction == -1:
+ image, expected = image.flip(-1), expected.flip(-1)
+ if axis == 1:
+ image, expected = image.transpose(-2, -1), expected.transpose(-2, -1)
+ noise = torch.zeros(2, 2, 5, 5, device=device, dtype=dtype)
+ noise[:, axis] = direction
+ # A constant displacement of two pixels; the 1-tap Gaussian leaves the field unchanged.
+ scale = 1.0 if align_corners else 0.8
+ output = elastic_transform2d(
+ image,
+ noise,
+ kernel_size=(1, 1),
+ sigma=(1.0, 1.0),
+ alpha=(scale, scale),
+ align_corners=align_corners,
+ mode=mode,
+ padding_mode=padding_mode,
+ )
+ # A rounded float16 grid can land just inside the zero-padding boundary (5 * 2**-9 here).
+ tolerance = {"rtol": 1e-3, "atol": 1e-2} if dtype == torch.float16 else {}
+ self.assert_close(output, expected, **tolerance)
+
+ @pytest.mark.parametrize("align_corners", [False, True])
+ def test_zero_padding_fractional_boundary(self, device, align_corners):
+ image = torch.ones(1, 1, 5, 5, device=device)
+ noise = torch.zeros(1, 2, 5, 5, device=device)
+ noise[:, 0] = 1.0
+ # Three quarters of a pixel beyond the final centre leaves one quarter of its bilinear weight.
+ scale = 0.375 if align_corners else 0.3
+ output = elastic_transform2d(
+ image,
+ noise,
+ kernel_size=(1, 1),
+ sigma=(1.0, 1.0),
+ alpha=(scale, 0.0),
+ align_corners=align_corners,
+ padding_mode="zeros",
+ )
+ expected = torch.ones_like(image)
+ expected[..., -1] = 0.25
+ self.assert_close(output, expected)
+
+ @pytest.mark.parametrize("align_corners", [False, True])
+ def test_reflected_displacement_gradient(self, device, align_corners):
+ image = torch.arange(1, 6, device=device, dtype=torch.float32).view(1, 1, 1, 5).expand(1, 1, 5, 5)
+ noise = torch.zeros(1, 2, 5, 5, device=device)
+ noise[:, 0] = 1.0
+ noise.requires_grad_()
+ # The last column samples strictly inside the reflected image, beyond normalized coordinate 1.
+ scale = 1.15 if align_corners else 0.92
+ output = elastic_transform2d(
+ image,
+ noise,
+ kernel_size=(1, 1),
+ sigma=(1.0, 1.0),
+ alpha=(scale, 0.0),
+ align_corners=align_corners,
+ padding_mode="reflection",
+ )
+ gradient = torch.autograd.grad(output[..., -1].sum(), noise)[0]
+ expected = torch.zeros_like(noise)
+ expected[:, 0, :, -1] = -2.3
+ self.assert_close(gradient, expected)
+
def test_smoke(self, device, dtype):
image = torch.rand(1, 4, 5, 5, device=device, dtype=dtype)
noise = torch.rand(1, 2, 5, 5, device=device, dtype=dtype)
@@ -221,8 +300,7 @@ class TestElasticTransform(BaseTester):
assert spread_y_wide > 5 * spread_x_wide
def test_convention_padding_mode_border_differs_from_zeros(self, device, dtype):
- # padding_mode is forwarded: once the displacement pushes the (clamped) sampling grid to the
- # edge, the 'zeros' default and 'border' give different rows.
+ # Displacements beyond the image use zeros by default, or the edge pixel with 'border'.
image = torch.zeros(1, 1, 5, 5, device=device, dtype=dtype)
image[0, 0, 2, 4] = 5.0
noise = torch.zeros(1, 2, 5, 5, device=device, dtype=dtype)
@@ -236,7 +314,7 @@ class TestElasticTransform(BaseTester):
# elastic_transform2d(image, noise, **kwargs)[0, 0, 2] # default row
# elastic_transform2d(image, noise, padding_mode="border", **kwargs)[0, 0, 2] # 'border' row
out_default = elastic_transform2d(image, noise, **kwargs)
- expected_zeros_row = torch.tensor([2.5, 2.5, 2.5, 2.5, 2.5], device=device, dtype=dtype)
+ expected_zeros_row = torch.zeros(5, device=device, dtype=dtype)
self.assert_close(out_default[0, 0, 2], expected_zeros_row, rtol=1e-2, atol=1e-2)
if not supports_2d_border_padding(device):