π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(feature): convention blocks and pins for the patch descriptors (#5836)
Dmytro Mishkin83655d28873c
diff --git a/changelog.d/5836.added.md b/changelog.d/5836.added.mdnew file mode 100644index 000000000..7f0cd55da--- /dev/null+++ b/changelog.d/5836.added.md@@ -0,0 +1 @@+Document the conventions of the `kornia.feature` patch descriptors (`SIFTDescriptor`, `DenseSIFTDescriptor`, `SIFTDescriptorFromPyramid`, `HardNet`, `HardNet8`, `SOSNet`, `TFeat`, `HyNet`, `FilterResponseNorm2d`, `TLU` and `MKDDescriptor`) as Convention blocks and pointers: the patch shape and sampling, which intensity changes leave a descriptor unchanged, the output norm and width, SIFT clipping and RootSIFT, and the dense and pyramid SIFT cell geometry.diff --git a/docs/source/feature.descriptors.rst b/docs/source/feature.descriptors.rstindex 47e916b7a..8279404f0 100644--- a/docs/source/feature.descriptors.rst+++ b/docs/source/feature.descriptors.rst@@ -49,12 +49,11 @@ in a few octaves. See the recordedGeneral affine frames use an approximate angular remapping and spatial pooling;this is not numerically identical to patch extraction.-Its ``orient_and_describe(image, lafs)`` method additionally estimates orientation.-The automatic orientation used by ``SIFTFeature(descriptor_backend="pyramid")``-was repaired in `#5762 <https://github.com/kornia/kornia/pull/5762>`_ by integrating-smoothed gradients before angular binning. `#5748 <https://github.com/kornia/kornia/issues/5748>`_-remains open for its performance and accuracy acceptance criteria. That validation-does not invalidate the descriptor-only ``forward`` use on supplied oriented LAFs.+Its ``orient_and_describe(image, lafs)`` method additionally estimates orientation,+integrating smoothed gradients before angular binning; this is the orientation+used by ``SIFTFeature(descriptor_backend="pyramid")``. Its performance and accuracy+acceptance criteria are tracked in `#5748 <https://github.com/kornia/kornia/issues/5748>`_;+they do not concern the descriptor-only ``forward`` use on supplied oriented LAFs.The :ref:`validation and possible deprecation plan <sift-pipelines>` retains allthree standalone descriptor interfaces.diff --git a/docs/source/feature.local_features.rst b/docs/source/feature.local_features.rstindex 329bc90a0..533a77f60 100644--- a/docs/source/feature.local_features.rst+++ b/docs/source/feature.local_features.rst@@ -52,8 +52,7 @@ always faster.* - ``SIFTFeature(..., descriptor_backend="pyramid")``- The same multiresolution detector; a separate image pyramid supplies smoothedgradients for orientation and pooled histogram maps for description.- - Its automatic orientation was repaired in #5762. Use it for measured- multiresolution workloads; #5748 remains open for the validation below.+ - Measured multiresolution workloads; see the validation below.The two feature classes have different detector algorithms. :class:`SIFTFeature`applies a single-scale DoG response independently at each image resolution, with@@ -98,23 +97,22 @@ combination at the intended feature budget.Validation and possible deprecation^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-`#5762 <https://github.com/kornia/kornia/pull/5762>`_ repaired the automatic-orientation used by ``SIFTFeature(descriptor_backend="pyramid")``. It integrates-a 19x19 support of smoothed image gradients before angular binning, without-extracting image patches. The issue tracked in-`#5748 <https://github.com/kornia/kornia/issues/5748>`_ remains open: its-acceptance criteria include performance at 1024 features and Oxford accuracy at-2048 features. Promotion of this convenience combination requires recovered-accuracy and a demonstrated runtime or memory advantage on a stated workload.+The automatic orientation used by ``SIFTFeature(descriptor_backend="pyramid")``+integrates a 19x19 support of smoothed image gradients before angular binning,+without extracting image patches. Its acceptance criteria, tracked in+`#5748 <https://github.com/kornia/kornia/issues/5748>`_, include performance at+1024 features and Oxford accuracy at 2048 features. Promotion of this convenience+combination requires accuracy matching the patch backend and a demonstrated+runtime or memory advantage on a stated workload.Validation should compare with the patch backend at 1024 and 2048 features onIMC PhotoTourism pose estimation and Oxford homography estimation, reportingmatcher settings, device and timing methodology.-If repair does not establish those benefits, the plan is to deprecate this+If validation does not establish those benefits, the plan is to deprecate thisconvenience combination and remove it only after the :doc:`API stability policy</get-started/stability>` window: at least one minor release of warnings and a-documented replacement. No formal deprecation warning or removal version is-introduced here. This plan concerns the combination, not the standalone+documented replacement. No deprecation warning or removal version is set.+This plan concerns the combination, not the standalone:class:`SIFTDescriptorFromPyramid` descriptor-only interface; see:ref:`sift-descriptor-interfaces`.diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.pyindex 43616fd7d..8d7d102f1 100644--- a/kornia/feature/hardnet.py+++ b/kornia/feature/hardnet.py@@ -45,6 +45,23 @@ class HardNet(nn.Module):This is based on the original code from paper "Working hard to know your neighbor'smargins: Local descriptor learning loss". See :cite:`HardNet2017` for more details.+ Convention:+ - Patches are ``(B, 1, 32, 32)``, one grayscale channel, and another shape raises; ``patch_size`` is a class+ attribute. :func:`~kornia.feature.get_laf_descriptors` extracts such patches from LAFs at its default+ ``patch_size``, sampled as :func:`~kornia.feature.extract_patches_from_pyramid` describes+ (see :ref:`Local features <local-features-conventions>`).+ :class:`~kornia.feature.HardNet8`, :class:`~kornia.feature.SOSNet`, :class:`~kornia.feature.TFeat` and+ :class:`~kornia.feature.HyNet` take the same patches.+ - The intensity range does not matter: HardNet and HardNet8 standardise each patch to zero mean and unit+ standard deviation, and SOSNet and TFeat start with an ``InstanceNorm2d``, so :math:`a x + b` with+ :math:`a > 0` gives the same descriptor unless it leaves the patch nearly flat. That InstanceNorm adds+ ``1e-5`` to the variance, so for SOSNet and TFeat a low-contrast patch in ``[0, 1]`` can already give a+ different descriptor than the same patch in ``[0, 255]``. HyNet is invariant to a scale only; see its+ Convention block.+ - The descriptors have unit L2 norm, except TFeat's (see its Convention block); with ``pretrained=False``,+ HardNet and HardNet8 map a flat patch to an all-zero descriptor.+ - ``pretrained=False``, the default, leaves the weights randomly initialised.+Args:pretrained: Download and set pretrained weights to the model.@@ -98,7 +115,7 @@ class HardNet(nn.Module):@staticmethoddef _normalize_input(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:- """Normalize the input by batch."""+ """Standardise each patch to zero mean and unit standard deviation."""if is_mps_tensor_safe(x) or _is_tracing_or_exporting():# `torch.std_mean` is unsupported on MPS and decomposes to `prims.sum`, which has no ONNX lowering.mp = torch.mean(x, dim=(-3, -2, -1), keepdim=True)@@ -111,7 +128,7 @@ class HardNet(nn.Module):return (x - mp.detach()) / (sp.detach() + eps)def forward(self, input: torch.Tensor) -> torch.Tensor:- """Compute HardNet descriptors for normalized 32x32 patches.+ """Compute HardNet descriptors for grayscale 32x32 patches.Args:input: Grayscale patch tensor of shape :math:`(B, 1, 32, 32)`.@@ -138,6 +155,9 @@ class HardNet8(nn.Module):This is based on the original code from paper "Improving the HardNet Descriptor".See :cite:`HardNet2020` for more details.+ Convention:+ See the Convention block on :class:`~kornia.feature.HardNet`.+Args:pretrained: Download and set pretrained weights to the model. The 512-d features are projected to 128-d by aPCA stored with the weights; without them, the projection keeps the first 128 features.@@ -212,7 +232,7 @@ class HardNet8(nn.Module):@staticmethoddef _normalize_input(x: torch.Tensor, eps: float = 1e-7) -> torch.Tensor:- """Normalize the input by batch."""+ """Standardise each patch to zero mean and unit standard deviation."""if is_mps_tensor_safe(x) or _is_tracing_or_exporting():# `torch.std_mean` is unsupported on MPS and decomposes to `prims.sum`, which has no ONNX lowering.mp = torch.mean(x, dim=(-3, -2, -1), keepdim=True)@@ -231,7 +251,7 @@ class HardNet8(nn.Module):input: Grayscale patch tensor of shape :math:`(B, 1, 32, 32)`.Returns:- L2-normalized descriptor tensor after learned PCA projection.+ L2-normalized descriptor tensor with shape :math:`(B, 128)`, after the PCA projection."""KORNIA_CHECK_SHAPE(input, ["B", "1", "32", "32"])x_norm: torch.Tensor = self._normalize_input(input)diff --git a/kornia/feature/hynet.py b/kornia/feature/hynet.pyindex 36e4cb68a..80dd3aaa6 100644--- a/kornia/feature/hynet.py+++ b/kornia/feature/hynet.py@@ -40,19 +40,23 @@ urls["yosemite"] = [class FilterResponseNorm2d(nn.Module):- r"""Feature Response Normalization layer from 'Filter Response Normalization Layer: Eliminating Batch Dependence+ r"""Filter Response Normalization layer from 'Filter Response Normalization Layer: Eliminating Batch Dependencein the Training of Deep Neural Networks', see :cite:`FRN2019` for more details... math::- y = \gamma \times \frac{x}{\sqrt{\mathrm{E}[x^2]} + |\epsilon|} + \beta+ y = \gamma \frac{x}{\sqrt{\nu^2 + |\epsilon|}} + \beta+ Convention:+ - :math:`\nu^2` is the mean of :math:`x^2` over the ``H x W`` map of each sample and channel, so the output+ does not depend on the rest of the batch; no mean is subtracted. :math:`\gamma` (``weight``) and+ :math:`\beta` (``bias``) are per-channel parameters initialised to 1 and 0, applied only when ``is_scale``+ and ``is_bias`` are set.Args:num_features: number of channelseps: normalization constantis_bias: use biasis_scale: use scale- drop_rate: dropout rate,is_eps_leanable: if eps is learnableReturns:@@ -142,11 +146,15 @@ class FilterResponseNorm2d(nn.Module):class TLU(nn.Module):r"""TLU layer from 'Filter Response Normalization Layer: Eliminating Batch Dependence in the Training of Deep- Neural Networks, see :cite:`FRN2019` for more details. :math:`{\tau}` is learnable per channel.+ Neural Networks', see :cite:`FRN2019` for more details. :math:`{\tau}` is learnable per channel... math::y = \max(x, {\tau})+ Convention:+ - :math:`\tau` (``tau``) is a ``(1, num_features, 1, 1)`` parameter, one threshold per channel, initialised+ to -1.+Args:num_features: number of channels@@ -202,9 +210,17 @@ class HyNet(nn.Module):"HyNet: Learning Local Descriptor with Hybrid Similarity Measure and Triplet Loss".See :cite:`hynet2020` for more details.+ Convention:+ - It takes the ``(B, 1, 32, 32)`` patches of :class:`~kornia.feature.HardNet` and returns unit-norm rows, but+ its first layer is a :class:`~kornia.feature.FilterResponseNorm2d` on the raw patch, which divides by the root+ mean square and subtracts no mean, as in the reference implementation. A scale :math:`a x` with+ :math:`a > 0` therefore gives the same descriptor as long as the mean squares of the patch and of its scaled+ copy are both large compared with that layer's ``eps``, while an offset :math:`x + b` changes it: feed+ non-negative intensities such as ``[0, 1]`` or ``[0, 255]``, not mean-subtracted or standardised patches.+Args:pretrained: Download and set pretrained weights to the model.- is_bias: use bias in TLU layers+ is_bias: use bias in the convolution layers (the final 8 x 8 convolution has none either way)is_bias_FRN: use bias in FRN layersdim_desc: descriptor dimensionality,drop_rate: dropout rate,@@ -215,7 +231,7 @@ class HyNet(nn.Module):Shape:- Input: :math:`(B, 1, 32, 32)`- - Output: :math:`(B, 128)`+ - Output: :math:`(B, \text{dim\_desc})`Note:With float16 weights, the final BatchNorm keeps its running statistics in float32.diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.pyindex ce0a63451..bb051a121 100644--- a/kornia/feature/mkd.py+++ b/kornia/feature/mkd.py@@ -557,19 +557,32 @@ class MKDDescriptor(nn.Module):This is based on the paper "Understanding and Improving Kernel Local Descriptors".See :cite:`mukundan2019understanding` for more details.+ Convention:+ - Patches are ``(B, 1, patch_size, patch_size)``: ``patch_size`` must be the input's size, and another size+ raises ``ShapeError``. The kernels are centred on the patch centre :math:`(\text{patch\_size} - 1) / 2`.+ - The descriptor has unit L2 norm, and an intensity change :math:`a x + b` with :math:`a > 0` gives the same+ descriptor unless it leaves the patch nearly flat. The exception is a flat float16 patch with+ ``whitening=None``: the ``1e-8`` added to the gradient magnitudes underflows in float16, and the descriptor+ is all zero.+ - With whitening the descriptor is :math:`\min(\text{output\_dims}, E)` wide, where :math:`E` is the width of+ the kernel embedding: 238 for ``'concat'``, 175 for ``'polar'`` and 63 for ``'cart'``. With+ ``whitening=None`` it is that embedding, :math:`E` wide whatever ``output_dims`` says. Constructing a whitened+ descriptor loads its whitening model, and downloads it then if it is not cached yet; ``whitening=None``+ needs no download.+Args:patch_size: Input patch size in pixels.kernel_type: Parametrization of kernel ``'concat'``, ``'cart'``, ``'polar'``.whitening: Whitening transform to apply ``None``, ``'lw'``, ``'pca'``, ``'pcawt'``, ``'pcaws'``.training_set: Set that model was trained on ``'liberty'``, ``'notredame'``, ``'yosemite'``.- output_dims: Dimensionality reduction.+ output_dims: Width of the whitened descriptor, at most the embedding width; ignored with ``whitening=None``.Returns:- Explicit cartesian or polar embedding.+ Descriptors of the patches, of unit norm except as stated in the Convention block.Shape:- - Input: :math:`(B, 1, P, P)` with :math:`P` = ``patch_size``; the spatial encoding is precomputed for it.- - Output: :math:`(B, out_{dims})`.+ - Input: :math:`(B, 1, \text{patch\_size}, \text{patch\_size})`.+ - Output: :math:`(B, D)`, with :math:`D` as in the Convention block.Examples:>>> patches = torch.rand(23, 1, 32, 32)@@ -649,15 +662,13 @@ class MKDDescriptor(nn.Module):"""Compute Multiple Kernel Descriptor (MKD) vectors for image patches.Args:- patches: Grayscale patch tensor with shape :math:`(B, 1, P, P)`, where ``B`` is the number of patches- and :math:`P` is ``patch_size``.+ patches: Grayscale patch tensor with shape ``(B, 1, patch_size, patch_size)``.Returns:- Descriptor tensor with shape :math:`(B, D)`, where ``D`` is the configured- output descriptor dimension after optional whitening.+ Descriptor tensor with shape :math:`(B, D)`, with ``D`` as in the class's Convention block.Raises:- ShapeError: if ``patches`` is not :math:`(B, 1, P, P)`.+ ShapeError: if ``patches`` is not ``(B, 1, patch_size, patch_size)``."""if not isinstance(patches, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(patches)}")diff --git a/kornia/feature/sift/pyramid.py b/kornia/feature/sift/pyramid.pyindex e16e30a41..6ae3ca111 100644--- a/kornia/feature/sift/pyramid.py+++ b/kornia/feature/sift/pyramid.py@@ -53,12 +53,9 @@ class SIFTDescriptorFromPyramid(nn.Module):sharing one pyramid between orientation assignment and description. Thepyramid belongs to this descriptor; it is not reused from the detector.- Automatic orientation was repaired in- `#5762 <https://github.com/kornia/kornia/pull/5762>`_. The remaining- performance and accuracy acceptance criteria are tracked in- `#5748 <https://github.com/kornia/kornia/issues/5748>`_. The descriptor-only- ``forward(image, lafs)`` uses supplied oriented frames without estimating- their orientation. See+ The performance and accuracy acceptance criteria of its automatic+ orientation are tracked in+ `#5748 <https://github.com/kornia/kornia/issues/5748>`_. See:ref:`sift-descriptor-interfaces` for the distinct patch, dense-map andsupplied-frame descriptor contracts.@@ -80,6 +77,25 @@ class SIFTDescriptorFromPyramid(nn.Module):interval by its centre direction, and spatial pooling is performed in theimage pyramid before the affine footprint is sampled.+ Convention:+ - ``lafs`` are in the pixel frame of ``image``, with the layout of+ :func:`~kornia.feature.laf_from_center_scale_ori` (see :ref:`Local features <local-features-conventions>`).+ Cell ``(i, j)`` of the ``num_spatial_bins`` x ``num_spatial_bins`` grid is centred at ``c + A (u_j, u_i)``+ with ``u_k = (2 k + 1) / num_spatial_bins - 1``, at whichever octave the LAF selects: the cell centres of a+ ``num_spatial_bins``-pixel patch from :func:`~kornia.feature.extract_patches_from_pyramid`, row 0 on the+ frame's :math:`-y` side.+ - :meth:`orient_and_describe`, unless ``upright=True``, rotates each valid frame so that its dominant+ gradient, measured in the frame's own coordinates, points along the frame's :math:`+x` axis, whatever+ orientation the frame had. This is the orientation convention of :class:`~kornia.feature.LAFOrienter`, and it+ puts that gradient direction in the descriptor's angle bin 0.+ - A frame that :func:`~kornia.feature.laf_is_valid` rejects, such as the all-zero padding LAF, gets an all-zero+ descriptor, with or without RootSIFT, and :meth:`orient_and_describe` returns the frame unchanged.+ :class:`~kornia.feature.SIFTDescriptor` instead describes the flat patch that a zero LAF extracts by ``1e-5``+ in every entry with RootSIFT.+ - Clipping, RootSIFT (the default) and kornia's angle-major layout are those of+ :class:`~kornia.feature.SIFTDescriptor`, whose Convention block gives them;+ :func:`~kornia.feature.convert_sift_descriptor_layout` reorders the descriptors to OpenCV's.+Args:num_ang_bins: Number of descriptor angular bins.num_spatial_bins: Number of descriptor spatial bins per axis.@@ -96,9 +112,6 @@ class SIFTDescriptorFromPyramid(nn.Module):- image: :math:`(B, 1, H, W)`- lafs: :math:`(B, N, 2, 3)` in image pixel coordinates- descriptors: :math:`(B, N, num_ang_bins * num_spatial_bins^2)`-- The descriptors are in kornia's angle-major SIFT layout, as :class:`~kornia.feature.SIFTDescriptor`'s are;- :func:`~kornia.feature.convert_sift_descriptor_layout` reorders them to OpenCV's."""def __init__(diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.pyindex 6fea17154..4d6754a96 100644--- a/kornia/feature/siftdesc.py+++ b/kornia/feature/siftdesc.py@@ -156,6 +156,28 @@ def get_sift_bin_ksize_stride_pad(patch_size: int, num_spatial_bins: int) -> Tupclass SIFTDescriptor(nn.Module):r"""nn.Module which computes SIFT descriptors of given patches.+ Convention:+ - The input is a stack of grayscale patches, ``patch_size`` pixels square (41 by default; another size+ raises), with rows along :math:`+y` and columns along :math:`+x`, as+ :func:`~kornia.feature.extract_patches_from_pyramid` samples them from LAFs+ (see :ref:`Local features <local-features-conventions>`).+ - The output is in kornia's angle-major SIFT layout, which+ :func:`~kornia.feature.convert_sift_descriptor_layout` defines and reorders to OpenCV's. In the patch of a+ LAF oriented by :class:`~kornia.feature.LAFOrienter`, the dominant gradient direction it found points along+ :math:`+x`, the centre of angle bin 0.+ - The ``num_spatial_bins`` x ``num_spatial_bins`` grid of spatial cells and the Gaussian weighting window are+ both centred on the patch centre :math:`(\text{patch\_size} - 1) / 2`; ``get_sift_bin_ksize_stride_pad``+ gives the cell spacing and pooling kernel. A patch mirrored upside down therefore has a descriptor that is a+ permutation of the original's; so does a patch mirrored left to right when ``num_ang_bins`` is even, and a+ ``torch.rot90``-rotated one when ``num_ang_bins`` is a multiple of four, as the default 8 is.+ - The descriptor is L2-normalised, clipped at ``clipval`` and L2-normalised again, so an output entry can+ exceed ``clipval``. With ``rootsift=True``, the default, it is then L1-normalised and square-rooted+ (RootSIFT). Either way a row has unit L2 norm, except for a flat patch: it has no gradient and gives an+ all-zero descriptor, or ``1e-5`` in every entry with RootSIFT. OpenCV's ``cv2.SIFT`` returns the+ ``rootsift=False`` descriptor scaled to an L2 norm of about 512 and rounded to integers.+ - An intensity change :math:`a x + b` with :math:`a > 0` gives the same descriptor unless it leaves the patch+ nearly flat, so a patch in ``[0, 1]`` and the same patch in ``[0, 255]`` give one descriptor.+Args:patch_size: Input patch size in pixels.num_ang_bins: Number of angular bins.@@ -170,15 +192,6 @@ class SIFTDescriptor(nn.Module):- Input: :math:`(B, 1, \text{patch_size}, \text{patch_size})`- Output: :math:`(B, \text{num_ang_bins * num_spatial_bins ** 2})`- The output is in kornia's angle-major SIFT layout; :func:`~kornia.feature.convert_sift_descriptor_layout` reorders- it to OpenCV's.-- The ``num_spatial_bins`` x ``num_spatial_bins`` grid of spatial cells and the Gaussian weighting window are both- centred on the patch centre :math:`(\text{patch\_size} - 1) / 2`; :func:`get_sift_bin_ksize_stride_pad` gives the- cell spacing and pooling kernel. A patch mirrored upside down therefore has a descriptor that is a permutation of- the original's; so does a patch mirrored left to right when ``num_ang_bins`` is even, and a ``torch.rot90``-rotated- one when ``num_ang_bins`` is a multiple of four, as the default 8 is.-Example:>>> input = torch.rand(23, 1, 32, 32)>>> SIFT = SIFTDescriptor(32, 8, 4)@@ -376,8 +389,9 @@ def convert_sift_descriptor_layout(of the frame, with :math:`A` = ``num_ang_bins`` and :math:`S` = ``num_spatial_bins``:- ``"kornia"``, the layout of every kornia SIFT descriptor (:class:`~kornia.feature.SIFTDescriptor`,- :class:`~kornia.feature.SIFTDescriptorFromPyramid`, and :class:`~kornia.feature.SIFTFeature` and- :class:`~kornia.feature.SIFTFeatureScaleSpace` with either ``descriptor_backend``): angle-major, value+ :class:`~kornia.feature.SIFTDescriptorFromPyramid`, the channels of :class:`~kornia.feature.DenseSIFTDescriptor`,+ and :class:`~kornia.feature.SIFTFeature` and :class:`~kornia.feature.SIFTFeatureScaleSpace` with either+ ``descriptor_backend``): angle-major, value:math:`(a, y, x)` at index :math:`a S^2 + y S + x`. Bin :math:`a` is centred on the direction:math:`2 \pi a / A`, measured from :math:`+x` towards :math:`+y`, with :math:`y` growing downwards as imagerows do.@@ -449,11 +463,23 @@ def sift_describe(class DenseSIFTDescriptor(nn.Module):"""nn.Module, which computes SIFT descriptor densely over the image.- Every output pixel is a SIFT descriptor of the image around the input position given below. Its- ``num_spatial_bins`` x ``num_spatial_bins`` cells are ``spatial_bin_size`` pixels apart, each cell pooling a- triangular window of ``spatial_bin_size`` pixels (see :func:`get_sift_pooling_kernel`), so the cells tile an- extent of ``num_spatial_bins * spatial_bin_size`` pixels. The cell spacing is that of :class:`SIFTDescriptor` and- of the VLFeat ``vl_dsift`` grid.+ Convention:+ - Every output pixel is a SIFT descriptor of the image around the input position given below. Its+ ``num_spatial_bins`` x ``num_spatial_bins`` cells are ``spatial_bin_size`` pixels apart, each cell pooling a+ triangular window of ``spatial_bin_size`` pixels (see ``get_sift_pooling_kernel``), so the cells tile an+ extent of ``num_spatial_bins * spatial_bin_size`` pixels. The cell spacing is that of+ :class:`SIFTDescriptor` and of the VLFeat ``vl_dsift`` grid.+ - Output pixel ``(i, j)`` describes the neighbourhood centred on the input position+ ``x = j * stride - padding + (num_spatial_bins - 1) * spatial_bin_size / 2 - e / 2`` (``y`` likewise from+ ``i``), in pixel-centre coordinates where the first input pixel is at 0, with ``e`` 1 for an even+ ``spatial_bin_size`` and 0 for an odd one. The centre lies on a pixel when+ ``(num_spatial_bins - 1) * spatial_bin_size`` and ``e`` have the same parity, and half way between two+ pixels otherwise.+ - The channels are in kornia's angle-major SIFT layout, channel+ ``a * num_spatial_bins**2 + cy * num_spatial_bins + cx`` for angle bin ``a`` and cell ``(cy, cx)``, the entry+ order of :class:`SIFTDescriptor`; move them last before :func:`convert_sift_descriptor_layout`. Clipping,+ RootSIFT (the default) and the output for a flat neighbourhood are those of :class:`SIFTDescriptor` (see its+ Convention block), but the cells are not weighted by a Gaussian window.Args:num_ang_bins: Number of angular bins. (8 is default)@@ -475,12 +501,6 @@ class DenseSIFTDescriptor(nn.Module):``H_out = (H + e + 2 * padding - (num_spatial_bins - 1) * spatial_bin_size - 1) // stride + 1`` and``W_out`` likewise, where ``e`` is 1 for an even ``spatial_bin_size`` and 0 for an odd one.- Output pixel ``(i, j)`` describes the neighbourhood centred on the input position- ``x = j * stride - padding + (num_spatial_bins - 1) * spatial_bin_size / 2 - e / 2`` (``y`` likewise from- ``i``), in pixel-centre coordinates where the first input pixel is at 0. The centre lies on a pixel when- ``(num_spatial_bins - 1) * spatial_bin_size`` and ``e`` have the same parity, and half way between two pixels- otherwise.-Examples::>>> input = torch.rand(2, 1, 200, 300)>>> SIFT = DenseSIFTDescriptor()diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.pyindex c3354e927..5e288c448 100644--- a/kornia/feature/sosnet.py+++ b/kornia/feature/sosnet.py@@ -41,6 +41,9 @@ class SOSNet(nn.Module):This is based on the original code from paper"SOSNet:Second Order Similarity Regularization for Local Descriptor Learning".+ Convention:+ - See the Convention block on :class:`~kornia.feature.HardNet`.+Args:pretrained: Download and set pretrained weights to the model.diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.pyindex 1bf0c20c6..86a47a147 100644--- a/kornia/feature/tfeat.py+++ b/kornia/feature/tfeat.py@@ -45,6 +45,12 @@ class TFeat(nn.Module):with triplets and shallow convolutional neural networks".See :cite:`TFeat2016` for more details+ Convention:+ - It takes the patches of :class:`~kornia.feature.HardNet`, with the intensity rule of HardNet's Convention+ block, but returns the final ``tanh`` layer of the reference implementation without L2 normalisation: each+ entry lies in ``[-1, 1]`` and the rows are not unit vectors. Normalise them where a distance threshold+ assumes unit descriptors.+Args:pretrained: Download and set pretrained weights to the model.diff --git a/tests/feature/test_hardnet.py b/tests/feature/test_hardnet.pyindex c2fa38f8c..0ccf60e25 100644--- a/tests/feature/test_hardnet.py+++ b/tests/feature/test_hardnet.py@@ -18,9 +18,10 @@import pytestimport torch-from kornia.feature import HardNet, HardNet8+from kornia.core.check import ShapeError+from kornia.feature import HardNet, HardNet8, HyNet, MKDDescriptor, SIFTDescriptor, SOSNet, TFeat-from testing.base import BaseTester, supports_conv2d+from testing.base import BaseTester, supports_conv2d, supports_replicate_paddingclass TestHardNet(BaseTester):@@ -143,3 +144,72 @@ class TestHardNetConstantPatchIsFinite(BaseTester):patches = torch.zeros(2, 1, 32, 32, device=device, dtype=desc_dtype)out = model().to(device, desc_dtype)(patches)assert torch.isfinite(out).all()+++# Each patch descriptor with the weights it gets without a download, its patch size, its output width and whether it+# pads with mode="replicate" (its gradient filters). MKD runs unwhitened, which needs no download either and returns+# the full 238-dimensional concat embedding.+_PATCH_DESCRIPTORS = {+ "HardNet": (HardNet, 32, 128, False),+ "HardNet8": (HardNet8, 32, 128, False),+ "HyNet": (HyNet, 32, 128, False),+ "SOSNet": (SOSNet, 32, 128, False),+ "TFeat": (TFeat, 32, 128, False),+ "MKDDescriptor": (lambda: MKDDescriptor(whitening=None), 32, 238, True),+ "SIFTDescriptor": (lambda: SIFTDescriptor(32), 32, 128, True),+}+++class TestConventionsPatchDescriptors(BaseTester):+ """Pins for the patch-descriptor family: the patch each takes, its output norm and its intensity-range rule."""++ @staticmethod+ def _model(name, device, dtype):+ factory, patch_size, dim, pads = _PATCH_DESCRIPTORS[name]+ if not supports_conv2d(device, dtype):+ pytest.skip(f"no conv2d kernel for {dtype} on {device.type}")+ if pads and not supports_replicate_padding(device, dtype):+ pytest.skip(f"no replicate-padding kernel for {dtype} on {device.type}")+ torch.manual_seed(0) # random-init weights: no pin downloads+ return factory().to(device, dtype), patch_size, dim++ @pytest.mark.parametrize("name", ["HardNet", "HardNet8", "HyNet", "SOSNet", "TFeat"])+ def test_convention_learned_descriptors_take_one_channel_32x32_patches(self, device, dtype, name):+ # The input is validated: another size or channel count raises instead of returning another width (HyNet's+ # rejection is also pinned by test_hynet.py::TestHyNet::test_wrong_patch_shape_is_rejected_5724).+ model, _, _ = self._model(name, device, dtype)+ assert type(model).patch_size == 32+ assert model(torch.rand(3, 1, 32, 32, device=device, dtype=dtype)).shape == (3, 128)+ for shape in [(3, 1, 40, 40), (3, 1, 64, 64), (3, 3, 32, 32), (3, 1, 32, 31)]:+ with pytest.raises(ShapeError):+ model(torch.rand(*shape, device=device, dtype=dtype))++ @pytest.mark.parametrize("name", ["HardNet", "HardNet8", "HyNet", "SOSNet", "MKDDescriptor", "SIFTDescriptor"])+ def test_convention_patch_descriptors_return_unit_norm_rows(self, device, dtype, name):+ # TFeat is the exception, a tanh output as in its reference: test_tfeat.py::TestConventionsTFeat.+ model, patch_size, dim = self._model(name, device, dtype)+ out = model(torch.rand(5, 1, patch_size, patch_size, device=device, dtype=dtype))+ assert out.shape == (5, dim)+ self.assert_close(out.norm(dim=1), torch.ones(5, device=device, dtype=dtype))++ @pytest.mark.parametrize("name", ["HardNet", "HardNet8", "SOSNet", "TFeat", "MKDDescriptor", "SIFTDescriptor"])+ def test_convention_patch_descriptors_ignore_an_affine_intensity_change(self, device, dtype, name):+ # HardNet and HardNet8 standardise each patch, SOSNet and TFeat start with InstanceNorm2d, MKD and SIFT use+ # gradients and an L2 normalisation, so a [0, 1] patch, 2x + 1 and 255x give one descriptor. SOSNet and TFeat+ # are invariant only up to the InstanceNorm eps (1e-5 on the variance): it moves TFeat by ~1e-5 here, and with+ # pretrained weights a low-contrast patch moves both; random weights hide this for SOSNet, whose bias-free+ # layers are positively homogeneous. HyNet is the exception (scale only): test_hynet.py::TestConventionsHyNet.+ model, patch_size, _ = self._model(name, device, dtype)+ patches = torch.rand(4, 1, patch_size, patch_size, device=device, dtype=dtype)+ desc = model(patches)+ tol = {"rtol": 0.0, "atol": 1e-4} if dtype in (torch.float32, torch.float64) else {}+ # A float16 InstanceNorm that accumulates the squares of a [0, 255] patch in float16 overflows (torch 2.5.1 on+ # CPU does), so that leg scales by 16 instead.+ scale = 16.0 if dtype == torch.float16 and name in ("SOSNet", "TFeat") else 255.0+ self.assert_close(model(2 * patches + 1), desc, **tol)+ self.assert_close(model(scale * patches), desc, **tol)+ if dtype in (torch.float32, torch.float64):+ # each patch is normalised on its own: a different a x + b per patch still gives each patch its descriptor+ a = torch.tensor([1.0, 16.0, 0.5, 3.0], device=device, dtype=dtype).view(4, 1, 1, 1)+ b = torch.tensor([0.0, 0.0, -2.0, 1.0], device=device, dtype=dtype).view(4, 1, 1, 1)+ self.assert_close(model(a * patches + b), desc, **tol)diff --git a/tests/feature/test_hynet.py b/tests/feature/test_hynet.pyindex 8e9ea9a9c..a31722dd3 100644--- a/tests/feature/test_hynet.py+++ b/tests/feature/test_hynet.py@@ -15,13 +15,15 @@# limitations under the License.#+import math+import pytestimport torchfrom kornia.core.check import ShapeError-from kornia.feature import FilterResponseNorm2d, HyNet+from kornia.feature import TLU, FilterResponseNorm2d, HyNet-from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available, supports_conv2dclass TestHyNet(BaseTester):@@ -98,3 +100,63 @@ class TestHyNet(BaseTester):model = HyNet().to(patches.device, patches.dtype).eval()model_jit = torch.jit.script(model)self.assert_close(model(patches), model_jit(patches))+++class TestConventionsHyNet(BaseTester):+ """Pins for HyNet's input-range rule and its two normalisation layers, FilterResponseNorm2d and TLU."""++ def test_convention_hynet_is_scale_invariant_but_not_offset_invariant(self, device, dtype):+ # HyNet's first layer is FilterResponseNorm2d on the raw patch: it divides by the RMS and subtracts no mean, as+ # in the reference (yuruntian/HyNet model.py, trained on uint8 patches cast to float). So 255x gives x's+ # descriptor, while x + 1 and the mean-subtracted x - 0.5 do not (best row cosine about 0.9 and 0.7 with random+ # weights). Feed it non-negative intensities, not standardised patches.+ if not supports_conv2d(device, dtype):+ pytest.skip(f"no conv2d kernel for {dtype} on {device.type}")+ torch.manual_seed(0)+ model = HyNet().to(device, dtype)+ patches = torch.rand(4, 1, 32, 32, device=device, dtype=dtype)+ desc = model(patches)+ self.assert_close(model(255 * patches), desc)+ for moved in (patches + 1, patches - 0.5):+ cos = torch.nn.functional.cosine_similarity(model(moved).float(), desc.float(), dim=1)+ assert cos.max() < 0.95, cos++ def test_convention_filter_response_norm_divides_each_map_by_its_rms_with_eps_under_the_root(self, device, dtype):+ # y = weight * x / sqrt(mean_HW(x^2) + |eps|) + bias, per sample and channel (weight 1, bias 0 at init).+ # eps = 1 makes its place visible: a constant map of 1 gives 1 / sqrt(2), where eps outside the root would give+ # 1 / (1 + 1) = 0.5; a constant 3 gives 3 / sqrt(10), not 0.75.+ frn = FilterResponseNorm2d(2, eps=1.0).to(device, dtype)+ x = torch.tensor(+ [[[[1.0, 1.0, 1.0, 1.0]], [[3.0, 3.0, 3.0, 3.0]]], [[[0.0, 1.0, 2.0, 3.0]], [[-2.0, 0.0, 0.0, 2.0]]]],+ device=device,+ dtype=dtype,+ )+ # mean squares 1, 9, 3.5 and 2, each plus eps+ expected = torch.tensor(+ [+ [[[1 / math.sqrt(2)] * 4], [[3 / math.sqrt(10)] * 4]],+ [+ [[0.0, 1 / math.sqrt(4.5), 2 / math.sqrt(4.5), 3 / math.sqrt(4.5)]],+ [[-2 / math.sqrt(3), 0, 0, 2 / math.sqrt(3)]],+ ],+ ],+ device=device,+ dtype=dtype,+ )+ self.assert_close(frn(x), expected)+ self.assert_close(frn(x[1:]), expected[1:]) # each sample on its own: no batch statistics+ self.assert_close(FilterResponseNorm2d(2, eps=-1.0).to(device, dtype)(x), expected) # |eps|++ def test_convention_tlu_floors_each_channel_at_its_tau_initialised_to_minus_one(self, device, dtype):+ tlu = TLU(3).to(device, dtype)+ assert tlu.tau.shape == (1, 3, 1, 1)+ x = torch.tensor([-3.0, -1.0, -0.5, 2.0], device=device, dtype=dtype).view(1, 1, 1, 4).repeat(2, 3, 1, 1)+ at_minus_one = torch.tensor([-1.0, -1.0, -0.5, 2.0], device=device, dtype=dtype)+ self.assert_close(tlu(x), at_minus_one.expand(2, 3, 1, 4))+ with torch.no_grad():+ tlu.tau[0, 1] = 0.0+ # max(x, tau) per channel: only channel 1 now floors at 0+ at_zero = torch.tensor([0.0, 0.0, 0.0, 2.0], device=device, dtype=dtype)+ self.assert_close(+ tlu(x), torch.stack([at_minus_one, at_zero, at_minus_one]).view(1, 3, 1, 4).expand(2, 3, 1, 4)+ )diff --git a/tests/feature/test_mkd.py b/tests/feature/test_mkd.pyindex 83066426f..e8040dc91 100644--- a/tests/feature/test_mkd.py+++ b/tests/feature/test_mkd.py@@ -593,3 +593,38 @@ class TestSimpleKD(BaseTester):return skd(patches.double())self.gradcheck(skd_describe, (patches, ps), nondet_tol=1e-4)+++class TestConventionsMKDDescriptor(BaseTester):+ """Pin for the frame of MKD's kernels within the patch."""++ @pytest.mark.parametrize("kernel_type", ["concat", "polar", "cart"])+ def test_convention_mkd_kernels_are_centred_on_the_patch_centre(self, device, dtype, kernel_type):+ # The kernel grid spans [-1, 1] across the patch_size pixels, so its origin is pixel (patch_size - 1) / 2, as in+ # manyids2/mkd_pytorch (between two pixels at the even 32). Mirroring a patch about that centre maps the grid+ # onto itself and flips only the signs of the odd harmonics, so every entry keeps its magnitude; a grid half a+ # pixel off the centre does not. whitening=None needs no download and keeps the raw entries.+ if not supports_replicate_padding(device, dtype):+ pytest.skip(f"no replicate-padding kernel for {dtype} on {device.type}")+ torch.manual_seed(0)+ patches = torch.rand(4, 1, 32, 32, device=device, dtype=dtype)+ mkd = MKDDescriptor(patch_size=32, kernel_type=kernel_type, whitening=None).to(device, dtype)+ desc = mkd(patches)+ for mirrored in (patches.flip(-1), patches.flip(-2)):+ out = mkd(mirrored)+ self.assert_close(out.abs(), desc.abs())+ assert (out - desc).abs().max() > 0.02 # a mirrored random patch changes signs: the pin is not vacuous++ @pytest.mark.parametrize("kernel_type", ["concat", "polar", "cart"])+ def test_convention_mkd_flat_patch_is_unit_norm_except_in_float16_without_whitening(+ self, device, dtype, kernel_type+ ):+ # A flat patch has zero gradients, so its magnitudes are the sqrt of the 1e-8 added to them. In float16 the+ # 1e-8 underflows to 0 and, with whitening=None, the descriptor is all zero; in the other dtypes it is a unit+ # vector. whitening=None needs no download.+ if not supports_replicate_padding(device, dtype):+ pytest.skip(f"no replicate-padding kernel for {dtype} on {device.type}")+ mkd = MKDDescriptor(patch_size=19, kernel_type=kernel_type, whitening=None).to(device, dtype)+ out = mkd(torch.full((2, 1, 19, 19), 0.5, device=device, dtype=dtype))+ expected = 0.0 if dtype == torch.float16 else 1.0+ self.assert_close(out.norm(dim=1), torch.full((2,), expected, device=device, dtype=dtype))diff --git a/tests/feature/test_sift_pyramid.py b/tests/feature/test_sift_pyramid.pyindex 0f595fd55..c29cc1026 100644--- a/tests/feature/test_sift_pyramid.py+++ b/tests/feature/test_sift_pyramid.py@@ -17,12 +17,15 @@from __future__ import annotations+import math+import pytestimport torch-from kornia.feature import SIFTDescriptorFromPyramid, get_laf_orientation, laf_from_center_scale_ori+from kornia.feature import LAFOrienter, SIFTDescriptorFromPyramid, get_laf_orientation, laf_from_center_scale_ori+from kornia.filters import gaussian_blur2d-from testing.base import BaseTester, supports_reflect_padding+from testing.base import BaseTester, supports_reflect_padding, supports_replicate_paddingclass TestSIFTDescriptorFromPyramid(BaseTester):@@ -342,3 +345,65 @@ class TestSIFTDescriptorFromPyramid(BaseTester):monkeypatch.setattr(descriptor, "_pyramid", counted_pyramid)descriptor.orient_and_describe(image, lafs)assert len(calls) == 1+++class TestConventionsSIFTDescriptorFromPyramid(BaseTester):+ """Pins for the frame in which SIFTDescriptorFromPyramid reads LAFs and the orientation it assigns."""++ @staticmethod+ def _flip_lr(desc: torch.Tensor) -> torch.Tensor:+ """The descriptor of the left-right mirrored neighbourhood: angle bin a becomes 4 - a, cell column cx 3 - cx."""+ d = desc.reshape(-1, 8, 4, 4)+ return d[:, [(4 - a) % 8 for a in range(8)]].flip(-1).reshape(desc.shape)++ @staticmethod+ def _transpose(desc: torch.Tensor) -> torch.Tensor:+ """The descriptor of the transposed neighbourhood: angle bin a becomes 2 - a, cells (cy, cx) become (cx, cy)."""+ d = desc.reshape(-1, 8, 4, 4)+ return d[:, [(2 - a) % 8 for a in range(8)]].transpose(-1, -2).reshape(desc.shape)++ def test_convention_pyramid_sift_reads_lafs_in_pixel_coordinates(self, device, dtype):+ # A LAF centre (x, y) is the pixel centre of column x and row y, as everywhere in kornia.feature. A Gaussian+ # blob centred on pixel (41, 22) of a 60 x 75 image, described by an axis-aligned LAF at that pixel, is its own+ # mirror image, so its descriptor is a fixed point of the mirror permutation; the same LAF half a pixel to the+ # right is not (the residual is 0.058).+ ys, xs = torch.arange(60.0).view(-1, 1), torch.arange(75.0).view(1, -1)+ blob = torch.exp(-((xs - 41) ** 2 + (ys - 22) ** 2) / (2 * 4.0**2))[None, None].to(device, dtype)+ lafs = torch.tensor(+ [[[[6.0, 0.0, 41.0], [0.0, 6.0, 22.0]], [[6.0, 0.0, 41.5], [0.0, 6.0, 22.0]]]], device=device, dtype=dtype+ )+ desc = SIFTDescriptorFromPyramid(rootsift=False).to(device, dtype)(blob, lafs)[0]+ self.assert_close(self._flip_lr(desc[0]), desc[0])+ assert (self._flip_lr(desc[1]) - desc[1]).abs().max() > 0.04+ # Relabelling: transposing the image and the frame (A -> T A T, centre (x, y) -> (y, x)) transposes the+ # described neighbourhood, so the descriptor permutes; a sheared frame on a smooth random image.+ torch.manual_seed(0)+ image = gaussian_blur2d(torch.rand(1, 1, 60, 75, device=device), (7, 7), (1.5, 1.5)).to(dtype)+ laf = torch.tensor([[[[5.0, 1.5, 41.0], [-0.8, 6.0, 22.0]]]], device=device, dtype=dtype)+ laf_t = torch.tensor([[[[6.0, -0.8, 22.0], [1.5, 5.0, 41.0]]]], device=device, dtype=dtype)+ sift = SIFTDescriptorFromPyramid(rootsift=False).to(device, dtype)+ self.assert_close(sift(image.transpose(-1, -2), laf_t)[0], self._transpose(sift(image, laf)[0]))++ def test_convention_orient_and_describe_turns_the_laf_x_axis_onto_the_dominant_gradient(self, device, dtype):+ # The assigned orientation is minus the gradient's angle (measured from +x towards +y, image rows growing+ # downwards), whatever orientation the input LAF had, so the oriented frame's x axis lies along the gradient and+ # the descriptor's dominant angle bin is 0. LAFOrienter, which orients SIFTFeature's patch backend, assigns the+ # same orientation.+ ys, xs = torch.arange(60.0).view(-1, 1), torch.arange(75.0).view(1, -1)+ lafs = laf_from_center_scale_ori(+ torch.tensor([[[41.0, 22.0], [30.0, 35.0], [52.0, 30.0]]], device=device, dtype=dtype),+ torch.full((1, 3, 1, 1), 6.0, device=device, dtype=dtype),+ torch.tensor([[[0.0], [50.0], [-120.0]]], device=device, dtype=dtype),+ )+ atol = 0.05 if dtype in (torch.float32, torch.float64) else 1.0 # degrees; bfloat16 reads 135 to a degree+ sift = SIFTDescriptorFromPyramid(rootsift=False).to(device, dtype)+ for gradient_angle in (30.0, -60.0, 135.0):+ g = math.radians(gradient_angle)+ ramp = (0.01 * (math.cos(g) * xs + math.sin(g) * ys))[None, None].to(device, dtype)+ oriented, desc = sift.orient_and_describe(ramp, lafs)+ expected = torch.full((1, 3, 1), -gradient_angle, device=device, dtype=dtype)+ self.assert_close(get_laf_orientation(oriented), expected, rtol=0.0, atol=atol)+ assert desc.reshape(3, 8, 16).sum(-1).argmax(-1).tolist() == [0, 0, 0]+ if supports_replicate_padding(device, dtype): # LAFOrienter's patch gradients pad with mode="replicate"+ orienter = LAFOrienter(19).to(device, dtype)+ self.assert_close(get_laf_orientation(orienter(lafs, ramp)), expected, rtol=0.0, atol=2 * atol)diff --git a/tests/feature/test_siftdesc.py b/tests/feature/test_siftdesc.pyindex ce4efff61..09cf75e23 100644--- a/tests/feature/test_siftdesc.py+++ b/tests/feature/test_siftdesc.py@@ -18,8 +18,8 @@import pytestimport torch-from kornia.core.exceptions import BaseError-from kornia.feature import convert_sift_descriptor_layout+from kornia.core.exceptions import BaseError, ShapeError+from kornia.feature import SIFTDescriptorFromPyramid, convert_sift_descriptor_layout, laf_from_center_scale_orifrom kornia.feature.siftdesc import (DenseSIFTDescriptor,SIFTDescriptor,@@ -678,3 +678,123 @@ class TestConvertSIFTDescriptorLayout(BaseTester):return convert_sift_descriptor_layout(d, "kornia", "opencv")self.assert_close(torch_optimizer(op, fullgraph=True)(descriptors), op(descriptors))+++def _sift_family_member(kind, device, dtype, image, **kwargs):+ """Describe ``image`` with the ``kind`` SIFT descriptor; the descriptor axis is returned last."""+ if kind == "patch":+ return SIFTDescriptor(image.shape[-1], **kwargs).to(device, dtype)(image)+ if kind == "dense":+ return DenseSIFTDescriptor(**kwargs).to(device, dtype)(image).movedim(1, -1)+ # two oriented, sheared frames off the image centre, both straddling the step edge of the fixtures below+ lafs = laf_from_center_scale_ori(+ torch.tensor([[[30.0, 20.0], [33.0, 31.0]]], device=device, dtype=dtype),+ torch.tensor([[[[6.0]], [[5.0]]]], device=device, dtype=dtype),+ torch.tensor([[[20.0], [-40.0]]], device=device, dtype=dtype),+ )+ lafs[..., 0, 1] += 1.0+ return SIFTDescriptorFromPyramid(**kwargs).to(device, dtype)(image, lafs)+++class TestConventionsSIFTDescriptors(BaseTester):+ """Pins for the SIFT family's patch size, clipping, RootSIFT default, flat-patch output and dense channel layout."""++ def test_convention_sift_descriptor_takes_41_pixel_patches_by_default(self, device, dtype):+ # Unlike the 32-pixel learned descriptors and the patch_size=32 default of LAFDescriptor / get_laf_descriptors;+ # the size is validated.+ if not supports_replicate_padding(device, dtype):+ pytest.skip(f"no replicate-padding kernel for {dtype} on {device.type}")+ sift = SIFTDescriptor().to(device, dtype)+ assert sift.patch_size == 41+ assert sift(torch.rand(2, 1, 41, 41, device=device, dtype=dtype)).shape == (2, 128)+ with pytest.raises(ShapeError):+ sift(torch.rand(2, 1, 32, 32, device=device, dtype=dtype))++ def test_convention_sift_clips_at_clipval_between_two_l2_normalisations(self, device, dtype):+ # A vertical step between columns 24 and 25 of a 41-pixel patch: every gradient points along +x (angle bin 0)+ # and lies in cell column 2 only (cells centred at 5, 15, 25 and 35, each pooling 17 pixels). Index+ # a * 16 + cy * 4 + cx: entries 2, 6, 10 and 14. clipval=1.0 leaves the unit descriptor unclipped.+ if not supports_replicate_padding(device, dtype):+ pytest.skip(f"no replicate-padding kernel for {dtype} on {device.type}")+ patch = torch.zeros(1, 1, 41, 41, device=device, dtype=dtype)+ patch[..., 25:] = 1.0+ # Relabelling: the transposed patch has a horizontal step, angle bin 2 (+y, image rows grow downwards) in cell+ # row 2, entries 32 + 8 + cx.+ for image, entries in ((patch, [2, 6, 10, 14]), (patch.transpose(-1, -2), [40, 41, 42, 43])):+ raw = SIFTDescriptor(rootsift=False, clipval=1.0).to(device, dtype)(image)[0]+ out = SIFTDescriptor(rootsift=False).to(device, dtype)(image)[0]+ assert (raw > 0.1).nonzero().flatten().tolist() == entries+ self.assert_close(raw.norm(), torch.ones((), device=device, dtype=dtype))+ assert raw[entries].min() > 0.2 # every entry is clipped+ # the cells mirror about the patch centre, as the grid is centred there+ self.assert_close(raw[entries[:2]], raw[entries[::-1][:2]])+ # unequal before the clip (the window weights the middle cells more), so the 0.5 below is the clip's doing+ assert (raw[entries] - 0.5).abs().max() > 0.01+ # normalise, clip every entry at clipval = 0.2, normalise again: the four equal clipped entries become+ # 0.5, so an output entry can exceed clipval+ assert (out > 0.1).nonzero().flatten().tolist() == entries+ self.assert_close(out[entries], torch.full((4,), 0.5, device=device, dtype=dtype))++ @pytest.mark.parametrize("kind", ["patch", "dense", "pyramid"])+ def test_convention_sift_family_defaults_to_rootsift_of_the_clipped_descriptor(self, device, dtype, kind):+ # rootsift=True and clipval=0.2 by default in all three (pytorch-sift and OpenCV return plain SIFT): the+ # default output is sqrt(L1-normalise(clipped SIFT) + 1e-10), where clipped SIFT is the unit descriptor+ # clipped at 0.2 and renormalised. clipval=1.0 leaves a unit descriptor unclipped.+ if not supports_replicate_padding(device, dtype):+ pytest.skip(f"no replicate-padding kernel for {dtype} on {device.type}")+ torch.manual_seed(0)+ size = {"patch": (3, 1, 41, 41), "dense": (1, 1, 30, 37), "pyramid": (1, 1, 48, 64)}[kind]+ image = 0.2 * torch.rand(*size, device=device, dtype=dtype)+ image[..., size[-1] // 2 + 4 :] += 1.0 # a step edge, so that the clipping acts+ raw = _sift_family_member(kind, device, dtype, image, rootsift=False, clipval=1.0)+ raw = raw.to(torch.promote_types(dtype, torch.float32))+ assert raw.max() > 0.25+ clipped = torch.nn.functional.normalize(raw.clamp(0.0, 0.2), dim=-1)+ expected = (clipped / clipped.sum(dim=-1, keepdim=True) + 1e-10).sqrt()+ self.assert_close(_sift_family_member(kind, device, dtype, image), expected.to(dtype))++ @pytest.mark.parametrize("kind", ["patch", "dense", "pyramid"])+ def test_convention_sift_family_describes_a_flat_patch_by_a_zero_vector(self, device, dtype, kind):+ # A flat patch has no gradient, hence no orientation: its descriptor is zero rather than a unit vector, and+ # its RootSIFT is sqrt(1e-10) = 1e-5 in every bin. A zero-LAF padding slot hands SIFTDescriptor (behind+ # LAFDescriptor) such a patch. SIFTDescriptorFromPyramid instead treats a zero LAF as invalid and returns an+ # exact zero descriptor whether or not rootsift is set.+ if not supports_replicate_padding(device, dtype):+ pytest.skip(f"no replicate-padding kernel for {dtype} on {device.type}")+ size = {"patch": (3, 1, 41, 41), "dense": (1, 1, 30, 37), "pyramid": (1, 1, 48, 64)}[kind]+ image = torch.full(size, 0.5, device=device, dtype=dtype)+ plain = _sift_family_member(kind, device, dtype, image, rootsift=False)+ assert torch.equal(plain, torch.zeros_like(plain))+ root = _sift_family_member(kind, device, dtype, image)+ self.assert_close(root, torch.full_like(root, 1e-5), rtol=1e-2, atol=0.0)+ if kind == "pyramid":+ # a zero LAF next to a valid one, so that the invalid slot goes through the same pass as a real frame+ lafs = torch.zeros(1, 2, 2, 3, device=device, dtype=dtype)+ lafs[0, 0] = torch.tensor([[6.0, 1.0, 30.0], [0.0, 6.0, 20.0]], device=device, dtype=dtype)+ for rootsift in (False, True):+ desc = SIFTDescriptorFromPyramid(rootsift=rootsift).to(device, dtype)(image, lafs)[0]+ assert torch.equal(desc[1], torch.zeros_like(desc[1]))+ assert bool((desc[0] > 0).all()) == rootsift # the valid slot of the flat image: 1e-5 or 0+ oriented, _ = (+ SIFTDescriptorFromPyramid(rootsift=rootsift).to(device, dtype).orient_and_describe(image, lafs)+ )+ assert torch.equal(oriented[0, 1], lafs[0, 1]) # the padding frame comes back unchanged++ def test_convention_dense_sift_channels_are_angle_major_like_sift_descriptor(self, device, dtype):+ # Channel a * 16 + cy * 4 + cx, as SIFTDescriptor's entries. With the defaults output (i, j) is centred on+ # input (i + 4.5, j + 4.5) and its four cell columns sit 4 pixels apart, each pooling 4 pixels: at j = 25 the+ # cells pool columns 22-25, 26-29, 30-33 and 34-37. A vertical step between columns 35 and 36 has its+ # gradients (angle bin 0, +x) in cell column 3 only: channels 3, 7, 11 and 15, equal (no Gaussian weight), 0.5.+ if not supports_replicate_padding(device, dtype):+ pytest.skip(f"no replicate-padding kernel for {dtype} on {device.type}")+ image = torch.zeros(1, 1, 40, 53, device=device, dtype=dtype)+ image[..., 36:] = 1.0+ dense = DenseSIFTDescriptor(rootsift=False).to(device, dtype)+ # Relabelling: transposing the image transposes the output map and turns the step horizontal, angle bin 2+ # (+y) in cell row 3: channels 32 + 12 + cx.+ for out, entries in (+ (dense(image)[0, :, 12, 25], [3, 7, 11, 15]),+ (dense(image.transpose(-1, -2))[0, :, 25, 12], [44, 45, 46, 47]),+ ):+ assert (out > 0.1).nonzero().flatten().tolist() == entries+ self.assert_close(out[entries], torch.full((4,), 0.5, device=device, dtype=dtype))diff --git a/tests/feature/test_tfeat.py b/tests/feature/test_tfeat.pyindex f22017b19..4a5b86779 100644--- a/tests/feature/test_tfeat.py+++ b/tests/feature/test_tfeat.py@@ -20,7 +20,7 @@ import torchfrom kornia.feature import TFeat-from testing.base import BaseTester+from testing.base import BaseTester, supports_conv2dclass TestTFeat(BaseTester):@@ -58,3 +58,21 @@ class TestTFeat(BaseTester):tfeat = TFeat(True).to(patches.device, patches.dtype).eval()tfeat_jit = torch.jit.script(TFeat(True).to(patches.device, patches.dtype).eval())self.assert_close(tfeat_jit(patches), tfeat(patches))+++class TestConventionsTFeat(BaseTester):+ """Pin for TFeat's output, the patch-descriptor family's one non-unit-norm row."""++ def test_convention_tfeat_returns_its_tanh_layer_without_l2_normalisation(self, device, dtype):+ # As in the reference (vbalnt/tfeat tfeat_model.py: Linear(64 * 8 * 8, 128), then Tanh, then nothing), each+ # entry is a tanh output in [-1, 1] and the rows are not unit vectors: their norms are about 2 with random+ # weights and about 9 with the pretrained ones. Normalise them where a threshold assumes unit vectors.+ if not supports_conv2d(device, dtype):+ pytest.skip(f"no conv2d kernel for {dtype} on {device.type}")+ torch.manual_seed(0)+ model = TFeat().to(device, dtype)+ out = model(torch.rand(6, 1, 32, 32, device=device, dtype=dtype))+ assert out.shape == (6, 128)+ assert out.abs().max() <= 1.0+ norms = out.float().norm(dim=1)+ assert bool((norms > 1.2).all()), norms