Skip to content

šŸ Geometric Computer Vision Library for Spatial AI

docs(geometry.transform): trim convention blocks and pins to kornia scope (#4788)

Dmytro Mishkinb0805819a291
diff --git a/changelog.d/4788.fixed.md b/changelog.d/4788.fixed.md
new file mode 100644
index 000000000..05a69671f
--- /dev/null
+++ b/changelog.d/4788.fixed.md
@@ -0,0 +1 @@
+`geometry.transform` docstrings: removed the false `crop_by_boxes` note claiming a source box smaller than the destination box raises, and documented four known defects with their issues: `homography_warp(normalized_homography=False)` ignores `mode` and `align_corners` (#4772), `remap` resamples under an identity pixel map at its default `align_corners` (#4504), `warp_perspective` and `warp_perspective3d` warp a `float64` input through a `float32` grid (#4776), and `ScalePyramid` labels later levels below their real blur when `init_sigma` is below the assumed input blur (#4796).
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index cdb607d29..be77a554c 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -145,9 +145,10 @@ def affine(
.. image:: _static/img/warp_affine.png
Convention:
+ See :doc:`Conventions & Pitfalls </get-started/conventions>` for the ``align_corners``
+ defaults and sampling rules.
+
- ``matrix`` is the source→destination **pixel** affine matrix :math:`(B, 2, 3)`
- - align_corners: ``True`` by default
- - padding_mode: ``'zeros'`` by default
Args:
tensor: The image tensor to be warped in shapes of
@@ -204,8 +205,7 @@ def affine3d(
Convention:
- ``matrix`` is the source→destination **pixel** affine matrix :math:`(B, 3, 4)`
- - align_corners: ``False`` by default
- - padding_mode: ``'zeros'`` by default
+ - align_corners: ``False`` by default (the 2D :func:`affine` defaults to ``True``)
Args:
tensor: The image tensor to be warped in shapes of
@@ -269,8 +269,6 @@ def rotate(
Convention:
- ``center`` is ``(x, y)`` in pixels, origin at top-left; defaults to the tensor center
- positive ``angle`` rotates counter-clockwise as displayed (y-down image axes)
- - align_corners: ``True`` by default
- - padding_mode: ``'zeros'`` by default
Args:
tensor: The image tensor to be warped in shapes of :math:`(B, C, H, W)`.
@@ -340,8 +338,7 @@ def rotate3d(
Convention:
- ``center`` is ``(x, y, z)`` in pixels, origin at the top-left of the first depth
slice (``z = 0``); defaults to the tensor center
- - align_corners: ``False`` by default
- - padding_mode: ``'zeros'`` by default
+ - align_corners: ``False`` by default (the 2D :func:`rotate` defaults to ``True``)
Args:
tensor: The image tensor to be warped in shapes of :math:`(B, C, D, H, W)`.
@@ -411,8 +408,6 @@ def translate(
Convention:
- ``translation`` is ``(dx, dy)`` in pixels
- - align_corners: ``True`` by default
- - padding_mode: ``'zeros'`` by default
Args:
tensor: The image tensor to be warped in shapes of :math:`(B, C, H, W)`.
@@ -466,8 +461,6 @@ def scale(
Convention:
- ``center`` is ``(x, y)`` in pixels, origin at top-left; defaults to the tensor center
- - align_corners: ``True`` by default
- - padding_mode: ``'zeros'`` by default
Args:
tensor: The image tensor to be warped in shapes of :math:`(B, C, H, W)`.
@@ -532,8 +525,8 @@ def shear(
Convention:
- ``shear`` is ``(shx, shy)``
- - align_corners: ``False`` by default
- - padding_mode: ``'zeros'`` by default
+ - align_corners: ``False`` by default (differs from the other 2D affine warps and from
+ :class:`Shear`, which default to ``True``)
Args:
tensor: The image tensor to be skewed with shape of :math:`(B, C, H, W)`.
@@ -712,7 +705,7 @@ def resize_to_be_divisible(
"""Resize the input tensor to be divisible by a certain factor.
Convention:
- - align_corners: ``None`` by default; see the convention block of :func:`resize`
+ - see the convention block of :func:`resize`
- rounds ``height``/``width`` to the nearest multiple of ``divisible_factor`` before
delegating to :func:`resize`
@@ -754,8 +747,6 @@ def rescale(
Convention:
- ``factor`` is ``(factor_h, factor_w)`` when a pair — height first (contrast
:func:`scale`, whose ``scale_factor`` is x-first)
- - align_corners: ``None`` by default (follows ``torch.nn.functional.interpolate``;
- see the convention block of :func:`resize`)
- delegates to :func:`resize` after converting ``factor`` to an output ``size``
Args:
@@ -796,7 +787,6 @@ class Resize(nn.Module):
conventions. When resizing camera images, see
:doc:`camera and world conventions </get-started/camera-conventions>` for matching intrinsics scaling.
- - align_corners: ``None`` by default, matching :func:`resize`
- See the convention block of :func:`resize`.
Args:
@@ -866,7 +856,6 @@ class Affine(nn.Module):
r"""Apply multiple elementary affine transforms simultaneously.
Convention:
- - align_corners: ``True`` by default, matching :func:`affine`
- See the convention block of :func:`affine`.
Args:
@@ -1041,7 +1030,6 @@ class Rotate(nn.Module):
r"""Rotate the tensor anti-clockwise about the centre.
Convention:
- - align_corners: ``True`` by default, matching :func:`rotate`
- See the convention block of :func:`rotate`.
Args:
@@ -1103,7 +1091,6 @@ class Translate(nn.Module):
r"""Translate the tensor in pixel units.
Convention:
- - align_corners: ``True`` by default, matching :func:`translate`
- See the convention block of :func:`translate`.
Args:
@@ -1160,7 +1147,6 @@ class Scale(nn.Module):
r"""Scale the tensor by a factor.
Convention:
- - align_corners: ``True`` by default, matching :func:`scale`
- See the convention block of :func:`scale`.
Args:
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index d723db636..db0c4043d 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -50,13 +50,14 @@ def crop_and_resize(
r"""Extract crops from 2D images (4D torch.Tensor) and resize given a bounding box.
Convention:
+ See :doc:`Conventions & Pitfalls </get-started/conventions>` for the ``align_corners``
+ defaults and sampling rules.
+
- 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).
@@ -148,8 +149,6 @@ def center_crop(
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).
@@ -247,8 +246,6 @@ def crop_by_boxes(
: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).
@@ -288,10 +285,6 @@ def crop_by_boxes(
tensor([[[[ 5.0000, 6.0000],
[ 9.0000, 10.0000]]]])
- Note:
- If the src_box is smaller than dst_box, the following error will be thrown.
- RuntimeError: solve_cpu: For batch 0: U(2,2) is zero, singular U.
-
"""
bbox: Tuple[torch.Tensor, torch.Tensor] = infer_bbox_shape(dst_box)
if not ((bbox[0] == bbox[0][0]).all() and (bbox[1] == bbox[1][0]).all()):
@@ -345,21 +338,8 @@ def crop_by_transform_mat(
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 note below); :class:`CenterCrop2D` itself
- calls this with a :math:`(B, 2, 3)` transform
- - align_corners: ``True`` by default
- - padding_mode: ``'zeros'`` by default
-
- .. note::
- An ``out_size`` dimension equal to ``1`` is handled like any other size under
- both ``align_corners`` settings: the :math:`(B, 3, 3)` path keeps its projective
- row and agrees with the :math:`(B, 2, 3)` path for an affine transform. It used
- to return all-``NaN`` at ``align_corners=True`` and to silently fall back to
- :func:`warp_affine` at ``align_corners=False``
- (`#3929 <https://github.com/kornia/kornia/issues/3929>`_); the singleton axis
- now maps to the centre of the normalized range and the warp normalizes under
- the same convention it samples with.
+ matrix, so a non-trivial third (projective) row changes the output; an
+ ``out_size`` dimension of ``1`` is handled like any other size
Args:
input_tensor: the 2D image torch.Tensor with shape (B, C, H, W).
diff --git a/kornia/geometry/transform/crop3d.py b/kornia/geometry/transform/crop3d.py
index 1252d0581..002f53d28 100644
--- a/kornia/geometry/transform/crop3d.py
+++ b/kornia/geometry/transform/crop3d.py
@@ -401,12 +401,10 @@ def crop_by_transform_mat3d(
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
+ either :math:`(B, 3, 4)` affine or :math:`(B, 4, 4)` homogeneous; only the top
+ three rows are used, so a projective last row is ignored (unlike the 2D
+ :func:`crop_by_transform_mat`)
- align_corners: ``True`` by default
- - padding_mode: ``'zeros'`` by default
Args:
tensor: the 3D volume tensor with shape (B, C, D, H, W).
diff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.py
index 88c496371..8c7d697da 100644
--- a/kornia/geometry/transform/elastic_transform.py
+++ b/kornia/geometry/transform/elastic_transform.py
@@ -47,10 +47,8 @@ def elastic_transform2d(
grid (positive x-noise shifts image content left)
- displacements are smoothed with a Gaussian (``kernel_size``,
``sigma``) and scaled by ``alpha``
- - align_corners: ``False`` by default; it selects the normalization of the sampling
- grid as well as the ``grid_sample`` call, so zero ``noise`` is an identity under
- either setting
- - padding_mode: ``'zeros'`` by default
+ - align_corners: ``False`` by default (the matrix warps default to ``True``); zero
+ ``noise`` is an identity under either setting
Args:
image: Input image to be transformed with shape :math:`(B, C, H, W)`.
diff --git a/kornia/geometry/transform/flips.py b/kornia/geometry/transform/flips.py
index 08a40cec0..660dccbce 100644
--- a/kornia/geometry/transform/flips.py
+++ b/kornia/geometry/transform/flips.py
@@ -158,9 +158,8 @@ def rot180(input: torch.Tensor) -> torch.Tensor:
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
+ - requires rank ≄ 2: unbatched :math:`(H, W)`/:math:`(C, H, W)` or batched
+ :math:`(*, C, H, W)` all work
Args:
input: input torch.Tensor.
@@ -179,8 +178,7 @@ def hflip(input: torch.Tensor) -> torch.Tensor:
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)
+ (rank 0 is outside the contract)
Args:
input: input torch.Tensor.
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
index 169dd0800..19756276e 100644
--- a/kornia/geometry/transform/homography_warper.py
+++ b/kornia/geometry/transform/homography_warper.py
@@ -85,7 +85,6 @@ class HomographyWarper(BaseWarper):
See :doc:`Conventions & Pitfalls </get-started/conventions>` for homography direction, normalized
coordinates and sampling conventions.
- - align_corners: ``False`` by default, matching :func:`homography_warp`
- See the convention block of :func:`homography_warp`.
Args:
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 7c25be6d1..4a6e9548a 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -229,9 +229,8 @@ def warp_perspective(
- input: :math:`(B, C, H, W)`; ``dsize`` is ``(h, w)``
- ``M`` is the source→destination **pixel** homography :math:`(B, 3, 3)`
(contrast :func:`homography_warp`, which by default consumes destination→source normalized)
- - coordinates: ``(x, y)``, pixel centers, origin at top-left
- - align_corners: ``True`` by default
- - padding_mode: ``'zeros'`` by default
+ - a ``float64`` input is sampled through a ``float32`` grid, so it is warped only to float32
+ precision (`#4776 <https://github.com/kornia/kornia/issues/4776>`_)
- a zero output dimension returns an autograd-connected empty tensor;
negative output dimensions raise ``ValueError``
@@ -353,9 +352,6 @@ def warp_affine(
- input: :math:`(B, C, H, W)`; ``dsize`` is ``(h, w)``
- ``M`` is the source→destination **pixel** affine matrix :math:`(B, 2, 3)`
- - coordinates: ``(x, y)``, pixel centers, origin at top-left
- - align_corners: ``True`` by default
- - padding_mode: ``'zeros'`` by default
- a zero output dimension returns an autograd-connected empty tensor;
negative output dimensions raise ``ValueError``
@@ -671,8 +667,8 @@ def get_perspective_transform(points_src: torch.Tensor, points_dst: torch.Tensor
Convention:
- points: ``(x, y)``, pixel centers, origin at top-left; shape :math:`(B, 4, 2)`
- - returns the source→destination **pixel** homography :math:`(B, 3, 3)`
- (contrast :func:`homography_warp`, which by default consumes destination→source normalized)
+ - returns the source→destination **pixel** homography :math:`(B, 3, 3)` that
+ :func:`warp_perspective` takes
Args:
points_src: coordinates of quadrangle vertices in the source image with shape :math:`(B, 4, 2)`.
@@ -822,7 +818,9 @@ def remap(
- input: :math:`(B, C, H, W)`; ``map_x``/``map_y`` are :math:`(B, H, W)` pixel coordinates
unless ``normalized_coordinates=True``
- align_corners: ``None`` by default, resolved to ``False`` internally
- - padding_mode: ``'zeros'`` by default
+ - pixel maps are normalized with the ``align_corners=True`` convention whatever flag
+ reaches ``grid_sample``, so at ``False``/``None`` even an identity map resamples the image;
+ pass ``align_corners=True`` (`#4504 <https://github.com/kornia/kornia/issues/4504>`_)
- the output spatial size comes from the maps; a zero map axis returns an
autograd-connected empty output, including when the matching source axis is empty
@@ -1635,6 +1633,8 @@ def warp_perspective3d(
- border_mode: ``'zeros'`` by default
- a zero output dimension returns an autograd-connected empty tensor;
negative output dimensions raise ``ValueError``
+ - a ``float64`` input is sampled through a ``float32`` grid, so it is warped only to float32
+ precision (`#4776 <https://github.com/kornia/kornia/issues/4776>`_)
Args:
src: input image with shape :math:`(B, C, D, H, W)`.
@@ -1706,10 +1706,9 @@ def homography_warp(
consumed as the source→destination **pixel** homography, exactly like
:func:`warp_perspective`
- ``dsize`` is ``(h, w)``
- - align_corners: ``False`` by default; ``mode``: ``'bilinear'`` by default (both only
- honored when ``normalized_homography=True`` — the pixel-homography path currently
- forces ``align_corners=True`` and ``mode='bilinear'``)
- - padding_mode: ``'zeros'`` by default
+ - align_corners: ``False`` by default (differs from :func:`warp_perspective`)
+ - with ``normalized_homography=False``, ``mode`` and ``align_corners`` are ignored and
+ ``'bilinear'``/``True`` are used (`#4772 <https://github.com/kornia/kornia/issues/4772>`_)
- negative output dimensions raise ``ValueError``
Args:
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index e55659573..e8ad77504 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -156,30 +156,15 @@ class ScalePyramid(nn.Module):
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
+ - ``forward`` returns ``(pyr, sigmas, pixel_dists)``, one entry per octave: ``pyr[o]`` is
+ :math:`(B, C, L, H_o, W_o)` with ``L = n_levels + extra_levels``, and ``sigmas[o]`` and
+ ``pixel_dists[o]`` are :math:`(B, L)` nominal values (the targeted blur, not a measurement)
+ - ``sigmas`` is octave-relative: the blur in input pixels is ``sigmas[o] * pixel_dists[o]``
+ - an ``init_sigma`` below the assumed input blur (``0.5``, or ``1.0`` with
+ ``double_image=True``) leaves the first level at that blur, but ``sigmas`` still counts
+ from ``init_sigma``, so later levels are labelled below their real blur
+ (`#4796 <https://github.com/kornia/kornia/issues/4796>`_)
+ - the internal resizes use ``align_corners=True``; there is no ``align_corners`` parameter
Args:
n_levels: number of the levels in octave.
@@ -521,8 +506,6 @@ def build_pyramid(
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
diff --git a/kornia/geometry/transform/thin_plate_spline.py b/kornia/geometry/transform/thin_plate_spline.py
index 2e1c6971d..6f9e1943b 100644
--- a/kornia/geometry/transform/thin_plate_spline.py
+++ b/kornia/geometry/transform/thin_plate_spline.py
@@ -63,28 +63,15 @@ def get_tps_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> tup
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
- - 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`, both ``points_dst`` and ``points_src``
- here are normalized in the single frame selected by that function's
- ``align_corners`` — see its Convention block for both formulas)::
+ - ``points_src``/``points_dst``: :math:`(B, N, 2)` in ``(x, y)`` order, in whatever
+ coordinate frame the caller supplies; no normalization is applied
+ - returns kernel weights :math:`(B, N, 2)` and affine weights :math:`(B, 3, 2)`; the
+ identity mapping gives zero kernel weights and an identity affine up to solver round-off
+ - the tensor passed as the **second** argument is the ``kernel_centers`` that the warp
+ function must receive with these weights. :func:`warp_points_tps` is composed in the
+ natural ``(points_src, points_dst)`` order; :func:`warp_image_tps` samples from output
+ space back into input space, so it is composed **reversed**, with both point sets in the
+ normalized frame given in its Convention block::
kernel_weights, affine_weights = get_tps_transform(points_dst, points_src)
warped = warp_image_tps(image, kernel_centers=points_src,
@@ -156,17 +143,10 @@ def warp_points_tps(
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]`)
+ - points: :math:`(B, N, 2)` (or :math:`(B, K, 2)` for kernel centers) in ``(x, y)``
+ order; no normalization is applied, and the output is in the same frame, not clamped
+ - ``kernel_centers`` must be the second argument passed to :func:`get_tps_transform`
+ (see its Convention block)
Args:
points_src: torch.Tensor of source points :math:`(B, N, 2)`.
@@ -245,25 +225,15 @@ def warp_image_tps(
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 on **both** sides — ``kernel_centers`` and both arguments
- of the reversed :func:`get_tps_transform` call — live in the single
- normalized grid_sample coordinate frame selected by ``align_corners``
- below, where ``[-1, 1]`` is the in-bounds extent (values outside are
- allowed, subject to ``padding_mode``) rather than a validity bound. At
- the default ``align_corners=False`` that is the half-pixel mapping
- :math:`x_{norm} = (2x+1)/W - 1`; ``align_corners=True`` selects the
- corner-aligned :math:`x_{norm} = 2x/(W-1) - 1`. Pixel-space
- (unnormalized) control points silently produce a wrong warp of the
- correct shape, with no error raised
- - align_corners: ``False`` by default
- - padding_mode: ``'zeros'`` by default
+ - image: :math:`(B, C, H, W)`; the weights come from :func:`get_tps_transform` called
+ **reversed**, ``get_tps_transform(points_dst, points_src)``, and ``kernel_centers`` is
+ ``points_src`` (see its Convention block)
+ - all control points live in the normalized ``grid_sample`` frame selected by
+ ``align_corners``: the half-pixel :math:`x_{norm} = (2x+1)/W - 1` at the default
+ ``False``, the corner-aligned :math:`x_{norm} = 2x/(W-1) - 1` at ``True``; values outside
+ :math:`[-1, 1]` sample the padding. Pixel-space control points silently give a wrong
+ warp of the right shape
+ - align_corners: ``False`` by default (the matrix warps default to ``True``)
Args:
image: input image torch.Tensor :math:`(B, C, H, W)`.
diff --git a/tests/geometry/transform/test_crop2d.py b/tests/geometry/transform/test_crop2d.py
index ab4372085..24828a45c 100644
--- a/tests/geometry/transform/test_crop2d.py
+++ b/tests/geometry/transform/test_crop2d.py
@@ -174,10 +174,8 @@ class TestCropAndResize(BaseTester):
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.
+ # A single box broadcasts over a batch of images (test_crop_batch_broadcast), but a single
+ # image does not broadcast over a batch of boxes: it raises.
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]]],
@@ -430,12 +428,7 @@ class TestCropByTransform(BaseTester):
@pytest.mark.parametrize("align_corners", [True, False])
@pytest.mark.parametrize("out_size", [(1, 3), (3, 1), (1, 1)])
def test_convention_one_pixel_output(self, device, dtype, align_corners, out_size):
- # A 1-pixel output dimension must behave like any other size under both conventions
- # (#3929). The (B, 3, 3) path used to return all-NaN at align_corners=True (fixed by
- # #4006's singleton-axis mapping) and, at align_corners=False, to silently fall back to
- # warp_affine through a correction matrix built for the wrong grid convention, which
- # gave these pre-fix values on the same input:
- # (1, 3): [4.6111, 5.5000, 5.9815] (3, 1): [5.9444, 9.5000, 12.1204] (1, 1): [4.1667]
+ # A 1-pixel output dimension behaves like any other size under both conventions (#3929).
# Snippet used to generate expected (pure slicing, no resampling involved):
# inp = torch.arange(16.0).view(1, 1, 4, 4); h, w = out_size
# expected = inp[:, :, 1 : 1 + h, 1 : 1 + w]
diff --git a/tests/geometry/transform/test_elastic_transform.py b/tests/geometry/transform/test_elastic_transform.py
index d07383332..963641c82 100644
--- a/tests/geometry/transform/test_elastic_transform.py
+++ b/tests/geometry/transform/test_elastic_transform.py
@@ -157,10 +157,8 @@ class TestElasticTransform(BaseTester):
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).
+ # alpha is (x, y): alpha[0] scales the x-displacement, unlike kernel_size and sigma, which
+ # are (y, x) (test_convention_sigma_yx_order).
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)
@@ -222,46 +220,27 @@ class TestElasticTransform(BaseTester):
# 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.
+ def test_convention_padding_mode_border_differs_from_zeros(self, device, dtype):
+ # padding_mode is forwarded: once the displacement pushes the (clamped) sampling grid to the
+ # edge, the 'zeros' default and 'border' give different rows.
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
+ # elastic_transform2d(image, noise, **kwargs)[0, 0, 2] # default row
+ # elastic_transform2d(image, noise, padding_mode="border", **kwargs)[0, 0, 2] # 'border' row
+ out_default = elastic_transform2d(image, noise, **kwargs)
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 a17e4b21a..5fa192057 100644
--- a/tests/geometry/transform/test_flip.py
+++ b/tests/geometry/transform/test_flip.py
@@ -83,12 +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).
+ @pytest.mark.parametrize("op", ["vflip", "rot180"])
+ def test_convention_rank1_raises(self, op, device, dtype):
+ # vflip and rot180 need dim -2, so they require rank >= 2, unlike hflip
+ # (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)
+ with pytest.raises((IndexError, RuntimeError)):
+ getattr(kornia.geometry.transform, op)(x)
class TestHflip(BaseTester):
@@ -154,15 +155,10 @@ class TestHflip(BaseTester):
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.
+ # hflip flips dim -1 and accepts a rank-1 tensor, while vflip/rot180 require rank >= 2
+ # (TestVflip.test_convention_rank1_raises). Rank 0 is outside the contract and 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.])
+ # Snippet used to generate expected: 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)
@@ -229,10 +225,3 @@ 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_homography_warper.py b/tests/geometry/transform/test_homography_warper.py
index 67ec40499..a62377aa7 100644
--- a/tests/geometry/transform/test_homography_warper.py
+++ b/tests/geometry/transform/test_homography_warper.py
@@ -182,31 +182,15 @@ class TestHomographyWarper(BaseTester):
self.assert_close(patch_src[..., -1, -1], patch_dst[..., -1, -1], atol=1e-4, rtol=1e-4)
def test_convention_align_corners_default_false(self, device, dtype):
- # HomographyWarper's bare default align_corners=False (every HomographyWarper construction in
- # this file passes align_corners=True explicitly; this exercises the bare default). An identity
- # homography must reproduce the input under either convention: the internal sampling grid is
- # built to match align_corners, so the two agree rather than differing by half a pixel (#3904).
- if dtype in (torch.float16, torch.bfloat16):
- pytest.skip("hardcoded-literal pin only reliable at float32/float64 precision")
- # Snippet used to generate the pre-#3945 literal (the call under test, verbatim):
- # height, width = 4, 5
- # patch_src = torch.arange(float(height * width)).view(1, 1, height, width)
- # warper = kornia.geometry.transform.HomographyWarper(height, width) # no align_corners passed
- # expected = warper(patch_src, torch.eye(3)[None])
- # Pre-#3945 literal, i.e. what an *identity* warp returned under the bare default:
- # [[[[0.0000, 0.3750, 1.0000, 1.6250, 1.0000],
- # [2.0833, 4.9167, 6.1667, 7.4167, 4.0833],
- # [5.4167, 11.5833, 12.8333, 14.0833, 7.4167],
- # [3.7500, 7.8750, 8.5000, 9.1250, 4.7500]]]]
- # The corrected expectation is the input itself, so it needs no literal.
+ # At HomographyWarper's bare default align_corners=False, an identity homography reproduces
+ # the input: the sampling grid is built under the same convention it samples with (#3904).
height, width = 4, 5
patch_src = torch.arange(float(height * width), device=device, dtype=dtype).view(1, 1, height, width)
dst_homo_src = eye_like(3, patch_src)
warper = kornia.geometry.transform.HomographyWarper(height, width)
patch_dst = warper(patch_src, dst_homo_src)
self.assert_close(patch_dst, patch_src, atol=1e-3, rtol=1e-3)
- # the literal above cannot distinguish False from None (grid_sample treats them alike), so
- # the documented defaults are additionally pinned on the signatures of both APIs
+ # the identity holds under either setting, so the default itself is pinned on the signatures
import inspect
assert (
diff --git a/tests/geometry/transform/test_imgwarp.py b/tests/geometry/transform/test_imgwarp.py
index 5dce6be04..25196ddb1 100644
--- a/tests/geometry/transform/test_imgwarp.py
+++ b/tests/geometry/transform/test_imgwarp.py
@@ -741,6 +741,35 @@ class TestWarpPerspective(BaseTester):
hw = kornia.geometry.transform.homography_warp(x, _torch_inverse_cast(Hn), (3, 5), align_corners=True)
self.assert_close(hw, expected, atol=1e-4, rtol=1e-4)
+ def test_wart_float64_identity_goes_through_a_float32_grid_4776(self, device):
+ # warp_perspective builds its sampling grid in float32 and casts it, so a float64 identity warp
+ # is exact only to float32 precision, while warp_affine is exact (#4776). Flips once the grid
+ # is built in the input dtype.
+ if device.type == "mps":
+ pytest.skip("MPS has no float64")
+ x = torch.arange(64.0, device=device, dtype=torch.float64).view(1, 1, 8, 8) / 7.0
+ eye = torch.eye(3, device=device, dtype=torch.float64)[None]
+ affine = kornia.geometry.transform.warp_affine(x, eye[:, :2], (8, 8))
+ assert (affine - x).abs().max() < 1e-12
+ assert (kornia.geometry.transform.warp_perspective(x, eye, (8, 8)) - x).abs().max() > 1e-9
+
+ def test_wart_homography_warp_pixel_path_ignores_mode_and_align_corners_4772(self, device, dtype):
+ # With normalized_homography=False, homography_warp calls warp_perspective with mode="bilinear"
+ # and align_corners=True whatever it was given (#4772). Reflection padding makes align_corners
+ # visible; a 1.5-pixel shift makes nearest differ from bilinear. Flips once both are forwarded.
+ img = torch.arange(16.0, device=device, dtype=dtype).view(1, 1, 4, 4)
+ H = torch.tensor([[[1.0, 0.0, 1.5], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ warp = kornia.geometry.transform.warp_perspective
+ hw = kornia.geometry.transform.homography_warp(
+ img, H, (4, 4), padding_mode="reflection", align_corners=False, normalized_homography=False
+ )
+ self.assert_close(hw, warp(img, H, (4, 4), padding_mode="reflection", align_corners=True))
+ assert not torch.allclose(hw, warp(img, H, (4, 4), padding_mode="reflection", align_corners=False), atol=0.1)
+
+ hn = kornia.geometry.transform.homography_warp(img, H, (4, 4), mode="nearest", normalized_homography=False)
+ self.assert_close(hn, warp(img, H, (4, 4), mode="bilinear"))
+ assert not torch.allclose(hn, warp(img, H, (4, 4), mode="nearest"), atol=0.1)
+
@pytest.mark.parametrize("align_corners", [True, False])
def test_convention_identity_agrees_with_warp_affine(self, align_corners, device, dtype):
# An identity homography reproduces the input under either align_corners convention, and
@@ -933,6 +962,15 @@ class TestRemap(BaseTester):
self.assert_close(actual, image, atol=0.0, rtol=0.0)
+ def test_wart_remap_identity_pixel_map_resamples_at_default_4504(self, device, dtype):
+ # remap normalizes pixel maps with the align_corners=True mapping whatever flag it passes to
+ # grid_sample, so at the default (None, i.e. False) an identity map does not reproduce the
+ # input (#4504). Flips once the normalization follows align_corners.
+ image = torch.arange(16.0, device=device, dtype=dtype).view(1, 1, 4, 4)
+ grid = kornia.geometry.create_meshgrid(4, 4, normalized_coordinates=False, device=device, dtype=dtype)
+ self.assert_close(kornia.geometry.remap(image, grid[..., 0], grid[..., 1], align_corners=True), image)
+ assert not torch.allclose(kornia.geometry.remap(image, grid[..., 0], grid[..., 1]), image, atol=1.0)
+
@pytest.mark.parametrize("source_empty", [False, True])
def test_empty_maps_return_autograd_connected_output(self, source_empty, device, dtype):
_skip_if_mps_lacks_grid_sample_backward(device)
diff --git a/tests/geometry/transform/test_pyramid.py b/tests/geometry/transform/test_pyramid.py
index 638589753..252b3851b 100644
--- a/tests/geometry/transform/test_pyramid.py
+++ b/tests/geometry/transform/test_pyramid.py
@@ -38,24 +38,6 @@ 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):
@@ -84,28 +66,22 @@ 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)
+ @pytest.mark.parametrize("op, side", [("pyrdown", 5), ("pyrup", 4)])
+ def test_convention_align_corners_and_border_type_change_output(self, op, side, device, dtype):
+ # The align_corners (default False) and border_type (default 'reflect') defaults of pyrdown and
+ # pyrup, which are independent implementations, each change the output.
+ fn = getattr(kornia.geometry.transform, op)
+ x = torch.arange(float(side * side), device=device, dtype=dtype).view(1, 1, side, side)
- 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)
+ out_default = fn(x)
+ self.assert_close(out_default, fn(x, align_corners=False), rtol=1e-2, atol=1e-2)
+ assert not torch.allclose(out_default, fn(x, align_corners=True), atol=1e-2, rtol=1e-2)
+ self.assert_close(out_default, fn(x, border_type="reflect"), rtol=1e-2, atol=1e-2)
+ assert not torch.allclose(out_default, fn(x, border_type="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.)
+ # pyrdown uses floor(side / factor); OpenCV's pyrDown uses (side + 1) // 2, so an odd side
+ # differs: 5x5 at the default factor=2.0 gives 2x2, not 3x3.
x = torch.rand(1, 1, 5, 5, device=device, dtype=dtype)
assert kornia.geometry.transform.pyrdown(x).shape == (1, 1, 2, 2)
@@ -171,11 +147,11 @@ 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.
+ def test_wart_scale_pyramid_sigmas_underreport_blur_4796(self, device, dtype):
+ # With init_sigma=0.25 below the assumed input blur (0.5), level 0 stays at 0.5 but the
+ # sigma bookkeeping restarts at init_sigma, so level 1 (real blur about 0.66) is also
+ # labelled 0.5 (#4796). Flips once the labels follow the real blur or such an
+ # init_sigma is rejected.
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)
diff --git a/tests/geometry/transform/test_signature_defaults.py b/tests/geometry/transform/test_signature_defaults.py
new file mode 100644
index 000000000..d5219bf44
--- /dev/null
+++ b/tests/geometry/transform/test_signature_defaults.py
@@ -0,0 +1,48 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import inspect
+
+import pytest
+
+import kornia.geometry.transform as T
+
+# Signature defaults that the Convention blocks or the conventions page state because they differ
+# from a sibling (the 2D matrix warps and crops default to align_corners=True). One row per
+# stated default.
+_STATED_DEFAULTS = [
+ ("warp_perspective", "align_corners", True),
+ ("warp_affine", "align_corners", True),
+ ("remap", "align_corners", None),
+ ("elastic_transform2d", "align_corners", False),
+ ("warp_image_tps", "align_corners", False),
+ ("crop_by_indices", "align_corners", None),
+ ("affine3d", "align_corners", False),
+ ("rotate3d", "align_corners", False),
+ ("shear", "align_corners", False),
+ ("Shear", "align_corners", True),
+ ("rescale", "align_corners", None),
+ ("Rescale", "align_corners", True),
+]
+
+
[email protected](("name", "param", "default"), _STATED_DEFAULTS, ids=str)
+def test_convention_stated_signature_default(name, param, default):
+ obj = getattr(T, name)
+ sig = inspect.signature(obj.__init__ if inspect.isclass(obj) else obj)
+ assert sig.parameters[param].default == default
+ assert type(sig.parameters[param].default) is type(default)
diff --git a/tests/geometry/transform/test_thin_plate_spline.py b/tests/geometry/transform/test_thin_plate_spline.py
index 01b162d42..54c00dc99 100644
--- a/tests/geometry/transform/test_thin_plate_spline.py
+++ b/tests/geometry/transform/test_thin_plate_spline.py
@@ -289,35 +289,9 @@ class TestWarpImage(BaseTester):
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)")
+ # padding_mode is forwarded: 'border' differs from the 'zeros' default once the warp samples
+ # out of bounds.
if not supports_2d_border_padding(device):
pytest.skip("MPS 2D grid_sample lacks 'border' padding")
@@ -334,17 +308,10 @@ class TestWarpImage(BaseTester):
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")
+ # Control points live in the normalized frame selected by align_corners: at True, a
+ # one-pixel shift of a W=4 image is 2 / (4 - 1) in corner-aligned coordinates.
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("half-precision 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).
@@ -371,13 +338,8 @@ class TestWarpImage(BaseTester):
self.assert_close(warped, expected, atol=1e-4, rtol=1e-4)
def test_convention_default_align_corners_reproduces_identity(self, device, dtype):
- # An identity TPS transform warped with warp_image_tps's *default* align_corners
- # reproduces the input image, exactly like the align_corners=True case pinned by
- # test_identity_warp_align_corners above: the internal create_meshgrid now builds the
- # sampling grid under the same convention grid_sample is called with (#3928).
- if dtype == torch.float16:
- pytest.skip("get_tps_transform is numerically unstable in float16 (produces NaN)")
-
+ # An identity TPS transform reproduces the input at the default align_corners too, as
+ # test_identity_warp_align_corners does at True (#3928).
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
)