Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(augmentation): support inverse in slice-mode CenterCrop, RandomCrop and RandomResizedCrop (#5984)

Dmytro Mishkin215356a0cc01
diff --git a/changelog.d/5931.fixed.md b/changelog.d/5931.fixed.md
deleted file mode 100644
index a004c0796..000000000
--- a/changelog.d/5931.fixed.md
+++ /dev/null
@@ -1,4 +0,0 @@
-`kornia.augmentation.CenterCrop` and `kornia.augmentation.RandomResizedCrop` in `cropping_mode="slice"` raise
-`NotImplementedError` from `inverse` for every image and mask batch, as `RandomCrop` already does. They checked the
-mode only when inverting applied rows, so an empty batch, or one where no row was augmented, was returned instead.
-Boxes and keypoints still invert in slice mode.
diff --git a/changelog.d/5984.added.md b/changelog.d/5984.added.md
new file mode 100644
index 000000000..02544f1f6
--- /dev/null
+++ b/changelog.d/5984.added.md
@@ -0,0 +1 @@
+`kornia.augmentation.CenterCrop`, `RandomCrop` and `RandomResizedCrop` support `inverse` in their default `cropping_mode="slice"`: images and masks, and for `RandomCrop` also boxes and keypoints, are warped back onto the input canvas with the inverse of the recorded `transform_matrix`, as in resample mode. Cropped-away content is not restored. These calls used to raise `NotImplementedError`, except that `CenterCrop` and `RandomResizedCrop` returned a tensor for an empty batch or one the crop was not applied to.
diff --git a/changelog.d/5984.fixed.md b/changelog.d/5984.fixed.md
new file mode 100644
index 000000000..972b30631
--- /dev/null
+++ b/changelog.d/5984.fixed.md
@@ -0,0 +1 @@
+The image and mask inverse of the 2D crops also changed in resample mode. With `align_corners=True`, `CenterCrop` and `RandomCrop` spread a crop with a one-pixel axis over the whole canvas axis, and now paste it back. `RandomResizedCrop` with a one-pixel output or crop axis and corner alignment returned NaN in resample mode, and now samples the crop's first row or column (or repeats a one-pixel crop), as slice mode does. `RandomCrop` inverted an oversized crop (larger than the padded canvas) without its scale, returning the top-left corner of the upscaled crop, and now scales it back. Its mask inverse raised `ValueError` when the image `fill` had one value per channel, and now removes the added padding without a fill and pads a border that negative `padding` cropped with zeros.
diff --git a/docs/source/augmentation.base.rst b/docs/source/augmentation.base.rst
index 54565b9d3..5dbddf29e 100644
--- a/docs/source/augmentation.base.rst
+++ b/docs/source/augmentation.base.rst
@@ -64,8 +64,7 @@ calls pass masks, boxes, and keypoints through unchanged unless a subclass overr
`GeometricAugmentationBase2D` supplies the dispatch used for geometric coordinate transformations.
For a geometric operation, implement `compute_transformation` and `apply_transform`. Supporting image inversion
-also requires `inverse_transform`; the base provides matrix inversion. Some configurations, such as slice-mode
-crops, reject inversion.
+also requires `inverse_transform`; the base provides matrix inversion.
.. autoclass:: GeometricAugmentationBase2D
diff --git a/docs/source/augmentation.geometric.rst b/docs/source/augmentation.geometric.rst
index 0ef9fd200..37db01081 100644
--- a/docs/source/augmentation.geometric.rst
+++ b/docs/source/augmentation.geometric.rst
@@ -4,7 +4,7 @@
.. currentmodule:: kornia.augmentation
Spatial transformations and erasing operations. Matrix, inverse and annotation support depend on the class
-and configuration. Slice-mode crops reject inversion; non-rigid transforms do not carry boxes or keypoints
+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 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 90a4668bd..9552f9d7f 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -479,9 +479,8 @@ Augmentations
key's handler share their recorded parameters across the inputs; a transform
matrix alone does not mean every data key is supported.
- ``.inverse()`` restores keypoints to numerical precision when every
- geometric step is invertible. Slice-mode crops and the 3D geometric
- augmentations raise (crops accept ``cropping_mode="resample"`` for
- inversion); intensity and non-rigid children are skipped, so their effect
+ geometric step is invertible. The 3D geometric augmentations raise;
+ 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:
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index b54118348..744dd34af 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -54,7 +54,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
:class:`RandomTranslate`, :class:`RandomPerspective`, :class:`RandomElasticTransform` and
:class:`RandomThinPlateSpline` (`#4412 <https://github.com/kornia/kornia/issues/4412>`_).
- this base provides a matrix-based ``inverse`` interface. Whether a concrete augmentation can invert a
- call depends on its implementation and configuration: slice-mode crops, for example, do not support it.
+ call depends on its implementation: a subclass without ``inverse_transform`` raises ``NotImplementedError``.
Inverse resampling cannot recover image or mask information lost through cropping, padding, or
interpolation. Tensor-form boxes may lose rotated corners through axis-aligned enclosure.
For an empty batch, image and mask inverse restore the spatial dimensions recorded in the parameters.
diff --git a/kornia/augmentation/_2d/geometric/center_crop.py b/kornia/augmentation/_2d/geometric/center_crop.py
index e97259b64..23ea526e0 100644
--- a/kornia/augmentation/_2d/geometric/center_crop.py
+++ b/kornia/augmentation/_2d/geometric/center_crop.py
@@ -23,7 +23,7 @@ from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
from kornia.geometry.transform import crop_by_transform_mat
-from kornia.geometry.transform.crop2d import _crop_translation
+from kornia.geometry.transform.crop2d import _crop_inverse_by_transform_mat, _crop_translation
class CenterCrop(GeometricAugmentationBase2D):
@@ -58,9 +58,10 @@ class CenterCrop(GeometricAugmentationBase2D):
:class:`RandomCrop` and :class:`RandomResizedCrop` (`#4417 <https://github.com/kornia/kornia/issues/4417>`_).
``cropping_mode="slice"`` indexes the input and returns a copy, so writing to the result leaves the input
- unchanged. ``cropping_mode="resample"`` warps with the configured ``resample`` and ``align_corners``. Only
- resample mode supports :meth:`inverse`, which resamples onto the original canvas (zero padding unless the
- call passes ``padding_mode``) and cannot restore discarded data.
+ unchanged. ``cropping_mode="resample"`` warps with the configured ``resample`` and ``align_corners``. Both
+ modes support :meth:`inverse`, which warps the crop back onto the original canvas with the inverse of
+ ``transform_matrix`` (zero padding unless the call passes ``padding_mode``) and cannot restore discarded
+ data.
Examples:
>>> import torch
@@ -171,34 +172,15 @@ class CenterCrop(GeometricAugmentationBase2D):
transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
) -> torch.Tensor:
- if flags["cropping_mode"] != "resample":
- raise NotImplementedError(
- f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
- )
if size is None:
size = self.size
if not isinstance(transform, torch.Tensor):
raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
- return crop_by_transform_mat(
+ return _crop_inverse_by_transform_mat(
input,
- transform[:, :2, :],
+ transform,
size,
flags["resample"].name.lower(),
flags["padding_mode"],
flags["align_corners"],
)
-
- def inverse_inputs(
- self,
- input: torch.Tensor,
- params: Dict[str, torch.Tensor],
- flags: Dict[str, Any],
- transform: Optional[torch.Tensor] = None,
- **kwargs: Any,
- ) -> torch.Tensor:
- # Check the mode before the gate: an empty or unapplied batch never reaches inverse_transform, so a
- # slice-mode inverse succeeded for it and raised for any other batch. A keyword overrides the flag.
- cropping_mode = kwargs.get("cropping_mode", flags["cropping_mode"])
- if cropping_mode != "resample":
- raise NotImplementedError(f"`inverse` is only applicable for resample cropping mode. Got {cropping_mode}.")
- return super().inverse_inputs(input, params, flags, transform, **kwargs)
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index 5ada3d011..806f31146 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -31,7 +31,26 @@ from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat
from kornia.geometry.transform._crop import _compiled_slice_resize
-from kornia.geometry.transform.crop2d import _crop_translation
+from kornia.geometry.transform.crop2d import _crop_inverse_by_transform_mat, _crop_translation
+
+
+def _remove_padding(
+ input: torch.Tensor, padding: List[int], fill: Union[float, Sequence[float], torch.Tensor], padding_mode: str
+) -> torch.Tensor:
+ """Undo ``precrop_padding`` with its ``[left, right, top, bottom]`` padding.
+
+ A border the forward call added is sliced off, which needs no fill: an image's per-channel ``fill`` does not
+ fit a one-channel mask. A negative entry cropped the input, and that border is padded back as the forward call
+ pads; a per-channel ``fill`` that does not match the channels (a mask) pads it with zeros.
+ """
+ left, right, top, bottom = (max(side, 0) for side in padding)
+ output = input[..., top : input.shape[-2] - bottom, left : input.shape[-1] - right]
+ regrow = [max(-side, 0) for side in padding]
+ if any(regrow):
+ if not isinstance(fill, (int, float)) and torch.as_tensor(fill).numel() != output.shape[1]:
+ fill = 0.0
+ output = _pad_with_fill(output, regrow, fill, padding_mode)
+ return output
class RandomCrop(GeometricAugmentationBase2D):
@@ -98,8 +117,9 @@ class RandomCrop(GeometricAugmentationBase2D):
Slice mode uses :func:`~kornia.geometry.transform.crop_by_indices` with its own defaults and ignores this
class's ``resample`` and ``align_corners``. Resample mode uses the configured interpolation and
``align_corners`` and maps constant, replicate and reflect pre-padding to zero, border and reflection
- sampler padding. Only resample mode supports :meth:`inverse`, which removes the pre-crop padding but cannot
- restore cropped or interpolated content.
+ sampler padding. Both modes support :meth:`inverse`, for images, masks, boxes and keypoints: it warps with
+ the inverse of the mode's ``transform_matrix``, removes the pre-crop padding, and cannot restore cropped or
+ interpolated content.
For an empty batch, ``forward_input_shape`` records the original, unpadded canvas for inverse replay.
Note:
@@ -245,8 +265,16 @@ class RandomCrop(GeometricAugmentationBase2D):
return transform
padding_size = padding_size.to(device=input.device)
- padded_h = input.shape[-2] + padding_size[:, 2] + padding_size[:, 3]
- padded_w = input.shape[-1] + padding_size[:, 0] + padding_size[:, 1]
+ canvas = params.get("forward_input_shape")
+ if isinstance(canvas, torch.Tensor) and input.shape[0] > 0:
+ # The recorded padded canvas: an inverse passes the crop output as ``input``, and its shape would
+ # lose the scale of an oversized crop. A forward call records the canvas it is given, so it agrees.
+ canvas = canvas.to(device=input.device)
+ padded_h = canvas[-2].expand(input.shape[0])
+ padded_w = canvas[-1].expand(input.shape[0])
+ else:
+ padded_h = input.shape[-2] + padding_size[:, 2] + padding_size[:, 3]
+ padded_w = input.shape[-1] + padding_size[:, 0] + padding_size[:, 1]
h_out, w_out = flags["size"]
needs_scale = (h_out > padded_h) | (w_out > padded_w)
scale_w = torch.where(
@@ -351,10 +379,6 @@ class RandomCrop(GeometricAugmentationBase2D):
transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
) -> torch.Tensor:
- if flags["cropping_mode"] != "resample":
- raise NotImplementedError(
- f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
- )
if size is None:
raise RuntimeError("`size` has to be a tuple. Got None.")
if not isinstance(transform, torch.Tensor):
@@ -368,9 +392,9 @@ class RandomCrop(GeometricAugmentationBase2D):
padding_mode = "reflection"
else:
padding_mode = flags["padding_mode"]
- return crop_by_transform_mat(
+ return _crop_inverse_by_transform_mat(
input,
- transform[:, :2, :],
+ transform,
size,
flags["resample"].name.lower(),
padding_mode=padding_mode,
@@ -385,10 +409,6 @@ class RandomCrop(GeometricAugmentationBase2D):
transform: Optional[torch.Tensor] = None,
**kwargs: Any,
) -> torch.Tensor:
- # A keyword overrides the flag, and an empty or unapplied batch never reaches inverse_transform.
- cropping_mode = kwargs.get("cropping_mode", flags["cropping_mode"])
- if cropping_mode != "resample":
- raise NotImplementedError(f"`inverse` is only applicable for resample cropping mode. Got {cropping_mode}.")
if isinstance(transform, torch.Tensor):
# The inverse matrix returns original coordinates. The image inverse still renders
# onto forward_input_shape (the padded canvas), then removes its border below.
@@ -398,10 +418,9 @@ class RandomCrop(GeometricAugmentationBase2D):
if not to_apply.any():
return super().inverse_inputs(input, params, flags, transform, **kwargs)
padding_size = params["padding_size"].unique(dim=0).cpu().squeeze().tolist()
- unpadding = [-padding_size[0], -padding_size[1], -padding_size[2], -padding_size[3]]
if to_apply.all():
out = super().inverse_inputs(input, params, flags, transform, **kwargs)
- return self.precrop_padding(out, unpadding)
+ return _remove_padding(out, padding_size, flags["fill"], flags["padding_mode"])
# A mixed gate: the applied rows come back at the unpadded input size, so invert and unpad them on
# their own, and judge the shape change the caller sees, not the padded canvas.
in_tensor = self.transform_tensor(input)
@@ -414,37 +433,9 @@ class RandomCrop(GeometricAugmentationBase2D):
applied_transform = transform[to_apply] if isinstance(transform, torch.Tensor) else transform
out = super().inverse_inputs(in_tensor[to_apply], applied_params, flags, applied_transform, **kwargs)
output = in_tensor.clone()
- output[to_apply] = self.precrop_padding(out, unpadding)
+ output[to_apply] = _remove_padding(out, padding_size, flags["fill"], flags["padding_mode"])
return output
- def inverse_boxes(
- self,
- input: Boxes,
- params: Dict[str, torch.Tensor],
- flags: Dict[str, Any],
- transform: Optional[torch.Tensor] = None,
- **kwargs: Any,
- ) -> Boxes:
- if flags["cropping_mode"] != "resample":
- raise NotImplementedError(
- f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
- )
- return super().inverse_boxes(input, params, flags, transform, **kwargs)
-
- def inverse_keypoints(
- self,
- input: Keypoints,
- params: Dict[str, torch.Tensor],
- flags: Dict[str, Any],
- transform: Optional[torch.Tensor] = None,
- **kwargs: Any,
- ) -> Keypoints:
- if flags["cropping_mode"] != "resample":
- raise NotImplementedError(
- f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
- )
- return super().inverse_keypoints(input, params, flags, transform, **kwargs)
-
# Override parameters for precrop
def forward_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
input_pad = self.compute_padding(batch_shape)
diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.py
index 5579b127d..3002cf16e 100644
--- a/kornia/augmentation/_2d/geometric/resized_crop.py
+++ b/kornia/augmentation/_2d/geometric/resized_crop.py
@@ -27,7 +27,22 @@ from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
from kornia.core.utils import is_compiling
from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform
-from kornia.geometry.transform._crop import _compiled_slice_resize, _half_pixel_resize_transform
+from kornia.geometry.transform._crop import (
+ _compiled_slice_resize,
+ _corner_aligned_resize_transform,
+ _half_pixel_resize_transform,
+)
+from kornia.geometry.transform.crop2d import _crop_inverse_by_transform_mat
+
+
+def _one_pixel_axes(box: torch.Tensor, device: torch.device) -> torch.Tensor:
+ """``(B, 2)`` mask of the x and y axes along which an inclusive box is one pixel wide.
+
+ Read from the box in its stored dtype: cast to a half-precision input's dtype first, neighbouring coordinates
+ above 256 can round to one value in bfloat16 and make a two-pixel box look one pixel wide.
+ """
+ box = box.to(device)
+ return (box[:, 2] - box[:, 0]) == 0
class RandomResizedCrop(GeometricAugmentationBase2D):
@@ -79,8 +94,11 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
mode resizes the crop on the half-pixel grid, ``x' = (x - x0 + 0.5) * W_out / W_crop - 0.5`` for a crop
starting at column ``x0`` (likewise for ``y``), while resample mode maps the crop's corner pixel centres
onto the output's. Nearest sampling in slice mode uses the half-pixel grid and PyTorch's
- ``nearest-exact`` interpolation. Only resample mode supports
- :meth:`inverse`, which resamples onto the original canvas and cannot recover discarded information.
+ ``nearest-exact`` interpolation. With corner alignment, an axis where the output is one pixel long samples
+ the crop's first row or column, and one where the crop is one pixel long repeats it, as ``F.interpolate``
+ does, in both modes. Both modes support
+ :meth:`inverse`, which warps the output back onto the original canvas with the inverse of the mode's
+ ``transform_matrix`` and cannot recover discarded information.
Note:
Compiled slice-mode interpolation matches eager execution to floating-point tolerance,
@@ -151,7 +169,15 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
input.shape[0], -1, -1
)
if flags["cropping_mode"] in ("resample", "slice"):
- transform: torch.Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
+ src, dst = params["src"].to(input), params["dst"].to(input)
+ transform: torch.Tensor = get_perspective_transform(src, dst)
+ # A one-pixel crop or output axis makes the box vertices collinear, and the solve returns NaN or a
+ # singular matrix. Corner-aligned resizing samples the crop's first pixel along that axis, which the
+ # extent matrix encodes; every other box keeps the solved matrix bit for bit.
+ one_pixel = (
+ _one_pixel_axes(params["src"], input.device) | _one_pixel_axes(params["dst"], input.device)
+ ).any(-1)
+ transform = torch.where(one_pixel[:, None, None], _corner_aligned_resize_transform(src, dst), transform)
return transform.expand(input.shape[0], -1, -1)
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
@@ -166,7 +192,7 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
if not isinstance(transform, torch.Tensor):
raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
- return crop_by_transform_mat(
+ output = crop_by_transform_mat(
input,
transform[:, :2, :],
flags["size"],
@@ -174,6 +200,11 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
padding_mode="zeros",
align_corners=flags["align_corners"],
)
+ # A one-pixel crop axis has no scale to warp with: the matrix puts its pixel at output index 0, and the
+ # rest of that axis repeats it, as slice mode's interpolation does.
+ one_pixel = _one_pixel_axes(params["src"], input.device)
+ output = torch.where(one_pixel[:, 0, None, None, None], output[..., :1].expand_as(output), output)
+ return torch.where(one_pixel[:, 1, None, None, None], output[..., :1, :].expand_as(output), output)
if flags["cropping_mode"] == "slice": # uses advanced slicing to crop
mode = "nearest-exact" if flags["resample"] == Resample.NEAREST else flags["resample"].name.lower()
# ``interpolate`` rejects ``align_corners`` for nearest resampling.
@@ -189,6 +220,29 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
)
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
+ def inverse_inputs(
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ **kwargs: Any,
+ ) -> torch.Tensor:
+ output = super().inverse_inputs(input, params, flags, transform, **kwargs)
+ # A one-pixel crop axis is a translation in the matrix, so the inverse warp also lays the repeated pixel
+ # onto the canvas pixels after it. With zero padding, everything outside the crop is zero.
+ if kwargs.get("padding_mode", flags["padding_mode"]) != "zeros" or output.shape[0] == 0:
+ return output
+ one_pixel = _one_pixel_axes(params["src"], output.device) & self._gate(params).to(output.device)[:, None]
+ # Integer pixel indices: in bfloat16 neighbouring indices above 256 round to the same value.
+ start = params["src"][:, 0].to(output.device).round().long()
+ columns = torch.arange(output.shape[-1], device=output.device)
+ rows = torch.arange(output.shape[-2], device=output.device)
+ keep_columns = ~one_pixel[:, :1] | (columns == start[:, :1])
+ keep_rows = ~one_pixel[:, 1:] | (rows == start[:, 1:])
+ keep = keep_rows[:, None, :, None] & keep_columns[:, None, None, :]
+ return torch.where(keep, output, torch.zeros_like(output))
+
def inverse_transform(
self,
input: torch.Tensor,
@@ -196,36 +250,17 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
) -> torch.Tensor:
- if flags["cropping_mode"] != "resample":
- raise NotImplementedError(
- f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
- )
if not isinstance(size, tuple):
raise TypeError(f"Expected the size be a tuple. Got {type(size)}")
if not isinstance(transform, torch.Tensor):
raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
- return crop_by_transform_mat(
+ return _crop_inverse_by_transform_mat(
input,
- transform[:, :2, :],
+ transform,
size,
flags["resample"].name.lower(),
flags["padding_mode"],
flags["align_corners"],
)
-
- def inverse_inputs(
- self,
- input: torch.Tensor,
- params: Dict[str, torch.Tensor],
- flags: Dict[str, Any],
- transform: Optional[torch.Tensor] = None,
- **kwargs: Any,
- ) -> torch.Tensor:
- # Check the mode before the gate: an empty or unapplied batch never reaches inverse_transform, so a
- # slice-mode inverse succeeded for it and raised for any other batch. A keyword overrides the flag.
- cropping_mode = kwargs.get("cropping_mode", flags["cropping_mode"])
- if cropping_mode != "resample":
- raise NotImplementedError(f"`inverse` is only applicable for resample cropping mode. Got {cropping_mode}.")
- return super().inverse_inputs(input, params, flags, transform, **kwargs)
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 6605bbd88..dfab7a639 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -172,10 +172,9 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
``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.
+ 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
+ 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.
- Nested :class:`AugmentationSequential` children contribute the matrix they record for the current call
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 1cf69508b..a6b8b482f 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -90,9 +90,9 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
does not honor its ordinary selection weight. Each selected member is recorded in ``_params``, but
a plain module records a ``None`` payload: only augmentation members carry a parameter draw to replay.
- ``inverse`` treats a plain ``nn.Module`` member according to ``if_unsupported_ops``, and a nested
- container according to its own setting. Augmentation children can still raise, for example a
- slice-mode crop or a 3D geometric augmentation, while intensity and non-rigid augmentation children
- are left applied; the round trip is not in general the input.
+ container according to its own setting. Augmentation children can still raise, for example a 3D
+ geometric augmentation, while intensity and non-rigid augmentation children are left applied; the round
+ trip is not in general the input.
.. note::
Transformation matrix returned only considers the transformation applied in ``kornia.augmentation`` module.
diff --git a/kornia/geometry/transform/_crop.py b/kornia/geometry/transform/_crop.py
index b6650ad7d..e077200e6 100644
--- a/kornia/geometry/transform/_crop.py
+++ b/kornia/geometry/transform/_crop.py
@@ -32,6 +32,25 @@ def _half_pixel_resize_transform(src: torch.Tensor, dst: torch.Tensor) -> torch.
return transform
+def _corner_aligned_resize_transform(src: torch.Tensor, dst: torch.Tensor) -> torch.Tensor:
+ """Map pixel indices between inclusive, axis-aligned crop and output boxes, as ``align_corners=True`` resizes.
+
+ Corner alignment has no scale along an axis where either box is one pixel wide. There ``F.interpolate``
+ samples only the crop's first pixel (a one-pixel output) or repeats it (a one-pixel crop). That axis is a
+ translation sending the first pixel onto output pixel 0, so the matrix stays invertible and, unlike a large
+ scale, representable in half precision. The caller repeats a one-pixel crop along the output axis, and clears
+ what the inverse warp brings back onto the canvas next to it.
+ """
+ src_extent = src[:, 2] - src[:, 0]
+ dst_extent = dst[:, 2] - dst[:, 0]
+ one_pixel = (src_extent == 0) | (dst_extent == 0)
+ ones = torch.ones_like(src_extent)
+ scale = torch.where(one_pixel, ones, dst_extent / torch.where(one_pixel, ones, src_extent))
+ transform = torch.diag_embed(torch.cat((scale, ones[:, :1]), dim=-1))
+ transform[:, :2, 2] = dst[:, 0] - scale * src[:, 0]
+ return transform
+
+
def _resize_coordinates(
start: torch.Tensor,
end: torch.Tensor,
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index 16aa662f2..b018e2e2e 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -417,6 +417,34 @@ def crop_by_transform_mat(
return patches
+def _crop_inverse_by_transform_mat(
+ input_tensor: torch.Tensor,
+ transform: torch.Tensor,
+ out_size: Tuple[int, int],
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
+ align_corners: bool = True,
+) -> torch.Tensor:
+ """:func:`crop_by_transform_mat` for warping a crop back onto its canvas, also from a one-pixel axis.
+
+ ``grid_sample`` cannot place a source axis of length 1: with ``align_corners=True`` every sample lands on its
+ only pixel, so the whole canvas axis gets its value, and with ``False`` it blends it into the next pixel. One
+ pixel of padding on each side of such an axis, in the warp's own padding (a reflected one-pixel axis repeats
+ its pixel), gives the sampler a neighbour to interpolate towards, and ``transform`` is shifted to match.
+ ``transform`` is the :math:`(B, 3, 3)` crop-to-canvas pixel matrix.
+ """
+ pad_h = int(input_tensor.shape[-2] == 1)
+ pad_w = int(input_tensor.shape[-1] == 1)
+ if pad_h or pad_w:
+ pad_mode = "constant" if padding_mode == "zeros" else "replicate"
+ input_tensor = F.pad(input_tensor, (pad_w, pad_w, pad_h, pad_h), mode=pad_mode)
+ shift = torch.eye(3, device=transform.device, dtype=transform.dtype)
+ shift[0, 2] = -pad_w
+ shift[1, 2] = -pad_h
+ transform = transform @ shift
+ return crop_by_transform_mat(input_tensor, transform[:, :2, :], out_size, mode, padding_mode, align_corners)
+
+
def crop_by_indices(
input_tensor: torch.Tensor,
src_box: torch.Tensor,
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 844582482..24aba8e35 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -1211,6 +1211,12 @@ class TestAugmentationSequential:
assert outputs[3].dtype == dtype, "Output keypoints dtype should match the input dtype"
+class _FailingInverseCrop(K.RandomResizedCrop):
+ # A crop whose image and mask inverse raises, to check what an exception inside inverse leaves behind.
+ def inverse_transform(self, *args, **kwargs):
+ raise NotImplementedError("inverse_transform failed")
+
+
@pytest.mark.usefixtures("restore_torch_rng")
class TestConventionAugmentationSequential(BaseTester):
"""Convention checks and pins for documented `AugmentationSequential` limitations."""
@@ -1359,15 +1365,15 @@ class TestConventionAugmentationSequential(BaseTester):
def test_inverse_mask_exception_preserves_next_image_5290(self, mask_first, device, dtype):
image = torch.arange(16 * 20, device=device, dtype=dtype).reshape(1, 1, 16, 20) / 320
mask = (image > 0.5).to(dtype)
- seq = K.AugmentationSequential(K.RandomResizedCrop((12, 14), p=1.0), data_keys=["input", "mask"])
- reference = K.AugmentationSequential(K.RandomResizedCrop((12, 14), p=1.0), data_keys=["input", "mask"])
+ seq = K.AugmentationSequential(_FailingInverseCrop((12, 14), p=1.0), data_keys=["input", "mask"])
+ reference = K.AugmentationSequential(_FailingInverseCrop((12, 14), p=1.0), data_keys=["input", "mask"])
out_image, out_mask = seq(image, mask)
params = seq._params
original_flags = dict(seq[0].flags)
inverse_args = (out_mask, out_image) if mask_first else (out_mask,)
inverse_keys = ["mask", "input"] if mask_first else ["mask"]
- with pytest.raises(NotImplementedError, match=r"resample cropping mode\. Got slice\."):
+ with pytest.raises(NotImplementedError, match="inverse_transform failed"):
seq.inverse(*inverse_args, data_keys=inverse_keys)
# Explicit keys keep this independent of the container's separate data_keys restoration bug.
@@ -1379,12 +1385,12 @@ class TestConventionAugmentationSequential(BaseTester):
@pytest.mark.parametrize("align_corners", [None, False, True])
@pytest.mark.parametrize("shared_flags", [True, False])
def test_direct_inverse_mask_exception_preserves_flags_5290(self, align_corners, shared_flags, device, dtype):
- aug = K.RandomResizedCrop((4, 6), align_corners=True, p=1.0)
+ aug = _FailingInverseCrop((4, 6), align_corners=True, p=1.0)
mask = aug(torch.ones(1, 1, 6, 8, device=device, dtype=dtype))
flags = aug.flags if shared_flags else dict(aug.flags)
original_flags = dict(flags)
- with pytest.raises(NotImplementedError, match=r"resample cropping mode\. Got slice\."):
+ with pytest.raises(NotImplementedError, match="inverse_transform failed"):
aug.inverse_masks(mask, aug._params, flags, transform=aug.transform_matrix, align_corners=align_corners)
assert flags["align_corners"] == original_flags["align_corners"]
@@ -2305,11 +2311,16 @@ class TestConventionAugmentationSequential(BaseTester):
outer(torch.rand(1, 1, 6, 8, device=device, dtype=dtype))
@pytest.mark.parametrize("crop_cls", [K.CenterCrop, K.RandomCrop, K.RandomResizedCrop])
- def test_convention_slice_crop_inverse_raises(self, crop_cls, device, dtype):
+ def test_convention_slice_crop_inverse_restores_the_canvas(self, crop_cls, device, dtype):
+ # Slice-mode crops invert like resample-mode ones: the output is warped back onto the input canvas.
seq = K.AugmentationSequential(crop_cls((4, 6), p=1.0), data_keys=["input"])
- out = seq(torch.rand(1, 3, 6, 8, device=device, dtype=dtype))
- with pytest.raises(NotImplementedError, match="resample cropping mode"):
- seq.inverse(out)
+ image = torch.rand(1, 3, 6, 8, device=device, dtype=dtype)
+ out = seq(image)
+ restored = seq.inverse(out)
+ assert restored.shape == image.shape
+ if crop_cls is not K.RandomResizedCrop:
+ left, top = seq[0]._params["src"][0, 0].long().tolist()
+ self.assert_close(restored[..., top : top + 4, left : left + 6], out)
def test_convention_3d_inverse_raises_for_geometry_and_skips_intensity(self, device, dtype):
# Enough voxels in two populated histogram bins force an actual equalization in every dtype.
diff --git a/tests/augmentation/container/test_sequential_aug.py b/tests/augmentation/container/test_sequential_aug.py
index d62108045..64b7b0958 100644
--- a/tests/augmentation/container/test_sequential_aug.py
+++ b/tests/augmentation/container/test_sequential_aug.py
@@ -142,11 +142,12 @@ class TestConventionImageSequential(BaseTester):
with pytest.raises(ValueError, match="Invalid output_type"):
aug(torch.zeros(1, 3, 4, 4, device=device, dtype=dtype), output_type="jpg")
- def test_convention_slice_crop_inverse_raises(self, device, dtype):
+ def test_convention_slice_crop_inverse_restores_the_canvas(self, device, dtype):
seq = K.ImageSequential(K.CenterCrop((4, 6), p=1.0))
out = seq(torch.rand(1, 3, 6, 8, device=device, dtype=dtype))
- with pytest.raises(NotImplementedError, match="resample cropping mode"):
- seq.inverse(out)
+ restored = seq.inverse(out)
+ assert restored.shape == (1, 3, 6, 8)
+ self.assert_close(restored[..., 1:5, 1:7], out)
def test_convention_get_transformation_matrix_recomputes_older_params(self, device, dtype):
# Module matrices hold only the most recent call. Supplying recorded parameters from an earlier call
diff --git a/tests/augmentation/test_conventions_geometric_crop.py b/tests/augmentation/test_conventions_geometric_crop.py
index 3306b6496..93c2a1742 100644
--- a/tests/augmentation/test_conventions_geometric_crop.py
+++ b/tests/augmentation/test_conventions_geometric_crop.py
@@ -35,8 +35,12 @@ class TestGeometricCropConventions(BaseTester):
slice_crop = K.CenterCrop(4, cropping_mode="slice")
self.assert_close(slice_crop(x), expected)
- with pytest.raises(NotImplementedError, match="only applicable for resample"):
- slice_crop.inverse(expected)
+ # The inverse pastes the crop back onto a zero canvas of the input size.
+ restored = slice_crop.inverse(expected)
+ assert restored.shape == x.shape
+ self.assert_close(restored[..., 1:5, 2:6], expected)
+ self.assert_close(restored[..., :1, :], torch.zeros_like(restored[..., :1, :]))
+ self.assert_close(restored[..., :, :2], torch.zeros_like(restored[..., :, :2]))
resample_crop = K.CenterCrop((4, 4), cropping_mode="resample")
resample_output = resample_crop(x)
@@ -94,8 +98,7 @@ class TestGeometricCropConventions(BaseTester):
assert resample.inverse(output).shape == x.shape
slice_crop = K.RandomCrop((3, 3), p=1.0, cropping_mode="slice")
slice_output = slice_crop(x)
- with pytest.raises(NotImplementedError, match="only applicable for resample"):
- slice_crop.inverse(slice_output)
+ self.assert_close(slice_crop.inverse(slice_output), x)
image = torch.arange(48, device=device, dtype=dtype).reshape(1, 1, 6, 8)
nearest = K.RandomCrop((3, 3), resample="nearest", align_corners=False, p=1.0, cropping_mode="resample")
@@ -311,11 +314,7 @@ class TestGeometricCropConventions(BaseTester):
crop = K.RandomResizedCrop(cropping_mode=mode, **kwargs)
output = crop(x)
assert output.shape == (1, 1, 3, 4)
- if mode == "resample":
- assert crop.inverse(output).shape == x.shape
- else:
- with pytest.raises(NotImplementedError, match="only applicable for resample"):
- crop.inverse(output)
+ assert crop.inverse(output).shape == x.shape
nearest = K.RandomResizedCrop(
size=(6, 8),
@@ -331,6 +330,166 @@ class TestGeometricCropConventions(BaseTester):
params["dst"] = torch.tensor([[[0, 0], [7, 0], [7, 5], [0, 5]]], device=device, dtype=dtype)
self.assert_close(nearest(x, params=params), x)
+ @pytest.mark.parametrize("align_corners", [True, False])
+ @pytest.mark.parametrize("mode", ["slice", "resample"])
+ @pytest.mark.parametrize("crop_cls", [K.CenterCrop, K.RandomCrop])
+ @pytest.mark.parametrize("size", [(1, 1), (1, 3), (3, 1)])
+ def test_convention_crop_inverse_with_a_one_pixel_axis(self, size, crop_cls, mode, align_corners, device, dtype):
+ # grid_sample cannot place a source axis of length 1: the inverse spread the crop's only row or column over
+ # the whole canvas (align_corners=True) or into the next pixel. It pastes the crop back like any other.
+ torch.manual_seed(0)
+ x = (torch.arange(1, 36, device=device, dtype=dtype) / 35).reshape(1, 1, 5, 7)
+ kwargs = {"p": 1.0} if crop_cls is K.RandomCrop else {}
+ crop = crop_cls(size, cropping_mode=mode, align_corners=align_corners, **kwargs)
+ output = crop(x)
+ left, top = crop._params["src"][0, 0].long().tolist()
+ expected = torch.zeros_like(x)
+ expected[..., top : top + size[0], left : left + size[1]] = x[..., top : top + size[0], left : left + size[1]]
+ self.assert_close(crop.inverse(output), expected, low_tolerance=True)
+ inverse_matrix = crop.compute_inverse_transformation(crop.transform_matrix)
+ self.assert_close(
+ crop.inverse_masks(output, crop._params, crop.flags, inverse_matrix), expected, low_tolerance=True
+ )
+
+ @pytest.mark.parametrize("mode", ["slice", "resample"])
+ def test_convention_random_crop_inverse_of_an_oversized_crop(self, mode, device, dtype):
+ # The inverse rebuilt the matrix from the crop output's shape, so the scale of an oversized crop was lost and
+ # the inverse took the top-left corner of the upscaled crop. It scales against the recorded canvas now.
+ ys, xs = torch.meshgrid(torch.arange(5), torch.arange(5), indexing="ij")
+ ramp = ((xs + 2 * ys) / 15)[None, None].to(device, dtype)
+ crop = K.RandomCrop((10, 10), p=1.0, cropping_mode=mode)
+ restored = crop.inverse(crop(ramp))
+ # Slice mode upsamples on the half-pixel grid, which clamps at the border.
+ self.assert_close(restored[..., 1:-1, 1:-1], ramp[..., 1:-1, 1:-1], low_tolerance=True)
+
+ @pytest.mark.parametrize("padding", [1, -1, (1, -1)])
+ @pytest.mark.parametrize("mode", ["slice", "resample"])
+ def test_convention_random_crop_mask_inverse_with_a_per_channel_fill(self, mode, padding, device, dtype):
+ # Removing the pre-crop padding from a mask went through the forward padding, whose per-channel image fill
+ # does not fit a one-channel mask, and raised.
+ crop = K.RandomCrop((3, 5), padding=padding, fill=(0.1, 0.2, 0.3), p=1.0, cropping_mode=mode)
+ seq = K.AugmentationSequential(crop, data_keys=["input", "mask"])
+ image = torch.rand(1, 3, 5, 7, device=device, dtype=dtype)
+ mask = torch.rand(1, 1, 5, 7, device=device, dtype=dtype)
+ restored_image, restored_mask = seq.inverse(*seq(image, mask), data_keys=["input", "mask"])
+ assert restored_image.shape == image.shape
+ assert restored_mask.shape == mask.shape
+
+ @pytest.mark.parametrize("padding", [-1, (1, -1), (-1, 2, 0, -1)])
+ @pytest.mark.parametrize("mode", ["slice", "resample"])
+ def test_convention_random_crop_inverse_restores_a_negatively_padded_canvas(self, mode, padding, device, dtype):
+ # Negative padding crops the input before the crop: the inverse pads that border back onto the canvas.
+ x = torch.arange(35, device=device, dtype=dtype).reshape(1, 1, 5, 7)
+ crop = K.RandomCrop((3, 5), padding=padding, p=1.0, cropping_mode=mode)
+ restored = crop.inverse(crop(x))
+ assert restored.shape == x.shape
+ if padding == -1:
+ expected = torch.zeros_like(x)
+ expected[..., 1:4, 1:6] = x[..., 1:4, 1:6]
+ self.assert_close(restored, expected, low_tolerance=True)
+
+ def test_convention_resized_crop_with_a_one_pixel_crop(self, device, dtype):
+ # A one-pixel crop axis has no corner-aligned scale. Slice mode repeats the pixel, and resample mode, which
+ # returned NaN, now repeats it too instead of sampling its neighbours; the inverse puts it back.
+ x = torch.arange(35, device=device, dtype=dtype).reshape(1, 1, 5, 7)
+ kwargs = {"size": (3, 3), "scale": (1.0, 1.0), "ratio": (1.0, 1.0), "align_corners": True, "p": 1.0}
+ slice_crop = K.RandomResizedCrop(cropping_mode="slice", **kwargs)
+ params = slice_crop.forward_parameters(x.shape)
+ params["src"] = torch.tensor([[[4.0, 3.0], [4.0, 3.0], [4.0, 3.0], [4.0, 3.0]]], device=device, dtype=dtype)
+ slice_output = slice_crop(x, params=params)
+ self.assert_close(slice_output, torch.full_like(slice_output, 25))
+ resample_output = K.RandomResizedCrop(cropping_mode="resample", **kwargs)(x, params=params)
+ self.assert_close(resample_output, slice_output)
+ expected = torch.zeros_like(x)
+ expected[..., 3, 4] = 25
+ self.assert_close(slice_crop.inverse(slice_output, params=params), expected, low_tolerance=True)
+
+ @pytest.mark.parametrize(("canvas", "column", "row"), [(256, 200, 180), (512, 256, 256), (512, 257, 300)])
+ def test_convention_resized_crop_with_a_one_pixel_crop_on_a_large_canvas(self, canvas, column, row, device, dtype):
+ # A scale large enough to push the next canvas pixel off the output overflowed the translation in float16
+ # (448 x 200 > 65504): the matrix held -inf and the inverse NaN. The one-pixel axis is a translation, and
+ # the inverse clears the canvas next to the crop by integer index: in bfloat16, 256 and 257 coincide.
+ x = torch.ones(1, 1, canvas, canvas, device=device, dtype=dtype)
+ kwargs = {"size": (224, 224), "scale": (1.0, 1.0), "ratio": (1.0, 1.0), "align_corners": True, "p": 1.0}
+ slice_crop = K.RandomResizedCrop(cropping_mode="slice", **kwargs)
+ params = slice_crop.forward_parameters(x.shape)
+ params["src"] = torch.tensor([[[column, row]] * 4], device=device, dtype=torch.float32)
+ slice_output = slice_crop(x, params=params)
+ assert torch.isfinite(slice_crop.transform_matrix).all()
+ resample_output = K.RandomResizedCrop(cropping_mode="resample", **kwargs)(x, params=params)
+ self.assert_close(resample_output, slice_output)
+ restored = slice_crop.inverse(slice_output, params=params)
+ if device.type == "mps" and dtype in (torch.float16, torch.bfloat16):
+ # MPS samples a half-precision image on a half-precision grid, about 0.1 px off on a 512-pixel axis, so
+ # only the place of the restored pixel is exact.
+ assert restored.count_nonzero() == 1
+ assert restored[..., row, column] > 0.5
+ else:
+ expected = torch.zeros_like(x)
+ expected[..., row, column] = 1
+ self.assert_close(restored, expected, low_tolerance=True)
+ # Border padding extends the crop's only pixel, which is the pixel itself.
+ self.assert_close(
+ slice_crop.inverse(slice_output, params=params, padding_mode="border"),
+ torch.ones_like(x),
+ low_tolerance=True,
+ )
+
+ @pytest.mark.parametrize("size", [(1, 1), (1, 3), (3, 1)])
+ def test_convention_resized_crop_with_a_one_pixel_output_axis(self, size, device, dtype):
+ # The box vertices are collinear along a one-pixel axis, and the solved matrix was NaN: resample mode
+ # returned NaN and the slice-mode inverse a canvas of NaN. Corner-aligned resizing samples the crop's first
+ # row or column there, so both modes return it and the inverse puts it back.
+ x = torch.arange(1, 36, device=device, dtype=dtype).reshape(1, 1, 5, 7)
+ kwargs = {"size": size, "scale": (1.0, 1.0), "ratio": (7 / 5, 7 / 5), "align_corners": True, "p": 1.0}
+ slice_crop = K.RandomResizedCrop(cropping_mode="slice", **kwargs)
+ slice_output = slice_crop(x)
+ resample_output = K.RandomResizedCrop(cropping_mode="resample", **kwargs)(x, params=slice_crop._params)
+ self.assert_close(resample_output, slice_output, low_tolerance=True)
+ expected = torch.zeros_like(x)
+ rows = slice(0, 1) if size[0] == 1 else slice(None)
+ columns = slice(0, 1) if size[1] == 1 else slice(None)
+ expected[..., rows, columns] = x[..., rows, columns]
+ self.assert_close(slice_crop.inverse(slice_output), expected, low_tolerance=True)
+ assert slice_crop.inverse(slice_output).isfinite().all()
+
+ @pytest.mark.parametrize("align_corners", [True, False])
+ @pytest.mark.parametrize(
+ "make_crop",
+ [
+ lambda ac: K.CenterCrop((8, 11), align_corners=ac, cropping_mode="slice"),
+ lambda ac: K.RandomCrop((8, 11), align_corners=ac, p=1.0, cropping_mode="slice"),
+ lambda ac: K.RandomCrop((8, 11), padding=(2, 1), align_corners=ac, p=1.0, cropping_mode="slice"),
+ lambda ac: K.RandomCrop((24, 33), pad_if_needed=True, align_corners=ac, p=1.0, cropping_mode="slice"),
+ lambda ac: K.RandomCrop((24, 33), align_corners=ac, p=1.0, cropping_mode="slice"),
+ lambda ac: K.RandomResizedCrop((12, 12), scale=(0.3, 0.5), align_corners=ac, p=1.0, cropping_mode="slice"),
+ ],
+ ids=["center", "random", "random-padding", "random-pad-if-needed", "random-oversized", "resized"],
+ )
+ def test_convention_slice_crop_inverse_follows_the_transform_matrix(self, make_crop, align_corners, device, dtype):
+ # Slice mode records the crop's transform_matrix like resample mode, and its inverse warps back with it. A
+ # bilinear resize and warp reproduce a linear ramp, so the ramp comes back wherever the crop covered it.
+ torch.manual_seed(0)
+ height, width = 20, 30
+ ys, xs = torch.meshgrid(torch.arange(height), torch.arange(width), indexing="ij")
+ ramp = (torch.stack([xs / width, ys / height, (xs + 2 * ys) / (width + 2 * height)])[None] * 0.9 + 0.05).to(
+ device, dtype
+ )
+ ramp = ramp.expand(2, -1, -1, -1).contiguous()
+ crop = make_crop(align_corners)
+ restored = crop.inverse(crop(ramp))
+ assert restored.shape == ramp.shape
+ # Canvas pixels that map at least one pixel inside the crop output.
+ # Mapped on the CPU in float64 (MPS has no float64).
+ points = torch.stack([xs.flatten(), ys.flatten(), torch.ones(height * width, dtype=torch.long)]).double()
+ mapped = crop.transform_matrix.cpu().double() @ points
+ out_height, out_width = crop(ramp, params=crop._params).shape[-2:]
+ u, v = mapped[:, 0] / mapped[:, 2], mapped[:, 1] / mapped[:, 2]
+ inside = (u >= 1) & (u <= out_width - 2) & (v >= 1) & (v <= out_height - 2)
+ inside = inside.view(2, 1, height, width).to(device).expand_as(ramp)
+ assert inside.any()
+ self.assert_close(restored[inside], ramp[inside], low_tolerance=True)
+
@pytest.mark.device_agnostic
@pytest.mark.parametrize(
"shape,crops",
diff --git a/tests/augmentation/test_empty_inverse.py b/tests/augmentation/test_empty_inverse.py
index 3649dcd67..74a236a54 100644
--- a/tests/augmentation/test_empty_inverse.py
+++ b/tests/augmentation/test_empty_inverse.py
@@ -396,42 +396,33 @@ class TestEmptyGeometricInverse(BaseTester):
],
ids=["random-crop", "center-crop", "resized-crop"],
)
- def test_slice_crop_inverse_is_unsupported_4429(self, make_aug, data_key, p, batch_size, device, dtype):
- # The mode is checked before the gate: CenterCrop and RandomResizedCrop checked it only in inverse_transform,
- # which an empty or unapplied batch never reaches, so their slice-mode inverse succeeded for those batches.
+ def test_slice_crop_inverse_4429(self, make_aug, data_key, p, batch_size, device, dtype):
+ # Slice mode inverts like resample mode, at every batch size: an empty or unapplied batch keeps its canvas,
+ # and an applied one is warped back with the inverse of the recorded transform matrix.
aug = make_aug(p)
channels = 3 if data_key == "input" else 1
image = torch.rand(batch_size, channels, 6, 8, device=device, dtype=dtype)
output = aug(image)
method = aug.inverse_inputs if data_key == "input" else aug.inverse_masks
- with pytest.raises(NotImplementedError, match="only applicable for resample cropping mode"):
- method(output, aug._params, aug.flags, aug.transform_matrix)
+ restored = method(output, aug._params, aug.flags, aug.compute_inverse_transformation(aug.transform_matrix))
+ assert restored.shape == image.shape
+ if p == 0.0:
+ self.assert_close(restored, image)
seq = K.AugmentationSequential(make_aug(p), data_keys=["input", "mask"])
mask = torch.rand(batch_size, 1, 6, 8, device=device, dtype=dtype)
outputs = dict(zip(["input", "mask"], seq(torch.rand(batch_size, 3, 6, 8, device=device, dtype=dtype), mask)))
- with pytest.raises(NotImplementedError, match="only applicable for resample cropping mode"):
- seq.inverse(outputs[data_key], data_keys=[data_key])
-
- @pytest.mark.parametrize("batch_size", [0, 2])
- @pytest.mark.parametrize("method", ["inverse_inputs", "inverse_masks"])
- @pytest.mark.parametrize("crop_type", [K.RandomCrop, K.CenterCrop, K.RandomResizedCrop])
- def test_slice_crop_inverse_keyword_override_4429(self, crop_type, method, batch_size, device, dtype):
- # A cropping_mode keyword overrides the flag, as in the public inverse, before the empty-batch shortcut.
- aug = crop_type((4, 5), p=1.0, cropping_mode="resample")
- output = aug(torch.rand(batch_size, 3 if method == "inverse_inputs" else 1, 6, 8, device=device, dtype=dtype))
- inverse = getattr(aug, method)
- with pytest.raises(NotImplementedError, match="Got slice"):
- inverse(output, aug._params, aug.flags, aug.transform_matrix, cropping_mode="slice")
- assert inverse(output, aug._params, aug.flags, aug.transform_matrix).shape[-2:] == (6, 8)
+ assert seq.inverse(outputs[data_key], data_keys=[data_key]).shape[-2:] == (6, 8)
@pytest.mark.parametrize("batch_size", [0, 2])
@pytest.mark.parametrize(
"make_aug",
[
lambda: K.CenterCrop((4, 5), cropping_mode="slice"),
+ lambda: K.RandomCrop((4, 5), p=1.0, cropping_mode="slice"),
+ lambda: K.RandomCrop((4, 5), padding=1, p=1.0, cropping_mode="slice"),
lambda: K.RandomResizedCrop((4, 5), p=1.0, cropping_mode="slice"),
],
- ids=["center-crop", "resized-crop"],
+ ids=["center-crop", "random-crop", "random-crop-padding", "resized-crop"],
)
def test_slice_crop_inverse_keeps_geometry(self, make_aug, batch_size, device, dtype):
# Boxes and keypoints invert through the transform matrix, which slice mode records too.