π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): resample slice-mode masks with the module's align_corners (#4894)
Aditya Malkard027a925671a
diff --git a/changelog.d/4894.breaking.md b/changelog.d/4894.breaking.mdnew file mode 100644index 000000000..acb9f1b70--- /dev/null+++ b/changelog.d/4894.breaking.md@@ -0,0 +1,7 @@+A mask override with `align_corners=None` in `AugmentationSequential(extra_args=...)` now means the module's own+`align_corners` in `cropping_mode="slice"` as well as in `"resample"`. Slice mode used to keep `None`, which+`interpolate` reads as `False`, so with `RandomResizedCrop`'s default `align_corners=True` a bilinear or bicubic+mask was resized on a different grid from its image and no longer lined up with it. Outputs change only for that+combination: slice-mode `RandomResizedCrop` with a bilinear or bicubic mask override, `align_corners=None`, and+`align_corners=True` on the module. Nearest masks, `align_corners=False` and resample mode are unchanged, as are+`RandomCrop` and `CenterCrop`. Fixes #4854.diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.pyindex 87a565b62..30e4d9a78 100644--- a/kornia/augmentation/_2d/geometric/base.py+++ b/kornia/augmentation/_2d/geometric/base.py@@ -159,27 +159,20 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):Note:Uses ``flags["resample"]`` as given; :meth:`transform_masks` supplies "nearest" when the callerdid not choose one.- Normalize "align_corners" from None to False to match PyTorch's default behavior.+ Treats ``align_corners=None`` as the module's own ``align_corners``, so a mask is resampled on the+ same grid as its input."""align_corners_was_none: bool = Falseoriginal_align_corners: Optional[bool] = None- # 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- # 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)+ # When align_corners=None is in flags (from extra_args), use the module's default, so masks use the+ # same align_corners as inputs. This holds in 'slice' cropping_mode too: RandomResizedCrop drops+ # align_corners for nearest itself (#4852), and RandomCrop's slice resize does not read it.if "align_corners" in flags and flags["align_corners"] is None:align_corners_was_none = Trueoriginal_align_corners = None- if flags.get("cropping_mode") == "slice":- pass- else:- # Use the module's default align_corners value from self.flags- # This ensures masks use the same align_corners as inputs- # For 'resample' mode, warp_affine/grid_sample accepts align_corners with nearest- flags["align_corners"] = self.flags.get("align_corners", False)+ flags["align_corners"] = self.flags.get("align_corners", False)output = self.apply_transform(input, params, flags, transform)@@ -285,24 +278,15 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):# This ensures masks use the same align_corners setting in inverse as in forwardif "align_corners" in kwargs: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- # except in 'slice' cropping_mode, which keeps None (as in apply_transform_mask, #4854)+ # When align_corners=None is in kwargs, use the module's default, as apply_transform_mask does.# We need to normalize it in kwargs too, because inverse_inputs will call# _process_kwargs_to_params_and_flags which merges kwargs into flagsif kwargs["align_corners"] is None:align_corners_was_none_in_kwargs = True- if flags.get("cropping_mode") == "slice":- # Don't modify flags or kwargs- pass- else:- # Use the module's default align_corners value- # This ensures masks use the same align_corners as inputs- # For 'resample' mode, warp_affine/grid_sample accepts align_corners with nearest- normalized_align_corners = self.flags.get("align_corners", False)- flags["align_corners"] = normalized_align_corners- # Also update kwargs to prevent _process_kwargs_to_params_and_flags from overwriting- kwargs["align_corners"] = normalized_align_corners+ normalized_align_corners = self.flags.get("align_corners", False)+ flags["align_corners"] = normalized_align_corners+ # Also update kwargs to prevent _process_kwargs_to_params_and_flags from overwriting+ kwargs["align_corners"] = normalized_align_cornerselse:flags["align_corners"] = kwargs["align_corners"]output = self.inverse_inputs(input, params, flags, transform, **kwargs)diff --git a/tests/augmentation/test_conventions_geometric_crop.py b/tests/augmentation/test_conventions_geometric_crop.pyindex 1c2e43dfc..351d66153 100644--- a/tests/augmentation/test_conventions_geometric_crop.py+++ b/tests/augmentation/test_conventions_geometric_crop.py@@ -21,6 +21,7 @@ import pytestimport torchimport kornia.augmentation as K+from kornia.constants import DataKey, Resamplefrom testing.base import BaseTester, supports_2d_border_padding, supports_bilinear_2d_grid_sample@@ -408,6 +409,30 @@ class TestGeometricCropConventions(BaseTester):explicit = K.RandomResizedCrop((4, 4), resample="nearest", align_corners=None, p=1.0)(image, params=params)assert torch.equal(default, explicit)+ @pytest.mark.device_agnostic+ @pytest.mark.parametrize("cropping_mode", ["slice", "resample"])+ @pytest.mark.parametrize("resample", ["nearest", "bilinear", "bicubic"])+ @pytest.mark.parametrize("align_corners", [True, False])+ @pytest.mark.parametrize("nested", [False, True])+ def test_convention_random_resized_crop_mask_override_none_follows_module_4854(+ self, cropping_mode, resample, align_corners, nested+ ):+ # #4854: a mask override with align_corners=None means the module's align_corners in both cropping modes.+ # Slice mode used to leave it None, which interpolate reads as False, so with the default+ # align_corners=True a bilinear or bicubic mask no longer lined up with the image.+ image = torch.rand(2, 1, 16, 16)+ aug = K.RandomResizedCrop(+ (11, 11), resample=resample, align_corners=align_corners, cropping_mode=cropping_mode, p=1.0+ )+ inner = K.AugmentationSequential(aug, data_keys=["input", "mask"]) if nested else aug+ seq = K.AugmentationSequential(+ inner,+ data_keys=["input", "mask"],+ extra_args={DataKey.MASK: {"resample": Resample.get(resample), "align_corners": None}},+ )+ output, mask = seq(image, image.clone())+ self.assert_close(mask, output)+def test_convention_resize_side_policies_and_inverse(self, device, dtype):x = torch.arange(70, device=device, dtype=dtype).reshape(1, 1, 7, 10)exact = K.Resize((3, 5), p=1.0)