Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): honor align_corners in coordinate normalization (#3904… (#3945)

Leonardo Vannibac094d3d18e
diff --git a/changelog.d/3945.breaking.md b/changelog.d/3945.breaking.md
new file mode 100644
index 000000000..c049744c5
--- /dev/null
+++ b/changelog.d/3945.breaking.md
@@ -0,0 +1,21 @@
+Outputs of `warp_perspective`, `warp_affine`, `homography_warp`, `HomographyWarper`,
+`warp_image_tps`, `crop_by_transform_mat` and `shear` change under `align_corners=False`. They now
+match the `align_corners=True` result up to out-of-bounds handling, instead of carrying a spurious
+sub-pixel scale and shift. `align_corners=True` call sites are bit-identical.
+
+**Several of these default to `align_corners=False`, so plain calls that pass no flag change too.**
+Measured on a 4x5 `arange` image with an identity transform, `float64`, as `max|out - in|`:
+
+| Call, default arguments | before | after |
+|---|---|---|
+| `homography_warp(x, I, (4, 5))` | 14.25 | 1.8e-15 |
+| `HomographyWarper(4, 5)(x, I)` | 14.25 | 1.8e-15 |
+| `warp_image_tps(x, pts, kernel, affine)` | 14.25 | 1.8e-15 |
+| `ImageRegistrator("homography").warp_src_into_dst(x)`, identity model | 14.25 | 0.0 |
+| `shear(ones(1, 1, 4, 4), [[0.5, 0.0]])`, first row | `0.75, 1, 1, 1` | `1, 1, 1, 1` |
+
+The augmentations that default to `align_corners=False` (`RandomAffine`, `RandomPerspective`,
+`RandomShear`, `RandomTranslate`, `RandomThinPlateSpline`) sample different pixels for the same
+reason; their transform matrices are unchanged. At those defaults an identity transform is now
+actually the identity: `RandomPerspective(distortion_scale=0.)` goes from 0.734 to 6e-07 and
+`RandomThinPlateSpline(scale=0.)` from 0.734 to 1.5e-08 on a 6x8 ramp. Refs #3904, #4411.
diff --git a/changelog.d/3945.fixed.md b/changelog.d/3945.fixed.md
new file mode 100644
index 000000000..25cfa7662
--- /dev/null
+++ b/changelog.d/3945.fixed.md
@@ -0,0 +1,13 @@
+`warp_perspective`, `warp_affine`, `homography_warp`, `HomographyWarper` and `warp_image_tps` now
+build their sampling grid and homography normalization under the same `align_corners` convention
+they pass to `grid_sample`. Previously the grid was always corner-aligned, so with
+`align_corners=False` an identity homography did not reproduce its input (max deviation `11.25`
+on a 4x4 `arange` image) and a whole-pixel translation resampled at fractional offsets;
+`warp_image_tps` was affected on its default path. `create_meshgrid`, `normal_transform_pixel`,
+`normalize_homography` and `denormalize_homography` gain an `align_corners` parameter (last,
+default `True`, so existing calls are unchanged). `crop_by_transform_mat` drops the #3650
+correction matrix and the 1-pixel `warp_affine` fallback that worked around the mismatch, so
+1-pixel outputs are exact under both settings. `normal_transform_pixel` also writes the
+`align_corners=False` offset as a single division, so eager and graph capture agree bit for bit at
+every size rather than differing by one `float32` step at 5 of the first 4999.
+Fixes #3904, #3928, #3929, #4411.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index d900d15df..cf46e9ce4 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -132,6 +132,11 @@ Transformation matrices and homographies
b = homography_warp(img, M_norm_inv, (16, 8), align_corners=True)
assert torch.allclose(a, b, atol=1e-5)
+``normalize_homography`` takes its own ``align_corners`` (default ``True``),
+and it must match the one you pass to the warp β€” the normalized ``[-1, 1]``
+coordinates mean different things under the two conventions. Above, both are
+``True``; note that ``homography_warp`` alone would default to ``False``.
+
``align_corners`` defaults
--------------------------
@@ -148,7 +153,7 @@ with ``torch.nn.functional.interpolate``/``grid_sample``, pass
- ``True``
* - ``resize``
- ``None`` (PyTorch's per-mode default)
- * - ``homography_warp``
+ * - ``homography_warp``, ``elastic_transform2d``
- ``False``
* - ``undistort_image``
- ``True``
@@ -156,6 +161,51 @@ with ``torch.nn.functional.interpolate``/``grid_sample``, pass
- ``True``
* - ``DepthWarper`` / ``depth_warp``
- ``True`` (default)
+ * - ``remap``
+ - ``None`` (resolved to ``False`` internally)
+
+The flag selects only how Kornia normalizes coordinates for ``grid_sample``
+(``True``: pixel *centers* 0 and ``size-1`` sit at ``Β±1``; ``False``: the outer
+pixel *edges* do). Transforms you pass in are pixel-space either way, so a warp
+that should be an identity is one under both settings, and ``warp_affine`` and
+``warp_perspective`` agree with each other:
+
+.. code-block:: python
+
+ import torch
+ from kornia.geometry.transform import get_perspective_transform, warp_affine, warp_perspective
+
+ img = torch.arange(16.0).view(1, 1, 4, 4)
+ pts = torch.tensor([[[0.0, 0.0], [3.0, 0.0], [3.0, 3.0], [0.0, 3.0]]])
+ M = get_perspective_transform(pts, pts) # identity
+
+ for align_corners in (True, False):
+ a = warp_affine(img, M[:, :2, :], (4, 4), align_corners=align_corners)
+ p = warp_perspective(img, M, (4, 4), align_corners=align_corners)
+ assert torch.allclose(a, img, atol=1e-4)
+ assert torch.allclose(p, img, atol=1e-4)
+
+Where the two settings genuinely differ is out-of-bounds sampling, since ``Β±1``
+covers a slightly different extent of the source image.
+
+.. warning::
+
+ :func:`kornia.geometry.transform.remap` is the 2D exception left: it normalizes its
+ pixel maps with the ``align_corners=True`` convention regardless of the flag it passes
+ to ``grid_sample``, so with its default (``None``, i.e. ``False``) even an identity
+ pixel map resamples the image, by ``11.25`` on a 4x4 ``arange`` image. Pass
+ ``align_corners=True`` until this is fixed. Tracked in
+ `#4504 <https://github.com/kornia/kornia/issues/4504>`_.
+
+ The 3-D warps are the other exception. ``normal_transform_pixel3d`` and
+ ``normalize_homography3d`` take no ``align_corners`` at all, so
+ :func:`kornia.geometry.transform.warp_affine3d` and
+ :func:`kornia.geometry.transform.warp_perspective3d` normalize with the corner-aligned
+ convention whatever flag they pass to ``grid_sample``, and have the same mismatch at
+ ``align_corners=False``: an identity ``warp_perspective3d`` changes a 4x4x4 ``arange``
+ volume by up to ``55.1`` there, against exactly ``0`` at ``align_corners=True``. Pass
+ ``align_corners=True`` to the 3-D warps until this is fixed. Tracked in
+ `#4503 <https://github.com/kornia/kornia/issues/4503>`_.
Bounding boxes
--------------
diff --git a/kornia/augmentation/_2d/geometric/perspective.py b/kornia/augmentation/_2d/geometric/perspective.py
index 07867886a..5a9ac1f40 100644
--- a/kornia/augmentation/_2d/geometric/perspective.py
+++ b/kornia/augmentation/_2d/geometric/perspective.py
@@ -58,13 +58,13 @@ class RandomPerspective(GeometricAugmentationBase2D):
>>> aug = RandomPerspective(0.5, p=0.5)
>>> out = aug(inputs)
>>> out
- tensor([[[[0.0000, 0.2289, 0.0000],
- [0.0000, 0.4800, 0.0000],
+ tensor([[[[0.2795, 0.3852, 0.0000],
+ [0.0000, 0.6243, 0.0000],
[0.0000, 0.0000, 0.0000]]]])
>>> aug.inverse(out)
- tensor([[[[0.0500, 0.0961, 0.0000],
- [0.2011, 0.3144, 0.0000],
- [0.0031, 0.0130, 0.0053]]]])
+ tensor([[[[0.3417, 0.3022, 0.0436],
+ [0.3767, 0.4769, 0.1879],
+ [0.1434, 0.1958, 0.1091]]]])
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.randn(1, 3, 32, 32)
diff --git a/kornia/augmentation/_2d/geometric/translate.py b/kornia/augmentation/_2d/geometric/translate.py
index 967fcfff3..c3f7ff8fd 100644
--- a/kornia/augmentation/_2d/geometric/translate.py
+++ b/kornia/augmentation/_2d/geometric/translate.py
@@ -56,15 +56,15 @@ class RandomTranslate(GeometricAugmentationBase2D):
>>> aug = RandomTranslate((-0.2, 0.2), (-0.1, 0.1), p=1.)
>>> out = aug(input)
>>> out, aug.transform_matrix
- (tensor([[[[0.3403, 0.6439, 0.2920],
- [0.1377, 0.3383, 0.5569],
- [0.3226, 0.6909, 0.4844]]]]), tensor([[[ 1.0000, 0.0000, 0.1588],
+ (tensor([[[[0.3897, 0.6847, 0.2314],
+ [0.1384, 0.3297, 0.5771],
+ [0.3749, 0.7565, 0.4780]]]]), tensor([[[ 1.0000, 0.0000, 0.1588],
[ 0.0000, 1.0000, -0.0907],
[ 0.0000, 0.0000, 1.0000]]]))
>>> aug.inverse(out)
- tensor([[[[0.3565, 0.4839, 0.1922],
- [0.2164, 0.4134, 0.3968],
- [0.3797, 0.6075, 0.3765]]]])
+ tensor([[[[0.3969, 0.5571, 0.1770],
+ [0.1930, 0.3910, 0.4591],
+ [0.4113, 0.6812, 0.4096]]]])
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.randn(1, 3, 32, 32)
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index d6cf49d66..e8c8ef075 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -1839,7 +1839,10 @@ def angle_to_rotation_matrix(angle: torch.Tensor) -> torch.Tensor:
def normalize_homography(
- dst_pix_trans_src_pix: torch.Tensor, dsize_src: tuple[int, int], dsize_dst: tuple[int, int]
+ dst_pix_trans_src_pix: torch.Tensor,
+ dsize_src: tuple[int, int],
+ dsize_dst: tuple[int, int],
+ align_corners: bool = True,
) -> torch.Tensor:
r"""Normalize a given homography in pixels to [-1, 1].
@@ -1867,9 +1870,10 @@ def normalize_homography(
- batching is per sample: element ``i`` of the output depends only on
element ``i`` of the input
- the :math:`[-1, 1]` frames are
- :func:`~kornia.geometry.conversions.normal_transform_pixel`'s
- **corner-aligned** ones, inherited unconditionally β€” see the
- convention warning below
+ :func:`~kornia.geometry.conversions.normal_transform_pixel`'s, under
+ the convention ``align_corners`` selects: **corner-aligned** by
+ default (``True``), half-pixel for ``False`` β€” see the convention
+ warning below
- the shape guard accepts a :math:`(3, 3)` or a :math:`(B, 3, 3)`
matrix and nothing else. An unbatched ``(3, 3)`` is promoted to
``(1, 3, 3)`` β€” the returned matrix is batched even though the input
@@ -1955,26 +1959,37 @@ def normalize_homography(
Tracked in `#3959 <https://github.com/kornia/kornia/issues/3959>`_.
.. warning::
- The :math:`[-1, 1]` frames are corner-aligned
- (``align_corners=True``) and there is no way to select the half-pixel
- convention: :func:`~kornia.geometry.conversions.denormalize_homography`,
- :func:`~kornia.geometry.conversions.normalize_homography3d` and
- :func:`~kornia.geometry.transform.warp_perspective` all inherit it. That
- is a separate fact from why an identity ``warp_perspective`` called with
- ``align_corners=False`` does not reproduce its input β€” on a 4x4
- ``arange`` image the maximum deviation is ``11.25``, against ``1.4e-05``
- at ``align_corners=True``. This function is not that cause: for equal
- source and destination sizes, an identity homography normalizes back to
- the identity to within a single ``float32`` rounding step β€” the
- deviation is exactly ``0`` at most equal sizes and ``5.96e-08`` at the
- rest, with the ``4x4`` case above among the latter; which size lands
- where is a property of the inverse-and-matmul chain and not a rule
- about the scale, so read the size you care about rather than a pattern
- off these β€” and ``warp_perspective``'s
- ``11.25`` comes from its own ``create_meshgrid``-built, corner-aligned
- grid being sampled by ``grid_sample`` under the ``align_corners=False``
- half-pixel convention. Recorded in
+ The :math:`[-1, 1]` frames follow this function's own ``align_corners``,
+ which defaults to ``True`` (corner-aligned) β€” **not** the ``False`` that
+ :py:func:`torch.nn.functional.grid_sample` and
+ :func:`~kornia.geometry.transform.homography_warp` default to. The
+ value passed here must match the ``grid_sample`` call that consumes the
+ result; a mismatch applies a spurious sub-pixel scale and shift.
+ :func:`~kornia.geometry.transform.warp_perspective`,
+ :func:`~kornia.geometry.transform.warp_affine` and
+ :func:`~kornia.geometry.transform.homography_warp` forward their own
+ flag, so they are consistent under both settings. Before that was the
+ case, an identity ``warp_perspective`` at ``align_corners=False``
+ deviated from its input by ``11.25`` on a 4x4 ``arange`` image, against
+ ``1.4e-05`` at ``align_corners=True``; the cause was the corner-aligned
+ grid being sampled under the half-pixel convention, not this function.
+ For equal source and destination sizes an identity homography
+ normalizes back to the identity to within a single ``float32`` rounding
+ step under either convention β€” exactly ``0`` at most sizes and
+ ``5.96e-08`` at the rest. *Which* sizes land where differs between the
+ two conventions, because it is a property of the inverse-and-matmul
+ chain rather than of the scale, so read the size you care about rather
+ than a pattern off any list. At the default ``align_corners=True``,
+ swept over equal sizes 2..32, the residual is ``5.96e-08`` at 4, 6, 7,
+ 11, 13, 14, 21, 25 and 27 and exactly ``0`` everywhere else; ``4x4`` is
+ in that first group, which is where the ``1.4e-05`` figure above comes
+ from. Recorded in
`#3904 <https://github.com/kornia/kornia/issues/3904>`_.
+ :func:`~kornia.geometry.conversions.normalize_homography3d` still has
+ no ``align_corners`` parameter and is corner-aligned unconditionally, so
+ :func:`~kornia.geometry.transform.warp_affine3d` keeps this mismatch at
+ ``align_corners=False``. Tracked in
+ `#4503 <https://github.com/kornia/kornia/issues/4503>`_.
Args:
dst_pix_trans_src_pix: homography/ies from source to destination to be
@@ -1982,6 +1997,11 @@ def normalize_homography(
is promoted to :math:`(1, 3, 3)`
dsize_src: size of the source image (height, width).
dsize_dst: size of the destination image (height, width).
+ align_corners: which :py:func:`torch.nn.functional.grid_sample` convention the
+ normalized :math:`[-1, 1]` coordinates follow, forwarded to
+ :func:`normal_transform_pixel`. Must match the ``align_corners`` of the
+ ``grid_sample`` call that ultimately consumes the result, otherwise the warp
+ picks up a spurious sub-pixel scale and shift.
Returns:
the normalized homography of shape :math:`(B, 3, 3)`.
@@ -1998,12 +2018,16 @@ def normalize_homography(
dst_h, dst_w = dsize_dst
# compute the transformation pixel/norm for src/dst
- src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel(src_h, src_w).to(dst_pix_trans_src_pix)
+ src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel(src_h, src_w, align_corners=align_corners).to(
+ dst_pix_trans_src_pix
+ )
# Closed-form 3x3 inverse of the (well-conditioned) pixel-normalization matrix: cusolver-free,
# so homography normalization runs on the Jetson wheel where ``torch.linalg.inv`` dlopen-fails.
src_pix_trans_src_norm = _inverse_3x3_closed_form(src_norm_trans_src_pix)
- dst_norm_trans_dst_pix: torch.Tensor = normal_transform_pixel(dst_h, dst_w).to(dst_pix_trans_src_pix)
+ dst_norm_trans_dst_pix: torch.Tensor = normal_transform_pixel(dst_h, dst_w, align_corners=align_corners).to(
+ dst_pix_trans_src_pix
+ )
# compute chain transformations
dst_norm_trans_src_norm: torch.Tensor = dst_norm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_pix_trans_src_norm)
@@ -2016,6 +2040,7 @@ def normal_transform_pixel(
eps: float = 1e-14,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
+ align_corners: bool = True,
) -> torch.Tensor:
r"""Compute the normalization matrix from image size in pixels to [-1, 1].
@@ -2025,9 +2050,11 @@ def normal_transform_pixel(
``x`` indexing columns and scaled by ``width`` and ``y`` indexing rows
and scaled by ``height``. The positional argument order is the other
way round, ``(height, width)``
- - the mapping is **corner-aligned**: scale ``2 / (size - 1)``, offset
- ``-1``, so the pixel *centres* ``0`` and ``size - 1`` map to exactly
- ``-1`` and ``+1``. ``normal_transform_pixel(4, 5)`` has rows
+ - the mapping is **corner-aligned by default**: scale ``2 / (size - 1)``,
+ offset ``-1``, so the pixel *centres* ``0`` and ``size - 1`` map to
+ exactly ``-1`` and ``+1``. ``align_corners=False`` selects the
+ half-pixel mapping instead; see the ``align_corners`` bullet below.
+ ``normal_transform_pixel(4, 5)`` has rows
``[0.5, 0.0, -1.0]`` and ``[0.0, 0.6667, -1.0]``, and sends the pixels
``(0, 0)``, ``(4, 3)`` and ``(2, 1.5)`` to ``(-1, -1)``, ``(1, 1)``
and ``(0, 0)``
@@ -2073,15 +2100,21 @@ def normal_transform_pixel(
``2 * 2 ** -10`` rather than ``2 * 2 ** -23`` for ``TF32``
``float32`` β€” which is what the pin enforces there, so such a
configuration widens the bound rather than exceeding it
- - the convention is applied **unconditionally** β€” there is no
- ``align_corners`` parameter β€” and
- :func:`~kornia.geometry.conversions.normalize_homography` and its
- siblings inherit it; see the convention warning there
+ - the convention is selected by ``align_corners`` (``True`` by
+ default). ``False`` is the half-pixel mapping with scale ``2 / size``
+ and offset ``1 / size - 1``, so that :math:`\pm 1` fall on the outer
+ pixel *edges*. :func:`~kornia.geometry.conversions.normalize_homography`
+ and :func:`~kornia.geometry.conversions.denormalize_homography` forward
+ their own ``align_corners`` here, while
+ :func:`~kornia.geometry.conversions.normal_transform_pixel3d` is still
+ corner-aligned unconditionally; see the convention warning there
- a singleton axis maps its only pixel to the centre of the normalized
- range: that axis uses scale ``1`` and offset ``0``. The unit scale is
- an invertible extension outside the lone valid coordinate, allowing
- homography composition to handle one-pixel source and destination
- sizes. Zero and negative sizes raise ``ValueError``
+ range. Under ``align_corners=True`` that axis uses scale ``1`` and
+ offset ``0`` β€” an invertible extension outside the lone valid
+ coordinate, allowing homography composition to handle one-pixel
+ source and destination sizes. Under ``align_corners=False`` the
+ general formula already lands there (scale ``2``, offset ``0``) and no
+ special case is needed. Zero and negative sizes raise ``ValueError``
- with ``dtype=None`` the matrix is built from Python floats, so it
takes ``torch.get_default_dtype()``: ``float32`` by default, and
``float64`` under ``torch.set_default_dtype(torch.float64)``. An
@@ -2110,6 +2143,11 @@ def normal_transform_pixel(
eps: deprecated compatibility parameter. It is ignored.
device: device to place the result on.
dtype: dtype of the result. ``None`` means ``torch.get_default_dtype()``.
+ align_corners: which :py:func:`torch.nn.functional.grid_sample` convention to
+ normalize to. ``True`` maps pixel centers :math:`[0, size-1]` to
+ :math:`[-1, 1]`; ``False`` uses the half-pixel mapping
+ :math:`x_{norm} = (2x + 1) / W - 1`, where :math:`\pm 1` are the outer pixel
+ *edges*.
Returns:
normalized transform with shape :math:`(1, 3, 3)`.
@@ -2130,10 +2168,22 @@ def normal_transform_pixel(
# Eager and TorchScript take the scalar branch, which is an order of magnitude
# cheaper on this hot path. Graph capture takes the tensor form below so symbolic
# sizes retain the singleton decision.
- sx = 1.0 if width == 1 else 2.0 / (width - 1.0)
- sy = 1.0 if height == 1 else 2.0 / (height - 1.0)
- tx = 0.0 if width == 1 else -1.0
- ty = 0.0 if height == 1 else -1.0
+ if align_corners:
+ sx = 1.0 if width == 1 else 2.0 / (width - 1.0)
+ sy = 1.0 if height == 1 else 2.0 / (height - 1.0)
+ tx = 0.0 if width == 1 else -1.0
+ ty = 0.0 if height == 1 else -1.0
+ else:
+ # Half-pixel mapping. It is finite for a size of 1 and lands that pixel on the
+ # centre (scale 2, offset 0), so it needs no singleton special case. The offset is
+ # written as a single division rather than ``1 / size - 1`` so that the graph-capture
+ # branch below, which evaluates it in float32 instead of Python doubles, rounds once
+ # and stays bit-identical to this one; the two-step form differs by one float32 step
+ # at 5 of the first 4999 sizes.
+ sx = 2.0 / width
+ sy = 2.0 / height
+ tx = (1.0 - width) / width
+ ty = (1.0 - height) / height
tr_mat = torch.tensor([[sx, 0.0, tx], [0.0, sy, ty], [0.0, 0.0, 1.0]], device=device, dtype=dtype)
else:
# Low-precision floating types cannot represent every practical image size exactly
@@ -2149,12 +2199,19 @@ def normal_transform_pixel(
one = torch.ones((), device=device, dtype=work_dtype)
zero = torch.zeros((), device=device, dtype=work_dtype)
- # A singleton axis has no extent. Map its only pixel to the normalized centre
- # while keeping the homogeneous transform invertible for homography composition.
- sx_t = torch.where(width_t == 1, one, 2.0 / (width_t - 1.0))
- sy_t = torch.where(height_t == 1, one, 2.0 / (height_t - 1.0))
- tx_t = torch.where(width_t == 1, zero, -one)
- ty_t = torch.where(height_t == 1, zero, -one)
+ if align_corners:
+ # A singleton axis has no extent. Map its only pixel to the normalized centre
+ # while keeping the homogeneous transform invertible for homography composition.
+ sx_t = torch.where(width_t == 1, one, 2.0 / (width_t - 1.0))
+ sy_t = torch.where(height_t == 1, one, 2.0 / (height_t - 1.0))
+ tx_t = torch.where(width_t == 1, zero, -one)
+ ty_t = torch.where(height_t == 1, zero, -one)
+ else:
+ # Single division, matching the scalar branch above bit for bit.
+ sx_t = 2.0 / width_t
+ sy_t = 2.0 / height_t
+ tx_t = (one - width_t) / width_t
+ ty_t = (one - height_t) / height_t
# Construct the matrix in one shot (no in-place mutation).
tr_mat = torch.stack(
@@ -2178,8 +2235,9 @@ def normal_transform_pixel3d(
- the 3-D counterpart of
:func:`~kornia.geometry.conversions.normal_transform_pixel`: same
corner-aligned ``2 / (size - 1)`` scaling with offset ``-1``, same
- unconditional application, same ``dtype=None`` /
- ``torch.get_default_dtype()`` rule, and likewise **never batched**.
+ ``dtype=None`` / ``torch.get_default_dtype()`` rule, and likewise
+ **never batched**. Unlike the 2-D function it has no ``align_corners``
+ parameter, so it applies that scaling unconditionally.
Singleton axes use the same invertible centre mapping, and zero or
negative sizes raise ``ValueError``. Only the lines below differ
- the result has shape :math:`(1, 4, 4)` and acts on homogeneous
@@ -2281,7 +2339,10 @@ def normal_transform_pixel3d(
def denormalize_homography(
- dst_pix_trans_src_pix: torch.Tensor, dsize_src: tuple[int, int], dsize_dst: tuple[int, int]
+ dst_pix_trans_src_pix: torch.Tensor,
+ dsize_src: tuple[int, int],
+ dsize_dst: tuple[int, int],
+ align_corners: bool = True,
) -> torch.Tensor:
r"""De-normalize a given homography in pixels from [-1, 1] to actual height and width.
@@ -2293,12 +2354,13 @@ def denormalize_homography(
source pixels to destination pixels. Everything else β€” the
``(height, width)`` ``dsize`` tuples, ``dsize_src`` on the right and
``dsize_dst`` on the left, ``(x, y, 1)`` column vectors, per-sample
- batching, the corner-aligned frames β€” is as documented there, and so
+ batching, the ``align_corners``-selected frames β€” is as documented
+ there, and so
is the shape guard: this function carries the same one and rejects
the same shapes. That function's dtype-pass-through
(`#3958 <https://github.com/kornia/kornia/issues/3958>`_), int64-handling
(`#3959 <https://github.com/kornia/kornia/issues/3959>`_ β€” this
- function's own clause there) and corner-alignment (`#3904
+ function's own clause there) and ``align_corners`` (`#3904
<https://github.com/kornia/kornia/issues/3904>`_) warnings apply
here too. The exception is the closed-form-inverse warning: in eager
mode this function inverts through ``torch.linalg.inv`` rather than
@@ -2342,6 +2404,9 @@ def denormalize_homography(
which is promoted to :math:`(1, 3, 3)`
dsize_src: size of the source image (height, width).
dsize_dst: size of the destination image (height, width).
+ align_corners: which :py:func:`torch.nn.functional.grid_sample` convention the
+ incoming normalized coordinates follow. Must match the value used to produce
+ them, so that this function inverts :func:`normalize_homography`.
Returns:
the denormalized homography of shape :math:`(B, 3, 3)`.
@@ -2358,9 +2423,13 @@ def denormalize_homography(
dst_h, dst_w = dsize_dst
# compute the transformation pixel/norm for src/dst
- src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel(src_h, src_w).to(dst_pix_trans_src_pix)
+ src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel(src_h, src_w, align_corners=align_corners).to(
+ dst_pix_trans_src_pix
+ )
- dst_norm_trans_dst_pix: torch.Tensor = normal_transform_pixel(dst_h, dst_w).to(dst_pix_trans_src_pix)
+ dst_norm_trans_dst_pix: torch.Tensor = normal_transform_pixel(dst_h, dst_w, align_corners=align_corners).to(
+ dst_pix_trans_src_pix
+ )
dst_denorm_trans_dst_pix = _torch_inverse_cast(dst_norm_trans_dst_pix)
# compute chain transformations
dst_norm_trans_src_norm: torch.Tensor = dst_denorm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_norm_trans_src_pix)
@@ -2377,12 +2446,13 @@ def normalize_homography3d(
:func:`~kornia.geometry.conversions.normalize_homography`: same
composition ``N_dst @ H @ inv(N_src)``, same source-to-destination
direction re-expressed in normalized frames, same ``dsize_src`` on the
- right and ``dsize_dst`` on the left, and the same corner-aligned
- frames β€” with
+ right and ``dsize_dst`` on the left, and corner-aligned frames β€” with
:func:`~kornia.geometry.conversions.normal_transform_pixel3d` in place
- of the 2-D helper. It is **not** the 2-D function with wider matrices,
- though: the shapes, the missing inverse and β€” least visibly β€” the
- inversion routine all differ, as the bullets below record
+ of the 2-D helper. Unlike the 2-D function it has no ``align_corners``
+ parameter, so its frames are corner-aligned unconditionally. It is
+ **not** the 2-D function with wider matrices, though: the shapes, the
+ missing inverse and β€” least visibly β€” the inversion routine all
+ differ, as the bullets below record
- **the two do not invert their normalization matrix by the same
routine**, and the difference reaches callers. This function inverts
with ``torch.linalg.inv``;
diff --git a/kornia/geometry/grid.py b/kornia/geometry/grid.py
index 76bf8c246..0baf4eff2 100644
--- a/kornia/geometry/grid.py
+++ b/kornia/geometry/grid.py
@@ -29,8 +29,9 @@ def create_meshgrid(
normalized_coordinates: bool = True,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
+ align_corners: bool = True,
) -> torch.Tensor:
- """Generate a coordinate grid for an image.
+ r"""Generate a coordinate grid for an image.
When the flag ``normalized_coordinates`` is set to True, the grid is
normalized to be in the range :math:`[-1,1]` to be consistent with the pytorch
@@ -39,6 +40,11 @@ def create_meshgrid(
produces a correspondingly empty grid; this differs from pixel-coordinate
normalization, where a zero-sized coordinate system is undefined.
+ ``grid_sample`` has two such conventions, selected by its own ``align_corners``
+ flag, and ``align_corners`` here picks the matching one. Feeding a grid built
+ under one convention to a ``grid_sample`` call using the other applies a
+ spurious sub-pixel scale and shift, so the two flags must agree.
+
See :doc:`Conventions & Pitfalls </get-started/conventions>` for the library-wide pixel-centre and
normalized-coordinate conventions used by this grid.
@@ -50,6 +56,11 @@ def create_meshgrid(
PyTorch function :py:func:`torch.nn.functional.grid_sample`.
device: the device on which the grid will be generated.
dtype: the data type of the generated grid.
+ align_corners: which normalization convention to use when
+ ``normalized_coordinates`` is ``True``. ``True`` maps pixel centers
+ :math:`[0, size-1]` to :math:`[-1, 1]`; ``False`` uses the half-pixel
+ mapping :math:`x_{norm} = (2x + 1) / W - 1`, where :math:`\pm 1` are the
+ outer pixel *edges*. Ignored when ``normalized_coordinates`` is ``False``.
Return:
grid tensor with shape :math:`(1, H, W, 2)`.
@@ -62,6 +73,13 @@ def create_meshgrid(
[[-1., 1.],
[ 1., 1.]]]])
+ >>> create_meshgrid(2, 2, align_corners=False)
+ tensor([[[[-0.5000, -0.5000],
+ [ 0.5000, -0.5000]],
+ <BLANKLINE>
+ [[-0.5000, 0.5000],
+ [ 0.5000, 0.5000]]]])
+
>>> create_meshgrid(2, 2, normalized_coordinates=False)
tensor([[[[0., 0.],
[1., 0.]],
@@ -112,13 +130,22 @@ def create_meshgrid(
# to be rounded back down mid-expression.
width_t = torch.scalar_tensor(width, device=xs.device, dtype=work_dtype)
height_t = torch.scalar_tensor(height, device=ys.device, dtype=work_dtype)
- xs = torch.where(width_t > 1, (xs / (width_t - 1) - 0.5) * 2, xs * 0.0)
- ys = torch.where(height_t > 1, (ys / (height_t - 1) - 0.5) * 2, ys * 0.0)
- else:
+ if align_corners:
+ xs = torch.where(width_t > 1, (xs / (width_t - 1) - 0.5) * 2, xs * 0.0)
+ ys = torch.where(height_t > 1, (ys / (height_t - 1) - 0.5) * 2, ys * 0.0)
+ else:
+ # The half-pixel mapping is finite for a singleton axis and lands it on the
+ # centre without a special case: (2 * 0 + 1) / 1 - 1 == 0.
+ xs = (2.0 * xs + 1.0) / width_t - 1.0
+ ys = (2.0 * ys + 1.0) / height_t - 1.0
+ elif align_corners:
# ``* 0.0`` rather than ``zeros_like`` so that a singleton axis follows the
# same integer-to-float promotion the non-singleton branch performs.
xs = (xs / (width - 1) - 0.5) * 2 if width > 1 else xs * 0.0
ys = (ys / (height - 1) - 0.5) * 2 if height > 1 else ys * 0.0
+ else:
+ xs = (2.0 * xs + 1.0) / width - 1.0
+ ys = (2.0 * ys + 1.0) / height - 1.0
if widened:
# The single rounding, after the whole normalization.
xs = xs.to(ramp_dtype)
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index 0d909533e..bd4792c4e 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -333,17 +333,20 @@ def crop_by_transform_mat(
by shape β€” :math:`(B, 2, 3)` takes the cheaper :func:`warp_affine` path,
while :math:`(B, 3, 3)` takes :func:`warp_perspective` and uses the **full**
matrix, so a non-trivial third (projective) row changes the output for
- non-degenerate ``out_size`` (see warning below); :class:`CenterCrop2D` itself
+ non-degenerate ``out_size`` (see note below); :class:`CenterCrop2D` itself
calls this with a :math:`(B, 2, 3)` transform
- align_corners: ``True`` by default
- padding_mode: ``'zeros'`` by default
- .. warning::
- With ``align_corners=False`` and an ``out_size`` dimension equal to ``1``, this
- function silently falls back to the :math:`(B, 2, 3)` :func:`warp_affine` path
- (dropping the projective row entirely), so two :math:`(B, 3, 3)` matrices that
- differ only in their third row produce byte-identical output. Tracked in
- `#3929 <https://github.com/kornia/kornia/issues/3929>`_.
+ .. note::
+ An ``out_size`` dimension equal to ``1`` is handled like any other size under
+ both ``align_corners`` settings: the :math:`(B, 3, 3)` path keeps its projective
+ row and agrees with the :math:`(B, 2, 3)` path for an affine transform. It used
+ to return all-``NaN`` at ``align_corners=True`` and to silently fall back to
+ :func:`warp_affine` at ``align_corners=False``
+ (`#3929 <https://github.com/kornia/kornia/issues/3929>`_); the singleton axis
+ now maps to the centre of the normalized range and the warp normalizes under
+ the same convention it samples with.
Args:
input_tensor: the 2D image torch.Tensor with shape (B, C, H, W).
@@ -378,35 +381,6 @@ def crop_by_transform_mat(
align_corners=align_corners,
)
- h_out, w_out = out_size
- if not align_corners and (h_out == 1 or w_out == 1):
- # the destination-side reparametrization below is singular for 1-pixel outputs,
- # so keep the historical affine sampling for this degenerate size
- return warp_affine(
- input_tensor,
- dst_trans_src[:, :2, :],
- out_size,
- mode=mode,
- padding_mode=padding_mode,
- align_corners=align_corners,
- )
-
- if not align_corners:
- # warp_perspective always builds its grid with align_corners=True spacing, while this
- # function historically followed warp_affine/F.affine_grid; this destination-side
- # reparametrization maps one convention onto the other. It depends only on out_size,
- # keeping the graph free of data-dependent control flow for torch.export.
- correction = torch.tensor(
- [
- [w_out / (w_out - 1.0), 0.0, -0.5],
- [0.0, h_out / (h_out - 1.0), -0.5],
- [0.0, 0.0, 1.0],
- ],
- device=dst_trans_src.device,
- dtype=dst_trans_src.dtype,
- )
- dst_trans_src = correction.unsqueeze(0) @ dst_trans_src
-
patches: torch.Tensor = warp_perspective(
input_tensor,
dst_trans_src,
diff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.py
index 06f9511d4..cd49ad19d 100644
--- a/kornia/geometry/transform/elastic_transform.py
+++ b/kornia/geometry/transform/elastic_transform.py
@@ -47,7 +47,9 @@ def elastic_transform2d(
grid (positive x-noise shifts image content left)
- displacements are smoothed with a Gaussian (``kernel_size``,
``sigma``) and scaled by ``alpha``
- - align_corners: ``False`` by default
+ - align_corners: ``False`` by default; it selects the normalization of the sampling
+ grid as well as the ``grid_sample`` call, so zero ``noise`` is an identity under
+ either setting
- padding_mode: ``'zeros'`` by default
Args:
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
index 1e5071436..169dd0800 100644
--- a/kornia/geometry/transform/homography_warper.py
+++ b/kornia/geometry/transform/homography_warper.py
@@ -115,8 +115,11 @@ class HomographyWarper(BaseWarper):
self.padding_mode = padding_mode
self.normalized_coordinates = normalized_coordinates
self.align_corners = align_corners
- # create base grid to compute the flow
- self.grid = create_meshgrid(height, width, normalized_coordinates=normalized_coordinates)
+ # create base grid to compute the flow, under the same normalization convention that
+ # forward() will hand to grid_sample, so the precomputed path matches the direct one
+ self.grid = create_meshgrid(
+ height, width, normalized_coordinates=normalized_coordinates, align_corners=align_corners
+ )
# initialice the warped destination grid
self._warped_grid = None
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 24c2c5f8e..4980da076 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -291,7 +291,9 @@ def warp_perspective(
)
# we F.normalize the 3x3 transformation matrix and convert to 3x4
- dst_norm_trans_src_norm: torch.Tensor = normalize_homography(M, (H, W), (h_out, w_out)) # Bx3x3
+ dst_norm_trans_src_norm: torch.Tensor = normalize_homography(
+ M, (H, W), (h_out, w_out), align_corners=align_corners
+ ) # Bx3x3
# Closed-form 3x3 inverse (pure arithmetic) instead of ``torch.linalg.inv``: numerically
# equivalent for these well-conditioned transforms, and it runs where the LAPACK/cusolver
@@ -301,7 +303,9 @@ def warp_perspective(
# Substitutes F.affine_grid (which only handles the affine 2x3 case) by applying the full 3x3
# projective transform to every grid point directly.
- grid = create_meshgrid(h_out, w_out, normalized_coordinates=True, device=src.device).to(src.dtype)
+ grid = create_meshgrid(
+ h_out, w_out, normalized_coordinates=True, device=src.device, align_corners=align_corners
+ ).to(src.dtype)
if torch.jit.is_tracing():
# Under tracing/ONNX use the reference transform_points path (its op set exports cleanly).
grid = transform_points(src_norm_trans_dst_norm[:, None, None], grid.expand(B, h_out, w_out, 2))
@@ -413,7 +417,7 @@ def warp_affine(
)
M_3x3: torch.Tensor = convert_affinematrix_to_homography(M)
- dst_norm_trans_src_norm: torch.Tensor = normalize_homography(M_3x3, (H, W), dsize)
+ dst_norm_trans_src_norm: torch.Tensor = normalize_homography(M_3x3, (H, W), dsize, align_corners=align_corners)
# Closed-form 3x3 inverse (see warp_perspective) β€” cusolver-free, so affine warps run on the
# Jetson wheel where ``torch.linalg.inv`` dlopen-fails.
@@ -1754,7 +1758,12 @@ 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
+ 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)
diff --git a/kornia/geometry/transform/thin_plate_spline.py b/kornia/geometry/transform/thin_plate_spline.py
index 4a9f6bcf2..df34fbaa2 100644
--- a/kornia/geometry/transform/thin_plate_spline.py
+++ b/kornia/geometry/transform/thin_plate_spline.py
@@ -79,10 +79,9 @@ def get_tps_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> tup
is typically composed **reversed** β€” ``get_tps_transform(points_dst,
points_src)`` β€” since image warping samples from output space back
into input space; the recipe for warping an image end-to-end (when
- targeting :func:`warp_image_tps`, ``points_dst`` here is the always
- corner-aligned output lattice and ``points_src`` here is the input-side
- frame selected by :func:`warp_image_tps`'s ``align_corners`` β€” see that
- function's Convention block for both formulas)::
+ targeting :func:`warp_image_tps`, both ``points_dst`` and ``points_src``
+ here are normalized in the single frame selected by that function's
+ ``align_corners`` β€” see its Convention block for both formulas)::
kernel_weights, affine_weights = get_tps_transform(points_dst, points_src)
warped = warp_image_tps(image, kernel_centers=points_src,
@@ -250,43 +249,19 @@ def warp_image_tps(
argument to that reversed :func:`get_tps_transform` call (i.e.
``points_src``); see :func:`get_tps_transform`'s Convention block for the
full binding rule and recipe
- - control points span two different normalized grid_sample coordinate
- frames, where ``[-1, 1]`` is the in-bounds extent (values outside are
- allowed, subject to ``padding_mode``) rather than a validity bound:
-
- - ``get_tps_transform``'s reversed **first** argument (the
- destination/output lattice) is always corner-aligned,
- :math:`x_{norm} = 2x/(W-1) - 1`, because this function's internal
- sampling grid is always built via
- ``create_meshgrid(h, w, normalized_coordinates=True)`` regardless of
- ``align_corners`` below (see the warning)
- - ``kernel_centers`` and ``get_tps_transform``'s reversed **second**
- argument (the source/input side) must instead match this
- function's own ``align_corners``: at the default
- ``align_corners=False`` that is the half-pixel mapping
- :math:`x_{norm} = (2x+1)/W - 1`; passing ``align_corners=True``
- switches it to the same corner-aligned formula as the output
- lattice, so both sides can then share one normalization β€” the
- simplest usage
- - pixel-space (unnormalized) control points on either side silently
- produce a wrong warp of the correct shape, with no error raised
+ - control points on **both** sides β€” ``kernel_centers`` and both arguments
+ of the reversed :func:`get_tps_transform` call β€” live in the single
+ normalized grid_sample coordinate frame selected by ``align_corners``
+ below, where ``[-1, 1]`` is the in-bounds extent (values outside are
+ allowed, subject to ``padding_mode``) rather than a validity bound. At
+ the default ``align_corners=False`` that is the half-pixel mapping
+ :math:`x_{norm} = (2x+1)/W - 1`; ``align_corners=True`` selects the
+ corner-aligned :math:`x_{norm} = 2x/(W-1) - 1`. Pixel-space
+ (unnormalized) control points silently produce a wrong warp of the
+ correct shape, with no error raised
- align_corners: ``False`` by default
- padding_mode: ``'zeros'`` by default
- .. warning::
- This function's own sampling grid (the destination/output lattice) is
- always corner-aligned regardless of the ``align_corners`` argument below,
- while the source-side control points must match ``align_corners`` (see
- the Convention block above). So the common idiom of normalizing both
- sides the same corner-aligned way and calling this function at the
- default ``align_corners=False`` does **not** reproduce even a
- mathematically-identity TPS transform exactly β€” this is likely
- unintended and tracked in
- `#3928 <https://github.com/kornia/kornia/issues/3928>`_. Passing
- ``align_corners=True`` explicitly (keeping both sides corner-aligned)
- removes the mismatch, leaving an identity round-trip up to ordinary
- floating-point precision.
-
Args:
image: input image torch.Tensor :math:`(B, C, H, W)`.
kernel_centers: kernel center points :math:`(B, K, 2)`.
@@ -335,7 +310,9 @@ def warp_image_tps(
raise ValueError(f"Invalid shape for affine_weights, expected BxNx2. Got {affine_weights.shape}")
batch_size, _, h, w = image.shape
- coords: torch.Tensor = create_meshgrid(h, w, device=image.device, dtype=image.dtype, normalized_coordinates=True)
+ coords: torch.Tensor = create_meshgrid(
+ h, w, device=image.device, dtype=image.dtype, normalized_coordinates=True, align_corners=align_corners
+ )
coords = coords.reshape(-1, 2).expand(batch_size, -1, -1)
warped: torch.Tensor = warp_points_tps(coords, kernel_centers, kernel_weights, affine_weights)
warped = warped.view(-1, h, w, 2)
diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txt
index 1a6991552..f287bd54b 100644
--- a/testing/half_precision_xfails/cpu_bfloat16.txt
+++ b/testing/half_precision_xfails/cpu_bfloat16.txt
@@ -420,17 +420,12 @@ call builtins.AssertionError tests/geometry/transform/test_affine.py::TestRescal
call builtins.AssertionError tests/geometry/transform/test_affine.py::TestRotate::test_angle90[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_affine.py::TestRotate::test_angle90_batch2[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_affine.py::TestRotate::test_angle90_batch2_broadcast[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_affine.py::TestShear::test_shear_batch2[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_affine.py::TestShear::test_shear_batch2_broadcast[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_affine.py::TestShear::test_shear_x[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_affine.py::TestShear::test_shear_y[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_affine.py::TestTranslate::test_dxdy[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_affine.py::TestTranslate::test_dxdy_batch[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_affine.py::TestTranslate::test_dxdy_batch_broadcast[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_crop2d.py::TestCenterCrop::test_center_crop_h2_w4[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_crop2d.py::TestCenterCrop::test_center_crop_h4_w2[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_crop2d.py::TestCenterCrop::test_center_crop_h4_w2_batch[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_crop2d.py::TestCropAndResize::test_align_corners_false[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_crop2d.py::TestCropAndResize::test_align_corners_true[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_crop2d.py::TestCropAndResize::test_crop_batch[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_crop2d.py::TestCropAndResize::test_crop_batch_broadcast[cpu-bfloat16]
@@ -467,6 +462,7 @@ call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpP
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_crop_center_resize[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_rotation_inverse[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_translation[cpu-bfloat16]
+call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_translation_align_corners[cpu-bfloat16-True]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_translation_normalized[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestGetRotationMatrix3d::test_rot90x[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestGetRotationMatrix3d::test_rot90y[cpu-bfloat16]
diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txt
index c1ab96495..7929b59e6 100644
--- a/testing/half_precision_xfails/cpu_float16.txt
+++ b/testing/half_precision_xfails/cpu_float16.txt
@@ -432,14 +432,11 @@ call builtins.AssertionError tests/geometry/transform/test_affine.py::TestAffine
call builtins.AssertionError tests/geometry/transform/test_affine.py::TestRotate::test_angle90[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_affine.py::TestRotate::test_angle90_batch2[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_affine.py::TestRotate::test_angle90_batch2_broadcast[cpu-float16]
-call builtins.AssertionError tests/geometry/transform/test_affine.py::TestShear::test_shear_batch2[cpu-float16]
-call builtins.AssertionError tests/geometry/transform/test_affine.py::TestShear::test_shear_batch2_broadcast[cpu-float16]
-call builtins.AssertionError tests/geometry/transform/test_affine.py::TestShear::test_shear_x[cpu-float16]
-call builtins.AssertionError tests/geometry/transform/test_affine.py::TestShear::test_shear_y[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_affine.py::TestTranslate::test_dxdy_batch[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_crop2d.py::TestCropAndResize::test_crop_non_parallel_box[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCenterCrop3D::test_center_crop_357[cpu-float16-crop_size2]
call builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCenterCrop3D::test_center_crop_357_batch[cpu-float16-crop_size2]
+call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyNormalTransform::test_normalize_denormalize_round_trip_align_corners_false[cpu-float16-2-5]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper3D::test_normalize_homography_identity[cpu-float16-1]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper3D::test_normalize_homography_identity[cpu-float16-3]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_normalize_homography_identity[cpu-float16-1]
@@ -458,10 +455,12 @@ call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestRotat
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestRotationMatrix2d::test_rotation_90deg_and_scale[cpu-float16-5]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpAffine::test_fill_padding_translation[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpAffine::test_translation[cpu-float16]
+call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpAffine::test_translation_align_corners[cpu-float16-True]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_convention_normalize_invert_equivalence[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_fill_padding_translation[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_rotation_inverse[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_translation[cpu-float16]
+call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_translation_align_corners[cpu-float16-True]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_translation_normalized[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestGetRotationMatrix3d::test_rot90x[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestGetRotationMatrix3d::test_rot90y[cpu-float16]
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 7de55de11..153f86c2b 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -1035,8 +1035,18 @@ class TestConventionAugmentationSequential(BaseTester):
# NEAREST after merging the override, so asking for bilinear changed nothing on `RandomAffine`, while
# the `align_corners` half of the same dict was honoured. `RandomElasticTransform`, which has its own
# mask path, honours both halves.
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu), seed 0, a
- # (1, 1, 6, 8) mask with a 1-block: RandomPerspective align_corners override 1.0.
+ # Snippet used to generate expected: this body, executed 2026-09-14 (torch 2.9.1, cpu), seed 0, a
+ # (1, 1, 6, 8) mask with a 1-block: RandomAffine with padding_mode="reflection" align_corners
+ # override 1.0.
+ # The align_corners fixture was `RandomPerspective(0.5, p=1.0)` with zero padding until #3945. That
+ # delta was 1.0 only because the two conventions disagreed on in-bounds samples: the sampling grid
+ # was built corner-aligned whatever flag reached grid_sample, so align_corners=True vs False shifted
+ # the mask by half a pixel. #3945 makes the grid follow the flag, so the two now agree wherever the
+ # sample lands inside the image and that delta collapsed to 0.0 (float32, float64, float16 and
+ # bfloat16 alike). They still differ out of bounds, because +/-1 spans a different extent under each
+ # convention, so the fixture moves to a transform that samples outside the frame and a padding_mode
+ # that makes those samples observable. Sweep, seeds 0-9: delta is exactly 1.0 at every seed on cpu
+ # float32, float64, float16 and bfloat16.
# The elastic half uses its own fixture, reusing the #4420 pin's style below: `RandomElasticTransform
# (alpha=(5.0, 5.0), sigma=(4.0, 4.0), p=1.0)` on a checkerboard mask, same (1, 1, 6, 8), H != W frame,
# instead of the default alpha/sigma with a solid block. #4382 ("fix: respect align_corners in elastic
@@ -1067,8 +1077,8 @@ class TestConventionAugmentationSequential(BaseTester):
affine = lambda: K.RandomAffine(degrees=(45.0, 45.0), p=1.0) # noqa: E731
assert (mask_of(affine, bilinear) - mask_of(affine, None)).abs().max().item() > 0.0
- perspective = lambda: K.RandomPerspective(0.5, p=1.0) # noqa: E731
- assert (mask_of(perspective, align) - mask_of(perspective, None)).abs().max().item() == 1.0
+ reflected = lambda: K.RandomAffine(degrees=(45.0, 45.0), p=1.0, padding_mode="reflection") # noqa: E731
+ assert (mask_of(reflected, align) - mask_of(reflected, None)).abs().max().item() == 1.0
def elastic_mask_of(extra):
torch.manual_seed(0)
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index ced6d7e55..35e2f304f 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -5720,12 +5720,16 @@ class TestRandomThinPlateSpline(CommonTests):
assert params["dst"].dtype == dtype
self.assert_close(params["dst"], params["src"], atol=0, rtol=0)
+ @pytest.mark.parametrize("align_corners", [True, False])
@pytest.mark.parametrize("same_on_batch", [False, True])
- def test_zero_scale_identity(self, same_on_batch, device, dtype):
+ def test_zero_scale_identity(self, same_on_batch, align_corners, device, dtype):
if dtype == torch.float16:
pytest.skip("get_tps_transform is numerically unstable in float16 (produces NaN)")
- # align_corners=False has a separate sampling-grid defect tracked in #3928.
- aug = self._augmentation_cls(scale=0.0, align_corners=True, same_on_batch=same_on_batch, p=1.0)
+ # Both conventions: a zero-scale spline is the identity whichever one the class is built
+ # with, and align_corners=False is the class default. This used to be pinned at True only,
+ # because warp_image_tps built its sampling grid corner-aligned whatever flag reached
+ # grid_sample, so the default path moved the image by half a pixel (#3928, #4411).
+ aug = self._augmentation_cls(scale=0.0, align_corners=align_corners, same_on_batch=same_on_batch, p=1.0)
image = torch.arange(48, device=device, dtype=dtype).reshape(1, 1, 6, 8) / 48
image = image.expand(2, 1, 6, 8).clone().requires_grad_()
diff --git a/tests/augmentation/test_perspective_rand.py b/tests/augmentation/test_perspective_rand.py
index 78e17e535..c53220ccf 100644
--- a/tests/augmentation/test_perspective_rand.py
+++ b/tests/augmentation/test_perspective_rand.py
@@ -104,20 +104,36 @@ class TestRandomPerspective(BaseTester):
torch.manual_seed(0)
x_data = torch.rand(1, 2, 4, 5).to(device).type(dtype)
+ # RandomPerspective samples with align_corners=False. expected_transform below is the
+ # pixel-space transform and is unaffected by #3904; only the resampling changed, now that
+ # warp_perspective normalizes to the convention grid_sample is actually called with.
+ # Snippet used to generate expected_output (the call under test, verbatim):
+ # torch.manual_seed(0); x_data = torch.rand(1, 2, 4, 5)
+ # aug = kornia.augmentation.RandomPerspective(torch.tensor(0.5), p=0.99999999)
+ # expected_output = aug(x_data)
+ # Pre-#3945 literal from the same snippet:
+ # [[[[0.0000, 0.0000, 0.0000, 0.0197, 0.0429],
+ # [0.0000, 0.5632, 0.5322, 0.3677, 0.1430],
+ # [0.0000, 0.3083, 0.4032, 0.1761, 0.0000],
+ # [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],
+ # [[0.0000, 0.0000, 0.0000, 0.1189, 0.0586],
+ # [0.0000, 0.7087, 0.5420, 0.3995, 0.0863],
+ # [0.0000, 0.2695, 0.5981, 0.5888, 0.0000],
+ # [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]]]
expected_output = torch.tensor(
[
[
[
- [0.0000, 0.0000, 0.0000, 0.0197, 0.0429],
- [0.0000, 0.5632, 0.5322, 0.3677, 0.1430],
- [0.0000, 0.3083, 0.4032, 0.1761, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.1917, 0.3701, 0.1529, 0.0913, 0.2540],
+ [0.3200, 0.5976, 0.6278, 0.4746, 0.4695],
+ [0.0854, 0.4027, 0.2665, 0.1858, 0.1531],
+ [0.0000, 0.2196, 0.0264, 0.0000, 0.0000],
],
[
- [0.0000, 0.0000, 0.0000, 0.1189, 0.0586],
- [0.0000, 0.7087, 0.5420, 0.3995, 0.0863],
- [0.0000, 0.2695, 0.5981, 0.5888, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.2632, 0.4507, 0.3209, 0.5829, 0.3465],
+ [0.3679, 0.7943, 0.4226, 0.2346, 0.2755],
+ [0.0746, 0.5083, 0.5565, 0.4573, 0.3209],
+ [0.0000, 0.0134, 0.0153, 0.0000, 0.0000],
],
]
],
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index 35f49585e..6750b303e 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -3618,16 +3618,48 @@ def test_normal_transform_export_crosses_singleton_boundary(is_3d, dtype, runtim
assert_close(exported(runtime), ExportTransform()(runtime), atol=0.0, rtol=0.0)
[email protected]("align_corners", [True, False])
[email protected]("size", [3, 11, 31, 251, 4051])
[email protected](not dynamic_export_is_available(), reason=DYNAMIC_EXPORT_UNAVAILABLE_REASON)
+def test_normal_transform_capture_matches_eager_bitwise(align_corners, size):
+ """Graph capture must reproduce eager's normalization matrix exactly, under either convention.
+
+ Eager evaluates the offset in Python doubles and rounds once on store, while the capture branch
+ evaluates it in float32 so a symbolic size stays dynamic. Writing the ``align_corners=False``
+ offset as ``1 / size - 1`` therefore rounded twice under capture and landed one float32 step
+ away from eager. The five sizes here are exactly those below 5000 where the two forms disagree;
+ writing the offset as the single division ``(1 - size) / size`` makes both paths round once.
+ ``align_corners=True`` never had the defect and is parametrized to keep it that way.
+ """
+
+ class ExportTransform(torch.nn.Module):
+ def forward(self, image):
+ return kornia.geometry.normal_transform_pixel(
+ image.shape[-2], image.shape[-1], device=image.device, align_corners=align_corners
+ )
+
+ example = torch.zeros(1, 1, 4, 2)
+ exported = torch.export.export(
+ ExportTransform(),
+ (example,),
+ dynamic_shapes=({3: torch.export.Dim("width", min=1, max=size + 1)},),
+ ).module()
+
+ runtime = torch.zeros(1, 1, 4, size)
+ assert_close(exported(runtime), ExportTransform()(runtime), atol=0.0, rtol=0.0)
+
+
class TestNormalTransformPixel(BaseTester):
# normal_transform_pixel and normal_transform_pixel3d have no test class of their own in this
# file -- their existing coverage lives in tests/geometry/transform/test_homography_warper.py.
# The convention pins live here, next to the pixel-coordinate family whose [-1, 1] convention
# they share (an executed agreement, not a shared-code argument: see
# test_convention_agrees_with_normalize_pixel_coordinates below).
- # NOTE: kornia#3904 (reserved) may extend this surface. EVERY literal in this class -- not only
- # the pins that repeat this line -- is built from the unconditional corner-aligned 2/(size - 1)
- # constants, so all of them would flip if #3904 made the normalization respect align_corners.
- # They record current default behavior; none of them is a ratified contract for that choice.
+ # NOTE: kornia#3904 landed and did NOT move any literal here. It gave normal_transform_pixel an
+ # align_corners parameter, but left the default at True, so every literal in this class is still
+ # the corner-aligned 2/(size - 1) one and every bare call still produces it. What would flip them
+ # is a change to that default, not the existence of the parameter. They record current default
+ # behavior; none of them is a ratified contract for that choice.
def test_convention_returns_one_unbatched_matrix_in_the_ambient_default_dtype(self, device):
# Convention pin: both helpers return exactly one matrix behind a leading axis of 1 --
@@ -4060,13 +4092,14 @@ class TestNormalizeHomography(BaseTester):
# and needs a tolerance instead.
# No pin asserts anything about kornia#3962 (no denormalize_homography3d, no
# ColmapQTVecs_to_ARKitQTVecs) -- a missing symbol is a scope question, not a defect.
- # NOTE: kornia#3904 (reserved) may extend this surface. EVERY literal in this class -- the
- # composition, direction, round-trip, batching and 3-D pins as much as the #3957 singleton and
- # #3958 bug pins, and whether or not the pin repeats this line -- is built from the corner-aligned
- # 2/(size - 1) constants these three functions inherit from normal_transform_pixel, so a #3904
- # fix that made the normalization respect align_corners would flip all of them. They record
- # current default behavior; none of them ratifies that choice as contract. (The #3958 pins would
- # also flip on a #3958 fix, which is their point; the #3904 exposure is separate and additional.)
+ # NOTE: kornia#3904 landed and moved none of these. normalize_homography and
+ # denormalize_homography now take an align_corners argument and forward it to
+ # normal_transform_pixel, but it defaults to True, so the composition, direction, round-trip,
+ # batching and 3-D pins here -- and the #3957 singleton and #3958 bug pins -- still see the
+ # corner-aligned 2/(size - 1) constants they were written against. normalize_homography3d has no
+ # such argument at all. A change to that default, not the parameter, is what would flip them.
+ # They record current default behavior; none of them ratifies that choice as contract. (The
+ # #3958 pins would also flip on a #3958 fix, which is their point and is separate from this.)
def test_gradcheck(self, device):
# The three functions are on the warp_perspective path and are differentiable in their
@@ -4137,7 +4170,9 @@ class TestNormalizeHomography(BaseTester):
# float32 is hardcoded and the dtype fixture dropped: 5.96e-08 IS 2**-24, a float32 rounding
# step, so the figure is only meaningful in float32 and every other dtype would need its own.
# NOT a contract that these sizes must keep these residuals -- the class header's #3904 note
- # covers the whole surface, and a #3904 fix is expected to move both cells.
+ # covers the whole surface. #3904 has since landed and moved neither cell, because it left
+ # the default at align_corners=True; at align_corners=False the two sets differ (4 is exact
+ # there and 3 is not), which is why the warning now quotes the default's figures only.
# Snippet used to generate expected (torch only, executed on cpu, torch 2.9.1):
# I = torch.eye(3)[None]
# (normalize_homography(I, (n, n), (n, n)) - I).abs().max() for n = 4 -> 5.960464477539063e-08
diff --git a/tests/geometry/test_grid.py b/tests/geometry/test_grid.py
index fc65808bb..c67ffb520 100644
--- a/tests/geometry/test_grid.py
+++ b/tests/geometry/test_grid.py
@@ -337,6 +337,30 @@ def test_normalized_meshgrid_half_dtype_matches_compile(is_3d, grid_dtype, devic
assert_close(actual, expected, atol=torch.finfo(grid_dtype).eps if inexact_division else 0.0, rtol=0.0)
+def test_create_meshgrid_align_corners(device, dtype):
+ # align_corners selects which grid_sample normalization the grid is built for: True puts pixel
+ # centers 0 and W-1 at -1 and +1, False puts the outer pixel EDGES there (#3904).
+ height, width = 2, 4
+
+ grid_true = kornia.geometry.create_meshgrid(height, width, True, device=device, dtype=dtype, align_corners=True)
+ grid_false = kornia.geometry.create_meshgrid(height, width, True, device=device, dtype=dtype, align_corners=False)
+
+ # align_corners=True is the default, so the bare call must match it
+ assert_close(kornia.geometry.create_meshgrid(height, width, True, device=device, dtype=dtype), grid_true)
+
+ assert_close(grid_true[0, :, 0, 0], torch.tensor([-1.0, -1.0], device=device, dtype=dtype))
+ assert_close(grid_true[0, :, -1, 0], torch.tensor([1.0, 1.0], device=device, dtype=dtype))
+ # False: x centers land at (2x + 1)/W - 1, i.e. -0.75 and 0.75 for W = 4
+ assert_close(grid_false[0, :, 0, 0], torch.tensor([-0.75, -0.75], device=device, dtype=dtype))
+ assert_close(grid_false[0, :, -1, 0], torch.tensor([0.75, 0.75], device=device, dtype=dtype))
+
+ # align_corners is only about the normalization, so it is a no-op for pixel coordinates
+ assert_close(
+ kornia.geometry.create_meshgrid(height, width, False, device=device, dtype=dtype, align_corners=True),
+ kornia.geometry.create_meshgrid(height, width, False, device=device, dtype=dtype, align_corners=False),
+ )
+
+
def test_create_meshgrid3d(device, dtype):
depth, height, width = 5, 4, 6
normalized_coordinates = False
diff --git a/tests/geometry/transform/test_affine.py b/tests/geometry/transform/test_affine.py
index 10b954de5..dcc33c0e3 100644
--- a/tests/geometry/transform/test_affine.py
+++ b/tests/geometry/transform/test_affine.py
@@ -604,8 +604,17 @@ class TestShear(BaseTester):
device=device,
dtype=dtype,
)
+ # x-shear by 0.5 about the origin: dst[x, y] samples src[x - 0.5 * y, y], so row y=1
+ # samples x=-0.5 (half outside, zero padding -> 0.5), row y=2 samples x=-1 (fully
+ # outside -> 0), row y=3 samples x=-1.5 and x=-0.5 -> 0, 0.5.
+ # Snippet used to generate expected (identical to the call under test):
+ # inp = torch.ones(1, 4, 4); shear = torch.tensor([[0.5, 0.0]])
+ # expected = kornia.geometry.transform.Shear(shear, align_corners=False)(inp)
+ # Pre-#3945 literal from the same snippet, when warp_affine(align_corners=False) still
+ # normalized against a corner-aligned grid (the 0.75 / 0.25 are that sub-pixel artifact):
+ # [[[0.75, 1.0, 1.0, 1.0], [0.25, 1.0, 1.0, 1.0], [0.0, 0.75, 1.0, 1.0], [0.0, 0.25, 1.0, 1.0]]]
expected = torch.tensor(
- [[[0.75, 1.0, 1.0, 1.0], [0.25, 1.0, 1.0, 1.0], [0.0, 0.75, 1.0, 1.0], [0.0, 0.25, 1.0, 1.0]]],
+ [[[1.0, 1.0, 1.0, 1.0], [0.5, 1.0, 1.0, 1.0], [0.0, 1.0, 1.0, 1.0], [0.0, 0.5, 1.0, 1.0]]],
device=device,
dtype=dtype,
)
@@ -622,8 +631,11 @@ class TestShear(BaseTester):
device=device,
dtype=dtype,
)
+ # y-shear by 0.5 about the origin: the transpose of the test_shear_x case above.
+ # Pre-#3945 literal (shear = [[0.0, 0.5]], otherwise the test_shear_x snippet):
+ # [[[0.75, 0.25, 0.0, 0.0], [1.0, 1.0, 0.75, 0.25], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]]
expected = torch.tensor(
- [[[0.75, 0.25, 0.0, 0.0], [1.0, 1.0, 0.75, 0.25], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]],
+ [[[1.0, 0.5, 0.0, 0.0], [1.0, 1.0, 1.0, 0.5], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]],
device=device,
dtype=dtype,
)
@@ -641,10 +653,12 @@ class TestShear(BaseTester):
dtype=dtype,
).repeat(2, 1, 1, 1)
+ # the test_shear_x and test_shear_y expectations, stacked; the pre-#3945 literals
+ # recorded in those two tests stack the same way
expected = torch.tensor(
[
- [[[0.75, 1.0, 1.0, 1.0], [0.25, 1.0, 1.0, 1.0], [0.0, 0.75, 1.0, 1.0], [0.0, 0.25, 1.0, 1.0]]],
- [[[0.75, 0.25, 0.0, 0.0], [1.0, 1.0, 0.75, 0.25], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]],
+ [[[1.0, 1.0, 1.0, 1.0], [0.5, 1.0, 1.0, 1.0], [0.0, 1.0, 1.0, 1.0], [0.0, 0.5, 1.0, 1.0]]],
+ [[[1.0, 0.5, 0.0, 0.0], [1.0, 1.0, 1.0, 0.5], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]],
],
device=device,
dtype=dtype,
@@ -663,8 +677,9 @@ class TestShear(BaseTester):
dtype=dtype,
).repeat(2, 1, 1, 1)
+ # the test_shear_x expectation broadcast over the batch (pre-#3945 literal recorded there)
expected = torch.tensor(
- [[[[0.75, 1.0, 1.0, 1.0], [0.25, 1.0, 1.0, 1.0], [0.0, 0.75, 1.0, 1.0], [0.0, 0.25, 1.0, 1.0]]]],
+ [[[[1.0, 1.0, 1.0, 1.0], [0.5, 1.0, 1.0, 1.0], [0.0, 1.0, 1.0, 1.0], [0.0, 0.5, 1.0, 1.0]]]],
device=device,
dtype=dtype,
).repeat(2, 1, 1, 1)
diff --git a/tests/geometry/transform/test_crop2d.py b/tests/geometry/transform/test_crop2d.py
index a28bb1b6e..afdf0e2f0 100644
--- a/tests/geometry/transform/test_crop2d.py
+++ b/tests/geometry/transform/test_crop2d.py
@@ -49,7 +49,17 @@ class TestCropAndResize(BaseTester):
)
height, width = 2, 3
- expected = torch.tensor([[[[6.7222, 7.1667, 7.6111], [9.3889, 9.8333, 10.2778]]]], device=device, dtype=dtype)
+ # The box corners are pixel coordinates, so they pin the sampling geometry regardless of
+ # align_corners: the box spans src x, y in [1, 2] and the 2x3 output samples pixel centers
+ # at x = 1, 1.5, 2 and y = 1, 2 -- the same values the align_corners=True case produces.
+ # Snippet used to generate expected (identical to the call under test):
+ # inp = torch.arange(1.0, 17.0).view(1, 1, 4, 4)
+ # boxes = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]])
+ # expected = kornia.geometry.transform.crop_and_resize(inp, boxes, (2, 3), align_corners=False)
+ # Pre-#3945 literal from the same snippet (the #3650 correction matrix reparametrized the
+ # crop for a grid convention warp_perspective did not actually use):
+ # [[[[6.7222, 7.1667, 7.6111], [9.3889, 9.8333, 10.2778]]]]
+ expected = torch.tensor([[[[6.0, 6.5, 7.0], [10.0, 10.5, 11.0]]]], device=device, dtype=dtype)
boxes = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype) # 1x4x2
@@ -266,10 +276,13 @@ class TestCenterCrop(BaseTester):
expected = op(img, (4, 2))
self.assert_close(actual, expected, rtol=1e-4, atol=1e-4)
- def test_convention_align_corners_ignored_under_slice_mode(self, device, dtype):
+ def test_convention_align_corners_ignored_for_an_in_bounds_crop(self, device, dtype):
# CenterCrop2D's align_corners constructor arg has NO effect under the default
- # cropping_mode='slice' (pure integer-index slicing, no resampling); it only changes the
- # output under cropping_mode='resample'.
+ # cropping_mode='slice' (pure integer-index slicing, no resampling). Under
+ # cropping_mode='resample' it also has no effect for a crop that samples strictly
+ # in bounds: the crop box is specified in pixel coordinates, so both align_corners
+ # conventions must resolve it to the same pixel centers (#3904). align_corners still
+ # selects grid_sample's convention, which shows up only in out-of-bounds handling.
inp = torch.arange(0.0, 16.0, device=device, dtype=dtype).view(1, 1, 4, 4)
out_slice_true = kornia.geometry.transform.CenterCrop2D((2, 2), align_corners=True, cropping_mode="slice")(inp)
@@ -284,7 +297,12 @@ class TestCenterCrop(BaseTester):
out_resample_false = kornia.geometry.transform.CenterCrop2D(
(2, 2), align_corners=False, cropping_mode="resample"
)(inp)
- assert not torch.allclose(out_resample_true, out_resample_false, atol=1e-2, rtol=1e-2)
+ # dtype-aware default rather than a fixed 1e-4: align_corners=True normalizes by 2 / (size - 1),
+ # which is 2/3 for this 4x4 input and so is not exactly representable at half precision, leaving
+ # the True result a fraction of a pixel off the exact slice that the False result hits exactly
+ self.assert_close(out_resample_true, out_resample_false)
+ # and both agree with the plain integer-index slice of the same region
+ self.assert_close(out_resample_false, inp[:, :, 1:3, 1:3], atol=1e-4, rtol=1e-4)
class TestCropByBoxes(BaseTester):
@@ -362,6 +380,40 @@ class TestCropByTransform(BaseTester):
patches = kornia.geometry.transform.crop_by_transform_mat(inp, transform, (2, 3))
self.assert_close(patches, expected, rtol=1e-4, atol=1e-4)
+ @pytest.mark.parametrize("align_corners", [True, False])
+ @pytest.mark.parametrize("out_size", [(1, 3), (3, 1), (1, 1)])
+ def test_convention_one_pixel_output(self, device, dtype, align_corners, out_size):
+ # A 1-pixel output dimension must behave like any other size under both conventions
+ # (#3929). The (B, 3, 3) path used to return all-NaN at align_corners=True (fixed by
+ # #4006's singleton-axis mapping) and, at align_corners=False, to silently fall back to
+ # warp_affine through a correction matrix built for the wrong grid convention, which
+ # gave these pre-fix values on the same input:
+ # (1, 3): [4.6111, 5.5000, 5.9815] (3, 1): [5.9444, 9.5000, 12.1204] (1, 1): [4.1667]
+ # Snippet used to generate expected (pure slicing, no resampling involved):
+ # inp = torch.arange(16.0).view(1, 1, 4, 4); h, w = out_size
+ # expected = inp[:, :, 1 : 1 + h, 1 : 1 + w]
+ inp = torch.arange(16.0, device=device, dtype=dtype).view(1, 1, 4, 4)
+ h, w = out_size
+ expected = inp[:, :, 1 : 1 + h, 1 : 1 + w]
+
+ # translate by (-1, -1): destination pixel (0, 0) reads source pixel (1, 1)
+ transform = torch.tensor(
+ [[[1.0, 0.0, -1.0], [0.0, 1.0, -1.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
+ ) # 1x3x3
+
+ homogeneous = kornia.geometry.transform.crop_by_transform_mat(
+ inp, transform, out_size, align_corners=align_corners
+ )
+ affine = kornia.geometry.transform.crop_by_transform_mat(
+ inp, transform[:, :2], out_size, align_corners=align_corners
+ )
+
+ assert not homogeneous.isnan().any()
+ # the (B, 3, 3) and (B, 2, 3) forms must agree exactly, which is the subject here; matching the
+ # exact slice takes the dtype-aware default, since align_corners=True normalizes by 2 / (size - 1)
+ self.assert_close(homogeneous, affine, rtol=1e-4, atol=1e-4)
+ self.assert_close(homogeneous, expected)
+
def test_gradcheck(self, device):
inp = torch.randn((1, 1, 3, 3), device=device, dtype=torch.float64)
transform = torch.tensor(
diff --git a/tests/geometry/transform/test_homography_warper.py b/tests/geometry/transform/test_homography_warper.py
index 6c7037a2d..67ec40499 100644
--- a/tests/geometry/transform/test_homography_warper.py
+++ b/tests/geometry/transform/test_homography_warper.py
@@ -183,36 +183,28 @@ class TestHomographyWarper(BaseTester):
def test_convention_align_corners_default_false(self, device, dtype):
# HomographyWarper's bare default align_corners=False (every HomographyWarper construction in
- # this file passes align_corners=True explicitly; this exercises the bare default), warping an
- # identity homography over a padding_mode="zeros" grid so that align_corners visibly changes output.
+ # this file passes align_corners=True explicitly; this exercises the bare default). An identity
+ # homography must reproduce the input under either convention: the internal sampling grid is
+ # built to match align_corners, so the two agree rather than differing by half a pixel (#3904).
if dtype in (torch.float16, torch.bfloat16):
pytest.skip("hardcoded-literal pin only reliable at float32/float64 precision")
- # Snippet used to generate expected:
- # height, width = 4, 5
- # patch_src = torch.arange(float(height * width)).view(1, 1, height, width)
- # dst_homo_src = torch.eye(3)[None]
- # warper = kornia.geometry.transform.HomographyWarper(height, width) # no align_corners passed
- # expected = warper(patch_src, dst_homo_src)
+ # Snippet used to generate the pre-#3945 literal (the call under test, verbatim):
+ # height, width = 4, 5
+ # patch_src = torch.arange(float(height * width)).view(1, 1, height, width)
+ # warper = kornia.geometry.transform.HomographyWarper(height, width) # no align_corners passed
+ # expected = warper(patch_src, torch.eye(3)[None])
+ # Pre-#3945 literal, i.e. what an *identity* warp returned under the bare default:
+ # [[[[0.0000, 0.3750, 1.0000, 1.6250, 1.0000],
+ # [2.0833, 4.9167, 6.1667, 7.4167, 4.0833],
+ # [5.4167, 11.5833, 12.8333, 14.0833, 7.4167],
+ # [3.7500, 7.8750, 8.5000, 9.1250, 4.7500]]]]
+ # The corrected expectation is the input itself, so it needs no literal.
height, width = 4, 5
patch_src = torch.arange(float(height * width), device=device, dtype=dtype).view(1, 1, height, width)
dst_homo_src = eye_like(3, patch_src)
warper = kornia.geometry.transform.HomographyWarper(height, width)
patch_dst = warper(patch_src, dst_homo_src)
- expected = torch.tensor(
- [
- [
- [
- [0.0000, 0.3750, 1.0000, 1.6250, 1.0000],
- [2.0833, 4.9167, 6.1667, 7.4167, 4.0833],
- [5.4167, 11.5833, 12.8333, 14.0833, 7.4167],
- [3.7500, 7.8750, 8.5000, 9.1250, 4.7500],
- ]
- ]
- ],
- device=device,
- dtype=dtype,
- )
- self.assert_close(patch_dst, expected, atol=1e-3, rtol=1e-3)
+ self.assert_close(patch_dst, patch_src, atol=1e-3, rtol=1e-3)
# the literal above cannot distinguish False from None (grid_sample treats them alike), so
# the documented defaults are additionally pinned on the signatures of both APIs
import inspect
@@ -302,6 +294,26 @@ class TestHomographyWarper(BaseTester):
self.assert_close(patch_dst_to_src, patch_dst_to_src_functional, atol=1e-4, rtol=1e-4)
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_precompute_warp_grid_matches_direct(self, device, dtype, align_corners):
+ # the cached grid must be built under the convention forward() hands to grid_sample,
+ # otherwise the precomputed path silently disagrees with the direct one (#3904)
+ height, width = 8, 6
+ patch_src = torch.rand(1, 1, height, width, device=device, dtype=dtype)
+ dst_homo_src = eye_like(3, patch_src)
+
+ warper = kornia.geometry.transform.HomographyWarper(height, width, align_corners=align_corners)
+ direct = warper(patch_src, dst_homo_src)
+
+ warper.precompute_warp_grid(dst_homo_src)
+ precomputed = warper(patch_src)
+
+ # the cached-vs-direct comparison is the actual subject and is bit-exact in every dtype; the
+ # identity-reproduces-input half takes the dtype-aware default, because the [-1, 1] scale is
+ # not exactly representable at half precision
+ self.assert_close(precomputed, direct, atol=1e-4, rtol=1e-4)
+ self.assert_close(direct, patch_src)
+
@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
@@ -397,6 +409,31 @@ class TestHomographyNormalTransform(BaseTester):
output = kornia.geometry.linalg.transform_points(transform, input)
self.assert_close(output, expected.to(device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
+ def test_transform_apply_align_corners_false(self, device, dtype):
+ # align_corners=False normalizes to grid_sample's half-pixel convention, where +/-1 are the
+ # outer pixel EDGES: pixel centers 0 and W-1 land at -1 + 1/W and 1 - 1/W (#3904).
+ height, width = 2, 5
+ input = torch.tensor([[0.0, 0.0], [width - 1, height - 1]], device=device, dtype=dtype)
+ expected = torch.tensor([[-0.8, -0.5], [0.8, 0.5]], device=device, dtype=dtype)
+ transform = kornia.geometry.conversions.normal_transform_pixel(
+ height, width, device=device, dtype=dtype, align_corners=False
+ )
+ output = kornia.geometry.linalg.transform_points(transform, input)
+ self.assert_close(output, expected, atol=1e-4, rtol=1e-4)
+
+ @pytest.mark.parametrize("height", [1, 2, 5])
+ @pytest.mark.parametrize("width", [1, 2, 5])
+ def test_normalize_denormalize_round_trip_align_corners_false(self, height, width, device, dtype):
+ # denormalize_homography must invert normalize_homography for either convention. The
+ # align_corners=False mapping is also non-singular at a size of 1, unlike align_corners=True.
+ homo = torch.tensor([[[1.0, 0.2, 0.5], [-0.1, 1.0, -0.3], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ norm = kornia.geometry.conversions.normalize_homography(homo, (height, width), (height, width), False)
+ assert torch.isinf(norm).sum().item() == 0
+ restored = kornia.geometry.conversions.denormalize_homography(norm, (height, width), (height, width), False)
+ # dtype-aware default: the round trip multiplies by 2 / size and back, and the True-path sibling
+ # test_normalize_homography_identity is already a half-precision manifest entry for the same reason
+ self.assert_close(restored, homo)
+
@pytest.mark.parametrize("height,width,depth,expected", [(2, 6, 4, expected_3d_0), (1, 6, 4, expected_3d_1)])
def test_transform3d(self, height, width, depth, expected, device, dtype):
output = kornia.geometry.conversions.normal_transform_pixel3d(depth, height, width, device=device, dtype=dtype)
diff --git a/tests/geometry/transform/test_imgwarp.py b/tests/geometry/transform/test_imgwarp.py
index 91a5a18a7..5dce6be04 100644
--- a/tests/geometry/transform/test_imgwarp.py
+++ b/tests/geometry/transform/test_imgwarp.py
@@ -542,6 +542,29 @@ class TestWarpAffine(BaseTester):
img_a = kornia.geometry.warp_affine(img_b, aff_ab, (h, w))
self.assert_close(img_a, expected)
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_translation_align_corners(self, align_corners, device, dtype):
+ # A whole-pixel translation must shift by exactly that many pixels under either
+ # align_corners convention: M is a pixel-space transform, so align_corners selects only
+ # how the sampling grid is normalized for grid_sample, never the geometry (#3904).
+ offset = 1.0
+ h, w = 3, 4
+ aff_ab = torch.eye(2, 3, device=device, dtype=dtype)[None]
+ aff_ab[..., -1] += offset
+
+ img_b = torch.arange(float(h * w), device=device, dtype=dtype).view(1, 1, h, w)
+
+ expected = torch.zeros_like(img_b)
+ expected[..., 1:, 1:] = img_b[..., :2, :3]
+
+ img_a = kornia.geometry.warp_affine(img_b, aff_ab, (h, w), align_corners=align_corners)
+ # No explicit tolerance: BaseTester's dtype-aware defaults are what makes this run at
+ # float16/bfloat16. Normalizing pixel coordinates into [-1, 1] only lands on pixel centres
+ # exactly when the scale is a power of two, so at half precision one convention or the other
+ # drifts depending on the size, and the sibling True-only pins are already half-precision
+ # manifest entries for that reason.
+ self.assert_close(img_a, expected)
+
def test_rotation_inverse(self, device, dtype):
h, w = 4, 4
img_b = torch.rand(1, 1, h, w, device=device, dtype=dtype)
@@ -718,6 +741,47 @@ class TestWarpPerspective(BaseTester):
hw = kornia.geometry.transform.homography_warp(x, _torch_inverse_cast(Hn), (3, 5), align_corners=True)
self.assert_close(hw, expected, atol=1e-4, rtol=1e-4)
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_convention_identity_agrees_with_warp_affine(self, align_corners, device, dtype):
+ # An identity homography reproduces the input under either align_corners convention, and
+ # agrees with warp_affine fed the same identity. warp_perspective used to normalize with
+ # the align_corners=True mapping unconditionally while calling grid_sample with the
+ # requested flag, so at align_corners=False this drifted by half a pixel (#3904).
+ img = torch.arange(16.0, device=device, dtype=dtype).view(1, 1, 4, 4)
+ pts = torch.tensor([[[0.0, 0.0], [3.0, 0.0], [3.0, 3.0], [0.0, 3.0]]], device=device, dtype=dtype)
+ H = kornia.geometry.transform.get_perspective_transform(pts, pts)
+
+ out_perspective = kornia.geometry.transform.warp_perspective(img, H, (4, 4), align_corners=align_corners)
+ out_affine = kornia.geometry.transform.warp_affine(img, H[:, :2, :], (4, 4), align_corners=align_corners)
+
+ # the two warps must agree exactly; the identity-reproduces-input half needs the dtype-aware
+ # default, since align_corners=True normalizes by 2 / (size - 1), which no half dtype can hold
+ # exactly for size 4
+ self.assert_close(out_perspective, out_affine, atol=1e-4, rtol=1e-4)
+ self.assert_close(out_perspective, img)
+
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_translation_align_corners(self, align_corners, device, dtype):
+ # Companion to TestWarpAffine::test_translation_align_corners: a whole-pixel translation
+ # must shift by exactly that many pixels under either convention.
+ offset = 1.0
+ h, w = 3, 4
+
+ img_b = torch.arange(float(h * w), device=device, dtype=dtype).view(1, 1, h, w)
+ homo_ab = kornia.core.ops.eye_like(3, img_b)
+ homo_ab[..., :2, -1] += offset
+
+ expected = torch.zeros_like(img_b)
+ expected[..., 1:, 1:] = img_b[..., :2, :3]
+
+ img_a = kornia.geometry.warp_perspective(img_b, homo_ab, (h, w), align_corners=align_corners)
+ # No explicit tolerance: BaseTester's dtype-aware defaults are what makes this run at
+ # float16/bfloat16. Normalizing pixel coordinates into [-1, 1] only lands on pixel centres
+ # exactly when the scale is a power of two, so at half precision one convention or the other
+ # drifts depending on the size, and the sibling True-only pins are already half-precision
+ # manifest entries for that reason.
+ self.assert_close(img_a, expected)
+
def test_rotation_inverse(self, device, dtype):
h, w = 4, 4
img_b = torch.rand(1, 1, h, w, device=device, dtype=dtype)
diff --git a/tests/geometry/transform/test_thin_plate_spline.py b/tests/geometry/transform/test_thin_plate_spline.py
index f90e8c492..8177df3a6 100644
--- a/tests/geometry/transform/test_thin_plate_spline.py
+++ b/tests/geometry/transform/test_thin_plate_spline.py
@@ -178,9 +178,13 @@ class TestWarpImage(BaseTester):
tensor[:, :, 2:6, 2:6] = 1.0
expected = torch.ones_like(tensor)
- # nn.grid_sample interpolates the at the edges it seems, so the boundaries have values < 1
- expected[:, :, [0, -1], :] *= 0.5
- expected[:, :, :, [0, -1]] *= 0.5
+ # nn.grid_sample interpolates the at the edges it seems, so the boundaries have values < 1.
+ # Under the default align_corners=False, the outermost output pixel maps back to input
+ # pixel 1.75 -- three quarters of the way from the zero at pixel 1 to the one at pixel 2.
+ # Pre-#3945 the same warp gave a border factor of 0.5 (input pixel 1.5): the corner-aligned
+ # grid sampled under grid_sample's half-pixel convention shifted the zoom by a quarter pixel.
+ expected[:, :, [0, -1], :] *= 0.75
+ expected[:, :, :, [0, -1]] *= 0.75
kernel, affine = kornia.geometry.transform.get_tps_transform(dst, src)
warp = kornia.geometry.transform.warp_image_tps(tensor, src, kernel, affine)
@@ -304,7 +308,9 @@ class TestWarpImage(BaseTester):
src = torch.tensor(
[[[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0], [0.0, 0.0]]], device=device, dtype=dtype
)
- kernel, affine = kornia.geometry.transform.get_tps_transform(src, src)
+ # zoom out, so the warp samples beyond the input extent and padding_mode is observable --
+ # an identity warp now stays strictly in bounds and the two modes would agree
+ kernel, affine = kornia.geometry.transform.get_tps_transform(src * 0.5, src)
img = torch.arange(16.0, device=device, dtype=dtype).view(1, 1, 4, 4)
out_default = kornia.geometry.transform.warp_image_tps(img, src, kernel, affine)
@@ -348,16 +354,11 @@ class TestWarpImage(BaseTester):
)
self.assert_close(warped, expected, atol=1e-4, rtol=1e-4)
- @pytest.mark.xfail(reason="warp_image_tps default align_corners=False breaks identity β€” kornia#3928", strict=True)
def test_convention_default_align_corners_reproduces_identity(self, device, dtype):
- # Intended/correct behavior: an identity TPS transform warped with warp_image_tps's
- # *default* align_corners should reproduce the input image, exactly like the
- # align_corners=True case already pinned by test_identity_warp_align_corners above.
- # It currently does not (internal create_meshgrid always builds the sampling grid
- # using the align_corners=True convention, mismatching grid_sample's default False
- # convention -- see the warning in warp_image_tps's Convention block, #3928). This
- # test is marked xfail(strict=True) so that once #3928 is fixed it XPASSes and fails
- # loudly, forcing the xfail mark to be removed instead of silently staying green.
+ # An identity TPS transform warped with warp_image_tps's *default* align_corners
+ # reproduces the input image, exactly like the align_corners=True case pinned by
+ # test_identity_warp_align_corners above: the internal create_meshgrid now builds the
+ # sampling grid under the same convention grid_sample is called with (#3928).
if dtype == torch.float16:
pytest.skip("get_tps_transform is numerically unstable in float16 (produces NaN)")