Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(augmentation): Convention blocks (batch 6b: 2D geometric) (#4538)

Dmytro Mishkin90650596d4de
diff --git a/changelog.d/4538.added.md b/changelog.d/4538.added.md
new file mode 100644
index 000000000..654723e71
--- /dev/null
+++ b/changelog.d/4538.added.md
@@ -0,0 +1 @@
+Document per-class coordinate, sampling, crop, resize, padding, and non-rigid warp conventions for 2D geometric augmentations, with executable tests for current behavior and known limitations. Clarify sampler migration after module and container moves.
diff --git a/docs/source/augmentation.geometric.rst b/docs/source/augmentation.geometric.rst
index 9075dbad2..0ef9fd200 100644
--- a/docs/source/augmentation.geometric.rst
+++ b/docs/source/augmentation.geometric.rst
@@ -23,6 +23,7 @@ and mask values without moving coordinates. See
.. autoclass:: RandomRotation
.. autoclass:: RandomShear
.. autoclass:: RandomThinPlateSpline
+.. autoclass:: RandomTranslate
.. autoclass:: RandomVerticalFlip
Resize
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index 1c0e6dc1d..6794fa28f 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -336,14 +336,23 @@ Randomness in augmentations
- ``set_rng_device_and_dtype`` requests a sampling device and dtype. It
updates the gate configuration and asks the parameter generator to rebuild
its samplers, but some generators retain internal CPU tensors or ignore
- the requested precision. A move can fail in the setter itself or during
- a later forward, depending on the configuration
- (`#4415 <https://github.com/kornia/kornia/issues/4415>`_,
- `#4426 <https://github.com/kornia/kornia/issues/4426>`_).
+ the requested precision
+ (`#4426 <https://github.com/kornia/kornia/issues/4426>`_).
Returned parameter placement is separate: an affine without shear can
sample angles on MPS and return them on CPU. Numeric ranges or tensor-valued
constructor ranges can determine the returned device/dtype, so inspecting
``_params`` alone does not establish where or at what precision draws ran.
+- Module migration through ``.to(...)`` also updates the augmentation gate
+ and registered parameter generators' sampling configuration, including
+ moves through a container. A dtype-only move preserves the sampling device;
+ a device-only move preserves its dtype. Invalid integer-dtype requests are
+ rejected before changing the samplers. This does not make every generator
+ support every device/dtype, or force returned parameters onto the sampling
+ device. This limitation affects multiple generators, including numeric-range
+ ``RandomAffine``, ``RandomPerspective``, ``RandomRotation``, ``RandomCrop``,
+ and ``RandomShear`` with scalar, pair, or four-value ranges: returned transform
+ parameters can remain CPU float32 while ``batch_prob`` is on the accelerator
+ (`#4426 <https://github.com/kornia/kornia/issues/4426>`_).
- Reproducibility uses the global generators on the sampling devices.
``torch.manual_seed`` reproduces draws for the same configuration, inputs,
backend and dtype; matching across devices or PyTorch versions is not
diff --git a/kornia/augmentation/_2d/geometric/affine.py b/kornia/augmentation/_2d/geometric/affine.py
index 6748602b0..8fb4b6f14 100644
--- a/kornia/augmentation/_2d/geometric/affine.py
+++ b/kornia/augmentation/_2d/geometric/affine.py
@@ -63,6 +63,21 @@ class RandomAffine(GeometricAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - See :class:`~kornia.augmentation.AugmentationBase2D` for input, sampling, and replay,
+ :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
+ :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
+ Pixel coordinates are ``(x, y)`` with inclusive image corners
+ ``(0, 0)`` and ``(W - 1, H - 1)``; the affine center is ``((W - 1) / 2, (H - 1) / 2)``.
+ - ``degrees``, scale, and shear are sampled independently per selected sample unless ``same_on_batch=True``.
+ ``translate=(a, b)``
+ samples pixel offsets from ``[-a W, a W]`` and ``[-b H, b H]``; positive offsets move content right
+ and down. A positive ``degrees`` value instead rotates the displayed image clockwise, unlike
+ :class:`RandomRotation`; this inherited affine-composer convention is tracked in `#4408
+ <https://github.com/kornia/kornia/issues/4408>`_.
+ - The defaults are bilinear resampling, zero padding, and ``align_corners=False``. The matrix maps input
+ pixel coordinates to output pixel coordinates and is available as :attr:`transform_matrix`.
+
.. note::
This function internally uses :func:`kornia.geometry.transform.warp_affine`.
diff --git a/kornia/augmentation/_2d/geometric/center_crop.py b/kornia/augmentation/_2d/geometric/center_crop.py
index 3062f66be..7a6c234c5 100644
--- a/kornia/augmentation/_2d/geometric/center_crop.py
+++ b/kornia/augmentation/_2d/geometric/center_crop.py
@@ -51,6 +51,22 @@ class CenterCrop(GeometricAugmentationBase2D):
.. note::
This function internally uses :func:`kornia.geometry.transform.crop_by_boxes`.
+ Convention:
+ See :class:`~kornia.augmentation.AugmentationBase2D` for input, dtype, probability, and replay,
+ :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
+ :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
+ ``size`` accepts an integer for a square crop or an
+ ``(height, width)`` tuple. The fixed centre crop is shared by every selected image in a batch.
+
+ When the crop is selected, ``cropping_mode="slice"`` indexes the input directly and returns a writable view
+ of it; modifying the result therefore modifies the corresponding centre region of the input. This wart is
+ tracked in
+ `#4413 <https://github.com/kornia/kornia/issues/4413>`_. ``cropping_mode="resample"`` uses
+ ``crop_by_transform_mat`` with the configured ``resample`` (bilinear by default), ``align_corners`` (``True``
+ by default), and zero padding. Only resample mode supports
+ :meth:`inverse`; it resamples onto the original canvas with zero padding by default and cannot restore discarded
+ data. The inverse call can override ``padding_mode``, for example with ``padding_mode="border"``.
+
Examples:
>>> import torch
>>> rng = torch.manual_seed(0)
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index 13c36f5c5..03574c83b 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -70,9 +70,37 @@ class RandomCrop(GeometricAugmentationBase2D):
Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 3, 3)`), then the
applied transformation will be merged int to the input transformation torch.Tensor and returned.
- ``p`` selects or skips the whole batch; ``same_on_batch`` controls whether selected images share
- the same crop parameters. When the batch is skipped, the returned images, masks, keypoints, and
- boxes remain unchanged, including when ``padding`` or ``pad_if_needed`` is set.
+ Convention:
+ See :class:`~kornia.augmentation.AugmentationBase2D` for input, dtype, probability, and replay,
+ :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
+ :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
+ ``size`` is an ``(height, width)`` tuple; unlike
+ :class:`CenterCrop`, a bare integer raises ``AssertionError`` by default, or ``TypeError`` during padding
+ computation with ``pad_if_needed=True``. The split is tracked in
+ `#4417 <https://github.com/kornia/kornia/issues/4417>`_. Here ``p`` selects or skips the whole batch together.
+ Within a selected batch, each image samples a crop independently unless ``same_on_batch=True``.
+ When skipped, images, masks, keypoints, and boxes remain unchanged, even with padding configured.
+
+ Explicit ``padding`` is applied before sampling, in ``(left, top, right, bottom)`` order after its scalar
+ or two-value shorthand is expanded. ``pad_if_needed=True`` takes the per-side maximum of that padding and
+ the positive crop-minus-input size difference on each axis. Without explicit padding this is symmetric;
+ asymmetric explicit padding can remain asymmetric after the merge.
+
+ With ``pad_if_needed=False``, an oversized request does not raise. Slice mode resizes the available slice
+ to the requested size. Resample mode instead uses a mis-scaled warp that can blend in zero padding; when
+ either axis is oversized, both matrix axes are rescaled, including an axis that would fit. This wart is
+ tracked in `#4414 <https://github.com/kornia/kornia/issues/4414>`_. The same correction compares against the
+ unpadded input even when explicit padding makes the crop fit: slice-mode images then disagree with the
+ matrix-transformed keypoints and boxes, and resample-mode images are also distorted. This explicit-padding
+ defect is tracked in `#4542 <https://github.com/kornia/kornia/issues/4542>`_.
+
+ Slice mode calls ``crop_by_indices`` with that
+ function's bilinear/``align_corners=None`` defaults, ignoring this class's ``resample`` and
+ ``align_corners`` flags. Resample mode uses ``crop_by_transform_mat`` with the configured interpolation and
+ ``align_corners``; it maps constant, replicate, and reflect pre-padding to zero, border, and reflection
+ sampler padding respectively. Only
+ resample mode supports :meth:`inverse`; inverse removes pre-crop padding but cannot restore cropped or
+ interpolated content.
Examples:
>>> import torch
diff --git a/kornia/augmentation/_2d/geometric/elastic_transform.py b/kornia/augmentation/_2d/geometric/elastic_transform.py
index 5610619e6..49d79c339 100644
--- a/kornia/augmentation/_2d/geometric/elastic_transform.py
+++ b/kornia/augmentation/_2d/geometric/elastic_transform.py
@@ -30,6 +30,17 @@ class RandomElasticTransform(AugmentationBase2D):
.. image:: _static/img/RandomElasticTransform.png
+ Convention:
+ See the shared contract on :class:`~kornia.augmentation.AugmentationBase2D`.
+ This is a dense backward sampling field, with no ``transform_matrix`` or ``inverse`` interface.
+ Noise has shape ``(B, 2, H, W)`` with channels ``(x, y)``; ``alpha`` scales displacement in
+ normalized sampling coordinates, whereas ``kernel_size`` and ``sigma`` use ``(y, x)`` order.
+ The default sampler is bilinear with zero padding and ``align_corners=False``. The displaced
+ grid is clamped to ``[-1, 1]`` before sampling. Zero ``alpha`` preserves the image up to
+ interpolation rounding for either ``align_corners`` value.
+ Spatial labels in containers have additional limitations; see
+ `#4420 <https://github.com/kornia/kornia/issues/4420>`_.
+
Args:
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,
@@ -38,7 +49,7 @@ class RandomElasticTransform(AugmentationBase2D):
in the x and y directions, respectively -- the opposite order to ``kernel_size`` and ``sigma``.
align_corners: Interpolation flag used by `grid_sample`.
resample: Interpolation mode used by `grid_sample`. Either 'nearest' (0) or 'bilinear' (1).
- padding_mode: The padding used by ```grid_sample```. Either 'torch.zeros', 'border' or 'refection'.
+ padding_mode: The padding used by ``grid_sample``. Either 'zeros', 'border' or 'reflection'.
same_on_batch: apply the same transformation across the batch.
p: probability of applying the transformation.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
diff --git a/kornia/augmentation/_2d/geometric/fisheye.py b/kornia/augmentation/_2d/geometric/fisheye.py
index e57a14da6..1bf215d52 100644
--- a/kornia/augmentation/_2d/geometric/fisheye.py
+++ b/kornia/augmentation/_2d/geometric/fisheye.py
@@ -30,6 +30,17 @@ class RandomFisheye(AugmentationBase2D):
.. image:: _static/img/RandomFisheye.png
+ Convention:
+ See the shared contract on :class:`~kornia.augmentation.AugmentationBase2D`.
+ Coordinates are normalized to ``[-1, 1]`` with corner pixel centres at the endpoints.
+ At output coordinate ``(x, y)``, let ``r`` be its distance from the sampled centre.
+ The input sampling coordinate is ``(x * (1 + r**gamma), y * (1 + r**gamma))``:
+ the centre changes the distance, but scaling is about the coordinate origin.
+ Sampling is bilinear with zero padding and ``align_corners=True``; these settings are fixed.
+ Output spatial size is unchanged. This non-rigid class has no ``transform_matrix`` or
+ ``inverse`` interface. For spatial labels in containers, see
+ `#4420 <https://github.com/kornia/kornia/issues/4420>`_.
+
Args:
center_x: Ranges to sample respect to x-coordinate center with shape (2,).
center_y: Ranges to sample respect to y-coordinate center with shape (2,).
diff --git a/kornia/augmentation/_2d/geometric/horizontal_flip.py b/kornia/augmentation/_2d/geometric/horizontal_flip.py
index 5fd118ca2..98ea24652 100644
--- a/kornia/augmentation/_2d/geometric/horizontal_flip.py
+++ b/kornia/augmentation/_2d/geometric/horizontal_flip.py
@@ -48,6 +48,14 @@ class RandomHorizontalFlip(GeometricAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - See :class:`~kornia.augmentation.AugmentationBase2D` for input, sampling, and replay,
+ :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
+ :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
+ Coordinates are inclusive pixel centers: a selected flip maps
+ ``(x, y)`` to ``(W - 1 - x, y)`` and applies the exact discrete :func:`~kornia.geometry.transform.hflip`
+ operation, without resampling.
+
.. note::
This function internally uses :func:`kornia.geometry.transform.hflip`.
diff --git a/kornia/augmentation/_2d/geometric/pad.py b/kornia/augmentation/_2d/geometric/pad.py
index 0172e4648..7629a2b33 100644
--- a/kornia/augmentation/_2d/geometric/pad.py
+++ b/kornia/augmentation/_2d/geometric/pad.py
@@ -44,6 +44,22 @@ class PadTo(GeometricAugmentationBase2D):
.. note::
This function internally uses :func:`torch.nn.functional.pad`.
+ Convention:
+ See :class:`~kornia.augmentation.AugmentationBase2D` for input, dtype, probability, and replay,
+ :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
+ :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
+ This operation always runs and applies its padding on the
+ right and bottom, using ``pad_mode`` and ``pad_value``. A target smaller than the input supplies negative
+ padding to :func:`torch.nn.functional.pad`, which crops those axes instead; a target can consequently pad
+ one axis while cropping the other. This wart is tracked in
+ `#4410 <https://github.com/kornia/kornia/issues/4410>`_.
+
+ :meth:`inverse` slices to the prior input size. It exactly removes right/bottom padding, but after a crop it
+ returns the cropped result unchanged rather than restoring discarded pixels. The transformation matrix is
+ identity, leaving coordinates unchanged. Keypoints and boxes are not clipped or removed when cropping
+ puts them outside the output canvas. Canvas extents are carried separately in the input metadata used by
+ :meth:`inverse`.
+
Examples:
>>> import torch
>>> img = torch.tensor([[[[0., 0., 0.],
diff --git a/kornia/augmentation/_2d/geometric/perspective.py b/kornia/augmentation/_2d/geometric/perspective.py
index 5a9ac1f40..18be85b9e 100644
--- a/kornia/augmentation/_2d/geometric/perspective.py
+++ b/kornia/augmentation/_2d/geometric/perspective.py
@@ -47,6 +47,23 @@ class RandomPerspective(GeometricAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - See :class:`~kornia.augmentation.AugmentationBase2D` for input, sampling, and replay,
+ :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
+ :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
+ The source corners are the inclusive pixel coordinates ``(0, 0)``,
+ ``(W - 1, 0)``, ``(W - 1, H - 1)``, and ``(0, H - 1)``; :attr:`transform_matrix` maps those source
+ coordinates to the sampled destination corners.
+ - ``basic`` samples each corner inward by at most ``distortion_scale * (W, H) / 2``. ``area_preserving``
+ samples each coordinate in both directions over the same extent. Defaults are bilinear resampling, zero
+ padding, and ``align_corners=False``. ``same_on_batch=True`` reuses the sampled destination corners for
+ every selected sample.
+
+ - With ``distortion_scale=0`` and ``H > 1``, ``W > 1``, the image warp is identity up to numerical
+ precision for either ``align_corners`` setting. If either spatial dimension is 1, coincident source
+ corners instead produce a NaN transformation matrix and output even at zero distortion. This limitation
+ is recorded in `#4538 <https://github.com/kornia/kornia/pull/4538#pullrequestreview-5209122169>`_.
+
.. note::
This function internally uses :func:`kornia.geometry.transform.warp_pespective`.
diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.py
index 7090038e1..aa725682d 100644
--- a/kornia/augmentation/_2d/geometric/resize.py
+++ b/kornia/augmentation/_2d/geometric/resize.py
@@ -41,6 +41,23 @@ class Resize(GeometricAugmentationBase2D):
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
+ Convention:
+ See :class:`~kornia.augmentation.AugmentationBase2D` for input, dtype, probability, and replay,
+ :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
+ :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
+ A tuple ``size`` is the exact ``(height, width)`` output.
+ With an integer, ``side`` selects which input side is set to that value while preserving aspect ratio:
+ ``"short"`` (the default) selects the shortest side, ``"long"`` the longest, ``"vert"`` the height, and
+ ``"horz"`` the width. The derived side is truncated toward zero; if it becomes zero, the resize raises
+ ``AssertionError`` (for example, ``Resize(4, side="long")`` or ``LongestMaxSize(4)`` on a 1-by-10 image).
+ This class uses
+ :func:`kornia.geometry.transform.resize`; ``align_corners`` is forwarded for bilinear and bicubic sampling,
+ and ``antialias`` affects downscaling only. The operation has a fixed, whole-batch resize whenever it is
+ selected.
+
+ :meth:`inverse` resamples to the prior canvas with zero padding through ``crop_by_transform_mat``. It
+ restores the shape but cannot recover values discarded by a resize.
+
"""
def __init__(
@@ -137,6 +154,12 @@ class LongestMaxSize(Resize):
Args:
max_size: maximum size of the image after the transformation.
+ Convention:
+ See :class:`Resize` for the common resize conventions. This behaves like
+ ``Resize(max_size, side="long", antialias=False, keepdim=False)``; ``antialias`` and ``keepdim``
+ are not accepted constructor arguments. Its longest output side equals ``max_size`` and the other
+ side is truncated while preserving aspect ratio.
+
"""
def __init__(
@@ -156,6 +179,12 @@ class SmallestMaxSize(Resize):
Args:
max_size: maximum size of the image after the transformation.
+ Convention:
+ See :class:`Resize` for the common resize conventions. This behaves like
+ ``Resize(max_size, side="short", antialias=False, keepdim=False)``; ``antialias`` and ``keepdim``
+ are not accepted constructor arguments. Its shortest output side equals ``max_size`` and the other
+ side is truncated while preserving aspect ratio.
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.py
index 8557df054..11f254565 100644
--- a/kornia/augmentation/_2d/geometric/resized_crop.py
+++ b/kornia/augmentation/_2d/geometric/resized_crop.py
@@ -56,6 +56,26 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 3, 3)`), then the
applied transformation will be merged int to the input transformation torch.Tensor and returned.
+ Convention:
+ See :class:`~kornia.augmentation.AugmentationBase2D` for input, dtype, probability, and replay,
+ :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
+ :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
+ ``size`` is an ``(height, width)`` tuple. A bare integer
+ is rejected, unlike :class:`CenterCrop`; the sibling split is tracked in
+ `#4417 <https://github.com/kornia/kornia/issues/4417>`_. Here ``p`` selects or skips the whole batch together.
+ Within a selected batch, the generator tries ten candidate crops per image, sampling area fractions from
+ ``scale`` and width/height ratios from ``ratio`` (shared with ``same_on_batch=True``). Rounded candidate
+ dimensions must be positive and strictly smaller than the input on both axes. If no candidate fits,
+ a fallback chooses dimensions by comparing input height/width with ``min(ratio)``, then clamps them to
+ the input size. This fallback can violate both requested ranges: on an 8x6 input, ``scale=(1.0, 1.0)``
+ with the default ratio produces a 4x6 crop, with half the input area and width/height ratio 1.5.
+ The selected crop is resized to the requested output size.
+
+ Slice mode calls index cropping with the configured interpolation and ``align_corners``; resample mode
+ calls ``crop_by_transform_mat`` with zero padding. Both default to bilinear sampling and
+ ``align_corners=True``. Only resample mode supports :meth:`inverse`; its inverse
+ resamples onto the original canvas and cannot recover information discarded by cropping or interpolation.
+
Example:
>>> rng = torch.manual_seed(0)
>>> inputs = torch.tensor([[[0., 1., 2.],
diff --git a/kornia/augmentation/_2d/geometric/rotation.py b/kornia/augmentation/_2d/geometric/rotation.py
index c8bd7013b..40b0562a7 100644
--- a/kornia/augmentation/_2d/geometric/rotation.py
+++ b/kornia/augmentation/_2d/geometric/rotation.py
@@ -46,6 +46,16 @@ class RandomRotation(GeometricAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - See :class:`~kornia.augmentation.AugmentationBase2D` for input, sampling, and replay,
+ :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
+ :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
+ Coordinates are inclusive pixel centers, and rotation is about
+ ``((W - 1) / 2, (H - 1) / 2)``.
+ - A positive sampled angle rotates the displayed image counter-clockwise. The default is bilinear
+ resampling with zero padding and ``align_corners=True``; this default differs from several 2D geometric
+ augmentations and is tracked in `#4412 <https://github.com/kornia/kornia/issues/4412>`_.
+
.. note::
This function internally uses :func:`kornia.geometry.transform.affine`.
@@ -153,6 +163,17 @@ class RandomRotation90(GeometricAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - See :class:`~kornia.augmentation.AugmentationBase2D` for input, sampling, and replay,
+ :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
+ :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
+ Coordinates are inclusive pixel centers and positive rounded ``times`` values rotate the displayed image
+ counter-clockwise by ``times * 90`` degrees.
+ - ``times`` is sampled from the supplied uniform range and rounded before multiplication by 90. The output
+ retains the input ``(H, W)`` shape, including for non-square images; both behaviors are tracked in
+ `#4409 <https://github.com/kornia/kornia/issues/4409>`_. Its defaults match :class:`RandomRotation`:
+ bilinear resampling, zero padding, and ``align_corners=True``.
+
.. note::
This function internally uses :func:`kornia.geometry.transform.affine`. This version is relatively
slow as it operates based on affine transformations.
diff --git a/kornia/augmentation/_2d/geometric/shear.py b/kornia/augmentation/_2d/geometric/shear.py
index 65dc4ec09..49ac981e4 100644
--- a/kornia/augmentation/_2d/geometric/shear.py
+++ b/kornia/augmentation/_2d/geometric/shear.py
@@ -50,6 +50,16 @@ class RandomShear(GeometricAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - See :class:`~kornia.augmentation.AugmentationBase2D` for input, sampling, and replay,
+ :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
+ :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
+ Pixel coordinates are inclusive, and the shear is centered at
+ ``((W - 1) / 2, (H - 1) / 2)``. Positive ``shear_x`` and ``shear_y`` use the same signs as
+ :class:`RandomAffine`'s shear parameters.
+ - ``shear`` supplies one or two degree ranges for the x and y shears; a scalar or pair supplies only x
+ shear. Defaults are bilinear resampling, zero padding, and ``align_corners=False``.
+
.. note::
This function internally uses :func:`kornia.geometry.transform.warp_affine`.
diff --git a/kornia/augmentation/_2d/geometric/thin_plate_spline.py b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
index dd9fb7d6b..b8766dea0 100644
--- a/kornia/augmentation/_2d/geometric/thin_plate_spline.py
+++ b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
@@ -31,11 +31,30 @@ class RandomThinPlateSpline(AugmentationBase2D):
.. image:: _static/img/RandomThinPlateSpline.png
+ Convention:
+ See the shared contract on :class:`~kornia.augmentation.AugmentationBase2D`.
+ Five control points use normalized ``(x, y)`` coordinates: ``(-1, -1)``, ``(-1, 1)``,
+ ``(1, -1)``, ``(1, 1)``, and ``(0, 0)``. Each destination coordinate receives uniform
+ noise between ``-scale`` and ``scale``; zero scale leaves these points unchanged.
+ Sampling is bilinear with zero padding and ``align_corners=False`` by default; no
+ interpolation-mode argument is exposed. Output spatial size is unchanged, and there is
+ no ``transform_matrix`` or ``inverse`` interface. Spatial labels in containers have
+ additional limitations; see `#4420 <https://github.com/kornia/kornia/issues/4420>`_.
+
+ With zero scale, the image warp is identity up to numerical precision for either ``align_corners``
+ setting with float32, float64, and bfloat16 inputs.
+
+ .. warning::
+ Float16 has a kernel-epsilon underflow that produces non-finite weights and NaN output for either
+ ``align_corners`` setting; this is tracked in `#4557 <https://github.com/kornia/kornia/issues/4557>`_.
+ The solve has additional dtype limitations documented on
+ :func:`~kornia.geometry.transform.get_tps_transform`.
+
Args:
scale: the non-negative scale factor to apply to the destination points.
Zero leaves the control points unchanged.
align_corners: Interpolation flag used by ``grid_sample``.
- mode: Interpolation mode used by `grid_sample`. Either 'bilinear' or 'nearest'.
+ padding_mode: Padding used by ``grid_sample``: 'zeros', 'border' or 'reflection'.
same_on_batch: apply the same transformation across the batch.
p: probability of applying the transformation.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
diff --git a/kornia/augmentation/_2d/geometric/translate.py b/kornia/augmentation/_2d/geometric/translate.py
index c3f7ff8fd..95738c04c 100644
--- a/kornia/augmentation/_2d/geometric/translate.py
+++ b/kornia/augmentation/_2d/geometric/translate.py
@@ -46,6 +46,16 @@ class RandomTranslate(GeometricAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - See :class:`~kornia.augmentation.AugmentationBase2D` for input, sampling, and replay,
+ :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
+ :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
+ Coordinates are inclusive pixel centers. ``translate_x`` and
+ ``translate_y`` are independently sampled fractions and multiplied by ``W`` and ``H`` respectively;
+ positive values move content right and down. Omitting either range fixes that axis at zero.
+ - The defaults are bilinear resampling, zero padding, and ``align_corners=False``. The matrix maps input
+ pixel coordinates to output pixel coordinates.
+
.. note::
This function internally uses :func:`kornia.geometry.transform.warp_affine`.
diff --git a/kornia/augmentation/_2d/geometric/vertical_flip.py b/kornia/augmentation/_2d/geometric/vertical_flip.py
index 43d38c3c5..3c6405413 100644
--- a/kornia/augmentation/_2d/geometric/vertical_flip.py
+++ b/kornia/augmentation/_2d/geometric/vertical_flip.py
@@ -39,6 +39,14 @@ class RandomVerticalFlip(GeometricAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - See :class:`~kornia.augmentation.AugmentationBase2D` for input, sampling, and replay,
+ :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
+ :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
+ Coordinates are inclusive pixel centers: a selected flip maps
+ ``(x, y)`` to ``(x, H - 1 - y)`` and applies the exact discrete :func:`~kornia.geometry.transform.vflip`
+ operation, without resampling.
+
.. note::
This function internally uses :func:`kornia.geometry.transform.vflip`.
diff --git a/tests/augmentation/test_conventions_geometric_crop.py b/tests/augmentation/test_conventions_geometric_crop.py
new file mode 100644
index 000000000..35cfae34c
--- /dev/null
+++ b/tests/augmentation/test_conventions_geometric_crop.py
@@ -0,0 +1,256 @@
+# 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.
+#
+
+from __future__ import annotations
+
+import pytest
+import torch
+
+import kornia.augmentation as K
+
+from testing.base import BaseTester, supports_2d_border_padding
+
+
+class TestGeometricCropConventions(BaseTester):
+ """Batch-6 convention pins for crop, resize, and pad augmentations."""
+
+ def test_convention_center_crop_size_mode_and_inverse(self, device, dtype):
+ x = torch.arange(48, device=device, dtype=dtype).reshape(1, 1, 6, 8)
+ expected = x[..., 1:5, 2:6]
+
+ slice_crop = K.CenterCrop(4, cropping_mode="slice")
+ self.assert_close(slice_crop(x), expected)
+ with pytest.raises(NotImplementedError, match="only applicable for resample"):
+ slice_crop.inverse(expected)
+
+ resample_crop = K.CenterCrop((4, 4), cropping_mode="resample")
+ resample_output = resample_crop(x)
+ assert resample_output.shape == expected.shape
+ assert resample_crop.inverse(resample_output).shape == x.shape
+
+ nearest = K.CenterCrop((4, 4), resample="nearest", align_corners=False, cropping_mode="resample")
+ self.assert_close(nearest(x), expected)
+
+ def test_wart_center_crop_slice_aliases_input_4413(self, device, dtype):
+ # #4413: default slice mode returns its direct tensor slice. The write lands at the crop's centre offset.
+ x = torch.arange(48, device=device, dtype=dtype).reshape(1, 1, 6, 8)
+ output = K.CenterCrop(4, cropping_mode="slice")(x)
+ assert output.untyped_storage().data_ptr() == x.untyped_storage().data_ptr()
+ output[0, 0, 0, 0] = -99
+ assert x[0, 0, 1, 2] == -99
+
+ def test_convention_random_crop_padding_modes_and_inverse(self, device, dtype):
+ x = torch.arange(9, device=device, dtype=dtype).reshape(1, 1, 3, 3)
+ crop = K.RandomCrop((3, 3), padding=(1, 2, 3, 4), fill=9, p=1.0, cropping_mode="slice")
+ assert crop.compute_padding((1, 1, 3, 3)) == [1, 3, 2, 4]
+ torch.manual_seed(0)
+ padded = crop(x)
+ assert padded.shape == x.shape
+ assert (padded == 9).any()
+
+ needed = K.RandomCrop((4, 5), pad_if_needed=True, fill=9, p=1.0)
+ assert needed.compute_padding((1, 1, 2, 3)) == [2, 2, 2, 2]
+ prepared = needed.precrop_padding(torch.ones(1, 1, 2, 3, device=device, dtype=dtype))
+ assert prepared.shape == (1, 1, 6, 7)
+ assert (prepared[..., 0, :] == 9).all()
+
+ resample = K.RandomCrop((3, 3), p=1.0, cropping_mode="resample")
+ output = resample(x)
+ assert resample.inverse(output).shape == x.shape
+ slice_crop = K.RandomCrop((3, 3), p=1.0, cropping_mode="slice")
+ slice_output = slice_crop(x)
+ with pytest.raises(NotImplementedError, match="only applicable for resample"):
+ slice_crop.inverse(slice_output)
+
+ image = torch.arange(48, device=device, dtype=dtype).reshape(1, 1, 6, 8)
+ nearest = K.RandomCrop((3, 3), resample="nearest", align_corners=False, p=1.0, cropping_mode="resample")
+ params = nearest.forward_parameters(image.shape)
+ params["src"] = image.new_tensor([[[2, 1], [4, 1], [4, 3], [2, 3]]])
+ self.assert_close(nearest(image, params=params), image[..., 1:4, 2:5])
+
+ @pytest.mark.device_agnostic
+ def test_convention_random_crop_merges_needed_padding_per_side(self):
+ crop = K.RandomCrop((4, 5), padding=(5, 0, 1, 4), pad_if_needed=True)
+ assert crop.compute_padding((1, 1, 2, 3)) == [5, 2, 2, 4]
+
+ @pytest.mark.parametrize(
+ "padding_mode, expected",
+ [
+ ("constant", [[0, 0, 0], [0, 0, 1], [0, 3, 4]]),
+ ("replicate", [[0, 0, 1], [0, 0, 1], [3, 3, 4]]),
+ ("reflect", [[4, 3, 4], [1, 0, 1], [4, 3, 4]]),
+ ],
+ )
+ def test_convention_random_crop_sampler_padding(self, device, dtype, padding_mode, expected):
+ if padding_mode == "replicate" and not supports_2d_border_padding(device):
+ pytest.skip("2D border padding is unavailable on this backend")
+ image = torch.arange(9, device=device, dtype=dtype).reshape(1, 1, 3, 3)
+ crop = K.RandomCrop((3, 3), cropping_mode="resample", padding_mode=padding_mode, align_corners=True, p=1.0)
+ params = crop.forward_parameters(image.shape)
+ # Force sampling beyond the top/left edges, where zeros, border and reflection differ.
+ params["src"] = image.new_tensor([[[-1, -1], [1, -1], [1, 1], [-1, 1]]])
+ self.assert_close(crop(image, params=params), image.new_tensor(expected).reshape_as(image))
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("kind", ["crop", "resized_crop"])
+ def test_convention_random_crops_gate_the_whole_batch(self, kind):
+ crop = K.RandomCrop((3, 4), p=0.5) if kind == "crop" else K.RandomResizedCrop((3, 4), p=0.5)
+ torch.manual_seed(0)
+ gates = [crop.forward_parameters((16, 1, 6, 8))["batch_prob"] for _ in range(16)]
+ assert all(torch.equal(gate, gate[:1].expand_as(gate)) for gate in gates)
+ assert any(gate.all() for gate in gates)
+ assert any(not gate.any() for gate in gates)
+
+ @pytest.mark.parametrize("mode", ["slice", "resample"])
+ def test_wart_random_crop_explicit_padding_scales_matrix_4542(self, device, dtype, mode):
+ image = torch.arange(9, device=device, dtype=dtype).reshape(1, 1, 3, 3) / 8
+ crop = K.RandomCrop((4, 4), padding=1, cropping_mode=mode, p=1.0)
+ seq = K.AugmentationSequential(crop, data_keys=["input", "keypoints", "bbox"])
+ params = seq.forward_parameters(image.shape)
+ params[0].data["src"] = image.new_tensor([[[0, 0], [3, 0], [3, 3], [0, 3]]])
+ points = image.new_tensor([[[2, 2]]])
+ boxes = image.new_tensor([[[[1, 1], [2, 1], [2, 2], [1, 2]]]])
+ output, out_points, out_boxes = seq(image, points, boxes, params=params)
+ self.assert_close(crop.transform_matrix, image.new_tensor([[[4 / 3, 0, 0], [0, 4 / 3, 0], [0, 0, 1]]]))
+ self.assert_close(out_points, image.new_tensor([[[4, 4]]]))
+ self.assert_close(out_boxes, (boxes + 1) * (4 / 3))
+ # Slice mode puts the original (2, 2) pixel at (3, 3); resampling also distorts its value.
+ expected = (
+ [[0, 0, 0, 0], [0, 0, 1, 2], [0, 3, 4, 5], [0, 6, 7, 8]]
+ if mode == "slice"
+ else [[0, 0, 0, 0], [0, 0, 0.375, 0.9375], [0, 1.125, 2, 2.75], [0, 2.8125, 4.25, 5]]
+ )
+ self.assert_close(output, image.new_tensor(expected).reshape(1, 1, 4, 4) / 8)
+
+ @pytest.mark.parametrize("mode", ["slice", "resample"])
+ @pytest.mark.parametrize("size", [(10, 10), (10, 4), (4, 10)])
+ def test_wart_random_crop_oversized_rescales_both_matrix_axes_4414(self, device, dtype, mode, size):
+ image = torch.arange(48, device=device, dtype=dtype).reshape(1, 1, 6, 8) / 48
+ crop = K.RandomCrop(size, cropping_mode=mode, p=1.0)
+ params = crop.forward_parameters(image.shape)
+ h, w = size
+ left, top = (2, 0) if size == (10, 4) else ((0, 1) if size == (4, 10) else (0, 0))
+ params["src"] = image.new_tensor(
+ [[[left, top], [left + w - 1, top], [left + w - 1, top + h - 1], [left, top + h - 1]]]
+ )
+ output = crop(image, params=params)
+ self.assert_close(crop.transform_matrix, image.new_tensor([[[w / 8, 0, -left], [0, h / 6, -top], [0, 0, 1]]]))
+ # Explicit ramp rows distinguish the slice resize from the mis-scaled, zero-padded warp.
+ rows = {
+ ((10, 10), "slice"): [40, 40.7, 41.5, 42.3, 43.1, 43.9, 44.7, 45.5, 46.3, 47],
+ ((10, 10), "resample"): [24, 24.48, 24.96, 25.44, 25.92, 26.4, 26.88, 27.36, 27.84, 22.56],
+ ((10, 4), "slice"): [2, 3, 4, 5],
+ ((10, 4), "resample"): [4, 6, 0, 0],
+ ((4, 10), "slice"): [8, 8.7, 9.5, 10.3, 11.1, 11.9, 12.7, 13.5, 14.3, 15],
+ ((4, 10), "resample"): [12, 12.8, 13.6, 14.4, 15.2, 16, 16.8, 17.6, 18.4, 15.2],
+ }
+ row = -1 if size == (10, 10) else 0
+ self.assert_close(output[0, 0, row], image.new_tensor(rows[size, mode]) / 48, low_tolerance=True)
+
+ def test_convention_random_resized_crop_size_modes_and_inverse(self, device, dtype):
+ x = torch.arange(48, device=device, dtype=dtype).reshape(1, 1, 6, 8)
+ kwargs = {"size": (3, 4), "scale": (1.0, 1.0), "ratio": (0.75, 0.75), "p": 1.0}
+ for mode in ("slice", "resample"):
+ crop = K.RandomResizedCrop(cropping_mode=mode, **kwargs)
+ output = crop(x)
+ assert output.shape == (1, 1, 3, 4)
+ if mode == "resample":
+ assert crop.inverse(output).shape == x.shape
+ else:
+ with pytest.raises(NotImplementedError, match="only applicable for resample"):
+ crop.inverse(output)
+
+ nearest = K.RandomResizedCrop(
+ size=(6, 8),
+ scale=(1.0, 1.0),
+ ratio=(0.75, 0.75),
+ resample="nearest",
+ align_corners=True,
+ cropping_mode="resample",
+ p=1.0,
+ )
+ params = nearest.forward_parameters(x.shape)
+ params["src"] = torch.tensor([[[0, 0], [7, 0], [7, 5], [0, 5]]], device=device, dtype=dtype)
+ params["dst"] = torch.tensor([[[0, 0], [7, 0], [7, 5], [0, 5]]], device=device, dtype=dtype)
+ self.assert_close(nearest(x, params=params), x)
+
+ @pytest.mark.device_agnostic
+ def test_convention_random_resized_crop_fallback_can_escape_scale_and_ratio(self):
+ params = K.RandomResizedCrop((4, 4), scale=(1.0, 1.0), p=1.0).forward_parameters((1, 1, 8, 6))
+
+ src = params["src"]
+ crop_height = (src[0, 2, 1] - src[0, 1, 1]).item() + 1
+ crop_width = (src[0, 1, 0] - src[0, 0, 0]).item() + 1
+ assert (crop_height, crop_width) == (4, 6)
+ assert crop_height * crop_width / (8 * 6) != 1.0
+ assert crop_width / crop_height > 4 / 3
+
+ @pytest.mark.device_agnostic
+ def test_wart_crop_siblings_disagree_on_integer_size_4417(self):
+ # #4417: CenterCrop accepts an int while its random siblings reject it through implementation details.
+ assert K.CenterCrop(4).size == (4, 4)
+ with pytest.raises(AssertionError):
+ K.RandomCrop(4)(torch.ones(1, 1, 6, 8)) # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="not subscriptable"):
+ K.RandomCrop(4, pad_if_needed=True)(torch.ones(1, 1, 6, 8)) # type: ignore[arg-type]
+ with pytest.raises(TypeError):
+ K.RandomResizedCrop(4) # type: ignore[arg-type]
+
+ def test_convention_resize_side_policies_and_inverse(self, device, dtype):
+ x = torch.arange(70, device=device, dtype=dtype).reshape(1, 1, 7, 10)
+ exact = K.Resize((3, 5), p=1.0)
+ assert exact(x).shape == (1, 1, 3, 5)
+ assert exact.inverse(exact(x)).shape == x.shape
+ assert K.Resize(4, side="short", p=1.0)(x).shape == (1, 1, 4, 5)
+ assert K.Resize(4, side="long", p=1.0)(x).shape == (1, 1, 2, 4)
+ assert K.Resize(4, side="vert", p=1.0)(x).shape == (1, 1, 4, 5)
+ assert K.Resize(4, side="horz", p=1.0)(x).shape == (1, 1, 2, 4)
+ portrait = x.transpose(-1, -2)
+ assert K.Resize(4, side="vert", p=1.0)(portrait).shape == (1, 1, 4, 2)
+ assert K.Resize(4, side="horz", p=1.0)(portrait).shape == (1, 1, 5, 4)
+ assert K.LongestMaxSize(4)(x).shape == (1, 1, 2, 4)
+ assert K.SmallestMaxSize(4)(x).shape == (1, 1, 4, 5)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("kind", ["resize", "longest"])
+ def test_convention_resize_rejects_a_truncated_zero_dimension(self, kind):
+ aug = K.Resize(4, side="long") if kind == "resize" else K.LongestMaxSize(4)
+ with pytest.raises(AssertionError, match="2 positive integers"):
+ aug(torch.ones(1, 1, 1, 10))
+
+ def test_wart_pad_to_smaller_target_crops_and_inverse_is_noop_4410(self, device, dtype):
+ # #4410: negative right/bottom padding crops, and the identity matrix leaves inverse unable to restore it.
+ x = torch.arange(48, device=device, dtype=dtype).reshape(1, 1, 6, 8)
+ crop = K.PadTo((4, 5), pad_value=9)
+ seq = K.AugmentationSequential(crop, data_keys=["input", "keypoints", "bbox"])
+ points = x.new_tensor([[[7, 5]]])
+ boxes = x.new_tensor([[[[6, 4], [7, 4], [7, 5], [6, 5]]]])
+ output, out_points, out_boxes = seq(x, points, boxes)
+ self.assert_close(out_points, points)
+ self.assert_close(out_boxes, boxes)
+ self.assert_close(output, x[..., :4, :5])
+ self.assert_close(crop.inverse(output), output)
+ self.assert_close(crop.transform_matrix, torch.eye(3, device=device, dtype=dtype)[None])
+
+ def test_convention_pad_to_right_bottom_padding_round_trips(self, device, dtype):
+ x = torch.arange(48, device=device, dtype=dtype).reshape(1, 1, 6, 8)
+ pad = K.PadTo((10, 12), pad_value=9)
+ output = pad(x)
+ assert output.shape == (1, 1, 10, 12)
+ self.assert_close(output[..., :6, :8], x)
+ self.assert_close(output[..., 6:, :], torch.full((1, 1, 4, 12), 9, device=device, dtype=dtype))
+ self.assert_close(pad.inverse(output), x)
diff --git a/tests/augmentation/test_conventions_geometric_dense.py b/tests/augmentation/test_conventions_geometric_dense.py
new file mode 100644
index 000000000..c4a5b42cc
--- /dev/null
+++ b/tests/augmentation/test_conventions_geometric_dense.py
@@ -0,0 +1,130 @@
+# 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.
+#
+
+from __future__ import annotations
+
+import math
+
+import pytest
+import torch
+
+import kornia.augmentation as K
+from kornia.constants import Resample, SamplePadding
+
+from testing.base import BaseTester, supports_bilinear_2d_grid_sample
+
+
+class TestDenseGeometricConventions(BaseTester):
+ @pytest.fixture(autouse=True)
+ def require_sampler(self, device, dtype):
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("2D bilinear grid sampling is unavailable for this device/dtype")
+
+ @staticmethod
+ def require_tps(dtype):
+ if dtype == torch.float16:
+ pytest.skip("#4557: the TPS kernel epsilon underflows in float16, producing non-finite weights")
+
+ @pytest.mark.parametrize("align_corners", [False, True])
+ def test_convention_elastic_zero_displacement(self, device, dtype, align_corners):
+ image = torch.arange(35, device=device, dtype=dtype).reshape(1, 1, 5, 7) / 35
+ aug = K.RandomElasticTransform(kernel_size=(3, 5), alpha=(0.0, 0.0), align_corners=align_corners, p=1)
+ self.assert_close(aug(image), image)
+ assert aug.flags["resample"] == Resample.BILINEAR
+ assert aug.flags["padding_mode"] == "zeros"
+ assert K.RandomElasticTransform().flags["align_corners"] is False
+
+ @pytest.mark.parametrize("axis", [0, 1])
+ def test_convention_elastic_normalized_xy_displacement_and_clamp(self, device, dtype, axis):
+ image = torch.arange(35, device=device, dtype=dtype).reshape(1, 1, 5, 7)
+ # With corner alignment, one input pixel is 2/(size - 1) normalized units.
+ alpha = (2 / 6, 0.0) if axis == 0 else (0.0, 2 / 4)
+ aug = K.RandomElasticTransform(kernel_size=(1, 1), alpha=alpha, align_corners=True, p=1)
+ params = aug.forward_parameters(image.shape)
+ assert params["noise"].shape == (1, 2, 5, 7)
+ params["noise"] = torch.ones(1, 2, 5, 7, device=device, dtype=dtype)
+ expected = image[..., [1, 2, 3, 4, 5, 6, 6]] if axis == 0 else image[..., [1, 2, 3, 4, 4], :]
+ self.assert_close(aug(image, params=params), expected)
+
+ @pytest.mark.parametrize("kernel_size", [(3, 1), (1, 3)])
+ def test_convention_elastic_kernel_and_sigma_yx(self, device, dtype, kernel_size):
+ image = torch.arange(5, device=device, dtype=dtype).repeat(5, 1).reshape(1, 1, 5, 5)
+ # sigma_y gives weights (1/4, 1/2, 1/4); sigma_x gives (1/6, 2/3, 1/6).
+ sigma = (math.sqrt(1 / (2 * math.log(2))), math.sqrt(1 / (2 * math.log(4))))
+ aug = K.RandomElasticTransform(kernel_size=kernel_size, sigma=sigma, alpha=(0.5, 0), align_corners=True, p=1)
+ params = aug.forward_parameters(image.shape)
+ params["noise"] = torch.zeros(1, 2, 5, 5, device=device, dtype=dtype)
+ params["noise"][0, 0, 2, 2] = 1
+ expected = image.clone()
+ if kernel_size == (3, 1):
+ expected[0, 0, 1:4, 2] += image.new_tensor([0.25, 0.5, 0.25])
+ else:
+ expected[0, 0, 2, 1:4] += image.new_tensor([1 / 6, 2 / 3, 1 / 6])
+ self.assert_close(aug(image, params=params), expected)
+
+ def test_convention_fisheye_normalized_radial_sampling(self, device, dtype):
+ image = torch.arange(25, device=device, dtype=dtype).reshape(1, 1, 5, 5)
+ aug = K.RandomFisheye(torch.tensor([0.5, 0.5]), torch.tensor([0.0, 0.0]), torch.tensor([2.0, 2.0]), p=1)
+ # q=(x,y)*(1+(x-.5)^2+y^2), mapped to pixel coordinates by 2*(q+1).
+ # Bilinear interpolation with zero outside [0,4] gives this literal;
+ # e.g. output (row=3,col=2) reads row=3.5,col=2, averaging 17 and 22.
+ expected = image.new_tensor(
+ [[0, 0, 0, 0, 0], [0, 0, 4.5, 7, 0], [0, 10, 12, 13, 7], [0, 11.25, 19.5, 19.5, 0], [0, 0, 0, 0, 0]]
+ ).reshape_as(image)
+ self.assert_close(aug(image), expected)
+
+ @pytest.mark.device_agnostic
+ def test_convention_tps_control_points_and_noise_sample_on_cpu(self):
+ aug = K.RandomThinPlateSpline(scale=0.2, same_on_batch=True, p=1)
+ params = aug.forward_parameters((2, 1, 5, 7))
+ expected = torch.tensor([[-1, -1], [-1, 1], [1, -1], [1, 1], [0, 0]], dtype=torch.float32)
+ assert params["src"].device.type == "cpu"
+ assert params["src"].dtype == torch.float32
+ assert params["dst"].device.type == "cpu"
+ assert params["dst"].dtype == torch.float32
+ self.assert_close(params["src"], expected.expand(2, 5, 2))
+ assert ((params["dst"] - params["src"]).abs() <= 0.201).all()
+ self.assert_close(params["dst"][0], params["dst"][1], atol=0, rtol=0)
+ zero = K.RandomThinPlateSpline(scale=0, p=1).forward_parameters((2, 1, 5, 7))
+ assert zero["src"].device.type == "cpu"
+ assert zero["src"].dtype == torch.float32
+ self.assert_close(zero["src"], zero["dst"], atol=0, rtol=0)
+ assert aug.flags["padding_mode"] == SamplePadding.ZEROS
+ assert aug.flags["align_corners"] is False
+
+ @pytest.mark.parametrize("align_corners", [False, True])
+ def test_convention_thin_plate_spline_identity_grid_3928(self, device, dtype, align_corners):
+ self.require_tps(dtype)
+ image = torch.ones(1, 1, 3, 3, device=device, dtype=dtype)
+ aug = K.RandomThinPlateSpline(scale=0, align_corners=align_corners, p=1)
+ self.assert_close(aug(image), image)
+
+ @pytest.mark.parametrize("kind", ["elastic", "fisheye", "tps"])
+ def test_convention_dense_shape_and_matrix_interface(self, device, dtype, kind):
+ if kind == "tps":
+ self.require_tps(dtype)
+ aug = {
+ "elastic": lambda: K.RandomElasticTransform(kernel_size=(3, 3), p=1),
+ "fisheye": lambda: K.RandomFisheye(
+ torch.tensor([0.0, 0.0]), torch.tensor([0.0, 0.0]), torch.tensor([1.0, 1.0]), p=1
+ ),
+ "tps": lambda: K.RandomThinPlateSpline(scale=0, p=1),
+ }[kind]()
+ image = torch.ones(2, 1, 5, 7, device=device, dtype=dtype)
+ assert aug(image).shape == image.shape
+ assert not hasattr(aug, "transform_matrix")
+ assert not hasattr(aug, "inverse")
diff --git a/tests/augmentation/test_conventions_geometric_matrix.py b/tests/augmentation/test_conventions_geometric_matrix.py
new file mode 100644
index 000000000..0efe35a9d
--- /dev/null
+++ b/tests/augmentation/test_conventions_geometric_matrix.py
@@ -0,0 +1,224 @@
+# 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.
+#
+
+from __future__ import annotations
+
+import pytest
+import torch
+
+import kornia.augmentation as K
+from kornia.constants import Resample, SamplePadding
+
+from testing.base import BaseTester
+
+
+class TestConventionGeometricMatrices(BaseTester):
+ @pytest.mark.device_agnostic
+ def test_convention_flips_use_inclusive_pixel_coordinates(self):
+ x = torch.zeros(1, 1, 5, 7)
+ x[..., 1, 2] = 1
+ horizontal = K.RandomHorizontalFlip(p=1.0)(x)
+ vertical = K.RandomVerticalFlip(p=1.0)(x)
+
+ assert horizontal[0, 0].argmax().item() == 1 * 7 + 4
+ assert vertical[0, 0].argmax().item() == 3 * 7 + 2
+
+ def test_convention_flips_expose_their_discrete_coordinate_matrices(self, device, dtype):
+ x = torch.zeros(1, 1, 5, 7, device=device, dtype=dtype)
+ horizontal = K.RandomHorizontalFlip(p=1.0)
+ vertical = K.RandomVerticalFlip(p=1.0)
+ horizontal(x)
+ vertical(x)
+
+ self.assert_close(
+ horizontal.transform_matrix,
+ torch.tensor([[[-1.0, 0.0, 6.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype),
+ )
+ self.assert_close(
+ vertical.transform_matrix,
+ torch.tensor([[[1.0, 0.0, 0.0], [0.0, -1.0, 4.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype),
+ )
+
+ @pytest.mark.device_agnostic
+ def test_convention_affine_translate_and_shear_sample_pixel_parameters(self):
+ shape = (128, 1, 5, 7)
+ torch.manual_seed(0)
+ affine = K.RandomAffine(
+ degrees=(0.0, 0.0), translate=(0.2, 0.3), scale=(2.0, 2.0), shear=(10.0, 10.0, 20.0, 20.0), p=1.0
+ ).forward_parameters(shape)
+ shear = K.RandomShear((10.0, 10.0, 20.0, 20.0), p=1.0).forward_parameters(shape)
+ translate = K.RandomTranslate((0.2, 0.2), (-0.3, -0.3), p=1.0).forward_parameters(shape)
+
+ for params in (affine, shear):
+ self.assert_close(params["center"], params["center"].new_tensor([3.0, 2.0]).expand(128, 2))
+ self.assert_close(params["shear_x"], params["shear_x"].new_full((128,), 10.0))
+ self.assert_close(params["shear_y"], params["shear_y"].new_full((128,), 20.0))
+ self.assert_close(affine["scale"], affine["scale"].new_full((128, 2), 2.0))
+ offsets = affine["translations"]
+ extent = offsets.new_tensor([0.2 * 7, 0.3 * 5])
+ assert (offsets.abs() <= extent).all()
+ # Both ends must be approached: swapping W/H must fail even if all samples fit one bound.
+ assert (offsets.amin(dim=0) < -0.9 * extent).all()
+ assert (offsets.amax(dim=0) > 0.9 * extent).all()
+ self.assert_close(translate["translate_x"], translate["translate_x"].new_full((128,), 1.4))
+ self.assert_close(translate["translate_y"], translate["translate_y"].new_full((128,), -1.5))
+
+ @pytest.mark.parametrize("kind", ["affine", "translate"])
+ def test_convention_positive_translation_moves_content_right_and_down(self, device, dtype, kind):
+ # Corner-aligned 5x9 grids have exactly representable steps even in half precision.
+ image = torch.zeros(1, 1, 5, 9, device=device, dtype=dtype)
+ image[..., 1, 2] = 1
+ if kind == "affine":
+ aug = K.RandomAffine(0.0, translate=(0.2, 0.3), align_corners=True, p=1.0)
+ params = aug.forward_parameters(image.shape)
+ params["translations"] = image.new_tensor([[1.0, 2.0]])
+ else:
+ aug = K.RandomTranslate((1 / 9, 1 / 9), (2 / 5, 2 / 5), align_corners=True, p=1.0)
+ params = aug.forward_parameters(image.shape)
+ expected = torch.zeros_like(image)
+ expected[..., 3, 3] = 1
+ self.assert_close(aug(image, params=params), expected)
+ self.assert_close(aug.transform_matrix[0, :2, 2], image.new_tensor([1.0, 2.0]))
+
+ def test_convention_perspective_uses_inclusive_source_corners(self, device, dtype):
+ x = torch.zeros(1, 1, 5, 7, device=device, dtype=dtype)
+ augmentation = K.RandomPerspective(distortion_scale=0.0, p=1.0)
+ augmentation(x)
+
+ for name in ("start_points", "end_points"):
+ points = augmentation._params[name]
+ expected = points.new_tensor([[[0.0, 0.0], [6.0, 0.0], [6.0, 4.0], [0.0, 4.0]]])
+ self.assert_close(points, expected)
+ self.assert_close(augmentation.transform_matrix, torch.eye(3, device=device, dtype=dtype)[None])
+
+ @pytest.mark.device_agnostic
+ def test_convention_perspective_sampling_extents_and_directions(self):
+ shape = (64, 1, 5, 7)
+ torch.manual_seed(0)
+ basic = K.RandomPerspective(0.5, p=1.0).forward_parameters(shape)
+ area = K.RandomPerspective(0.5, p=1.0, sampling_method="area_preserving").forward_parameters(shape)
+ basic_offset = basic["end_points"] - basic["start_points"]
+ area_offset = area["end_points"] - area["start_points"]
+ extent = basic_offset.new_tensor([1.75, 1.25])
+
+ assert (basic_offset[:, 0] >= 0).all()
+ assert (basic_offset[:, 1, 0] <= 0).all() and (basic_offset[:, 1, 1] >= 0).all()
+ assert (basic_offset[:, 2] <= 0).all()
+ assert (basic_offset[:, 3, 0] >= 0).all() and (basic_offset[:, 3, 1] <= 0).all()
+ assert (basic_offset.abs() <= extent).all()
+ assert (basic_offset.abs().amax(dim=(0, 1)) > 0.9 * extent).all()
+ assert (area_offset.abs() <= extent).all()
+ assert (area_offset.abs().amax(dim=(0, 1)) > 0.9 * extent).all()
+ assert (area_offset.amin(dim=(0, 1)) < 0).all()
+ assert (area_offset.amax(dim=(0, 1)) > 0).all()
+
+ @pytest.mark.device_agnostic
+ def test_convention_perspective_same_on_batch_reuses_destination_corners(self):
+ params = K.RandomPerspective(0.5, p=1.0, same_on_batch=True).forward_parameters((3, 1, 5, 7))
+
+ self.assert_close(params["end_points"], params["end_points"][:1].expand_as(params["end_points"]))
+
+ @pytest.mark.parametrize("constant", [False, True])
+ @pytest.mark.parametrize("align_corners", [False, True])
+ def test_convention_random_perspective_identity_warp_is_identity_4411(self, device, dtype, constant, align_corners):
+ image = torch.ones(1, 1, 5, 7, device=device, dtype=dtype)
+ if not constant:
+ image = torch.arange(35, device=device, dtype=dtype).reshape_as(image)
+ self.assert_close(
+ K.RandomPerspective(0.0, align_corners=align_corners, p=1.0)(image), image, low_tolerance=True
+ )
+
+ @pytest.mark.parametrize("size", [(1, 7), (5, 1), (1, 1)])
+ @pytest.mark.parametrize("align_corners", [False, True])
+ def test_wart_random_perspective_singleton_dimensions_4538(self, device, dtype, size, align_corners):
+ height, width = size
+ image = torch.arange(height * width, device=device, dtype=dtype).reshape(1, 1, height, width)
+ augmentation = K.RandomPerspective(0.0, align_corners=align_corners, p=1.0)
+
+ output = augmentation(image)
+
+ # Coincident source corners make the perspective solve degenerate, even without distortion.
+ assert torch.isnan(augmentation.transform_matrix).all()
+ assert torch.isnan(output).all()
+
+ def test_wart_random_affine_rotation_sign_4408(self, device, dtype):
+ x = torch.zeros(1, 1, 7, 7, device=device, dtype=dtype)
+ x[..., 1, 4] = 1
+ rotation = K.RandomRotation((90.0, 90.0), p=1.0)(x)
+ affine = K.RandomAffine((90.0, 90.0), p=1.0)(x)
+
+ # Positive RandomRotation is visually counter-clockwise, while the affine composer is clockwise.
+ assert rotation[0, 0].argmax().item() == 2 * 7 + 1
+ assert affine[0, 0].argmax().item() == 4 * 7 + 5
+
+ def test_wart_random_rotation90_continuously_samples_then_rounds_4409(self, device, dtype):
+ augmentation = K.RandomRotation90((0, 1), p=1.0)
+ torch.manual_seed(1)
+ params = augmentation.forward_parameters((64, 1, 5, 7))
+
+ assert ((params["times"] >= 0) & (params["times"] <= 1)).all()
+ assert not torch.equal(params["times"], params["times"].round())
+
+ x = torch.zeros(2, 1, 7, 7, device=device, dtype=dtype)
+ x[..., 1, 4] = 1
+ params = augmentation.forward_parameters(x.shape)
+ params["times"] = x.new_tensor([0.6, 0.4])
+ output = augmentation(x, params=params)
+ assert output[0, 0].argmax().item() == 2 * 7 + 1
+ assert output[1, 0].argmax().item() == 1 * 7 + 4
+
+ @pytest.mark.device_agnostic
+ def test_wart_random_rotation90_keeps_non_square_shape_4409(self):
+ x = torch.zeros(1, 1, 5, 7)
+ assert K.RandomRotation90((1, 1), p=1.0)(x).shape == x.shape
+
+ @pytest.mark.device_agnostic
+ def test_wart_align_corners_defaults_split_geometric_augmentations_4412(self):
+ assert K.RandomRotation(0.0).flags["align_corners"] is True
+ assert K.RandomRotation90((0, 0)).flags["align_corners"] is True
+ assert K.RandomAffine(0.0).flags["align_corners"] is False
+ assert K.RandomShear(0.0).flags["align_corners"] is False
+ assert K.RandomTranslate().flags["align_corners"] is False
+ assert K.RandomPerspective().flags["align_corners"] is False
+
+ def test_convention_geometric_resample_and_padding_defaults(self, device, dtype):
+ affine = K.RandomAffine(0.0)
+ shear = K.RandomShear(0.0)
+ translate = K.RandomTranslate()
+ perspective = K.RandomPerspective()
+ rotation = K.RandomRotation(0.0)
+ rotation90 = K.RandomRotation90((0, 0))
+
+ for augmentation in (affine, shear, translate):
+ assert augmentation.flags["resample"] is Resample.BILINEAR
+ assert augmentation.flags["padding_mode"] is SamplePadding.ZEROS
+ for augmentation in (perspective, rotation, rotation90):
+ assert augmentation.flags["resample"] is Resample.BILINEAR
+
+ x = torch.ones(1, 1, 5, 7, device=device, dtype=dtype)
+ translated = K.RandomTranslate((1.0, 1.0), (0.0, 0.0), p=1.0)(x)
+ self.assert_close(translated, torch.zeros_like(x))
+
+ perspective_params = {
+ "start_points": x.new_tensor([[[0, 0], [6, 0], [6, 4], [0, 4]]]),
+ "end_points": x.new_tensor([[[1, 1], [5, 1], [5, 3], [1, 3]]]),
+ }
+ perspective_output = K.RandomPerspective(0.5, p=1.0)(x, params=perspective_params)
+ rotation_output = K.RandomRotation((45.0, 45.0), p=1.0)(x)
+ rotation90_output = K.RandomRotation90((1, 1), p=1.0)(x)
+ for border in (perspective_output[..., 0, :], rotation_output[..., 0, 0], rotation90_output[..., :, 0]):
+ self.assert_close(border, torch.zeros_like(border))