π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): restore the input shape in PadTo.inverse after a crop (#6314)
Saksham Sharma573a102639cb
diff --git a/changelog.d/6314.fixed.md b/changelog.d/6314.fixed.mdnew file mode 100644index 000000000..8d2e1b08c--- /dev/null+++ b/changelog.d/6314.fixed.md@@ -0,0 +1 @@+`kornia.augmentation.PadTo.inverse` now restores the input shape on every axis. It used to return the cropped tensor unchanged when the target was smaller than the input, so a pipeline's `inverse` did not get back to the input size. A cropped axis is now regrown at the right/bottom with zeros, as the crop augmentations' inverses do; padding is still removed exactly.diff --git a/kornia/augmentation/_2d/geometric/pad.py b/kornia/augmentation/_2d/geometric/pad.pyindex 887aaaec0..b8b4a8f9e 100644--- a/kornia/augmentation/_2d/geometric/pad.py+++ b/kornia/augmentation/_2d/geometric/pad.py@@ -51,12 +51,12 @@ class PadTo(GeometricAugmentationBase2D):See :class:`~kornia.augmentation.GeometricAugmentationBase2D` for coordinates, defaults and inverse.This operation always runs and pads on the right and bottom, using ``pad_mode`` and ``pad_value``. With thedefault ``crop_if_exceeds=True``, a target smaller than the input crops that axis instead, so a target can pad- one axis while cropping the other (`#4410 <https://github.com/kornia/kornia/issues/4410>`_). With- ``crop_if_exceeds=False``, that axis passes through unchanged.+ one axis while cropping the other. With ``crop_if_exceeds=False``, that axis passes through unchanged.- :meth:`inverse` slices to the prior input size. It exactly removes right/bottom padding, but after a crop it- returns the cropped result unchanged rather than restoring discarded pixels. The transformation matrix is- identity, so keypoints and boxes are neither moved nor clipped when cropping puts them outside the canvas.+ :meth:`inverse` restores the prior input shape on every axis. It exactly removes right/bottom padding, and it+ regrows a cropped axis at the right/bottom with zeros, as the crop augmentations' inverses do: the discarded+ pixels cannot be recovered. The transformation matrix is identity, because every kept pixel keeps its+ coordinates, so keypoints and boxes are neither moved nor clipped when cropping puts them outside the canvas.Examples:>>> import torch@@ -75,6 +75,12 @@ class PadTo(GeometricAugmentationBase2D):[0., 0., 0.],[0., 0., 0.]]]])+ >>> crop = PadTo((2, 4))+ >>> crop.inverse(crop(torch.ones(1, 1, 3, 3)))+ tensor([[[[1., 1., 1.],+ [1., 1., 1.],+ [0., 0., 0.]]]])+>>> img_large = torch.zeros(1, 1, 4, 4)>>> PadTo((2, 2), crop_if_exceeds=False)(img_large).shapetorch.Size([1, 1, 4, 4])@@ -97,8 +103,8 @@ class PadTo(GeometricAugmentationBase2D):"crop_if_exceeds": crop_if_exceeds,}- # TODO: It is incorrect to return identity- # TODO: Having a resampled version with ``warp_affine``+ # PadTo pads and crops only at the right and bottom, so every pixel it keeps stays at the same coordinates: the+ # identity is the exact transformation for keypoints and boxes in both directions.def compute_transformation(self, image: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:return self.identity_matrix(image)@@ -125,4 +131,7 @@ class PadTo(GeometricAugmentationBase2D):) -> Tensor:if size is None:raise RuntimeError("`size` has to be a tuple. Got None.")- return input[..., : size[0], : size[1]]+ # Negative padding removes the right/bottom padding; positive padding regrows a cropped axis with zeros+ # rather than ``pad_mode``, which would invent content from the pixels that were kept.+ height, width = input.shape[-2:]+ return torch.nn.functional.pad(input, [0, size[1] - width, 0, size[0] - height], mode="constant", value=0.0)diff --git a/tests/augmentation/test_conventions_geometric_crop.py b/tests/augmentation/test_conventions_geometric_crop.pyindex 5e81173d1..b3eac688b 100644--- a/tests/augmentation/test_conventions_geometric_crop.py+++ b/tests/augmentation/test_conventions_geometric_crop.py@@ -685,9 +685,11 @@ class TestGeometricCropConventions(BaseTester):with pytest.raises(AssertionError, match="2 positive integers"):aug(torch.ones(1, 1, 1, 10))- def test_wart_pad_to_smaller_target_crops_and_inverse_is_noop_4410(self, device, dtype):- # #4410: negative right/bottom padding crops, and the identity matrix leaves inverse unable to restore it.- x = torch.arange(48, device=device, dtype=dtype).reshape(1, 1, 6, 8)+ def test_convention_pad_to_smaller_target_crops_and_inverse_regrows_4410(self, device, dtype):+ # A target smaller than the input crops at the right/bottom. Every kept pixel keeps its coordinates, so the+ # matrix is identity and keypoints and boxes are untouched. inverse restores the input shape and fills the+ # discarded region with zeros, as the crop inverses do: the cropped pixels cannot come back.+ x = torch.arange(1, 49, device=device, dtype=dtype).reshape(1, 1, 6, 8)crop = K.PadTo((4, 5), pad_value=9)seq = K.AugmentationSequential(crop, data_keys=["input", "keypoints", "bbox"])points = x.new_tensor([[[7, 5]]])@@ -696,9 +698,48 @@ class TestGeometricCropConventions(BaseTester):self.assert_close(out_points, points)self.assert_close(out_boxes, boxes)self.assert_close(output, x[..., :4, :5])- self.assert_close(crop.inverse(output), output)self.assert_close(crop.transform_matrix, torch.eye(3, device=device, dtype=dtype)[None])+ expected = torch.zeros_like(x)+ expected[..., :4, :5] = x[..., :4, :5]+ self.assert_close(crop.inverse(output), expected)+ restored, restored_points, restored_boxes = seq.inverse(output, out_points, out_boxes)+ self.assert_close(restored, expected)+ self.assert_close(restored_points, points)+ self.assert_close(restored_boxes, boxes)++ @pytest.mark.parametrize("pad_mode", ["constant", "replicate", "reflect"])+ def test_convention_pad_to_inverse_of_a_mixed_target_restores_the_shape_4410(self, pad_mode, device, dtype):+ # Crop the height and pad the width. inverse removes the padding exactly and regrows the cropped rows with+ # zeros whatever pad_mode is: replicate or reflect would invent rows from the pixels that were kept.+ x = torch.arange(1, 49, device=device, dtype=dtype).reshape(1, 1, 6, 8)+ pad = K.PadTo((4, 12), pad_mode=pad_mode)+ output = pad(x)+ assert output.shape == (1, 1, 4, 12)+ expected = torch.zeros_like(x)+ expected[..., :4, :] = x[..., :4, :]+ self.assert_close(pad.inverse(output), expected)++ @pytest.mark.device_agnostic+ @pytest.mark.parametrize("mask_dtype", [torch.bool, torch.int64, torch.float32])+ def test_convention_pad_to_mask_inverse_regrows_with_zeros_4410(self, mask_dtype, device):+ # Masks take the same path: a cropped mask inverts to the input shape, background in the regrown region.+ image = torch.rand(2, 3, 6, 8, device=device)+ mask = torch.ones(2, 1, 6, 8, device=device, dtype=mask_dtype)+ seq = K.AugmentationSequential(K.PadTo((4, 10)), data_keys=["input", "mask"])+ _, restored = seq.inverse(*seq(image, mask))+ assert restored.shape == mask.shape+ assert restored.dtype == mask_dtype+ expected = torch.zeros_like(mask)+ expected[..., :4, :] = 1+ assert torch.equal(restored, expected)++ def test_convention_pad_to_crop_if_exceeds_false_inverse_is_identity_4410(self, device, dtype):+ # With crop_if_exceeds=False nothing was cropped, so inverse returns the input unchanged.+ x = torch.arange(48, device=device, dtype=dtype).reshape(1, 1, 6, 8)+ pad = K.PadTo((4, 5), crop_if_exceeds=False)+ self.assert_close(pad.inverse(pad(x)), x)+def test_convention_pad_to_right_bottom_padding_round_trips(self, device, dtype):x = torch.arange(48, device=device, dtype=dtype).reshape(1, 1, 6, 8)pad = K.PadTo((10, 12), pad_value=9)