Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix: respect align_corners in elastic transform grid (#4382)

3901984509cry64a15120fb73
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8fb94185c..bbee881c3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -410,6 +410,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* Make calibration `distort_points` and `undistort_points` tilt checks compatible with
`torch.compile(fullgraph=True)`, preserving eager behavior. (#4391)
* Canny hysteresis preserves the input dtype, avoiding a convolution dtype mismatch for half-precision images. (#4393)
+* `elastic_transform2d` now builds its identity sampling grid with the requested `align_corners`
+ convention, so a zero displacement field preserves the input image. (closes #4235). (#4382)
* `rad2deg` and `deg2rad` now handle integer tensor inputs correctly and preserve
float64 precision. `angle_to_rotation_matrix` inherits the corrected conversion,
diff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.py
index 78aa2fe48..06f9511d4 100644
--- a/kornia/geometry/transform/elastic_transform.py
+++ b/kornia/geometry/transform/elastic_transform.py
@@ -23,7 +23,6 @@ import torch.nn.functional as F
from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.filters import filter2d_separable
from kornia.filters.kernels import get_gaussian_kernel1d
-from kornia.geometry.grid import create_meshgrid
__all__ = ["elastic_transform2d"]
@@ -122,9 +121,19 @@ def elastic_transform2d(
# torch.stack and F.normalize displacement
disp = torch.cat([disp_x, disp_y], 1).permute(0, 2, 3, 1)
- # Warp image based on displacement matrix
+ # Warp image based on displacement matrix. ``create_meshgrid`` uses the
+ # corner-aligned coordinate convention, while ``grid_sample`` interprets
+ # normalized coordinates according to ``align_corners``. Build the identity
+ # grid with the same convention as the sampler so that zero displacement is
+ # an identity transform for both values of ``align_corners``.
_, _, h, w = image.shape
- grid = create_meshgrid(h, w, device=image.device).to(image.dtype)
+ # CPU does not implement ``affine_grid`` for half or bfloat16 tensors. Generate those
+ # coordinate grids in float32 and narrow once; the grid must still match the image dtype
+ # before it is passed to ``grid_sample``.
+ grid_dtype = torch.float32 if image.dtype in (torch.float16, torch.bfloat16) else image.dtype
+ 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)
warped = F.grid_sample(
image, (grid + disp).clamp(-1, 1), align_corners=align_corners, mode=mode, padding_mode=padding_mode
)
diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txt
index 59b705bab..b1b164867 100644
--- a/testing/half_precision_xfails/cpu_bfloat16.txt
+++ b/testing/half_precision_xfails/cpu_bfloat16.txt
@@ -483,7 +483,6 @@ call builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCenter
call builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCenterCrop3D::test_center_crop_357_batch[cpu-bfloat16-crop_size2]
call builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCropByBoxes3D::test_crop_by_boxes_no_resizing[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCropByBoxes3D::test_crop_by_boxes_resizing[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_elastic_transform.py::TestElasticTransform::test_values[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper3D::test_normalize_homography_identity[cpu-bfloat16-1]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper3D::test_normalize_homography_identity[cpu-bfloat16-3]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_normalize_homography_identity[cpu-bfloat16-1]
diff --git a/tests/geometry/transform/test_elastic_transform.py b/tests/geometry/transform/test_elastic_transform.py
index 2033cb585..d07383332 100644
--- a/tests/geometry/transform/test_elastic_transform.py
+++ b/tests/geometry/transform/test_elastic_transform.py
@@ -103,13 +103,33 @@ class TestElasticTransform(BaseTester):
noise = torch.ones(1, 2, 3, 3, device=device, dtype=dtype)
expected = torch.tensor(
- [[[[0.0005, 0.3795, 0.1905], [0.1034, 0.4235, 0.0702], [0.0259, 0.2007, 0.2193]]]],
+ [[[[0.0062, 0.7506, 0.7487], [0.2058, 0.4235, 0.1397], [0.1036, 0.3996, 0.8693]]]],
device=device,
dtype=dtype,
)
actual = elastic_transform2d(image, noise)
- self.assert_close(actual, expected, atol=1e-3, rtol=1e-3)
+ # bfloat16's 7-bit mantissa makes the reference values intentionally rounded more
+ # coarsely than float16/float32; retain a tolerance that covers that representation.
+ tolerance = 1e-2 if dtype is torch.bfloat16 else 1e-3
+ self.assert_close(actual, expected, atol=tolerance, rtol=tolerance)
+
+ @pytest.mark.parametrize("align_corners", [False, True])
+ def test_zero_displacement_is_identity(self, device, dtype, align_corners):
+ """Zero displacement should preserve the input for either grid convention."""
+ image = torch.arange(16.0, device=device, dtype=dtype).reshape(1, 1, 4, 4)
+ noise = torch.zeros(1, 2, 4, 4, device=device, dtype=dtype)
+
+ output = elastic_transform2d(
+ image,
+ noise,
+ kernel_size=(3, 3),
+ sigma=(1.0, 1.0),
+ alpha=(1.0, 1.0),
+ align_corners=align_corners,
+ )
+
+ self.assert_close(output, image)
@pytest.mark.parametrize("requires_grad", [True, False])
def test_gradcheck(self, device, dtype, requires_grad):