π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): replay annotations from supplied params (#5416)
Karnajeet Gosavi521a1dbdd119
diff --git a/changelog.d/5416.fixed.md b/changelog.d/5416.fixed.mdnew file mode 100644index 000000000..fb0622737--- /dev/null+++ b/changelog.d/5416.fixed.md@@ -0,0 +1 @@+Geometric annotation replay now uses the transformation parameters supplied to the replay call, even after a later image call updates the augmentation state.diff --git a/docs/source/augmentation.base.rst b/docs/source/augmentation.base.rstindex 5fa86bfca..5e2f5939b 100644--- a/docs/source/augmentation.base.rst+++ b/docs/source/augmentation.base.rst@@ -48,8 +48,8 @@ Kornia augmentations generally follow a `sample-apply` routine.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` 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+ 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. Non-rigid coordinate transforms are not supplied automatically(`#4420 <https://github.com/kornia/kornia/issues/4420>`_).Custom Augmentation Classesdiff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.pyindex 42891d5a9..8b6f4ae1c 100644--- a/kornia/augmentation/_2d/base.py+++ b/kornia/augmentation/_2d/base.py@@ -25,7 +25,7 @@ from torch import float16, float32, float64from kornia.augmentation.base import _AugmentationBasefrom kornia.augmentation.utils import _transform_input, _transform_input_by_shape, _validate_input_dtypefrom kornia.core.ops import eye_like-from kornia.core.utils import is_autocast_enabled+from kornia.core.utils import is_autocast_enabled, is_exportingfrom kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints@@ -168,6 +168,7 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):# ``apply_func`` defers the matrix and ``transform_matrix`` computes it on first access._compute_matrix_lazily: bool = False_lazy_matrix_args: Optional[_LazyMatrixArgs] = None+ _transform_matrix_params: Optional[Dict[str, Any]] = None@propertydef transform_matrix(self) -> Optional[torch.Tensor]:@@ -278,6 +279,10 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):) -> torch.Tensor:if flags is None:flags = self.flags+ # ``forward`` committed the caller's params dict as ``_params`` before overriding a copy for this call (and+ # ``transform_inputs`` commits that copy). Pair the caller's dict with the matrix, so the container's annotation+ # handlers can tell a replay of this draw from another one by identity.+ matrix_params = self._paramsif self._compute_matrix_lazily:# apply_transform ignores the matrix for these ops, so don't build it here; defer to@@ -298,10 +303,14 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):# PyTorch 2.5 snapshots torch.Size as a tuple during non-strict export.matrix_input = _InputMetadata(tuple(in_tensor.shape), in_tensor.dtype, in_tensor.device)self._commit_state(transform_matrix=None, lazy_matrix_args=(matrix_input, params, flags))+ if not is_exporting():+ self._transform_matrix_params = matrix_paramsreturn self.transform_inputs(in_tensor, params, flags, None)trans_matrix = self.generate_transformation_matrix(in_tensor, params, flags)output = self.transform_inputs(in_tensor, params, flags, trans_matrix)self._commit_state(transform_matrix=trans_matrix, lazy_matrix_args=None)+ if not is_exporting():+ self._transform_matrix_params = matrix_paramsreturn outputdiff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex bbd433315..a989a34c6 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -151,8 +151,10 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):warps lose the pixels they move out of the frame and, when they resample, restore the rest onlyapproximately. Tracked in `#4477 <https://github.com/kornia/kornia/issues/4477>`_.- 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+ :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` subclass, receive the transform of the+ call's ``params``: the one the child recorded when it last transformed an image with those params, or+ else one recomputed from them, so a replay without the image or after a newer draw follows ``params``.+ 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.- ``.inverse()`` undoes the 2D geometric steps and leaves intensity, custom rigid and non-rigid stepsdiff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.pyindex cc11bc10a..3da4d11a2 100644--- a/kornia/augmentation/container/ops.py+++ b/kornia/augmentation/container/ops.py@@ -25,6 +25,7 @@ from torch import nnimport kornia.augmentation as Kfrom kornia.augmentation.base import _AugmentationBasefrom kornia.constants import DataKey+from kornia.core.utils import is_exportingfrom kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints@@ -60,6 +61,36 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):raise TypeError(f"Expected param (ParamItem.data) be a dictionary. Got {param}.")return _params+ @classmethod+ def get_transform_matrix(cls, module: nn.Module, param: ParamItem, input: Any) -> torch.Tensor:+ """Get the matrix recorded by these params, not by the module's most recent image call."""+ params = cls.get_instance_module_param(param)+ # The image call records the params dict it was given next to the matrix it computed from it. The same dict+ # object is the same draw, so the recorded matrix is reused; other params are replayed from their values.+ if not is_exporting() and getattr(module, "_transform_matrix_params", None) is params:+ transform = getattr(module, "transform_matrix", None)+ if transform is not None:+ return transform++ forward_input_shape = params.get("forward_input_shape")+ if forward_input_shape is None:+ raise ValueError("`forward_input_shape` is required to replay geometric annotations without an image.")++ if isinstance(input, list):+ input = input[0] if input else None+ if isinstance(input, (Boxes, Keypoints)):+ input = input.data+ reference = input if isinstance(input, torch.Tensor) else None+ device = reference.device if reference is not None else forward_input_shape.device+ dtype = reference.dtype if reference is not None and torch.is_floating_point(reference) else torch.float32+ input_shape = tuple(forward_input_shape.tolist())+ padding_size = params.get("padding_size")+ if not is_exporting() and isinstance(padding_size, torch.Tensor) and len(input_shape) >= 2:+ left, right, top, bottom = padding_size[0].tolist()+ input_shape = (*input_shape[:-2], input_shape[-2] - top - bottom, input_shape[-1] - left - right)+ matrix_input = torch.empty((), device=device, dtype=dtype).expand(input_shape)+ return module.generate_transformation_matrix(matrix_input, params, module.flags)+@classmethoddef get_sequential_module_param(cls, param: ParamItem) -> List[ParamItem]:"""Extract nested sequential parameters from a :class:`ParamItem`.@@ -445,7 +476,7 @@ class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):input,params=cls.get_instance_module_param(param),flags=module.flags,- transform=module.transform_matrix,+ transform=cls.get_transform_matrix(module, param, input),**extra_args,)@@ -501,7 +532,11 @@ class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):for i, inp in enumerate(input):params_i["batch_prob"] = params["batch_prob"][i]tfm_inp = module.transform_masks(- inp, params=params_i, flags=module.flags, transform=module.transform_matrix, **extra_args+ inp,+ params=params_i,+ flags=module.flags,+ transform=cls.get_transform_matrix(module, param, inp),+ **extra_args,)tfm_input.append(tfm_inp)input = tfm_input@@ -553,9 +588,7 @@ class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):extra_args = {}if isinstance(module, (K.GeometricAugmentationBase2D,)):- if module.transform_matrix is None:- raise ValueError(f"No valid transformation matrix found in {module.__class__}.")- transform = module.compute_inverse_transformation(module.transform_matrix)+ transform = module.compute_inverse_transformation(cls.get_transform_matrix(module, param, input))input = module.inverse_masks(input,params=cls.get_instance_module_param(param),@@ -594,9 +627,7 @@ class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):extra_args = {}if isinstance(module, (K.GeometricAugmentationBase2D,)):- if module.transform_matrix is None:- raise ValueError(f"No valid transformation matrix found in {module.__class__}.")- transform = module.compute_inverse_transformation(module.transform_matrix)+ transform = module.compute_inverse_transformation(cls.get_transform_matrix(module, param, input))params = cls.get_instance_module_param(param)params_i = copy.deepcopy(params)inv_input = []@@ -656,7 +687,7 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):_input,cls.get_instance_module_param(param),module.flags,- transform=module.transform_matrix,+ transform=cls.get_transform_matrix(module, param, _input),**extra_args,)@@ -702,9 +733,7 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):_input = input.clone()if isinstance(module, (K.GeometricAugmentationBase2D,)):- if module.transform_matrix is None:- raise ValueError(f"No valid transformation matrix found in {module.__class__}.")- transform = module.compute_inverse_transformation(module.transform_matrix)+ transform = module.compute_inverse_transformation(cls.get_transform_matrix(module, param, _input))_input = module.inverse_boxes(_input,param.data, # type: ignore[arg-type]@@ -756,7 +785,7 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):_input,cls.get_instance_module_param(param),module.flags,- transform=module.transform_matrix,+ transform=cls.get_transform_matrix(module, param, _input),**extra_args,)@@ -810,9 +839,7 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):_input = input.clone()if isinstance(module, (K.GeometricAugmentationBase2D,)):- if module.transform_matrix is None:- raise ValueError(f"No valid transformation matrix found in {module.__class__}.")- transform = module.compute_inverse_transformation(module.transform_matrix)+ transform = module.compute_inverse_transformation(cls.get_transform_matrix(module, param, _input))_input = module.inverse_keypoints(_input, cls.get_instance_module_param(param), module.flags, transform=transform, **extra_args)diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex 8532e0cea..9cc28a533 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -1848,3 +1848,87 @@ class TestConventionAugmentationSequential(BaseTester):for helper in (lambda: aug.show(display=False), lambda: aug.save(name=str(tmp_path / "none.jpg"))):with pytest.raises(ValueError, match="No pre-computed images found"):helper()+++class TestAugmentationSequentialReplay:+ def test_annotation_replay_uses_matrices_from_params(self, device, dtype):+ with torch.random.fork_rng(devices=[device] if device.type == "cuda" else []):+ torch.manual_seed(0)+ image = torch.rand(1, 1, 16, 16, device=device, dtype=dtype)+ mask = torch.zeros_like(image)+ mask[..., 4:8, 2:6] = 1+ boxes = torch.tensor([[[2.0, 4.0, 6.0, 8.0]]], device=device, dtype=dtype)+ keypoints = torch.tensor([[[3.0, 5.0]]], device=device, dtype=dtype)+ data_keys = ["input", "mask", "bbox_xyxy", "keypoints"]+ aug = K.AugmentationSequential(K.RandomAffine(45.0, translate=(0.2, 0.2), p=1.0), data_keys=data_keys)++ first = aug(image, mask, boxes, keypoints)+ params = aug._params+ expected_inverse = aug.inverse(*first, params=params)++ aug(+ torch.rand(2, 1, 16, 16, device=device, dtype=dtype),+ mask.expand(2, -1, -1, -1),+ boxes.expand(2, -1, -1),+ keypoints.expand(2, -1, -1),+ )++ replayed = aug(mask, boxes, keypoints, params=params, data_keys=data_keys[1:])+ assert_close(replayed[0], first[1])+ assert_close(replayed[1], first[2])+ assert_close(replayed[2], first[3])++ actual_inverse = aug.inverse(*first, params=params)+ for actual, expected in zip(actual_inverse, expected_inverse):+ assert_close(actual, expected)++ def test_annotations_reuse_the_matrix_of_the_image_call(self, device, dtype, monkeypatch):+ # Within one call the image records its matrix next to the params dict it was given, and the mask, box and+ # keypoint handlers reuse it instead of recomputing one matrix each. The inverse recomputes the image's matrix+ # once, as an image-only inverse does, and its annotation handlers reuse the recorded one.+ calls = []+ generate = K.RandomAffine.generate_transformation_matrix++ def counted(self, *args, **kwargs):+ calls.append(None)+ return generate(self, *args, **kwargs)++ monkeypatch.setattr(K.RandomAffine, "generate_transformation_matrix", counted)+ image = torch.zeros(2, 1, 16, 16, device=device, dtype=dtype)+ boxes = torch.tensor([[[2.0, 4.0, 6.0, 8.0]]], device=device, dtype=dtype).expand(2, -1, -1)+ keypoints = torch.tensor([[[3.0, 5.0]]], device=device, dtype=dtype).expand(2, -1, -1)+ aug = K.AugmentationSequential(+ K.RandomAffine(45.0, p=1.0), data_keys=["input", "mask", "bbox_xyxy", "keypoints"]+ )+ out = aug(image, image, boxes, keypoints)+ assert len(calls) == 1+ aug.inverse(*out)+ assert len(calls) == 2++ def test_annotation_replay_after_a_direct_leaf_call(self, device, dtype):+ # A child called on its own between the container call and the replay records another draw; the replay+ # must still use the params it is given.+ with torch.random.fork_rng(devices=[device] if device.type == "cuda" else []):+ torch.manual_seed(0)+ image = torch.rand(1, 1, 16, 16, device=device, dtype=dtype)+ keypoints = torch.tensor([[[3.0, 5.0]]], device=device, dtype=dtype)+ aug = K.AugmentationSequential(K.RandomAffine(45.0, p=1.0), data_keys=["input", "keypoints"])+ out_image, out_keypoints = aug(image, keypoints)+ params = aug._params+ aug[0](torch.rand(3, 1, 16, 16, device=device, dtype=dtype))+ _, back = aug.inverse(out_image, out_keypoints, params=params)+ assert_close(back, keypoints)++ def test_annotation_replay_of_an_oversized_padded_crop(self, device, dtype):+ # A crop larger than the padded canvas is scaled against that canvas. The replayed matrix must use the+ # unpadded input shape (``forward_input_shape`` minus ``padding_size``), or the keypoints shift.+ with torch.random.fork_rng(devices=[device] if device.type == "cuda" else []):+ torch.manual_seed(0)+ image = torch.rand(2, 1, 16, 16, device=device, dtype=dtype)+ keypoints = torch.tensor([[[3.0, 5.0], [9.0, 12.0]]], device=device, dtype=dtype).expand(2, -1, -1)+ aug = K.AugmentationSequential(K.RandomCrop((20, 22), padding=1, p=1.0), data_keys=["input", "keypoints"])+ _, expected = aug(image, keypoints)+ params = aug._params+ aug(torch.rand(3, 1, 15, 17, device=device, dtype=dtype), keypoints[:1].expand(3, -1, -1))+ replayed = aug(keypoints, params=params, data_keys=["keypoints"])+ assert_close(replayed, expected)