Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): return a copy from CenterCrop slice mode (#4727)

Suliman Abdulrazzaqf19b879d23ed
diff --git a/changelog.d/4727.breaking.md b/changelog.d/4727.breaking.md
new file mode 100644
index 000000000..08dea81cb
--- /dev/null
+++ b/changelog.d/4727.breaking.md
@@ -0,0 +1,5 @@
+`CenterCrop` in the default `cropping_mode="slice"` now returns a copy of the cropped region. Previously it returned a
+view that shared storage with the input: writing to the output changed the input at the crop offset, and writing to the
+input after the call changed the output. Code that relied on either direction of that aliasing must now write to the
+tensor it wants changed. The crop now allocates one crop-sized tensor per call, as `RandomCrop` and `RandomResizedCrop`
+already do in slice mode, and no longer keeps the whole input alive through the output. Fixes #4413.
diff --git a/kornia/augmentation/_2d/geometric/center_crop.py b/kornia/augmentation/_2d/geometric/center_crop.py
index 309a95034..9358148c5 100644
--- a/kornia/augmentation/_2d/geometric/center_crop.py
+++ b/kornia/augmentation/_2d/geometric/center_crop.py
@@ -58,10 +58,8 @@ class CenterCrop(GeometricAugmentationBase2D):
``size`` accepts an integer for a square crop or an
``(height, width)`` tuple. The fixed centre crop is shared by every selected image in a batch.
- When the crop is selected, ``cropping_mode="slice"`` indexes the input directly and returns a writable view
- of it; modifying the result therefore modifies the corresponding centre region of the input. This wart is
- tracked in
- `#4413 <https://github.com/kornia/kornia/issues/4413>`_. ``cropping_mode="resample"`` uses
+ When the crop is selected, ``cropping_mode="slice"`` indexes the input directly and returns a copy of the
+ indexed region, so writing to the result leaves the input unchanged. ``cropping_mode="resample"`` uses
``crop_by_transform_mat`` with the configured ``resample`` (bilinear by default), ``align_corners`` (``True``
by default), and zero padding. Only resample mode supports
:meth:`inverse`; it resamples onto the original canvas with zero padding by default and cannot restore discarded
@@ -159,11 +157,14 @@ class CenterCrop(GeometricAugmentationBase2D):
# `int(coord_tensor[i])` indexing break torch.compile fullgraph. The offsets match
# `center_crop_generator` (`int(dim/2 - size/2)` == `(dim - size) // 2` for size <=
# dim, which the generator guarantees) and the slice equals the requested size, so
- # this is byte-identical.
+ # this is byte-identical. The slice is a view of the caller's tensor, so return a copy:
+ # writing to the output must not modify the input, matching `RandomCrop`/`RandomResizedCrop`
+ # in slice mode and `resample` mode (#4413). `contiguous()` is not enough, because a
+ # full-size or rows-only crop can already be contiguous and would come back as the view.
crop_h, crop_w = int(flags["size"][0]), int(flags["size"][1])
top = (input.shape[-2] - crop_h) // 2
left = (input.shape[-1] - crop_w) // 2
- return input[..., top : top + crop_h, left : left + crop_w]
+ return input[..., top : top + crop_h, left : left + crop_w].clone()
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
def inverse_transform(
diff --git a/tests/augmentation/test_conventions_geometric_crop.py b/tests/augmentation/test_conventions_geometric_crop.py
index 45d97d6e5..6844fe5e0 100644
--- a/tests/augmentation/test_conventions_geometric_crop.py
+++ b/tests/augmentation/test_conventions_geometric_crop.py
@@ -45,13 +45,18 @@ class TestGeometricCropConventions(BaseTester):
nearest = K.CenterCrop((4, 4), resample="nearest", align_corners=False, cropping_mode="resample")
self.assert_close(nearest(x), expected)
- def test_wart_center_crop_slice_aliases_input_4413(self, device, dtype):
- # #4413: default slice mode returns its direct tensor slice. The write lands at the crop's centre offset.
+ @pytest.mark.parametrize("size", [(4, 4), (4, 8), (6, 8)])
+ def test_convention_center_crop_slice_returns_a_copy_4413(self, device, dtype, size):
+ # #4413: default slice mode used to return a view, so writing to the output changed the input.
+ # (4, 8) keeps whole rows and (6, 8) is the full image: both slices are already contiguous.
x = torch.arange(48, device=device, dtype=dtype).reshape(1, 1, 6, 8)
- output = K.CenterCrop(4, cropping_mode="slice")(x)
- assert output.untyped_storage().data_ptr() == x.untyped_storage().data_ptr()
- output[0, 0, 0, 0] = -99
- assert x[0, 0, 1, 2] == -99
+ original = x.clone()
+ output = K.CenterCrop(size, cropping_mode="slice")(x)
+ input_storage = x.untyped_storage().data_ptr()
+ output_storage = output.untyped_storage().data_ptr()
+ assert output_storage != input_storage
+ output.fill_(-99)
+ self.assert_close(x, original)
def test_convention_random_crop_padding_modes_and_inverse(self, device, dtype):
x = torch.arange(9, device=device, dtype=dtype).reshape(1, 1, 3, 3)