Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): include crop padding in transform matrix (#5114)

Puttala Jeevan Kumare3e7b22459ae
diff --git a/changelog.d/5114.breaking.md b/changelog.d/5114.breaking.md
new file mode 100644
index 000000000..f48c8326e
--- /dev/null
+++ b/changelog.d/5114.breaking.md
@@ -0,0 +1 @@
+`RandomCrop` and `RandomCrop3D` previously exposed `transform_matrix` in padded-canvas coordinates, so callers had to add the pre-crop left/top (and front for 3D) padding themselves. They now map original input coordinates directly to output coordinates; callers that manually added padding must remove that workaround.
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index 30e4d9a78..eecd738b7 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -44,9 +44,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
- pixel coordinates are ``(x, y)`` at integer pixel centres, with corners ``(0, 0)`` and
``(W - 1, H - 1)`` (see :doc:`/get-started/conventions`); rotations, shears and affine maps are centred
at ``((W - 1) / 2, (H - 1) / 2)``, and ``transform_matrix`` maps input pixel coordinates to output pixel
- coordinates. Two exceptions: with pre-crop padding (``padding`` or ``pad_if_needed``), the matrix of
- :class:`RandomCrop` starts from the padded canvas
- (`#4801 <https://github.com/kornia/kornia/issues/4801>`_); at ``align_corners=False``, the bilinear and
+ coordinates. At ``align_corners=False``, the bilinear and
bicubic interpolation of :class:`Resize`, :class:`LongestMaxSize`, :class:`SmallestMaxSize` and
slice-mode :class:`RandomResizedCrop` samples on a half-pixel grid that the matrix does not follow
(`#4804 <https://github.com/kornia/kornia/issues/4804>`_).
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index 3da8e85c6..652ede5f4 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -77,9 +77,8 @@ class RandomCrop(GeometricAugmentationBase2D):
See :class:`~kornia.augmentation.GeometricAugmentationBase2D` for coordinates, defaults and inverse.
``size`` is an ``(height, width)`` tuple; a bare integer raises, unlike :class:`CenterCrop`
(`#4417 <https://github.com/kornia/kornia/issues/4417>`_). ``p`` selects or skips the whole batch
- together; a skipped batch is returned unchanged and unpadded. With ``padding`` or ``pad_if_needed``,
- ``transform_matrix`` maps the padded canvas, not the input, to the crop
- (`#4801 <https://github.com/kornia/kornia/issues/4801>`_).
+ together; a skipped batch is returned unchanged and unpadded. ``transform_matrix`` maps original input
+ coordinates to the crop, including the translation from ``padding`` or ``pad_if_needed``.
Explicit ``padding`` is applied before sampling, in ``(left, top, right, bottom)`` order after its scalar
or two-value shorthand is expanded. ``pad_if_needed=True`` pads each side by the maximum of that padding
@@ -195,8 +194,24 @@ class RandomCrop(GeometricAugmentationBase2D):
return input
+ def _padding_offset(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ padding = params.get("padding_size")
+ if is_exporting() or not isinstance(padding, torch.Tensor):
+ # Recompute the canvas from the module flags, as ``precrop_padding`` does for the pixels.
+ padding = _constant_tensor(tuple(self.compute_padding(tuple(input.shape))), dtype=torch.long)[None]
+ return padding[:, ::2].to(input)
+
def compute_transformation(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
+ transform = self._compute_crop_transformation(input, params, flags)
+ # Column vectors: M = crop @ padding, including the existing oversized-crop scale.
+ offset = self._padding_offset(input, params)
+ transform[:, :2, 2] += (transform[:, :2, :2] @ offset[..., None]).squeeze(-1)
+ return transform
+
+ def _compute_crop_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
if flags["cropping_mode"] in ("resample", "slice"):
src = params["src"].to(input)
@@ -245,10 +260,8 @@ class RandomCrop(GeometricAugmentationBase2D):
flags: Dict[str, Any],
transform: Optional[torch.Tensor] = None,
) -> Keypoints:
- """Pad and transform keypoints without modifying the skipped branch."""
- padding_size = params["padding_size"].to(device=input.device)
- # pad mutates its input; keep the original coordinates for the non-transform branch.
- input = input.clone().pad(padding_size)
+ """Transform original keypoints without modifying the skipped branch."""
+ input = input.clone()
return super().apply_transform_keypoint(input=input, params=params, flags=flags, transform=transform)
def apply_transform_box(
@@ -258,10 +271,8 @@ class RandomCrop(GeometricAugmentationBase2D):
flags: Dict[str, Any],
transform: Optional[torch.Tensor] = None,
) -> Boxes:
- """Pad and transform boxes without modifying the skipped branch."""
- padding_size = params["padding_size"]
- # pad mutates its input; keep the original coordinates for the non-transform branch.
- input = input.clone().pad(padding_size)
+ """Transform original boxes without modifying the skipped branch."""
+ input = input.clone()
return super().apply_transform_box(input=input, params=params, flags=flags, transform=transform)
def apply_transform(
@@ -278,6 +289,17 @@ class RandomCrop(GeometricAugmentationBase2D):
padding_size = None
elif "padding_size" in params and isinstance(params["padding_size"], torch.Tensor):
padding_size = params["padding_size"].unique(dim=0).cpu().squeeze().tolist()
+ if flags["cropping_mode"] == "resample" and isinstance(transform, torch.Tensor):
+ # Pixels are padded below; sample with the padded-canvas crop matrix.
+ offset = self._padding_offset(input, params)
+ if not (self.p == 1.0 and self.p_batch == 1.0):
+ # Only selected matrices include padding. Keep skipped rows as identity,
+ # including when a shape-changing blend returns the whole transformed image.
+ applied = torch.atleast_1d(params["batch_prob"] > 0.5).to(offset)
+ applied = applied if applied.shape[0] == transform.shape[0] else applied.any()
+ offset = offset * applied.reshape(-1, 1)
+ transform = transform.clone()
+ transform[:, :2, 2] -= (transform[:, :2, :2] @ offset[..., None]).squeeze(-1)
input = self.precrop_padding(input, padding_size, flags)
flags = self.flags if flags is None else flags
@@ -353,6 +375,11 @@ class RandomCrop(GeometricAugmentationBase2D):
raise NotImplementedError(
f"`inverse` is only applicable for resample cropping mode. Got {flags['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.
+ transform = transform.clone()
+ transform[:, :2, 2] += params["padding_size"][:, ::2].to(transform)
out = super().inverse_inputs(input, params, flags, transform, **kwargs)
if not params["batch_prob"].all():
return out
@@ -372,11 +399,7 @@ class RandomCrop(GeometricAugmentationBase2D):
raise NotImplementedError(
f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
)
- output = super().inverse_boxes(input, params, flags, transform, **kwargs)
- if not params["batch_prob"].all():
- return output
-
- return output.unpad(params["padding_size"])
+ return super().inverse_boxes(input, params, flags, transform, **kwargs)
def inverse_keypoints(
self,
@@ -390,11 +413,7 @@ class RandomCrop(GeometricAugmentationBase2D):
raise NotImplementedError(
f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
)
- output = super().inverse_keypoints(input, params, flags, transform, **kwargs)
- if not params["batch_prob"].all():
- return output
-
- return output.unpad(params["padding_size"].to(device=input.device))
+ 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]:
diff --git a/kornia/augmentation/_3d/geometric/base.py b/kornia/augmentation/_3d/geometric/base.py
index 4cdcd05d7..b882f02d2 100644
--- a/kornia/augmentation/_3d/geometric/base.py
+++ b/kornia/augmentation/_3d/geometric/base.py
@@ -34,10 +34,8 @@ class GeometricAugmentationBase3D(RigidAffineAugmentationBase3D):
Convention:
- subclasses record a source-to-destination ``(B, 4, 4)`` voxel-coordinate matrix. Coordinates are
- ordered ``(x, y, z)``, while volume tensor axes are ``(D, H, W)``. For :class:`RandomCrop3D`
- (`#4801 <https://github.com/kornia/kornia/issues/4801>`_), the source
- frame is the padded volume: the matrix omits the translation introduced by pre-crop padding.
- Resampling follows the matrix in that source frame at ``align_corners=True``; at
+ ordered ``(x, y, z)``, while volume tensor axes are ``(D, H, W)``. The source frame is the original
+ input, including for crops with pre-padding. Resampling follows the matrix at ``align_corners=True``; at
``align_corners=False`` normalization can make the applied warp differ from the recorded matrix
(`#4503 <https://github.com/kornia/kornia/issues/4503>`_).
Matrices use the input dtype, so integer voxel translations are rounded when that dtype cannot represent
diff --git a/kornia/augmentation/_3d/geometric/crop.py b/kornia/augmentation/_3d/geometric/crop.py
index 28af97926..008e78d91 100644
--- a/kornia/augmentation/_3d/geometric/crop.py
+++ b/kornia/augmentation/_3d/geometric/crop.py
@@ -81,11 +81,8 @@ class RandomCrop3D(GeometricAugmentationBase3D):
- ``size`` and the output shape are ordered ``(D, H, W)``. A scalar ``padding`` expands to every side;
three values expand as ``(left/right, top/bottom, front/back)``, and six are passed to
:func:`torch.nn.functional.pad` as ``(left, right, top, bottom, front, back)`` before the crop is drawn.
- - ``transform_matrix`` maps the padded volume to the crop, not the original input to the crop
- (`#4801 <https://github.com/kornia/kornia/issues/4801>`_). Add the left, top, and front padding to an
- original ``(x, y, z)`` point before applying this matrix: padding a ``3 x 3 x 3`` input by ``1`` and
- cropping the full ``5 x 5 x 5`` volume records an identity matrix although voxel ``(1, 1, 1)`` moves to
- ``(2, 2, 2)``.
+ - ``transform_matrix`` maps original input ``(x, y, z)`` coordinates to the crop, including the
+ left, top, and front translation from explicit padding and ``pad_if_needed``.
- its ``p`` is a call-wide gate. Size validation uses the padded input even when the call is skipped: a
crop larger than the padded volume along any axis, even by one voxel, raises; a crop equal to it is
valid. The exception types differ from :class:`CenterCrop3D`'s, and an ``int`` ``size`` is rejected
@@ -182,6 +179,10 @@ class RandomCrop3D(GeometricAugmentationBase3D):
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
transform = _crop_translation3d(params["src"].to(input), params["dst"].to(input))
+ for padding in self._compute_padding(tuple(input.shape), flags):
+ transform[:, 0, 3] += padding[0]
+ transform[:, 1, 3] += padding[2]
+ transform[:, 2, 3] += padding[4]
return transform.expand(input.shape[0], -1, -1)
def apply_transform(
@@ -194,6 +195,12 @@ class RandomCrop3D(GeometricAugmentationBase3D):
if not isinstance(transform, torch.Tensor):
raise TypeError(f"Expected the transform to be a torch.Tensor. Gotcha {type(transform)}")
+ # Resampling starts from the padded volume; the public matrix starts from the original input.
+ transform = transform.clone()
+ for padding in self._compute_padding(tuple(input.shape), flags):
+ transform[:, :3, 3] -= (
+ transform[:, :3, 0] * padding[0] + transform[:, :3, 1] * padding[2] + transform[:, :3, 2] * padding[4]
+ )
input = self.precrop_padding(input, flags)
return crop_by_transform_mat3d(
input, transform, flags["size"], mode=flags["resample"].name.lower(), align_corners=flags["align_corners"]
diff --git a/kornia/contrib/augmentation_audit.py b/kornia/contrib/augmentation_audit.py
index bd729d426..18c538c57 100644
--- a/kornia/contrib/augmentation_audit.py
+++ b/kornia/contrib/augmentation_audit.py
@@ -259,13 +259,15 @@ def _crop_matrix(
# The shape-changing blend returns every transformed row, but slice uses
# src indices even where the cached per-row matrix is the identity.
return None, "mixed-application slice crop has no reliable per-row image matrix after changing shape"
- if static or changed_shape:
- # These paths return the entire transformed branch, including prepadding.
- applied = torch.ones_like(applied)
+ if static or not changed_shape:
+ return matrix, None
+ # Selected matrices already map original coordinates, including padding.
+ # A shape-changing resample still returns padded pixels for skipped rows whose
+ # public matrix is identity. Only those rows need the image-only correction.
padding = params["padding_size"].to(matrix)
translation = torch.eye(3, device=matrix.device, dtype=matrix.dtype).expand_as(matrix).clone()
- translation[:, 0, 2] = padding[:, 0] * applied.to(matrix)
- translation[:, 1, 2] = padding[:, 2] * applied.to(matrix)
+ translation[:, 0, 2] = padding[:, 0] * (~applied).to(matrix)
+ translation[:, 1, 2] = padding[:, 2] * (~applied).to(matrix)
return matrix @ translation, None
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 54c10d099..7f64686bc 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -441,12 +441,6 @@ class Boxes:
supported; the unbatched form carries a single image, so ``padding_size``
must have exactly one row.
- Note:
- Padded :class:`~kornia.augmentation.RandomCrop` routes bounding boxes
- through this method, and so accepts either container: a rank-3
- :math:`(B, N, 4)` ``bbox`` builds a batched one, and a rank-2
- :math:`(N, 4)` ``bbox`` for a single image builds an unbatched one.
-
Args:
padding_size: Per-batch padding in ``(left, right, top, bottom)``
order, shaped :math:`(B, 4)`. A single row broadcasts across the
diff --git a/tests/augmentation/_3d/test_random_crop_3d.py b/tests/augmentation/_3d/test_random_crop_3d.py
index af64bfb95..d6c530c79 100644
--- a/tests/augmentation/_3d/test_random_crop_3d.py
+++ b/tests/augmentation/_3d/test_random_crop_3d.py
@@ -300,3 +300,42 @@ class TestRandomCrop3D(BaseTester):
RandomCrop3D((4, 4, 4), padding=1, fill=(1.0, 0.0, 0.0), padding_mode="replicate", p=1.0).precrop_padding(
volume
)
+
+
+class TestRandomCrop3DPaddingMatrix(BaseTester):
+ @pytest.mark.parametrize("same_on_batch", [False, True])
+ @pytest.mark.parametrize(
+ "padding,automatic,size",
+ [
+ (None, False, (4, 5, 6)),
+ ((1, 2, 2, 1, 3, 1), False, (7, 7, 8)),
+ (None, True, (6, 7, 8)),
+ ((1, 0, 2, 0, 0, 1), True, (7, 9, 9)),
+ ],
+ )
+ def test_original_voxel_coordinates_and_replay_4801(self, same_on_batch, padding, automatic, size, device, dtype):
+ torch.manual_seed(4)
+ volume = torch.zeros(2, 1, 5, 6, 7, device=device, dtype=dtype)
+ volume[..., 2, 3, 3] = 1
+ aug = RandomCrop3D(
+ size,
+ padding=padding,
+ pad_if_needed=automatic,
+ same_on_batch=same_on_batch,
+ resample="nearest",
+ p=1.0,
+ )
+ output = aug(volume)
+ matrix = aug.transform_matrix.clone()
+ mapped = (matrix @ volume.new_tensor([3, 3, 2, 1]))[:, :3]
+ for row in range(2):
+ indices = (output[row, 0] == 1).nonzero()
+ assert indices.shape == (1, 3)
+ self.assert_close(mapped[row], indices[0].flip(0).to(volume), rtol=0, atol=0)
+ if same_on_batch:
+ self.assert_close(matrix[0], matrix[1], rtol=0, atol=0)
+ self.assert_close(aug(volume, params=aug._params), output, rtol=0, atol=0)
+ self.assert_close(aug.transform_matrix, matrix, rtol=0, atol=0)
+ skipped = RandomCrop3D(size, padding=padding, pad_if_needed=automatic, p=0.0)
+ self.assert_close(skipped(volume), volume, rtol=0, atol=0)
+ self.assert_close(skipped.transform_matrix, torch.eye(4, device=device, dtype=dtype).expand(2, -1, -1))
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index aa2c71567..b872d86c7 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -212,8 +212,8 @@ class TestAugmentationSequential:
@pytest.mark.parametrize("num_boxes", [1, 2])
def test_convention_padded_random_crop_accepts_rank2_bboxes_4244(self, num_boxes, device, dtype):
- # kornia#4244: RandomCrop's padded path routes bounding boxes through Boxes.pad and
- # Boxes.unpad. A rank-2 (N, 4) bbox for a single image builds an *unbatched* Boxes
+ # kornia#4244: RandomCrop's padded path routed bounding boxes through Boxes.pad and
+ # Boxes.unpad until #4801. A rank-2 (N, 4) bbox for a single image builds an *unbatched* Boxes
# container, which those methods crashed on with "output with shape [1, 4] doesn't match
# the broadcast shape [1, 1, 4]". This is the reproducer from the issue's follow-up, and it
# is the only public route to that container: a rank-3 (B, N, 4) bbox builds a batched one,
diff --git a/tests/augmentation/container/test_random_crop.py b/tests/augmentation/container/test_random_crop.py
index 27a980a14..2d5bd35f3 100644
--- a/tests/augmentation/container/test_random_crop.py
+++ b/tests/augmentation/container/test_random_crop.py
@@ -283,3 +283,90 @@ class TestRandomCropAnnotations(BaseTester):
for actual, expected in zip(output, inputs):
self.assert_close(actual, expected, rtol=0, atol=0)
+
+
+class TestRandomCropPaddingMatrix(BaseTester):
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ @pytest.mark.parametrize("size", [(4, 8), (6, 10)])
+ def test_dynamo_mixed_padding_4801(self, device, dtype, torch_optimizer, size):
+ image = torch.zeros(2, 1, 6, 10, device=device, dtype=dtype)
+ image[:, 0, 1, 3] = 1
+ crop = K.RandomCrop(size, padding=(1, 2), p=0.5, cropping_mode="resample", resample="nearest")
+ params = crop.forward_parameters(image.shape)
+ params["batch_prob"] = image.new_tensor([0, 1])
+ params["src"] = (
+ image.new_tensor([[[1, 1], [size[1], 1], [size[1], size[0]], [1, size[0]]]]).expand(2, -1, -1).clone()
+ )
+ output = torch_optimizer(crop)(image, params=params)
+ padded = torch.nn.functional.pad(image, (1, 1, 2, 2))
+ expected = padded[..., 1 : size[0] + 1, 1 : size[1] + 1].clone()
+ expected[0] = image[0] if size == image.shape[-2:] else padded[0, :, : size[0], : size[1]]
+ self.assert_close(output, expected, rtol=0, atol=0)
+ matrix = image.new_tensor([[[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[1, 0, 0], [0, 1, 1], [0, 0, 1]]])
+ self.assert_close(crop.transform_matrix, matrix, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("mode", ["slice", "resample"])
+ @pytest.mark.parametrize("same_on_batch", [False, True])
+ @pytest.mark.parametrize(
+ "padding,automatic,size",
+ [(None, False, (4, 6)), ((2, 1, 3, 2), False, (6, 9)), (None, True, (6, 9)), ((3, 0, 1, 2), True, (6, 9))],
+ )
+ def test_original_coordinates_match_pixels_and_annotations_4801(
+ self, mode, same_on_batch, padding, automatic, size, device, dtype
+ ):
+ torch.manual_seed(4)
+ image = torch.zeros(2, 1, 5, 7, device=device, dtype=dtype)
+ image[..., 2, 3] = 1
+ points = image.new_tensor([[[3, 2]]]).expand(2, -1, -1).clone()
+ boxes = image.new_tensor([[[[2, 1], [3, 1], [3, 2], [2, 2]]]]).expand(2, -1, -1, -1).clone()
+ crop = K.RandomCrop(
+ size,
+ padding=padding,
+ pad_if_needed=automatic,
+ cropping_mode=mode,
+ same_on_batch=same_on_batch,
+ resample="nearest",
+ p=1.0,
+ )
+ seq = K.AugmentationSequential(crop, K.RandomHorizontalFlip(p=1.0), data_keys=["input", "keypoints", "bbox"])
+ output, out_points, out_boxes = seq(image, points, boxes)
+ matrix = seq.transform_matrix.clone()
+ params = deepcopy(seq._params)
+ homogeneous = torch.cat([points, torch.ones_like(points[..., :1])], -1)
+ mapped = (homogeneous @ matrix.transpose(-1, -2))[..., :2]
+ self.assert_close(out_points, mapped)
+ box_homogeneous = torch.cat([boxes[:, 0], torch.ones_like(boxes[:, 0, :, :1])], -1)
+ mapped_boxes = (box_homogeneous @ matrix.transpose(-1, -2))[..., :2]
+ # Tensor-form boxes reorder corners after a flip; compare their coordinate bounds.
+ self.assert_close(out_boxes[:, 0].amin(1), mapped_boxes.amin(1))
+ self.assert_close(out_boxes[:, 0].amax(1), mapped_boxes.amax(1))
+ for row in range(2):
+ y, x = divmod(output[row, 0].argmax().item(), size[1])
+ self.assert_close(mapped[row, 0], image.new_tensor([x, y]), rtol=0, atol=0)
+ assert output[row, 0, y, x] == 1
+ if same_on_batch:
+ self.assert_close(crop.transform_matrix[0], crop.transform_matrix[1], rtol=0, atol=0)
+ replay = seq(image, points, boxes, params=params)
+ for actual, expected in zip(replay, (output, out_points, out_boxes)):
+ self.assert_close(actual, expected, rtol=0, atol=0)
+ self.assert_close(seq.transform_matrix, matrix, rtol=0, atol=0)
+ if mode == "resample":
+ restored, restored_points, restored_boxes = seq.inverse(*replay, params=params)
+ assert restored.shape == image.shape
+ self.assert_close(restored_points, points)
+ self.assert_close(restored_boxes, boxes)
+ self.assert_close(restored[..., 2, 3], image[..., 2, 3])
+
+ @pytest.mark.parametrize("resample", ["bilinear", "nearest"])
+ def test_full_padded_image_inverse_4801(self, device, dtype, resample):
+ image = torch.arange(20, device=device, dtype=dtype).reshape(1, 1, 4, 5) / 20
+ crop = K.RandomCrop((9, 10), padding=(2, 1, 3, 4), cropping_mode="resample", resample=resample, p=1.0)
+ output = crop(image)
+ if resample == "nearest":
+ self.assert_close(crop.inverse(output), image, rtol=0, atol=0)
+ else:
+ # Float16 normalized grids lose subpixel precision even for the upstream
+ # identity warp. Budget one epsilon over the padded extent; keep the
+ # default tolerances for other dtypes and the exact nearest control above.
+ atol = torch.finfo(dtype).eps * max(output.shape[-2:]) if dtype == torch.float16 else None
+ self.assert_close(crop.inverse(output), image, rtol=0 if atol is not None else None, atol=atol)
diff --git a/tests/augmentation/test_conventions_3d.py b/tests/augmentation/test_conventions_3d.py
index 5f6859f1e..f71594e56 100644
--- a/tests/augmentation/test_conventions_3d.py
+++ b/tests/augmentation/test_conventions_3d.py
@@ -418,8 +418,8 @@ class Test3DAugmentationConventions(BaseTester):
"padding,size,marker",
[(1, (5, 5, 5), (2, 2, 2)), ((1, 2, 3), (9, 7, 5), (4, 3, 2))],
)
- def test_wart_random_crop3d_matrix_uses_the_padded_source_frame_4801(self, padding, size, marker, device, dtype):
- # #4801: flips when the recorded matrix includes the padding offset.
+ def test_convention_random_crop3d_matrix_maps_original_coordinates_4801(self, padding, size, marker, device, dtype):
+ # #4801: the recorded matrix includes the left, top, and front padding.
if not supports_nearest_3d_grid_sample(device, dtype):
pytest.skip("nearest 3D grid_sample is unavailable for this device and dtype")
volume = torch.zeros(1, 1, 3, 3, 3, device=device, dtype=dtype)
@@ -430,8 +430,8 @@ class Test3DAugmentationConventions(BaseTester):
expected = torch.zeros_like(output)
expected[..., marker[0], marker[1], marker[2]] = 1
self.assert_close(output, expected)
- # Taking the whole padded canvas records identity, despite moving the original marker by the padding.
- self.assert_close(augmentation.transform_matrix, torch.eye(4, device=device, dtype=dtype)[None])
+ mapped = augmentation.transform_matrix[0] @ volume.new_tensor([1, 1, 1, 1])
+ self.assert_close(mapped[:3], volume.new_tensor(marker[::-1]), rtol=0, atol=0)
@pytest.mark.device_agnostic
def test_convention_motion_blur3d_kernel_range_is_drawn_once_per_call_bounds_included(self):
diff --git a/tests/augmentation/test_conventions_geometric_crop.py b/tests/augmentation/test_conventions_geometric_crop.py
index 351d66153..af362711d 100644
--- a/tests/augmentation/test_conventions_geometric_crop.py
+++ b/tests/augmentation/test_conventions_geometric_crop.py
@@ -146,8 +146,8 @@ class TestGeometricCropConventions(BaseTester):
points = image.new_tensor([[[2, 2]]])
boxes = image.new_tensor([[[[1, 1], [2, 1], [2, 2], [1, 2]]]])
output, out_points, out_boxes = seq(image, points, boxes, params=params)
- # The matrix starts from the padded canvas (#4801); the keypoint and box handlers add the padding.
- self.assert_close(crop.transform_matrix, image.new_tensor([[[1, 0, 0], [0, 1, 0], [0, 0, 1]]]))
+ # The matrix includes padding and applies directly to original coordinates (#4801).
+ self.assert_close(crop.transform_matrix, image.new_tensor([[[1, 0, 1], [0, 1, 1], [0, 0, 1]]]))
self.assert_close(out_points, image.new_tensor([[[3, 3]]]))
self.assert_close(out_boxes, boxes + 1)
expected = [[0, 0, 0, 0], [0, 0, 1, 2], [0, 3, 4, 5], [0, 6, 7, 8]]
@@ -165,7 +165,7 @@ class TestGeometricCropConventions(BaseTester):
boxes = image.new_tensor([[[[1, 1], [2, 1], [2, 2], [1, 2]]]])
output, out_points, out_boxes = seq(image, points, boxes, params=params)
expected = image.new_tensor([[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 3, 4], [0, 0, 6, 7]]).reshape(1, 1, 4, 4) / 8
- self.assert_close(crop.transform_matrix, image.new_tensor([[[1, 0, 0], [0, 1, 0], [0, 0, 1]]]))
+ self.assert_close(crop.transform_matrix, image.new_tensor([[[1, 0, 2], [0, 1, 1], [0, 0, 1]]]))
self.assert_close(output, expected)
self.assert_close(out_points, image.new_tensor([[[4, 3]]]))
self.assert_close(out_boxes, boxes + image.new_tensor([2, 1]))
@@ -191,19 +191,24 @@ class TestGeometricCropConventions(BaseTester):
params["src"] = image.new_tensor([[[0, 0], [3, 0], [3, 3], [0, 3]]])
crop.flags["padding"] = 0
output = crop(image, params=params)
- self.assert_close(crop.transform_matrix, image.new_tensor([[[1, 0, 0], [0, 1, 0], [0, 0, 1]]]))
+ self.assert_close(crop.transform_matrix, image.new_tensor([[[1, 0, 1], [0, 1, 1], [0, 0, 1]]]))
expected = image.new_tensor([[[[0, 0, 0, 0], [0, 0, 1, 2], [0, 3, 4, 5], [0, 6, 7, 8]]]]) / 8
self.assert_close(output, expected)
+ @pytest.mark.parametrize("override", [{}, {"padding": 0}, {"padding": 2}])
@pytest.mark.parametrize("mode", ["slice", "resample"])
- def test_random_crop_explicit_padding_recomputes_static_canvas_without_saved_padding(self, device, dtype, mode):
+ def test_random_crop_explicit_padding_recomputes_static_canvas_without_saved_padding(
+ self, device, dtype, mode, override
+ ):
image = torch.arange(9, device=device, dtype=dtype).reshape(1, 1, 3, 3) / 8
crop = K.RandomCrop((4, 4), padding=1, cropping_mode=mode, p=1.0)
params = crop.forward_parameters(image.shape)
params["src"] = image.new_tensor([[[0, 0], [3, 0], [3, 3], [0, 3]]])
params.pop("padding_size")
- output = crop(image, params=params)
- self.assert_close(crop.transform_matrix, image.new_tensor([[[1, 0, 0], [0, 1, 0], [0, 0, 1]]]))
+ # The canvas is recomputed from the module's own padding; the matrix must follow the pixels even when the
+ # call overrides the padding flag (#4801).
+ output = crop(image, params=params, **override)
+ self.assert_close(crop.transform_matrix, image.new_tensor([[[1, 0, 1], [0, 1, 1], [0, 0, 1]]]))
expected = image.new_tensor([[[[0, 0, 0, 0], [0, 0, 1, 2], [0, 3, 4, 5], [0, 6, 7, 8]]]]) / 8
self.assert_close(output, expected)
@@ -352,8 +357,8 @@ class TestGeometricCropConventions(BaseTester):
K.RandomResizedCrop(4) # type: ignore[arg-type]
@pytest.mark.parametrize("mode", ["slice", "resample"])
- def test_wart_random_crop_matrix_starts_from_the_padded_canvas_4801(self, device, dtype, mode):
- # #4801: flips when the recorded matrix includes the padding offset and maps (2, 1) to (3, 2).
+ def test_convention_random_crop_matrix_maps_original_coordinates_4801(self, device, dtype, mode):
+ # #4801: the recorded matrix and the pixel both map (2, 1) to (3, 2).
image = torch.zeros(1, 1, 3, 4, device=device, dtype=dtype)
image[0, 0, 1, 2] = 1 # pixel (x=2, y=1); cropping the whole padded canvas has one placement
seq = K.AugmentationSequential(
@@ -362,11 +367,12 @@ class TestGeometricCropConventions(BaseTester):
output, points = seq(image, image.new_tensor([[[2.0, 1.0]]]))
assert output[0, 0].argmax().item() == 2 * 6 + 3
self.assert_close(points, image.new_tensor([[[3.0, 2.0]]]))
- self.assert_close(seq.transform_matrix, torch.eye(3, device=device, dtype=dtype)[None])
+ mapped = seq.transform_matrix[0] @ image.new_tensor([2.0, 1.0, 1.0])
+ self.assert_close(mapped[:2], points[0, 0], rtol=0, atol=0)
@pytest.mark.parametrize("mode", ["slice", "resample"])
- def test_wart_random_crop_pad_if_needed_matrix_omits_the_padding_4801(self, device, dtype, mode):
- # #4801: flips when the matrix includes the `pad_if_needed` offset, (2, 1) for a 6 x 9 crop of 5 x 7.
+ def test_convention_random_crop_pad_if_needed_matrix_includes_padding_4801(self, device, dtype, mode):
+ # #4801: automatic padding belongs in the original-input-to-output matrix.
image = torch.zeros(1, 1, 5, 7, device=device, dtype=dtype)
image[0, 0, 2, 1] = 1 # pixel (x=1, y=2)
torch.manual_seed(0)
@@ -377,7 +383,7 @@ class TestGeometricCropConventions(BaseTester):
row, col = divmod(output[0, 0].argmax().item(), 9)
self.assert_close(points, image.new_tensor([[[col, row]]])) # the keypoint follows the pixel
via_matrix = seq.transform_matrix[0] @ image.new_tensor([1.0, 2.0, 1.0])
- self.assert_close(points[0, 0] - via_matrix[:2], image.new_tensor([2.0, 1.0]))
+ self.assert_close(points[0, 0], via_matrix[:2], rtol=0, atol=0)
@pytest.mark.device_agnostic
def test_wart_interpolate_paths_record_a_corner_aligned_matrix_4804(self):
diff --git a/tests/contrib/test_augmentation_audit.py b/tests/contrib/test_augmentation_audit.py
index 6c6c35b62..6c211e64a 100644
--- a/tests/contrib/test_augmentation_audit.py
+++ b/tests/contrib/test_augmentation_audit.py
@@ -554,6 +554,7 @@ class TestAugmentationAudit(BaseTester):
[
((4, 8), None, False),
((4, 8), (1, 2), False),
+ ((4, 8), (1, 2, 3, 0), False),
((6, 10), (1, 2, 3, 0), False),
((8, 12), None, True),
],
@@ -581,8 +582,16 @@ class TestAugmentationAudit(BaseTester):
)
aug = K.AugmentationSequential(module, data_keys=["input", "keypoints", "bbox"])
outputs, report = audit(aug, image, points, boxes, params=[ParamItem("RandomCrop_0", params)])
- selected = params["batch_prob"] > 0.5
+ selected = (params["batch_prob"] > 0.5).to(device=image.device)
static = p == 1.0
+ # Public matrices include padding; the dynamic gate leaves skipped rows as identity.
+ public_shift = image.new_tensor([pad[0] - x, pad[2] - y]).expand(2, -1)
+ public_shift = torch.where((selected | static)[:, None], public_shift, 0)
+ self.assert_close(module.transform_matrix[:, :2, 2], public_shift)
+ # An explicitly overridden batch_prob still gates labels even for static p=1.
+ label_shift = torch.where(selected[:, None], public_shift, 0)
+ self.assert_close(outputs[1], points + label_shift[:, None])
+ self.assert_close(outputs[2].data, boxes.data + label_shift[:, None, None])
all_transformed = static or (size != image.shape[-2:] and bool(selected.any()))
transformed = torch.ones_like(selected) if all_transformed else selected
padded = torch.nn.functional.pad(image, pad)