Skip to content

šŸ Geometric Computer Vision Library for Spatial AI

fix(geometry): homography_warp and HomographyWarper normalize the pixel grid with normalized_coordinates=False (#6191)

Dmytro Mishkin98d6789907fb
diff --git a/changelog.d/6191.fixed.md b/changelog.d/6191.fixed.md
new file mode 100644
index 000000000..ac4c4c45e
--- /dev/null
+++ b/changelog.d/6191.fixed.md
@@ -0,0 +1,10 @@
+`homography_warp(..., normalized_coordinates=False)` and `HomographyWarper(..., normalized_coordinates=False)`, on
+both the direct and the `precompute_warp_grid` path, now warp by a destination→source **pixel** homography: the
+warped grid of source pixel coordinates is normalized under the call's `align_corners` before `grid_sample`, as
+`warp_perspective` does. Previously the pixel grid reached `grid_sample` unnormalized, so almost every sample fell
+outside the image and an identity homography returned a nearly blank image instead of the input. The result now
+matches `warp_perspective` with the inverse homography; the pixel grid is warped and normalized in at least
+`float32`, also under a half default dtype and in a caller's autocast region, scripted or not, so `float16` and
+`bfloat16` do not lose half or whole pixels to coordinate rounding. Callers that pre-multiplied the homography by
+`normal_transform_pixel` to work around this must drop that factor. The default `normalized_coordinates=True` is
+unchanged. Fixes #6170.
diff --git a/docs/export_support/cases_geomA.py b/docs/export_support/cases_geomA.py
index ea419e5f0..c0c254f09 100644
--- a/docs/export_support/cases_geomA.py
+++ b/docs/export_support/cases_geomA.py
@@ -509,10 +509,7 @@ CASES = [
"transform.HomographyWarper[pixel]",
G,
T.HomographyWarper(H, W, normalized_coordinates=False),
- # The normal_transform_pixel factor works around #6170 (the pixel grid reaches grid_sample unnormalized, so
- # a pixel homography samples outside the image and the output is a constant zero); drop it when #6170 is fixed.
- [img, K.geometry.conversions.normal_transform_pixel(H, W) @ homo33_pert],
- note="homography includes normal_transform_pixel until #6170 is fixed",
+ [img, homo33_pert],
),
case(
"transform.HomographyWarper[precomputed]",
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index 862a9078a..d8390c7bf 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -287,8 +287,9 @@ Transformation matrices and homographies
- :func:`kornia.geometry.transform.homography_warp` is different on every
axis: it takes the **destination→source** homography, **normalized** to
``[-1, 1]`` by default (``normalized_homography=True``), and defaults to
- ``align_corners=False``. Convert a pixel source→destination homography by
- normalizing it FIRST with
+ ``align_corners=False``. ``normalized_coordinates=False`` takes the same
+ destination→source homography in pixels. Convert a pixel
+ source→destination homography by normalizing it FIRST with
:func:`kornia.geometry.conversions.normalize_homography` (which expects
the forward src→dst homography) and inverting AFTER — inverting first
with unswapped sizes is silently wrong whenever the source and
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
index 466e01654..561034a83 100644
--- a/kornia/geometry/transform/homography_warper.py
+++ b/kornia/geometry/transform/homography_warper.py
@@ -26,7 +26,7 @@ from torch import nn
from kornia.core.utils import _torch_grid_sample
from kornia.geometry.grid import create_meshgrid
-from .imgwarp import homography_warp, warp_grid
+from .imgwarp import _normalize_warped_pixel_grid, _warp_pixel_grid, homography_warp, warp_grid
__all__ = ["BaseWarper", "HomographyWarper"]
@@ -86,6 +86,9 @@ class HomographyWarper(BaseWarper):
coordinates and sampling conventions.
- See the convention block of :func:`homography_warp`.
+ - with ``normalized_coordinates=False`` a grid from :meth:`precompute_warp_grid` holds source pixel
+ coordinates computed as in :func:`homography_warp` (in at least float32, unaffected by autocast), normalized
+ at sampling time with the size of the patch passed to ``forward`` and then cast to the homography's dtype
Args:
height: The height of the destination torch.Tensor.
@@ -93,12 +96,14 @@ class HomographyWarper(BaseWarper):
mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
``'zeros'`` | ``'border'`` | ``'reflection'``.
- normalized_coordinates: whether to use a grid with normalized coordinates.
+ normalized_coordinates: whether the homographies are in normalized :math:`[-1, 1]` coordinates
+ (``True``) or in pixel coordinates (``False``), as in :func:`homography_warp`.
align_corners: interpolation flag.
"""
_warped_grid: Optional[torch.Tensor]
+ _warped_grid_dtype: Optional[torch.dtype]
def __init__(
self,
@@ -120,8 +125,9 @@ class HomographyWarper(BaseWarper):
height, width, normalized_coordinates=normalized_coordinates, align_corners=align_corners
)
- # initialice the warped destination grid
+ # initialice the warped destination grid, and in pixel mode the dtype forward() returns it to
self._warped_grid = None
+ self._warped_grid_dtype = None
def precompute_warp_grid(self, src_homo_dst: torch.Tensor) -> None:
r"""Compute and store internally the transformations of the points.
@@ -133,10 +139,17 @@ class HomographyWarper(BaseWarper):
transform all points in the grid. Shape of the homography
has to be :math:`(1, 3, 3)`, :math:`(N, 3, 3)` or :math:`(N, 1, 3, 3)`.
The homography assumes normalized coordinates [-1, 1] if
- normalized_coordinates is True.
+ normalized_coordinates is True, and pixel coordinates otherwise.
"""
- self._warped_grid = warp_grid(self.grid, src_homo_dst)
+ if self.normalized_coordinates:
+ self._warped_grid = warp_grid(self.grid, src_homo_dst)
+ return
+ # Source pixels, from a pixel grid built and warped as in homography_warp (in at least float32, unaffected by
+ # autocast; not from self.grid, which a half default dtype has already rounded), kept until forward()
+ # normalizes them with the patch size; the normalized grid then returns to the homography's dtype.
+ self._warped_grid = _warp_pixel_grid(src_homo_dst, self.height, self.width)
+ self._warped_grid_dtype = src_homo_dst.dtype
def forward(self, patch_src: torch.Tensor, src_homo_dst: Optional[torch.Tensor] = None) -> torch.Tensor:
r"""Warp a torch.Tensor from source into reference frame.
@@ -145,7 +158,8 @@ class HomographyWarper(BaseWarper):
patch_src: The torch.Tensor to warp.
src_homo_dst: The homography or torch.stack of
homographies from destination to source. The homography assumes
- normalized coordinates [-1, 1] if normalized_coordinates is True.
+ normalized coordinates [-1, 1] if normalized_coordinates is True,
+ and pixel coordinates otherwise.
Return:
Patch sampled at locations from source to destination.
@@ -184,6 +198,15 @@ class HomographyWarper(BaseWarper):
" precompute_warp_grid() with the correct device for the homograhy"
" or change the patch device."
)
+ if not self.normalized_coordinates:
+ # the cached grid holds source pixels; normalize them with the size of the patch being sampled
+ _warped_grid = _normalize_warped_pixel_grid(
+ _warped_grid, patch_src.shape[-2], patch_src.shape[-1], self.align_corners
+ )
+ # getattr: a module pickled before this attribute existed has no _warped_grid_dtype
+ warped_grid_dtype = getattr(self, "_warped_grid_dtype", None)
+ if warped_grid_dtype is not None:
+ _warped_grid = _warped_grid.to(warped_grid_dtype)
warped_patch = _torch_grid_sample(
patch_src,
_warped_grid,
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 040adee07..9e19abb35 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -37,6 +37,8 @@ from kornia.geometry.conversions import (
axis_angle_to_rotation_matrix,
convert_affinematrix_to_homography,
convert_affinematrix_to_homography3d,
+ convert_points_from_homogeneous,
+ normal_transform_pixel,
normalize_homography,
normalize_homography3d,
normalize_pixel_coordinates,
@@ -637,6 +639,49 @@ def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
return flow.view(batch_size, height, width, 2) # NxHxWx2
+def _pixel_grid_work_dtype(src_homo_dst: torch.Tensor) -> torch.dtype:
+ """Return the dtype a pixel-coordinate sampling grid is warped and normalized in: float32 for a half homography.
+
+ Pixel coordinates reach the image size, where float16 rounds them to half pixels from 512 and to whole pixels from
+ 1024, and bfloat16 already from 64 and 128. The grid is therefore warped and normalized in float32, and only the
+ normalized result, whose values lie near ``[-1, 1]``, returns to the homography's dtype. Other dtypes are kept.
+ """
+ if src_homo_dst.dtype in (torch.float16, torch.bfloat16):
+ return torch.float32
+ return src_homo_dst.dtype
+
+
+def _warp_pixel_grid(src_homo_dst: torch.Tensor, height: int, width: int) -> torch.Tensor:
+ """Warp the ``(height, width)`` grid of destination pixels by ``src_homo_dst`` into source pixel coordinates.
+
+ The grid is built and warped in :func:`_pixel_grid_work_dtype`, whatever the default dtype, with the projective
+ gauge and homogeneous division of :func:`warp_grid`. The homography is applied as a sum of elementwise column
+ products rather than a matrix product: a caller's autocast region would run a matrix product in half precision,
+ also in a scripted call, which cannot leave it, and round the pixel coordinates of a 640 px wide grid to whole
+ pixels in bfloat16. Autocast leaves elementwise products alone, so eager and scripted calls compute the same grid.
+ """
+ work_dtype = _pixel_grid_work_dtype(src_homo_dst)
+ grid = create_meshgrid(height, width, normalized_coordinates=False, device=src_homo_dst.device, dtype=work_dtype)
+ matrix = src_homo_dst.to(work_dtype)
+ matrix = matrix / _unit_projective_scale(matrix)
+ # Broadcasting covers both (N, 3, 3) and (N, 1, 3, 3).
+ matrix = matrix.reshape(src_homo_dst.shape[0], 1, 1, 3, 3)
+ warped = grid[..., :1] * matrix[..., 0] + grid[..., 1:] * matrix[..., 1] + matrix[..., 2]
+ return convert_points_from_homogeneous(warped)
+
+
+def _normalize_warped_pixel_grid(grid: torch.Tensor, height: int, width: int, align_corners: bool) -> torch.Tensor:
+ """Map a ``(N, H, W, 2)`` grid of source pixel coordinates to the ``[-1, 1]`` coordinates ``grid_sample`` reads.
+
+ ``height`` and ``width`` are the source's. The map is :func:`~kornia.geometry.conversions.normal_transform_pixel`
+ under ``align_corners``, the one :func:`warp_perspective` conjugates its pixel homography with, applied per axis.
+ """
+ norm = normal_transform_pixel(height, width, device=grid.device, dtype=grid.dtype, align_corners=align_corners)[0]
+ scale = torch.stack((norm[0, 0], norm[1, 1]))
+ offset = torch.stack((norm[0, 2], norm[1, 2]))
+ return grid * scale + offset
+
+
def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
r"""Compute the grid to warp the coordinates grid by the homography/ies.
@@ -1857,13 +1902,19 @@ def homography_warp(
coordinates and ``align_corners`` sampling rules.
- input: :math:`(N, C, H, W)`
- - ``src_homo_dst`` is the destination→source homography :math:`(N, 3, 3)`, in normalized
- :math:`[-1, 1]` coordinates by default (``normalized_coordinates=True``), when
- ``normalized_homography=True`` (default); with ``normalized_homography=False`` it is
- consumed as the source→destination **pixel** homography, exactly like
- :func:`warp_perspective`
+ - ``src_homo_dst`` is the destination→source homography :math:`(N, 3, 3)` when
+ ``normalized_homography=True`` (default), in normalized :math:`[-1, 1]` coordinates by default
+ (``normalized_coordinates=True``). With ``normalized_coordinates=False`` it is in **pixel**
+ coordinates, pixel centres at integers: it maps the pixel ``(x, y)`` of the ``dsize`` output to the
+ source pixel it samples, so an identity returns the top-left ``dsize`` window of the input
+ - with ``normalized_homography=False`` it is consumed as the source→destination **pixel** homography,
+ exactly like :func:`warp_perspective`, and ``normalized_coordinates`` is ignored
+ - with ``normalized_coordinates=False`` the pixel grid is warped and normalized in at least float32, also
+ under a half default dtype and in a caller's autocast region, and then cast to the homography's dtype
- ``dsize`` is ``(h, w)``
- - align_corners: ``False`` by default (differs from :func:`warp_perspective`)
+ - align_corners: ``False`` by default (differs from :func:`warp_perspective`). Along a source axis longer
+ than one pixel, a pixel homography samples the same positions under both settings, which then differ
+ only in ``padding_mode="reflection"``
- negative output dimensions raise ``ValueError``
Args:
@@ -1871,15 +1922,15 @@ def homography_warp(
src_homo_dst: The homography or torch.stack of homographies of shape :math:`(N, 3, 3)` —
destination to source when ``normalized_homography=True`` (default), source to
destination (pixel) when ``normalized_homography=False``.
- dsize:
- if homography normalized: The height and width of the image to warp.
- if homography not normalized: size of the output image (height, width).
+ dsize: output size ``(h, w)``.
mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values ``'zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: interpolation flag.
- normalized_coordinates: Whether the homography assumes [-1, 1] normalized coordinates or not.
- normalized_homography: whether ``src_homo_dst`` is a normalized (destination→source)
- homography (``True``, default) or a pixel source→destination homography (``False``).
+ normalized_coordinates: whether ``src_homo_dst`` is in normalized :math:`[-1, 1]` coordinates
+ (``True``) or in pixel coordinates (``False``). Ignored when ``normalized_homography=False``.
+ normalized_homography: whether ``src_homo_dst`` is a destination→source homography in the coordinates
+ ``normalized_coordinates`` selects (``True``, default) or a pixel source→destination homography
+ (``False``).
Return:
Patch sampled at locations from source to destination.
@@ -1906,15 +1957,23 @@ def homography_warp(
)
if normalized_homography:
height, width = dsize
- grid = create_meshgrid(
- height,
- width,
- normalized_coordinates=normalized_coordinates,
- device=patch_src.device,
- dtype=patch_src.dtype,
- align_corners=align_corners,
- )
- warped_grid = warp_grid(grid, src_homo_dst)
+ if normalized_coordinates:
+ grid = create_meshgrid(
+ height,
+ width,
+ normalized_coordinates=True,
+ device=patch_src.device,
+ dtype=patch_src.dtype,
+ align_corners=align_corners,
+ )
+ warped_grid = warp_grid(grid, src_homo_dst)
+ else:
+ # A pixel homography lands on source pixels, which grid_sample reads normalized. The pixel arithmetic
+ # runs in at least float32, unaffected by autocast, then the grid returns to the homography's dtype.
+ warped_grid = _warp_pixel_grid(src_homo_dst, height, width)
+ warped_grid = _normalize_warped_pixel_grid(
+ warped_grid, patch_src.shape[-2], patch_src.shape[-1], align_corners
+ ).to(src_homo_dst.dtype)
return _torch_grid_sample(
patch_src, warped_grid, mode=mode, padding_mode=padding_mode, align_corners=align_corners
diff --git a/tests/geometry/transform/test_homography_warper.py b/tests/geometry/transform/test_homography_warper.py
index 0d0163a17..e577efc26 100644
--- a/tests/geometry/transform/test_homography_warper.py
+++ b/tests/geometry/transform/test_homography_warper.py
@@ -20,7 +20,7 @@ import torch
import kornia
from kornia.core.ops import eye_like
-from kornia.core.utils import _torch_inverse_cast
+from kornia.core.utils import _torch_grid_sample, _torch_inverse_cast
from testing.base import BaseTester
from testing.error import compute_patch_abs_error
@@ -391,6 +391,273 @@ class TestHomographyWarper(BaseTester):
# evaluate function gradient
self.gradcheck(warper, (patch_src, dst_homo_src), requires_grad=(True, False), nondet_tol=1e-8)
+ @staticmethod
+ def _pixel_warp(entry, image, src_homo_dst, dsize, **options):
+ # The three ways to warp with a pixel homography: the function, the module, and the module's cached grid.
+ if entry == "functional":
+ return kornia.geometry.transform.homography_warp(
+ image, src_homo_dst, dsize, normalized_coordinates=False, **options
+ )
+ warper = kornia.geometry.transform.HomographyWarper(*dsize, normalized_coordinates=False, **options)
+ if entry == "module":
+ return warper(image, src_homo_dst)
+ warper.precompute_warp_grid(src_homo_dst)
+ return warper(image)
+
+ @pytest.mark.parametrize("entry", ["functional", "module", "precomputed"])
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_pixel_coordinates_identity(self, entry, align_corners, device, dtype):
+ # With normalized_coordinates=False the homography is in pixels: an identity returns the input, and a
+ # smaller destination is the top-left crop of the source rather than a resize of it (#6170).
+ image = torch.arange(2 * 5 * 7, device=device, dtype=dtype).view(1, 2, 5, 7) / 70
+ identity = eye_like(3, image)
+
+ self.assert_close(self._pixel_warp(entry, image, identity, (5, 7), align_corners=align_corners), image)
+ self.assert_close(
+ self._pixel_warp(entry, image, identity, (3, 4), align_corners=align_corners), image[..., :3, :4]
+ )
+
+ @pytest.mark.parametrize("entry", ["functional", "module", "precomputed"])
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_pixel_coordinates_whole_pixel_translation(self, entry, align_corners, device, dtype):
+ # src_homo_dst maps destination pixels to source pixels, so a translation (tx, ty) samples
+ # out[y, x] = src[y + ty, x + tx], one homography per sample, and zeros where that leaves the source.
+ image = torch.arange(2 * 6 * 8, device=device, dtype=dtype).view(2, 1, 6, 8) / 96
+ src_homo_dst = eye_like(3, image).clone()
+ src_homo_dst[0, 0, 2] = 2.0
+ src_homo_dst[1, 0, 2] = -3.0
+ src_homo_dst[1, 1, 2] = 1.0
+ expected = torch.zeros_like(image)
+ expected[0, :, :, :6] = image[0, :, :, 2:]
+ expected[1, :, :5, 3:] = image[1, :, 1:, :5]
+
+ actual = self._pixel_warp(entry, image, src_homo_dst, (6, 8), align_corners=align_corners)
+ self.assert_close(actual, expected)
+
+ @pytest.mark.parametrize("entry", ["functional", "module", "precomputed"])
+ @pytest.mark.parametrize("align_corners", [True, False])
+ @pytest.mark.parametrize("padding_mode", ["zeros", "border", "reflection"])
+ def test_pixel_coordinates_match_warp_perspective(self, entry, align_corners, padding_mode, device, dtype):
+ # warp_perspective takes the source->destination pixel homography; its inverse is the destination->source
+ # pixel homography the pixel mode reads. Both normalize under the same align_corners, so they agree for every
+ # padding mode, here with a perspective term and a destination of another size than the source.
+ image = (torch.arange(2 * 3 * 7 * 9, device=device, dtype=dtype).view(2, 3, 7, 9) % 11) / 11
+ dst_trans_src = torch.tensor(
+ [
+ [[0.9, 0.1, 1.5], [-0.05, 1.1, -0.7], [0.01, -0.02, 1.0]],
+ [[1.2, 0.0, -2.0], [0.0, 0.8, 1.0], [0.0, 0.0, 1.0]],
+ ],
+ dtype=torch.float64,
+ )
+ # inverted in float64 on the CPU, which every device can then take in its own dtype
+ src_homo_dst = torch.linalg.inv(dst_trans_src).to(device=device, dtype=dtype)
+ dsize = (5, 11)
+
+ expected = kornia.geometry.transform.warp_perspective(
+ image,
+ dst_trans_src.to(device=device, dtype=dtype),
+ dsize,
+ align_corners=align_corners,
+ padding_mode=padding_mode,
+ )
+ actual = self._pixel_warp(
+ entry, image, src_homo_dst, dsize, align_corners=align_corners, padding_mode=padding_mode
+ )
+ # in half precision the two matrices are rounded separately, one before and one after the inversion
+ self.assert_close(actual, expected, low_tolerance=dtype in (torch.float16, torch.bfloat16))
+
+ @pytest.mark.parametrize("entry", ["functional", "module", "precomputed"])
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_pixel_coordinates_wide_identity(self, entry, align_corners, device, dtype):
+ # Pixel coordinates reach the image width, where float16 rounds them to half pixels from 512 and bfloat16 to
+ # whole pixels from 128. The pixel grid is warped and normalized in float32 and only the normalized grid
+ # returns to the homography's dtype, so a 640 px wide identity samples where the default normalized path
+ # does, and in float16 within an eighth of a pixel of every column. The image holds the column index.
+ width = 640
+ image = torch.arange(width, device=device).to(dtype).expand(1, 1, 3, width)
+ identity = eye_like(3, image)
+
+ actual = self._pixel_warp(entry, image, identity, (3, width), align_corners=align_corners)
+ normalized = kornia.geometry.transform.homography_warp(image, identity, (3, width), align_corners=align_corners)
+
+ # Interior columns only: the outermost ones border the zero padding, where any sub-pixel offset of the last
+ # column (value 639) costs a large value error. Values are column indices, so tolerances are in pixels.
+ actual, normalized, image = actual[..., 1:-1], normalized[..., 1:-1], image[..., 1:-1]
+ if dtype in (torch.float16, torch.bfloat16):
+ self.assert_close(actual, normalized, rtol=0, atol=0.125 if dtype == torch.float16 else 1.0)
+ else:
+ self.assert_close(actual, normalized)
+ # bfloat16 stores these column indices only to within 2 to 4, so it is checked against the default path alone
+ if dtype != torch.bfloat16:
+ max_error = 0.125 if dtype == torch.float16 else 1e-3
+ assert (actual.float() - image.float()).abs().max() <= max_error
+
+ @pytest.mark.parametrize("entry", ["functional", "module", "precomputed"])
+ def test_pixel_coordinates_backward_keeps_dtype(self, entry, device, dtype):
+ # The pixel grid is warped in float32 for a half homography and cast back: gradients still reach the image
+ # and the homography, finite and in their own dtype.
+ image = ((torch.arange(2 * 6 * 8, device=device) % 13) / 13).to(dtype).view(1, 2, 6, 8).requires_grad_()
+ src_homo_dst = torch.tensor(
+ [[[1.05, 0.02, 0.3], [0.01, 0.95, -0.4], [1e-3, -2e-3, 1.0]]], device=device, dtype=dtype
+ ).requires_grad_()
+
+ self._pixel_warp(entry, image, src_homo_dst, (5, 7)).float().square().sum().backward()
+
+ for tensor in (image, src_homo_dst):
+ assert tensor.grad is not None
+ assert tensor.grad.dtype == dtype
+ assert torch.isfinite(tensor.grad).all()
+ assert tensor.grad.abs().sum() > 0
+
+ @pytest.mark.parametrize(("default_dtype", "width"), [(torch.float16, 4096), (torch.bfloat16, 640)])
+ def test_pixel_coordinates_precomputed_under_half_default_dtype(self, default_dtype, width, device):
+ # A warper constructed under a half default dtype holds a half base grid, whose integer columns round from
+ # 2048 (float16) or 256 (bfloat16) on. The cached pixel grid is built like the direct one instead, so a
+ # cached identity samples every column of a float32 column-index image.
+ previous = torch.get_default_dtype()
+ try:
+ torch.set_default_dtype(default_dtype)
+ warper = kornia.geometry.transform.HomographyWarper(2, width, normalized_coordinates=False)
+ finally:
+ torch.set_default_dtype(previous)
+ image = torch.arange(width, device=device, dtype=torch.float32).expand(1, 1, 2, width)
+ identity = eye_like(3, image)
+
+ direct = warper(image, identity)
+ warper.precompute_warp_grid(identity)
+ cached = warper(image)
+
+ self.assert_close(cached, direct, rtol=0, atol=0)
+ self.assert_close(cached[..., 1:-1], image[..., 1:-1])
+
+ @pytest.mark.parametrize("entry", ["functional", "module", "precomputed"])
+ def test_autocast_does_not_reach_the_pixel_grid(self, entry, device):
+ # A caller's bfloat16 autocast ran the homography's matrix product in bfloat16 and rounded the pixel columns
+ # of a 640 px grid to whole pixels (x = 257 sampled 256, 639 fell outside the image); a grid cached inside
+ # autocast kept the error outside it. The pixel grid is warped with elementwise products, which autocast
+ # leaves alone.
+ if device.type not in ("cpu", "cuda"):
+ pytest.skip("CPU and CUDA autocast")
+ width = 640
+ image = torch.arange(width, device=device, dtype=torch.float32).expand(1, 1, 2, width)
+ identity = eye_like(3, image)
+ expected = self._pixel_warp(entry, image, identity, (2, width))
+
+ warper = kornia.geometry.transform.HomographyWarper(2, width, normalized_coordinates=False)
+ with torch.autocast(device.type, dtype=torch.bfloat16):
+ actual = self._pixel_warp(entry, image, identity, (2, width))
+ warper.precompute_warp_grid(identity)
+ cached_inside = warper(image)
+
+ assert actual.dtype == torch.float32
+ self.assert_close(actual, expected, rtol=0, atol=0)
+ self.assert_close(cached_inside, expected, rtol=0, atol=0)
+ self.assert_close(expected[..., 1:-1], image[..., 1:-1])
+
+ @pytest.mark.parametrize("autocast_dtype,width", [(torch.bfloat16, 640), (torch.float16, 4096)])
+ @pytest.mark.parametrize("align_corners", [True, False])
+ @pytest.mark.parametrize("local_homography", [True, False])
+ def test_pixel_coordinates_torchscript_autocast(
+ self, autocast_dtype, width, align_corners, local_homography, device
+ ):
+ if device.type not in ("cpu", "cuda"):
+ pytest.skip("CPU and CUDA autocast")
+ # A scripted call cannot leave a caller's autocast region, which would round the pixel coordinates of a
+ # matrix product at these widths and sample padding even under an identity homography.
+ image = torch.arange(width, device=device, dtype=torch.float32).expand(2, 1, 2, width)
+ src_homo_dst = eye_like(3, image)
+ src_homo_dst[1, 0, 2] = -1.0
+ if not local_homography:
+ src_homo_dst = src_homo_dst.unsqueeze(1)
+ scripted = torch.jit.script(kornia.geometry.transform.homography_warp)
+ expected = kornia.geometry.transform.homography_warp(
+ image, src_homo_dst, (2, width), normalized_coordinates=False, align_corners=align_corners
+ )
+
+ with torch.autocast(device.type, dtype=autocast_dtype):
+ actual = scripted(
+ image, src_homo_dst, (2, width), normalized_coordinates=False, align_corners=align_corners
+ )
+
+ assert actual.dtype == image.dtype
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+ def test_pixel_coordinates_torchscript(self, device, dtype):
+ # A scripted call computes the eager pixel grid, bit for bit.
+ image = (torch.arange(2 * 5 * 7, device=device) % 11 / 11).to(dtype).view(1, 2, 5, 7)
+ src_homo_dst = torch.tensor(
+ [[[1.05, 0.02, 0.3], [0.01, 0.95, -0.4], [1e-3, -2e-3, 1.0]]], device=device, dtype=dtype
+ )
+ scripted = torch.jit.script(kornia.geometry.transform.homography_warp)
+
+ actual = scripted(image, src_homo_dst, (4, 6), normalized_coordinates=False)
+ expected = kornia.geometry.transform.homography_warp(image, src_homo_dst, (4, 6), normalized_coordinates=False)
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("scale", [1.0, -0.5, 8.0])
+ def test_pixel_coordinates_torchscript_backward(self, scale, device, dtype):
+ # A scripted call keeps the eager values and gradients for scaled homographies.
+ image = torch.linspace(0, 1, 35, device=device, dtype=dtype).view(1, 1, 5, 7).requires_grad_()
+ matrix = torch.tensor([[[1.05, 0.02, 0.3], [0.01, 0.95, 0.4], [1e-3, 2e-3, 1.0]]], device=device, dtype=dtype)
+ matrix = (matrix * scale).requires_grad_()
+ scripted = torch.jit.script(kornia.geometry.transform.homography_warp)
+ expected = kornia.geometry.transform.homography_warp(image, matrix, (3, 4), normalized_coordinates=False)
+ actual = scripted(image, matrix, (3, 4), normalized_coordinates=False)
+ expected_grads = torch.autograd.grad(expected.sum(), (image, matrix))
+ actual_grads = torch.autograd.grad(actual.sum(), (image, matrix))
+
+ self.assert_close(actual, expected)
+ for actual_grad, expected_grad in zip(actual_grads, expected_grads):
+ self.assert_close(actual_grad, expected_grad)
+
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_normalized_coordinates_path_is_the_plain_grid_warp(self, align_corners, device, dtype):
+ # The default normalized path is grid_sample over warp_grid of a normalized meshgrid, bit for bit; the
+ # pixel-mode normalization must not reach it (#6170).
+ image = (torch.arange(2 * 5 * 6, device=device, dtype=dtype).view(1, 2, 5, 6) % 7) / 7
+ src_homo_dst = torch.tensor(
+ [[[0.95, 0.05, 0.1], [-0.03, 1.05, -0.08], [0.02, -0.01, 1.0]]], device=device, dtype=dtype
+ )
+ grid = kornia.geometry.create_meshgrid(
+ 4, 3, normalized_coordinates=True, device=device, dtype=dtype, align_corners=align_corners
+ )
+ warped_grid = kornia.geometry.transform.warp_grid(grid, src_homo_dst)
+ expected = _torch_grid_sample(image, warped_grid, align_corners=align_corners)
+
+ actual = kornia.geometry.transform.homography_warp(image, src_homo_dst, (4, 3), align_corners=align_corners)
+ warper = kornia.geometry.transform.HomographyWarper(4, 3, align_corners=align_corners)
+ direct = warper(image, src_homo_dst)
+ warper.precompute_warp_grid(src_homo_dst)
+ precomputed = warper(image)
+ # the cached path warps the module's own base grid, built once in the default dtype
+ expected_precomputed = _torch_grid_sample(
+ image, kornia.geometry.transform.warp_grid(warper.grid, src_homo_dst), align_corners=align_corners
+ )
+
+ self.assert_close(actual, expected, rtol=0, atol=0)
+ self.assert_close(direct, expected, rtol=0, atol=0)
+ self.assert_close(precomputed, expected_precomputed, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_gradcheck_pixel_coordinates(self, align_corners, device):
+ # Gradients reach both the image and the pixel homography; sub-pixel sample positions keep the bilinear
+ # kinks away from the finite differences.
+ image = torch.rand(1, 2, 5, 6, device=device, dtype=torch.float64)
+ src_homo_dst = torch.tensor(
+ [[[1.05, 0.02, 0.3], [0.01, 0.95, -0.4], [1e-3, -2e-3, 1.0]]], device=device, dtype=torch.float64
+ )
+
+ def warp(image, src_homo_dst):
+ return kornia.geometry.transform.homography_warp(
+ image, src_homo_dst, (4, 5), align_corners=align_corners, normalized_coordinates=False
+ )
+
+ warper = kornia.geometry.transform.HomographyWarper(
+ 4, 5, align_corners=align_corners, normalized_coordinates=False
+ )
+ self.gradcheck(warp, (image, src_homo_dst), nondet_tol=1e-8)
+ self.gradcheck(warper, (image, src_homo_dst), nondet_tol=1e-8)
+
@pytest.mark.parametrize("batch_size", [1, 2, 3])
@pytest.mark.parametrize("align_corners", [True, False])
@pytest.mark.parametrize("normalized_coordinates", [True, False])
@@ -415,6 +682,12 @@ class TestHomographyWarper(BaseTester):
homo_delta = torch.rand_like(dst_homo_src) * 0.3
dst_homo_src_i = dst_homo_src + homo_delta
+ # the same warp as a destination->source pixel homography: N^-1 H N, with N this align_corners' normalization
+ pixel_homo = kornia.geometry.conversions.denormalize_homography(
+ dst_homo_src_i, (height, width), (height, width), align_corners=align_corners
+ )
+ if not normalized_coordinates:
+ dst_homo_src_i = pixel_homo
# transform the points with and without jit
patch_dst = kornia.geometry.transform.homography_warp(
@@ -433,6 +706,16 @@ class TestHomographyWarper(BaseTester):
)
self.assert_close(patch_dst, patch_dst_optimized, atol=1e-4, rtol=1e-4)
+ # compiled-vs-eager passes on a wrong result too (#6170): also check the compiled output against an eager
+ # reference that does not run this code, warp_perspective of the source->destination pixel homography. It
+ # runs in float64 on the CPU: in float32 its own error reaches 5e-4 on torch 2.9.1 for these perspectives.
+ expected = kornia.geometry.transform.warp_perspective(
+ patch_src.cpu().double(),
+ torch.linalg.inv(pixel_homo.cpu().double()),
+ (height, width),
+ align_corners=align_corners,
+ ).to(device=device, dtype=dtype)
+ self.assert_close(patch_dst_optimized, expected, atol=1e-4, rtol=1e-4)
class TestHomographyNormalTransform(BaseTester):