π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): explain unsupported masks in TPS and Fisheye (#6262)
Zhenhuan Wangd57a87450593
diff --git a/changelog.d/6262.fixed.md b/changelog.d/6262.fixed.mdnew file mode 100644index 000000000..ea8378b7a--- /dev/null+++ b/changelog.d/6262.fixed.md@@ -0,0 +1 @@+`RandomThinPlateSpline` and `RandomFisheye` now identify the augmentation and unsupported mask input in their existing `NotImplementedError`, including when `p=0`.diff --git a/kornia/augmentation/_2d/geometric/fisheye.py b/kornia/augmentation/_2d/geometric/fisheye.pyindex 551c61056..25f714460 100644--- a/kornia/augmentation/_2d/geometric/fisheye.py+++ b/kornia/augmentation/_2d/geometric/fisheye.py@@ -39,6 +39,7 @@ class RandomFisheye(AugmentationBase2D):Sampling is bilinear with zero padding and ``align_corners=True``; these settings are fixed.There is no ``transform_matrix`` or ``inverse``; spatial labels in containers have limitations(`#4420 <https://github.com/kornia/kornia/issues/4420>`_).+ A ``mask`` data key raises ``NotImplementedError`` identifying this augmentation, even at ``p=0``.Args:center_x: Ranges to sample respect to x-coordinate center with shape (2,).@@ -114,3 +115,27 @@ class RandomFisheye(AugmentationBase2D):field_x = field_x + field_x * distance**gamma # BxHxwfield_y = field_y + field_y * distance**gamma # BxHxWreturn remap(input, field_x, field_y, normalized_coordinates=True, align_corners=True)++ def apply_transform_mask(+ self,+ input: torch.Tensor,+ params: Dict[str, torch.Tensor],+ flags: Dict[str, Any],+ transform: Optional[torch.Tensor] = None,+ ) -> torch.Tensor:+ """Reject mask inputs, which this augmentation does not support."""+ raise NotImplementedError(+ f"{type(self).__name__} does not support mask inputs. See https://github.com/kornia/kornia/issues/4420."+ )++ def apply_non_transform_mask(+ self,+ input: torch.Tensor,+ params: Dict[str, torch.Tensor],+ flags: Dict[str, Any],+ transform: Optional[torch.Tensor] = None,+ ) -> torch.Tensor:+ """Reject mask inputs even when the transformation is not applied."""+ raise NotImplementedError(+ f"{type(self).__name__} does not support mask inputs. See https://github.com/kornia/kornia/issues/4420."+ )diff --git a/kornia/augmentation/_2d/geometric/thin_plate_spline.py b/kornia/augmentation/_2d/geometric/thin_plate_spline.pyindex d21f06b94..01b59361d 100644--- a/kornia/augmentation/_2d/geometric/thin_plate_spline.py+++ b/kornia/augmentation/_2d/geometric/thin_plate_spline.py@@ -39,6 +39,7 @@ class RandomThinPlateSpline(AugmentationBase2D):Sampling is bilinear, with no interpolation-mode argument. Zero scale is an identity warp up tointerpolation roundoff for either ``align_corners``. There is no ``transform_matrix`` or ``inverse``;spatial labels in containers have limitations (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).+ A ``mask`` data key raises ``NotImplementedError`` identifying this augmentation, even at ``p=0``.Its defaults and the ``align_corners`` split across classes(`#4412 <https://github.com/kornia/kornia/issues/4412>`_) are listed on:class:`~kornia.augmentation.GeometricAugmentationBase2D`.@@ -122,3 +123,27 @@ class RandomThinPlateSpline(AugmentationBase2D):# NOTE: warp_image_tps need to use inverse parameterskernel, affine = get_tps_transform(dst, src)return warp_image_tps(input, src, kernel, affine, flags["align_corners"], flags["padding_mode"].name.lower())++ def apply_transform_mask(+ self,+ input: torch.Tensor,+ params: Dict[str, torch.Tensor],+ flags: Dict[str, Any],+ transform: Optional[torch.Tensor] = None,+ ) -> torch.Tensor:+ """Reject mask inputs, which this augmentation does not support."""+ raise NotImplementedError(+ f"{type(self).__name__} does not support mask inputs. See https://github.com/kornia/kornia/issues/4420."+ )++ def apply_non_transform_mask(+ self,+ input: torch.Tensor,+ params: Dict[str, torch.Tensor],+ flags: Dict[str, Any],+ transform: Optional[torch.Tensor] = None,+ ) -> torch.Tensor:+ """Reject mask inputs even when the transformation is not applied."""+ raise NotImplementedError(+ f"{type(self).__name__} does not support mask inputs. See https://github.com/kornia/kornia/issues/4420."+ )diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex baee3f840..b7ae88537 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -188,7 +188,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential)::class:`~kornia.augmentation.RandomElasticTransform` warps the image **and** a ``mask`` key with it,but returns keypoints and boxes unchanged, and:class:`~kornia.augmentation.RandomThinPlateSpline` and :class:`~kornia.augmentation.RandomFisheye`- return keypoints and boxes unchanged and raise a bare ``NotImplementedError`` on a ``mask`` key.+ return keypoints and boxes unchanged and raise ``NotImplementedError`` on a ``mask`` key,+ with a message identifying the unsupported augmentation (including at ``p=0``).Tracked in `#4420 <https://github.com/kornia/kornia/issues/4420>`_... note::diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex ba778db84..2eccd823e 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -2819,14 +2819,46 @@ class TestConventionAugmentationSequential(BaseTester):assert bool(((out == 0) | (out == 1)).all())assert aug.flags["resample"] == Resample.BILINEAR+ @pytest.mark.parametrize("augmentation", ["RandomThinPlateSpline", "RandomFisheye"])+ @pytest.mark.parametrize("p", [0.0, 1.0])+ def test_unsupported_non_rigid_mask_reports_augmentation_4420(self, augmentation, p, device, dtype):+ if augmentation == "RandomThinPlateSpline":+ aug = K.RandomThinPlateSpline(p=p)+ else:+ aug = K.RandomFisheye(+ torch.tensor([-0.3, 0.3], device=device, dtype=dtype),+ torch.tensor([-0.3, 0.3], device=device, dtype=dtype),+ torch.tensor([0.9, 1.0], device=device, dtype=dtype),+ p=p,+ )+ image = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)+ mask = torch.zeros(2, 1, 6, 8, device=device, dtype=dtype)+ with pytest.raises(NotImplementedError, match=rf"{augmentation}.*mask.*4420"):+ K.AugmentationSequential(aug, data_keys=["input", "mask"])(image, mask)++ @pytest.mark.parametrize("augmentation", ["RandomThinPlateSpline", "RandomFisheye"])+ @pytest.mark.parametrize("method", ["apply_transform_mask", "apply_non_transform_mask"])+ def test_unsupported_non_rigid_mask_hooks_report_augmentation_4420(self, augmentation, method, device, dtype):+ # The container calls the transform hook first even at p=0, so exercise the skipped-input hook directly.+ if augmentation == "RandomThinPlateSpline":+ aug = K.RandomThinPlateSpline()+ else:+ aug = K.RandomFisheye(+ torch.tensor([-0.3, 0.3], device=device, dtype=dtype),+ torch.tensor([-0.3, 0.3], device=device, dtype=dtype),+ torch.tensor([0.9, 1.0], device=device, dtype=dtype),+ )+ mask = torch.zeros(2, 1, 6, 8, device=device, dtype=dtype)+ with pytest.raises(NotImplementedError, match=rf"{augmentation}.*mask.*4420"):+ getattr(aug, method)(mask, {}, aug.flags)+def test_wart_non_rigid_augmentation_desynchronizes_the_data_keys_4420(self, device, dtype):# Wart pin (#4420): the container promises that one call applies the same sampled transform to every# registered data type, but a non-rigid augmentation has no transform matrix, so the coordinate keys# pass through untouched instead of raising: `RandomElasticTransform` warps the image *and* the mask# - it carries its own mask path, which resamples the mask through the very same displacement field,# nearest - while the keypoints and the boxes stay exactly where they were, and- # `RandomThinPlateSpline` / `RandomFisheye` raise a bare `NotImplementedError` (no message) on a mask- # key.+ # `RandomThinPlateSpline` / `RandomFisheye` raise `NotImplementedError` on a mask key.# Seed zero and a checkerboard with a stronger displacement expose both the image and mask warp.torch.manual_seed(0)aug = K.AugmentationSequential(