Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): dispatch custom rigid annotation handlers (#5105)

A Aswanth Rajead47f558613
diff --git a/changelog.d/5105.fixed.md b/changelog.d/5105.fixed.md
new file mode 100644
index 000000000..83a7e1888
--- /dev/null
+++ b/changelog.d/5105.fixed.md
@@ -0,0 +1,8 @@
+`AugmentationSequential` now calls the box and keypoint handlers of a custom `RigidAffineAugmentationBase2D`
+subclass with its recorded matrix, as it does for a geometric child. It used to return those annotations unchanged
+next to the moved image, while `transform_matrix` reported the move. Mask handlers of such a subclass now receive the
+matrix too instead of `transform=None`, and a registered box or keypoint key whose handler the subclass does not
+implement raises `NotImplementedError` instead of passing through. With an annotation key listed before `input` in
+`data_keys`, the container used to transform the annotation before the image call recorded the matrix, so a
+geometric child such as `RandomAffine` raised on the first call and warped the annotation with the previous call's
+matrix after it; the image is now transformed first, and the outputs keep the caller's order. (#4481)
diff --git a/docs/source/augmentation.base.rst b/docs/source/augmentation.base.rst
index 627a27928..5f5ee5adf 100644
--- a/docs/source/augmentation.base.rst
+++ b/docs/source/augmentation.base.rst
@@ -47,10 +47,10 @@ Kornia augmentations generally follow a `sample-apply` routine.
- `apply`: with the generated (or user-provided) parameters, the augmentation is performed accordingly.
Apart from transforming image tensors, Kornia also supports inverse operations that revert the transform,
and transforms of other data modalities (`data keys` in Kornia) such as masks, keypoints, and bounding boxes.
- These features depend on the concrete operation and its data-key handlers. `AugmentationSequential` dispatches
- geometric coordinate transforms by the geometric base type; implementing a matrix on a custom rigid base alone
- does not enable that dispatch (`#4481 <https://github.com/kornia/kornia/issues/4481>`_). Non-rigid coordinate
- transforms are not supplied automatically (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).
+ These features depend on the concrete operation and its data-key handlers. `AugmentationSequential` passes the
+ recorded matrix to the mask, box and keypoint handlers of geometric children and of custom
+ `RigidAffineAugmentationBase2D` subclasses. Non-rigid coordinate transforms are not supplied automatically
+ (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).
Custom Augmentation Classes
---------------------------
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index 2b446a6c1..42891d5a9 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -150,9 +150,10 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):
Convention:
- a subclass implements :meth:`compute_transformation`, which returns the ``(B, 3, 3)`` matrix of the
sampled transform, and ``apply_transform`` for images. Direct mask, box, and keypoint handlers are
- incomplete on this base; inherit the geometric base for its matrix-based handlers. Container dispatch
- recognizes geometric children, so custom rigid subclasses need integration work of their own. See
- `#4481 <https://github.com/kornia/kornia/issues/4481>`_.
+ incomplete on this base; inherit the geometric base for its matrix-based handlers.
+ :class:`~kornia.augmentation.container.AugmentationSequential` calls the subclass's mask, box and
+ keypoint handlers with ``transform_matrix`` as ``transform``, as it does for a geometric child, and
+ raises ``NotImplementedError`` for a registered data key whose handler is missing.
- the matrix of the last call is readable as ``transform_matrix``. Subclasses opt into lazy construction
with ``_compute_matrix_lazily``; a lazy matrix keeps only the input's shape, dtype and device, unless the
subclass overrides ``transform_tensor``, ``generate_transformation_matrix``, ``compute_transformation``
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index e05da3745..2cc404938 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -132,14 +132,16 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
same per-entry gate. A flip round-trips each entry, subject to the working-dtype rounding above; other
warps lose the pixels they move out of the frame and, when they resample, restore the rest only
approximately. Tracked in `#4477 <https://github.com/kornia/kornia/issues/4477>`_.
- - supported geometric data-key handlers share the recorded transform, subject to the mask limitations
- above. Custom rigid subclasses are not dispatched solely because they supply a matrix
- (`#4481 <https://github.com/kornia/kornia/issues/4481>`_). A non-rigid warp child has no matrix, so
- the coordinate keys are left unchanged; see the warning below.
- - ``.inverse()`` undoes the 2D geometric steps and leaves intensity and non-rigid steps applied. Slice-mode
- crops and 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
- corners. Content lost to cropping, padding or interpolation is not recovered.
+ - the ``mask``, box and ``keypoints`` handlers of a geometric child, or of a custom
+ :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` subclass, receive the transform it recorded,
+ subject to the mask limitations above; 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.
+ - ``.inverse()`` undoes the 2D geometric steps and leaves intensity, custom rigid and non-rigid steps
+ applied. Slice-mode crops and 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 corners. Content lost to cropping, padding or
+ interpolation is not recovered.
- ``same_on_batch`` and ``keepdim`` default to ``None``, which keeps each child's own setting;
``True`` or ``False`` overrides it.
- ``.transform_matrix`` of a chain holding a nested container is unreliable: it can raise, omit the
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index cb5549f04..8125610f7 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -201,14 +201,26 @@ class AugmentationSequentialOps:
),
)
- outputs = []
- for inp, dcate in zip(arg, _data_keys):
+ # Rigid annotation handlers read the matrix produced by the image call. Process that input first even
+ # when the caller supplies data keys in another order, then restore the caller's output order.
+ order = list(range(len(arg)))
+ if (
+ isinstance(module, K.RigidAffineAugmentationBase2D)
+ and not isinstance(module, K.IntensityAugmentationBase2D)
+ and DataKey.INPUT in _data_keys
+ ):
+ image_index = _data_keys.index(DataKey.INPUT)
+ order.insert(0, order.pop(image_index))
+
+ outputs = list(arg)
+ for index in order:
+ inp, dcate = arg[index], _data_keys[index]
op = self._get_op(dcate)
extra_arg = extra_args.get(dcate, {})
if dcate.name == "MASK" and isinstance(inp, list):
- outputs.append(MaskSequentialOps.transform_list(inp, module, param=param, extra_args=extra_arg))
+ outputs[index] = MaskSequentialOps.transform_list(inp, module, param=param, extra_args=extra_arg)
else:
- outputs.append(op.transform(inp, module, param=param, extra_args=extra_arg))
+ outputs[index] = op.transform(inp, module, param=param, extra_args=extra_arg)
if len(outputs) == 1 and isinstance(outputs, (list, tuple)):
return outputs[0]
return outputs
@@ -427,7 +439,9 @@ class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):
if extra_args is None:
extra_args = {}
- if isinstance(module, (K.GeometricAugmentationBase2D,)):
+ if isinstance(module, K.RigidAffineAugmentationBase2D) and not isinstance(
+ module, K.IntensityAugmentationBase2D
+ ):
extra_args = cls._mask_extra_args(module, extra_args)
input = module.transform_masks(
input,
@@ -482,7 +496,9 @@ class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):
"""
if extra_args is None:
extra_args = {}
- if isinstance(module, (K.GeometricAugmentationBase2D,)):
+ if isinstance(module, K.RigidAffineAugmentationBase2D) and not isinstance(
+ module, K.IntensityAugmentationBase2D
+ ):
extra_args = cls._mask_extra_args(module, extra_args)
tfm_input = []
params = cls.get_instance_module_param(param)
@@ -646,7 +662,9 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):
extra_args = {}
_input = input.clone()
- if isinstance(module, (K.GeometricAugmentationBase2D,)):
+ if isinstance(module, K.RigidAffineAugmentationBase2D) and not isinstance(
+ module, K.IntensityAugmentationBase2D
+ ):
_input = module.transform_boxes(
_input,
cls.get_instance_module_param(param),
@@ -749,7 +767,9 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):
extra_args = {}
_input = input.clone()
- if isinstance(module, (K.GeometricAugmentationBase2D,)):
+ if isinstance(module, K.RigidAffineAugmentationBase2D) and not isinstance(
+ module, K.IntensityAugmentationBase2D
+ ):
_input = module.transform_keypoints(
_input,
cls.get_instance_module_param(param),
diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.py
index e9bfc4779..90faf4b4f 100644
--- a/tests/augmentation/test_base.py
+++ b/tests/augmentation/test_base.py
@@ -754,6 +754,9 @@ class TestConventionAugmentationBase2D(BaseTester):
):
with pytest.raises(NotImplementedError):
handler(data, aug._params, aug.flags, transform=aug.transform_matrix)
+ for key, data in (("mask", image), ("bbox_xyxy", boxes), ("keypoints", keypoints)):
+ with pytest.raises(NotImplementedError):
+ K.AugmentationSequential(aug, data_keys=["input", key])(image, data)
def test_convention_direct_geometric_mask_handler_rejects_bool(self, device, dtype):
# The container casts bool masks around geometric dispatch. Calling the geometric handler directly
@@ -788,24 +791,102 @@ class TestConventionAugmentationBase2D(BaseTester):
_, output_boxes = container(image, boxes)
self.assert_close(output_boxes.data, boxes.data)
- def test_wart_container_skips_custom_rigid_box_handlers_4481(self, device, dtype):
- class ShiftBoxes(K.RigidAffineAugmentationBase2D):
+ @pytest.mark.parametrize("p", [0.0, 1.0])
+ @pytest.mark.parametrize("as_objects", [False, True])
+ @pytest.mark.parametrize("annotations_first", [False, True])
+ def test_convention_container_dispatches_custom_rigid_annotations_4481(
+ self, device, dtype, p, as_objects, annotations_first
+ ):
+ # Every handler reads the matrix the container passes, so a handler called with ``transform=None`` fails.
+ class ShiftRight(K.RigidAffineAugmentationBase2D):
def compute_transformation(self, input, params, flags):
- return self.identity_matrix(input)
+ matrix = self.identity_matrix(input).clone()
+ matrix[:, 0, 2] = 1.0
+ return matrix
def apply_transform(self, input, params, flags, transform=None):
+ return input.roll(1, dims=-1)
+
+ def apply_non_transform_mask(self, input, params, flags, transform=None):
return input
+ def apply_transform_mask(self, input, params, flags, transform=None):
+ return input.roll(int(transform[0, 0, 2]), dims=-1)
+
def apply_transform_box(self, input, params, flags, transform=None):
- return Boxes(input.data + 1, mode=input.mode)
+ return input.transform_boxes_(transform)
- image = torch.ones(1, 1, 4, 4, device=device, dtype=dtype)
+ def apply_transform_keypoint(self, input, params, flags, transform=None):
+ return input.transform_keypoints_(transform)
+
+ image = torch.zeros(1, 1, 4, 5, device=device, dtype=dtype)
+ image[0, 0, 1, 1] = 1.0
+ mask = image.clone()
boxes = Boxes.from_tensor(torch.tensor([[[0.0, 0.0, 2.0, 2.0]]], device=device, dtype=dtype), mode="xyxy")
- augmentation = ShiftBoxes(p=1.0)
- direct = augmentation.transform_boxes(boxes, augmentation.forward_parameters(image.shape), augmentation.flags)
- self.assert_close(direct.data, boxes.data + 1)
- _, output_boxes = K.AugmentationSequential(augmentation, data_keys=["input", "bbox_xyxy"])(image, boxes)
- self.assert_close(output_boxes.data, boxes.data)
+ keypoints = Keypoints(torch.tensor([[[1.0, 1.0]]], device=device, dtype=dtype))
+ augmentation = ShiftRight(p=p)
+ sequence = K.AugmentationSequential(augmentation, data_keys=["input", "mask", "bbox_xyxy", "keypoints"])
+ box_input = boxes if as_objects else boxes.to_tensor("xyxy")
+ keypoint_input = keypoints if as_objects else keypoints.data
+ if annotations_first:
+ output_mask, output_boxes, output_keypoints, output_image = sequence(
+ mask,
+ box_input,
+ keypoint_input,
+ image,
+ data_keys=["mask", "bbox_xyxy", "keypoints", "input"],
+ )
+ else:
+ output_image, output_mask, output_boxes, output_keypoints = sequence(image, mask, box_input, keypoint_input)
+
+ expected_boxes = boxes.to_tensor("xyxy") + torch.tensor([p, 0.0, p, 0.0], device=device, dtype=dtype)
+ expected_keypoints = keypoints.data + torch.tensor([p, 0.0], device=device, dtype=dtype)
+ actual_boxes = output_boxes.to_tensor("xyxy") if isinstance(output_boxes, Boxes) else output_boxes
+ actual_keypoints = output_keypoints.data if isinstance(output_keypoints, Keypoints) else output_keypoints
+ self.assert_close(output_image, image.roll(int(p), dims=-1))
+ self.assert_close(output_mask, output_image)
+ self.assert_close(actual_boxes, expected_boxes)
+ self.assert_close(actual_keypoints, expected_keypoints)
+ self.assert_close(sequence.transform_matrix[:, 0, 2], torch.tensor([p], device=device, dtype=dtype))
+ # A direct call with the same parameters and matrix agrees with the container.
+ params, flags, transform = augmentation._params, augmentation.flags, augmentation.transform_matrix
+ self.assert_close(
+ augmentation.transform_boxes(boxes, params, flags, transform).to_tensor("xyxy"), expected_boxes
+ )
+ self.assert_close(
+ augmentation.transform_keypoints(keypoints, params, flags, transform).data, expected_keypoints
+ )
+ # A list of masks takes the per-entry path, which passes the matrix too.
+ mask_sequence = K.AugmentationSequential(augmentation, data_keys=["input", "mask"])
+ if annotations_first:
+ output_masks, list_output_image = mask_sequence([mask[0]], image, data_keys=["mask", "input"])
+ else:
+ list_output_image, output_masks = mask_sequence(image, [mask[0]])
+ self.assert_close(list_output_image, output_image)
+ self.assert_close(output_masks[0], output_image)
+
+ @pytest.mark.parametrize("key", ["mask", "bbox_xyxy", "keypoints"])
+ def test_convention_container_transforms_image_first_for_geometric_children(self, device, dtype, key):
+ # Annotation handlers read the matrix the image call records. With the annotation listed before the image,
+ # a built-in geometric child used to raise on the first call and reuse the previous call's matrix after it.
+ image = torch.linspace(0, 1, 2 * 3 * 16 * 20, device=device, dtype=dtype).reshape(2, 3, 16, 20)
+ annotations = {
+ "mask": (image[:, :1] > 0.5).to(dtype),
+ "bbox_xyxy": torch.tensor([[[2.0, 3.0, 8.0, 9.0]], [[4.0, 1.0, 12.0, 7.0]]], device=device, dtype=dtype),
+ "keypoints": torch.tensor(
+ [[[3.0, 4.0], [10.0, 6.0]], [[5.0, 5.0], [15.0, 12.0]]], device=device, dtype=dtype
+ ),
+ }
+ annotation = annotations[key]
+ reference = K.AugmentationSequential(RandomAffine(30.0, p=1.0))
+ sequence = K.AugmentationSequential(RandomAffine(30.0, p=1.0))
+ for seed in (0, 1):
+ torch.manual_seed(seed)
+ expected_image, expected = reference(image, annotation, data_keys=["input", key])
+ torch.manual_seed(seed)
+ output, output_image = sequence(annotation, image, data_keys=[key, "input"])
+ self.assert_close(output_image, expected_image)
+ self.assert_close(output, expected)
def test_convention_random_erasing_also_erases_container_masks(self, device, dtype):
image = torch.ones(1, 1, 6, 8, device=device, dtype=dtype)