Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): accept zero scale in RandomThinPlateSpline (#4463)

trueoneplusoneb8ee3eb03b7a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4eefedb37..21c1234a3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -381,6 +381,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* `RandomThinPlateSpline(scale=0.0)` now generates zero control-point displacement instead of
+ raising an error when constructing a degenerate uniform distribution. (#4463)
* `RandomRain` with `same_on_batch=True` now samples the same number of rain drops for all samples in the batch. (#4453)
* `RandomRain` now rejects drop heights equal to the image height and absolute drop widths equal to the image
width with the documented validation error, instead of allowing boundary-sized drops to reach an internal
diff --git a/kornia/augmentation/_2d/geometric/thin_plate_spline.py b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
index d21ee534d..9d531b774 100644
--- a/kornia/augmentation/_2d/geometric/thin_plate_spline.py
+++ b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
@@ -31,7 +31,8 @@ class RandomThinPlateSpline(AugmentationBase2D):
.. image:: _static/img/RandomThinPlateSpline.png
Args:
- scale: the scale factor to apply to the destination points.
+ scale: the non-negative scale factor to apply to the destination points.
+ Zero leaves the control points unchanged.
align_corners: Interpolation flag used by ``grid_sample``.
mode: Interpolation mode used by `grid_sample`. Either 'bilinear' or 'nearest'.
same_on_batch: apply the same transformation across the batch.
@@ -69,7 +70,7 @@ class RandomThinPlateSpline(AugmentationBase2D):
"align_corners": align_corners,
"padding_mode": SamplePadding.get(padding_mode),
}
- self.dist = torch.distributions.Uniform(-scale, scale)
+ self.dist = None if scale == 0 else torch.distributions.Uniform(-scale, scale)
def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
B, _, _, _ = shape
@@ -84,7 +85,9 @@ class RandomThinPlateSpline(AugmentationBase2D):
dtype=dtype,
).expand(B, 5, 2)
- if self.same_on_batch:
+ if self.dist is None:
+ noise = torch.zeros_like(src)
+ elif self.same_on_batch:
noise = self.dist.rsample((1, 5, 2)).to(device=device, dtype=dtype)
noise = noise.expand(B, 5, 2)
else:
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 0c4b31f4c..d91f4095f 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -5545,6 +5545,35 @@ class TestRandomThinPlateSpline(CommonTests):
assert any(d > 0 for d in diffs)
+ @pytest.mark.parametrize("batch_size", [0, 1, 4])
+ @pytest.mark.parametrize("same_on_batch", [False, True])
+ def test_zero_scale_parameters(self, batch_size, same_on_batch, device, dtype):
+ aug = self._augmentation_cls(scale=0.0, same_on_batch=same_on_batch, p=1.0)
+ aug.set_rng_device_and_dtype(device=device, dtype=dtype)
+
+ params = aug.generate_parameters((batch_size, 3, 6, 8))
+
+ assert params["dst"].shape == (batch_size, 5, 2)
+ assert params["dst"].device == device
+ assert params["dst"].dtype == dtype
+ self.assert_close(params["dst"], params["src"], atol=0, rtol=0)
+
+ @pytest.mark.parametrize("same_on_batch", [False, True])
+ def test_zero_scale_identity(self, same_on_batch, device, dtype):
+ if dtype == torch.float16:
+ pytest.skip("get_tps_transform is numerically unstable in float16 (produces NaN)")
+ # align_corners=False has a separate sampling-grid defect tracked in #3928.
+ aug = self._augmentation_cls(scale=0.0, align_corners=True, same_on_batch=same_on_batch, p=1.0)
+ image = torch.arange(48, device=device, dtype=dtype).reshape(1, 1, 6, 8) / 48
+ image = image.expand(2, 1, 6, 8).clone().requires_grad_()
+
+ output = aug(image)
+
+ self.assert_close(output, image)
+ self.assert_close(aug(image, params=aug._params), output)
+ output.sum().backward()
+ self.assert_close(image.grad, torch.ones_like(image))
+
@pytest.mark.slow
def _test_gradcheck_implementation(self, params):
# RandomThinPlateSpline generates fresh random control points on every forward call,