π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): align nearest resize matrices (#5458)
Arc000007997ee638a596
diff --git a/changelog.d/5458.breaking.md b/changelog.d/5458.breaking.mdnew file mode 100644index 000000000..25da4d95e--- /dev/null+++ b/changelog.d/5458.breaking.md@@ -0,0 +1 @@+`Resize`, `LongestMaxSize`, `SmallestMaxSize` and slice-mode `RandomResizedCrop` with `resample="nearest"` now resize with PyTorch's `nearest-exact` grid, which copies source column `floor((u + 0.5) * W_in / W_out)` into output column `u`, and record the matching half-pixel `transform_matrix`, `x' = (x + 0.5) * W_out / W_in - 0.5` (likewise for `y`). Previously they copied the legacy `floor(u * W_in / W_out)` column and recorded a corner-to-corner matrix that the image did not follow, so keypoints and boxes landed up to one output pixel away from the pixels they belong to (#5293). Nearest-resized images and the recorded matrices change. So do masks resized by these augmentations in `AugmentationSequential`, which resamples masks with nearest even when images use bilinear.diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.pyindex b59ac3662..91db3ac20 100644--- a/kornia/augmentation/_2d/geometric/resize.py+++ b/kornia/augmentation/_2d/geometric/resize.py@@ -52,7 +52,9 @@ class Resize(GeometricAugmentationBase2D):This class uses :func:`kornia.geometry.transform.resize`; ``align_corners`` is forwarded for bilinear andbicubic sampling, and ``transform_matrix`` follows the grid they sample: at ``align_corners=False`` it isthe half-pixel map ``x' = (x + 0.5) * W_out / W_in - 0.5`` (likewise for ``y``), and at ``True`` it maps- the corner pixel centres onto each other. :meth:`inverse` resamples to the prior canvas and cannot recover+ the corner pixel centres onto each other. Nearest sampling uses the half-pixel grid and PyTorch's+ ``nearest-exact`` interpolation.+ :meth:`inverse` resamples to the prior canvas and cannot recovervalues discarded by a resize."""@@ -85,7 +87,9 @@ class Resize(GeometricAugmentationBase2D):def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> torch.Tensor:- if not flags["align_corners"] and flags["resample"] in (Resample.BILINEAR, Resample.BICUBIC):+ if flags["resample"] == Resample.NEAREST or (+ not flags["align_corners"] and flags["resample"] in (Resample.BILINEAR, Resample.BICUBIC)+ ):return _half_pixel_resize_transform(params["src"].to(input), params["dst"].to(input)).expand(input.shape[0], -1, -1)@@ -124,7 +128,7 @@ class Resize(GeometricAugmentationBase2D):return resize(input,out_size,- interpolation=flags["resample"].name.lower(),+ interpolation="nearest-exact" if flags["resample"] == Resample.NEAREST else flags["resample"].name.lower(),align_corners=(flags["align_corners"] if flags["resample"] in [Resample.BILINEAR, Resample.BICUBIC] else None),@@ -144,8 +148,18 @@ class Resize(GeometricAugmentationBase2D):if not isinstance(transform, torch.Tensor):raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")+ if flags["resample"] == Resample.NEAREST:+ # ``grid_sample`` only supports legacy ``nearest``. The forward path uses+ # ``nearest-exact``, so invert a resize with the same interpolation rule.+ return resize(input, size, interpolation="nearest-exact")+return crop_by_transform_mat(- input, transform[:, :2, :], size, flags["resample"].name.lower(), "zeros", flags["align_corners"]+ input,+ transform[:, :2, :],+ size,+ flags["resample"].name.lower(),+ "zeros",+ flags["align_corners"],)diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.pyindex 42a43a4b4..a8af81e96 100644--- a/kornia/augmentation/_2d/geometric/resized_crop.py+++ b/kornia/augmentation/_2d/geometric/resized_crop.py@@ -78,8 +78,9 @@ class RandomResizedCrop(GeometricAugmentationBase2D):follows its ``transform_matrix``, and at ``align_corners=False`` the two modes give different images: slicemode resizes the crop on the half-pixel grid, ``x' = (x - x0 + 0.5) * W_out / W_crop - 0.5`` for a cropstarting at column ``x0`` (likewise for ``y``), while resample mode maps the crop's corner pixel centres- onto the output's. Only resample mode supports :meth:`inverse`, which resamples onto the original canvas- and cannot recover discarded information.+ 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.Note:Compiled slice-mode interpolation matches eager execution to floating-point tolerance,@@ -142,10 +143,9 @@ class RandomResizedCrop(GeometricAugmentationBase2D):def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> torch.Tensor:- if (- flags["cropping_mode"] == "slice"- and not flags["align_corners"]- and flags["resample"] in (Resample.BILINEAR, Resample.BICUBIC)+ if flags["cropping_mode"] == "slice" and (+ flags["resample"] == Resample.NEAREST+ or (not flags["align_corners"] and flags["resample"] in (Resample.BILINEAR, Resample.BICUBIC))):return _half_pixel_resize_transform(params["src"].to(input), params["dst"].to(input)).expand(input.shape[0], -1, -1@@ -175,9 +175,9 @@ class RandomResizedCrop(GeometricAugmentationBase2D):align_corners=flags["align_corners"],)if flags["cropping_mode"] == "slice": # uses advanced slicing to crop- mode = flags["resample"].name.lower()+ mode = "nearest-exact" if flags["resample"] == Resample.NEAREST else flags["resample"].name.lower()# ``interpolate`` rejects ``align_corners`` for nearest resampling.- align_corners = None if mode == "nearest" else flags["align_corners"]+ align_corners = None if mode in ("nearest", "nearest-exact") else flags["align_corners"]if is_compiling():return _compiled_slice_resize(input, params["src"], flags["size"], mode, align_corners)return crop_by_indices(diff --git a/kornia/geometry/transform/_crop.py b/kornia/geometry/transform/_crop.pyindex 7dcc0f2ee..b6650ad7d 100644--- a/kornia/geometry/transform/_crop.py+++ b/kornia/geometry/transform/_crop.py@@ -42,14 +42,17 @@ def _resize_coordinates() -> torch.Tensor:length = end - startpositions = torch.arange(output_size, device=start.device, dtype=start.dtype)- if mode == "nearest":+ if mode in ("nearest", "nearest-exact"):# ATen computes the scale on the host (usually float32; see the CPU-double path). CUDA/Inductor# tensor float32 division can change pixels at integer boundaries (e.g. 26 -> 22).# Build scales in CPU float64 before casting, like host scalar arithmetic. Tensor# arange keeps input_size symbolic under dynamic=True; a Python range specializes it.# No float64 GPU/MPS ops or device-to-host copies of sampled coordinates are needed.scales = (torch.arange(input_size + 1, device="cpu", dtype=torch.float64) / output_size).to(start)- return (positions * scales[length.long()]).float().floor()+ scale = scales[length.long()]+ if mode == "nearest-exact":+ return ((positions + 0.5) * scale).float().floor()+ return (positions * scale).float().floor()if align_corners:coordinates = positions * ((length - 1) / (output_size - 1) if output_size > 1 else length * 0.0)else:@@ -130,7 +133,7 @@ def _compiled_slice_resize(indices = (y_index.unsqueeze(-1) * width + x_index.unsqueeze(-2)).reshape(batch, 1, -1)return flat.gather(2, indices.expand(-1, channels, -1)).reshape(batch, channels, *size)- if mode == "nearest":+ if mode in ("nearest", "nearest-exact"):return gather(x, y).to(input.dtype)def preserve_slice(result: torch.Tensor, slice_values: torch.Tensor) -> torch.Tensor:diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex 863c582e8..2329c4f28 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -616,8 +616,8 @@ def resize(output size will be matched to this. If size is an int, smaller edge of the image willbe matched to this number. i.e, if height > width, then image will be rescaledto (size * height / width, size)- interpolation: algorithm used for upsampling: ``'nearest'`` | ``'linear'`` | ``'bilinear'`` |- 'bicubic' | 'trilinear' | 'area'.+ interpolation: algorithm used for upsampling: ``'nearest'`` | ``'nearest-exact'`` | ``'linear'`` |+ ``'bilinear'`` | 'bicubic' | 'trilinear' | 'area'.align_corners: interpolation flag.side: Corresponding side if ``size`` is an integer. Can be one of ``'short'``, ``'long'``, ``'vert'``,or ``'horz'``.@@ -691,7 +691,15 @@ def resize(input = gaussian_blur2d(input, ks, sigmas)- output = torch.nn.functional.interpolate(input, size=size, mode=interpolation, align_corners=align_corners)+ if interpolation == "nearest-exact" and torch.onnx.is_in_onnx_export():+ # The TorchScript ONNX exporter has no symbolic for ``nearest-exact``; gather the+ # half-pixel indices ``floor((i + 0.5) * in / out)`` that ``interpolate`` samples.+ for dim, (in_size, out_size) in zip((-2, -1), ((h, size[0]), (w, size[1]))):+ index = ((torch.arange(out_size, device=input.device) + 0.5) * (in_size / out_size)).floor()+ input = input.index_select(dim, index.long().clamp(max=in_size - 1))+ output = input+ else:+ output = torch.nn.functional.interpolate(input, size=size, mode=interpolation, align_corners=align_corners)if len(original_shape) == 2:output = output[0, 0]diff --git a/tests/augmentation/test_conventions_geometric_matrix.py b/tests/augmentation/test_conventions_geometric_matrix.pyindex 014a1678b..f7eb962e1 100644--- a/tests/augmentation/test_conventions_geometric_matrix.py+++ b/tests/augmentation/test_conventions_geometric_matrix.py@@ -27,6 +27,68 @@ from testing.base import BaseTesterclass TestConventionGeometricMatrices(BaseTester):+ def test_nearest_resize_uses_nearest_exact_and_half_pixel_matrix(self):+ image = torch.arange(49, dtype=torch.float64).view(1, 1, 7, 7)+ augmentation = K.Resize((14, 21), resample="nearest")++ output = augmentation(image)+ expected = torch.nn.functional.interpolate(image, size=(14, 21), mode="nearest-exact")+ self.assert_close(output, expected)+ self.assert_close(+ augmentation.transform_matrix,+ image.new_tensor([[[3.0, 0.0, 1.0], [0.0, 2.0, 0.5], [0.0, 0.0, 1.0]]]),+ )++ @pytest.mark.parametrize("input_size,output_size", [((7, 7), (21, 21)), ((12, 12), (9, 9)), ((5, 5), (8, 8))])+ def test_nearest_resize_inverse_roundtrip(self, input_size, output_size):+ image = torch.arange(input_size[0] * input_size[1], dtype=torch.float32).view(1, 1, *input_size)+ augmentation = K.AugmentationSequential(K.Resize(output_size, resample="nearest"))+ restored = augmentation.inverse(augmentation(image))+ assert restored.shape == image.shape+ # Nearest downsampling is lossy, but inverse resampling must still cover both image edges.+ self.assert_close(restored[..., 0, 0], image[..., 0, 0])+ self.assert_close(restored[..., -1, -1], image[..., -1, -1])++ @pytest.mark.parametrize(+ "augmentation", [K.LongestMaxSize(21, resample="nearest"), K.SmallestMaxSize(9, resample="nearest")]+ )+ def test_nearest_max_size_matches_nearest_exact(self, augmentation):+ image = torch.arange(35, dtype=torch.float64).view(1, 1, 5, 7)+ output = augmentation(image)+ expected = torch.nn.functional.interpolate(image, size=output.shape[-2:], mode="nearest-exact")+ self.assert_close(output, expected)++ @pytest.mark.parametrize("align_corners", [False, True])+ def test_nearest_slice_resized_crop_uses_nearest_exact(self, align_corners):+ image = torch.arange(11, dtype=torch.float64).view(1, 1, 1, 11).expand(1, 1, 5, -1)+ augmentation = K.RandomResizedCrop(+ (6, 21), resample="nearest", align_corners=align_corners, cropping_mode="slice"+ )+ params = augmentation.forward_parameters(image.shape)+ params["src"] = image.new_tensor([[[2, 1], [8, 1], [8, 3], [2, 3]]])++ output = augmentation(image, params=params)+ expected = torch.nn.functional.interpolate(image[..., 1:4, 2:9], size=(6, 21), mode="nearest-exact")+ self.assert_close(output, expected)+ self.assert_close(+ augmentation.transform_matrix,+ image.new_tensor([[[3.0, 0.0, -5.0], [0.0, 2.0, -1.5], [0.0, 0.0, 1.0]]]),+ )++ @pytest.mark.parametrize(+ "augmentation,output_size",+ [+ (K.Resize((6, 9), resample="nearest"), (6, 9)),+ (K.LongestMaxSize(9, resample="nearest"), (7, 9)),+ (K.SmallestMaxSize(6, resample="nearest"), (6, 7)),+ ],+ )+ def test_nearest_resize_handles_empty_batch(self, augmentation, output_size):+ image = torch.empty(0, 1, 4, 5)+ output = augmentation(image)+ assert output.shape == (0, 1, *output_size)+ assert augmentation.transform_matrix.shape == (0, 3, 3)+def test_convention_flips_use_inclusive_pixel_coordinates(self, device, dtype):x = torch.zeros(1, 1, 5, 7, device=device, dtype=dtype)x[..., 1, 2] = 1diff --git a/tests/augmentation/test_onnx_export.py b/tests/augmentation/test_onnx_export.pyindex 429016f3a..846537301 100644--- a/tests/augmentation/test_onnx_export.py+++ b/tests/augmentation/test_onnx_export.py@@ -356,3 +356,14 @@ def test_onnx_export_numerically_matches_eager(name: str, factory: Callable[[],assert eager.shape == onnx_out.shape, f"{name}: shape mismatch {eager.shape} vs {onnx_out.shape}"max_diff = float(np.abs(eager - onnx_out).max())assert max_diff < 1e-3, f"{name}: max abs diff {max_diff:.4f} exceeds 1e-3"++[email protected]("size", [(9, 21), (5, 7)])[email protected]_agnostic+def test_onnx_nearest_resize_exports_through_the_legacy_tracer(size: Tuple[int, int]) -> None:+ """Nearest ``Resize`` samples ``nearest-exact``, which the legacy tracer cannot lower; export gathers instead."""+ image = torch.arange(3 * 7 * 12, dtype=torch.float32).reshape(1, 3, 7, 12)+ aug = K.Resize(size, resample="nearest").eval()+ eager = aug(image).numpy()+ onnx_out = _run_onnx(aug, image)+ assert np.array_equal(onnx_out, eager)diff --git a/tests/augmentation/test_resize_matrix.py b/tests/augmentation/test_resize_matrix.pyindex 5be142c0a..ad670fadb 100644--- a/tests/augmentation/test_resize_matrix.py+++ b/tests/augmentation/test_resize_matrix.py@@ -154,7 +154,7 @@ class TestResizeMatrix(BaseTester):self.assert_close(output, sliced)@pytest.mark.parametrize("kind", ["resize", "crop"])- @pytest.mark.parametrize("resample,align_corners", [("bilinear", True), ("nearest", True), ("nearest", False)])+ @pytest.mark.parametrize("resample,align_corners", [("bilinear", True)])def test_unchanged_matrix_paths(self, device, dtype, kind, resample, align_corners):image = self._ramp(5, 7, device, dtype)aug = self._augmentation(kind, (8, 11), align_corners, device, dtype)diff --git a/tests/geometry/transform/test_crop2d.py b/tests/geometry/transform/test_crop2d.pyindex d6b95232c..a559166ea 100644--- a/tests/geometry/transform/test_crop2d.py+++ b/tests/geometry/transform/test_crop2d.py@@ -859,3 +859,22 @@ class TestCropSizeValidation:inp = torch.rand(1, 1, 4, 4, device=device, dtype=dtype)with pytest.raises(ValueError, match="tuple/list of length 2"):kornia.geometry.transform.center_crop(inp, (2, 2, 2))+++class TestSliceResizeFullgraphPathEager(BaseTester):+ """The fullgraph slice-resize path, run eagerly against ``crop_by_indices`` in float64."""++ @pytest.mark.parametrize(+ "mode,align_corners", [("bilinear", False), ("bilinear", True), ("bicubic", False), ("nearest-exact", None)]+ )+ def test_float64_coordinates_match_crop_by_indices(self, mode, align_corners):+ # Every mode but legacy nearest samples float64 coordinates for float64 images; float32 ones are ~1e-6 off.+ from kornia.geometry.transform._crop import _compiled_slice_resize++ image = torch.linspace(0, 40, 2 * 3 * 23 * 31, dtype=torch.float64).sin().reshape(2, 3, 23, 31)+ src = torch.tensor([[[2, 1], [20, 1], [20, 17], [2, 17]], [[0, 3], [28, 3], [28, 20], [0, 20]]])+ expected = kornia.geometry.transform.crop_by_indices(+ image, src, (13, 29), interpolation=mode, align_corners=align_corners+ )+ actual = _compiled_slice_resize(image, src, (13, 29), mode, align_corners)+ self.assert_close(actual, expected, rtol=1e-12, atol=1e-12)