Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): make grid warps independent of the homography scale (#5949)

Adarsh Mishra524e4f173088
diff --git a/changelog.d/5949.fixed.md b/changelog.d/5949.fixed.md
new file mode 100644
index 000000000..36c4c496e
--- /dev/null
+++ b/changelog.d/5949.fixed.md
@@ -0,0 +1,11 @@
+`warp_grid`, `warp_grid3d`, `homography_warp` (with the default `normalized_homography=True`), `HomographyWarper`,
+`homography_warp3d` and `warp_perspective3d` now give the same result for `s * H` as for `H`, apart from grid points
+whose homogeneous coordinate is still within `1e-8` of zero after the matrix is rescaled. A homography and any
+nonzero multiple of it describe the same projective map, but the grid passed every point with `|w| <= 1e-8` to
+`grid_sample` undivided, so the arbitrary scale of the matrix changed the output without a NaN or an error: for a
+homography with entries between 0.01 and 1, `1e-8 * H` (`1e8 * M` for `warp_perspective3d`, which inverts its pixel
+matrix first) differed from `H` by up to 0.50 of the image range in float64. The grid warps now divide the matrix by
+the detached projective scale #5752 introduced for `warp_perspective`, so gradients follow `dL/d(s*H) = (dL/dH)/s`.
+A matrix whose nonzero entries all have magnitude above 1, or all below 1, changes its results at rounding level; any
+other matrix, such as one with `H[2, 2] = 1`, gives bit-identical results. `warp_perspective3d` rescales the
+normalized inverse of its pixel matrix, so its results can change at rounding level even when `M[3, 3] = 1`.
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index e617466a9..364a84052 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -108,6 +108,28 @@ def _runs_in_float32(src: torch.Tensor, other: torch.Tensor) -> bool:
return src.device.type == "cpu" and src.dtype in (torch.float16, torch.bfloat16) and other.dtype == src.dtype
+def _unit_projective_scale(matrix: torch.Tensor) -> torch.Tensor:
+ """Return the detached projective scale of ``matrix``: the value closest to 1 in its nonzero-magnitude range.
+
+ A homography and any nonzero multiple of it describe the same map, yet
+ :func:`kornia.geometry.convert_points_from_homogeneous` leaves a point with ``|w| <= eps``
+ undivided using an *absolute* ``eps``. Feeding that routine a grid built from an arbitrarily
+ scaled matrix therefore changes the sampled pixels instead of the warp. Dividing by this scale
+ first puts every equivalent matrix in the same numeric range. Choosing between the largest and
+ smallest nonzero magnitude, rather than just dividing by the largest, keeps a unit diagonal from
+ being shrunk toward zero by large translations. The scale is a projective gauge, so detaching it
+ leaves the warp's derivative unchanged.
+ """
+ magnitude = matrix.detach().abs()
+ largest = magnitude.amax(dim=(-2, -1), keepdim=True)
+ smallest = magnitude.masked_fill(magnitude == 0, float("inf")).amin(dim=(-2, -1), keepdim=True)
+ scale = torch.minimum(largest, torch.ones_like(largest)).clamp_min(smallest)
+ # An all-zero matrix leaves `smallest` infinite, and dividing by infinity would collapse the
+ # warp's gradient to zero. Anything that is not a finite positive scale is left alone.
+ usable = (scale > 0) & torch.isfinite(scale)
+ return torch.where(usable, scale, torch.ones_like(scale))
+
+
def _empty_warp_output_2d(
src: torch.Tensor,
transform: torch.Tensor,
@@ -311,15 +333,8 @@ def warp_perspective(
# H and s*H represent the same projective map. Remove that arbitrary scale before
# the coordinate change and inverse: the cubic determinant can overflow/underflow
# even when every entry, the sampling positions and their gradients are finite.
- # The scale is a projective gauge, so detaching it leaves the warp's derivative unchanged.
if M.is_floating_point():
- magnitude = M.detach().abs()
- largest = magnitude.amax(dim=(-2, -1), keepdim=True)
- smallest = magnitude.masked_fill(magnitude == 0, float("inf")).amin(dim=(-2, -1), keepdim=True)
- # Choose the scale closest to 1 between the nonzero magnitudes. Dividing a large
- # translation by its maximum would instead shrink the unit diagonal toward zero.
- scale = torch.minimum(largest, torch.ones_like(largest)).clamp_min(smallest)
- M = M / torch.where(scale > 0, scale, torch.ones_like(scale))
+ M = M / _unit_projective_scale(M)
dst_norm_trans_src_norm: torch.Tensor = normalize_homography(
M, (H, W), (h_out, w_out), align_corners=align_corners
@@ -543,6 +558,12 @@ def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
:math:`(N, 3, 3)` or :math:`(N, 1, 3, 3)`
- only the :math:`(1, H, W, 2)` grid broadcasts over homography batches; a batched grid
requires a matching batch of :math:`N` homographies
+ - ``src_homo_dst`` is divided by a detached scale toward unit magnitude before the
+ homogeneous division, as in :func:`warp_perspective`, so a nonzero scalar multiple of it
+ returns the same grid, except at grid points whose homogeneous coordinate is within
+ ``1e-8`` of zero after that rescaling: those are left undivided, as
+ :func:`~kornia.geometry.conversions.convert_points_from_homogeneous` does for points at
+ infinity
Args:
grid: Unwrapped grid of the shape :math:`(1, H, W, 2)`, or :math:`(N, H, W, 2)` with a
@@ -561,6 +582,10 @@ def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
grid = grid.expand(batch_size, -1, -1, -1) # NxHxWx2
if len(src_homo_dst.shape) == 3: # local homography case
src_homo_dst = src_homo_dst.view(batch_size, 1, 3, 3) # Nx1x3x3
+ # H and s*H are the same warp, but the absolute eps inside convert_points_from_homogeneous
+ # would otherwise make the sampled grid depend on the matrix's arbitrary scale.
+ if src_homo_dst.is_floating_point():
+ src_homo_dst = src_homo_dst / _unit_projective_scale(src_homo_dst)
# perform the actual grid transformation,
# the grid is copied to input device and casted to the same type
flow: torch.Tensor = transform_points(src_homo_dst, grid.to(src_homo_dst)) # NxHxWx2
@@ -577,6 +602,12 @@ def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
:math:`(N, 4, 4)` or :math:`(N, 1, 4, 4)`
- only the :math:`(1, D, H, W, 3)` grid broadcasts over homography batches; a batched
grid requires a matching batch of :math:`N` homographies
+ - ``src_homo_dst`` is divided by a detached scale toward unit magnitude before the
+ homogeneous division, as in :func:`warp_perspective`, so a nonzero scalar multiple of it
+ returns the same grid, except at grid points whose homogeneous coordinate is within
+ ``1e-8`` of zero after that rescaling: those are left undivided, as
+ :func:`~kornia.geometry.conversions.convert_points_from_homogeneous` does for points at
+ infinity
Args:
grid: Unwrapped grid of the shape :math:`(1, D, H, W, 3)`, or :math:`(N, D, H, W, 3)`
@@ -595,6 +626,9 @@ def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
grid = grid.expand(batch_size, -1, -1, -1, -1) # NxDxHxWx3
if len(src_homo_dst.shape) == 3: # local homography case
src_homo_dst = src_homo_dst.view(batch_size, 1, 4, 4) # Nx1x3x3
+ # Same projective gauge as in warp_grid: a scaled 4x4 matrix must not move the grid.
+ if src_homo_dst.is_floating_point():
+ src_homo_dst = src_homo_dst / _unit_projective_scale(src_homo_dst)
# perform the actual grid transformation,
# the grid is copied to input device and casted to the same type
flow: torch.Tensor = transform_points(src_homo_dst, grid.to(src_homo_dst)) # NxDxHxWx3
diff --git a/tests/geometry/transform/test_homography_warper.py b/tests/geometry/transform/test_homography_warper.py
index cc647737b..0d0163a17 100644
--- a/tests/geometry/transform/test_homography_warper.py
+++ b/tests/geometry/transform/test_homography_warper.py
@@ -298,6 +298,81 @@ class TestHomographyWarper(BaseTester):
self.assert_close(precomputed, direct, atol=1e-4, rtol=1e-4)
self.assert_close(direct, patch_src)
+ @pytest.mark.parametrize("align_corners", [False, True])
+ @pytest.mark.parametrize("scale", [1e-7, 1e-8, 1e-12, 1e-30, 1e12, -1e8])
+ def test_warp_grid_ignores_the_homography_scale(self, scale, align_corners, device, dtype):
+ # A homography and any nonzero multiple of it describe the same warp. An absolute eps inside
+ # convert_points_from_homogeneous used to leave grid points with |w| <= eps undivided, so the
+ # sampled pixels depended on the matrix's arbitrary scale (#5761).
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("these scales test the float32/float64 arithmetic range")
+ height, width = 6, 6
+ image = torch.arange(float(height * width), device=device, dtype=dtype).reshape(1, 1, height, width) / 36
+ dst_homo_src = torch.tensor(
+ [[[1.0, 0.1, 0.03], [0.05, 1.0, 0.02], [0.1, 0.2, 1.0]]], device=device, dtype=dtype
+ )
+ grid = kornia.geometry.create_meshgrid(
+ height, width, normalized_coordinates=True, device=device, dtype=dtype, align_corners=align_corners
+ )
+
+ self.assert_close(
+ kornia.geometry.transform.warp_grid(grid, scale * dst_homo_src),
+ kornia.geometry.transform.warp_grid(grid, dst_homo_src),
+ )
+
+ warper = kornia.geometry.transform.HomographyWarper(height, width, align_corners=align_corners)
+ self.assert_close(warper(image, scale * dst_homo_src), warper(image, dst_homo_src))
+
+ dst_homo_src_norm = _torch_inverse_cast(
+ kornia.geometry.normalize_homography(
+ dst_homo_src, (height, width), (height, width), align_corners=align_corners
+ )
+ )
+ warp = kornia.geometry.homography_warp
+ kwargs = {"align_corners": align_corners, "normalized_homography": True}
+ scaled = warp(image, scale * dst_homo_src_norm, (height, width), **kwargs)
+ assert torch.isfinite(scaled).all()
+ self.assert_close(scaled, warp(image, dst_homo_src_norm, (height, width), **kwargs))
+
+ @pytest.mark.parametrize("scale", [1e-8, 1e-12, 1e12])
+ def test_homography_warp_gradient_follows_the_projective_gauge(self, scale, device, dtype):
+ # The scale is divided out with a detached factor, so the image is unchanged and the gradient
+ # obeys the projective rule dL/d(s*H) = (dL/dH)/s rather than being silently rescaled (#5761).
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("these scales test the float32/float64 arithmetic range")
+ height, width = 6, 6
+ image = torch.arange(float(height * width), device=device, dtype=dtype).reshape(1, 1, height, width) / 36
+ dst_homo_src = torch.tensor(
+ [[[1.0, 0.1, 0.03], [0.05, 1.0, 0.02], [0.1, 0.2, 1.0]]], device=device, dtype=dtype
+ )
+ normalized = _torch_inverse_cast(
+ kornia.geometry.normalize_homography(dst_homo_src, (height, width), (height, width))
+ )
+ reference_matrix = normalized.clone().requires_grad_()
+ scaled_matrix = (normalized * scale).requires_grad_()
+
+ reference = kornia.geometry.homography_warp(image, reference_matrix, (height, width))
+ actual = kornia.geometry.homography_warp(image, scaled_matrix, (height, width))
+ reference_grad = torch.autograd.grad(reference.square().sum(), reference_matrix)[0]
+ actual_grad = torch.autograd.grad(actual.square().sum(), scaled_matrix)[0]
+
+ assert torch.isfinite(actual_grad).all()
+ self.assert_close(actual, reference)
+ self.assert_close(actual_grad * scale, reference_grad)
+
+ def test_warp_grid_keeps_a_gradient_for_an_all_zero_matrix(self, device, dtype):
+ # A zero matrix has no nonzero magnitude to scale by. The gauge must fall back to 1 instead of
+ # dividing by the infinite "smallest magnitude", which would collapse every grid gradient to 0.
+ grid = kornia.geometry.create_meshgrid(3, 3, normalized_coordinates=True, device=device, dtype=dtype)
+ matrix = torch.zeros(1, 3, 3, device=device, dtype=dtype).requires_grad_(True)
+
+ warped = kornia.geometry.transform.warp_grid(grid, matrix)
+ grad = torch.autograd.grad(warped.sum(), matrix)[0]
+
+ assert torch.isfinite(warped).all()
+ assert torch.isfinite(grad).all()
+ assert grad.abs().sum() > 0
+
@pytest.mark.parametrize("batch_shape", [(1, 1, 7, 5), (2, 3, 8, 5), (1, 1, 7, 16)])
def test_gradcheck(self, batch_shape, device):
dtype = torch.float64
diff --git a/tests/geometry/transform/test_imgwarp3d.py b/tests/geometry/transform/test_imgwarp3d.py
index c1fc620e2..56a1e154f 100644
--- a/tests/geometry/transform/test_imgwarp3d.py
+++ b/tests/geometry/transform/test_imgwarp3d.py
@@ -22,7 +22,7 @@ import kornia
import kornia.geometry.transform as proj
from kornia.core.utils import _torch_inverse_cast
-from testing.base import BaseTester
+from testing.base import BaseTester, assert_close
class TestWarpAffine3dEmptyBatch(BaseTester):
@@ -227,6 +227,59 @@ def test_homography_warp3d_negative_destination_raises(device, dtype):
proj.homography_warp3d(src, transform, (-1, 4, 5))
[email protected]("align_corners", [False, True])
[email protected]("scale", [1e-7, 1e-8, 1e-12, 1e-30, 1e12, -1e8])
+def test_warp_grid3d_ignores_the_homography_scale(scale, align_corners, device, dtype):
+ # A homography and any nonzero multiple of it describe the same warp. An absolute eps inside
+ # convert_points_from_homogeneous used to leave grid points with |w| <= eps undivided, so the
+ # sampled voxels depended on the matrix's arbitrary scale (#5761). Comparing a scaled call with an
+ # unscaled one cancels the 3D normalization convention tracked in #4503, which both share.
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("these scales test the float32/float64 arithmetic range")
+ dsize = (4, 5, 6)
+ d, h, w = dsize
+ volume = torch.arange(float(d * h * w), device=device, dtype=dtype).view(1, 1, d, h, w) / (d * h * w)
+ dst_homo_src = torch.tensor(
+ [
+ [
+ [1.0, 0.05, 0.1, 0.03],
+ [0.02, 1.0, 0.05, 0.02],
+ [0.03, 0.01, 1.0, 0.01],
+ [0.1, 0.2, 0.15, 1.0],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ grid = torch.stack(
+ torch.meshgrid(
+ torch.linspace(-1, 1, d, device=device, dtype=dtype),
+ torch.linspace(-1, 1, h, device=device, dtype=dtype),
+ torch.linspace(-1, 1, w, device=device, dtype=dtype),
+ indexing="ij",
+ ),
+ dim=-1,
+ ).unsqueeze(0)
+
+ reference_grid = proj.warp_grid3d(grid, dst_homo_src)
+ actual_grid = proj.warp_grid3d(grid, scale * dst_homo_src)
+ assert_close(actual_grid, reference_grid)
+
+ reference = proj.homography_warp3d(volume, dst_homo_src, dsize, align_corners=align_corners)
+ actual = proj.homography_warp3d(volume, scale * dst_homo_src, dsize, align_corners=align_corners)
+ assert torch.isfinite(actual).all()
+ assert_close(actual, reference)
+
+ # warp_perspective3d consumes a source-to-destination pixel matrix and inverts it internally, so a
+ # large matrix becomes a small inverse and reaches the same threshold from the other side.
+ src_homo_dst = torch.eye(4, device=device, dtype=dtype).unsqueeze(0) * 0.5
+ src_homo_dst[:, :3, 3] = torch.tensor([0.2, -0.1, 0.05], device=device, dtype=dtype)
+ reference_p = proj.warp_perspective3d(volume, src_homo_dst, dsize, align_corners=align_corners)
+ actual_p = proj.warp_perspective3d(volume, scale * src_homo_dst, dsize, align_corners=align_corners)
+ assert torch.isfinite(actual_p).all()
+ assert_close(actual_p, reference_p)
+
+
class TestWarpPerspective3d(BaseTester):
# Before #4502 none of these could pass: homography_warp3d handed create_meshgrid3d's (d, x, y)
# grid straight to warp_grid3d and grid_sample, which both read (x, y, z), so even an identity