π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): disable antialiasing for masks (#4540)
Hrithik Sharmaf38731981c1e
diff --git a/changelog.d/4540.fixed.md b/changelog.d/4540.fixed.mdnew file mode 100644index 000000000..2922a2b50--- /dev/null+++ b/changelog.d/4540.fixed.md@@ -0,0 +1 @@+`Resize(antialias=True)` no longer antialiases masks, so their label set is preserved; pass `antialias=True` in `extra_args[DataKey.MASK]` (or to `transform_masks`) to filter soft masks explicitly.diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex cf46e9ce4..1c0e6dc1d 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -273,10 +273,7 @@ Augmentations:class:`kornia.augmentation.RandomErasing` fills the erased mask region withzero.- The geometric mask path normally uses nearest interpolation. That avoids- interpolating labels only when no other operation changes their values:- padding can introduce its fill value, and ``Resize(antialias=True)`` filters- masks before sampling, producing fractional labels or changing integer and- boolean masks (`#4479 <https://github.com/kornia/kornia/issues/4479>`_).+ interpolating labels, but padding can still introduce its fill value.- Put the image before masks, including in dictionary insertion order, soconversion uses its working dtype. Earlier masks use the previous imagedtype, or ``float32`` on a fresh container. Integer labels outside thediff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.pyindex 87524a220..740fe2688 100644--- a/kornia/augmentation/_2d/geometric/base.py+++ b/kornia/augmentation/_2d/geometric/base.py@@ -46,8 +46,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):Inverse resampling cannot recover image or mask information lost through cropping, padding, orinterpolation. Tensor-form boxes may lose rotated corners through axis-aligned enclosure.- container mask processing has dtype- and operator-specific limitations; see- `#4478 <https://github.com/kornia/kornia/issues/4478>`_ and- `#4479 <https://github.com/kornia/kornia/issues/4479>`_. Direct ``transform_masks`` calls use the+ `#4478 <https://github.com/kornia/kornia/issues/4478>`_. Direct ``transform_masks`` calls use theimage dtype guard and therefore reject ``bool`` masks.- a subclass supplies its own :meth:`inverse_transform` -- the base raises ``NotImplementedError`` --while :meth:`compute_inverse_transformation` defaults to inverting the sampled matrix.@@ -56,7 +55,9 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):Masks are resampled with nearest neighbour whatever ``resample`` the augmentation uses for images,unless ``resample`` is passed explicitly to :meth:`transform_masks` or :meth:`inverse_masks` --which is what ``extra_args[DataKey.MASK]`` does in a container. An explicit value is honoured in- both directions.+ both directions. Antialiasing is disabled for masks by default, even when it is enabled for images.+ Pass ``antialias=True`` explicitly to :meth:`transform_masks` or through ``extra_args[DataKey.MASK]``+ to filter soft masks."""@@ -115,6 +116,12 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):# Nearest is the mask default, but an explicit ``resample`` wins, matching ``inverse_masks``.if "resample" not in kwargs and "resample" in (self.flags if flags is None else flags):kwargs["resample"] = Resample.get("nearest")++ # Disable antialiasing by default for masks so discrete labels are preserved,+ # while allowing an explicit override for soft masks.+ if "antialias" not in kwargs and "antialias" in (self.flags if flags is None else flags):+ kwargs["antialias"] = False+return super().transform_masks(input, params, flags, transform=transform, **kwargs)def apply_transform_mask(diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 96fc00e60..c24d28541 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -125,9 +125,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential)::func:`~kornia.geometry.transform.hflip`: ``x' = W - 1 - x`` and ``y' = H - 1 - y``, for the image,the mask, the keypoints and all three box spellings alike, and ``bbox_xywh`` keeps its ``w`` and``h``. Labels are passed through untouched by a geometric step.- - mask resampling normally uses nearest interpolation, but this does not guarantee label preservation.- ``Resize(antialias=True)`` filters masks before sampling and can change labels- (`#4479 <https://github.com/kornia/kornia/issues/4479>`_); padding can introduce a fill value.+ - mask resampling normally uses nearest interpolation, but this does not guarantee label preservation:+ padding can introduce a fill value.Put the image before the masks, includingin dictionary insertion order, so mask conversion uses that image's working dtype. Masks precedingthe image use the previous call's image dtype, or ``float32`` on a fresh container. The containerdiff --git a/testing/half_precision_eager_rng.py b/testing/half_precision_eager_rng.pyindex 3fbdc2c8c..cd71cb37d 100644--- a/testing/half_precision_eager_rng.py+++ b/testing/half_precision_eager_rng.py@@ -149,7 +149,7 @@ AUDITED_EAGER_RNG_CALLS = tuple((*_audited("tests/augmentation/container/test_augmentation_sequential.py",- 48,+ 49,"torch.randn",2,(diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex 153f86c2b..9fc573a88 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -28,6 +28,7 @@ from kornia.constants import BorderType, DataKey, Resamplefrom kornia.core._compat import torch_version_ltfrom kornia.geometry.bbox import bbox_to_maskfrom kornia.geometry.boxes import Boxes+from kornia.geometry.transform import resizefrom testing.augmentation.utils import reproducibility_testfrom testing.base import BaseTester, assert_close@@ -862,15 +863,68 @@ class TestConventionAugmentationSequential(BaseTester):bool_mask[:, :, 1:4, 2:6] = Trueassert aug(torch.rand(2, 3, 6, 8, device=device, dtype=dtype), bool_mask)[1].dtype == torch.bool- def test_wart_resize_antialias_blurs_masks_4479(self, device, dtype):- # Resize applies antialiasing before the mask's nearest interpolation, introducing values outside the- # input label set. This is a current wart, tracked in #4479.- image = torch.rand(1, 3, 8, 8, device=device, dtype=dtype)- mask = torch.full((1, 1, 8, 8), 2.0, device=device, dtype=dtype)- mask[:, :, :, 4:] = 3.0- aug = K.AugmentationSequential(K.Resize((4, 4), antialias=True), data_keys=["input", "mask"])+ @pytest.mark.parametrize("mask_dtype", [torch.float32, torch.int64, torch.bool])+ def test_resize_antialias_preserves_mask_labels_4479(self, mask_dtype, device, dtype):+ yy, xx = torch.meshgrid(+ torch.arange(12, device=device),+ torch.arange(16, device=device),+ indexing="ij",+ )+ blocks = ((yy // 2) + (xx // 2)) % 2++ if mask_dtype == torch.bool:+ mask = blocks.bool()+ else:+ mask = (2 + blocks).to(mask_dtype)++ mask = mask[None, None]+ image = torch.rand(1, 3, 12, 16, device=device, dtype=dtype)++ without_antialias = K.AugmentationSequential(+ K.Resize((6, 8), antialias=False),+ data_keys=["input", "mask"],+ )+ with_antialias = K.AugmentationSequential(+ K.Resize((6, 8), antialias=True),+ data_keys=["input", "mask"],+ )++ expected_mask = without_antialias(image, mask)[1]+ out_image, out_mask = with_antialias(image, mask)+ expected_image = resize(image, (6, 8), "bilinear", align_corners=True, antialias=True)++ assert out_mask.dtype == mask_dtype+ assert torch.equal(out_mask, expected_mask)+ assert set(out_mask.unique().tolist()) == set(mask.unique().tolist())+ self.assert_close(out_image, expected_image)++ def test_resize_mask_explicit_antialias_override_4479(self, device, dtype):+ yy, xx = torch.meshgrid(+ torch.arange(12, device=device),+ torch.arange(16, device=device),+ indexing="ij",+ )+ mask = (((yy // 2) + (xx // 2)) % 2).to(dtype)[None, None]+ image = torch.rand(1, 3, 12, 16, device=device, dtype=dtype)++ aug = K.AugmentationSequential(+ K.Resize((6, 8), antialias=True),+ data_keys=["input", "mask"],+ extra_args={+ DataKey.MASK: {+ "resample": Resample.BILINEAR,+ "align_corners": True,+ "antialias": True,+ }+ },+ )+out_mask = aug(image, mask)[1]- assert not set(out_mask.unique().tolist()).issubset({2.0, 3.0})+ expected = resize(mask, (6, 8), "bilinear", align_corners=True, antialias=True)+ without_antialias = resize(mask, (6, 8), "bilinear", align_corners=True, antialias=False)++ self.assert_close(out_mask, expected)+ assert not torch.equal(out_mask, without_antialias)def test_convention_boxes_follow_the_xyxy_plus_convention(self, device, dtype):# Convention pin: the container's box arithmetic is `Boxes`' inclusive `xyxy_plus` mode, for a scaling