Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation)!: refuse keypoints and boxes through a non-rigid warp (#6391)

Dmytro Mishkin7f95a55a66b1
diff --git a/changelog.d/6391.breaking.md b/changelog.d/6391.breaking.md
new file mode 100644
index 000000000..2946b34ca
--- /dev/null
+++ b/changelog.d/6391.breaking.md
@@ -0,0 +1 @@
+`AugmentationSequential` now raises `NotImplementedError` on a keypoint or box data key (`keypoints`, `bbox`, `bbox_xyxy`, `bbox_xywh`) when the pipeline contains `RandomElasticTransform`, `RandomThinPlateSpline` or `RandomFisheye`, also inside a nested container or a `VideoSequential`. These warps have no transformation matrix, so the call used to return the keypoints and boxes unchanged while the image moved, and the labels no longer matched the image (#4420). The check reads the pipeline, not the sampled gates, so it also raises at `p=0` and when `random_apply` does not draw the warp; those calls used to succeed. Masks are unchanged: `RandomElasticTransform` warps them and the other two raise. A direct `RandomElasticTransform.apply_transform_box` call also raises instead of returning the boxes unchanged. Run keypoints and boxes through a pipeline without these warps.
diff --git a/docs/source/augmentation.base.rst b/docs/source/augmentation.base.rst
index 94d3f0d61..00ed4bd21 100644
--- a/docs/source/augmentation.base.rst
+++ b/docs/source/augmentation.base.rst
@@ -51,8 +51,12 @@ Kornia augmentations generally follow a `sample-apply` routine.
matrix of the call's parameters to the mask, box and keypoint handlers of geometric children and of custom
`RigidAffineAugmentationBase2D` subclasses, recomputing it from replayed ``params`` that the child did not last
apply to an image or that were edited since. An in-place edit made inside ``torch.inference_mode`` is not seen,
- because inference tensors have no version counter; replace the value instead. Non-rigid coordinate transforms
- are not supplied automatically (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).
+ because inference tensors have no version counter; replace the value instead.
+ `RandomElasticTransform`, `RandomThinPlateSpline` and `RandomFisheye` have no matrix, so a forward call through
+ a pipeline that contains one refuses keypoint and box data keys. The container does not call the box and
+ keypoint handlers of a custom child that subclasses `AugmentationBase2D` directly, so those keys come back
+ unchanged; subclass `GeometricAugmentationBase2D` to move them
+ (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).
Custom Augmentation Classes
---------------------------
diff --git a/docs/source/augmentation.geometric.rst b/docs/source/augmentation.geometric.rst
index 37db01081..4508a474f 100644
--- a/docs/source/augmentation.geometric.rst
+++ b/docs/source/augmentation.geometric.rst
@@ -4,8 +4,9 @@
.. currentmodule:: kornia.augmentation
Spatial transformations and erasing operations. Matrix, inverse and annotation support depend on the class
-and configuration. Non-rigid transforms do not carry boxes or keypoints
-along with the image (`#4420 <https://github.com/kornia/kornia/issues/4420>`_). `RandomErasing` changes image
+and configuration. The non-rigid `RandomElasticTransform`, `RandomThinPlateSpline` and `RandomFisheye` cannot
+move boxes and keypoints with the image, so a forward call with either raises; ``.inverse()`` leaves these steps
+applied (`#4420 <https://github.com/kornia/kornia/issues/4420>`_). `RandomErasing` changes image
and mask values without moving coordinates. See
:class:`~kornia.augmentation.AugmentationSequential` for the supported data-key paths and their limitations.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index eefd0ad50..00d8a6a54 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -524,12 +524,12 @@ Augmentations
intensity and non-rigid children are skipped, so their effect
stays. Tensor box outputs are axis-aligned enclosures, so a rotation round
trip does not restore a box.
-- Non-rigid children do not move coordinate annotations:
- :class:`kornia.augmentation.RandomElasticTransform` warps masks but leaves
- keypoints and boxes unchanged, and
- :class:`kornia.augmentation.RandomThinPlateSpline` and
- :class:`kornia.augmentation.RandomFisheye` leave coordinates unchanged and
- raise on masks (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).
+- Non-rigid children cannot move coordinate annotations, so a pipeline that
+ contains :class:`kornia.augmentation.RandomElasticTransform`,
+ :class:`kornia.augmentation.RandomThinPlateSpline` or
+ :class:`kornia.augmentation.RandomFisheye` raises ``NotImplementedError`` on
+ a keypoint or box data key, even at ``p=0``. Elastic warps masks; the other
+ two raise on masks (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).
- Intensity augmentations leave masks unchanged, except
:class:`kornia.augmentation.RandomErasing`, which erases the same rectangle
in the mask and fills it with ``0`` (background) whatever ``value`` fills
diff --git a/kornia/augmentation/_2d/geometric/elastic_transform.py b/kornia/augmentation/_2d/geometric/elastic_transform.py
index 3bb0d96a4..bf610afd5 100644
--- a/kornia/augmentation/_2d/geometric/elastic_transform.py
+++ b/kornia/augmentation/_2d/geometric/elastic_transform.py
@@ -37,8 +37,9 @@ class RandomElasticTransform(AugmentationBase2D):
``p=1.0`` to warp every sample.
Convention:
- This is a dense backward sampling field with no ``transform_matrix`` or ``inverse``; spatial labels in
- containers have limitations (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).
+ This is a dense backward sampling field with no ``transform_matrix`` or ``inverse``. A ``mask`` data key
+ is resampled through the same field; keypoint and box data keys raise ``NotImplementedError``, even at
+ ``p=0`` (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).
Noise has shape ``(B, 2, H, W)`` with channels ``(x, y)``; ``alpha`` scales displacement in
normalized sampling coordinates, whereas ``kernel_size`` and ``sigma`` use ``(y, x)`` order.
Coordinates displaced outside the image are filled by ``padding_mode`` as in ``grid_sample``. Zero
@@ -153,9 +154,10 @@ class RandomElasticTransform(AugmentationBase2D):
flags: Dict[str, Any],
transform: Optional[torch.Tensor] = None,
) -> Boxes:
- """Process masks corresponding to the inputs that are transformed."""
- # We assume that boxes may not be affected too much by the deformation.
- return input
+ """Reject box inputs, which this augmentation does not move."""
+ raise NotImplementedError(
+ f"{type(self).__name__} does not support box inputs. See https://github.com/kornia/kornia/issues/4420."
+ )
def apply_transform_class(
self,
diff --git a/kornia/augmentation/_2d/geometric/fisheye.py b/kornia/augmentation/_2d/geometric/fisheye.py
index dd88a7111..d789038ef 100644
--- a/kornia/augmentation/_2d/geometric/fisheye.py
+++ b/kornia/augmentation/_2d/geometric/fisheye.py
@@ -38,9 +38,9 @@ class RandomFisheye(AugmentationBase2D):
The input sampling coordinate is ``(x * (1 + r**gamma), y * (1 + r**gamma))``:
the centre changes the distance, but scaling is about the coordinate origin.
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
+ There is no ``transform_matrix`` or ``inverse``. A ``mask``, keypoint or box data key raises
+ ``NotImplementedError`` identifying this augmentation, even at ``p=0``
(`#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,).
diff --git a/kornia/augmentation/_2d/geometric/thin_plate_spline.py b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
index d6859a878..5d7d6470f 100644
--- a/kornia/augmentation/_2d/geometric/thin_plate_spline.py
+++ b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
@@ -37,9 +37,9 @@ class RandomThinPlateSpline(AugmentationBase2D):
``(1, -1)``, ``(1, 1)``, and ``(0, 0)``. Each destination coordinate receives uniform
noise between ``-scale`` and ``scale``; zero scale leaves these points unchanged.
Sampling is bilinear, with no interpolation-mode argument. Zero scale is an identity warp up to
- interpolation 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``.
+ interpolation roundoff for either ``align_corners``. There is no ``transform_matrix`` or ``inverse``.
+ A ``mask``, keypoint or box data key raises ``NotImplementedError`` identifying this augmentation, even at
+ ``p=0`` (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).
Its defaults and the ``align_corners`` split across classes
(`#4412 <https://github.com/kornia/kornia/issues/4412>`_) are listed on
:class:`~kornia.augmentation.GeometricAugmentationBase2D`.
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index ca0b3b31f..bbbb31bc0 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -23,6 +23,9 @@ import torch
from torch import nn
from kornia.augmentation._2d.base import RigidAffineAugmentationBase2D
+from kornia.augmentation._2d.geometric.elastic_transform import RandomElasticTransform
+from kornia.augmentation._2d.geometric.fisheye import RandomFisheye
+from kornia.augmentation._2d.geometric.thin_plate_spline import RandomThinPlateSpline
from kornia.augmentation._3d.base import AugmentationBase3D, RigidAffineAugmentationBase3D
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.utils.helpers import _boxes_to_padded_tensor
@@ -53,6 +56,8 @@ _KEYPOINTS_OPTIONS = (DataKey.KEYPOINTS,)
_IMG_OPTIONS = (DataKey.INPUT, DataKey.IMAGE)
_MSK_OPTIONS = (DataKey.MASK,)
_CLS_OPTIONS = (DataKey.CLASS, DataKey.LABEL)
+# Warps without a transformation matrix: they move the image but not keypoints or boxes (#4420).
+_NON_RIGID_WARPS = (RandomElasticTransform, RandomFisheye, RandomThinPlateSpline)
MaskDataType = Union[torch.Tensor, List[torch.Tensor]]
@@ -171,8 +176,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
the image, after a newer draw or after an edit follows ``params``. Inference tensors have no version
counter, so an in-place edit made inside ``torch.inference_mode`` is not seen; replace the value instead.
The mask limitations above apply; a handler the subclass does not implement raises
- ``NotImplementedError``. A non-rigid warp child has no matrix, so the coordinate keys are left unchanged;
- see the warning below.
+ ``NotImplementedError``. A non-rigid warp child has no matrix, so the coordinate keys are refused; see
+ the note below.
- ``.inverse()`` undoes the 2D geometric steps and leaves intensity, custom rigid and non-rigid steps
applied. 3D geometric children raise ``NotImplementedError``, mix children ``RuntimeError``. Tensor
boxes come back as axis-aligned enclosures; pass :class:`~kornia.geometry.boxes.Boxes` to keep rotated
@@ -184,14 +189,14 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
skipped. A plain :class:`ImageSequential` child is still omitted from the outer matrix
(`#4476 <https://github.com/kornia/kornia/issues/4476>`_).
- .. warning::
- A non-rigid child silently desynchronizes the coordinate data keys:
- :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 ``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::
+ :class:`~kornia.augmentation.RandomElasticTransform`, :class:`~kornia.augmentation.RandomThinPlateSpline`
+ and :class:`~kornia.augmentation.RandomFisheye` warp the image without a transformation matrix, so a
+ keypoint or box data key raises ``NotImplementedError`` when any of them is in the pipeline, nested
+ containers included. The check reads the pipeline, not the sampled gates: it raises at ``p=0`` and when
+ ``random_apply`` does not draw the warp. A ``mask`` key follows the image through
+ :class:`~kornia.augmentation.RandomElasticTransform` and raises on the other two
+ (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).
.. note::
A mix child (e.g. RandomMixUpV2, RandomCutMixV2, RandomMosaic) receives ``mask``, box and ``keypoints``
@@ -518,6 +523,19 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
if size is not None and entry.shape[-2:] != size:
raise ValueError(f"Mask list entry {i} must have spatial size {tuple(size)}; got {tuple(entry.shape)}.")
+ def _reject_coordinates_through_non_rigid_warps(self, data_keys: List[DataKey]) -> None:
+ # The check reads the pipeline, not the sampled gates, so a call raises at any ``p`` and whichever children
+ # ``random_apply`` draws: a pipeline cannot pass on some batches and fail on others.
+ for key in data_keys:
+ if key not in _KEYPOINTS_OPTIONS and key not in _BOXES_OPTIONS:
+ continue
+ for module in self.modules():
+ if isinstance(module, _NON_RIGID_WARPS):
+ raise NotImplementedError(
+ f"{type(module).__name__} does not support {key.name.lower()} inputs. "
+ "See https://github.com/kornia/kornia/issues/4420."
+ )
+
def _validate_args_datakeys(
self, *args: DataType, data_keys: List[DataKey], params: Optional[List[ParamItem]] = None
) -> None:
@@ -712,6 +730,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
try:
self._validate_args_datakeys(*args, data_keys=original_data_keys, params=params)
+ self._reject_coordinates_through_non_rigid_warps(original_data_keys)
in_args = self._arguments_preproc(*args, data_keys=original_data_keys, params=params)
diff --git a/kornia/contrib/augmentation_audit.py b/kornia/contrib/augmentation_audit.py
index 245e7e6a8..654f1c863 100644
--- a/kornia/contrib/augmentation_audit.py
+++ b/kornia/contrib/augmentation_audit.py
@@ -410,7 +410,9 @@ def audit(
The sequence must use one BCHW image first, followed by batched masks (``(B, C, H, W)`` or ``(B, H, W)``), boxes or
keypoints described by positional ``data_keys``. ``params`` and ``data_keys``
have the same meaning as in :meth:`kornia.augmentation.AugmentationSequential.forward`.
- Unknown or non-rigid operations run normally and make composed geometry unavailable.
+ Unknown or non-rigid operations run normally and make composed geometry unavailable. Keypoints and boxes through
+ ``RandomElasticTransform``, ``RandomThinPlateSpline`` or ``RandomFisheye`` raise ``NotImplementedError``, as in
+ the sequence (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).
Reporting is an eager diagnostic operation. It snapshots executed operations and
parameters, checks spatial round trips, and never evaluates image reconstruction.
diff --git a/testing/half_precision_eager_rng.py b/testing/half_precision_eager_rng.py
index 596d31982..f315bdcc2 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",
- 79,
+ 80,
"torch.randn",
2,
(
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index b71bd764b..fa8e0f371 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -24,6 +24,7 @@ import torch
import kornia
import kornia.augmentation as K
+from kornia.augmentation.container.augment import _NON_RIGID_WARPS
from kornia.augmentation.container.base import ParamItem
from kornia.constants import BorderType, DataKey, Resample
from kornia.core._compat import torch_version_lt
@@ -2853,29 +2854,96 @@ class TestConventionAugmentationSequential(BaseTester):
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 `NotImplementedError` on a mask key.
+ @staticmethod
+ def _non_rigid_warp(augmentation, p, device, dtype):
+ if augmentation == "RandomElasticTransform":
+ return K.RandomElasticTransform(p=p)
+ if augmentation == "RandomThinPlateSpline":
+ return K.RandomThinPlateSpline(p=p)
+ return 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,
+ )
+
+ @pytest.mark.parametrize("augmentation", ["RandomElasticTransform", "RandomThinPlateSpline", "RandomFisheye"])
+ @pytest.mark.parametrize("data_key", ["keypoints", "bbox", "bbox_xyxy", "bbox_xywh"])
+ @pytest.mark.parametrize("p", [0.0, 1.0])
+ def test_non_rigid_augmentation_refuses_keypoints_and_boxes_4420(self, augmentation, data_key, p, device, dtype):
+ # A non-rigid warp has no transformation matrix, so keypoints and boxes used to come back unchanged while the
+ # image moved. The container refuses them instead, at any `p`, until the warp moves them too.
+ image = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
+ if data_key == "keypoints":
+ coordinates = torch.tensor([[[1.0, 2.0]], [[3.0, 4.0]]], device=device, dtype=dtype)
+ elif data_key == "bbox":
+ corners = torch.tensor([[0.0, 0.0], [3.0, 0.0], [3.0, 2.0], [0.0, 2.0]], device=device, dtype=dtype)
+ coordinates = corners.expand(2, 1, 4, 2).clone()
+ else:
+ coordinates = torch.tensor([[[0.0, 0.0, 3.0, 2.0]], [[2.0, 1.0, 3.0, 3.0]]], device=device, dtype=dtype)
+ aug = K.AugmentationSequential(
+ self._non_rigid_warp(augmentation, p, device, dtype), data_keys=["input", data_key]
+ )
+ with pytest.raises(NotImplementedError, match=rf"{augmentation} does not support {data_key} inputs.*4420"):
+ aug(image, coordinates)
+
+ @pytest.mark.parametrize("arrangement", ["random_apply", "nested", "video"])
+ def test_non_rigid_refusal_reads_the_pipeline_not_the_draw_4420(self, arrangement, device, dtype):
+ # The refusal does not depend on which children a call draws: a `random_apply` weight of zero never draws
+ # the warp, yet the call raises, so a pipeline cannot pass on some batches and fail on others. A warp one
+ # container down, or applied frame by frame, is refused too.
+ flip = K.RandomHorizontalFlip(p=1.0)
+ warp = K.RandomElasticTransform(p=1.0)
+ image = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
+ keypoints = torch.tensor([[[1.0, 2.0]], [[3.0, 4.0]]], device=device, dtype=dtype)
+ if arrangement == "random_apply":
+ aug = K.AugmentationSequential(
+ flip, warp, data_keys=["input", "keypoints"], random_apply=1, random_apply_weights=[1.0, 0.0]
+ )
+ elif arrangement == "nested":
+ aug = K.AugmentationSequential(flip, K.ImageSequential(warp), data_keys=["input", "keypoints"])
+ else:
+ aug = K.AugmentationSequential(K.VideoSequential(flip, warp), data_keys=["input", "keypoints"])
+ image = torch.rand(2, 3, 3, 6, 8, device=device, dtype=dtype)
+ keypoints = keypoints.unsqueeze(1).expand(2, 3, 1, 2).clone()
+ with pytest.raises(NotImplementedError, match=r"RandomElasticTransform does not support keypoints.*4420"):
+ aug(image, keypoints)
+
+ def test_non_rigid_refusal_lists_every_unhandled_augmentation_4420(self):
+ # The container moves keypoints and boxes through rigid, intensity and mix children only; a shipped 2D
+ # augmentation outside them would return the coordinates unchanged, so it must be refused.
+ handled = (K.RigidAffineAugmentationBase2D, K.IntensityAugmentationBase2D, K.MixAugmentationBaseV2)
+ unhandled = {
+ cls
+ for cls in vars(K).values()
+ if isinstance(cls, type)
+ and issubclass(cls, K.AugmentationBase2D)
+ and cls is not K.AugmentationBase2D
+ and not issubclass(cls, handled)
+ }
+ assert unhandled == set(_NON_RIGID_WARPS)
+
+ def test_elastic_box_hook_refuses_boxes_4420(self, device, dtype):
+ # A direct call reaches the hook that used to return the boxes unchanged.
+ aug = K.RandomElasticTransform(p=1.0)
+ boxes = Boxes.from_tensor(torch.tensor([[[0.0, 0.0, 3.0, 2.0]]], device=device, dtype=dtype))
+ with pytest.raises(NotImplementedError, match=r"RandomElasticTransform does not support box inputs.*4420"):
+ aug.apply_transform_box(boxes, {}, aug.flags)
+
+ def test_convention_non_rigid_augmentation_masks_4420(self, device, dtype):
+ # Masks are untouched by the keypoint and box refusal: `RandomElasticTransform` resamples a mask through
+ # the image's displacement field (nearest), and `RandomThinPlateSpline` / `RandomFisheye` raise on one.
# Seed zero and a checkerboard with a stronger displacement expose both the image and mask warp.
torch.manual_seed(0)
aug = K.AugmentationSequential(
- K.RandomElasticTransform(p=1.0, alpha=(5.0, 5.0), sigma=(4.0, 4.0)),
- data_keys=["input", "keypoints", "mask", "bbox_xyxy"],
+ K.RandomElasticTransform(p=1.0, alpha=(5.0, 5.0), sigma=(4.0, 4.0)), data_keys=["input", "mask"]
)
img = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
- kpts = torch.tensor([[[1.0, 2.0]], [[3.0, 4.0]]], device=device, dtype=dtype)
yy, xx = torch.meshgrid(torch.arange(6, device=device), torch.arange(8, device=device), indexing="ij")
mask = ((yy + xx) % 2).to(dtype).expand(2, 1, 6, 8).clone()
- boxes = torch.tensor([[[0.0, 0.0, 3.0, 2.0]], [[2.0, 1.0, 5.0, 4.0]]], device=device, dtype=dtype)
- out_img, out_kpts, out_mask, out_boxes = aug(img, kpts, mask, boxes)
+ out_img, out_mask = aug(img, mask)
assert (out_img - img).abs().max().item() > 0.1 # the image really moved
assert (out_mask != mask).sum().item() > 0 # and so did the mask, through the same displacement field
- self.assert_close(out_kpts, kpts) # the wart: the coordinate keys did not follow
- self.assert_close(out_boxes, boxes)
for factory in (
lambda: K.RandomThinPlateSpline(p=1.0),
lambda: K.RandomFisheye(
diff --git a/tests/contrib/test_augmentation_audit.py b/tests/contrib/test_augmentation_audit.py
index 0889832bb..2325b9c4e 100644
--- a/tests/contrib/test_augmentation_audit.py
+++ b/tests/contrib/test_augmentation_audit.py
@@ -216,19 +216,22 @@ class TestAugmentationAudit(BaseTester):
self.assert_close(report.spatial[0].roundtrip_max, torch.tensor([7], device=device, dtype=diagnostic_dtype))
assert "round-trip error" in report.summary()
- def test_nonrigid_silent_identity_is_not_supported(self, device, dtype):
+ def test_nonrigid_geometry_is_not_supported(self, device, dtype):
image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
- aug = K.AugmentationSequential(K.RandomElasticTransform(p=1), data_keys=["input", "keypoints"])
- points = image.new_tensor([[[1, 2]]])
- outputs, report = audit(aug, image, points)
- self.assert_close(outputs[1], points)
+ aug = K.AugmentationSequential(K.RandomElasticTransform(p=1), data_keys=["input", "mask"])
+ _, report = audit(aug, image, torch.ones_like(image))
assert report.geometry_status == "unsupported"
assert report.matrix is None
assert report.inverse_matrix is None
- assert report.spatial[0].roundtrip_valid_count.item() == 0
- assert torch.isnan(report.spatial[0].roundtrip_max).all()
assert "non-rigid" in report.summary()
+ def test_nonrigid_keypoints_are_refused(self, device, dtype):
+ # The sequence refuses keypoints through a non-rigid warp (#4420); they used to come back unchanged.
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ aug = K.AugmentationSequential(K.RandomElasticTransform(p=1), data_keys=["input", "keypoints"])
+ with pytest.raises(NotImplementedError, match="RandomElasticTransform does not support keypoints"):
+ audit(aug, image, image.new_tensor([[[1, 2]]]))
+
def test_singular_and_nonfinite_matrices(self, device, dtype):
class SingularFlip(K.RandomHorizontalFlip):
def compute_transformation(self, input, params, flags):