Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(geometry): per-op Convention blocks for crops, flips, pyramid, TPS and elastic (#3926)

Dmytro Mishkina2745009f9db
diff --git a/CLAUDE.md b/CLAUDE.md
index 1e7b87fbf..623f7555b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -94,6 +94,8 @@ class TestMyFunction(BaseTester):
The `device` and `dtype` fixtures are injected automatically. Use `self.assert_close()` for tensor comparisons. Test configurations are driven by env vars `KORNIA_TEST_DEVICE` and `KORNIA_TEST_DTYPE`, or by `--device`/`--dtype` pytest args.
+Tests actually run under the repo `.venv` (`pixi run test`/`test-quick`/etc. all shell out to `uv run pytest`, which uses `.venv`) β€” the separate `.pixi` conda environment is not what test invocations use and its package versions should not be assumed to match `.venv`.
+
## Coding Standards
- **Python >= 3.11** with `from __future__ import annotations` for non-JIT modules
diff --git a/docs/source/geometry.transform.rst b/docs/source/geometry.transform.rst
index acb8bc163..6a32d6070 100644
--- a/docs/source/geometry.transform.rst
+++ b/docs/source/geometry.transform.rst
@@ -72,9 +72,18 @@ Crop operators
.. autofunction:: crop_by_indices
.. autofunction:: crop_by_boxes
+.. autofunction:: crop_by_transform_mat
.. autofunction:: center_crop
.. autofunction:: crop_and_resize
+Crop operators (3D)
+--------------------
+
+.. autofunction:: crop_by_boxes3d
+.. autofunction:: crop_by_transform_mat3d
+.. autofunction:: center_crop3d
+.. autofunction:: crop_and_resize3d
+
Module
------
@@ -95,6 +104,7 @@ Module
.. autoclass:: Affine
.. autoclass:: BaseWarper
.. autoclass:: HomographyWarper
+.. autoclass:: CenterCrop2D
Image registration
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index f0890d678..26d7671fb 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -48,6 +48,15 @@ def crop_and_resize(
) -> torch.Tensor:
r"""Extract crops from 2D images (4D torch.Tensor) and resize given a bounding box.
+ Convention:
+ - input: :math:`(B, C, H, W)`; ``size`` is ``(h, w)``
+ - ``boxes``: :math:`(B, 4, 2)` corner points in ``(x, y)`` order
+ top-left, top-right, bottom-right, bottom-left; coordinates are
+ **inclusive** pixel positions (box ``(1, 1)``..``(2, 2)`` selects a
+ :math:`2 \times 2` pixel block), origin at top-left
+ - align_corners: ``True`` by default
+ - padding_mode: ``'zeros'`` by default
+
Args:
input_tensor: the 2D image torch.Tensor with shape (B, C, H, W).
boxes : a torch.Tensor containing the coordinates of the bounding boxes to be extracted.
@@ -59,7 +68,7 @@ def crop_and_resize(
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'torch.zeros'`` | ``'border'`` | 'reflection'.
+ ``'zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: mode for grid_generation.
Returns:
@@ -122,6 +131,12 @@ def center_crop(
) -> torch.Tensor:
r"""Crop the 2D images (4D torch.Tensor) from the center.
+ Convention:
+ - input: :math:`(B, C, H, W)` (strictly 4D β€” no unbatched ``(C, H, W)``/
+ ``(H, W)`` input is accepted); ``size`` is ``(h, w)``
+ - align_corners: ``True`` by default
+ - padding_mode: ``'zeros'`` by default
+
Args:
input_tensor: the 2D image torch.Tensor with shape (B, C, H, W).
size: a tuple with the expected height and width
@@ -129,7 +144,7 @@ def center_crop(
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: mode for grid_generation.
Returns:
@@ -207,6 +222,16 @@ def crop_by_boxes(
So far, the ragged torch.Tensor is not supported by PyTorch right now. This function hereby requires
the bounding boxes in a batch must be rectangles with same width and height.
+ Convention:
+ - input: :math:`(B, C, H, W)`
+ - ``src_box``/``dst_box``: :math:`(B, 4, 2)` corner points in ``(x, y)`` order
+ top-left, top-right, bottom-right, bottom-left β€” same convention as
+ :func:`crop_and_resize`; ``dst_box`` determines the output resolution
+ - a single box (batch size 1) broadcasts over a batch of images, but a single
+ image does not broadcast over a batch of boxes
+ - align_corners: ``True`` by default
+ - padding_mode: ``'zeros'`` by default
+
Args:
input_tensor: the 2D image torch.Tensor with shape (B, C, H, W).
src_box: a torch.Tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes
@@ -220,7 +245,7 @@ def crop_by_boxes(
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: mode for grid_generation.
validate_boxes: flag to perform validation on boxes.
@@ -281,6 +306,28 @@ def crop_by_transform_mat(
) -> torch.Tensor:
"""Perform crop transform on 2D images (4D torch.Tensor) given a perspective transformation matrix.
+ Convention:
+ - input: :math:`(B, C, H, W)`; ``out_size`` is ``(h, w)``
+ - ``transform`` is the source→destination **pixel** transform, accepted as
+ either :math:`(B, 2, 3)` affine or :math:`(B, 3, 3)` homogeneous; dispatch is
+ 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
+ calls this with a :math:`(B, 2, 3)` transform
+ - align_corners: ``True`` by default
+ - padding_mode: ``'zeros'`` by default
+
+ .. warning::
+ The :math:`(B, 3, 3)` full-matrix behavior above has degenerate-``out_size``
+ exceptions: with ``align_corners=True`` and an ``out_size`` dimension equal to
+ ``1``, the destination-side grid is singular and the output is all-``NaN``; 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>`_.
+
Args:
input_tensor: the 2D image torch.Tensor with shape (B, C, H, W).
transform: a perspective transformation matrix with shape (B, 3, 3), or an
@@ -289,7 +336,7 @@ def crop_by_transform_mat(
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode (str): padding mode for outside grid values
- ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: mode for grid_generation.
Returns:
@@ -366,6 +413,21 @@ def crop_by_indices(
) -> torch.Tensor:
"""Crop tensors with naive indices.
+ Convention:
+ - input: :math:`(B, C, H, W)`; ``size`` is ``(h, w)`` if given, else inferred
+ from ``src_box``
+ - ``src_box``: :math:`(B, 4, 2)` corner points in ``(x, y)`` order top-left,
+ top-right, bottom-right, bottom-left β€” same convention as :func:`crop_and_resize`
+ - unlike the other crop operators in this module: ``interpolation=`` (not
+ ``mode=``), ``align_corners=None`` by default (not ``True``), and an
+ ``antialias=False`` option
+ - ``shape_compensation`` (``'resize'`` by default) only takes effect when
+ ``src_box`` is not literally identical across the batch (same position and
+ size for every item); when ``src_box`` **is** identical across the batch,
+ ``shape_compensation`` is ignored β€” the result is an exact integer slice
+ when the slice shape already matches ``size`` (or when ``size=None``), and
+ is resized to ``size`` otherwise
+
Args:
input_tensor: the 2D image torch.Tensor with shape (B, C, H, W).
src_box: a torch.Tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes
@@ -383,6 +445,11 @@ def crop_by_indices(
shape_compensation: if the cropped slice sizes are not exactly align `size`, the image can either be padded
or resized.
+ Returns:
+ The cropped torch.Tensor with shape :math:`(B, C, h, w)`, where
+ :math:`(h, w)` is ``size`` if given, otherwise the shape inferred
+ from ``src_box``.
+
"""
KORNIA_CHECK_SHAPE(input_tensor, ["B", "C", "H", "W"])
KORNIA_CHECK_SHAPE(src_box, ["B", "4", "2"])
@@ -438,6 +505,12 @@ def crop_by_indices(
class CenterCrop2D(nn.Module):
"""Center crop the input torch.Tensor.
+ Convention:
+ - ``align_corners`` (and ``resample``) only take effect when
+ ``cropping_mode='resample'``; the default ``cropping_mode='slice'`` performs
+ integer-index slicing and ignores both
+ - See the convention block of :func:`~kornia.geometry.transform.center_crop`.
+
Args:
size: Size (h, w) in pixels of the resized region or just one side.
align_corners: interpolation flag.
diff --git a/kornia/geometry/transform/crop3d.py b/kornia/geometry/transform/crop3d.py
index 5269ef2ca..67f376aef 100644
--- a/kornia/geometry/transform/crop3d.py
+++ b/kornia/geometry/transform/crop3d.py
@@ -35,13 +35,23 @@ def crop_and_resize3d(
) -> torch.Tensor:
r"""Extract crops from 3D volumes (5D tensor) and resize them.
+ Convention:
+ - input: :math:`(B, C, D, H, W)`; ``size`` is ``(d, h, w)``
+ - ``boxes``: :math:`(B, 8, 3)` corner points in ``(x, y, z)`` order, front face
+ then back face, each face top-left, top-right, bottom-right, bottom-left β€”
+ same ``(x, y)``/inclusive-pixel convention as :func:`crop_and_resize`, with
+ ``z`` anchored at the top-left of the first depth slice (``z = 0``);
+ reproducing the exact integer-voxel slice requires ``align_corners=True`` β€”
+ the default ``False`` interpolates instead
+ - align_corners: ``False`` by default
+
Args:
tensor: the 3D volume tensor with shape (B, C, D, H, W).
boxes: a tensor with shape (B, 8, 3) containing the coordinates of the bounding boxes
to be extracted. The tensor must have the shape of Bx8x3, where each box is defined in the clockwise
order: front-top-left, front-top-right, front-bottom-right, front-bottom-left, back-top-left,
back-top-right, back-bottom-right, back-bottom-left. The coordinates must be in x, y, z order.
- size: a tuple with the height and width that will be
+ size: a tuple with the depth, height and width that will be
used to resize the extracted patches.
interpolation: Interpolation flag.
align_corners: mode for grid_generation.
@@ -133,6 +143,10 @@ def center_crop3d(
) -> torch.Tensor:
r"""Crop the 3D volumes (5D tensor) at the center.
+ Convention:
+ - input: :math:`(B, C, D, H, W)`; ``size`` is ``(d, h, w)``
+ - align_corners: ``True`` by default
+
Args:
tensor: the 3D volume tensor with shape (B, C, D, H, W).
size: a tuple with the expected depth, height and width
@@ -251,13 +265,21 @@ def crop_by_boxes3d(
interpolation: str = "bilinear",
align_corners: bool = False,
) -> torch.Tensor:
- """Perform crop transform on 3D volumes (5D tensor) by bounding boxes.
+ r"""Perform crop transform on 3D volumes (5D tensor) by bounding boxes.
Given an input tensor, this function selected the interested areas by the provided bounding boxes (src_box).
Then the selected areas would be fitted into the targeted bounding boxes (dst_box) by a perspective transformation.
So far, the ragged tensor is not supported by PyTorch right now. This function hereby requires the bounding boxes
in a batch must be rectangles with same width, height and depth.
+ Convention:
+ - input: :math:`(B, C, D, H, W)`
+ - ``src_box``/``dst_box``: :math:`(B, 8, 3)` corner points in ``(x, y, z)``
+ order, front face then back face, each face top-left, top-right,
+ bottom-right, bottom-left β€” same convention as :func:`crop_and_resize3d`;
+ ``dst_box`` determines the output resolution
+ - align_corners: ``False`` by default
+
Args:
tensor : the 3D volume tensor with shape (B, C, D, H, W).
src_box : a tensor with shape (B, 8, 3) containing the coordinates of the bounding boxes
@@ -358,9 +380,20 @@ def crop_by_transform_mat3d(
) -> torch.Tensor:
"""Perform crop transform on 3D volumes (5D tensor) given a perspective transformation matrix.
+ Convention:
+ - input: :math:`(B, C, D, H, W)`; ``out_size`` is ``(d, h, w)``
+ - ``transform`` is the source→destination **pixel** transform, accepted as
+ either :math:`(B, 3, 4)` affine or :math:`(B, 4, 4)` homogeneous β€” for the
+ homogeneous form only the top three rows are kept before this function passes
+ the result to :func:`warp_affine3d`, which itself requires :math:`(B, 3, 4)`
+ and rejects a :math:`(B, 4, 4)` input
+ - align_corners: ``True`` by default
+ - padding_mode: ``'zeros'`` by default
+
Args:
- tensor: the 2D image tensor with shape (B, C, H, W).
- transform: a perspective transformation matrix with shape (B, 4, 4).
+ tensor: the 3D volume tensor with shape (B, C, D, H, W).
+ transform: the source->destination pixel transform, either affine with
+ shape (B, 3, 4) or homogeneous with shape (B, 4, 4).
out_size: size of the output image (depth, height, width).
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
diff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.py
index 8a5a444a7..78aa2fe48 100644
--- a/kornia/geometry/transform/elastic_transform.py
+++ b/kornia/geometry/transform/elastic_transform.py
@@ -42,19 +42,28 @@ def elastic_transform2d(
.. image:: _static/img/elastic_transform2d.png
+ Convention:
+ - image: :math:`(B, C, H, W)`; ``noise``: :math:`(B, 2, H, W)` with
+ channel 0 the x- and channel 1 the y-displacement of the sampling
+ 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
+ - padding_mode: ``'zeros'`` by default
+
Args:
image: Input image to be transformed with shape :math:`(B, C, H, W)`.
noise: Noise image used to spatially transform the input image. Same
resolution as the input image with shape :math:`(B, 2, H, W)`. The coordinates order
it is expected to be in x-y.
- kernel_size: the size of the Gaussian kernel.
+ kernel_size: the size of the Gaussian kernel, in the y and x directions, respectively.
sigma: The standard deviation of the Gaussian in the y and x directions,
respectively. Larger sigma results in smaller pixel displacements.
alpha : The scaling factor that controls the intensity of the deformation
- in the y and x directions, respectively.
- align_corners: Interpolation flag used by ```grid_sample```.
- mode: Interpolation mode used by ```grid_sample```. Either ``'bilinear'`` or ``'nearest'``.
- padding_mode: The padding used by ```grid_sample```. Either ``'torch.zeros'``, ``'border'`` or ``'refection'``.
+ in the x and y directions, respectively.
+ align_corners: Interpolation flag used by ``grid_sample``.
+ mode: Interpolation mode used by ``grid_sample``. Either ``'bilinear'`` or ``'nearest'``.
+ padding_mode: The padding used by ``grid_sample``. Either ``'zeros'``, ``'border'`` or ``'reflection'``.
Returns:
the elastically transformed input image with shape :math:`(B,C,H,W)`.
diff --git a/kornia/geometry/transform/flips.py b/kornia/geometry/transform/flips.py
index f0ec4c2a0..08a40cec0 100644
--- a/kornia/geometry/transform/flips.py
+++ b/kornia/geometry/transform/flips.py
@@ -24,7 +24,8 @@ __all__ = ["Hflip", "Rot180", "Vflip", "hflip", "rot180", "vflip"]
class Vflip(nn.Module):
r"""Vertically flip a torch.Tensor image or a batch of torch.Tensor images.
- Input must be a torch.Tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ Convention:
+ - See the convention block of :func:`~kornia.geometry.transform.vflip`.
Args:
input: input torch.Tensor.
@@ -67,7 +68,8 @@ class Vflip(nn.Module):
class Hflip(nn.Module):
r"""Horizontally flip a torch.Tensor image or a batch of torch.Tensor images.
- Input must be a torch.Tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ Convention:
+ - See the convention block of :func:`~kornia.geometry.transform.hflip`.
Args:
input: input torch.Tensor.
@@ -110,7 +112,8 @@ class Hflip(nn.Module):
class Rot180(nn.Module):
r"""Rotate a torch.Tensor image or a batch of torch.Tensor images 180 degrees.
- Input must be a torch.Tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ Convention:
+ - See the convention block of :func:`~kornia.geometry.transform.rot180`.
Args:
input: input torch.Tensor.
@@ -152,7 +155,12 @@ def rot180(input: torch.Tensor) -> torch.Tensor:
.. image:: _static/img/rot180.png
- Input must be a torch.Tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ Convention:
+ - flips both the height and width axes (equivalent to :func:`vflip` followed by
+ :func:`hflip`)
+ - requires rank β‰₯ 2 (operates on dim ``-2``, flipping dims ``-2`` and ``-1``):
+ unbatched :math:`(H, W)`/:math:`(C, H, W)` or batched :math:`(*, C, H, W)`
+ all work
Args:
input: input torch.Tensor.
@@ -169,7 +177,10 @@ def hflip(input: torch.Tensor) -> torch.Tensor:
.. image:: _static/img/hflip.png
- Input must be a torch.Tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ Convention:
+ - flips the last dimension (dim ``-1``); accepts any rank :math:`\geq 1`
+ (rank-0 input is currently returned unchanged, but that behavior is
+ outside the documented contract)
Args:
input: input torch.Tensor.
@@ -186,7 +197,10 @@ def vflip(input: torch.Tensor) -> torch.Tensor:
.. image:: _static/img/vflip.png
- Input must be a torch.Tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ Convention:
+ - flips along the height axis (the second-to-last dimension)
+ - requires rank β‰₯ 2 (operates on dim ``-2``): unbatched :math:`(H, W)`/
+ :math:`(C, H, W)` or batched :math:`(*, C, H, W)` all work
Args:
input: input torch.Tensor.
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index a33ccde01..bb4169d0c 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -50,6 +50,9 @@ def _get_pyramid_gaussian_kernel() -> torch.Tensor:
class PyrDown(nn.Module):
r"""Blur a torch.Tensor and downsamples it.
+ Convention:
+ - See the convention block of :func:`~kornia.geometry.transform.pyrdown`.
+
Args:
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
@@ -99,8 +102,11 @@ class PyrDown(nn.Module):
class PyrUp(nn.Module):
r"""Upsample a torch.Tensor and then blurs it.
+ Convention:
+ - See the convention block of :func:`~kornia.geometry.transform.pyrup`.
+
Args:
- borde_type: the padding mode to be applied before convolving.
+ border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
``'replicate'`` or ``'circular'``.
align_corners: interpolation flag.
@@ -147,6 +153,33 @@ class ScalePyramid(nn.Module):
Images are consequently smoothed with Gaussian blur and downscaled.
+ Convention:
+ - input: :math:`(B, C, H, W)`
+ - ``forward`` returns a 3-tuple ``(pyr, sigmas, pixel_dists)``, one entry per
+ octave: ``pyr[octave]`` is :math:`(B, C, L, H_i, W_i)` with
+ ``L = n_levels + extra_levels`` stacked levels; ``sigmas[octave]`` and
+ ``pixel_dists[octave]`` are :math:`(B, L)` β€” these are **nominal**
+ bookkeeping scale metadata (the values the scale-space construction
+ targets), not measured physical blur. ``sigmas`` is octave-relative,
+ resetting to the same ``init_sigma``-seeded sequence at the start of
+ every octave (octave 0's first entry is instead the assumed input
+ blur, ``0.5``, or ``1.0`` when ``double_image=True``, whenever
+ ``init_sigma`` is below that value) β€” e.g.
+ ``ScalePyramid(n_levels=1, init_sigma=0.25)`` returns octave 0
+ ``[0.5, 0.5, 1.0, 2.0]`` and octave 1+ ``[0.25, 0.5, 1.0, 2.0]`` (the
+ per-level values scale with ``n_levels``/``extra_levels``); and
+ ``pixel_dists`` is the pixel spacing of each level relative to the
+ input. The nominal blur in original-image pixels is
+ ``sigmas[octave] * pixel_dists[octave]``, not ``sigmas[octave]``
+ alone. Caveat: when ``init_sigma`` is below the assumed input blur,
+ the true blur exceeds this nominal value for octave-0 levels
+ :math:`\geq 1` and for everything seeded from them in later octaves
+ (each octave is seeded from an earlier octave's under-labelled
+ level, so the gap propagates onward)
+ - no ``align_corners`` constructor parameter β€” the internal ``double_image``
+ and octave-seeding resizes are hardcoded to ``align_corners=True`` and are
+ not user-configurable
+
Args:
n_levels: number of the levels in octave.
init_sigma: initial blur level.
@@ -316,9 +349,12 @@ class ScalePyramid(nn.Module):
Returns:
Three lists with one entry per octave. ``pyr`` contains stacked
- image levels, ``sigmas`` contains the absolute blur sigma for each
- level, and ``pixel_dists`` contains the pixel spacing of each level
- relative to the original image.
+ image levels, ``sigmas`` contains the octave-relative nominal blur
+ sigma for each level (multiply by the matching ``pixel_dists``
+ entry for the nominal absolute blur in original-image pixels β€” see
+ the class Convention block for when the true blur exceeds this
+ nominal value), and ``pixel_dists`` contains the pixel spacing of
+ each level relative to the original image.
"""
bs, _, _, _ = x.size()
cur_level, cur_sigma, pixel_distance = self.get_first_level(x)
@@ -377,6 +413,14 @@ def pyrdown(
.. image:: _static/img/pyrdown.png
+ Convention:
+ - input: :math:`(B, C, H, W)`
+ - output spatial size is ``floor(side / factor)`` per dimension
+ (:math:`5 \times 5 \to 2 \times 2` at the default ``factor=2.0`` β€”
+ note OpenCV's ``pyrDown`` rounds up instead)
+ - border_type: ``'reflect'`` by default (blur before downsample)
+ - align_corners: ``False`` by default
+
Args:
input: the torch.Tensor to be downsampled.
border_type: the padding mode to be applied before convolving.
@@ -418,14 +462,21 @@ def pyrup(input: torch.Tensor, border_type: str = "reflect", align_corners: bool
.. image:: _static/img/pyrup.png
+ Convention:
+ - input: :math:`(B, C, H, W)`
+ - output spatial size is exactly doubled per dimension (no ``factor``
+ parameter, unlike :func:`pyrdown`; :math:`3 \times 3 \to 6 \times 6`)
+ - border_type: ``'reflect'`` by default (blur after upsample)
+ - align_corners: ``False`` by default
+
Args:
- input: the torch.Tensor to be downsampled.
+ input: the torch.Tensor to be upsampled.
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.
align_corners: interpolation flag.
Return:
- the downsampled torch.Tensor.
+ the upsampled torch.Tensor.
Examples:
>>> input = torch.arange(4, dtype=torch.float32).reshape(1, 1, 2, 2)
@@ -461,10 +512,25 @@ def build_pyramid(
The function constructs a vector of images and builds the Gaussian pyramid
by recursively applying pyrDown to the previously built pyramid layers.
+ Convention:
+ - input: :math:`(B, C, H, W)`
+ - ``max_level`` is the total number of levels returned (including the
+ unchanged original as level 0), not a 0-based index of the last level
+ - each subsequent level is produced by :func:`pyrdown` (``floor(side / 2)``
+ per dimension)
+ - border_type: ``'reflect'`` by default
+ - align_corners: ``False`` by default
+
+ .. warning::
+ The ``max_level`` bounds check does not currently reject non-positive
+ **integer** values: passing an integer ``max_level <= 0`` returns the
+ same single-element list as ``max_level=1`` instead of raising. Tracked in
+ `#3927 <https://github.com/kornia/kornia/issues/3927>`_.
+
Args:
input : the torch.Tensor to be used to construct the pyramid.
- max_level: 0-based index of the last (the smallest) pyramid layer.
- It must be non-negative.
+ max_level: the number of pyramid levels to return, including the
+ unchanged original image as level 0.
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
``'replicate'`` or ``'circular'``.
@@ -514,17 +580,48 @@ def build_laplacian_pyramid(
See :cite:`burt1987laplacian` for more details.
+ Convention:
+ - input: :math:`(B, C, H, W)`
+ - ``max_level`` is the total number of levels returned, not a 0-based
+ index of the last level
+ - levels ``0`` through ``max_level - 2`` are band-pass residuals: level
+ ``i`` = :func:`build_pyramid` Gaussian level ``i`` minus a
+ :func:`pyrup`-expanded Gaussian level ``i + 1``; only the last
+ element (index ``max_level - 1``) is the unsubtracted final Gaussian
+ level β€” level 0 is **not** the unchanged original image whenever
+ ``max_level > 1``
+ - the input is reflect-padded up to the next power of two (per
+ dimension) only when **neither** the height **nor** the width is
+ already a power of two; when it is applied, every returned level
+ β€” including level 0 β€” is shaped from the padded size
+ - border_type: ``'reflect'`` by default
+ - align_corners: ``False`` by default
+
+ .. warning::
+ For a mixed odd/power-of-two input size (one dimension a power of two,
+ the other not), no padding is applied and the level-to-level
+ subtraction can raise ``RuntimeError`` from a shape mismatch when
+ ``max_level > 1`` (e.g. a :math:`(1, 1, 5, 8)` input with
+ ``max_level=2``). This is likely unintended and tracked in
+ `#3927 <https://github.com/kornia/kornia/issues/3927>`_. Separately, the
+ ``max_level`` bounds check does not currently reject non-positive
+ **integer** values: passing an integer ``max_level <= 0`` returns the
+ same single-element list as ``max_level=1`` instead of raising β€” also
+ tracked in `#3927 <https://github.com/kornia/kornia/issues/3927>`_.
+
Args:
input : the torch.Tensor to be used to construct the pyramid with shape :math:`(B, C, H, W)`.
- max_level: 0-based index of the last (the smallest) pyramid layer.
- It must be non-negative.
+ max_level: the number of pyramid levels to return (see Convention
+ above for what each level contains).
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
``'replicate'`` or ``'circular'``.
align_corners: interpolation flag.
Return:
- Output: :math:`[(B, C, H, W), (B, C, H/2, W/2), ...]`
+ Output: :math:`[(B, C, H', W'), (B, C, H'/2, W'/2), ...]`, where
+ :math:`(H', W')` equals the input :math:`(H, W)` unless padding was
+ applied (see Convention above), in which case it is the padded size.
"""
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
diff --git a/kornia/geometry/transform/thin_plate_spline.py b/kornia/geometry/transform/thin_plate_spline.py
index 76f202f7e..4a9f6bcf2 100644
--- a/kornia/geometry/transform/thin_plate_spline.py
+++ b/kornia/geometry/transform/thin_plate_spline.py
@@ -59,6 +59,35 @@ def get_tps_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> tup
The input to this function is a torch.Tensor of :math:`(x, y)` source points :math:`(B, N, 2)` and a corresponding
torch.Tensor of target :math:`(x, y)` points :math:`(B, N, 2)`.
+ Convention:
+ - ``points_src``/``points_dst``: :math:`(B, N, 2)` in ``(x, y)`` order, in
+ whatever coordinate frame the caller supplies β€” the function performs no
+ normalization of its own
+ - returns kernel weights :math:`(B, N, 2)` and affine weights :math:`(B, 3, 2)`,
+ consumed by :func:`warp_points_tps`/:func:`warp_image_tps`; the identity
+ mapping (``points_src == points_dst``) yields kernel weights and an affine
+ that are mathematically zero/identity, realized only up to linear-solver
+ (LU) round-off β€” not bit-exact in general, and the residual size is
+ dtype- and backend-dependent; float16 currently produces NaN weights
+ - neither :func:`warp_points_tps` nor :func:`warp_image_tps` calls this
+ function β€” the caller composes them explicitly; whichever tensor is
+ passed as this function's **second** positional argument is
+ ``kernel_centers`` for the returned ``kernel_weights``/``affine_weights``
+ pair, and must be passed as ``kernel_centers`` again to the warp
+ function; :func:`warp_points_tps` is typically composed in the
+ natural ``(points_src, points_dst)`` order, while :func:`warp_image_tps`
+ 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)::
+
+ kernel_weights, affine_weights = get_tps_transform(points_dst, points_src)
+ warped = warp_image_tps(image, kernel_centers=points_src,
+ kernel_weights=kernel_weights, affine_weights=affine_weights)
+
Args:
points_src: batch of source points :math:`(B, N, 2)` as :math:`(x, y)` coordinate vectors.
points_dst: batch of target points :math:`(B, N, 2)` as :math:`(x, y)` coordinate vectors.
@@ -124,10 +153,23 @@ def warp_points_tps(
torch.Tensor[..., 0] contains the weights for the x-transform and torch.Tensor[..., 1] the weights
for the y-transform.
+ Convention:
+ - points: :math:`(B, N, 2)` (or :math:`(B, K, 2)` for kernel centers) in
+ ``(x, y)`` order, in whatever coordinate frame the input points are already
+ in β€” this function performs no normalization of its own
+ - ``kernel_centers`` must be the ``points_dst`` argument (the second
+ positional argument) passed to :func:`get_tps_transform`; see its
+ Convention block for the full binding rule and recipe
+ - returns points warped in that same coordinate frame/units as the input, with
+ no renormalization; the output is **not** clamped β€” a valid TPS transform can
+ map an in-range point outside that frame (e.g. warping ``(0.75, 0)`` through a
+ transform that is exactly a 2x affine scale returns ``(1.5, 0)``, outside
+ :math:`[-1, 1]`)
+
Args:
points_src: torch.Tensor of source points :math:`(B, N, 2)`.
kernel_centers: torch.Tensor of kernel center points :math:`(B, K, 2)`.
- kernel_weights: torch.Tensor of kernl weights :math:`(B, K, 2)`.
+ kernel_weights: torch.Tensor of kernel weights :math:`(B, K, 2)`.
affine_weights: torch.Tensor of affine weights :math:`(B, 3, 2)`.
Returns:
@@ -200,10 +242,55 @@ def warp_image_tps(
The input `image` is a :math:`(B, C, H, W)` torch.Tensor. The kernel centers, kernel weight and affine weights
are the same as in `warp_points_tps`.
+ Convention:
+ - image: :math:`(B, C, H, W)`; kernel/affine weights as returned by
+ :func:`get_tps_transform` called **reversed** β€”
+ ``get_tps_transform(points_dst, points_src)`` β€” see its Convention block
+ - ``kernel_centers`` must be the tensor passed as the **second** positional
+ 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
+ - 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)`.
- kernel_weights: torch.Tensor of kernl weights :math:`(B, K, 2)`.
+ kernel_weights: torch.Tensor of kernel weights :math:`(B, K, 2)`.
affine_weights: torch.Tensor of affine weights :math:`(B, 3, 2)`.
align_corners: interpolation flag used by `grid_sample`.
padding_mode: padding flag used by `grid_sample`.
diff --git a/testing/base.py b/testing/base.py
index 91bb4127c..29d6ad413 100644
--- a/testing/base.py
+++ b/testing/base.py
@@ -18,10 +18,12 @@
from __future__ import annotations
import math
+from functools import cache
from typing import Any, Callable, Optional, Sequence, Union
import pytest
import torch
+import torch.nn.functional as F
from torch.autograd import gradcheck
from torch.testing import assert_close as _assert_close
@@ -83,6 +85,33 @@ def tensor_to_gradcheck_var(
return t
+_UNSUPPORTED_BORDER_PADDING_MSG = "Unsupported Border padding mode"
+
+
+@cache
+def _supports_2d_border_padding_probe(device_type: str) -> bool:
+ inp = torch.zeros(1, 1, 2, 2, device=device_type)
+ grid = torch.zeros(1, 1, 1, 2, device=device_type)
+ try:
+ F.grid_sample(inp, grid, padding_mode="border", align_corners=True)
+ except RuntimeError as e:
+ if _UNSUPPORTED_BORDER_PADDING_MSG in str(e):
+ return False
+ raise
+ return True
+
+
+def supports_2d_border_padding(device: torch.device) -> bool:
+ """Whether this device's 2D ``grid_sample`` supports ``padding_mode='border'``.
+
+ Probed at runtime (and cached per device type): MPS's 2D ``grid_sample`` currently
+ raises "Unsupported Border padding mode"; its 3D ``grid_sample`` does support it, so
+ this guard is only needed for 2D call sites. Probing (rather than hardcoding on
+ ``device.type == "mps"``) means this auto-enables once PyTorch adds support.
+ """
+ return _supports_2d_border_padding_probe(device.type)
+
+
class BaseTester:
@staticmethod
def assert_close(
diff --git a/tests/geometry/transform/test_crop2d.py b/tests/geometry/transform/test_crop2d.py
index b6b05b6bc..a28bb1b6e 100644
--- a/tests/geometry/transform/test_crop2d.py
+++ b/tests/geometry/transform/test_crop2d.py
@@ -163,6 +163,40 @@ class TestCropAndResize(BaseTester):
expected = op(img, boxes, (crop_height, crop_width))
self.assert_close(actual, expected, rtol=1e-4, atol=1e-4)
+ def test_convention_single_image_does_not_broadcast_over_boxes(self, device, dtype):
+ # A single box broadcasts over a batch of N images (see test_crop_batch_broadcast),
+ # but a single image does NOT broadcast over a batch of N boxes -- it raises
+ # RuntimeError instead, so the broadcasting crop_and_resize supports is
+ # one-directional, not general batch broadcasting.
+ inp_one = torch.arange(0.0, 16.0, device=device, dtype=dtype).view(1, 1, 4, 4)
+ two_boxes = torch.tensor(
+ [[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]], [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]],
+ device=device,
+ dtype=dtype,
+ )
+ with pytest.raises(RuntimeError):
+ kornia.geometry.transform.crop_and_resize(inp_one, two_boxes, (2, 2))
+
+ def test_convention_padding_mode_default_zeros(self, device, dtype):
+ # crop_and_resize's padding_mode default is 'zeros': a box sampling outside the image
+ # bounds fills the out-of-bounds region with 0, not the edge value ('border' would).
+ inp = torch.arange(1.0, 17.0, device=device, dtype=dtype).view(1, 1, 4, 4)
+ boxes = torch.tensor([[[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]]], device=device, dtype=dtype)
+
+ out_default = kornia.geometry.transform.crop_and_resize(inp, boxes, (3, 3))
+ # Snippet used to generate expected (independent F.grid_sample call, not through
+ # crop_and_resize's own box-to-grid machinery):
+ # import torch.nn.functional as F
+ # inp = torch.arange(1.0, 17.0).view(1, 1, 4, 4)
+ # xs = ys = torch.tensor([-1.0, 0.0, 1.0])
+ # gx, gy = 2 * xs / (4 - 1) - 1, 2 * ys / (4 - 1) - 1
+ # grid = torch.stack(torch.meshgrid(gy, gx, indexing="ij")[::-1], dim=-1).unsqueeze(0)
+ # expected = F.grid_sample(inp, grid, mode="bilinear", padding_mode="zeros", align_corners=True)
+ expected_zeros = torch.tensor(
+ [[[[0.0, 0.0, 0.0], [0.0, 1.0, 2.0], [0.0, 5.0, 6.0]]]], device=device, dtype=dtype
+ )
+ self.assert_close(out_default, expected_zeros, rtol=1e-2, atol=1e-2)
+
class TestCenterCrop(BaseTester):
def test_center_crop_h2_w4(self, device, dtype):
@@ -232,6 +266,26 @@ 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):
+ # 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'.
+ 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)
+ out_slice_false = kornia.geometry.transform.CenterCrop2D((2, 2), align_corners=False, cropping_mode="slice")(
+ inp
+ )
+ self.assert_close(out_slice_true, out_slice_false)
+
+ out_resample_true = kornia.geometry.transform.CenterCrop2D(
+ (2, 2), align_corners=True, cropping_mode="resample"
+ )(inp)
+ 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)
+
class TestCropByBoxes(BaseTester):
def test_crop_by_boxes_no_resizing(self, device, dtype):
@@ -356,6 +410,64 @@ class TestCropByIndices(BaseTester):
with pytest.raises(ValueError, match="All boxes in the batch must have the same height and width"):
kornia.geometry.transform.crop_by_indices(img, src_box, size=None)
+ def test_convention_shape_compensation_pad_vs_resize(self, device, dtype):
+ # shape_compensation is pinned per the crop_by_indices Convention block: when
+ # src_box is identical across the batch it is ignored (exact integer slice if the
+ # slice already matches `size`, resized otherwise); it only takes effect for a
+ # non-uniform batch, where 'pad' trims via F.pad's negative padding (keeps the
+ # top-left corner, no interpolation) while 'resize' downsamples via interpolation.
+ inp = torch.arange(0.0, 32.0, device=device, dtype=dtype).view(1, 1, 4, 8).repeat(2, 1, 1, 1)
+
+ # --- identical src_box across the batch: shape_compensation is ignored ---
+ box_3x3 = torch.tensor([[[0, 0], [2, 0], [2, 2], [0, 2]]], device=device, dtype=torch.int64).expand(2, -1, -1)
+ box_2x2 = torch.tensor([[[0, 0], [1, 0], [1, 1], [0, 1]]], device=device, dtype=torch.int64).expand(2, -1, -1)
+ size = (2, 2)
+
+ # slice (2x2) already matches `size`: exact integer slice under both settings.
+ out_resize_match = kornia.geometry.transform.crop_by_indices(
+ inp, box_2x2, size=size, shape_compensation="resize"
+ )
+ out_pad_match = kornia.geometry.transform.crop_by_indices(inp, box_2x2, size=size, shape_compensation="pad")
+ expected_slice = inp[..., 0:2, 0:2]
+ self.assert_close(out_resize_match, expected_slice, atol=0.0, rtol=0.0)
+ self.assert_close(out_pad_match, expected_slice, atol=0.0, rtol=0.0)
+
+ # slice (3x3) differs from `size` (2x2): resized under both settings.
+ out_resize_diff = kornia.geometry.transform.crop_by_indices(
+ inp, box_3x3, size=size, shape_compensation="resize"
+ )
+ out_pad_diff = kornia.geometry.transform.crop_by_indices(inp, box_3x3, size=size, shape_compensation="pad")
+ self.assert_close(out_resize_diff, out_pad_diff, atol=0.0, rtol=0.0)
+ assert out_resize_diff.shape[-2:] == size
+
+ # --- non-uniform batch (box 0 != box 1): shape_compensation genuinely takes effect ---
+ src_box = torch.tensor(
+ [
+ [[0, 0], [2, 0], [2, 2], [0, 2]], # 3x3 box, LARGER than size=(2, 2)
+ [[0, 0], [1, 0], [1, 1], [0, 1]], # 2x2 box, matches size=(2, 2)
+ ],
+ device=device,
+ dtype=torch.int64,
+ )
+
+ out_resize = kornia.geometry.transform.crop_by_indices(inp, src_box, size=size, shape_compensation="resize")
+ out_pad = kornia.geometry.transform.crop_by_indices(inp, src_box, size=size, shape_compensation="pad")
+
+ # Snippet used to generate expected (requires torch + kornia.geometry.transform.resize):
+ # inp = torch.arange(0.0, 32.0).view(1, 1, 4, 8).repeat(2, 1, 1, 1)
+ # slice3x3 = inp[0:1, :, 0:3, 0:3]
+ # expected_resize_0 = kornia.geometry.transform.resize(
+ # slice3x3, (2, 2), interpolation="bilinear", align_corners=None, side="short", antialias=False
+ # )[0, 0]
+ # expected_pad_0 = torch.nn.functional.pad(slice3x3, (0, -1, 0, -1))[0, 0]
+ expected_resize_0 = torch.tensor([[2.25, 3.75], [14.25, 15.75]], device=device, dtype=dtype)
+ expected_pad_0 = torch.tensor([[0.0, 1.0], [8.0, 9.0]], device=device, dtype=dtype)
+ self.assert_close(out_resize[0, 0], expected_resize_0, rtol=1e-2, atol=1e-2)
+ self.assert_close(out_pad[0, 0], expected_pad_0, rtol=1e-2, atol=1e-2)
+ # sample 1's own cropped slice already matches `size`, so its per-item branch takes
+ # the plain-copy path, and 'pad'/'resize' agree there too.
+ self.assert_close(out_resize[1], out_pad[1])
+
class TestCropSizeValidation:
"""Tests that crop functions properly reject invalid size arguments."""
diff --git a/tests/geometry/transform/test_crop3d.py b/tests/geometry/transform/test_crop3d.py
index 9a8698cf5..91c444f9f 100644
--- a/tests/geometry/transform/test_crop3d.py
+++ b/tests/geometry/transform/test_crop3d.py
@@ -158,6 +158,17 @@ class TestCenterCrop3D(BaseTester):
expected = kornia.geometry.transform.center_crop3d(img, (4, 3, 2))
self.assert_close(actual, expected, rtol=1e-4, atol=1e-4)
+ def test_convention_align_corners_default_is_true(self, device, dtype):
+ # center_crop3d's align_corners default is True, not merely a value that every existing
+ # test happens to pass explicitly: omitting the kwarg must equal align_corners=True and
+ # differ from align_corners=False.
+ inp = torch.arange(0.0, 343.0, device=device, dtype=dtype).view(1, 1, 7, 7, 7)
+ out_default = kornia.geometry.transform.center_crop3d(inp, (3, 3, 3))
+ out_true = kornia.geometry.transform.center_crop3d(inp, (3, 3, 3), align_corners=True)
+ out_false = kornia.geometry.transform.center_crop3d(inp, (3, 3, 3), align_corners=False)
+ self.assert_close(out_default, out_true, rtol=1e-2, atol=1e-2)
+ assert not torch.allclose(out_default, out_false, atol=1e-2, rtol=1e-2)
+
class TestCropByBoxes3D(BaseTester):
def test_crop_by_boxes_no_resizing(self, device, dtype):
@@ -327,6 +338,96 @@ class TestCropByBoxes3D(BaseTester):
kornia.geometry.transform.crop_by_boxes3d, (inp, src_box, dst_box), requires_grad=(True, False, False)
)
+ def test_convention_align_corners_default_is_false(self, device, dtype):
+ # crop_by_boxes3d's align_corners default is False -- every other dedicated test in
+ # this class passes align_corners=True explicitly, so the default itself was never
+ # exercised until now. Also pins the docstring's "inclusive coordinates" consequence
+ # with the same fixture: the box extent (1, 1, 1)..(2, 2, 2) reproduces the exact
+ # integer-voxel slice only under align_corners=True -- the align_corners=False
+ # default interpolates instead.
+ vol = torch.arange(64.0, device=device, dtype=dtype).view(1, 1, 4, 4, 4)
+ src_box = torch.tensor(
+ [
+ [
+ [1.0, 1.0, 1.0],
+ [2.0, 1.0, 1.0],
+ [2.0, 2.0, 1.0],
+ [1.0, 2.0, 1.0],
+ [1.0, 1.0, 2.0],
+ [2.0, 1.0, 2.0],
+ [2.0, 2.0, 2.0],
+ [1.0, 2.0, 2.0],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ dst_box = torch.tensor(
+ [
+ [
+ [0.0, 0.0, 0.0],
+ [1.0, 0.0, 0.0],
+ [1.0, 1.0, 0.0],
+ [0.0, 1.0, 0.0],
+ [0.0, 0.0, 1.0],
+ [1.0, 0.0, 1.0],
+ [1.0, 1.0, 1.0],
+ [0.0, 1.0, 1.0],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ expected_slice = vol[:, :, 1:3, 1:3, 1:3]
+
+ out_default = kornia.geometry.transform.crop_by_boxes3d(vol, src_box, dst_box)
+ out_true = kornia.geometry.transform.crop_by_boxes3d(vol, src_box, dst_box, align_corners=True)
+ out_false = kornia.geometry.transform.crop_by_boxes3d(vol, src_box, dst_box, align_corners=False)
+
+ self.assert_close(out_default, out_false, rtol=1e-2, atol=1e-2)
+ assert not torch.allclose(out_default, out_true, atol=1e-2, rtol=1e-2)
+ self.assert_close(out_true, expected_slice, rtol=1e-2, atol=1e-2)
+ assert not torch.allclose(out_default, expected_slice, atol=1e-2, rtol=1e-2)
+
+ def test_convention_crop_by_transform_mat3d_direct(self, device, dtype):
+ # crop_by_transform_mat3d has no direct test anywhere in this file -- it is only ever
+ # exercised indirectly through crop_by_boxes3d. Pin it directly: align_corners=True
+ # default, and out_size in (depth, height, width) order.
+ inp = torch.arange(0.0, 64.0, device=device, dtype=dtype).view(1, 1, 4, 4, 4)
+ transform = torch.tensor(
+ [[[1.0, 0.0, 0.0, -1.0], [0.0, 1.0, 0.0, -1.0], [0.0, 0.0, 1.0, -1.0], [0.0, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=dtype,
+ )
+ out_default = kornia.geometry.transform.crop_by_transform_mat3d(inp, transform, (2, 2, 2))
+ out_true = kornia.geometry.transform.crop_by_transform_mat3d(inp, transform, (2, 2, 2), align_corners=True)
+ expected = inp[:, :, 1:3, 1:3, 1:3]
+ self.assert_close(out_default, out_true)
+ self.assert_close(out_default, expected, rtol=1e-2, atol=1e-2)
+
+ def test_convention_padding_mode_default_zeros_3d(self, device, dtype):
+ # crop_by_transform_mat3d's padding_mode default is 'zeros': sampling past the volume
+ # bounds fills with 0, not the edge value ('border' would).
+ inp = torch.arange(1.0, 65.0, device=device, dtype=dtype).view(1, 1, 4, 4, 4)
+ transform = torch.tensor(
+ [[[1.0, 0.0, 0.0, 2.0], [0.0, 1.0, 0.0, 2.0], [0.0, 0.0, 1.0, 2.0], [0.0, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=dtype,
+ )
+ out_default = kornia.geometry.transform.crop_by_transform_mat3d(inp, transform, (3, 3, 3), align_corners=True)
+ out_zeros = kornia.geometry.transform.crop_by_transform_mat3d(
+ inp, transform, (3, 3, 3), align_corners=True, padding_mode="zeros"
+ )
+ self.assert_close(out_default, out_zeros)
+
+ # Intentionally unguarded on MPS: 3D grid_sample supports padding_mode='border' there;
+ # only 2D grid_sample has the MPS 'border' limitation guarded elsewhere (see
+ # testing/base.py's supports_2d_border_padding).
+ out_border = kornia.geometry.transform.crop_by_transform_mat3d(
+ inp, transform, (3, 3, 3), align_corners=True, padding_mode="border"
+ )
+ assert not torch.allclose(out_default, out_border, atol=1e-2, rtol=1e-2)
+
class TestCrop3DSizeValidation:
"""Tests that 3D crop functions properly reject invalid size arguments."""
diff --git a/tests/geometry/transform/test_elastic_transform.py b/tests/geometry/transform/test_elastic_transform.py
index f1d55222a..2033cb585 100644
--- a/tests/geometry/transform/test_elastic_transform.py
+++ b/tests/geometry/transform/test_elastic_transform.py
@@ -20,7 +20,17 @@ import torch
from kornia.geometry.transform import elastic_transform2d
-from testing.base import BaseTester
+from testing.base import BaseTester, supports_2d_border_padding
+
+
+def _row_spread_std(out: torch.Tensor, reference: torch.Tensor) -> torch.Tensor:
+ # weighted standard deviation (over interior rows) of the displaced energy,
+ # i.e. how far the affected region spreads vertically.
+ energy = (out[0, 0, 1:-1] - reference[0, 0, 1:-1]).abs().sum(dim=1)
+ rows = torch.arange(energy.shape[0], dtype=energy.dtype, device=energy.device)
+ weights = energy / energy.sum()
+ mean = (weights * rows).sum()
+ return (weights * (rows - mean) ** 2).sum().sqrt()
class TestElasticTransform(BaseTester):
@@ -108,3 +118,130 @@ class TestElasticTransform(BaseTester):
assert self.gradcheck(
elastic_transform2d, (image, noise), raise_exception=True, fast_mode=True, nondet_tol=1e-4
)
+
+ def test_convention_noise_channel0_is_x_positive_shifts_left(self, device, dtype):
+ # noise channel 0 is the x-sampling-offset channel; a positive constant value there
+ # shifts image content LEFT (not right, and not channel 1/y). test_values uses a
+ # symmetric (both-channels-equal) noise tensor and so cannot discriminate this.
+ image = torch.zeros(1, 1, 5, 5, device=device, dtype=dtype)
+ image[0, 0, 2, 2] = 1.0
+ noise = torch.zeros(1, 2, 5, 5, device=device, dtype=dtype)
+ noise[0, 0] = 0.5
+
+ # Snippet used to generate expected:
+ # img = torch.zeros(1, 1, 5, 5); img[0, 0, 2, 2] = 1.0
+ # noise = torch.zeros(1, 2, 5, 5); noise[0, 0] = 0.5
+ # out = elastic_transform2d(img, noise, kernel_size=(3, 3), sigma=(1., 1.), alpha=(1., 1.))
+ # (out[0, 0] > 0.1).nonzero() -> [[2, 1]]
+ out = elastic_transform2d(image, noise, kernel_size=(3, 3), sigma=(1.0, 1.0), alpha=(1.0, 1.0))
+ assert (out[0, 0] > 0.1).nonzero().tolist() == [[2, 1]]
+
+ def test_convention_alpha_xy_order(self, device, dtype):
+ # alpha is genuinely (x, y) order in the executed code: alpha[0] always scales the
+ # x-displacement and alpha[1] the y-displacement -- contradicting the "in the y and x
+ # directions, respectively" docstring text, which only holds for kernel_size/sigma
+ # (see test_convention_sigma_yx_order for that half).
+ image = torch.zeros(1, 1, 9, 9, device=device, dtype=dtype)
+ image[0, 0, 4, 4] = 1.0
+ noise = torch.zeros(1, 2, 9, 9, device=device, dtype=dtype)
+ noise[0, 0] = 0.2
+
+ out_a = elastic_transform2d(image, noise, kernel_size=(3, 3), sigma=(1.0, 1.0), alpha=(2.0, 0.5))
+ out_b = elastic_transform2d(image, noise, kernel_size=(3, 3), sigma=(1.0, 1.0), alpha=(0.5, 2.0))
+
+ # Snippet used to generate expected (requires only this module):
+ # image = torch.zeros(1, 1, 9, 9); image[0, 0, 4, 4] = 1.0
+ # noise = torch.zeros(1, 2, 9, 9); noise[0, 0] = 0.2
+ # out_a = elastic_transform2d(image, noise, kernel_size=(3, 3), sigma=(1.0, 1.0), alpha=(2.0, 0.5))
+ # out_b = elastic_transform2d(image, noise, kernel_size=(3, 3), sigma=(1.0, 1.0), alpha=(0.5, 2.0))
+ # (out_a[0, 0] > 0.05).nonzero().tolist() / (out_b[0, 0] > 0.05).nonzero().tolist()
+ # alpha=(2.0, 0.5): larger alpha[0] -> larger x-displacement -> marker moves further left.
+ assert (out_a[0, 0] > 0.05).nonzero().tolist() == [[4, 2], [4, 3]]
+ # alpha=(0.5, 2.0): smaller alpha[0] -> smaller x-displacement -> marker moves less.
+ assert (out_b[0, 0] > 0.05).nonzero().tolist() == [[4, 3], [4, 4]]
+
+ def test_convention_sigma_yx_order(self, device, dtype):
+ # sigma is genuinely (sigma_y, sigma_x): an impulse in the x-displacement noise channel,
+ # blurred with a strongly anisotropic sigma, spreads along ROWS when sigma[0] is large and
+ # is confined to a single row when sigma[1] is large instead -- pinning sigma[0] to the y
+ # (row) direction (matching the docstring; see test_convention_alpha_xy_order for the
+ # contrasting alpha order).
+ #
+ # Pinned as an ORDERING PROPERTY (row-wise spread of the affected region), not as exact
+ # threshold-crossing pixel lists: compute the per-row total displaced energy, then the
+ # weighted standard deviation of that energy across rows (how far the effect spreads
+ # vertically). sigma=(3.0, 0.3) must spread markedly wider across rows than sigma=(0.3, 3.0).
+ #
+ # Snippet used to generate expected (requires only this module):
+ # N, c = 21, 10
+ # image = torch.zeros(1, 1, N, N); image[0, 0, :, c] = 1.0
+ # noise = torch.zeros(1, 2, N, N); noise[0, 0, c, c] = 1.0
+ # kwargs = dict(kernel_size=(9, 9), alpha=(3.0, 0.0))
+ # out_y = elastic_transform2d(image, noise, sigma=(3.0, 0.3), **kwargs)
+ # out_x = elastic_transform2d(image, noise, sigma=(0.3, 3.0), **kwargs)
+ # def row_std(out):
+ # energy = (out[0, 0, 1:-1] - image[0, 0, 1:-1]).abs().sum(dim=1)
+ # rows = torch.arange(energy.shape[0], dtype=energy.dtype)
+ # w = energy / energy.sum()
+ # mean = (w * rows).sum()
+ # return (w * (rows - mean) ** 2).sum().sqrt().item()
+ # row_std(out_y), row_std(out_x) # -> 2.582, 0.144 (ratio ~18x)
+ n_sigma, center = 21, 10
+ sigma_image = torch.zeros(1, 1, n_sigma, n_sigma, device=device, dtype=dtype)
+ sigma_image[0, 0, :, center] = 1.0
+ sigma_noise = torch.zeros(1, 2, n_sigma, n_sigma, device=device, dtype=dtype)
+ sigma_noise[0, 0, center, center] = 1.0
+ sigma_kwargs = {"kernel_size": (9, 9), "alpha": (3.0, 0.0)}
+
+ out_sigma_y_wide = elastic_transform2d(sigma_image, sigma_noise, sigma=(3.0, 0.3), **sigma_kwargs)
+ out_sigma_x_wide = elastic_transform2d(sigma_image, sigma_noise, sigma=(0.3, 3.0), **sigma_kwargs)
+
+ spread_y_wide = _row_spread_std(out_sigma_y_wide, sigma_image)
+ spread_x_wide = _row_spread_std(out_sigma_x_wide, sigma_image)
+ # sigma=(3.0, 0.3) (large sigma_y) spreads markedly wider across rows than
+ # sigma=(0.3, 3.0) (large sigma_x) -- a robust ordering property, not an exact pixel list.
+ assert spread_y_wide > 5 * spread_x_wide
+
+ def test_convention_padding_mode_default_zeros(self, device, dtype):
+ # padding_mode's default ('zeros') genuinely affects boundary sampling, but only once the
+ # displacement pushes the (internally clamped-to-[-1,1]) sampling grid all the way to the
+ # edge -- no other existing test drives the displacement far enough to reach it.
+ image = torch.zeros(1, 1, 5, 5, device=device, dtype=dtype)
+ image[0, 0, 2, 4] = 5.0
+ noise = torch.zeros(1, 2, 5, 5, device=device, dtype=dtype)
+ noise[0, 0] = 1.0
+ kwargs = {"kernel_size": (3, 3), "sigma": (1.0, 1.0), "alpha": (4.0, 0.0)}
+
+ out_default = elastic_transform2d(image, noise, **kwargs)
+ out_zeros = elastic_transform2d(image, noise, padding_mode="zeros", **kwargs)
+ # Snippet used to generate expected (requires only this module):
+ # image = torch.zeros(1, 1, 5, 5); image[0, 0, 2, 4] = 5.0
+ # noise = torch.zeros(1, 2, 5, 5); noise[0, 0] = 1.0
+ # kwargs = dict(kernel_size=(3, 3), sigma=(1.0, 1.0), alpha=(4.0, 0.0))
+ # elastic_transform2d(image, noise, **kwargs)[0, 0, 2] # 'zeros' row
+ expected_zeros_row = torch.tensor([2.5, 2.5, 2.5, 2.5, 2.5], device=device, dtype=dtype)
+ self.assert_close(out_default[0, 0, 2], expected_zeros_row, rtol=1e-2, atol=1e-2)
+ self.assert_close(out_zeros[0, 0, 2], expected_zeros_row, rtol=1e-2, atol=1e-2)
+
+ def test_convention_padding_mode_border_differs_from_zeros(self, device, dtype):
+ # Companion to test_convention_padding_mode_default_zeros above: 'border' padding must
+ # actually differ from the 'zeros' default. MPS's 2D grid_sample doesn't support 'border'
+ # (probed at runtime), so this half is skipped visibly there instead of silently no-op'ing
+ # inside an `if` guard.
+ if not supports_2d_border_padding(device):
+ pytest.skip("MPS 2D grid_sample lacks 'border' padding")
+
+ image = torch.zeros(1, 1, 5, 5, device=device, dtype=dtype)
+ image[0, 0, 2, 4] = 5.0
+ noise = torch.zeros(1, 2, 5, 5, device=device, dtype=dtype)
+ noise[0, 0] = 1.0
+ kwargs = {"kernel_size": (3, 3), "sigma": (1.0, 1.0), "alpha": (4.0, 0.0)}
+
+ # Snippet used to generate expected (requires only this module):
+ # image = torch.zeros(1, 1, 5, 5); image[0, 0, 2, 4] = 5.0
+ # noise = torch.zeros(1, 2, 5, 5); noise[0, 0] = 1.0
+ # kwargs = dict(kernel_size=(3, 3), sigma=(1.0, 1.0), alpha=(4.0, 0.0))
+ # elastic_transform2d(image, noise, padding_mode="border", **kwargs)[0, 0, 2] # 'border' row
+ out_border = elastic_transform2d(image, noise, padding_mode="border", **kwargs)
+ expected_border_row = torch.tensor([5.0, 5.0, 5.0, 5.0, 5.0], device=device, dtype=dtype)
+ self.assert_close(out_border[0, 0, 2], expected_border_row, rtol=1e-2, atol=1e-2)
diff --git a/tests/geometry/transform/test_flip.py b/tests/geometry/transform/test_flip.py
index d5641de29..a17e4b21a 100644
--- a/tests/geometry/transform/test_flip.py
+++ b/tests/geometry/transform/test_flip.py
@@ -83,6 +83,13 @@ class TestVflip(BaseTester):
input = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.0]], device=device, dtype=torch.float64)
self.gradcheck(kornia.geometry.transform.Vflip(), (input,))
+ def test_convention_rank1_raises(self, device, dtype):
+ # vflip flips dim -2; a rank-1 tensor has no such dim and raises IndexError, unlike
+ # hflip which only needs dim -1 (see TestHflip.test_convention_rank1_supported).
+ x = torch.tensor([0.0, 1.0, 2.0, 3.0], device=device, dtype=dtype)
+ with pytest.raises(IndexError):
+ kornia.geometry.transform.vflip(x)
+
class TestHflip(BaseTester):
def smoke_test(self, device, dtype):
@@ -146,6 +153,19 @@ class TestHflip(BaseTester):
input = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.0]], device=device, dtype=torch.float64)
self.gradcheck(kornia.geometry.transform.Hflip(), (input,))
+ def test_convention_rank1_supported(self, device, dtype):
+ # hflip flips dim -1 and enforces no rank floor: a bare rank-1 tensor (no H/W
+ # structure at all) works, while vflip/rot180 require rank >= 2 (see
+ # TestVflip/TestRot180.test_convention_rank1_raises). PyTorch currently accepts
+ # rank-0 input as a no-op, but that behavior is outside the documented contract
+ # and intentionally unpinned.
+ x = torch.tensor([0.0, 1.0, 2.0, 3.0], device=device, dtype=dtype)
+ # Snippet used to generate expected (requires only this module): hflip reverses the
+ # last dimension, so for a rank-1 tensor that is simply the element order reversed.
+ # x.flip(-1) -> tensor([3., 2., 1., 0.])
+ expected = torch.tensor([3.0, 2.0, 1.0, 0.0], device=device, dtype=dtype)
+ self.assert_close(kornia.geometry.transform.hflip(x), expected)
+
class TestRot180(BaseTester):
def smoke_test(self, device, dtype):
@@ -209,3 +229,10 @@ class TestRot180(BaseTester):
) # 3 x 3
self.gradcheck(kornia.geometry.transform.Rot180(), (input,))
+
+ def test_convention_rank1_raises(self, device, dtype):
+ # rot180 flips dims -2 and -1; a rank-1 tensor has no dim -2 and raises IndexError,
+ # unlike hflip which only needs dim -1 (see TestHflip.test_convention_rank1_supported).
+ x = torch.tensor([0.0, 1.0, 2.0, 3.0], device=device, dtype=dtype)
+ with pytest.raises(IndexError):
+ kornia.geometry.transform.rot180(x)
diff --git a/tests/geometry/transform/test_pyramid.py b/tests/geometry/transform/test_pyramid.py
index 8f0e17ef9..638589753 100644
--- a/tests/geometry/transform/test_pyramid.py
+++ b/tests/geometry/transform/test_pyramid.py
@@ -38,6 +38,24 @@ class TestPyrUp(BaseTester):
img = torch.rand(1, 2, 5, 4, device=device, dtype=torch.float64)
self.gradcheck(kornia.geometry.pyrup, (img,), nondet_tol=1e-8)
+ def test_convention_align_corners_and_border_type_change_output(self, device, dtype):
+ # pyrup's align_corners (default False) and border_type (default 'reflect') defaults
+ # actually change the output values -- existing tests only check output shape. pyrup is
+ # an independent implementation (interpolate-then-blur, no delegation to pyrdown), so the
+ # sibling pin on TestPyrDown gives this op no coverage on its own.
+ x = torch.arange(0.0, 16.0, device=device, dtype=dtype).view(1, 1, 4, 4)
+
+ out_ac_false = kornia.geometry.transform.pyrup(x, align_corners=False)
+ out_ac_true = kornia.geometry.transform.pyrup(x, align_corners=True)
+ out_default = kornia.geometry.transform.pyrup(x)
+ self.assert_close(out_default, out_ac_false, rtol=1e-2, atol=1e-2)
+ assert not torch.allclose(out_ac_false, out_ac_true, atol=1e-2, rtol=1e-2)
+
+ out_reflect = kornia.geometry.transform.pyrup(x, border_type="reflect")
+ out_constant = kornia.geometry.transform.pyrup(x, border_type="constant")
+ self.assert_close(out_default, out_reflect, rtol=1e-2, atol=1e-2)
+ assert not torch.allclose(out_reflect, out_constant, atol=1e-2, rtol=1e-2)
+
class TestPyrDown(BaseTester):
def test_shape(self, device, dtype):
@@ -66,6 +84,31 @@ class TestPyrDown(BaseTester):
img = torch.rand(1, 2, 5, 4, device=device, dtype=torch.float64)
self.gradcheck(kornia.geometry.pyrdown, (img,), nondet_tol=1e-8)
+ def test_convention_align_corners_and_border_type_change_output(self, device, dtype):
+ # pyrdown's align_corners (default False) and border_type (default 'reflect') defaults
+ # actually change the output values -- existing tests only check output shape, never a
+ # discriminating-literal comparison of the defaults against their alternatives.
+ x = torch.arange(0.0, 25.0, device=device, dtype=dtype).view(1, 1, 5, 5)
+
+ out_ac_false = kornia.geometry.transform.pyrdown(x, align_corners=False)
+ out_ac_true = kornia.geometry.transform.pyrdown(x, align_corners=True)
+ out_default = kornia.geometry.transform.pyrdown(x)
+ self.assert_close(out_default, out_ac_false, rtol=1e-2, atol=1e-2)
+ assert not torch.allclose(out_ac_false, out_ac_true, atol=1e-2, rtol=1e-2)
+
+ out_reflect = kornia.geometry.transform.pyrdown(x, border_type="reflect")
+ out_constant = kornia.geometry.transform.pyrdown(x, border_type="constant")
+ self.assert_close(out_default, out_reflect, rtol=1e-2, atol=1e-2)
+ assert not torch.allclose(out_reflect, out_constant, atol=1e-2, rtol=1e-2)
+
+ def test_convention_floor_not_ceil_on_odd_size(self, device, dtype):
+ # pyrdown uses floor(side / factor), diverging from OpenCV's ceil((side + 1) / 2) on
+ # odd/non-exactly-divisible sizes: 5x5 at the default factor=2.0 gives 2x2, not 3x3.
+ # (test_shape/test_shape_custom_factor only use exactly-divisible sizes, where floor and
+ # ceil agree.)
+ x = torch.rand(1, 1, 5, 5, device=device, dtype=dtype)
+ assert kornia.geometry.transform.pyrdown(x).shape == (1, 1, 2, 2)
+
class TestScalePyramid(BaseTester):
def test_shape_tuple(self, device, dtype):
@@ -128,6 +171,23 @@ class TestScalePyramid(BaseTester):
self.gradcheck(sp_tuple, (img,), nondet_tol=1e-4)
+ def test_convention_octave0_sigmas_example(self, device, dtype):
+ # Pins the Convention block's worked example: with n_levels=1 (default
+ # extra_levels=3), init_sigma=0.25 below the assumed input blur (0.5) makes
+ # octave 0's first sigma the input blur itself, while octave 1+ starts from
+ # init_sigma as usual -- the two octaves diverge only in that first entry.
+ inp = torch.rand(1, 1, 32, 32, device=device, dtype=dtype)
+ sp = kornia.geometry.ScalePyramid(n_levels=1, init_sigma=0.25)
+ _, sigmas, _ = sp(inp)
+ # Snippet used to generate expected (requires only this module):
+ # sp = kornia.geometry.ScalePyramid(n_levels=1, init_sigma=0.25)
+ # _, sigmas, _ = sp(torch.rand(1, 1, 32, 32))
+ # sigmas[0][0].tolist(), sigmas[1][0].tolist()
+ expected_octave0 = torch.tensor([0.5, 0.5, 1.0, 2.0], device=device, dtype=dtype)
+ expected_octave1 = torch.tensor([0.25, 0.5, 1.0, 2.0], device=device, dtype=dtype)
+ self.assert_close(sigmas[0][0], expected_octave0, rtol=1e-3, atol=1e-3)
+ self.assert_close(sigmas[1][0], expected_octave1, rtol=1e-3, atol=1e-3)
+
class TestBuildPyramid(BaseTester):
def test_smoke(self, device, dtype):
diff --git a/tests/geometry/transform/test_thin_plate_spline.py b/tests/geometry/transform/test_thin_plate_spline.py
index cf0a3ef5e..8fabb23c9 100644
--- a/tests/geometry/transform/test_thin_plate_spline.py
+++ b/tests/geometry/transform/test_thin_plate_spline.py
@@ -20,7 +20,7 @@ import torch
import kornia
-from testing.base import BaseTester
+from testing.base import BaseTester, supports_2d_border_padding
def _sample_points(batch_size, device, dtype=torch.float32):
@@ -274,3 +274,104 @@ class TestWarpImage(BaseTester):
kernel, affine = kornia.geometry.transform.get_tps_transform(dst, dst)
warped = kornia.geometry.transform.warp_image_tps(image, dst, kernel, affine, align_corners=True)
self.assert_close(warped, image, atol=1e-4, rtol=1e-4)
+
+ def test_convention_default_padding_mode_zeros(self, device, dtype):
+ # warp_image_tps's padding_mode default is 'zeros': grid_sample calls that sample
+ # outside bounds fill with 0, not the edge value ('border' would). This is
+ # independent of the align_corners identity-mismatch bug pinned separately by
+ # test_convention_default_align_corners_reproduces_identity below.
+ if dtype == torch.float16:
+ # get_tps_transform's linear solve is numerically unstable in float16 (produces NaN
+ # kernel/affine weights) -- matches this file's pre-existing
+ # test_identity_warp_align_corners float16 failure, unrelated to this convention.
+ pytest.skip("get_tps_transform is numerically unstable in float16 (produces NaN)")
+
+ 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)
+ 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)
+
+ out_zeros = kornia.geometry.transform.warp_image_tps(img, src, kernel, affine, padding_mode="zeros")
+ self.assert_close(out_default, out_zeros)
+
+ def test_convention_padding_mode_border_differs_from_zeros(self, device, dtype):
+ # Companion to test_convention_default_padding_mode_zeros above: 'border' padding
+ # must actually differ from the 'zeros' default. MPS's 2D grid_sample doesn't
+ # support 'border' (probed at runtime), so this half is skipped visibly there
+ # instead of silently no-op'ing inside an `if` guard.
+ if dtype == torch.float16:
+ pytest.skip("get_tps_transform is numerically unstable in float16 (produces NaN)")
+ if not supports_2d_border_padding(device):
+ pytest.skip("MPS 2D grid_sample lacks 'border' padding")
+
+ 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)
+ 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)
+ out_border = kornia.geometry.transform.warp_image_tps(img, src, kernel, affine, padding_mode="border")
+ assert not torch.allclose(out_default, out_border, atol=1e-2, rtol=1e-2)
+
+ def test_convention_control_points_normalized_coords(self, device, dtype):
+ # warp_image_tps's destination/output lattice is always corner-aligned
+ # (create_meshgrid(h, w, normalized_coordinates=True)), independent of the
+ # align_corners argument -- see the Convention block. With align_corners=True
+ # passed explicitly, grid_sample's own convention matches that lattice, so
+ # corner-aligned control points on both sides reproduce the intended warp
+ # exactly. Pinned here with a small translation expressed in corner-aligned
+ # normalized coordinates against a hardcoded expected output.
+ if dtype == torch.float16:
+ pytest.skip("get_tps_transform is numerically unstable in float16 (produces NaN)")
+ if dtype == torch.bfloat16:
+ pytest.skip("bfloat16 rounding of near-zero boundary values exceeds this test's atol")
+
+ img = torch.arange(16.0, device=device, dtype=dtype).view(1, 1, 4, 4)
+ # 4 corners + center, normalized [-1, 1] coordinates (align_corners=True mapping).
+ 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
+ )
+ dst = src.clone()
+ dst[..., 0] += 2.0 / 3.0 # one-pixel shift in normalized coords for W=4 (2 / (4 - 1))
+
+ kernel, affine = kornia.geometry.transform.get_tps_transform(dst, src)
+ warped = kornia.geometry.transform.warp_image_tps(img, src, kernel, affine, align_corners=True)
+
+ # Snippet used to generate expected (requires only this module):
+ # img = torch.arange(16.0).view(1, 1, 4, 4)
+ # src = torch.tensor([[[-1.,-1.],[1.,-1.],[1.,1.],[-1.,1.],[0.,0.]]])
+ # dst = src.clone(); dst[..., 0] += 2.0 / 3.0
+ # kernel, affine = get_tps_transform(dst, src)
+ # warp_image_tps(img, src, kernel, affine, align_corners=True)
+ expected = torch.tensor(
+ [[[[0.0, 0.0, 1.0, 2.0], [0.0, 4.0, 5.0, 6.0], [0.0, 8.0, 9.0, 10.0], [0.0, 12.0, 13.0, 14.0]]]],
+ device=device,
+ dtype=dtype,
+ )
+ 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.
+ if dtype == torch.float16:
+ pytest.skip("get_tps_transform is numerically unstable in float16 (produces NaN)")
+
+ 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)
+ 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)
+ self.assert_close(out_default, img, atol=1e-2, rtol=1e-2)