Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): let RandomCrop.inverse select rows for an equal-size padded crop (#5525)

εŒΊζ’“η819cf97ad39c
diff --git a/changelog.d/5525.fixed.md b/changelog.d/5525.fixed.md
new file mode 100644
index 000000000..d71541ac8
--- /dev/null
+++ b/changelog.d/5525.fixed.md
@@ -0,0 +1,4 @@
+`RandomCrop.inverse` with `padding` and a crop size equal to the input size (#5512) now follows `forward` for a
+hand-made mixed `batch_prob`: the applied rows are inverted and unpadded on their own and the skipped rows stay
+untouched, where previously it raised with the internal padded canvas in the message. A mixed gate whose unpadded
+crop does change the shape is still rejected, and the message now names the unpadded shapes.
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index 5be670e39..e879f91bd 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -23,6 +23,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.augmentation.base import _mixed_gate_shape_error
from kornia.augmentation.utils.helpers import _constant_tensor, _pad_with_fill
from kornia.constants import Resample
from kornia.core.utils import is_compiling, is_exporting
@@ -392,12 +393,28 @@ class RandomCrop(GeometricAugmentationBase2D):
# onto forward_input_shape (the padded canvas), then removes its border below.
transform = transform.clone()
transform[:, :2, 2] += params["padding_size"][:, ::2].to(transform)
- out = super().inverse_inputs(input, params, flags, transform, **kwargs)
- if not params["batch_prob"].all():
- return out
+ to_apply = torch.atleast_1d(params["batch_prob"] > 0.5)
+ if not to_apply.any():
+ return super().inverse_inputs(input, params, flags, transform, **kwargs)
padding_size = params["padding_size"].unique(dim=0).cpu().squeeze().tolist()
- padding_size = [-padding_size[0], -padding_size[1], -padding_size[2], -padding_size[3]]
- return self.precrop_padding(out, padding_size)
+ unpadding = [-padding_size[0], -padding_size[1], -padding_size[2], -padding_size[3]]
+ if to_apply.all():
+ out = super().inverse_inputs(input, params, flags, transform, **kwargs)
+ return self.precrop_padding(out, unpadding)
+ # A mixed gate: the applied rows come back at the unpadded input size, so invert and unpad them on
+ # their own, and judge the shape change the caller sees, not the padded canvas.
+ in_tensor = self.transform_tensor(input)
+ canvas = params["forward_input_shape"].tolist()
+ unpadded = (canvas[-2] - padding_size[2] - padding_size[3], canvas[-1] - padding_size[0] - padding_size[1])
+ if tuple(in_tensor.shape[-2:]) != unpadded:
+ raise _mixed_gate_shape_error(in_tensor.shape[1:], (*in_tensor.shape[1:-2], *unpadded), inverse=True)
+ applied_params = dict(params)
+ applied_params["batch_prob"] = params["batch_prob"][to_apply]
+ applied_transform = transform[to_apply] if isinstance(transform, torch.Tensor) else transform
+ out = super().inverse_inputs(in_tensor[to_apply], applied_params, flags, applied_transform, **kwargs)
+ output = in_tensor.clone()
+ output[to_apply] = self.precrop_padding(out, unpadding)
+ return output
def inverse_boxes(
self,
diff --git a/tests/augmentation/container/test_random_crop.py b/tests/augmentation/container/test_random_crop.py
index 0583ed391..8164b997b 100644
--- a/tests/augmentation/container/test_random_crop.py
+++ b/tests/augmentation/container/test_random_crop.py
@@ -232,10 +232,41 @@ class TestRandomCropAnnotations(BaseTester):
for actual, target in zip(output, expected):
self.assert_close(actual, target)
# Equal spatial sizes let the image path select rows. A mixed gate on a shape-changing crop raises
- # (test_mixed_gate_with_shape_change_raises_4497); the mixed inverse is not asserted here.
+ # (test_mixed_gate_with_shape_change_raises_4497); the mixed inverse is in test_same_size_mixed_inverse_5512.
for actual, target in zip(output, inputs):
self.assert_close(actual[1], target[1], rtol=0, atol=0)
+ def test_same_size_mixed_inverse_5512(self, device, dtype):
+ # The inverse of an equal-size padded crop returns the unpadded input size, so, like forward (#4473),
+ # it selects rows: the applied rows are inverted and unpadded, the skipped rows are left alone.
+ inputs = self.inputs(2, device, dtype)
+ seq = K.AugmentationSequential(
+ K.RandomCrop((6, 10), padding=(1, 2, 3, 0), p=0.5, cropping_mode="resample", resample="nearest"),
+ data_keys=["input", "mask", "keypoints", "bbox_xyxy"],
+ )
+ mixed = self.fixed_params(seq, inputs[0].shape, [0.0, 1.0])
+ output = seq(*inputs, params=deepcopy(mixed))
+ forward_output = [value.clone() for value in output]
+ restored = seq.inverse(*output, params=deepcopy(mixed))
+ # The inverse writes the applied rows into a copy, not into the forward output it was given.
+ for actual, before in zip(output, forward_output):
+ self.assert_close(actual, before, rtol=0, atol=0)
+ whole = self.fixed_params(seq, inputs[0].shape, [1.0, 1.0])
+ reference = seq.inverse(*seq(*inputs, params=deepcopy(whole)), params=deepcopy(whole))
+ for actual, skipped, applied in zip(restored, inputs, reference):
+ assert actual.shape == skipped.shape
+ self.assert_close(actual[0], skipped[0], rtol=0, atol=0)
+ self.assert_close(actual[1], applied[1], rtol=0, atol=0)
+
+ # A padded crop that changes the size still rejects a mixed gate, naming the shapes the caller sees.
+ aug = K.RandomCrop((4, 8), padding=(1, 2, 3, 0), p=0.5, cropping_mode="resample")
+ params = aug.forward_parameters(inputs[0].shape)
+ params["batch_prob"] = torch.tensor([0.0, 1.0])
+ with pytest.raises(ValueError, match=r"from \(1, 6, 10\) to \(1, 4, 8\)"):
+ aug(inputs[0], params=deepcopy(params))
+ with pytest.raises(ValueError, match=r"from \(1, 4, 8\) to \(1, 6, 10\)"):
+ aug.inverse(torch.zeros(2, 1, 4, 8, device=device, dtype=dtype), params=deepcopy(params))
+
@pytest.mark.parametrize(
"make_aug",
[