π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(contrib,tracking): Convention blocks, fact fixes and pins for kornia.contrib and kornia.tracking (#5978)
Dmytro Mishkind39beedd712b
diff --git a/changelog.d/5978.added.md b/changelog.d/5978.added.mdnew file mode 100644index 000000000..240fbc833--- /dev/null+++ b/changelog.d/5978.added.md@@ -0,0 +1 @@+`kornia.tracking` and the numeric and tooling exports of `kornia.contrib` document their conventions in Convention blocks, the contrib page lists `histogram_matching` and `interp` and maps the connected-component connectivity onto SciPy, OpenCV and scikit-image, and the known defects link their issues (#5956, #5963, #5967, #5968, #5977).diff --git a/docs/source/contrib.rst b/docs/source/contrib.rstindex 3e5dbb9e1..d532ee0bd 100644--- a/docs/source/contrib.rst+++ b/docs/source/contrib.rst@@ -6,6 +6,8 @@ kornia.contrib.. currentmodule:: kornia.contrib+.. _augmentation-audit:+Augmentation Geometry Audit---------------------------@@ -245,9 +247,21 @@ Image Segmentation.. autofunction:: connected_components_union_find+.. _labeling-method:+Choosing a labeling method^^^^^^^^^^^^^^^^^^^^^^^^^^+Both functions label 8-connected components: two foreground pixels (pixels equal+to 1) that touch at an edge or a corner belong to one component. SciPy, OpenCV+and scikit-image take any non-zero pixel as foreground, so the same partition is+``scipy.ndimage.label(mask == 1, structure=np.ones((3, 3)))`` (SciPy's default+structure is 4-connected), ``cv2.connectedComponents((mask == 1).astype(np.uint8),+connectivity=8)`` (OpenCV's default connectivity) and+``skimage.measure.label(mask == 1, connectivity=2)`` (scikit-image's default for+2-D images). Label values differ between these libraries and between the two+functions: compare foreground partitions, not label values.+``connected_components_union_find`` computes the exact 8-connected partitionwithout an iteration budget. It accepts boolean masks and returns ``int64``labels, so half-precision inputs do not cause distinct component IDs to collide.@@ -258,10 +272,9 @@ the host, and the result is not differentiable.``connected_components`` retains its fixed-count pooling implementation; itreturns ``int64`` labels like ``connected_components_union_find`` but keeps itsown label convention. When using it, choose enough iterations for the largest-component's graph diameter: the default 100 steps can leave a long component-split into multiple labels. A small fixed budget may be faster than union-find-for small or fragmented masks, but does not guarantee convergence. The two implementations produce different numerical label IDs;-compare their foreground partitions instead of comparing label values directly.+component's graph diameter: the default 100 steps can leave a long or large+component split into multiple labels. A small fixed budget may be faster than+union-find for small or fragmented masks, but does not guarantee convergence.Segment Anything (SAM)^^^^^^^^^^^^^^^^^^^^^^@@ -290,6 +303,12 @@ Image Patches.. autoclass:: ExtractTensorPatches.. autoclass:: CombineTensorPatches+Histogram Matching+------------------++.. autofunction:: histogram_matching+.. autofunction:: interp+Image Classification--------------------@@ -313,10 +332,14 @@ Distance Transform------------------.. autofunction:: distance_transform-.. autofunction:: diamond_square.. autoclass:: DistanceTransform+Plasma Fractal Noise+--------------------++.. autofunction:: diamond_square+KMeans------diff --git a/kornia/contrib/augmentation_audit.py b/kornia/contrib/augmentation_audit.pyindex c505d06d6..245e7e6a8 100644--- a/kornia/contrib/augmentation_audit.py+++ b/kornia/contrib/augmentation_audit.py@@ -100,6 +100,9 @@ class AugmentationAuditStep:Parameters and flags are detached copies; ``occurrence`` is zero-based foreach qualified module name. Shapes describe the image path. Flags includekeyword overrides observed on that image call.++ Convention:+ See :ref:`augmentation-audit`."""name: str@@ -130,6 +133,9 @@ class SpatialAudit:Statistics cover only finite errors, in pixels; a batch with no valid errorshas NaN statistics and zero ``roundtrip_valid_count``. Diagnostics use float32for half inputs, otherwise the image dtype.++ Convention:+ See :ref:`augmentation-audit`."""input_index: int@@ -161,6 +167,9 @@ class AugmentationAuditReport:``inverse_matrix`` has NaNs for singular/nonfinite batches. No image inverseis evaluated: coordinate invertibility does not imply pixel reconstruction,particularly after cropping, interpolation or intensity changes.++ Convention:+ See :ref:`augmentation-audit`."""inputs: list[dict[str, Any]]@@ -408,6 +417,10 @@ def audit(The returned outputs retain the ordinary forward structure, values and gradients.Do not audit the same stateful sequence concurrently.+ Convention:+ :ref:`augmentation-audit` states the direction of ``report.matrix``, the pixel-centre rectangle of the+ out-of-frame test, the dtypes of the diagnostics and the inputs it accepts.+Args:sequence: The 2D augmentation sequence to execute and inspect.args: Image and optional spatial inputs accepted by the sequence.diff --git a/kornia/contrib/connected_components.py b/kornia/contrib/connected_components.pyindex 849d22e26..b3cdf8ce7 100644--- a/kornia/contrib/connected_components.py+++ b/kornia/contrib/connected_components.py@@ -34,10 +34,22 @@ def connected_components(image: torch.Tensor, num_iterations: int = 100) -> torc.. note::See a working example `here <https://www.kornia.org/tutorials/nbs/connected_components.html>`__.+ Convention:+ - Components are 8-connected: pixels that touch at a corner are connected. :ref:`labeling-method` maps this+ onto SciPy, OpenCV and scikit-image.+ - Foreground is a value exactly equal to 1: 0.5 and 2 are background. Other values and dtypes are accepted.+ - The label of a component is 1 plus the largest raster index of its pixels in the batch flattened to+ :math:`(N, H, W)`; background is 0. Labels are therefore not contiguous, and an image gets other labels at+ another batch position or transposed. On MPS an image of more than :math:`2^{24}` pixels raises+ ``ValueError``.+ - ``num_iterations`` is a fixed number of max-pooling steps, not a convergence test, and a label travels one+ pixel per step: the default 100 already splits a 1 x 102 line, and a filled 120 x 150 rectangle comes out+ with 1000 labels. :ref:`labeling-method` compares this with :func:`connected_components_union_find`.+ - The labels carry no gradient.+Args:- image: the binarized input image with shape :math:`(*, 1, H, W)`.- The image must be in floating point with range [0, 1].- num_iterations: the number of iterations to make the algorithm to converge.+ image: the binary input image with shape :math:`(*, 1, H, W)`.+ num_iterations: the number of max-pooling steps, at least 1.Return:int64 labels with the shape of the input.@@ -99,9 +111,12 @@ def connected_components_union_find(image: torch.Tensor) -> torch.Tensor:https://doi.org/10.1109/TPDS.2019.2934683. Root hooking with ``scatter_reduce_``and pointer jumping replace the paper's custom CUDA union kernels.- Unlike :func:`connected_components`, this function runs until convergence- and returns integer labels, including for half-precision inputs. There is- no iteration budget to choose based on component diameter.+ Unlike :func:`connected_components`, this function runs until convergence.+ There is no iteration budget to choose based on component diameter.++ Convention:+ :ref:`labeling-method` maps its 8-connectivity onto SciPy, OpenCV and scikit-image, and compares it with+ :func:`connected_components`.Args:image: Binary image of shape :math:`(*, 1, H, W)`. Boolean, integer anddiff --git a/kornia/contrib/diamond_square.py b/kornia/contrib/diamond_square.pyindex d09551002..a7eb67b43 100644--- a/kornia/contrib/diamond_square.py+++ b/kornia/contrib/diamond_square.py@@ -161,17 +161,42 @@ def diamond_square(device: Optional[torch.device] = None,dtype: Optional[torch.dtype] = None,) -> torch.Tensor:- """Generate Plasma Fractal Images using the diamond square algorithm.-- See: https://en.wikipedia.org/wiki/Diamond-square_algorithm+ r"""Generate Plasma Fractal Images using a variant of the diamond square algorithm.++ It ports `tormentor <https://github.com/anguelos/tormentor>`_'s variant of the+ `diamond-square algorithm <https://en.wikipedia.org/wiki/Diamond-square_algorithm>`_.++ Convention:+ - The map is grown on a :math:`2^n + 1` grid and cropped to ``output_size`` at its top-left corner, so it can+ be a non-contiguous view. The seed is a :math:`3 \times K` grid, transposed to :math:`K \times 3` for a map+ taller than wide, whose cell corners, the even nodes of its first and last rows (columns when transposed),+ are ``random_scale`` times a ``random_fn`` draw, and whose other nodes are the means of their neighbours.+ Each level sets a new node to+ :math:`(1 - s_k)\,\overline{n} + s_k\,u`, the mean :math:`\overline{n}` of its neighbours mixed with a+ ``random_fn`` draw :math:`u` by :math:`s_k = \mathrm{random\_scale} \cdot \mathrm{roughness}^k` at level+ :math:`k \geq 1`: both are mixing weights, not amplitudes. A border node of the square step averages its+ three neighbours; the diamond step's nodes are all interior, so its ``reflect`` padding never reaches them.+ - ``random_fn`` is called as ``random_fn(shape, device=device, dtype=dtype)`` and is the only source of+ randomness, so ``functools.partial(torch.rand, generator=g)`` leaves the global generator alone. With+ ``torch.rand`` the map stays in [0, 1] without normalization while ``random_scale`` and ``roughness`` are in+ [0, 1], and with ``random_scale=1`` it is flat in mean (0.5 everywhere), though its variance varies across+ the map.+ - ``roughness`` and ``random_scale`` are a float, a 0-d tensor or a :math:`(B,)` tensor with one value per+ sample, and follow ``device`` and ``dtype``.+ - ``normalize_range=(min, max)`` rescales each :math:`(b, c)` plane to that range with+ :func:`~kornia.enhance.normalize_min_max`.+ - Known defect: the mean is not flat when ``random_scale`` is neither 0 nor 1, ``roughness`` is non-zero and+ both sides of the map exceed 3, so that it grows past its seed. The seed's mean is ``0.5 * random_scale`` and+ every level mixes towards 0.5, so at ``random_scale=0.5`` the seed nodes average 0.25 and the other pixels+ more, by an amount that depends on ``roughness`` and the map size: 0.31 to 0.35 on a :math:`9 \times 17` map+ at the default ``roughness`` (`#5963 <https://github.com/kornia/kornia/issues/5963>`_).Args:output_size: a tuple of integers with the BxCxHxW of the image to be generated.- roughness: the scale value to apply at each recursion step.- random_scale: the initial value of the scale for recursion.+ roughness: the factor that scales the mixing weight at each recursion step.+ random_scale: the mixing weight before the first recursion step, which also scales the seed.random_fn: the callable function to use to sample a random torch.Tensor.- normalize_range: whether to F.normalize using min-max the output map. In case of a- range is specified, min-max norm is applied between the provided range.+ normalize_range: if given, the ``(min, max)`` range each plane is min-max normalized to.device: the torch device to place the output map.dtype: the torch dtype to place the output map.@@ -224,7 +249,7 @@ def diamond_square(img = img[..., :width, :height]img = img.view(output_size)- # F.normalize the output in the range using min-max+ # min-max normalize each (b, c) plane to the rangeif normalize_range is not None:min_val, max_val = float(normalize_range[0]), float(normalize_range[1])img = normalize_min_max(img.contiguous(), min_val, max_val)diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.pyindex 5cd104662..0e6e57d8a 100644--- a/kornia/contrib/distance_transform.py+++ b/kornia/contrib/distance_transform.py@@ -159,13 +159,34 @@ def _distance_transform_3d_impl(image: torch.Tensor, kernel_size: int, h: float)def distance_transform(image: torch.Tensor, kernel_size: int = 3, h: float = 0.35) -> torch.Tensor:r"""Approximates the Euclidean distance transform of images/volumes using cascaded convolution operations.- The value at each pixel/voxel represents the distance to the nearest non-zero element.It uses the method described in :cite:`pham2021dtlayer`.The transformation is applied independently across the channel dimension.+ Convention:+ - The distance is to the nearest non-zero pixel, where SciPy's ``distance_transform_edt`` and OpenCV's+ ``distanceTransform`` measure it to the nearest zero: ``distance_transform(x)`` approximates+ ``scipy.ndimage.distance_transform_edt(x == 0)``.+ - ``image`` is a binary mask whose sources are the pixels equal to 1. A value :math:`0 < v < 1` is a weaker+ source: it adds :math:`-h \log v` to a distance within ``kernel_size // 2`` of it whose window holds no+ other source, less where the window holds one, as the soft minimum sums them before its logarithm, and+ does not change the distances further away.+ - A mask without any non-zero pixel gives 0 everywhere, as a full mask does, which keeps the output and its+ gradient finite.+ - Known defect: the result is not Euclidean, and there is no general bound on its error+ (`#5956 <https://github.com/kornia/kornia/issues/5956>`_). From an isolated source it is exact only within+ ``kernel_size // 2``; beyond, it follows the number of cascade steps, so a diagonal comes out short by up to+ a fraction :math:`1 - 1/\sqrt{2}` (29 %) of its length in 2-D and :math:`1 - 1/\sqrt{3}` (42 %) in 3-D, at+ any ``kernel_size``. Separately, the soft minimum pulls a value down wherever several foreground or already+ reached pixels share its window (replicate padding counts a pixel on the image border twice), the more the+ larger ``h``: at the default ``h`` by 0.167 px beside a straight edge, 0.243 px midway between two sources+ 2 px apart and 0.579 px in a one-pixel hole, and in a hole towards 0 as ``h`` nears its upper bound.+ - Known defect: values above 1 are not rejected and change the distances; at the default ``kernel_size=3``+ and ``h=0.35`` a mask of 0 and 255 gives 0 everywhere+ (`#5977 <https://github.com/kornia/kornia/issues/5977>`_).+Args:image: Image or volume with shape :math:`(B,C,H,W)` or :math:`(B,C,D,H,W)`.- kernel_size: size of the convolution kernel. Must be an odd number.+ kernel_size: size of the convolution kernel. Must be an odd number of at least 3.h: value that influences the approximation of the min function. The cascade's kernel taps are``exp(-dist/h)``. Accepted: ``h`` large enough that the corner tap (distance``sqrt(ndim) * (kernel_size // 2)``) stays at or above the smallest normal number of the working@@ -178,7 +199,7 @@ def distance_transform(image: torch.Tensor, kernel_size: int = 3, h: float = 0.3result back, which widens the safe ``h`` range for those dtypes to match ``float32``.Returns:- tensor with the same shape as input.+ tensor with the shape and dtype of the input.Example:>>> # 2D example:@@ -218,6 +239,9 @@ def distance_transform(image: torch.Tensor, kernel_size: int = 3, h: float = 0.3class DistanceTransform(nn.Module):r"""Module that approximates the Euclidean distance transform of images/volumes using convolutions.+ Convention:+ See the Convention block of :func:`distance_transform`.+Args:kernel_size: size of the convolution kernel.h: value that influences the approximation of the min function. See :func:`distance_transform`@@ -233,9 +257,7 @@ class DistanceTransform(nn.Module):def forward(self, image: torch.Tensor) -> torch.Tensor:"""Compute the distance transform while preserving the original tensor layout.- The underlying functional implementation expects a single-channel tensor.- For multi-channel inputs, channels are temporarily folded into the batch- dimension, processed independently, and then reshaped back.+ Each channel is processed independently, as in :func:`distance_transform`.Args:image: Input tensor with shape :math:`(B, C, H, W)` for 2D data or@@ -248,7 +270,6 @@ class DistanceTransform(nn.Module):Returns:A distance-transform tensor with the same shape as ``image``.- Each channel is processed independently."""# Reshape multi-channel inputs to batch dimension to ensure independent processingif image.shape[1] > 1:diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.pyindex 66f30a396..ca9ac481a 100644--- a/kornia/contrib/extract_patches.py+++ b/kornia/contrib/extract_patches.py@@ -79,6 +79,10 @@ def compute_padding(Return:The required padding as a tuple of four ints: (top, bottom, left, right)+ Convention:+ See the Convention block of :class:`~kornia.contrib.ExtractTensorPatches`, which states where the padding+ goes.+Example:>>> image = torch.arange(12).view(1, 1, 4, 3)>>> padding = compute_padding((4,3), (3,3))@@ -91,7 +95,7 @@ def compute_padding(.. note::This function will be implicitly used in :func:`extract_tensor_patches` and :func:`combine_tensor_patches` if- `allow_auto_(un)padding` is set to True.+ `allow_auto_(un)padding` is set to True and no non-zero `(un)padding` is given.""" # noqa: D205original_size = cast(Tuple[int, int], _pair(original_size))@@ -129,29 +133,28 @@ def compute_padding(class ExtractTensorPatches(nn.Module):- r"""nn.Module that extract patches from tensors and torch.stack them.+ r"""nn.Module that extracts patches from tensors and stacks them.In the simplest case, the output value of the operator with input size:math:`(B, C, H, W)` is :math:`(B, N, C, H_{out}, W_{out})`.where- :math:`B` is the batch size.- - :math:`N` denotes the total number of extracted patches stacked in+ - :math:`N` denotes the total number of extracted patches.- :math:`C` denotes the number of input channels.- :math:`H`, :math:`W` the input height and width of the input in pixels.- - :math:`H_{out}`, :math:`W_{out}` denote to denote to the patch size+ - :math:`H_{out}`, :math:`W_{out}` denote the patch sizedefined in the function signature.- left-right and top-bottom order.An empty batch (:math:`B = 0`) gives an empty output with the same :math:`N`, :math:`C`, :math:`H_{out}` and- :math:`W_{out}` as a non-empty one. :math:`C` must be non-zero and the window sizes positive.+ :math:`W_{out}` as a non-empty one. :math:`C` must be non-zero and the window sizes and strides positive.* :attr:`window_size` is the size of the sliding window and controls theshape of the output torch.Tensor and defines the shape of the output patch.* :attr:`stride` controls the stride to apply to the sliding window andregulates the overlapping between the extracted patches.- * :attr:`padding` controls the amount of implicit torch.zeros-paddings on both- sizes at each dimension.+ * :attr:`padding` controls the amount of implicit zero padding on each side+ of each dimension.* :attr:`allow_auto_padding` allows automatic calculation of the padding requiredto fit the window and stride into the image.@@ -167,12 +170,28 @@ class ExtractTensorPatches(nn.Module):first two ints are for the height dimension while the last two ints are forthe width dimension.+ Convention:+ - Patches are stacked row-major over the grid of window positions, left to right and then top to bottom, the+ order of :func:`torch.nn.functional.unfold`.+ - A positive ``padding`` adds zeros and a negative one crops. A 4-tuple is ``(top, bottom, left, right)``,+ not the ``(left, right, top, bottom)`` of :func:`torch.nn.functional.pad`; a 2-tuple ``(ph, pw)`` adds+ ``ph`` rows above and below and ``pw`` columns left and right.+ - A window that does not fit warns and drops the last rows or columns; an image smaller than the window warns+ and then raises. ``allow_auto_padding=True`` pads instead, as :func:`compute_padding` computes: split evenly+ with the odd pixel at the bottom or right, and an image smaller than the window padded to one window.+ - A non-zero ``padding`` switches off both the fit warning and ``allow_auto_padding``, so a padding too small+ for the window drops the last rows or columns silently. An all-zero ``padding`` counts as none.+ - A ``window_size`` or ``stride`` component below 1 raises ``ValueCheckError``, a ``ValueError``, up front+ (at construction for the module classes), here and in :func:`combine_tensor_patches`,+ :func:`compute_padding` and :class:`CombineTensorPatches`, also under ``python -O`` and+ ``disable_checks()``.+Args:input: torch.Tensor image where to extract the patches with shape :math:`(B, C, H, W)`.window_size: the size of the sliding window and the output patch size.stride: stride of the sliding window.- padding: Zero-padding added to both side of the input.- allow_auto_adding: whether to allow automatic padding if the window and stride do not fit into the image.+ padding: zero padding, or cropping where negative: an int, ``(ph, pw)`` or ``(top, bottom, left, right)``.+ allow_auto_padding: whether to allow automatic padding if the window and stride do not fit into the image.Shape:- Input: :math:`(B, C, H, W)`@@ -241,17 +260,16 @@ class CombineTensorPatches(nn.Module):where- :math:`B` is the batch size.- - :math:`N` denotes the total number of extracted patches stacked in+ - :math:`N` denotes the total number of extracted patches.- :math:`C` denotes the number of input channels.- - :math:`H`, :math:`W` the input height and width of the input in pixels.- - :math:`H_{out}`, :math:`W_{out}` denote to denote to the patch size+ - :math:`H`, :math:`W` the height and width of the output image in pixels.+ - :math:`H_{out}`, :math:`W_{out}` denote the patch sizedefined in the function signature.- left-right and top-bottom order.An empty batch (:math:`B = 0`) is reconstructed with the same spatial size and unpadding as a non-empty one.* :attr:`original_size` is the size of the original image prior to- extracting torch.Tensor patches and defines the shape of the output patch.+ extracting torch.Tensor patches, which is the size of the output image.* :attr:`window_size` is the size of the sliding window used whileextracting torch.Tensor patches.* :attr:`stride` controls the stride to apply to the sliding window and@@ -275,12 +293,26 @@ class CombineTensorPatches(nn.Module):first two ints are for the height dimension while the last two ints are forthe width dimension.+ Convention:+ - Overlapping patches are averaged: each pixel is divided by the number of patches that cover it, where+ :func:`torch.nn.functional.fold` sums them. A pixel that no patch covers (patches that do not fit) is 0.+ - The output keeps the dtype of the patches. Integer patches are averaged exactly in ``int64``, with the mean+ truncated toward zero (on MPS before torch 2.9 they go through ``float32``, exact up to :math:`2^{24}`);+ ``bool`` patches are True where any covering patch is True; ``float16`` and ``bfloat16`` patches are summed+ in ``float32``.+ - A ``stride`` larger than ``window_size`` raises, because the patches leave pixels uncovered.+ - ``unpadding`` and ``allow_auto_unpadding`` follow the ``padding`` and ``allow_auto_padding`` rules of+ :class:`ExtractTensorPatches`; pass the values used to extract the patches.+ - ``stride`` defaults to ``window_size`` here and in :func:`compute_padding`, to 1 in+ :class:`ExtractTensorPatches` and :func:`extract_tensor_patches`, and has no default in+ :func:`combine_tensor_patches`, which also takes ``allow_auto_unpadding`` before ``unpadding``.+Args:patches: patched torch.Tensor with shape :math:`(B, N, C, H_{out}, W_{out})`.original_size: the size of the original torch.Tensor and the output size.window_size: the size of the sliding window used while extracting patches.- stride: stride of the sliding window.- unpadding: remove the padding added to both side of the input.+ stride: stride of the sliding window. Default: ``window_size``.+ unpadding: the padding used while extracting the patches, removed from the output.allow_auto_unpadding: whether to allow automatic unpadding of the inputif the window and stride do not fit into the original_size.@@ -367,14 +399,15 @@ def combine_tensor_patches() -> torch.Tensor:r"""Restore input from patches.- See :class:`~kornia.contrib.CombineTensorPatches` for details.+ Convention:+ See the Convention block of :class:`~kornia.contrib.CombineTensorPatches`.Args:patches: patched torch.Tensor with shape :math:`(B, N, C, H_{out}, W_{out})`.original_size: the size of the original torch.Tensor and the output size.window_size: the size of the sliding window used while extracting patches.- stride: stride of the sliding window.- unpadding: remove the padding added to both side of the input.+ stride: stride of the sliding window. Required.+ unpadding: the padding used while extracting the patches, removed from the output.allow_auto_unpadding: whether to allow automatic unpadding of the inputif the window and stride do not fit into the original_size.eps: deprecated, has no effect. Each covered pixel is divided by its exact overlap count and a pixel no patch@@ -559,13 +592,14 @@ def extract_tensor_patches() -> torch.Tensor:r"""Extract patches from tensors and stacks them.- See :class:`~kornia.contrib.ExtractTensorPatches` for details.+ Convention:+ See the Convention block of :class:`~kornia.contrib.ExtractTensorPatches`.Args:input: torch.Tensor image where to extract the patches with shape :math:`(B, C, H, W)`.window_size: the size of the sliding window and the output patch size.stride: stride of the sliding window.- padding: Zero-padding added to both side of the input.+ padding: zero padding, or cropping where negative: an int, ``(ph, pw)`` or ``(top, bottom, left, right)``.allow_auto_padding: whether to allow automatic padding if the window and stride do not fit into the image.Returns:diff --git a/kornia/contrib/histogram_matching.py b/kornia/contrib/histogram_matching.pyindex 4eadc6918..cb49a3e37 100644--- a/kornia/contrib/histogram_matching.py+++ b/kornia/contrib/histogram_matching.py@@ -22,22 +22,33 @@ def histogram_matching(source: torch.Tensor, template: torch.Tensor) -> torch.Te"""Adjust the pixel values of an image to match its histogram towards a target image.`Histogram matching <https://en.wikipedia.org/wiki/Histogram_matching>`_ is the transformation- of an image so that its histogram matches a specified histogram. In this implementation, the- histogram is computed over the flattened image array. Code referred to+ of an image so that its histogram matches a specified histogram. Code referred to`here <https://stackoverflow.com/questions/32655686/histogram-matching-of-two-images-in-python-2-x>`_.+ Convention:+ - One histogram of every element of ``source``, all batch items and channels together, is matched to one+ histogram of every element of ``template``, which can have any shape. This is+ ``skimage.exposure.match_histograms(source, template, channel_axis=None)``, which needs both inputs to have+ the same number of dimensions (flatten them otherwise); to match each sample or channel on its own, call the+ function on each slice.+ - A source value maps to the template value at its quantile, interpolated linearly between template values+ with :func:`interp`. The result stays inside the template's range once that range is rounded to the output+ dtype, so with a ``float64`` template and a ``float32`` source it can pass the unrounded ends by that+ rounding. It can also fall between template values: a ``uint8`` template gives fractional values, as in+ skimage.+ - A floating source keeps its dtype; an integer or ``bool`` source returns ``float32``. The quantiles are+ computed in ``float32`` (``float64`` for a ``float64`` source).+ - It is not differentiable: with a non-empty ``source``, no gradient reaches it and a backward pass into+ ``template`` raises.+ - An empty ``source`` with a non-empty ``template`` returns an empty tensor, still attached to its autograd+ graph; an empty ``template`` raises ``ValueError``, even when ``source`` is empty too.+Args:source: Image to transform.template: Template image. It can have different dimensions to source.Returns:- The transformed output image as the same shape as the source image. A floating source keeps its dtype; an- integer source returns ``float32``. The values come from the template, on its scale. The quantiles are- computed in ``float32`` (``float64`` for a ``float64`` source), so ``uint8``, ``float16`` and ``bfloat16``- images of any size work.-- Note:- This function does not matches histograms element-wisely if input a batched tensor.+ The transformed output image, with the shape of the source image."""oldshape = source.shape@@ -83,8 +94,16 @@ def interp(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.Tensor:Returns the one-dimensional piecewise linear interpolant to a function withgiven discrete data points :math:`(xp, fp)`, evaluated at :math:`x`.- This is confirmed to be a correct implementation.- See https://github.com/pytorch/pytorch/issues/1552#issuecomment-979998307+ Convention:+ - Outside ``[xp[0], xp[-1]]`` the end segments are extrapolated linearly, where :func:`numpy.interp` clamps to+ ``fp[0]`` and ``fp[-1]``; SciPy's ``interp1d(xp, fp, fill_value="extrapolate")`` makes the same choice. At a+ knot the result is that knot's ``fp``.+ - ``xp`` and ``fp`` are 1-D; ``x`` can have any shape, which the output keeps. ``xp`` must be increasing, which+ is not checked. The output dtype is the promoted dtype of ``x``, ``xp`` and ``fp``, or the default float+ dtype when all three are integer.+ - Known defects: with integer ``x`` and ``xp`` and a ``float16`` ``fp``, any coordinate difference above 65504+ overflows, and the result can be NaN, inf or silently wrong, such as 0; in ``float16`` a segment whose ``fp``+ difference overflows can be about one ulp off (`#5967 <https://github.com/kornia/kornia/issues/5967>`_).Args:x: the :math:`x`-coordinates at which to evaluate the interpolateddiff --git a/kornia/contrib/image_stitching.py b/kornia/contrib/image_stitching.pyindex 7a3bdf688..8622275a8 100644--- a/kornia/contrib/image_stitching.py+++ b/kornia/contrib/image_stitching.py@@ -28,26 +28,44 @@ from kornia.geometry.transform import warp_perspectiveclass ImageStitcher(nn.Module):- """Stitch two images with overlapping fields of view.+ """Stitch images with overlapping fields of view.++ Convention:+ - The images are RGB, :math:`(B, 3, H, W)`, all of one height, ordered left to right. ``matcher`` is a+ :class:`~kornia.feature.LoFTR` or a :class:`~kornia.feature.LocalFeatureMatcher`, which gets grayscale+ copies; any other matcher raises ``NotImplementedError``.+ - The panorama is in the first image's pixel frame and has its height: content that maps left of its first+ column, or above or below its rows, is lost. Each next image is warped onto the panorama so far with a+ homography from their matches; every sample needs 4 matches, or a ``RuntimeError`` names the sample.+ - ``"naive"`` blending keeps the warped image wherever it covers a pixel completely, so in an overlap the right+ image replaces the left one; a pixel it covers only in part keeps the panorama's value.+ - The result drops the empty trailing columns, those after the last column that any sample covers; an+ uncovered column before it, the first one included, is kept. A batch shares one crop, so it is cropped to its+ widest sample and a narrower sample keeps zero columns on its right.+ - ``estimator="ransac"`` uses ``RANSAC("homography")`` (``inl_th=2.0``); ``"vanilla"`` fits every match with+ iterated DLT.Args:- matcher: image feature matching module.+ matcher: image feature matching module, :class:`~kornia.feature.LoFTR` or+ :class:`~kornia.feature.LocalFeatureMatcher`.estimator: method to compute homography, either "vanilla" or "ransac"."ransac" is slower with a better accuracy.blending_method: method to blend two images together.Only "naive" is currently supported.- Note:- Current implementation requires strict image ordering from left to right.-.. code-block:: python- IS = ImageStitcher(KF.LoFTR(pretrained='outdoor'), estimator='ransac').cuda()- # Compute the stitched result with less GPU memory cost.+ import torch+ import kornia.feature as KF+ from kornia.contrib import ImageStitcher++ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")+ stitcher = ImageStitcher(KF.LoFTR(pretrained="outdoor"), estimator="ransac").to(device)+ # img_left and img_right: (1, 3, H, W) RGB images of one height on `device`with torch.inference_mode():- out = IS(img_left, img_right)- # Show the result- plt.imshow(K.tensor_to_image(out))+ panorama = stitcher(img_left, img_right)++ See :doc:`/applications/image_stitching` for a complete example."""@@ -148,11 +166,11 @@ class ImageStitcher(nn.Module):pixels covered by at least one input view.Returns:- The stitched image cropped to remove trailing invalid columns- (columns that contain no valid pixels in the mask).- If no redundant area is found, the original ``image`` is returned.+ The stitched image without its empty trailing columns, those after the last column that has a valid pixel+ in any sample of the mask. Uncovered columns before it are kept, and a mask without any valid pixel returns+ the original ``image``."""- # NOTE: assumes no batch mode. This method keeps all valid regions after stitching.+ # One crop for the whole batch: a column is valid if any sample has a valid pixel in it.mask_ = mask.sum((0, 1))index = int(mask_.bool().any(0).flip(0).long().argmax().item())if index == 0: # If no redundant space@@ -240,11 +258,11 @@ class ImageStitcher(nn.Module):Args:*imgs: Ordered image tensors from left to right. Each tensor is expectedto share a common height and overlap with the next image.- Each tensor typically follows :math:`(B, C, H, W)`.+ Each tensor is RGB, :math:`(B, 3, H, W)`.Returns:A single panorama tensor obtained by stitching all provided images- in order and cropping trailing empty space.+ in order and cropping it as :meth:`postprocess` does."""img_out = imgs[0]mask_left = torch.ones_like(img_out)diff --git a/kornia/contrib/kmeans.py b/kornia/contrib/kmeans.pyindex afeb9e69b..1368922a7 100644--- a/kornia/contrib/kmeans.py+++ b/kornia/contrib/kmeans.py@@ -26,14 +26,30 @@ from kornia.geometry.linalg import euclidean_distanceclass KMeans:- """Implements the kmeans clustering algorithm with euclidean distance as similarity measure.+ r"""Implements the kmeans clustering algorithm with euclidean distance as similarity measure.++ Convention:+ - :meth:`fit` stops after the first update whose squared total centre shift,+ :math:`(\sum_k \lVert c_k^{\text{new}} - c_k \rVert)^2`, is at most ``tolerance``, or after ``max_iterations``+ updates. ``max_iterations=0`` sets no limit, so ``tolerance`` must not be ``None`` then.+ - ``seed`` calls ``torch.manual_seed(seed)``, which reseeds the global generator. The initial centres, sampled+ from the data of each :meth:`fit` when ``cluster_centers`` is ``None``, and the points that empty clusters+ move to are drawn from it; there is no ``generator`` argument. A second :meth:`fit` on the same data+ therefore starts from other centres unless the global generator is reseeded first.+ - A point at the same distance from two centres goes to the one with the lower index. A cluster that gets no+ point moves to a random data point.+ - Distances and means are computed in the promoted dtype of the data and the centres, at least ``float32``+ (``int64`` for integer data and centres). The centres keep the dtype of the data, so an integer mean is+ truncated toward zero.Args:- num_clusters: number of clusters the data has to be assigned to- cluster_centers: torch.Tensor of starting cluster centres can be passed instead of num_clusters- tolerance: float value. the algorithm terminates if the shift in centers is less than tolerance- max_iterations: number of iterations to run the algorithm for- seed: number to set torch manual seed for reproducibility+ num_clusters: number of clusters the data has to be assigned to. Required, also with ``cluster_centers``.+ cluster_centers: the ``(num_clusters, D)`` starting centres, or ``None`` to sample them from the data in+ each :meth:`fit`.+ tolerance: the bound on the squared total centre shift that stops :meth:`fit`, or ``None`` to stop only after+ ``max_iterations`` updates.+ max_iterations: the maximum number of updates; 0 sets no limit.+ seed: if given, passed to ``torch.manual_seed`` when the object is created.Example:>>> kmeans = kornia.contrib.KMeans(3, None, 10e-4, 100, 0)diff --git a/kornia/contrib/lambda_module.py b/kornia/contrib/lambda_module.pyindex e714913bf..7a3dfdad4 100644--- a/kornia/contrib/lambda_module.py+++ b/kornia/contrib/lambda_module.py@@ -24,6 +24,9 @@ from torch import nnclass Lambda(nn.Module):"""Applies user-defined lambda as a transform.+ Convention:+ :meth:`forward` calls ``func(img, *args, **kwargs)`` and returns its result unchecked; it need not be a tensor.+Args:func: Callable function.@@ -39,14 +42,14 @@ class Lambda(nn.Module):"""- def __init__(self, func: Callable[..., torch.Tensor]) -> None:+ def __init__(self, func: Callable[..., Any]) -> None:super().__init__()if not callable(func):raise TypeError(f"Argument func should be callable, got {type(func).__name__!r}")self.func = func- def forward(self, img: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor:+ def forward(self, img: torch.Tensor, *args: Any, **kwargs: Any) -> Any:"""Run the user-provided transform function.This method simply forwards all arguments to ``self.func``.@@ -62,6 +65,6 @@ class Lambda(nn.Module):**kwargs: Additional keyword arguments forwarded to ``self.func``.Returns:- The output tensor returned by ``self.func``.+ Whatever ``self.func`` returns."""return self.func(img, *args, **kwargs)diff --git a/kornia/tracking/planar_tracker.py b/kornia/tracking/planar_tracker.pyindex 879ade2b9..d509f8cf1 100644--- a/kornia/tracking/planar_tracker.py+++ b/kornia/tracking/planar_tracker.py@@ -30,12 +30,30 @@ from kornia.geometry.transform import warp_perspectiveclass HomographyTracker(nn.Module):r"""Perform local-feature-based tracking of the target planar object in the sequence of the frames.+ Convention:+ - The returned homography ``H`` is :math:`(3, 3)` and maps target pixel coordinates :math:`(x, y)` to frame+ pixel coordinates, the direction of ``cv2.findHomography(target_points, frame_points)``.+ - The target and every frame are one grayscale image, :math:`(1, 1, H, W)`; a frame can have another size than+ the target. Call :meth:`set_target` before the first frame. The target is not a buffer, so+ :meth:`~torch.nn.Module.to` leaves it where it is: call :meth:`set_target` again after moving the tracker.+ - For a :class:`~kornia.feature.LoFTR`, a :class:`~kornia.feature.LocalFeatureMatcher` or a matcher with an+ ``extract_features`` module, :meth:`set_target` extracts the target's features once. Changes made in place to+ the target or to that matcher's weights afterwards are not noticed; call :meth:`set_target` again.+ - A failed match returns ``(H, False)`` with ``H`` uninitialised (:meth:`no_match`). A failure while tracking+ also drops the previous homography, so the next frame is matched from scratch by ``initial_matcher``.+ - Known defect: with ``float16`` or ``bfloat16`` images, tracking raises on the frame after the first match+ (`#5968 <https://github.com/kornia/kornia/issues/5968>`_).+Args:- initial_matcher: image matching module, e.g. :class:`~kornia.feature.LocalFeatureMatcher`- or :class:`~kornia.feature.LoFTR`. Default: :class:`~kornia.feature.GFTTAffNetHardNet`.- fast_matcher: fast image matching module, e.g. :class:`~kornia.feature.LocalFeatureMatcher`- or :class:`~kornia.feature.LoFTR`. Default: :class:`~kornia.feature.DescriptorMatcher`.- ransac: homography estimation module. Default: :class:`~kornia.geometry.RANSAC`.+ initial_matcher: image matching module for a frame without a previous homography, e.g.+ :class:`~kornia.feature.LocalFeatureMatcher` or :class:`~kornia.feature.LoFTR`. Default:+ ``LocalFeatureMatcher(GFTTAffNetHardNet(3000), DescriptorMatcher("smnn", 0.95))``.+ fast_matcher: image matching module for the next frames, matched after warping them with the previous+ homography, e.g. :class:`~kornia.feature.LocalFeatureMatcher` or :class:`~kornia.feature.LoFTR`. Default:+ ``LoFTR("outdoor")``.+ ransac: homography estimation module. Default: ``RANSAC("homography", inl_th=5.0, batch_size=4096,+ max_iter=10, max_lo_iters=10)``, looser than the ``RANSAC("homography")`` (``inl_th=2.0``) of+ :class:`~kornia.contrib.ImageStitcher`.minimum_inliers_num: threshold for number inliers for matching to be successful. RANSAC needs 4 correspondences,so fewer than 4 matches always count as a failed match, whatever this value is.@@ -180,7 +198,7 @@ class HomographyTracker(nn.Module):"""Return a failed-match response and clear current match statistics.Returns:- A tuple ``(H, is_valid)`` where ``H`` is an empty ``3 x 3`` tensor+ A tuple ``(H, is_valid)`` where ``H`` is an uninitialised ``3 x 3`` tensoron the tracker device and dtype, and ``is_valid`` is ``False``."""self.inliers_num = 0@@ -233,7 +251,7 @@ class HomographyTracker(nn.Module):A tuple ``(H, is_valid)`` where ``H`` is the updated homography and``is_valid`` indicates whether tracking remained reliable.- The frame is first prewarped by the inverse of the previous homography,+ The frame is first prewarped by the inverse of the previous homography, widened by a margin,then matched with ``fast_matcher`` and verified using RANSAC."""self._drop_prior_of_another_target()diff --git a/tests/contrib/test_augmentation_audit.py b/tests/contrib/test_augmentation_audit.pyindex 288e7a7bc..0889832bb 100644--- a/tests/contrib/test_augmentation_audit.py+++ b/tests/contrib/test_augmentation_audit.py@@ -39,7 +39,7 @@ class TestAugmentationAudit(BaseTester):assert not hasattr(K.AugmentationSequential, "audit")def test_bhw_mask_is_accepted_like_bchw(self, device, dtype):- # C-26: AugmentationSequential takes (B, H, W) masks (#5602); audit rejected them as "not batched".+ # AugmentationSequential takes (B, H, W) masks (#5602); audit rejected them as "not batched".seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])img = torch.rand(2, 3, 30, 40, device=device, dtype=dtype)mask = (torch.rand(2, 30, 40, device=device) > 0.5).to(dtype)diff --git a/tests/contrib/test_combine_tensor_patch.py b/tests/contrib/test_combine_tensor_patch.pyindex 065feefe8..f06911a72 100644--- a/tests/contrib/test_combine_tensor_patch.py+++ b/tests/contrib/test_combine_tensor_patch.py@@ -15,6 +15,7 @@# limitations under the License.#+import inspectimport warningsimport pytest@@ -280,7 +281,7 @@ class TestCombineTensorPatches(BaseTester):@pytest.mark.parametrize("stride", [2, 1])def test_float64_round_trip_is_exact(self, stride, device):- # A-9: eps was added to every divisor, so 1000.0 came back as 999.99999.+ # An eps added to every divisor returned 999.99999 for 1000.0.if device.type == "mps":pytest.skip("MPS has no float64")g = torch.Generator().manual_seed(0)@@ -293,9 +294,9 @@ class TestCombineTensorPatches(BaseTester):@pytest.mark.parametrize("stride", [2, 1])@pytest.mark.parametrize("int_dtype", [torch.uint8, torch.int32, torch.int64])def test_integer_round_trip_is_exact(self, stride, int_dtype, device):- # A-10: integers went through float32, so 16777217 came back as 16777216. Plan review P4: float64 would still- # round 2**53 + 1. Integer patches are summed in int64, exactly (on MPS from torch 2.9; older torch keeps the- # float32 fold). At stride 1 a pixel is covered up to 4 times, so 4 * (2**60 + 1) still fits int64.+ # Integers folded through float32 returned 16777216 for 16777217 (float64 would still round 2**53 + 1).+ # Integer patches are summed in int64, exactly (on MPS from torch 2.9; older torch keeps the float32 fold).+ # At stride 1 a pixel is covered up to 4 times, so 4 * (2**60 + 1) still fits int64.if int_dtype != torch.uint8 and device.type == "mps" and torch_version_lt(2, 9, 0):pytest.skip("MPS index_add_ has no int64 source before torch 2.9: the float32 fold is exact only to 2**24")big = {torch.uint8: 255, torch.int32: 2**31 - 1, torch.int64: 2**60 + 1}[int_dtype]@@ -309,7 +310,7 @@ class TestCombineTensorPatches(BaseTester):assert torch.equal(out, img)def test_integer_overlap_mean_truncates_toward_zero(self, device):- # A-6: overlapping, non-identical integer patches. Pixel (0, 1) is covered by patches 0 and 1: (5 + 2) / 2 = 3.5+ # Overlapping, non-identical integer patches. Pixel (0, 1) is covered by patches 0 and 1: (5 + 2) / 2 = 3.5# -> 3, and (-5 - 2) / 2 = -3.5 -> -3 (toward zero, as a float mean cast to an integer dtype does).patches = torch.zeros(1, 6, 1, 2, 2, dtype=torch.int32, device=device) # 3 x 4 image, 2 x 2 windows, stride 1patches[0, 0, 0, 0, 1] = 5@@ -319,9 +320,9 @@ class TestCombineTensorPatches(BaseTester):out = kornia.contrib.combine_tensor_patches(-patches, (3, 4), 2, 1)assert out[0, 0, 0, 1].item() == -3- def test_bool_overlap_keeps_main_result(self, device):- # Probe on main (4863aed8a): bool patches went through float32, the overlap mean was cast back to bool, so a- # pixel is True when any covering patch is True. Literal produced by:+ def test_bool_overlap_is_true_where_any_covering_patch_is_true(self, device):+ # A pixel is True when any covering patch is True, as a float overlap mean cast back to bool gives. Literal+ # produced by:# p = torch.zeros(1, 6, 1, 2, 2, dtype=torch.bool); p[0, 0] = True; p[0, 1] = True# combine_tensor_patches(p, (3, 4), 2, 1).tolist()patches = torch.zeros(1, 6, 1, 2, 2, dtype=torch.bool, device=device)@@ -390,8 +391,7 @@ class TestCombineTensorPatches(BaseTester):assert out.flatten(2).flatten(0, 1).tolist() == expecteddef test_uint64_overlap_mean_is_exact_above_2pow63(self, device):- # Codex review on #5960: an int64 cast wrapped 2**63 to -2**63, so (2**63 + 0) / 2 came back as 3 * 2**62.- # Main (4863aed8a) returned 2**62 here: 2**63 is exact in its float fold.+ # A plain int64 cast wraps 2**63 to -2**63, which returned 3 * 2**62 for (2**63 + 0) / 2 instead of 2**62.if device.type == "mps" and torch_version_lt(2, 9, 0):pytest.skip("MPS index_add_ has no int64 source before torch 2.9: the float32 fold is exact only to 2**24")# The values are set in int64 and viewed as uint64 (v - 2**64 for v >= 2**63): torch 2.5.1 cannot set a uint64@@ -442,8 +442,8 @@ class TestCombineTensorPatches(BaseTester):kornia.contrib.combine_tensor_patches(patches, (4, 6), 2, 2)def test_complex_round_trip(self, device):- # Complex patches are not integers: main cast them to float and discarded the imaginary part. They are folded- # as two real tensors, since MPS has no complex col2im kernel.+ # Complex patches are not integers: a cast to float discarded the imaginary part. They are folded as two real+ # tensors, since MPS has no complex col2im kernel.if device.type == "mps" and torch_version_lt(2, 9, 0):pytest.skip("complex MPS tensors abort the process in unfold on torch 2.5.1")g = torch.Generator().manual_seed(0)@@ -453,10 +453,9 @@ class TestCombineTensorPatches(BaseTester):self.assert_close(out, img)def test_eps_is_deprecated_and_has_no_effect(self, device, dtype):- # Plan review P7: eps was added to every divisor (A-9), and clamp_min(eps) would still have turned a singly- # covered 7 into 3.5 at eps=2. On main, eps=0 gave NaN and eps=-1 gave inf. Patches that do not fit- # (6 patches of a 4 x 6 image recombined to 5 x 7, the warned path) leave row 4 and column 6 uncovered: they- # stay 0 for every eps.+ # An eps added to every divisor changed every pixel; clamp_min(eps) would turn a singly covered 7 into 3.5 at+ # eps=2, and eps=0 or eps=-1 gave NaN or inf. Patches that do not fit (6 patches of a 4 x 6 image recombined+ # to 5 x 7, the warned path) leave row 4 and column 6 uncovered: they stay 0 for every eps.img = torch.arange(1, 25, device=device, dtype=dtype).view(1, 1, 4, 6)patches = kornia.contrib.extract_tensor_patches(img, 2, 2)with warnings.catch_warnings():@@ -472,9 +471,35 @@ class TestCombineTensorPatches(BaseTester):@pytest.mark.parametrize("half", [torch.float16, torch.bfloat16])def test_half_precision_heavy_overlap_round_trip_is_exact(self, half, device):- # A-11: 289 overlapping 0..255 values summed in float16 overflowed (51 inf); bfloat16 was off by 64.+ # 289 overlapping 0..255 values summed in float16 overflowed (51 inf); bfloat16 was off by 64.g = torch.Generator().manual_seed(0)img = (torch.rand(1, 3, 40, 52, generator=g) * 255).round().to(device, half)out = kornia.contrib.combine_tensor_patches(kornia.contrib.extract_tensor_patches(img, 17, 1), (40, 52), 17, 1)assert out.dtype == halfassert torch.equal(out, img)++ def test_convention_overlaps_are_averaged_where_fold_sums_them(self, device, dtype):+ patches = torch.ones(1, 2, 1, 2, 2, device=device, dtype=dtype)+ patches[0, 1] = 3.0+ out = kornia.contrib.combine_tensor_patches(patches, (2, 3), 2, 1)+ self.assert_close(out[0, 0], torch.tensor([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]], device=device, dtype=dtype))+ # torch.nn.functional.fold sums the overlap instead: [[1, 4, 3], [1, 4, 3]]+ # Patches that do not fit (the warned path) leave the last row and column uncovered: they are 0.+ img = torch.arange(1, 25, device=device, dtype=dtype).view(1, 1, 4, 6)+ with pytest.warns(UserWarning, match="will not fit"):+ out = kornia.contrib.combine_tensor_patches(kornia.contrib.extract_tensor_patches(img, 2, 2), (5, 7), 2, 2)+ assert (out[0, 0, -1] == 0).all()+ assert (out[0, 0, :, -1] == 0).all()+ self.assert_close(out[..., :4, :6], img)++ def test_convention_sibling_defaults_differ(self):+ assert kornia.contrib.ExtractTensorPatches(2).stride == 1+ assert inspect.signature(kornia.contrib.extract_tensor_patches).parameters["stride"].default == 1+ assert kornia.contrib.CombineTensorPatches((4, 6), (2, 3)).stride == (2, 3)+ assert kornia.contrib.compute_padding((5, 7), 3) == kornia.contrib.compute_padding((5, 7), 3, 3)+ function = inspect.signature(kornia.contrib.combine_tensor_patches).parameters+ assert function["stride"].default is inspect.Parameter.empty+ # The function and the module take allow_auto_unpadding and unpadding in opposite positional order.+ assert list(function)[4:6] == ["allow_auto_unpadding", "unpadding"]+ module = inspect.signature(kornia.contrib.CombineTensorPatches).parameters+ assert list(module)[3:5] == ["unpadding", "allow_auto_unpadding"]diff --git a/tests/contrib/test_connected_component.py b/tests/contrib/test_connected_component.pyindex eda0537c3..bbcde298b 100644--- a/tests/contrib/test_connected_component.py+++ b/tests/contrib/test_connected_component.py@@ -120,7 +120,7 @@ class TestConnectedComponents(BaseTester):@pytest.mark.parametrize("in_dtype", [torch.float32, torch.float16, torch.bfloat16, torch.bool, torch.uint8])def test_int64_labels_keep_distinct_components_apart(self, in_dtype, device):- # R3 / B-4 / B-5: float16 gave both pixels 2604.0, bool collapsed every label to True.+ # Labels in the input dtype: float16 gave both pixels 2604.0, bool collapsed every label to True.m = torch.zeros(1, 1, 3, 1400, device=device)m[0, 0, 1, 1202] = 1m[0, 0, 1, 1204] = 1@@ -129,13 +129,13 @@ class TestConnectedComponents(BaseTester):assert out[0, 0, 1, [1202, 1204]].tolist() == [1 * 1400 + 1202 + 1, 1 * 1400 + 1204 + 1]def test_uint8_pixel_at_raster_index_255_stays_foreground(self, device):- # B-5: uint8 labels wrapped mod 256, so this pixel got label 0 (background).+ # uint8 labels wrapped mod 256, so this pixel got label 0 (background).m = torch.zeros(1, 1, 9, 31, dtype=torch.uint8, device=device)m[0, 0, 8, 7] = 1assert kornia.contrib.connected_components(m, num_iterations=3)[0, 0, 8, 7].item() == 8 * 31 + 7 + 1def test_ids_stay_exact_past_2_pow_24_pixels(self, device):- # B-6: float32 ids merged indices 2**24 - 1 and 2**24 + 1 into 16777216.+ # float32 ids merged indices 2**24 - 1 and 2**24 + 1 into 16777216.if device.type == "mps":pytest.skip("MPS has no float64; covered by test_mps_raises_past_2_pow_24_pixels")m = torch.zeros(1, 1, 1, 2**24 + 8, device=device)@@ -174,7 +174,7 @@ class TestConnectedComponents(BaseTester):kornia.contrib.connected_components(torch.zeros(1, 1, 1, 2**24 + 8, device=device))def test_permuted_batch(self, device, dtype):- # B-8: a batch whose leading dims cannot be viewed together crashed on .view.+ # A batch whose leading dims cannot be viewed together crashed on .view.g = torch.Generator().manual_seed(0)img = (torch.rand(3, 2, 1, 5, 7, generator=g) > 0.5).to(device, dtype).permute(1, 0, 2, 3, 4)out = kornia.contrib.connected_components(img)@@ -183,8 +183,7 @@ class TestConnectedComponents(BaseTester):@pytest.mark.parametrize("shape", [(1, 1, 0, 5), (2, 1, 5, 0), (0, 1, 5, 7), (3, 0, 1, 5, 7)])def test_empty_input(self, shape, device, dtype):- # B-9: H = 0 crashed in reshape. Plan review P1: reshape(-1, 1, 0, 5) is itself ambiguous, so the empty- # check has to come first.+ # H = 0 crashed in reshape; reshape(-1, 1, 0, 5) is itself ambiguous, so the empty check has to come first.out = kornia.contrib.connected_components(torch.zeros(shape, device=device, dtype=dtype))assert out.shape == shapeassert out.dtype == torch.int64@@ -196,6 +195,24 @@ class TestConnectedComponents(BaseTester):op_jit = torch.jit.script(op)self.assert_close(op(img), op_jit(img))+ def test_convention_both_labelings_are_8_connected(self, device, dtype):+ # A diagonal pair is one component. scipy.ndimage.label's default structure is 4-connected (two components);+ # structure=np.ones((3, 3)) matches.+ pair = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype).view(1, 1, 2, 3)+ assert kornia.contrib.connected_components(pair).tolist() == [[[[5, 0, 0], [0, 5, 0]]]]+ assert kornia.contrib.connected_components_union_find(pair).tolist() == [[[[1, 0, 0], [0, 1, 0]]]]++ def test_convention_foreground_is_exactly_one(self, device, dtype):+ image = torch.tensor([1.0, 0.5, 2.0, 1.0, 0.75], device=device, dtype=dtype).view(1, 1, 1, 5)+ assert kornia.contrib.connected_components(image).tolist() == [[[[1, 0, 0, 4, 0]]]]++ def test_convention_the_default_budget_splits_a_line_longer_than_101_pixels(self, device, dtype):+ # A label travels one pixel per iteration; the 1 + largest raster index starts at the right end.+ line = torch.ones(1, 1, 1, 102, device=device, dtype=dtype)+ assert kornia.contrib.connected_components(line[..., :101]).unique().tolist() == [101]+ assert kornia.contrib.connected_components(line).unique().tolist() == [101, 102]+ assert kornia.contrib.connected_components(line, num_iterations=101).unique().tolist() == [102]+def test_compute_padding():assert kornia.contrib.compute_padding((6, 6), (2, 2)) == (0, 0, 0, 0)diff --git a/tests/contrib/test_conv_distance_transformer.py b/tests/contrib/test_conv_distance_transformer.pyindex 71bbbf91e..f08f60f79 100644--- a/tests/contrib/test_conv_distance_transformer.py+++ b/tests/contrib/test_conv_distance_transformer.py@@ -15,6 +15,8 @@# limitations under the License.#+import math+import pytestimport torch@@ -244,13 +246,6 @@ class TestConvDistanceTransform(BaseTester):tolerance = 5e-3 if dtype == torch.bfloat16 else 1e-3self.assert_close(out[0, 0], expected, rtol=tolerance, atol=tolerance)- # test_convention_small_h_keeps_nonzero_distances_4152, a strict xfail pinning the pre-fix silent- # wrong-output behavior for h=0.01 at kernel_size=3 in float16/bfloat16/mps-float32, is removed- # here: this PR fixes #4152, so that combination now raises BaseError (a different exception than- # the pinned `raises=AssertionError`) instead of returning a wrong value, which would make the- # xfail fail outright rather than pass. test_h_too_small_raises and- # test_h_too_small_raises_float32_regression below pin the new, fixed behavior instead.-def test_half_precision_matches_float64_reference(self, device, dtype):# #4152: the exp(-dist/h) kernel's far taps underflow to exactly zero in float16/bfloat16# at the documented default h=0.35 once kernel_size >= 15, and the convolution silently@@ -301,7 +296,7 @@ class TestConvDistanceTransform(BaseTester):[((1, 1, 40, 50), 31, 0.18), ((1, 1, 40, 50), 31, 0.22), ((1, 1, 12, 40, 50), 21, 0.125)],)def test_h_too_small_for_the_corner_tap_raises(self, shape, kernel_size, h, device):- # B-19: the guard checked only the axis tap exp(-k/h); these h passed it while the corner tap+ # A guard on the axis tap exp(-k/h) alone let these h through while the corner tap# exp(-sqrt(ndim) k/h) underflowed (float32 17.78 vs exact 21.21 at ks 31, h 0.18; MPS vs CPU 4.1 at h 0.22).with pytest.raises(BaseError, match="corner kernel tap"):kornia.contrib.distance_transform(torch.zeros(shape, device=device), kernel_size=kernel_size, h=h)@@ -316,7 +311,7 @@ class TestConvDistanceTransform(BaseTester):],)def test_h_too_large_raises(self, shape, kernel_size, h, device):- # Plan review P3: a pixel counts as reached when -h*log(sum of its window's taps over reached pixels) > 0.+ # A pixel counts as reached when -h*log(sum of its window's taps over reached pixels) > 0.# Once the off-centre taps can sum to >= 1, a pixel whose window is full of reached pixels reads as# foreground (0). Random 60 % masks, ks 3: 140 of 2805 background pixels were 0 at h 0.591, 2726 at h 2.0.# Bounds, float32 working precision (float64): 2-D 0.5624 (0.5626) at ks 3, 0.5084 (0.5085) at ks 5, ~0.501 at@@ -374,3 +369,81 @@ class TestConvDistanceTransform(BaseTester):input3d = torch.rand(1, 1, 8, 8, 8, device=device, dtype=dtype)self.assert_close(op(input3d), op_optimized(input3d))++ def test_convention_distance_is_to_the_nearest_nonzero_pixel(self, device, dtype):+ image = torch.zeros(1, 1, 23, 37, device=device, dtype=dtype)+ image[0, 0, 4, 9] = 1.0+ out = kornia.contrib.distance_transform(image)+ # SciPy 1.17.1 measures to the nearest zero; distance_transform_edt(image == 0) at (4, 9), (4, 10), (5, 10)+ # gives [0, 1, 1.4142135]: exact within kernel_size // 2.+ values = torch.stack([out[0, 0, 4, 9], out[0, 0, 4, 10], out[0, 0, 5, 10]])+ self.assert_close(values, torch.tensor([0.0, 1.0, 2.0**0.5], device=device, dtype=dtype))++ def test_convention_empty_mask_gives_zeros_like_a_full_mask(self, device, dtype):+ empty = kornia.contrib.distance_transform(torch.zeros(2, 3, 5, 7, device=device, dtype=dtype))+ full = kornia.contrib.distance_transform(torch.ones(2, 3, 5, 7, device=device, dtype=dtype))+ assert torch.equal(empty, torch.zeros_like(empty))+ assert torch.equal(full, empty)++ def test_convention_a_value_below_one_shifts_the_distances_near_it(self, device, dtype):+ image = torch.zeros(1, 1, 23, 37, device=device, dtype=dtype)+ image[0, 0, 4, 9] = 0.5+ binary = (image > 0).to(dtype)+ out, ref = kornia.contrib.distance_transform(image), kornia.contrib.distance_transform(binary)+ shift = -0.35 * math.log(0.5) # 0.2426, -h * log(v) at the default h+ values = torch.stack([out[0, 0, 4, 9], out[0, 0, 4, 10]])+ self.assert_close(values, torch.tensor([shift, 1.0 + shift], device=device, dtype=dtype))+ self.assert_close(out[0, 0, 4, 30], ref[0, 0, 4, 30]) # beyond kernel_size // 2 the value does not matter+ # A source sharing the window adds to the soft minimum before the log, so the shift shrinks: with a 1 beside+ # the 0.5, (2, 3) rises by 0.1689, not 0.2426. Literals from dt(pair.double())[0, 0, 2, 3] and+ # dt((pair > 0).double())[0, 0, 2, 3] at the default h.+ pair = torch.zeros(1, 1, 7, 7, device=device, dtype=dtype)+ pair[0, 0, 3, 3] = 0.5+ pair[0, 0, 3, 4] = 1.0+ dt = kornia.contrib.distance_transform+ values = torch.stack([dt(pair)[0, 0, 2, 3], dt((pair > 0).to(dtype))[0, 0, 2, 3]])+ self.assert_close(values, torch.tensor([1.0753916230203424, 0.9065031851948744], device=device, dtype=dtype))++ def test_wart_distance_transform_diagonal_underestimate_5956(self, device, dtype):+ image = torch.zeros(1, 1, 23, 37, device=device, dtype=dtype)+ image[0, 0, 4, 9] = 1.0+ out = kornia.contrib.distance_transform(image)+ # Beyond kernel_size // 2 the result follows the ring count: (16, 21) is 12 rings away and comes out as+ # 11 + sqrt(2) = 12.414, while scipy.ndimage.distance_transform_edt(image == 0) gives 12 * sqrt(2) = 16.971.+ self.assert_close(out[0, 0, 16, 21], torch.tensor(11.0 + 2.0**0.5, device=device, dtype=dtype))++ def test_wart_distance_transform_soft_min_bias_5956(self, device, dtype):+ # Where several reached pixels share a window, the soft-min pulls the value below the nearest distance+ # (exact: 1, 14, 1, 1). Literals from the same calls in float64 at the default h = 0.35:+ # dt = distance_transform; [dt(line.double())[0, 0, 7, 10], dt(line.double())[0, 0, 20, 10],+ # dt(two.double())[0, 0, 2, 3], dt(hole.double())[0, 0, 2, 3]]+ line = torch.zeros(1, 1, 23, 37, device=device, dtype=dtype)+ line[0, 0, 6] = 1.0+ two = torch.zeros(1, 1, 5, 7, device=device, dtype=dtype)+ two[0, 0, 2, 2] = 1.0+ two[0, 0, 2, 4] = 1.0+ hole = torch.ones(1, 1, 5, 7, device=device, dtype=dtype)+ hole[0, 0, 2, 3] = 0.0+ dt = kornia.contrib.distance_transform+ values = torch.stack([dt(line)[0, 0, 7, 10], dt(line)[0, 0, 20, 10], dt(two)[0, 0, 2, 3], dt(hole)[0, 0, 2, 3]])+ expected = torch.tensor(+ [0.8327901098243616, 13.832790109824362, 0.7573984868040191, 0.42130015880291255],+ device=device,+ dtype=dtype,+ )+ self.assert_close(values, expected)++ def test_wart_distance_transform_mask_above_one_5977(self, device, dtype):+ # A source of value v contributes -h * log(v) instead of 0: at v = 2 its neighbour reads 1 - 0.35 * log(2)+ # = 0.7574 instead of 1, and at v = 255 and the default kernel_size and h every pixel reads 0, as if on the+ # foreground. A smaller h shrinks the shift: at h = 0.1 the neighbour reads 1 - 0.1 * log(255) = 0.4459.+ image = torch.zeros(1, 1, 9, 13, device=device, dtype=dtype)+ image[0, 0, 4, 6] = 1.0+ binary = kornia.contrib.distance_transform(image)+ self.assert_close(binary[0, 0, 4, 7], torch.tensor(1.0, device=device, dtype=dtype))+ doubled = kornia.contrib.distance_transform(2 * image)+ self.assert_close(doubled[0, 0, 4, 7], torch.tensor(1.0 - 0.35 * math.log(2.0), device=device, dtype=dtype))+ assert (kornia.contrib.distance_transform(255 * image) == 0).all()+ small_h = kornia.contrib.distance_transform(255 * image, h=0.1)+ self.assert_close(small_h[0, 0, 4, 7], torch.tensor(1.0 - 0.1 * math.log(255.0), device=device, dtype=dtype))+ assert binary.max() > 5diff --git a/tests/contrib/test_diamond_square.py b/tests/contrib/test_diamond_square.pyindex 389ecb0af..532cfd78b 100644--- a/tests/contrib/test_diamond_square.py+++ b/tests/contrib/test_diamond_square.py@@ -15,6 +15,8 @@# limitations under the License.#+import functools+import pytestimport torch@@ -65,8 +67,8 @@ class TestDiamondSquare(BaseTester):@pytest.mark.parametrize("size", [(17, 5), (10, 14), (5, 17)])def test_mean_field_is_flat(self, size, device):- # A-35/A-36: every seed node is U(0, 1) and each step mixes (1 - s) * neighbour mean + s * U(0, 1), so the- # expected field is 0.5 everywhere. main's minimum mean was 0.165 (17x5, 10x14, 5x17, 4000 draws).+ # Every seed node is U(0, 1) and each step mixes (1 - s) * neighbour mean + s * U(0, 1), so the expected field+ # is 0.5 everywhere. A biased seed and border step gave a minimum mean of 0.165 (17x5, 10x14, 5x17, 4000 draws).# Sizes with H != W; (5, 17) and (17, 5) have a 3x9 seed, which exercises the interior row-1 square centres.torch.manual_seed(0)out = kornia.contrib.diamond_square((4000, 1, *size), device=device, dtype=torch.float32)@@ -77,7 +79,8 @@ class TestDiamondSquare(BaseTester):if not supports_reflect_padding(device, dtype):pytest.skip("reflection_pad2d is unavailable for this device/dtype")- # A-35/A-36: interpolating a constant must return the constant (main: corners 1/3, border midpoints 4/3).+ # Interpolating a constant must return the constant (a biased seed and border step gave corners 1/3 and+ # border midpoints 4/3).def ones(shape, device=None, dtype=None):return torch.ones(shape, device=device, dtype=dtype)@@ -85,13 +88,13 @@ class TestDiamondSquare(BaseTester):self.assert_close(out, torch.ones_like(out))def test_signed_random_fn_fills_every_pixel(self, device):- # A-37: centres were chosen by value > 0, so torch.randn left 56 % of the pixels at exactly 0.+ # Centres chosen by value > 0 left 56 % of the pixels at exactly 0 for torch.randn.torch.manual_seed(0)out = kornia.contrib.diamond_square((200, 1, 17, 33), random_fn=torch.randn, device=device)assert (out == 0).float().mean().item() < 1e-3def test_tensor_roughness_follows_the_requested_dtype_and_device(self, device):- # A-38: a float64 CPU roughness returned float64 for dtype=float32 and crashed for device='mps'.+ # A float64 CPU roughness returned float64 for dtype=float32 and crashed for device='mps'.r = torch.tensor([0.5, 0.6], dtype=torch.float64)s = torch.tensor(1.0, dtype=torch.float64)out = kornia.contrib.diamond_square(@@ -103,17 +106,17 @@ class TestDiamondSquare(BaseTester):def test_integer_normalize_range(self, device, dtype):if not supports_reflect_padding(device, dtype):pytest.skip("reflection_pad2d is unavailable for this device/dtype")- # A-39: (0, 1) raised TypeError in normalize_min_max.+ # An integer range (0, 1) raised TypeError in normalize_min_max.out = kornia.contrib.diamond_square((1, 1, 9, 14), normalize_range=(0, 1), device=device, dtype=dtype)assert out.min() >= 0assert out.max() <= 1def test_seed_values(self, device, dtype):- # A-35: the right-edge midpoint used the opposite corner, and the interior row-1 square centres of a seed- # with K >= 5 were never interpolated. At recursion depth 0 the output is the 3xK seed itself. Expected+ # A seed that divided its corners and centre by 3, used the opposite corner for the right-edge midpoint and+ # never interpolated the interior row-1 square centres of K >= 5 gave 0.333 / 92.58 / 459.25 for the 3x3+ # corners, centre and right midpoint. At recursion depth 0 the output is the 3xK seed itself. Expected# values are worked by hand: a diamond centre is the mean of its four corners, a border midpoint the mean of- # its three neighbours, an interior row-1 point the mean of its four neighbours. main gave 0.333 / 92.58 /- # 459.25 for the 3x3 corners, centre and right midpoint.+ # its three neighbours, an interior row-1 point the mean of its four neighbours.def draw(values):def fn(shape, device=None, dtype=None):return torch.tensor(values, device=device, dtype=dtype).expand(shape).clone()@@ -143,3 +146,72 @@ class TestDiamondSquare(BaseTester):# the transposed path: a 5x3 output is the 3x5 seed transposedout5t = kornia.contrib.diamond_square((1, 1, 5, 3), random_fn=draw(values5), device=device, dtype=dtype)self.assert_close(out5t[0, 0], expected5.transpose(0, 1))++ def test_convention_update_rule(self, device, dtype):+ if not supports_reflect_padding(device, dtype):+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")++ # One level from a 3x5 seed: a new value is (1 - s) * mean(neighbours) + s * U, s = random_scale * roughness+ # = 0.25, U = 1, seed corner draws [[1, 2, 4], [8, 16, 32]] scaled by random_scale. Worked by hand (scaled+ # seed: corner 0.5, centre 3.375, top midpoint 1.625, left midpoint 2.625; diamond (1, 3) = 2.271484375):+ # diamond (1, 1) = 0.75 * mean(0.5, 1.625, 2.625, 3.375) + 0.25 = 1.7734375+ # border square (0, 1) = 0.75 * mean(0.5, 1.625, 1.7734375) + 0.25 = 1.224609375 (three neighbours)+ # interior square (1, 2) = 0.75 * mean(1.625, 3.375, 1.7734375, 2.271484375) + 0.25 = 1.9459228515625+ def draw(shape, device=None, dtype=None):+ if shape[-2] == 2: # the seed's corner draws+ return torch.tensor([[1.0, 2.0, 4.0], [8.0, 16.0, 32.0]], device=device, dtype=dtype).expand(shape)+ return torch.ones(shape, device=device, dtype=dtype)++ out = kornia.contrib.diamond_square(+ (1, 1, 5, 9), roughness=0.5, random_scale=0.5, random_fn=draw, device=device, dtype=dtype+ )[0, 0]+ assert out.shape == (5, 9)+ # seed corner, seed centre, level-1 diamond centre, border square centre, interior square centre+ nodes = torch.stack([out[0, 0], out[2, 2], out[1, 1], out[0, 1], out[1, 2]])+ expected = torch.tensor([0.5, 3.375, 1.7734375, 1.224609375, 1.9459228515625], device=device, dtype=dtype)+ self.assert_close(nodes, expected)++ def test_convention_normalize_range_is_min_max_per_plane(self, device, dtype):+ if not supports_reflect_padding(device, dtype):+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")+ torch.manual_seed(0)+ out = kornia.contrib.diamond_square((3, 2, 9, 14), normalize_range=(-1.0, 1.0), device=device, dtype=dtype)+ self.assert_close(out.amin((-2, -1)), torch.full((3, 2), -1.0, device=device, dtype=dtype))+ self.assert_close(out.amax((-2, -1)), torch.full((3, 2), 1.0, device=device, dtype=dtype))++ def test_convention_random_fn_is_the_only_source_of_randomness(self, device):+ def device_state():+ if device.type == "cuda":+ return torch.cuda.get_rng_state(device)+ if device.type == "mps":+ return torch.mps.get_rng_state()+ return None++ g = torch.Generator(device=device)+ draw = functools.partial(torch.rand, generator=g)+ cpu_state, accelerator_state = torch.get_rng_state(), device_state()+ g.manual_seed(3)+ first = kornia.contrib.diamond_square((2, 1, 9, 14), random_fn=draw, device=device)+ g.manual_seed(3)+ second = kornia.contrib.diamond_square((2, 1, 9, 14), random_fn=draw, device=device)+ assert torch.equal(first, second)+ assert torch.equal(cpu_state, torch.get_rng_state())+ if accelerator_state is not None:+ assert torch.equal(accelerator_state, device_state())++ def test_wart_mean_field_drifts_for_random_scale_not_one_5963(self, device, dtype):+ if not supports_reflect_padding(device, dtype):+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")++ # The map is linear in the draws, so a constant 0.5 draw gives the expected field of torch.rand exactly.+ # With random_scale=0.5 the seed is 0.5 * 0.5 = 0.25, and each level mixes towards 0.5: a level-1 diamond is+ # 0.75 * 0.25 + 0.25 * 0.5 = 0.3125, a level-1 square 0.328125 at the border and 0.3359375 inside.+ def half(shape, device=None, dtype=None):+ return torch.full(shape, 0.5, device=device, dtype=dtype)++ out = kornia.contrib.diamond_square(+ (1, 1, 9, 17), random_scale=0.5, random_fn=half, device=device, dtype=dtype+ )[0, 0]+ nodes = torch.stack([out[0, 0], out[4, 8], out[2, 2], out[0, 2], out[2, 4]])+ expected = torch.tensor([0.25, 0.25, 0.3125, 0.328125, 0.3359375], device=device, dtype=dtype)+ self.assert_close(nodes, expected)diff --git a/tests/contrib/test_extract_tensor_patch.py b/tests/contrib/test_extract_tensor_patch.pyindex efa11cfb7..de16e8cbc 100644--- a/tests/contrib/test_extract_tensor_patch.py+++ b/tests/contrib/test_extract_tensor_patch.py@@ -266,13 +266,51 @@ class TestExtractTensorPatches(BaseTester):@pytest.mark.parametrize("padding", [(0, 0), (0, 0, 0, 0)])def test_all_zero_padding_means_no_padding(self, padding, device, dtype):- # A-5: a zero tuple used to switch off allow_auto_padding (N 6 instead of 12, last row/column dropped).+ # A truthy zero tuple switched off allow_auto_padding (N 6 instead of 12, last row/column dropped).img = torch.arange(1, 36, device=device, dtype=dtype).view(1, 1, 5, 7)expected = kornia.contrib.extract_tensor_patches(img, 2, 2, padding=0, allow_auto_padding=True)out = kornia.contrib.extract_tensor_patches(img, 2, 2, padding=padding, allow_auto_padding=True)assert out.shape == (1, 12, 1, 2, 2)self.assert_close(out, expected)+ def test_convention_patches_are_stacked_row_major_like_unfold(self, device, dtype):+ img = torch.arange(1, 57, device=device, dtype=dtype).view(1, 2, 4, 7)+ patches = kornia.contrib.extract_tensor_patches(img, (2, 3), (1, 2))+ # F.unfold's column order, reshaped to (B, N, C, h, w)+ unfold = torch.nn.functional.unfold(img, (2, 3), stride=(1, 2)).transpose(1, 2).reshape(1, -1, 2, 2, 3)+ assert patches.shape == (1, 9, 2, 2, 3)+ self.assert_close(patches, unfold)+ # Patch n starts at row (n // 3) * 1 and column (n % 3) * 2: left to right, then top to bottom.+ assert patches[0, :, 0, 0, 0].tolist() == [1, 3, 5, 8, 10, 12, 15, 17, 19]++ def test_convention_four_tuple_padding_is_top_bottom_left_right(self, device, dtype):+ img = torch.arange(1, 13, device=device, dtype=dtype).view(1, 1, 3, 4)+ out = kornia.contrib.extract_tensor_patches(img, (4, 6), padding=(1, 0, 0, 2))+ # (top, bottom, left, right) = (1, 0, 0, 2) is F.pad's (left, right, top, bottom) = (0, 2, 1, 0)+ self.assert_close(out[:, 0], torch.nn.functional.pad(img, (0, 2, 1, 0)))+ out = kornia.contrib.extract_tensor_patches(img, (5, 8), padding=(1, 2)) # (ph, pw) on each side+ self.assert_close(out[:, 0], torch.nn.functional.pad(img, (2, 2, 1, 1)))++ def test_convention_auto_padding_puts_the_odd_pixel_bottom_right(self, device, dtype):+ assert kornia.contrib.compute_padding((4, 5), 3, 3) == (1, 1, 0, 1)+ assert kornia.contrib.compute_padding((5, 4), 3, 3) == (0, 1, 1, 1)+ assert kornia.contrib.compute_padding((2, 3), (4, 4), 1) == (1, 1, 0, 1) # smaller than the window: one window+ img = torch.arange(1, 21, device=device, dtype=dtype).view(1, 1, 4, 5)+ patches = kornia.contrib.extract_tensor_patches(img, 3, 3, allow_auto_padding=True)+ assert patches.shape == (1, 4, 1, 3, 3)+ assert patches[0, 0, 0].tolist() == [[0, 0, 0], [1, 2, 3], [6, 7, 8]]+ assert patches[0, 3, 0].tolist() == [[14, 15, 0], [19, 20, 0], [0, 0, 0]]++ def test_convention_explicit_padding_switches_off_auto_padding_and_the_fit_warning(self, device, dtype):+ img = torch.arange(1, 36, device=device, dtype=dtype).view(1, 1, 5, 7)+ with warnings.catch_warnings():+ warnings.simplefilter("error")+ # One row of bottom padding: the 7 columns still do not fit stride 2, and the last one is dropped silently.+ out = kornia.contrib.extract_tensor_patches(img, 2, 2, padding=(0, 1, 0, 0), allow_auto_padding=True)+ assert out.shape == (1, 9, 1, 2, 2)+ assert not (out == 35).any()+ assert kornia.contrib.extract_tensor_patches(img, 2, 2, allow_auto_padding=True).shape == (1, 12, 1, 2, 2)+@pytest.mark.parametrize("argument", ["window_size", "stride"])@pytest.mark.parametrize("value", [0, (1, 0), -1])diff --git a/tests/contrib/test_hist_match.py b/tests/contrib/test_hist_match.pyindex f1d161460..2265521bd 100644--- a/tests/contrib/test_hist_match.py+++ b/tests/contrib/test_hist_match.py@@ -149,26 +149,26 @@ class TestHistMatch(BaseTester):assert torch.equal(kornia.contrib.interp(xp, xp, fp), fp)def test_interp_left_of_a_repeated_first_knot(self, device, dtype):- # A-31: np.interp([-1, 0, 0.5], [0, 0, 1], [5, 6, 7]) == [5, 6, 6.5]; kornia returned 6.0 left of the step.+ # np.interp([-1, 0, 0.5], [0, 0, 1], [5, 6, 7]) == [5, 6, 6.5]; 6.0 was returned left of the step.x = torch.tensor([-1.0, 0.0, 0.5], device=device, dtype=dtype)xp = torch.tensor([0.0, 0.0, 1.0], device=device, dtype=dtype)fp = torch.tensor([5.0, 6.0, 7.0], device=device, dtype=dtype)assert kornia.contrib.interp(x, xp, fp).tolist() == [5.0, 6.0, 6.5]def test_matching_an_image_to_itself_is_the_identity(self, device, dtype):- # A-21: 132 (float32) / 178 (float64) of 5328 pixels changed.+ # An interp inexact at its knots changed 132 (float32) / 178 (float64) of these 5328 pixels.g = torch.Generator().manual_seed(0)x = (torch.rand(2, 3, 24, 37, generator=g) * 255).round().to(device, dtype)assert torch.equal(kornia.contrib.histogram_matching(x, x), x)def test_uint8_result_survives_a_uint8_cast(self, device):- # A-21: [3, 1, 2] onto [10, 20, 30] gave [29.999998, 10, 20], i.e. 29 after .to(torch.uint8).+ # An interp inexact at its knots gave [29.999998, 10, 20] for [3, 1, 2] onto [10, 20, 30], 29 as uint8.src = torch.tensor([3, 1, 2], dtype=torch.uint8, device=device)tpl = torch.tensor([10, 20, 30], dtype=torch.uint8, device=device)assert kornia.contrib.histogram_matching(src, tpl).to(torch.uint8).tolist() == [30, 10, 20]def test_float32_output_stays_inside_the_template_range(self, device):- # A-22: #5794's range guarantee leaked one ulp in 24-49 of 300 random float32 pairs.+ # An interp inexact at its knots left the template range by one ulp for some random float32 pairs.outside = 0for seed in range(300):g = torch.Generator().manual_seed(seed)@@ -353,8 +353,7 @@ class TestHistMatch(BaseTester):assert out.tolist() == [float("inf")]def test_jit_script(self, device, dtype):- # Codex review on #5960: a recursive interp (for the complex parts) made both public functions unscriptable,- # also for real inputs; main (4863aed8a) scripted them.+ # A recursive interp (for the complex parts) made both public functions unscriptable, also for real inputs.interp_script = torch.jit.script(kornia.contrib.interp)x = torch.linspace(-1.0, 2.0, 13, device=device, dtype=dtype)xp = torch.tensor([0.0, 0.5, 1.0], device=device, dtype=dtype)@@ -369,3 +368,38 @@ class TestHistMatch(BaseTester):template = (torch.rand(1, 3, 10, 7, generator=g) ** 2).to(device, dtype)matched = torch.jit.script(kornia.contrib.histogram_matching)(source, template)self.assert_close(matched, kornia.contrib.histogram_matching(source, template))++ def test_convention_histogram_matching_pools_every_element(self, device, dtype):+ source = torch.tensor([0.1, 0.4, 0.2, 0.3, 0.6, 0.5], device=device, dtype=dtype).view(2, 1, 1, 3)+ template = torch.arange(1, 7, device=device, dtype=dtype).view(2, 1, 1, 3)+ # skimage 0.26.0: match_histograms(source, template, channel_axis=None) -> [[1, 4, 2], [3, 6, 5]].+ # Matching each sample on its own would give [2, 6, 4] for both.+ expected = torch.tensor([1.0, 4.0, 2.0, 3.0, 6.0, 5.0], device=device, dtype=dtype).view(2, 1, 1, 3)+ self.assert_close(kornia.contrib.histogram_matching(source, template), expected)++ def test_convention_integer_source_returns_float32_between_template_values(self, device):+ source = torch.tensor([0, 1, 2], dtype=torch.uint8, device=device)+ out = kornia.contrib.histogram_matching(source, torch.tensor([0, 10], dtype=torch.uint8, device=device))+ assert out.dtype == torch.float32+ # skimage 0.26.0 match_histograms gives [0, 3.333, 10] (in float64)+ self.assert_close(out, torch.tensor([0.0, 10.0 / 3.0, 10.0], device=device))++ def test_convention_interp_extrapolates_where_np_interp_clamps(self, device, dtype):+ xp = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=dtype)+ fp = torch.tensor([4.0, 2.0, 0.0], device=device, dtype=dtype)+ x = torch.tensor([[0.0, 0.5], [4.0, 6.0]], device=device, dtype=dtype)+ # np.interp([0, 0.5, 4, 6], [1, 2, 3], [4, 2, 0]) -> [4, 4, 0, 0]+ expected = torch.tensor([[6.0, 5.0], [-2.0, -6.0]], device=device, dtype=dtype)+ self.assert_close(kornia.contrib.interp(x, xp, fp), expected)++ def test_wart_interp_integer_x_with_half_fp_overflows_5967(self, device):+ # The weight is formed in float16 from integer differences above 65504. x = 100000 gives NaN where the right+ # value is 1.0; x = 60000 overflows only the segment width and gives a silent 0.0 where the right value is 0.6.+ x = torch.tensor([100000, 60000], device=device)+ xp = torch.tensor([0, 200000], device=device)+ out = kornia.contrib.interp(x, xp, torch.tensor([0.0, 2.0], device=device, dtype=torch.float16))+ assert out.dtype == torch.float16+ assert torch.isnan(out[0])+ assert out[1].item() == 0.0+ reference = kornia.contrib.interp(x, xp, torch.tensor([0.0, 2.0], device=device))+ self.assert_close(reference, torch.tensor([1.0, 0.6], device=device))diff --git a/tests/contrib/test_image_stitcher.py b/tests/contrib/test_image_stitcher.pyindex 44f9bdcea..7798213b8 100644--- a/tests/contrib/test_image_stitcher.py+++ b/tests/contrib/test_image_stitcher.py@@ -114,7 +114,7 @@ class TestImageStitcher(BaseTester):@pytest.mark.parametrize("img_dtype", [torch.float32, torch.float16, torch.bfloat16])@pytest.mark.parametrize("shift", [40.0, 40.5, 40.7])def test_subpixel_shift_has_no_dark_seam(self, shift, img_dtype, device):- # C-12: the mask was warped with nearest and the image bilinearly: s = 40.5 left a dark column (error 0.43),+ # A mask warped with nearest and an image warped bilinearly: s = 40.5 left a dark column (error 0.43),# s = 40.7 an extra dark trailing column (width 97, truth 96). The mask and the image share one warp, so they# share the sampling grid in half precision too (on MPS a half image keeps a half grid).torch.manual_seed(0)@@ -141,7 +141,7 @@ class TestImageStitcher(BaseTester):@pytest.mark.parametrize("img_dtype", [torch.float32, torch.float16])def test_image_and_mask_share_one_warp(self, img_dtype, device):- # I2: on MPS a half image is sampled on a half grid; a mask warped in a separate (float32) call lands on another+ # On MPS a half image is sampled on a half grid; a mask warped in a separate (float32) call lands on another# grid and marks pixels the image samples outside of as covered. One call keeps both on the same grid.left, right = _render(0, 64).to(device, img_dtype), _render(40.5, 56).to(device, img_dtype)stitcher = kornia.contrib.ImageStitcher(_ShiftMatcher([40.5]))@@ -177,7 +177,7 @@ class TestImageStitcher(BaseTester):stitcher.estimate_transform(keypoints0=kp, keypoints1=kp, batch_indexes=idx)def test_unmatched_sample_is_named(self, device):- # C-15: one unmatched sample failed the batch with grid_sampler's batch-size error.+ # One unmatched sample failed the batch with grid_sampler's batch-size error.left = torch.cat([_render(0, 64)] * 2).to(device)right = torch.cat([_render(40, 56), _render(30, 56)]).to(device)with pytest.raises(RuntimeError, match="sample 1"):@@ -245,10 +245,10 @@ class TestImageStitcher(BaseTester):@pytest.mark.parametrize("autocast_dtype", [torch.float16, torch.bfloat16])def test_float32_warp_under_autocast_keeps_the_border(self, autocast_dtype, device):- # Codex review 5529721894: under autocast the warp's homography matmuls ran in half precision, the coverage of- # completely covered border pixels fell below the float32 tolerance, and they were dropped: black pixels in- # the new columns and the panorama one column short (66, truth 67). The conftest skips tests named "autocast"- # on MPS; the same case failed there and passes with the fix.+ # Under autocast the warp's homography matmuls ran in half precision, the coverage of completely covered+ # border pixels fell below the float32 tolerance, and they were dropped: black pixels in the new columns and+ # the panorama one column short (66, truth 67). The conftest skips tests named "autocast" on MPS, where the+ # same case applies.if not torch.amp.is_autocast_available(device.type):pytest.skip(f"autocast is not available on {device.type}")left, right = torch.ones(1, 3, 48, 64, device=device), torch.ones(1, 3, 48, 64, device=device)@@ -408,3 +408,31 @@ class TestImageStitcher(BaseTester):stitcher = kornia.contrib.ImageStitcher(matcher).to(device=device, dtype=dtype)with pytest.raises(RuntimeError):stitcher(sample1, sample2)++ def test_convention_panorama_is_in_the_left_frame_and_the_right_image_wins_the_overlap(self, device, dtype):+ left, right = _render(0, 64).to(device, dtype), _render(40, 56).to(device, dtype)+ right[..., :24] = 0.25 # columns 40..63 of the panorama, where the left image also has content+ with torch.no_grad():+ out = kornia.contrib.ImageStitcher(_ShiftMatcher([40.0]))(left, right)+ assert out.shape == (1, 3, 48, 96) # the left image's height; the empty trailing columns are cropped+ self.assert_close(out[..., :40], left[..., :40])+ self.assert_close(out[..., 40:64], torch.full_like(out[..., 40:64], 0.25))+ self.assert_close(out[..., 64:], right[..., 24:], rtol=2e-2, atol=2e-2) # resampled through the homography++ def test_convention_a_batch_is_cropped_to_its_widest_sample(self, device):+ left = torch.cat([_render(0, 64)] * 2).to(device)+ right = torch.cat([_render(20, 56), _render(40, 56)]).to(device)+ with torch.no_grad():+ out = kornia.contrib.ImageStitcher(_ShiftMatcher([20.0, 40.0]))(left, right)+ assert out.shape == (2, 3, 48, 96)+ assert (out[0, ..., 76:] == 0).all() # the narrower sample keeps empty trailing columns++ def test_convention_image_stitcher_postprocess_gap_5971(self, device, dtype):+ stitcher = kornia.contrib.ImageStitcher(nn.Identity())+ image = torch.arange(6, device=device, dtype=dtype).view(1, 1, 1, 6).expand(1, 3, 4, 6)+ gap = torch.tensor([1.0, 0, 1, 1, 0, 0], device=device, dtype=dtype).view(1, 1, 1, 6).expand(1, 3, 4, 6)+ # a gap in the coverage is kept: the crop ends at the last covered column+ assert stitcher.postprocess(image, gap).shape[-1] == 4+ empty_first = torch.tensor([0.0, 1, 1, 0, 0, 0], device=device, dtype=dtype).view(1, 1, 1, 6).expand(1, 3, 4, 6)+ # an uncovered first column is kept and the empty suffix is still dropped+ assert stitcher.postprocess(image, empty_first).shape[-1] == 3diff --git a/tests/contrib/test_kmeans.py b/tests/contrib/test_kmeans.pyindex 9779e0c49..45ffc024f 100644--- a/tests/contrib/test_kmeans.py+++ b/tests/contrib/test_kmeans.py@@ -254,7 +254,7 @@ class TestKMeans(BaseTester):).to(device, dtype)def test_zero_tolerance_stops_at_the_fixed_point(self, device, dtype):- # B-25: tolerance=0.0 with the default max_iterations=0 never returned.+ # tolerance=0.0 with the default max_iterations=0 never returned.X = self._blobs(device, dtype)km = kornia.contrib.KMeans(3, X[[0, 60, 120]].clone(), tolerance=0.0)calls = {"n": 0}@@ -277,7 +277,7 @@ class TestKMeans(BaseTester):kornia.contrib.KMeans(3, None, tolerance=-1.0)def test_refit_samples_fresh_initial_centres(self, device, dtype):- # B-26: the second fit reused the first fit's sampled centres (and raised for another dimension).+ # A second fit reused the first fit's sampled centres (and raised for another dimension).km = kornia.contrib.KMeans(3, None, max_iterations=5, seed=0)km.fit(torch.rand(180, 2, device=device, dtype=dtype))X5 = torch.rand(100, 5, device=device, dtype=dtype) + 100@@ -286,13 +286,13 @@ class TestKMeans(BaseTester):assert (km.cluster_centers >= 100).all()def test_float16_distances_do_not_overflow(self, device):- # B-29: float16 squared distances overflowed to inf, so argmin returned [0, 0]; float64 gives [1, 0].+ # float16 squared distances overflowed to inf, so argmin returned [0, 0]; float64 gives [1, 0].c = torch.tensor([[0.0, 0.0, 0.0], [100.0, 0.0, 0.0]], device=device, dtype=torch.float16)p = torch.tensor([[255.0, 255.0, 255.0], [10.0, 200.0, 190.0]], device=device, dtype=torch.float16)assert kornia.contrib.KMeans(2, c, tolerance=None, max_iterations=1).predict(p).tolist() == [1, 0]def test_float16_fit_distances_do_not_overflow(self, device):- # B-29 in fit: the same overflow sent both points to cluster 0 and reseeded cluster 1 at random.+ # The same float16 overflow in fit sent both points to cluster 0 and reseeded cluster 1 at random.c = torch.tensor([[0.0, 0.0, 0.0], [100.0, 0.0, 0.0]], device=device, dtype=torch.float16)p = torch.tensor([[255.0, 255.0, 255.0], [10.0, 200.0, 190.0]], device=device, dtype=torch.float16)km = kornia.contrib.KMeans(2, c, tolerance=None, max_iterations=1)@@ -384,3 +384,32 @@ class TestKMeans(BaseTester):km = kornia.contrib.KMeans(2, torch.rand(2, 2, device=device, dtype=dtype), max_iterations=1)with pytest.raises(ShapeError):km.predict(torch.rand(4, 2, 1, device=device, dtype=dtype))++ @pytest.mark.parametrize(+ ("tolerance", "max_iterations", "updates"),+ [(0.25, 0, 1), (0.2, 0, 2), (None, 1, 1)],+ ids=["squared-shift-at-tolerance", "squared-shift-above-tolerance", "max-iterations"],+ )+ def test_convention_stopping_rule(self, tolerance, max_iterations, updates, device, dtype):+ # The first update moves each centre by 0.25 (to 0.5 and 10.5): the summed shift is 0.5 and its square 0.25,+ # which is compared with tolerance using <=. The second update moves nothing.+ X = torch.tensor([[0.0], [1.0], [10.0], [11.0]], device=device, dtype=dtype)+ km = kornia.contrib.KMeans(+ 2, torch.tensor([[0.25], [10.25]], device=device, dtype=dtype), tolerance, max_iterations+ )+ calls = []+ original = km._pairwise_euclidean_distance+ km._pairwise_euclidean_distance = lambda a, b: calls.append(1) or original(a, b)+ km.fit(X)+ assert len(calls) == updates + 1 # one distance per update, plus the final assignment+ self.assert_close(km.cluster_centers, torch.tensor([[0.5], [10.5]], device=device, dtype=dtype))++ def test_convention_seed_reseeds_the_global_generator(self):+ kornia.contrib.KMeans(3, None, seed=0)+ drawn = torch.rand(4)+ torch.manual_seed(0)+ assert torch.equal(drawn, torch.rand(4))++ def test_convention_a_tie_goes_to_the_first_cluster(self, device, dtype):+ km = kornia.contrib.KMeans(2, torch.tensor([[0.0], [1.0]], device=device, dtype=dtype), None, 1)+ assert km.predict(torch.tensor([[0.5]], device=device, dtype=dtype)).tolist() == [0]diff --git a/tests/contrib/test_lambda_module.py b/tests/contrib/test_lambda_module.pyindex 04ee8aae8..7222c7b69 100644--- a/tests/contrib/test_lambda_module.py+++ b/tests/contrib/test_lambda_module.py@@ -65,3 +65,10 @@ class TestLambdaModule(BaseTester):def test_non_callable_message_names_the_parameter(self):with pytest.raises(TypeError, match="func should be callable"):kornia.contrib.Lambda(3)++ def test_convention_the_return_value_of_func_is_passed_through(self, device, dtype):+ x = torch.zeros(1, 2, device=device, dtype=dtype)+ out = kornia.contrib.Lambda(lambda img, k, *, tag: (img + k, tag))(x, 2, tag="aux")+ assert isinstance(out, tuple)+ self.assert_close(out[0], x + 2)+ assert out[1] == "aux"diff --git a/tests/tracking/test_planar_tracking.py b/tests/tracking/test_planar_tracking.pyindex 9747ce5f4..da53a8e63 100644--- a/tests/tracking/test_planar_tracking.py+++ b/tests/tracking/test_planar_tracking.py@@ -21,6 +21,7 @@ from unittest.mock import MagicMockimport pytestimport torch+from kornia.contrib import ImageStitcherfrom kornia.core._compat import torch_version_lefrom kornia.core.exceptions import BaseErrorfrom kornia.feature import DescriptorMatcher, GFTTAffNetHardNet, LocalFeatureMatcher, LoFTR, SIFTFeature@@ -89,7 +90,7 @@ class TestHomographyTrackerCaching:return LocalFeatureMatcher(SIFTFeature(300), DescriptorMatcher("snn", 0.9))def test_target_features_are_extracted_once(self):- # C-4: the nn.Module guard never matched a method, so the target was re-extracted on every frame.+ # An nn.Module guard never matched a method, so the target was re-extracted on every frame.initial, fast = self._sift_matcher(), self._sift_matcher()shapes = []for m in (initial, fast):@@ -114,7 +115,7 @@ class TestHomographyTrackerCaching:assert calls == [(1, 1, 64, 80)] # only the pre-warped frame, at the target's sizedef test_loftr_without_cached_features_gets_image0(self):- # A target assigned directly, without set_target, has no cached features0, so LoFTR needs image0 (as on main).+ # A target assigned directly, without set_target, has no cached features0, so LoFTR needs image0.loftr = LoFTR(None)keys = []loftr.register_forward_pre_hook(lambda mod, args: keys.append(sorted(args[0])))@@ -148,7 +149,7 @@ class TestHomographyTrackerCaching:return LoFTR(None, config)def test_loftr_swapped_after_set_target_matches_an_uncached_call(self):- # CodeRabbit 4277422844: a LoFTR swapped in after set_target was fed the old LoFTR's cached features0.+ # A LoFTR swapped in after set_target was fed the old LoFTR's cached features0.old, new = self._loftr(1), self._loftr(2)tracker = HomographyTracker(old, self._sift_matcher(), minimum_inliers_num=10**6)target, frame = _texture(64, 80), _texture(72, 96, seed=1)@@ -190,14 +191,14 @@ class TestHomographyTrackerCaching:assert in_tracker == [(1, 1, 64, 80)] * 3 # the target once after the swap, then the warped frame twicedef test_track_next_frame_without_a_prior_raises(self):- # C-5: UnboundLocalError on Hwarp.+ # It raised UnboundLocalError on Hwarp.tracker = _make_tracker()tracker.set_target(torch.rand(1, 1, 8, 9))with pytest.raises(BaseError, match="previous homography"):tracker.track_next_frame(torch.rand(1, 1, 8, 9))def test_fewer_than_four_matches_is_a_failed_match(self):- # C-6: minimum_inliers_num < 4 let 3 matches reach RANSAC, which raised.+ # minimum_inliers_num < 4 let 3 matches reach RANSAC, which raised.tracker = _make_tracker(minimum_inliers_num=0)tracker.set_target(torch.rand(1, 1, 8, 9))tracker.initial_matcher.return_value = _match_dict(3, torch.device("cpu"), torch.float32)@@ -216,7 +217,7 @@ class TestHomographyTrackerCaching:assert tracker.previous_homography is Nonedef test_set_target_starts_a_new_track(self):- # C-7 (controller ruling): the old prior maps the old target's coordinates.+ # The old prior maps the old target's coordinates.tracker = _make_tracker()tracker.set_target(torch.rand(1, 1, 8, 9))tracker.previous_homography = torch.eye(3)@@ -224,7 +225,7 @@ class TestHomographyTrackerCaching:assert tracker.previous_homography is Nonedef test_target_assigned_directly_starts_a_new_track(self):- # CodeRabbit 4277848437: after a target was assigned directly, forward tracked it with the old target's prior.+ # After a target was assigned directly, forward tracked it with the old target's prior.tracker = _make_tracker()tracker.set_target(torch.rand(1, 1, 8, 9))tracker.initial_matcher.return_value = _match_dict(20, torch.device("cpu"), torch.float32)@@ -488,3 +489,63 @@ class TestHomographyTracker(BaseTester):homography, success = tracker(data["image1"])assert successself.assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)+++_H_TRUE = torch.tensor([[1.1, 0.05, 7.0], [-0.03, 0.95, 4.0], [1e-4, -2e-4, 1.0]])+++class _ExactMatcher(torch.nn.Module):+ """Exact correspondences ``keypoints1 = _H_TRUE(keypoints0)``, in float32 whatever the image dtype."""++ def forward(self, data: dict) -> dict:+ ys, xs = torch.meshgrid(torch.arange(3.0, 40, 4), torch.arange(3.0, 50, 4), indexing="ij")+ kp0 = torch.stack([xs.flatten(), ys.flatten()], -1)+ kp1 = transform_points(_H_TRUE[None], kp0[None])[0]+ return {"keypoints0": kp0, "keypoints1": kp1, "batch_indexes": torch.zeros(len(kp0), dtype=torch.long)}+++class TestHomographyTrackerConventions:+ def test_convention_homography_maps_target_pixels_to_frame_pixels(self):+ tracker = HomographyTracker(_ExactMatcher(), _ExactMatcher(), minimum_inliers_num=10)+ tracker.set_target(torch.rand(1, 1, 44, 54))+ H, ok = tracker(torch.rand(1, 1, 60, 70))+ assert ok+ torch.testing.assert_close(H / H[2, 2], _H_TRUE, rtol=1e-4, atol=1e-4)++ def test_convention_target_is_not_a_buffer(self):+ tracker = HomographyTracker(_ExactMatcher(), _ExactMatcher())+ tracker.set_target(torch.rand(1, 1, 44, 54))+ tracker.to(torch.float64)+ assert "target" not in dict(tracker.named_buffers())+ assert tracker.dtype == torch.float32 # .to() leaves the target behind: call set_target again++ def test_convention_default_ransac_is_looser_than_image_stitcher(self):+ tracker = HomographyTracker(_ExactMatcher(), _ExactMatcher())+ assert (tracker.ransac.inl_th, tracker.ransac.max_iter) == (5.0, 10)+ stitcher = ImageStitcher(LocalFeatureMatcher(SIFTFeature(10), DescriptorMatcher("snn", 0.9)))+ assert (stitcher.ransac.inl_th, stitcher.ransac.max_iter) == (2.0, 10)++ def test_convention_target_changed_in_place_keeps_its_cached_features(self):+ matcher = LocalFeatureMatcher(SIFTFeature(100), DescriptorMatcher("snn", 0.9))+ calls = []+ matcher.local_feature.register_forward_hook(lambda mod, inp, out: calls.append(tuple(inp[0].shape)))+ tracker = HomographyTracker(matcher, matcher, minimum_inliers_num=10**6)+ target = _texture(64, 80)+ tracker.set_target(target)+ cached = tracker.target_initial_representation["descriptors"].clone()+ calls.clear()+ target.mul_(0.5).add_(0.2)+ tracker(_texture(72, 96, seed=1))+ assert calls == [(1, 1, 72, 96)] # the frame only+ assert torch.equal(tracker.target_initial_representation["descriptors"], cached)++ @pytest.mark.parametrize("half", [torch.float16, torch.bfloat16])+ def test_wart_half_precision_tracking_fails_on_the_second_frame_5968(self, half):+ # The first frame returns a float32 homography (float32 keypoints); the second warps the half frame with its+ # float32 inverse and raises.+ tracker = HomographyTracker(_ExactMatcher(), _ExactMatcher(), minimum_inliers_num=10)+ tracker.set_target(torch.rand(1, 1, 44, 54, dtype=half))+ _, ok = tracker(torch.rand(1, 1, 60, 70, dtype=half))+ assert ok+ with pytest.raises(RuntimeError):+ tracker(torch.rand(1, 1, 60, 70, dtype=half))