Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(geometry): convention blocks and pins for grid and subpix (batch 10a) (#5068)

Dmytro Mishkin2f3417d72522
diff --git a/changelog.d/5068.added.md b/changelog.d/5068.added.md
new file mode 100644
index 000000000..cc7bc7bdc
--- /dev/null
+++ b/changelog.d/5068.added.md
@@ -0,0 +1 @@
+Convention blocks for `create_meshgrid`, `create_meshgrid3d` and `kornia.geometry.subpix` (the `(x, y)` / `(d, x, y)` coordinate orders, corner-aligned normalization, the `grid_sample` reorder for 3D grids, the conv soft-argmax windows, the quadratic refiners' rejection rules and strict NMS), the matching additions to the Conventions & Pitfalls page, and 14 convention and wart pins; the warts are documented and linked (#4503, #5020, #5065, #5066), not fixed.
diff --git a/docs/source/geometry.subpix.rst b/docs/source/geometry.subpix.rst
index 59cc1d8a4..8652f05e1 100644
--- a/docs/source/geometry.subpix.rst
+++ b/docs/source/geometry.subpix.rst
@@ -26,7 +26,10 @@ Convolutional
* **CPU** β†’ :func:`iterative_quad_interp3d` β€” processes only NMS maxima directly,
no dilation overhead.
- Both backends produce numerically identical results (max difference < 2 Γ— 10\ :sup:`-6`).
+ With ``max_candidates`` unset, the backends agree on every maximum whose centre stays within
+ ``dilation_radius`` voxels (default 1) of where it started. Beyond that :func:`conv_quad_interp3d` can reject a
+ maximum that :func:`iterative_quad_interp3d` still refines, so CPU and CUDA keypoints can differ;
+ ``dilation_radius=n_iters`` makes the backends agree.
.. code-block:: python
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index bb4dc7d7b..d49af513c 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -30,6 +30,8 @@ Image tensors
np_img = (np.random.rand(48, 64, 3) * 255).astype(np.uint8) # (H, W, C) uint8
t = kornia.image.image_to_tensor(np_img)[None].float() / 255.0 # (1, 3, 48, 64) in [0, 1]
+.. _coordinate-conventions:
+
Coordinates and sizes
---------------------
@@ -39,16 +41,33 @@ Coordinates and sizes
- Sizes and ``dsize`` arguments are ``(h, w)`` β€” the *opposite* order from
points. ``warp_perspective(img, M, dsize=(2, 8))`` produces a 2-row,
8-column image.
-- Normalized coordinates, where used, are ``[-1, 1]`` in both axes,
- identical to :func:`torch.nn.functional.grid_sample` **called with**
- ``align_corners=True`` β€” not to its default, ``align_corners=False``,
- which places the same values up to half a pixel off β€” exactly half a
- pixel at the image borders, and identically at the image center.
- :func:`kornia.geometry.grid.create_meshgrid` returns a normalized grid by
- default (``normalized_coordinates=True``).
+- Normalized coordinates, where used, are ``[-1, 1]`` in both axes.
+ :func:`kornia.geometry.grid.create_meshgrid` defaults to a corner-aligned
+ normalized grid (``normalized_coordinates=True``, ``align_corners=True``),
+ matching :func:`torch.nn.functional.grid_sample` with ``align_corners=True``:
+ the first and last pixel centres map to the endpoints. Passing
+ ``align_corners=False`` to ``create_meshgrid`` uses the half-pixel mapping
+ that matches ``grid_sample(..., align_corners=False)`` instead, where the
+ endpoints are the outer pixel edges. Use the same flag in both calls.
- 3D grids and 3D pixel coordinates are ``(d, x, y)`` β€” depth first, not
``(x, y, z)``; :func:`kornia.geometry.grid.create_meshgrid3d` produces this
order and the ``*_pixel_coordinates3d`` conversions consume it.
+ :func:`torch.nn.functional.grid_sample` reads a 3D grid as ``(x, y, z)``:
+ pass ``grid[..., [1, 2, 0]]`` and ``align_corners=True``, because the
+ normalized 3D grid is corner-aligned and has no ``align_corners`` argument
+ (`#4503 <https://github.com/kornia/kornia/issues/4503>`_).
+- Sub-pixel outputs follow the same orders: the soft-argmax functions of
+ :doc:`kornia.geometry.subpix </geometry.subpix>` return ``(x, y)`` in 2D
+ and ``(d, x, y)`` in 3D, and the quadratic refiners
+ (``conv_quad_interp3d``, ``iterative_quad_interp3d``) return ``(d, x, y)``
+ voxel indices of their input. Normalized outputs are corner-aligned, as
+ above.
+- Non-maximum suppression is **strict** in
+ :func:`kornia.geometry.subpix.nms2d`, ``nms3d``, ``nms3d_minmax`` and the
+ detectors built on them: with a window of at least 3 on every axis, every
+ pixel of a plateau is suppressed. ``skimage.feature.peak_local_max`` at its
+ default ``min_distance=1``, ``scipy.ndimage.maximum_filter(x, size=k) == x``
+ and ``cv2.dilate(x, kernel) == x`` keep every pixel of the plateau instead.
- Pixel ``(0, 0)`` is centred at ``(0, 0)`` β€” the OpenCV "integer" convention,
not COLMAP's half-pixel one. :doc:`camera-conventions` catalogues the
pixel-centre and camera-frame conventions of the surrounding ecosystem and
diff --git a/kornia/geometry/grid.py b/kornia/geometry/grid.py
index 35059abfb..01e051d2b 100644
--- a/kornia/geometry/grid.py
+++ b/kornia/geometry/grid.py
@@ -35,20 +35,13 @@ def create_meshgrid(
) -> torch.Tensor:
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
- function :py:func:`torch.nn.functional.grid_sample`. A singleton axis is
- represented by ``0``, the centre of the normalized range. A zero spatial size
- 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.
+ Convention:
+ - Coordinates follow :ref:`Coordinates and sizes <coordinate-conventions>`. With
+ ``normalized_coordinates=True``, the ``align_corners`` argument selects the matching
+ :py:func:`torch.nn.functional.grid_sample` convention; pass the same flag to both calls. The default is
+ corner-aligned (``align_corners=True``).
+ - A size-1 axis is ``0`` under either flag, and a size-0 axis gives an empty grid.
+ - An integer ``dtype`` is kept for a pixel grid; a normalized grid is then torch's default floating dtype.
Args:
height: the image height (rows).
@@ -167,20 +160,20 @@ def create_meshgrid3d(
) -> torch.Tensor:
"""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
- function :py:func:`torch.nn.functional.grid_sample`. A singleton axis is
- represented by ``0``, the centre of the normalized range. A zero spatial size
- produces a correspondingly empty grid; this differs from pixel-coordinate
- normalization, where a zero-sized coordinate system is undefined.
+ Convention:
+ - Coordinates follow :ref:`Coordinates and sizes <coordinate-conventions>`. A normalized grid is always
+ corner-aligned; reorder its last axis with ``grid[..., [1, 2, 0]]`` before passing it to
+ :py:func:`torch.nn.functional.grid_sample`.
+ - A size-1 axis is ``0`` and a size-0 axis gives an empty grid.
+ - Known defect: there is no ``align_corners`` argument, so the half-pixel grid that
+ ``grid_sample(..., align_corners=False)`` expects cannot be requested
+ (`#4503 <https://github.com/kornia/kornia/issues/4503>`_).
Args:
- depth: the image depth (channels).
+ depth: the volume depth (the ``D`` axis).
height: the image height (rows).
width: the image width (cols).
- normalized_coordinates: whether to normalize
- coordinates in the range :math:`[-1,1]` in order to be consistent with the
- PyTorch function :py:func:`torch.nn.functional.grid_sample`.
+ normalized_coordinates: whether to normalize coordinates to :math:`[-1, 1]`.
device: the device on which the grid will be generated.
dtype: the data type of the generated grid.
diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.py
index d67fdf8b3..ada0faa44 100644
--- a/kornia/geometry/subpix/dsnt.py
+++ b/kornia/geometry/subpix/dsnt.py
@@ -94,8 +94,10 @@ def spatial_softmax2d(input: torch.Tensor, temperature: Optional[torch.Tensor |
def spatial_expectation2d(input: torch.Tensor, normalized_coordinates: bool = True) -> torch.Tensor:
r"""Compute the expectation of coordinate values using spatial probabilities.
- The input heatmap is assumed to represent a valid spatial probability distribution,
- which can be achieved using :func:`~kornia.geometry.subpixel.spatial_softmax2d`.
+ Convention:
+ - Coordinates follow :ref:`Coordinates and sizes <coordinate-conventions>`. The input is used as given, not
+ renormalized, so each map should sum to one, as the output of
+ :func:`~kornia.geometry.subpix.spatial_softmax2d` does: a map summing to ``s`` scales the result by ``s``.
Args:
input: the input torch.Tensor representing dense spatial probabilities with shape :math:`(B, N, H, W)`.
@@ -146,6 +148,10 @@ def render_gaussian2d(
Each axis is normalised over the grid, so the heatmap sums to one. A mean outside the grid renders the part of
the Gaussian that falls on the grid, rescaled to sum to one; far outside, that mass sits on the nearest border.
+ Convention:
+ - ``mean`` and ``std`` follow :ref:`Coordinates and sizes <coordinate-conventions>`; ``size`` is
+ ``(height, width)``. The default normalized coordinates are corner-aligned.
+
Args:
mean: the mean location of the Gaussian to render, :math:`(\mu_x, \mu_y)`. Shape: :math:`(*, 2)`.
std: the standard deviation of the Gaussian to render, :math:`(\sigma_x, \sigma_y)`.
diff --git a/kornia/geometry/subpix/nms.py b/kornia/geometry/subpix/nms.py
index 45b706c79..4baa82a89 100644
--- a/kornia/geometry/subpix/nms.py
+++ b/kornia/geometry/subpix/nms.py
@@ -103,7 +103,8 @@ def _neighbourhood_max3d(x: torch.Tensor, kd: int, ky: int, kx: int) -> torch.Te
class NonMaximaSuppression2d(nn.Module):
r"""Apply non maxima suppression to filter.
- Flag `minima_are_also_good` is useful, when you want to detect both maxima and minima, e.g. for DoG
+ Convention:
+ - See the convention block of :func:`~kornia.geometry.subpix.nms2d`.
"""
def __init__(self, kernel_size: tuple[int, int]) -> None:
@@ -140,9 +141,6 @@ class NonMaximaSuppression2d(nn.Module):
neighbors are suppressed. This is commonly used to turn dense corner or
keypoint response maps into sparse candidate locations.
- A location within ``(k - 1) // 2`` of an edge is never a maximum: its window does not fit
- inside the input, so the comparisons that would decide it cannot be made.
-
Args:
x: Response tensor with shape :math:`(B, C, H, W)`, where
:math:`B` is the batch size, :math:`C` is the number of
@@ -293,7 +291,11 @@ class NonMaximaSuppression2d(nn.Module):
class NonMaximaSuppression3d(nn.Module):
- r"""Apply non maxima suppression to filter."""
+ r"""Apply non maxima suppression to filter.
+
+ Convention:
+ - See the convention block of :func:`~kornia.geometry.subpix.nms2d`.
+ """
def __init__(self, kernel_size: tuple[int, int, int]) -> None:
super().__init__()
@@ -310,9 +312,6 @@ class NonMaximaSuppression3d(nn.Module):
width. This is used by scale-space detectors to keep responses that are
locally maximal both in image position and in scale/depth.
- As in :meth:`NonMaximaSuppression2d.forward`, a voxel within ``(k - 1) // 2`` of a boundary
- in any axis is never a maximum: its window does not fit inside the input.
-
Args:
x: Response tensor with shape :math:`(B, C, D, H, W)`, where
:math:`B` is batch size, :math:`C` is channel count,
@@ -390,7 +389,16 @@ class NonMaximaSuppression3d(nn.Module):
def nms2d(input: torch.Tensor, kernel_size: tuple[int, int], mask_only: bool = False) -> torch.Tensor:
r"""Apply non maxima suppression to filter.
- See :class:`~kornia.geometry.subpix.NonMaximaSuppression2d` for details.
+ Convention:
+ - Only strict maxima survive: a position must be greater than every other value in its ``kernel_size``
+ window, so with ``k >= 3`` on every axis every pixel of a plateau is suppressed, even a plateau at the top
+ of the map. :ref:`Coordinates and sizes <coordinate-conventions>` compares this with scikit-image, scipy
+ and OpenCV.
+ - The window spans ``(k - 1) // 2`` positions before the centre and ``k // 2`` after it on each axis, so an
+ even ``k`` reaches one further forward, and the first ``(k - 1) // 2`` and last ``k // 2`` positions of
+ each axis are never maxima.
+ - The default output keeps the input value at each maximum and is ``0`` elsewhere, which is larger than a
+ negative maximum, so use ``mask_only=True`` for a signed response.
"""
return NonMaximaSuppression2d(kernel_size)(input, mask_only)
@@ -398,8 +406,8 @@ def nms2d(input: torch.Tensor, kernel_size: tuple[int, int], mask_only: bool = F
def nms3d(input: torch.Tensor, kernel_size: tuple[int, int, int], mask_only: bool = False) -> torch.Tensor:
r"""Apply non maxima suppression to filter.
- See
- :class: `~kornia.feature.NonMaximaSuppression3d` for details.
+ Convention:
+ - See the convention block of :func:`nms2d`, applied over depth, height and width.
"""
return NonMaximaSuppression3d(kernel_size)(input, mask_only)
@@ -415,6 +423,10 @@ def nms3d_minmax(input: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
comparison-and-reduction ops are visible to the compiler at trace time,
allowing full fusion into a minimal number of kernels.
+ Convention:
+ - The strict and border rules of :func:`nms2d` with a :math:`3 \times 3 \times 3` window, for maxima and
+ minima alike.
+
Args:
input: 5-D tensor of shape :math:`(B, C, D, H, W)`.
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index 67d563679..bf62f7a06 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -178,8 +178,8 @@ def _get_window_grid_kernel3d(d: int, h: int, w: int, device: Optional[torch.dev
class ConvSoftArgmax2d(nn.Module):
r"""nn.Module that calculates soft argmax 2d per window.
- See
- :func: `~kornia.geometry.subpix.conv_soft_argmax2d` for details.
+ Convention:
+ - See the convention block of :func:`~kornia.geometry.subpix.conv_soft_argmax2d`.
"""
def __init__(
@@ -245,8 +245,8 @@ class ConvSoftArgmax2d(nn.Module):
class ConvSoftArgmax3d(nn.Module):
r"""nn.Module that calculates soft argmax 3d per window.
- See
- :func: `~kornia.geometry.subpix.conv_soft_argmax3d` for details.
+ Convention:
+ - See the convention block of :func:`~kornia.geometry.subpix.conv_soft_argmax3d`.
"""
def __init__(
@@ -322,18 +322,32 @@ def conv_soft_argmax2d(
r"""Compute the convolutional spatial Soft-Argmax 2D over the windows of a given heatmap.
.. math::
- ij(X) = \frac{\sum{(i,j)} * exp(x / T) \in X} {\sum{exp(x / T) \in X}}
+ xy(X) = \frac{\sum_{p \in X} (x_p, y_p) \exp(v_p / T)}{\sum_{p \in X} \exp(v_p / T)}
.. math::
- val(X) = \frac{\sum{x * exp(x / T) \in X}} {\sum{exp(x / T) \in X}}
-
- where :math:`T` is temperature.
+ val(X) = \frac{\sum_{p \in X} v_p \exp(v_p / T)}{\sum_{p \in X} \exp(v_p / T)}
+
+ where :math:`X` is a window, :math:`(x_p, y_p)` the column and row of its pixel :math:`p`, :math:`v_p` the
+ heatmap value there and :math:`T` the temperature.
+
+ Convention:
+ - Coordinates follow :ref:`Coordinates and sizes <coordinate-conventions>`. This function defaults to
+ normalized, corner-aligned coordinates.
+ :func:`conv_soft_argmax3d` defaults to pixel coordinates and ``output_value=True`` instead.
+ - ``padding`` adds positions of zero weight, as if the input were padded with ``-inf``: with an odd
+ ``kernel_size``, a window that overhangs the border averages over its in-image pixels only.
+ - Known defects: the exponent is shifted by the maximum of the whole map and ``eps`` is added to each
+ window's denominator, so a window whose values sit far below that maximum, in units of ``temperature``, is
+ pulled toward its centre with a value near ``0``, or is ``NaN`` in float16
+ (`#5020 <https://github.com/kornia/kornia/issues/5020>`_); with an even ``kernel_size`` and
+ ``padding = k // 2`` the border windows average a zero-padded coordinate into their centre and report a
+ point far inside the image (`#5066 <https://github.com/kornia/kornia/issues/5066>`_).
Args:
input: the given heatmap with shape :math:`(N, C, H_{in}, W_{in})`.
kernel_size: the size of the window.
stride: the stride of the window.
- padding: input zero padding.
+ padding: the padding added to each side of the input.
temperature: softmax temperature: the input is divided by it; smaller is sharper. Must be positive.
A tensor temperature is not checked under ``torch.compile`` or export.
normalized_coordinates: whether to return the coordinates normalized in the range of :math:`[-1, 1]`.
@@ -437,21 +451,28 @@ def conv_soft_argmax3d(
r"""Compute the convolutional spatial Soft-Argmax 3D over the windows of a given heatmap.
.. math::
- ijk(X) = \frac{\sum{(i,j,k)} * exp(x / T) \in X} {\sum{exp(x / T) \in X}}
+ dxy(X) = \frac{\sum_{p \in X} (d_p, x_p, y_p) \exp(v_p / T)}{\sum_{p \in X} \exp(v_p / T)}
.. math::
- val(X) = \frac{\sum{x * exp(x / T) \in X}} {\sum{exp(x / T) \in X}}
+ val(X) = \frac{\sum_{p \in X} v_p \exp(v_p / T)}{\sum_{p \in X} \exp(v_p / T)}
+
+ where :math:`X` is a window, :math:`(d_p, x_p, y_p)` the depth, column and row of its voxel :math:`p`,
+ :math:`v_p` the heatmap value there and :math:`T` the temperature.
- where ``T`` is temperature.
+ Convention:
+ - See the convention block of :func:`conv_soft_argmax2d`, including its known defects
+ (`#5020 <https://github.com/kornia/kornia/issues/5020>`_,
+ `#5066 <https://github.com/kornia/kornia/issues/5066>`_). Coordinates follow
+ :ref:`Coordinates and sizes <coordinate-conventions>`; this function defaults to pixel coordinates.
Args:
input: the given heatmap with shape :math:`(N, C, D_{in}, H_{in}, W_{in})`.
kernel_size: size of the window.
stride: stride of the window.
- padding: input zero padding.
+ padding: the padding added to each side of the input.
temperature: softmax temperature: the input is divided by it; smaller is sharper. Must be positive.
A tensor temperature is not checked under ``torch.compile`` or export.
- normalized_coordinates: whether to return the coordinates normalized in the range of :math:[-1, 1]`.
+ normalized_coordinates: whether to return the coordinates normalized in the range of :math:`[-1, 1]`.
Otherwise, it will return the coordinates in the range of the input shape.
eps: small value to avoid zero division.
output_value: if True, val is output, if False, only ij.
@@ -553,6 +574,13 @@ def spatial_soft_argmax2d(
) -> torch.Tensor:
r"""Compute the Spatial Soft-Argmax 2D of a given input heatmap.
+ Convention:
+ - Coordinates follow :ref:`Coordinates and sizes <coordinate-conventions>`; this function defaults to
+ normalized, corner-aligned coordinates.
+ - It is ``spatial_expectation2d(spatial_softmax2d(input, temperature))``: the expected coordinate under the
+ softmax of each whole :math:`H \times W` map, so two equal peaks that dominate the map give their midpoint,
+ not either peak.
+
Args:
input: the given heatmap with shape :math:`(B, N, H, W)`.
temperature: softmax temperature: the input is divided by it; smaller is sharper. Must be positive.
@@ -561,8 +589,7 @@ def spatial_soft_argmax2d(
Otherwise, it will return the coordinates in the range of the input shape.
Returns:
- the index of the maximum 2d coordinates of the give map :math:`(B, N, 2)`.
- The output order is x-coord and y-coord.
+ the expected coordinates of each map with shape :math:`(B, N, 2)`.
Examples:
>>> input = torch.tensor([[[
@@ -581,7 +608,8 @@ def spatial_soft_argmax2d(
class SpatialSoftArgmax2d(nn.Module):
r"""Compute the Spatial Soft-Argmax 2D of a given heatmap.
- See :func:`~kornia.geometry.subpix.spatial_soft_argmax2d` for details.
+ Convention:
+ - See the convention block of :func:`~kornia.geometry.subpix.spatial_soft_argmax2d`.
"""
def __init__(self, temperature: Optional[torch.Tensor | float] = None, normalized_coordinates: bool = True) -> None:
@@ -773,8 +801,22 @@ def conv_quad_interp3d(
default ``max_subpixel_shift=0.6`` almost all keypoints converge within 1 move,
so the default ``dilation_radius=1`` (i.e. :math:`3^3 = 27` positions per
maximum) is sufficient. Use ``dilation_radius=2`` (:math:`5^3 = 125`) for
- extra safety. Setting it equal to ``n_iters`` recovers the original behaviour
- but is much slower on large images.
+ extra safety. Setting it to ``n_iters`` gives the result of
+ :func:`iterative_quad_interp3d`, but is much slower on large images.
+
+ Convention:
+ - ``coords_max`` follows :ref:`Coordinates and sizes <coordinate-conventions>` and holds absolute voxel
+ indices of the input: only refined maxima move off their own grid index. At a refined maximum ``y_max`` is
+ the quadratic fit's value at the refined point; non-maxima keep their input value.
+ - A maximum is not refined, and keeps its grid coordinates, when the determinant of its fit's Hessian is at
+ most ``1e-7`` in magnitude, when a move would reach the border voxels, when its centre leaves the voxels
+ precomputed for ``dilation_radius``, when the final shift exceeds ``1.5`` voxels on any axis, or when it
+ still requires an integer-centre move on the last iteration. A volume with a side shorter than 3 is returned
+ unrefined.
+ - Known defect: the ``1e-7`` determinant floor is absolute while the determinant is cubic in the response
+ amplitude, so low-amplitude maxima stay unrefined, among them most keypoints of the default
+ :class:`~kornia.feature.ScaleSpaceDetector` on a ``[0, 1]`` image
+ (`#5065 <https://github.com/kornia/kornia/issues/5065>`_).
Args:
input: response pyramid with shape :math:`(B, C, D, H, W)`.
@@ -1027,6 +1069,9 @@ class ConvQuadInterp3d(nn.Module):
table lookup with no GPU→CPU synchronisation — making the module compatible
with ``torch.compile`` and CUDA graphs.
+ Convention:
+ - See the convention block of :func:`~kornia.geometry.subpix.conv_quad_interp3d`.
+
Args:
n_iters: maximum localization iterations per keypoint.
strict_maxima_bonus: deprecated since kornia 0.9.0 and ignored; passing it emits a
@@ -1105,8 +1150,11 @@ def iterative_quad_interp3d(
function explicitly re-extracts the :math:`3 \times 3 \times 3` patch at each
NMS maximum and iterates up to ``n_iters`` times. When the estimated subpixel
shift along any spatial or scale axis exceeds ``max_subpixel_shift`` the integer
- center is moved one step in that direction and the solve is repeated β€” matching
- the localization loop from the HessAff / SIFT family of detectors.
+ center is moved one step in that direction and the solve is repeated.
+
+ Convention:
+ - See the convention block of :func:`conv_quad_interp3d`; here a maximum is not limited to a
+ ``dilation_radius`` neighbourhood.
Args:
input: response pyramid with shape :math:`(B, C, D, H, W)`.
@@ -1334,7 +1382,8 @@ def iterative_quad_interp3d(
class IterativeQuadInterp3d(nn.Module):
r"""Iterative subpixel localization of 3D extrema via quadratic interpolation.
- See :func:`~kornia.geometry.subpix.iterative_quad_interp3d` for details.
+ Convention:
+ - See the convention block of :func:`~kornia.geometry.subpix.iterative_quad_interp3d`.
"""
def __init__(
@@ -1403,6 +1452,9 @@ class AdaptiveQuadInterp3d(nn.Module):
* **CPU** β€” :func:`iterative_quad_interp3d` is faster for large images because
it processes only the NMS maxima directly without any dilation/dedup overhead.
+ Convention:
+ - See the convention block of :func:`~kornia.geometry.subpix.conv_quad_interp3d`.
+
Args:
mode: backend selection strategy.
diff --git a/testing/base.py b/testing/base.py
index cb915aa7c..a7d766c52 100644
--- a/testing/base.py
+++ b/testing/base.py
@@ -343,6 +343,20 @@ def supports_topk(device: torch.device, dtype: torch.dtype) -> bool:
return _supports_kernel_probe(_topk_op, device.type, dtype)
+def _avg_pool3d_op(device_type: str, dtype: torch.dtype) -> None:
+ F.avg_pool3d(_probe_zeros(device_type, dtype, 1, 1, 1, 1, 1), 1)
+
+
+def supports_avg_pool3d(device: torch.device, dtype: torch.dtype) -> bool:
+ """Whether this device has a 3D average-pooling kernel for ``dtype``.
+
+ :func:`kornia.geometry.subpix.conv_soft_argmax3d` pools its windows with ``avg_pool3d``, which
+ torch has no float16 / bfloat16 CPU kernel for. Probed at runtime and cached per (device type,
+ dtype), like :func:`supports_replicate_padding`.
+ """
+ return _supports_kernel_probe(_avg_pool3d_op, device.type, dtype)
+
+
class BaseTester:
@staticmethod
def assert_close(
diff --git a/tests/geometry/subpix/test_dsnt.py b/tests/geometry/subpix/test_dsnt.py
index d9afaa10f..c6f2bf88d 100644
--- a/tests/geometry/subpix/test_dsnt.py
+++ b/tests/geometry/subpix/test_dsnt.py
@@ -265,3 +265,66 @@ class TestSpatialExpectation2d(BaseTester):
op_optimized = torch_optimizer(op)
self.assert_close(op(data, True), op_optimized(data, True))
+
+
+class TestConventionsDsnt(BaseTester):
+ def test_convention_spatial_soft_argmax2d_is_xy_corner_aligned(self, device, dtype):
+ # The output is (x, y) = (column, row): pixel coordinates of the input grid, or normalized corner-aligned
+ # ones (pixel centres 0 and W - 1 at -1 and +1). H != W and an off-centre peak, so neither a (y, x) output
+ # nor a half-pixel grid can pass; the transposed map is the relabel control. A logit of 30 makes the softmax
+ # one-hot at every dtype.
+ heatmap = torch.zeros(1, 1, 4, 7, device=device, dtype=dtype)
+ heatmap[0, 0, 1, 5] = 30.0
+ pixel = kornia.geometry.subpix.spatial_soft_argmax2d(heatmap, normalized_coordinates=False)
+ self.assert_close(pixel, torch.tensor([[[5.0, 1.0]]], device=device, dtype=dtype))
+ transposed = heatmap.transpose(-2, -1).contiguous()
+ pixel = kornia.geometry.subpix.spatial_soft_argmax2d(transposed, normalized_coordinates=False)
+ self.assert_close(pixel, torch.tensor([[[1.0, 5.0]]], device=device, dtype=dtype))
+
+ normalized = kornia.geometry.subpix.spatial_soft_argmax2d(heatmap)
+ self.assert_close(normalized, torch.tensor([[[2 / 3, -1 / 3]]], device=device, dtype=dtype))
+ corner = torch.zeros(1, 1, 4, 7, device=device, dtype=dtype)
+ corner[0, 0, 0, 6] = 30.0
+ # corner-aligned: the last column is +1 and the first row -1; a half-pixel grid gives (6/7, -3/4)
+ normalized = kornia.geometry.subpix.spatial_soft_argmax2d(corner)
+ self.assert_close(normalized, torch.tensor([[[1.0, -1.0]]], device=device, dtype=dtype))
+
+ def test_convention_render_gaussian2d_mean_std_are_xy(self, device, dtype):
+ # mean and std are (x, y) = (column, row) and size is (H, W): an anisotropic Gaussian off the centre of a
+ # 25 x 21 canvas has a column marginal with mean 10 and std 2 and a row marginal with mean 12 and std 1.
+ mean = torch.tensor([[10.0, 12.0]], device=device, dtype=dtype)
+ std = torch.tensor([[2.0, 1.0]], device=device, dtype=dtype)
+ heatmap = kornia.geometry.subpix.render_gaussian2d(mean, std, (25, 21), False)
+ assert heatmap.shape == (1, 25, 21)
+
+ # Measure the rendered distribution's moments in float64.
+ h = heatmap[0].cpu().double()
+ total = h.sum()
+ cols = torch.arange(21, dtype=torch.float64)
+ rows = torch.arange(25, dtype=torch.float64)
+ mean_x = float((h.sum(0) * cols).sum() / total)
+ mean_y = float((h.sum(1) * rows).sum() / total)
+ std_x = float(((h.sum(0) * (cols - mean_x) ** 2).sum() / total).sqrt())
+ std_y = float(((h.sum(1) * (rows - mean_y) ** 2).sum() / total).sqrt())
+ tol = 5e-3 if dtype in (torch.float16, torch.bfloat16) else 1e-5
+ assert abs(mean_x - 10.0) < tol, mean_x
+ assert abs(mean_y - 12.0) < tol, mean_y
+ assert abs(std_x - 2.0) < tol, std_x
+ assert abs(std_y - 1.0) < tol, std_y
+
+ # relabel: swapping the (x, y) components and the (H, W) size renders the transpose
+ swapped = kornia.geometry.subpix.render_gaussian2d(mean.flip(-1), std.flip(-1), (21, 25), False)
+ self.assert_close(swapped[0], heatmap[0].T)
+
+ def test_convention_spatial_expectation2d_uses_the_input_as_given(self, device, dtype):
+ # The heatmap is not renormalized: a map summing to s scales the expected (x, y) by s, in pixels and in
+ # normalized coordinates alike. Mass 0.75 at (row 0, col 4) and 0.25 at (row 2, col 1) of a 3 x 5 map gives
+ # (x, y) = (3.25, 0.5) in pixels and (0.625, -0.5) normalized; doubling the map doubles both.
+ probs = torch.zeros(1, 1, 3, 5, device=device, dtype=dtype)
+ probs[0, 0, 0, 4] = 0.75
+ probs[0, 0, 2, 1] = 0.25
+ for scale in (1.0, 2.0):
+ pixel = kornia.geometry.subpix.spatial_expectation2d(scale * probs, normalized_coordinates=False)
+ self.assert_close(pixel, scale * torch.tensor([[[3.25, 0.5]]], device=device, dtype=dtype))
+ normalized = kornia.geometry.subpix.spatial_expectation2d(scale * probs)
+ self.assert_close(normalized, scale * torch.tensor([[[0.625, -0.5]]], device=device, dtype=dtype))
diff --git a/tests/geometry/subpix/test_nms.py b/tests/geometry/subpix/test_nms.py
index 2524f210f..1b7ae37f3 100644
--- a/tests/geometry/subpix/test_nms.py
+++ b/tests/geometry/subpix/test_nms.py
@@ -472,3 +472,23 @@ class TestNMS3dMinMax(BaseTester):
# nms3d_minmax is not differentiable (bool masks), so we just check it runs.
inp = torch.randn(1, 1, 5, 7, 7, device=device)
kornia.geometry.subpix.nms3d_minmax(inp)
+
+
+class TestConventionsNMS2d(BaseTester):
+ def test_convention_nms2d_value_output_zeroes_suppressed(self, device, dtype):
+ # The default output keeps the input value at each maximum and is 0 elsewhere, in the input dtype: suppressed
+ # positions are 0, not -inf. On a signed response a suppressed 0 therefore outranks a negative maximum, so
+ # rank with mask_only=True, which returns the boolean mask. H != W and an off-centre maximum.
+ response = torch.full((1, 1, 5, 7), -5.0, device=device, dtype=dtype)
+ response[0, 0, 2, 3] = -1.0
+ expected = torch.zeros(1, 1, 5, 7, device=device, dtype=dtype)
+ expected[0, 0, 2, 3] = -1.0
+
+ values = kornia.geometry.subpix.nms2d(response, (3, 3))
+ assert values.dtype == dtype
+ self.assert_close(values, expected, atol=0.0, rtol=0.0)
+ assert float(values.max()) == 0.0 > float(values[0, 0, 2, 3])
+
+ mask = kornia.geometry.subpix.nms2d(response, (3, 3), mask_only=True)
+ assert mask.dtype == torch.bool
+ assert mask.nonzero().tolist() == [[0, 0, 2, 3]]
diff --git a/tests/geometry/subpix/test_spatial_softargmax.py b/tests/geometry/subpix/test_spatial_softargmax.py
index d123c87ae..7657fed50 100644
--- a/tests/geometry/subpix/test_spatial_softargmax.py
+++ b/tests/geometry/subpix/test_spatial_softargmax.py
@@ -28,7 +28,7 @@ from kornia.geometry.subpix.spatial_soft_argmax import (
conv_quad_interp3d,
)
-from testing.base import BaseTester
+from testing.base import BaseTester, supports_avg_pool3d
class TestCenterKernel2d(BaseTester):
@@ -1112,3 +1112,168 @@ class TestStrictMaximaBonusDeprecated(BaseTester):
new = kornia.feature.ScaleSpaceDetector(16).to(device)
for got, want in zip(old(img), new(img)):
self.assert_close(got, want, atol=0, rtol=0)
+
+
+class TestConventionsConvSoftArgmax(BaseTester):
+ def test_convention_conv_soft_argmax2d_is_xy(self, device, dtype):
+ # Every window returns (x, y) = (column, row) of the input grid: pixel coordinates, or normalized
+ # corner-aligned ones (the default). One hot pixel at (row 1, col 6) of a 5 x 8 map: the window on it and the
+ # four windows beside it, which see it one step off their centre along one axis, all return (6, 1), so neither
+ # the window centres nor the in-window offsets may swap the axes. The transposed map is the relabel control.
+ heatmap = torch.zeros(1, 1, 5, 8, device=device, dtype=dtype)
+ heatmap[0, 0, 1, 6] = 30.0
+ coords = kornia.geometry.subpix.conv_soft_argmax2d(heatmap, (3, 3), normalized_coordinates=False)
+ assert coords.shape == (1, 1, 2, 5, 8)
+ expected = torch.tensor([6.0, 1.0], device=device, dtype=dtype)
+ for row, col in ((1, 6), (1, 5), (1, 7), (0, 6), (2, 6)):
+ self.assert_close(coords[0, 0, :, row, col], expected)
+
+ transposed = heatmap.transpose(-2, -1).contiguous()
+ coords = kornia.geometry.subpix.conv_soft_argmax2d(transposed, (3, 3), normalized_coordinates=False)
+ self.assert_close(coords[0, 0, :, 6, 1], torch.tensor([1.0, 6.0], device=device, dtype=dtype))
+
+ # corner-aligned: (2 * 6 / 7 - 1, 2 * 1 / 4 - 1); a half-pixel normalization gives (0.625, -0.4)
+ coords = kornia.geometry.subpix.conv_soft_argmax2d(heatmap, (3, 3))
+ self.assert_close(coords[0, 0, :, 1, 6], torch.tensor([5 / 7, -0.5], device=device, dtype=dtype))
+
+ def test_convention_conv_soft_argmax3d_is_dxy(self, device, dtype):
+ # The 3-D windows return (d, x, y) = (depth, column, row). D != H != W, one hot voxel at (d 2, row 1, col 6):
+ # the window on it and the six beside it return (2, 6, 1). Swapping D and W is the relabel control.
+ if not supports_avg_pool3d(device, dtype):
+ pytest.skip(f"torch has no avg_pool3d kernel for {device.type} {dtype}")
+ volume = torch.zeros(1, 1, 4, 5, 8, device=device, dtype=dtype)
+ volume[0, 0, 2, 1, 6] = 30.0
+ coords, _ = kornia.geometry.subpix.conv_soft_argmax3d(volume, (3, 3, 3))
+ assert coords.shape == (1, 1, 3, 4, 5, 8)
+ expected = torch.tensor([2.0, 6.0, 1.0], device=device, dtype=dtype)
+ for d, row, col in ((2, 1, 6), (1, 1, 6), (3, 1, 6), (2, 0, 6), (2, 2, 6), (2, 1, 5), (2, 1, 7)):
+ self.assert_close(coords[0, 0, :, d, row, col], expected)
+
+ permuted = volume.permute(0, 1, 4, 3, 2).contiguous() # (D, H, W) = (8, 5, 4), hot at (6, 1, 2)
+ coords, _ = kornia.geometry.subpix.conv_soft_argmax3d(permuted, (3, 3, 3))
+ self.assert_close(coords[0, 0, :, 6, 1, 2], torch.tensor([6.0, 2.0, 1.0], device=device, dtype=dtype))
+
+ coords, _ = kornia.geometry.subpix.conv_soft_argmax3d(volume, (3, 3, 3), normalized_coordinates=True)
+ expected = torch.tensor([1 / 3, 5 / 7, -0.5], device=device, dtype=dtype)
+ self.assert_close(coords[0, 0, :, 2, 1, 6], expected)
+
+ def test_wart_conv_soft_argmax_eps_erases_far_windows_5020(self, device, dtype):
+ # #5020: global stabilization and per-window eps erase a local peak far below the map maximum.
+ heatmap = torch.zeros(1, 1, 7, 15, device=device, dtype=dtype)
+ heatmap[0, 0, 3, 2] = 40.0 # the map maximum, eight columns from the window under test
+ heatmap[0, 0, 3, 10] = 1.0
+ heatmap[0, 0, 3, 11] = 0.8 # pulls the window's soft-argmax right of its centre
+ coords, values = kornia.geometry.subpix.conv_soft_argmax2d(
+ heatmap, (3, 3), normalized_coordinates=False, output_value=True
+ )
+ x, value = coords[0, 0, 0, 3, 10], values[0, 0, 3, 10]
+ if dtype == torch.float16:
+ assert bool(x.isnan()) and bool(value.isnan())
+ else:
+ assert abs(float(x) - 10.0) < 1e-6
+ assert abs(float(value)) < 1e-6
+ coords, values = kornia.geometry.subpix.conv_soft_argmax2d(
+ heatmap, (3, 3), normalized_coordinates=False, output_value=True, eps=0.0
+ )
+ assert float(coords[0, 0, 0, 3, 10]) > 10.05
+ assert float(values[0, 0, 3, 10]) > 0.3
+
+ def test_wart_conv_soft_argmax2d_even_window_border_centre_5066(self, device, dtype):
+ # #5066: zero padding moves an even border window's reported centre away from its hot pixel.
+ heatmap = torch.zeros(1, 1, 5, 9, device=device, dtype=dtype)
+ heatmap[0, 0, 2, 8] = 50.0
+ odd = kornia.geometry.subpix.conv_soft_argmax2d(heatmap, (3, 3), (1, 1), (1, 1), normalized_coordinates=False)
+ self.assert_close(odd[0, 0, 0, 2, -1], torch.tensor(8.0, device=device, dtype=dtype))
+ even = kornia.geometry.subpix.conv_soft_argmax2d(heatmap, (4, 4), (1, 1), (2, 2), normalized_coordinates=False)
+ assert even.shape[-1] == 10
+ assert float(even[0, 0, 0, 2, -1]) < 5.0
+
+
+class TestConventionsQuadInterp3d(BaseTester):
+ _FUNCTIONS = (kornia.geometry.subpix.conv_quad_interp3d, kornia.geometry.subpix.iterative_quad_interp3d)
+
+ @staticmethod
+ def _separable(device, dtype, profile_w, depth_peak=1.0):
+ # f(d, h, w) = profile_w[w] - (h - 2) ** 2 - (d - depth_peak) ** 2 on a 4 x 6 x 9 volume: no mixed terms, so
+ # the quadratic fit at a voxel solves each axis on its own from the samples either side of it.
+ d = torch.arange(4, dtype=torch.float64).view(4, 1, 1)
+ h = torch.arange(6, dtype=torch.float64).view(1, 6, 1)
+ w = torch.tensor(profile_w, dtype=torch.float64).view(1, 1, 9)
+ return (w - (h - 2) ** 2 - (d - depth_peak) ** 2)[None, None].to(device, dtype)
+
+ @pytest.mark.parametrize("fn", _FUNCTIONS, ids=["conv", "iterative"])
+ def test_convention_quad_interp3d_coords_are_dxy_voxel_indices(self, device, dtype, fn):
+ # The refined coordinates are (d, x, y) = (depth, column, row) absolute voxel indices of the input, not
+ # offsets. A 1.0 peak at (d 1, row 2, col 5) with one 0.5 neighbour on one axis at a time moves 1/6 toward
+ # it along that axis only; other voxels keep their grid index. The transposed volume is the relabel control.
+ cases = (
+ ((1, 2, 6), [1.0, 5 + 1 / 6, 2.0]), # right neighbour: x grows
+ ((1, 2, 4), [1.0, 5 - 1 / 6, 2.0]), # left neighbour: x shrinks
+ ((1, 3, 5), [1.0, 5.0, 2 + 1 / 6]), # neighbour one row down: y grows
+ ((2, 2, 5), [1 + 1 / 6, 5.0, 2.0]), # neighbour one level deeper: d grows
+ )
+ for neighbour, expected in cases:
+ volume = torch.zeros(1, 1, 4, 6, 9, device=device, dtype=dtype)
+ volume[0, 0, 1, 2, 5] = 1.0
+ volume[(0, 0, *neighbour)] = 0.5
+ coords, _ = fn(volume)
+ self.assert_close(coords[0, 0, :, 1, 2, 5], torch.tensor(expected, device=device, dtype=dtype))
+ self.assert_close(coords[0, 0, :, 3, 4, 7], torch.tensor([3.0, 7.0, 4.0], device=device, dtype=dtype))
+
+ volume = torch.zeros(1, 1, 4, 6, 9, device=device, dtype=dtype)
+ volume[0, 0, 1, 2, 5] = 1.0
+ volume[0, 0, 1, 2, 6] = 0.5
+ coords, _ = fn(volume.transpose(-2, -1).contiguous()) # peak at (1, 5, 2), neighbour one row down
+ self.assert_close(coords[0, 0, :, 1, 5, 2], torch.tensor([1.0, 2.0, 5 + 1 / 6], device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("fn", _FUNCTIONS, ids=["conv", "iterative"])
+ def test_convention_quad_interp3d_move_and_reject_thresholds(self, device, dtype, fn):
+ # A shift above max_subpixel_shift (0.6) on an axis moves the integer centre one voxel and the fit is solved
+ # again there; a final shift above 1.5 on any axis rejects the point, which then keeps its grid coordinates.
+ # The candidate is forced at (d 1, row 2, col 5) and only the x profile varies. The x samples are not one
+ # parabola, so the fit at col 6 disagrees with the fit at col 5 and the reported x shows whether it moved.
+ mask = torch.zeros(1, 1, 4, 6, 9, device=device, dtype=torch.bool)
+ mask[0, 0, 1, 2, 5] = True
+ low = -6.0
+ # fit at col 5: shift 0.55, no move -> 5.55 (a move would land on the fit at col 6: 6 - 1/3)
+ stays = [low, low, low, low, -2.1, 0.0, 0.1, -0.4, low]
+ # fit at col 5: shift 0.65, move; fit at col 6: shift -0.2, stay -> 5.8 (without the move: 5.65)
+ moves = [low, low, low, low, -2.3, 0.0, 0.3, -0.4, low]
+ for profile, expected in ((stays, 5.55), (moves, 5.8)):
+ coords, _ = fn(self._separable(device, dtype, profile), n_iters=2, precomputed_nms_mask=mask)
+ self.assert_close(coords[0, 0, :, 1, 2, 5], torch.tensor([1.0, expected, 2.0], device=device, dtype=dtype))
+
+ # With allow_scale_steps=False, the depth shift itself meets the 1.5 bound: 1.4 is kept, 1.6 is rejected.
+ parabola = [-((w - 5.0) ** 2) for w in range(9)]
+ for depth_peak, expected in ((2.4, [2.4, 5.0, 2.0]), (2.6, [1.0, 5.0, 2.0])):
+ volume = self._separable(device, dtype, parabola, depth_peak)
+ coords, _ = fn(volume, precomputed_nms_mask=mask, allow_scale_steps=False)
+ self.assert_close(coords[0, 0, :, 1, 2, 5], torch.tensor(expected, device=device, dtype=dtype))
+
+ # The same 1.5 bound on x: with max_subpixel_shift=2 an x shift of 1.4 or 1.6 does not move the centre, and
+ # only 1.6 rejects the point.
+ for peak, expected in ((6.4, 6.4), (6.6, 5.0)):
+ volume = self._separable(device, dtype, [-((w - peak) ** 2) for w in range(9)])
+ coords, _ = fn(volume, precomputed_nms_mask=mask, max_subpixel_shift=2.0)
+ self.assert_close(coords[0, 0, 1, 1, 2, 5], torch.tensor(expected, device=device, dtype=dtype))
+
+ # x peak at 7.4: two moves (col 5 -> 6 -> 7), then the shift 0.4 stays. The conv backend has solved only
+ # the voxels within dilation_radius of the candidate, so radius 1 rejects the point and radius 2 keeps it.
+ volume = self._separable(device, dtype, [-((w - 7.4) ** 2) for w in range(9)])
+ if fn is kornia.geometry.subpix.conv_quad_interp3d:
+ coords, _ = fn(volume, precomputed_nms_mask=mask, dilation_radius=1)
+ self.assert_close(coords[0, 0, 1, 1, 2, 5], torch.tensor(5.0, device=device, dtype=dtype))
+ coords, _ = fn(volume, precomputed_nms_mask=mask, dilation_radius=2)
+ else:
+ coords, _ = fn(volume, precomputed_nms_mask=mask)
+ self.assert_close(coords[0, 0, 1, 1, 2, 5], torch.tensor(7.4, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("fn", _FUNCTIONS, ids=["conv", "iterative"])
+ def test_wart_quad_interp3d_absolute_determinant_floor_5065(self, device, dtype, fn):
+ # #5065: the absolute Hessian determinant floor refines this peak at unit amplitude but rejects it at 1e-3.
+ for amplitude, expected_x in ((1.0, 5 + 1 / 6), (1e-3, 5.0)):
+ volume = torch.zeros(1, 1, 4, 6, 9, device=device, dtype=dtype)
+ volume[0, 0, 1, 2, 5] = amplitude
+ volume[0, 0, 1, 2, 6] = 0.5 * amplitude
+ coords, _ = fn(volume)
+ self.assert_close(coords[0, 0, 1, 1, 2, 5], torch.tensor(expected_x, device=device, dtype=dtype))
diff --git a/tests/geometry/test_grid.py b/tests/geometry/test_grid.py
index 5850117f6..0dd41e3e9 100644
--- a/tests/geometry/test_grid.py
+++ b/tests/geometry/test_grid.py
@@ -26,6 +26,8 @@ from testing.base import (
assert_close,
dynamic_export_is_available,
dynamo_is_available,
+ supports_bilinear_2d_grid_sample,
+ supports_bilinear_3d_grid_sample,
)
@@ -409,3 +411,53 @@ def test_normalized_meshgrid3d_trace_crosses_singleton_boundary(trace_depth, run
runtime = torch.zeros(1, 1, runtime_depth, 3, 4, device=device, dtype=dtype)
traced = torch.jit.trace(MeshGrid3d(), example)
assert_close(traced(runtime), MeshGrid3d()(runtime), atol=0.0, rtol=0.0)
+
+
+def test_convention_create_meshgrid_align_corners_matches_grid_sample(device, dtype):
+ # A normalized grid samples an image as the identity only under grid_sample's own align_corners flag: True puts
+ # pixel centres 0 and W - 1 at -1 and +1, False puts the outer pixel edges there. Crossing the flags shifts every
+ # sample. H != W, so neither axis can stand in for the other.
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip(f"torch has no bilinear 2D grid_sample kernel for {device.type} {dtype}")
+ generator = torch.Generator(device="cpu").manual_seed(0)
+ image = torch.rand(1, 1, 3, 5, generator=generator).to(device, dtype)
+
+ for align_corners in (True, False):
+ grid = kornia.geometry.create_meshgrid(3, 5, device=device, dtype=dtype, align_corners=align_corners)
+ same = torch.nn.functional.grid_sample(image, grid, align_corners=align_corners)
+ crossed = torch.nn.functional.grid_sample(image, grid, align_corners=not align_corners)
+ assert_close(same, image)
+ assert (crossed - image).abs().max() > 0.1
+
+
+def test_convention_create_meshgrid3d_reorder_for_grid_sample(device, dtype):
+ # The last axis of create_meshgrid3d is (d, x, y) -- depth, column, row -- while grid_sample reads (x, y, z), so
+ # the default corner-aligned grid samples a volume as the identity after the [1, 2, 0] reorder.
+ # D != H != W; the permuted volume is the relabel control.
+ if not supports_bilinear_3d_grid_sample(device, dtype):
+ pytest.skip(f"torch has no bilinear 3D grid_sample kernel for {device.type} {dtype}")
+ pixel = kornia.geometry.create_meshgrid3d(2, 3, 4, normalized_coordinates=False, device=device, dtype=dtype)
+ # (d, h, w) = (1, 2, 3) holds (d, x, y) = (1, 3, 2)
+ assert_close(pixel[0, 1, 2, 3], torch.tensor([1.0, 3.0, 2.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+
+ generator = torch.Generator(device="cpu").manual_seed(0)
+ volume = torch.rand(1, 1, 2, 3, 4, generator=generator).to(device, dtype)
+ grid = kornia.geometry.create_meshgrid3d(2, 3, 4, device=device, dtype=dtype)
+ reordered = torch.nn.functional.grid_sample(volume, grid[..., [1, 2, 0]], align_corners=True)
+ as_is = torch.nn.functional.grid_sample(volume, grid, align_corners=True)
+ assert_close(reordered, volume)
+ assert (as_is - volume).abs().max() > 0.1
+
+ permuted = volume.permute(0, 1, 4, 2, 3).contiguous() # (D, H, W) = (4, 2, 3)
+ grid = kornia.geometry.create_meshgrid3d(4, 2, 3, device=device, dtype=dtype)
+ assert_close(torch.nn.functional.grid_sample(permuted, grid[..., [1, 2, 0]], align_corners=True), permuted)
+
+
+ strict=True, raises=TypeError, reason="#4503: create_meshgrid3d cannot produce an align_corners=False grid"
+)
+def test_wart_create_meshgrid3d_lacks_align_corners_false_4503(device, dtype):
+ # Correct half-pixel coordinates for (D, H, W) = (2, 3, 4), in Kornia's (d, x, y) order.
+ grid = kornia.geometry.create_meshgrid3d(2, 3, 4, device=device, dtype=dtype, align_corners=False)
+ assert_close(grid[0, 0, 0, 0], torch.tensor([-0.5, -0.75, -2 / 3], device=device, dtype=dtype))
+ assert_close(grid[0, -1, -1, -1], torch.tensor([0.5, 0.75, 2 / 3], device=device, dtype=dtype))