Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): align resize matrices with half-pixel sampling (#5179)

Puttala Jeevan Kumar20e850998cee
diff --git a/changelog.d/5179.breaking.md b/changelog.d/5179.breaking.md
new file mode 100644
index 000000000..3bc1fad58
--- /dev/null
+++ b/changelog.d/5179.breaking.md
@@ -0,0 +1 @@
+`Resize`, `LongestMaxSize`, `SmallestMaxSize` and slice-mode `RandomResizedCrop` with `align_corners=False` and bilinear or bicubic resampling now record the half-pixel map their resize samples with, `x' = (x - x0 + 0.5) * W_out / W_crop - 0.5` and likewise for `y`, as `transform_matrix`, where `x0` and `W_crop` are the crop's first column and width (`0` and the input width for the resize classes). They used to record the corner-to-corner map `x' = (x - x0) * (W_out - 1) / (W_crop - 1)`, so keypoints and boxes moved through `AugmentationSequential` landed up to `|W_out / W_crop - 1| / 2` output pixels from the content they annotate (half a pixel at a 2x upscale), and the `inverse()` of the three resize classes warped the image back with that map, which did not return content to its original place. The resized images, `align_corners=True` (the default for these classes), nearest resampling and resample-mode crops are unchanged.
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index ed2c81bd1..11a592788 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -44,10 +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. 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>`_).
+ coordinates.
- the resampling classes, including the non-rigid :class:`RandomElasticTransform` and
:class:`RandomThinPlateSpline`, default to bilinear interpolation with zero sampler padding. The
``align_corners`` default is ``True`` for :class:`RandomRotation`, :class:`RandomRotation90` and the crop
diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.py
index 2402dcbb8..8cbaf6993 100644
--- a/kornia/augmentation/_2d/geometric/resize.py
+++ b/kornia/augmentation/_2d/geometric/resize.py
@@ -22,6 +22,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.base import _input_metadata_only
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.augmentation.utils._crop import _half_pixel_resize_transform
from kornia.constants import Resample
from kornia.core.utils import is_exporting
from kornia.geometry.transform import crop_by_transform_mat, get_perspective_transform, resize
@@ -49,9 +50,10 @@ class Resize(GeometricAugmentationBase2D):
``"horz"`` the width. The derived side is truncated toward zero; if it becomes zero, the resize raises
``AssertionError`` (for example, ``Resize(4, side="long")`` or ``LongestMaxSize(4)`` on a 1-by-10 image).
This class uses :func:`kornia.geometry.transform.resize`; ``align_corners`` is forwarded for bilinear and
- bicubic sampling, and at ``align_corners=False`` the image does not follow ``transform_matrix``
- (`#4804 <https://github.com/kornia/kornia/issues/4804>`_). :meth:`inverse` resamples to the prior canvas
- and cannot recover values discarded by a resize.
+ bicubic sampling, and ``transform_matrix`` follows the grid they sample: at ``align_corners=False`` it is
+ the 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
+ values discarded by a resize.
"""
@@ -83,6 +85,10 @@ 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):
+ return _half_pixel_resize_transform(params["src"].to(input), params["dst"].to(input)).expand(
+ input.shape[0], -1, -1
+ )
# NOTE: a former `if params["output_size"] == input.shape[-2:]: return eye_like(...)`
# short-circuit was dead code β€” comparing a tensor to a ``torch.Size`` falls back to
# identity ``==`` and is *always* Python ``False``, so the branch never ran. It also
diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.py
index 02db279b8..eef9decc6 100644
--- a/kornia/augmentation/_2d/geometric/resized_crop.py
+++ b/kornia/augmentation/_2d/geometric/resized_crop.py
@@ -24,7 +24,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.base import _input_metadata_only
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
-from kornia.augmentation.utils._crop import _compiled_slice_resize
+from kornia.augmentation.utils._crop import _compiled_slice_resize, _half_pixel_resize_transform
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
@@ -74,10 +74,12 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
torchvision, which centres the fallback crop, it is placed at a random position like any other crop.
Both cropping modes use the configured interpolation and ``align_corners``. Slice mode ignores
- ``align_corners`` for ``resample="nearest"``. At ``align_corners=False`` the two modes give
- different images, and slice mode does not follow ``transform_matrix``
- (`#4804 <https://github.com/kornia/kornia/issues/4804>`_). Only resample mode supports :meth:`inverse`,
- which resamples onto the original canvas and cannot recover discarded information.
+ ``align_corners`` for ``resample="nearest"``. With bilinear or bicubic interpolation, each mode's image
+ follows its ``transform_matrix``, and at ``align_corners=False`` the two modes give different images: slice
+ 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. 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,
@@ -140,6 +142,14 @@ 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)
+ ):
+ return _half_pixel_resize_transform(params["src"].to(input), params["dst"].to(input)).expand(
+ 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))
return transform.expand(input.shape[0], -1, -1)
diff --git a/kornia/augmentation/utils/_crop.py b/kornia/augmentation/utils/_crop.py
index 5e5797db0..7dcc0f2ee 100644
--- a/kornia/augmentation/utils/_crop.py
+++ b/kornia/augmentation/utils/_crop.py
@@ -22,6 +22,16 @@ from typing import Optional, Tuple
import torch
+def _half_pixel_resize_transform(src: torch.Tensor, dst: torch.Tensor) -> torch.Tensor:
+ """Map pixel centres between inclusive, axis-aligned crop and output boxes."""
+ scale = (dst[:, 2] - dst[:, 0] + 1) / (src[:, 2] - src[:, 0] + 1)
+ # x' = (x - x0 + 0.5) * scale - 0.5 + dst0, and likewise for y.
+ offset = dst[:, 0] - scale * src[:, 0] + (scale - 1) / 2
+ transform = torch.diag_embed(torch.cat((scale, torch.ones_like(scale[:, :1])), dim=-1))
+ transform[:, :2, 2] = offset
+ return transform
+
+
def _resize_coordinates(
start: torch.Tensor,
end: torch.Tensor,
diff --git a/tests/augmentation/test_conventions_geometric_crop.py b/tests/augmentation/test_conventions_geometric_crop.py
index aee1cd275..4397972d2 100644
--- a/tests/augmentation/test_conventions_geometric_crop.py
+++ b/tests/augmentation/test_conventions_geometric_crop.py
@@ -392,21 +392,15 @@ class TestGeometricCropConventions(BaseTester):
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):
- # #4804: at align_corners=False the image is resized on the half-pixel grid, the matrix corner to corner.
- # A ramp's value is the source x each output pixel sampled; flips when the two agree.
+ def test_convention_interpolate_matrix_follows_sampled_grid_4804(self):
+ # The ramp value is the source x sampled at output column 1.
ramp = torch.arange(7.0, dtype=torch.float64).expand(1, 1, 5, 7).contiguous()
- for align_corners, disagree in ((True, False), (False, True)):
- aug = K.Resize((10, 14), align_corners=align_corners, p=1.0)
+ for align_corners in (True, False):
+ aug = K.Resize((10, 14), align_corners=align_corners)
+ aug.set_rng_device_and_dtype("cpu", torch.float64)
sampled = aug(ramp)[0, 0, 2, 1]
inverse = torch.linalg.inv(aug.transform_matrix[0])
- assert bool((sampled - (inverse[0, 0] + inverse[0, 2])).abs() > 0.1) == disagree # output column 1
- torch.manual_seed(1)
- image = torch.rand(1, 1, 20, 24)
- sliced = K.RandomResizedCrop((9, 13), align_corners=align_corners, p=1.0)
- first = sliced(image)
- resampled = K.RandomResizedCrop((9, 13), align_corners=align_corners, p=1.0, cropping_mode="resample")
- assert bool((first - resampled(image, params=sliced._params)).abs().max() > 0.1) == disagree
+ self.assert_close(sampled, inverse[0, 0] + inverse[0, 2], atol=1e-12, rtol=1e-12)
@pytest.mark.device_agnostic
def test_random_resized_crop_slice_mode_accepts_nearest_4802(self):
diff --git a/tests/augmentation/test_resize_matrix.py b/tests/augmentation/test_resize_matrix.py
new file mode 100644
index 000000000..8a66be12a
--- /dev/null
+++ b/tests/augmentation/test_resize_matrix.py
@@ -0,0 +1,195 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+import pytest
+import torch
+
+import kornia.augmentation as K
+from kornia.constants import Resample
+from kornia.geometry.transform import get_perspective_transform
+
+from testing.base import BaseTester
+
+
+class TestResizeMatrix(BaseTester):
+ @staticmethod
+ def _ramp(height, width, device, dtype):
+ y, x = torch.meshgrid(
+ torch.arange(height, device=device, dtype=dtype),
+ torch.arange(width, device=device, dtype=dtype),
+ indexing="ij",
+ )
+ return torch.stack((x, y)).unsqueeze(0).repeat(2, 1, 1, 1)
+
+ @staticmethod
+ def _augmentation(kind, size, align_corners, device, dtype):
+ if kind == "resize":
+ aug = K.Resize(size, align_corners=align_corners)
+ elif kind == "longest":
+ aug = K.LongestMaxSize(size[1], align_corners=align_corners)
+ elif kind == "smallest":
+ aug = K.SmallestMaxSize(size[0], align_corners=align_corners)
+ else:
+ aug = K.RandomResizedCrop(size, align_corners=align_corners, cropping_mode="slice")
+ # The True path solves in the parameter dtype; use double for a tight double control.
+ aug.set_rng_device_and_dtype(device, torch.float64 if dtype == torch.float64 else torch.float32)
+ return aug
+
+ @pytest.mark.parametrize("kind", ["resize", "longest", "smallest", "crop"])
+ @pytest.mark.parametrize("size", [(10, 14), (3, 4), (5, 7), (5, 11)])
+ @pytest.mark.parametrize("align_corners", [False, True])
+ def test_matrix_predicts_sampled_coordinates_4804(self, device, dtype, kind, size, align_corners):
+ image = self._ramp(9, 12, device, dtype) if kind == "crop" else self._ramp(5, 7, device, dtype)
+ aug = self._augmentation(kind, size, align_corners, device, dtype)
+ params = aug.forward_parameters(image.shape)
+ if kind == "crop":
+ # Distinct origins and crop sizes expose translation signs and per-row scaling.
+ params["src"] = image.new_tensor([[[1, 2], [7, 2], [7, 6], [1, 6]], [[3, 1], [10, 1], [10, 6], [3, 6]]])
+ out = aug(image, params=params)
+ assert aug._transform_matrix is None # construction remains lazy
+ matrix = aug.transform_matrix
+ assert matrix.dtype == dtype and matrix.device == image.device
+ assert matrix.shape == (2, 3, 3)
+ assert aug.transform_matrix is matrix
+ src = params["src"].to(image)
+ origin = src[:, 0]
+ extent = src[:, 2] - origin
+ h, w = out.shape[-2:]
+ lengths = image.new_tensor([w, h])
+ scales = (lengths - 1) / extent if align_corners else lengths / (extent + 1)
+ offsets = -origin * scales
+ if not align_corners:
+ offsets = offsets + (scales - 1) / 2
+ expected = torch.eye(3, device=device, dtype=dtype).repeat(2, 1, 1)
+ expected[:, 0, 0], expected[:, 1, 1] = scales.unbind(-1)
+ expected[:, :2, 2] = offsets
+ tolerance = {"atol": 1e-12, "rtol": 1e-12} if dtype == torch.float64 else {}
+ self.assert_close(matrix, expected, **tolerance)
+ # Two ramps report the source x and y actually sampled. Invert the recorded
+ # matrix, then account for interpolate's clamping to the crop boundary.
+ grid = self._ramp(h, w, device, dtype).flatten(2)
+ homogeneous = torch.cat((grid, torch.ones_like(grid[:, :1])), dim=1)
+ work_dtype = torch.float64 if dtype == torch.float64 else torch.float32
+ predicted = (torch.linalg.inv(matrix.to(work_dtype)) @ homogeneous.to(work_dtype))[:, :2]
+ predicted = predicted.maximum(origin.unsqueeze(-1)).minimum((origin + extent).unsqueeze(-1))
+ self.assert_close(out.flatten(2), predicted.to(dtype), **tolerance)
+
+ @pytest.mark.parametrize("kind", ["resize", "crop"])
+ @pytest.mark.parametrize("shape,size", [((1, 7), (3, 4)), ((5, 1), (2, 3)), ((5, 7), (1, 1)), ((1, 1), (1, 1))])
+ def test_singleton_half_pixel_matrix_4804(self, device, dtype, kind, shape, size):
+ image = self._ramp(*shape, device, dtype)
+ aug = self._augmentation(kind, size, False, device, dtype)
+ params = aug.forward_parameters(image.shape)
+ h, w = shape
+ params["src"] = image.new_tensor([[[0, 0], [w - 1, 0], [w - 1, h - 1], [0, h - 1]]]).repeat(2, 1, 1)
+ out = aug(image, params=params)
+ sx, sy = size[1] / w, size[0] / h
+ expected = image.new_tensor([[sx, 0, (sx - 1) / 2], [0, sy, (sy - 1) / 2], [0, 0, 1]])
+ self.assert_close(aug.transform_matrix, expected.expand(2, -1, -1))
+ self.assert_close(out, torch.nn.functional.interpolate(image, size, mode="bilinear", align_corners=False))
+
+ @pytest.mark.parametrize("kind", ["resize", "longest", "smallest", "crop"])
+ def test_sequential_annotations_follow_pixels_4804(self, device, dtype, kind):
+ image = self._ramp(8, 12, device, dtype)
+ aug = self._augmentation(kind, (4, 6), False, device, dtype)
+ seq = K.AugmentationSequential(aug, data_keys=["input", "keypoints", "bbox"])
+ params = seq.forward_parameters(image.shape)
+ if kind == "crop":
+ params[0].data["src"] = image.new_tensor(
+ [[[2, 1], [9, 1], [9, 6], [2, 6]], [[1, 2], [8, 2], [8, 7], [1, 7]]]
+ )
+ # Select interior output pixels and derive their source centres analytically.
+ src = params[0].data["src"].to(image)
+ origin, extent = src[:, 0], src[:, 2] - src[:, 0] + 1
+ target = image.new_tensor([[[1, 1], [4, 1], [4, 2], [1, 2]]]).repeat(2, 1, 1)
+ points = (target + 0.5) * (extent / image.new_tensor([6, 4])).unsqueeze(1) - 0.5 + origin.unsqueeze(1)
+ output, mapped, boxes = seq(image, points, points.unsqueeze(1), params=params)
+ self.assert_close(mapped, target)
+ self.assert_close(boxes, target.unsqueeze(1))
+ self.assert_close(output[:, :, [1, 1, 2, 2], [1, 4, 4, 1]].transpose(1, 2), points)
+
+ @pytest.mark.parametrize("align_corners", [False, True])
+ @pytest.mark.parametrize("kind", ["resize", "crop"])
+ def test_bicubic_matrix_and_image_4804(self, device, dtype, kind, align_corners):
+ image = self._ramp(5, 7, device, dtype)
+ aug = self._augmentation(kind, (8, 11), align_corners, device, dtype)
+ params = aug.forward_parameters(image.shape)
+ params["src"] = params["src"].new_tensor([[[0, 0], [6, 0], [6, 4], [0, 4]]]).repeat(2, 1, 1)
+ aug(image, params=params)
+ bilinear_matrix = aug.transform_matrix.clone()
+ out = aug(image, params=params, resample=Resample.BICUBIC)
+ self.assert_close(aug.transform_matrix, bilinear_matrix, atol=0, rtol=0)
+ expected = torch.nn.functional.interpolate(image, (8, 11), mode="bicubic", align_corners=align_corners)
+ self.assert_close(out, expected)
+
+ @pytest.mark.parametrize("align_corners", [False, True])
+ def test_resample_keeps_corner_geometry_4804(self, device, dtype, align_corners):
+ image = self._ramp(8, 12, device, dtype)
+ aug = K.RandomResizedCrop((4, 6), cropping_mode="resample", align_corners=align_corners)
+ params = aug.forward_parameters(image.shape)
+ output = aug(image, params=params)
+ expected = get_perspective_transform(params["src"].to(image), params["dst"].to(image))
+ self.assert_close(aug.transform_matrix, expected, atol=0, rtol=0)
+ # Slice/resample agree for corner alignment; False intentionally uses distinct grids.
+ if align_corners and dtype in (torch.float32, torch.float64):
+ # Half-precision warp grids have additional rounding beyond interpolate.
+ sliced = K.RandomResizedCrop((4, 6), align_corners=True)(image, params=params)
+ self.assert_close(output, sliced)
+
+ @pytest.mark.parametrize("kind", ["resize", "crop"])
+ @pytest.mark.parametrize("resample,align_corners", [("bilinear", True), ("nearest", True), ("nearest", False)])
+ 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)
+ params = aug.forward_parameters(image.shape)
+ if kind == "crop":
+ # Random singleton crops make the unchanged corner-aligned solve singular.
+ params["src"] = params["src"].new_tensor(
+ [[[1, 1], [5, 1], [5, 4], [1, 4]], [[2, 0], [6, 0], [6, 3], [2, 3]]]
+ )
+ aug(image, params=params, resample=Resample.get(resample))
+ src, dst = aug._params["src"], aug._params["dst"]
+ if kind == "crop":
+ src, dst = src.to(image), dst.to(image)
+ expected = get_perspective_transform(src, dst).to(image)
+ self.assert_close(aug.transform_matrix, expected, atol=0, rtol=0)
+
+ @pytest.mark.parametrize("kind", ["resize", "crop"])
+ def test_gradcheck(self, device, kind):
+ image = self._ramp(3, 4, device, torch.float64)[:1]
+ points = image.new_tensor([[[1.25, 1.5]]])
+ aug = self._augmentation(kind, (2, 3), False, device, torch.float64)
+ seq = K.AugmentationSequential(aug, data_keys=["input", "keypoints"])
+ params = seq.forward_parameters(image.shape)
+ if kind == "crop":
+ params[0].data["src"] = image.new_tensor([[[0, 0], [3, 0], [3, 2], [0, 2]]])
+ self.gradcheck(lambda x, p: tuple(seq(x, p, params=params)), (image, points))
+
+ @pytest.mark.parametrize("kind", ["resize", "longest", "smallest"])
+ @pytest.mark.parametrize("align_corners", [False, True])
+ def test_inverse_restores_ramp_4804(self, device, dtype, kind, align_corners):
+ # Bilinear resampling reproduces a ramp, so warping a 2x upscale back with the recorded matrix restores
+ # the interior exactly. The corner-to-corner matrix at align_corners=False missed by 0.21 px here.
+ image = self._ramp(9, 13, device, dtype)
+ aug = self._augmentation(kind, (18, 26), align_corners, device, dtype)
+ restored = aug.inverse(aug(image))
+ # Two half-precision warps round by up to one bfloat16 ulp at 12 (0.0625), below the 0.21 px defect.
+ tolerances = {torch.float64: (1e-12, 1e-12), torch.float16: (0.05, 0), torch.bfloat16: (0.1, 0)}
+ atol, rtol = tolerances.get(dtype, (1e-4, 1e-4))
+ self.assert_close(restored[..., 1:-1, 1:-1], image[..., 1:-1, 1:-1], atol=atol, rtol=rtol)