Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): let RandomResizedCrop slice mode resample with nearest (#4852)

RitiGroverf23aa08c4e95
diff --git a/changelog.d/4852.fixed.md b/changelog.d/4852.fixed.md
new file mode 100644
index 000000000..337cf0b84
--- /dev/null
+++ b/changelog.d/4852.fixed.md
@@ -0,0 +1,2 @@
+`RandomResizedCrop(resample="nearest")` no longer raises in the default slice mode. Slice mode now ignores
+`align_corners` for nearest resampling, for images and masks. (#4852)
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index 7e0949482..87a565b62 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -167,16 +167,13 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
# When align_corners=None is in flags (from extra_args), use the module's default
# This ensures masks use the same align_corners value as inputs for consistency
- # However, for 'slice' cropping_mode with 'nearest' mode, align_corners must be None
- # because crop_by_indices -> resize -> interpolate doesn't accept align_corners with nearest
- # For 'resample' cropping_mode, warp_affine/grid_sample accepts align_corners with nearest
+ # except in 'slice' cropping_mode, which keeps None. RandomResizedCrop drops align_corners for
+ # nearest itself; for bilinear/bicubic interpolate reads None as False, so the mask no longer
+ # lines up with an align_corners=True input (tracked in #4854)
if "align_corners" in flags and flags["align_corners"] is None:
align_corners_was_none = True
original_align_corners = None
- # Check if we're using 'slice' cropping_mode which uses interpolate
- # interpolate doesn't accept align_corners with nearest mode
if flags.get("cropping_mode") == "slice":
- # Keep align_corners=None for slice mode with nearest (interpolate requirement)
pass
else:
# Use the module's default align_corners value from self.flags
@@ -290,17 +287,12 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
align_corners_value = flags.get("align_corners")
# When align_corners=None is in kwargs, use the module's default
# This ensures masks use the same align_corners value as inputs for consistency
- # However, for 'slice' cropping_mode with 'nearest' mode, align_corners must be None
- # because crop_by_indices -> resize -> interpolate doesn't accept align_corners with nearest
- # For 'resample' cropping_mode, warp_affine/grid_sample accepts align_corners with nearest
+ # except in 'slice' cropping_mode, which keeps None (as in apply_transform_mask, #4854)
# We need to normalize it in kwargs too, because inverse_inputs will call
# _process_kwargs_to_params_and_flags which merges kwargs into flags
if kwargs["align_corners"] is None:
align_corners_was_none_in_kwargs = True
- # Check if we're using 'slice' cropping_mode which uses interpolate
- # interpolate doesn't accept align_corners with nearest mode
if flags.get("cropping_mode") == "slice":
- # Keep align_corners=None for slice mode with nearest (interpolate requirement)
# Don't modify flags or kwargs
pass
else:
diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.py
index c72bab999..02db279b8 100644
--- a/kornia/augmentation/_2d/geometric/resized_crop.py
+++ b/kornia/augmentation/_2d/geometric/resized_crop.py
@@ -73,9 +73,8 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
short on the longer side also fits (8x6 gives 7x6 in about 18% of draws, as in torchvision). Unlike
torchvision, which centres the fallback crop, it is placed at a random position like any other crop.
- Both cropping modes use the configured interpolation and ``align_corners``, so slice mode raises for
- ``resample="nearest"`` unless ``align_corners=None``
- (`#4802 <https://github.com/kornia/kornia/issues/4802>`_). At ``align_corners=False`` the two modes give
+ Both cropping modes use the configured interpolation and ``align_corners``. Slice mode ignores
+ ``align_corners`` for ``resample="nearest"``. At ``align_corners=False`` the two modes give
different images, and slice mode does not follow ``transform_matrix``
(`#4804 <https://github.com/kornia/kornia/issues/4804>`_). Only resample mode supports :meth:`inverse`,
which resamples onto the original canvas and cannot recover discarded information.
@@ -166,16 +165,17 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
align_corners=flags["align_corners"],
)
if flags["cropping_mode"] == "slice": # uses advanced slicing to crop
+ mode = flags["resample"].name.lower()
+ # ``interpolate`` rejects ``align_corners`` for nearest resampling.
+ align_corners = None if mode == "nearest" else flags["align_corners"]
if is_compiling():
- return _compiled_slice_resize(
- input, params["src"], flags["size"], flags["resample"].name.lower(), flags["align_corners"]
- )
+ return _compiled_slice_resize(input, params["src"], flags["size"], mode, align_corners)
return crop_by_indices(
input,
params["src"],
flags["size"],
- interpolation=flags["resample"].name.lower(),
- align_corners=flags["align_corners"],
+ interpolation=mode,
+ align_corners=align_corners,
)
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index d018326ca..4998519d8 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -95,10 +95,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
that uses the base mask path the ``resample`` entry is honoured in both directions, and a
dict without one resamples masks with nearest neighbour. ``align_corners`` is
handler-dependent: some warps honor it, but resize mask paths replace it.
- With :class:`~kornia.augmentation.RandomResizedCrop`,
- boolean ``align_corners`` overrides raise ``ValueError`` in the default ``cropping_mode='slice'``
- mask path (`#4802 <https://github.com/kornia/kornia/issues/4802>`_); ``cropping_mode='resample'``
- accepts them. ``None`` works in both modes.
+ :class:`~kornia.augmentation.RandomResizedCrop` in the default ``cropping_mode='slice'``
+ ignores it for nearest resampling.
:class:`~kornia.augmentation.RandomElasticTransform` has its own mask path and honours
both entries. Unlike the constructors, the override is not normalized: a string ``resample``
raises ``AttributeError`` wherever the mask is resampled, so pass a
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index a12d6c39d..b8206f5d9 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -980,10 +980,8 @@ class TestConventionAugmentationSequential(BaseTester):
@pytest.mark.parametrize("cropping_mode", ["slice", "resample"])
@pytest.mark.parametrize("align_corners", [None, False, True])
- def test_wart_resized_crop_mask_align_corners_depends_on_mode_4802(
- self, cropping_mode, align_corners, device, dtype
- ):
- # #4802: the slice-mode raise flips when slice mode drops `align_corners` for nearest resampling.
+ def test_resized_crop_mask_accepts_any_align_corners_4802(self, cropping_mode, align_corners, device, dtype):
+ # #4802: slice mode drops `align_corners` for nearest resampling, so every override works in both modes.
image = torch.arange(16, device=device, dtype=dtype).reshape(1, 1, 4, 4) / 16
mask = torch.arange(16, device=device, dtype=dtype).reshape(1, 1, 4, 4).remainder(2)
seq = K.AugmentationSequential(
@@ -991,13 +989,9 @@ class TestConventionAugmentationSequential(BaseTester):
data_keys=["input", "mask"],
extra_args={DataKey.MASK: {"resample": Resample.NEAREST, "align_corners": align_corners}},
)
- if cropping_mode == "slice" and align_corners is not None:
- with pytest.raises(ValueError):
- seq(image, mask)
- else:
- out_image, out_mask = seq(image, mask)
- assert out_image.shape == out_mask.shape == (1, 1, 2, 2)
- assert set(out_mask.unique().tolist()).issubset({0.0, 1.0})
+ out_image, out_mask = seq(image, mask)
+ assert out_image.shape == out_mask.shape == (1, 1, 2, 2)
+ assert set(out_mask.unique().tolist()).issubset({0.0, 1.0})
def test_convention_masks_keep_labels_and_add_padding_fill_through_a_rotation(self, device, dtype):
# Convention pin: masks are resampled with nearest interpolation, so a {2, 3} mask still holds those
diff --git a/tests/augmentation/test_conventions_geometric_crop.py b/tests/augmentation/test_conventions_geometric_crop.py
index 151236342..1c2e43dfc 100644
--- a/tests/augmentation/test_conventions_geometric_crop.py
+++ b/tests/augmentation/test_conventions_geometric_crop.py
@@ -396,13 +396,17 @@ class TestGeometricCropConventions(BaseTester):
assert bool((first - resampled(image, params=sliced._params)).abs().max() > 0.1) == disagree
@pytest.mark.device_agnostic
- def test_wart_random_resized_crop_slice_mode_rejects_nearest_4802(self):
- # #4802: flips when slice mode drops the default align_corners for nearest resampling.
+ def test_random_resized_crop_slice_mode_accepts_nearest_4802(self):
+ # #4802: slice mode drops the default align_corners for nearest resampling.
image = torch.rand(1, 1, 8, 8)
- for kwargs in ({"cropping_mode": "resample"}, {"align_corners": None}):
- assert K.RandomResizedCrop((4, 4), resample="nearest", p=1.0, **kwargs)(image).shape == (1, 1, 4, 4)
- with pytest.raises(ValueError):
- K.RandomResizedCrop((4, 4), resample="nearest", p=1.0)(image)
+ for kwargs in ({"cropping_mode": "resample"}, {"align_corners": None}, {}, {"align_corners": False}):
+ aug = K.RandomResizedCrop((4, 4), resample="nearest", p=1.0, **kwargs)
+ assert aug(image).shape == (1, 1, 4, 4)
+ # Slice mode matches the result of passing align_corners=None explicitly.
+ params = aug.forward_parameters(image.shape)
+ default = K.RandomResizedCrop((4, 4), resample="nearest", p=1.0)(image, params=params)
+ explicit = K.RandomResizedCrop((4, 4), resample="nearest", align_corners=None, p=1.0)(image, params=params)
+ assert torch.equal(default, explicit)
def test_convention_resize_side_policies_and_inverse(self, device, dtype):
x = torch.arange(70, device=device, dtype=dtype).reshape(1, 1, 7, 10)