Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(feature): rewrite the matchers, LAFs, detectors, descriptors, local-feature pipelines and learned models of kornia.feature in the choose-then-use style (#6539)

Dmytro Mishkin6c79aabeab09
diff --git a/docs/source/feature.descriptors.rst b/docs/source/feature.descriptors.rst
index 8279404f0..f6ec1271f 100644
--- a/docs/source/feature.descriptors.rst
+++ b/docs/source/feature.descriptors.rst
@@ -3,6 +3,26 @@ Descriptors
.. currentmodule:: kornia.feature
+Patch descriptors and LAFs
+--------------------------
+
+:class:`SIFTDescriptor`, :class:`MKDDescriptor` and the learned :class:`HardNet`, :class:`HardNet8`,
+:class:`HyNet`, :class:`SOSNet` and :class:`TFeat` compute one descriptor per grayscale patch
+``(B, 1, PS, PS)``. The learned networks require ``PS = 32`` and load pretrained weights by default.
+SIFT and MKD accept a configurable ``patch_size``, with defaults of 41 and 32 respectively.
+All except TFeat return L2-normalised descriptors. See each descriptor's conventions for its response
+to changes in image brightness and contrast.
+
+To describe LAFs in an image, use :class:`LAFDescriptor` to reuse a descriptor module, or
+:func:`get_laf_descriptors` to supply one on each call. Both extract a patch for each LAF and compute its
+descriptor. Set ``patch_size`` to the size expected by the descriptor; the default is 32.
+:class:`LAFDescriptor` uses pretrained :class:`HardNet` by default. Patches follow the orientation of
+their LAFs, so orient the LAFs first, for example with :class:`LAFOrienter`.
+
+For SIFT descriptors of LAFs without extracting patches, use :class:`SIFTDescriptorFromPyramid`
+(see below). The :doc:`local-feature pipelines <feature.local_features>` combine a detector with a descriptor.
+:class:`SOLD2` detects, describes and matches line segments in whole images.
+
.. _sift-descriptor-interfaces:
Choosing a SIFT descriptor interface
diff --git a/docs/source/feature.detectors.rst b/docs/source/feature.detectors.rst
index 17f302eac..6da8cab28 100644
--- a/docs/source/feature.detectors.rst
+++ b/docs/source/feature.detectors.rst
@@ -3,6 +3,32 @@ Detectors
.. currentmodule:: kornia.feature
+Response functions score image locations; detectors select local maxima and return feature frames.
+Use a response function when you need a dense score map, or a detector when you need sparse keypoints.
+
+For an image ``(B, C, H, W)``, :func:`harris_response` and :func:`gftt_response` score corners;
+:func:`hessian_response` and :func:`dog_response_single` score blobs. These functions return maps of the same
+shape as the image, without non-maximum suppression. :func:`dog_response` instead takes a Gaussian scale stack
+``(B, C, D, H, W)`` and returns differences between adjacent levels, ``(B, C, D - 1, H, W)``.
+
+To use a response in a detector, choose its module form: :class:`CornerHarris`, :class:`CornerGFTT`,
+:class:`BlobHessian`, :class:`BlobDoGSingle` or :class:`BlobDoG`. Pass it as ``resp_module`` to
+:class:`ScaleSpaceDetector`, or as ``model`` to :class:`MultiResolutionDetector`.
+:class:`BlobDoG` requires a scale stack, so use it only with :class:`ScaleSpaceDetector` and
+``scale_space_response=True``.
+
+The detectors return LAFs ``(B, N, 2, 3)`` in input pixels and responses ``(B, N)``, strongest first.
+Unused slots contain zero LAFs and zero responses. Use :func:`laf_is_filled` to keep detected features and
+discard padded slots; apply the same mask to LAFs and responses.
+
+- :class:`ScaleSpaceDetector` takes a batch and refines maxima over a Gaussian scale space.
+ Its default response is the Hessian determinant.
+- :class:`MultiResolutionDetector` takes one image and finds maxima at integer pixels of each pyramid level,
+ without scale selection or subpixel refinement.
+- :class:`KeyNetDetector` uses :class:`MultiResolutionDetector` with the learned :class:`KeyNet` response.
+
+For detection and description together, see :doc:`feature.local_features`.
+
Response functions
------------------
diff --git a/docs/source/feature.laf.rst b/docs/source/feature.laf.rst
index ea64d2266..ba9a30e6a 100644
--- a/docs/source/feature.laf.rst
+++ b/docs/source/feature.laf.rst
@@ -3,54 +3,83 @@ Local affine frames (LAF)
.. currentmodule:: kornia.feature
-A local affine frame is a ``(B, N, 2, 3)`` tensor describing, for each keypoint, an affine transformation
-from a canonical patch to the image. Most detectors and descriptors in :mod:`kornia.feature` exchange LAFs.
+A local affine frame (LAF) describes a keypoint by a ``2 x 3`` matrix ``[A | c]``, and a set of them is a
+``(B, N, 2, 3)`` tensor. The centre ``c = (x, y)`` is in pixels, and the shape ``A`` maps the canonical patch frame
+onto the image, in pixels: its scale is :math:`\sqrt{|\det A|}` and its orientation ``atan2(a12, a11)``, in degrees
+counter-clockwise on screen for a LAF of positive determinant (clockwise for a mirrored one).
+:ref:`Local features <local-features-conventions>` gives the frame and the conversion of OpenCV keypoints. kornia's
+scale-space and KeyNet detectors (:class:`ScaleSpaceDetector`, :class:`MultiResolutionDetector`,
+:class:`KeyNetDetector`) return LAFs, :class:`LAFDescriptor` describes them, and :func:`match_fginn`,
+:func:`match_adalam` and :class:`LightGlueMatcher` read them; :func:`laf_from_center_scale_ori` turns the keypoints of
+the other detectors into LAFs.
-Functions
----------
+- To keep the detections of a fixed-size detector output, use :func:`laf_is_filled`; to also drop singular and
+ non-finite frames, :func:`laf_is_valid`; to keep the regions that lie inside the image, :func:`laf_is_inside_image`.
+- To sample patches to describe, use :func:`extract_patches_from_pyramid`, which reads each LAF from a pyramid level
+ chosen by its scale and limits aliasing. :func:`extract_patches_simple` reads the full-resolution image only and
+ aliases for large LAFs; a highly anisotropic LAF can still alias along its long axis.
+- To drop the orientation, use :func:`make_upright`; to set or add angles, :func:`set_laf_orientation` or
+ :func:`rotate_laf`; to estimate the orientation from the image, :class:`LAFOrienter`.
+- To adapt the affine shape to the image, use :class:`LAFAffineShapeEstimator` (the second-moment matrix of the
+ patch) or :class:`LAFAffNetShapeEstimator` (the learned AffNet); :class:`PassLAF` leaves the LAFs as they are.
-.. autofunction:: extract_patches_from_pyramid
-.. autofunction:: extract_patches_simple
-.. autofunction:: normalize_laf
-.. autofunction:: denormalize_laf
-.. autofunction:: laf_to_boundary_points
+Creating and reading LAFs
+-------------------------
+
+.. autofunction:: laf_from_center_scale_ori
.. autofunction:: ellipse_to_laf
-.. autofunction:: make_upright
-.. autofunction:: scale_laf
-.. autofunction:: get_laf_scale
+.. autofunction:: laf_from_three_points
.. autofunction:: get_laf_center
-.. autofunction:: rotate_laf
+.. autofunction:: get_laf_scale
.. autofunction:: get_laf_orientation
+.. autofunction:: laf_to_three_points
+.. autofunction:: laf_to_boundary_points
+
+Transforming LAFs
+-----------------
+
+.. autofunction:: scale_laf
+.. autofunction:: rotate_laf
.. autofunction:: set_laf_orientation
-.. autofunction:: laf_from_center_scale_ori
+.. autofunction:: make_upright
+.. autofunction:: perspective_transform_lafs
+.. autofunction:: normalize_laf
+.. autofunction:: denormalize_laf
+
+Checking LAFs
+-------------
+
+.. autofunction:: laf_is_valid
.. autofunction:: laf_is_filled
.. autofunction:: laf_is_inside_image
-.. autofunction:: laf_is_valid
-.. autofunction:: laf_to_three_points
-.. autofunction:: laf_from_three_points
.. autofunction:: KORNIA_CHECK_LAF
-.. autofunction:: perspective_transform_lafs
+
+Extracting patches
+------------------
+
+.. autofunction:: extract_patches_from_pyramid
+.. autofunction:: extract_patches_simple
Orientation and affine shape estimation
---------------------------------------
-.. autoclass:: PassLAF
+.. autoclass:: LAFOrienter
:members: forward
-.. autoclass:: PatchAffineShapeEstimator
+.. autoclass:: PatchDominantGradientOrientation
:members: forward
-.. autoclass:: LAFAffineShapeEstimator
+.. autoclass:: OriNet
:members: forward
-.. autoclass:: LAFOrienter
+.. autoclass:: LAFAffineShapeEstimator
:members: forward
-.. autoclass:: PatchDominantGradientOrientation
+.. autoclass:: PatchAffineShapeEstimator
:members: forward
-.. autoclass:: OriNet
+.. autoclass:: LAFAffNetShapeEstimator
:members: forward
-.. autoclass:: LAFAffNetShapeEstimator
+.. autoclass:: PassLAF
:members: forward
diff --git a/docs/source/feature.layers.rst b/docs/source/feature.layers.rst
index 4ea68a869..c5380350c 100644
--- a/docs/source/feature.layers.rst
+++ b/docs/source/feature.layers.rst
@@ -6,11 +6,18 @@ Layers and other models
Layers
------
+:class:`FilterResponseNorm2d` and :class:`TLU` are the normalisation and activation layers of :class:`HyNet`,
+from the Filter Response Normalization paper. They take a ``(B, num_features, H, W)`` feature map and use no
+batch statistics.
+
.. autoclass:: FilterResponseNorm2d
.. autoclass:: TLU
Fast moving objects
-------------------
+:class:`DeFMO` deblurs a fast-moving object, given the blurred image and an estimate of its background, into 24
+RGBA sub-frames of the object alone.
+
.. autoclass:: DeFMO
:members: forward
diff --git a/docs/source/feature.local_features.rst b/docs/source/feature.local_features.rst
index 20531dd76..dbf0dde51 100644
--- a/docs/source/feature.local_features.rst
+++ b/docs/source/feature.local_features.rst
@@ -3,6 +3,18 @@ Local features (detector and descriptor together)
.. currentmodule:: kornia.feature
+:class:`LocalFeature` combines a detector and a LAF descriptor. Its SIFT and HardNet presets return
+LAFs ``(B, N, 2, 3)`` in pixels, responses ``(B, N)`` and descriptors ``(B, N, D)``, with
+``N = num_features`` slots per image. Unused slots contain zero LAFs. Use :func:`laf_is_filled` to keep
+detected features and discard padded slots; apply the same mask to all three outputs.
+:class:`LocalFeatureMatcher` filters this padding automatically.
+
+:class:`SIFTFeature`, :class:`KeyNetHardNet` and :class:`KeyNetAffNetHardNet` take one grayscale image
+``(1, 1, H, W)`` per call. The other presets take a batch ``(B, 1, H, W)``.
+``SIFTFeatureScaleSpace(descriptor_backend="pyramid")`` also accepts an RGB batch and converts it to grayscale.
+The :ref:`learned models <learned-local-features>` have separate interfaces and are not
+:class:`LocalFeature` subclasses.
+
.. _sift-pipelines:
Choosing a SIFT pipeline
@@ -114,15 +126,117 @@ This plan concerns the combination, not the standalone
:class:`SIFTDescriptorFromPyramid` descriptor-only interface; see
:ref:`sift-descriptor-interfaces`.
+HardNet presets
+---------------
+
+The six HardNet presets describe 32 x 32 patches with pretrained :class:`HardNet` through
+:class:`LAFDescriptor`. They load pretrained weights for every network they use and start in evaluation mode.
+Choose a preset by its detector and whether you need affine shape adaptation. The AffNet presets adapt each
+frame's shape before estimating its orientation; ``upright=True`` skips orientation estimation.
+
+.. list-table:: HardNet presets
+ :header-rows: 1
+ :widths: 22 34 14 16 14
+
+ * - Preset
+ - Detector and frames
+ - Orientation
+ - Input, ``num_features``
+ - ``LightGlueMatcher`` mode
+ * - :class:`GFTTAffNetHardNet`
+ - :class:`ScaleSpaceDetector` on :class:`CornerGFTT` corners, AffNet shapes
+ - ``LAFOrienter(19)``
+ - ``(B, 1, H, W)``, 8000
+ - none
+ * - :class:`HesAffNetHardNet`
+ - :class:`ScaleSpaceDetector` on :class:`BlobHessian` blobs, AffNet shapes
+ - ``LAFOrienter(19)``
+ - ``(B, 1, H, W)``, 2048
+ - none
+ * - :class:`DoGHardNet`
+ - The DoG detector of ``SIFTFeatureScaleSpace(descriptor_backend="patch")``, frames scaled to 12 sigma
+ - ``LAFOrienter(19)``
+ - ``(B, 1, H, W)``, 2048
+ - ``"doghardnet"``
+ * - :class:`DoGAffNetHardNet`
+ - The same, with AffNet shapes
+ - ``LAFOrienter(19)``
+ - ``(B, 1, H, W)``, 2048
+ - ``"dog_affnet_hardnet"``
+ * - :class:`KeyNetHardNet`
+ - :class:`KeyNetDetector`
+ - :class:`OriNet`
+ - ``(1, 1, H, W)`` in ``[0, 1]``, 8000
+ - none
+ * - :class:`KeyNetAffNetHardNet`
+ - :class:`KeyNetDetector`, AffNet shapes
+ - :class:`OriNet`
+ - ``(1, 1, H, W)`` in ``[0, 1]``, 8000
+ - ``"keynet_affnet_hardnet"``
+
+For a preset with a :class:`LightGlueMatcher` mode, drop the padded slots and pass its LAFs and descriptors to the
+matcher in that mode. The DoG presets return the 12-sigma frames that the ``"doghardnet"`` weights expect.
+
+.. _learned-local-features:
+
+Learned local features
+----------------------
+
+:class:`ALIKED`, :class:`DISK`, :class:`XFeat` and :class:`DeDoDe` detect and describe keypoints.
+Load them with ``from_pretrained`` to get pretrained weights and evaluation mode. Their constructors otherwise
+create models in training mode with random weights, except that the default ``DeDoDe()`` also loads a pretrained
+DINOv2 backbone. :class:`SOLD2_detector` detects line segments and loads pretrained weights by default.
+
+The four keypoint models return ``(x, y)`` pixel coordinates. To match one image pair with
+:class:`LightGlueMatcher`, use :func:`laf_from_center_scale_ori` on ``keypoints[None]`` to construct LAFs,
+then pass the LAFs and descriptors to the matcher in the mode listed below.
+Subtract 0.5 from DeDoDe's keypoints first to convert its half-pixel centres to integer pixel centres.
+:meth:`ALIKED.forward_laf` can return LAFs directly.
+
+XFeat returns inference tensors. Match these outputs under ``torch.no_grad()`` or ``torch.inference_mode()``
+(`#6533 <https://github.com/kornia/kornia/issues/6533>`_).
+The :doc:`image matching guide </applications/image_matching>` compares the speed and accuracy of the four
+keypoint models with the authors' code on each device.
+
+.. list-table:: Learned local features
+ :header-rows: 1
+ :widths: 14 30 38 18
+
+ * - Model
+ - Input
+ - Output
+ - ``LightGlueMatcher`` mode
+ * - :class:`ALIKED`
+ - RGB ``(B, 3, H, W)`` in ``[0, 1]``, or grayscale ``(B, 1, H, W)``, of any size
+ - one :class:`ALIKEDFeatures` per image: sub-pixel keypoints and 128-D descriptors (64-D for ``"aliked-t16"``);
+ :meth:`ALIKED.forward_laf` pads them into LAF tensors
+ - ``"aliked"`` (not for ``"aliked-t16"``)
+ * - :class:`DISK`
+ - RGB ``(B, 3, H, W)``, sides multiples of 16 unless ``pad_if_not_divisible=True``
+ - one :class:`DISKFeatures` per image: integer-pixel keypoints in raster order and 128-D descriptors
+ - ``"disk"``
+ * - :class:`XFeat`
+ - ``(B, C, H, W)``, any channel count, resized to multiples of 32
+ - :meth:`XFeat.detectAndCompute`: one dict per image, keypoints and 64-D descriptors;
+ :meth:`XFeat.match_xfeat` and :meth:`XFeat.match_xfeat_star` also match image pairs
+ - ``"xfeat"``
+ * - :class:`DeDoDe`
+ - RGB ``(B, 3, H, W)`` in ``[0, 1]``, padded to multiples of 14
+ - tensors of the ``n`` best keypoints of each image, ``(B, N, 2)`` with pixel ``i`` at ``i + 0.5``, their
+ scores and 256-D descriptions
+ - ``"dedodeb"``, ``"dedodeg"``
+ * - :class:`SOLD2_detector`
+ - grayscale ``(B, 1, H, W)`` in ``[0, 1]``, sides multiples of 8
+ - line segments, one ``(N, 2, 2)`` tensor of ``(row, col)`` endpoints per image; :class:`SOLD2` also describes
+ and matches them
+ - none
+
API reference
-------------
.. autoclass:: LocalFeature
:members: forward
-.. autoclass:: SOLD2_detector
- :members: forward
-
.. autoclass:: ALIKED
:members: forward, from_pretrained, forward_laf
@@ -136,6 +250,10 @@ API reference
.. autoclass:: DISK
:members: forward, from_pretrained, heatmap_and_dense_descriptors
+.. autoclass:: DISKFeatures
+ :undoc-members:
+ :members: x, y, to
+
.. autoclass:: XFeat
:members: from_pretrained, detectAndCompute, detectAndComputeDense, match_xfeat, match_xfeat_star
@@ -145,9 +263,8 @@ API reference
.. autoclass:: InterpolateSparse2d
:members: forward
-.. autoclass:: DISKFeatures
- :undoc-members:
- :members: x, y, to
+.. autoclass:: SOLD2_detector
+ :members: forward
.. autoclass:: SIFTFeatureScaleSpace
:members: forward
diff --git a/docs/source/feature.matching.rst b/docs/source/feature.matching.rst
index 8347a2b71..aadf970ef 100644
--- a/docs/source/feature.matching.rst
+++ b/docs/source/feature.matching.rst
@@ -3,6 +3,42 @@ Matching
.. currentmodule:: kornia.feature
+Descriptor matchers return ``(dists, idxs)``: one value and one index pair per match.
+Each row of ``idxs`` is ``(index in desc1, index in desc2)``.
+Choose the matcher by its acceptance rule, and interpret its first output as follows:
+
+.. list-table:: Matcher selection and scores
+ :header-rows: 1
+ :widths: 28 42 30
+
+ * - Matcher
+ - Acceptance rule
+ - First output
+ * - :func:`match_nn`, :func:`match_mnn`
+ - Nearest neighbour; MNN also requires the reverse match.
+ - Distance; lower is better.
+ * - :func:`match_snn`, :func:`match_smnn`
+ - Nearest-to-second-nearest ratio test; SMNN requires mutual matches and tests both directions.
+ - Ratio; lower is better. SMNN returns the larger ratio.
+ * - :func:`match_fginn`
+ - Ratio test against a geometrically inconsistent neighbour, using LAFs.
+ - Ratio; lower is better.
+ * - :func:`match_adalam`
+ - Local affine consistency using LAFs.
+ - Inverse confidence, or a squared-distance ratio in the no-seed fallback; lower is better.
+ * - :class:`LightGlueMatcher`
+ - Learned matching with pretrained weights for the selected feature.
+ - Matching score; higher is better.
+
+:class:`DescriptorMatcher` wraps NN, MNN, SNN and SMNN as a module.
+:class:`GeometryAwareDescriptorMatcher` wraps FGINN and AdaLAM.
+For padded batches of descriptor pairs, use :func:`match_smnn_batched`; its index rows include the batch index.
+To detect, describe and match two images in one call, use :class:`LocalFeatureMatcher` with a descriptor-only matcher.
+
+:class:`LightGlue` takes feature dictionaries and returns the full network outputs; :class:`OnnxLightGlue`
+runs an exported model. :class:`LoFTR` matches images directly, without a detector.
+To keep matches that agree with a geometric model, use :class:`~kornia.geometry.ransac.RANSAC`.
+
Descriptor matching
-------------------
diff --git a/docs/source/feature.rst b/docs/source/feature.rst
index 265db01a7..7a5ab86c1 100644
--- a/docs/source/feature.rst
+++ b/docs/source/feature.rst
@@ -6,8 +6,8 @@ kornia.feature
.. currentmodule:: kornia.feature
-Local feature detection, description and matching, from classical operators to pretrained models, all as
-differentiable PyTorch modules. For guidance on which model to pick, see the
+Local feature detection, description and matching, from classical operators to pretrained models, as PyTorch
+functions and classes. For guidance on which model to pick, see the
:doc:`image matching guide </applications/image_matching>`.
For classical SIFT, start with the explicit scale-space pyramid recipe in the
:ref:`SIFT pipeline guide <sift-pipelines>`. For supplied patches or frames, see
@@ -17,19 +17,23 @@ the :ref:`SIFT descriptor interfaces <sift-descriptor-interfaces>`.
:widths: 30 70
* - :doc:`feature.detectors`
- - Keypoint detectors: Harris, GFTT, Hessian, DoG responses and the KeyNet, scale-space and multi-resolution detectors.
+ - Detect LAFs only: the scale-space, multi-resolution and KeyNet detectors, and the Harris, GFTT, Hessian, DoG
+ and KeyNet response maps they take.
* - :doc:`feature.descriptors`
- - Patch, dense and supplied-frame SIFT descriptors; MKD, HardNet, HardNet8, HyNet, TFeat, SOSNet,
- and the SOLD2 line descriptor.
+ - Describe patches (SIFT, MKD, HardNet, HardNet8, HyNet, SOSNet, TFeat), the LAFs of an image (LAFDescriptor,
+ get_laf_descriptors, SIFT from a pyramid) or every position (dense SIFT); SOLD2 for line segments.
* - :doc:`feature.local_features`
- - Detector + descriptor pipelines: DISK, ALIKED, DeDoDe, XFeat, SIFTFeatureScaleSpace,
- SIFTFeature, KeyNetAffNetHardNet and friends.
+ - Detect and describe in one call: the learned ALIKED, DISK, XFeat and DeDoDe, the SIFT and HardNet presets of
+ LocalFeature, and the SOLD2 line detector.
* - :doc:`feature.matching`
- - Nearest-neighbour, mutual, ratio-test, FGINN and AdaLAM matching; LightGlue and LoFTR.
+ - Match descriptors by nearest neighbour, mutual check, ratio test, FGINN or AdaLAM, or with the learned
+ LightGlue (LightGlueMatcher, LightGlue, OnnxLightGlue); match two images in one call (LocalFeatureMatcher,
+ LoFTR).
* - :doc:`feature.laf`
- - Local affine frames (LAFs): patch extraction, normalization, orientation and affine shape estimation.
+ - Local affine frames (LAFs): build, read, transform and check them, sample their patches, and estimate their
+ orientation and affine shape.
* - :doc:`feature.layers`
- - Building-block layers and the DeFMO fast-moving-object model.
+ - HyNet's FRN and TLU layers, and the DeFMO fast-moving-object model.
.. toctree::
:hidden:
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index b7d8ee9a6..a30056406 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -1269,16 +1269,18 @@ x axis and its second column that of the patch's y axis. The Convention blocks o
:func:`~kornia.feature.laf_from_center_scale_ori` and :func:`~kornia.feature.extract_patches_from_pyramid` give the
full rules.
-- The scale is :math:`\sqrt{|\det A|}` and the orientation is ``atan2(a12, a11)`` in degrees. A positive orientation
- turns the patch's x axis counter-clockwise on screen, with image y pointing down: with an orientation of ``90``, the
- ``+x`` side of the patch shows what lies above the centre.
+- The scale is :math:`\sqrt{|\det A|}` and the orientation is ``atan2(a12, a11)`` in degrees. For a LAF of positive
+ determinant, a positive orientation turns the patch's x axis counter-clockwise on screen, with image y pointing
+ down: with an orientation of ``90``, the ``+x`` side of the patch shows what lies above the centre. For a mirrored
+ LAF, of negative determinant, it turns clockwise, and ``90`` puts the ``+x`` side below the centre.
- The region of a LAF is the ellipse ``c + A u`` over the unit vectors ``u``, and a ``PS x PS`` patch covers the
square ``c + A [-1, 1]^2``: patch row 0 is on the patch's ``-y`` side, the top for an upright LAF, and the columns
run along the patch's x axis.
- :func:`~kornia.feature.normalize_laf` divides the centre by ``max(W - 1, 1)`` and ``max(H - 1, 1)`` and ``A`` by
the smaller of the two; its Convention block covers moving a LAF to an image of another size.
-- kornia's LAF detectors pad the slots that no detection filled with an all-zero LAF and a zero response, so that a
- batch is one tensor. Drop those slots with :func:`~kornia.feature.laf_is_filled` before matching.
+- kornia's LAF detectors pad unused slots with an all-zero LAF and a zero response, so that a
+ batch is one tensor. :func:`~kornia.feature.laf_is_filled` is true for detections; index LAFs, responses and
+ descriptors with it to drop padding before matching.
- The ``match_*`` functions return ``(dists, idxs)``, one row per match; a lower ``dists`` is a better match.
See the Convention block of :func:`~kornia.feature.match_nn` for each matcher's distance definition.
- ``idxs`` holds ``(index in desc1, index in desc2)`` for unbatched matchers. :func:`~kornia.feature.match_smnn_batched`
@@ -1298,9 +1300,10 @@ OpenCV keypoints and SIFT descriptors convert as follows:
- ``KeyPoint.pt``, in the same pixel frame: copy it unchanged. The default upscaling of ``cv2.SIFT`` biases
``pt`` by a fraction of a pixel; ``enable_precise_upscale=True`` removes the bias
* - orientation
- - degrees, counter-clockwise on screen, read by :func:`~kornia.feature.get_laf_orientation`
- - ``KeyPoint.angle``, degrees clockwise on screen: ``angle = (-orientation) mod 360`` and
- ``orientation = -angle``
+ - degrees, counter-clockwise on screen for a LAF of positive determinant (clockwise for a mirrored one), read by
+ :func:`~kornia.feature.get_laf_orientation`
+ - For a circular similarity frame ``A = s R``, ``KeyPoint.angle`` is ``(-orientation) mod 360``. For a general
+ affine frame, use ``atan2(a21, a11)`` in degrees modulo 360. A keypoint cannot retain affine shape or reflection.
* - scale
- :math:`\sqrt{|\det A|}`, read by :func:`~kornia.feature.get_laf_scale`; the frames of
:class:`~kornia.feature.SIFTFeatureScaleSpace` have the scale :math:`6 \sigma` for the detection scale
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index fde37750d..1507d6ffd 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -15,9 +15,70 @@
# limitations under the License.
#
-"""Kornia Feature — Feature detection, description, and matching for Kornia.
+r"""Detect, describe and match local features, from classical operators to pretrained models.
-This subpackage provides modules for keypoint detection, descriptors, and feature matching.
+Images are floating-point tensors ``(B, C, H, W)`` in :math:`[0, 1]`. Keypoints use ``(x, y)`` pixels with integer
+pixel centres, except :class:`DeDoDe` and :class:`LoFTR`, which place pixel ``i`` at ``i + 0.5``. Line endpoints use
+``(row, col)``. See each model's conventions for resizing and coordinate limitations.
+
+A local affine frame (LAF) ``[A | c]`` has shape ``(B, N, 2, 3)`` in pixels. It describes a patch with centre ``c``,
+scale :math:`\sqrt{|\det A|}` and orientation ``atan2(a12, a11)`` in degrees. Detectors that return LAFs pad unused
+slots with zero frames. Use :func:`laf_is_filled` to keep detected features and discard padded slots; apply the
+same mask to LAFs, responses and descriptors.
+
+Which function to use:
+
+- Match images: :class:`LoFTR` without a detector; :class:`LocalFeatureMatcher` with a local feature and a
+ descriptor-only matcher; :meth:`~kornia.feature.XFeat.match_xfeat` or :meth:`~kornia.feature.XFeat.match_xfeat_star`.
+- Detect and describe learned keypoints: :class:`ALIKED` (subpixel), :class:`DISK` (integer pixels), :class:`XFeat`
+ (64-D descriptors) or :class:`DeDoDe` (separate detector and descriptor networks); load with ``from_pretrained``.
+- Store per-image learned features: :class:`ALIKEDFeatures` and :class:`DISKFeatures` hold keypoints and descriptors.
+- Compose a detector and a LAF descriptor: :class:`LocalFeature`; the presets below return the same output tuple.
+- Extract SIFT features: :class:`SIFTFeatureScaleSpace` refines scale-space extrema;
+ :class:`SIFTFeature` detects independently at each pyramid level and takes one image per call.
+- Extract HardNet features from blobs: :class:`DoGHardNet`, :class:`DoGAffNetHardNet` or :class:`HesAffNetHardNet`;
+ from corners: :class:`GFTTAffNetHardNet`; the AffNet presets also adapt affine shape.
+- Extract HardNet features with KeyNet: :class:`KeyNetHardNet` or :class:`KeyNetAffNetHardNet`, one image per call.
+- Detect LAFs: :class:`ScaleSpaceDetector` refines scale-space extrema in a batch; :class:`MultiResolutionDetector`
+ finds per-level 2D maxima in one image; :class:`KeyNetDetector` uses the learned :class:`KeyNet` response.
+- Score corners: :func:`harris_response` or :func:`gftt_response`; module forms: :class:`CornerHarris`,
+ :class:`CornerGFTT`.
+- Score blobs: :func:`hessian_response` or :func:`dog_response_single`; module forms: :class:`BlobHessian`,
+ :class:`BlobDoGSingle`; for Gaussian scale stacks: :func:`dog_response` and :class:`BlobDoG`.
+- Describe grayscale patches: :class:`SIFTDescriptor` or :class:`MKDDescriptor`; learned 32 x 32 descriptors:
+ :class:`HardNet`, :class:`HardNet8`, :class:`HyNet`, :class:`SOSNet`, :class:`TFeat`.
+- Describe LAFs in an image: :class:`LAFDescriptor` reuses a patch descriptor, :func:`get_laf_descriptors` takes one
+ per call, and :class:`SIFTDescriptorFromPyramid` computes SIFT without extracting patches.
+- Describe every position: :class:`DenseSIFTDescriptor`; convert SIFT bin layouts:
+ :func:`convert_sift_descriptor_layout`.
+- Orient LAFs: :class:`LAFOrienter` with :class:`PatchDominantGradientOrientation` or the learned :class:`OriNet`.
+- Adapt affine shape: :class:`LAFAffineShapeEstimator` with :class:`PatchAffineShapeEstimator`, or the learned
+ :class:`LAFAffNetShapeEstimator`; pass LAFs through unchanged: :class:`PassLAF`.
+- Match descriptors: :func:`match_nn` (nearest), :func:`match_mnn` (mutual), :func:`match_snn` (ratio test),
+ :func:`match_smnn` (mutual and ratio), or :class:`DescriptorMatcher`; padded batches: :func:`match_smnn_batched`.
+- Match descriptors with LAF geometry: :func:`match_fginn`, :func:`match_adalam` or
+ :class:`GeometryAwareDescriptorMatcher`.
+- Match with a learned model: :class:`LightGlueMatcher` takes descriptors and LAFs; :class:`LightGlue` takes feature
+ dictionaries; :class:`OnnxLightGlue` runs an exported model with onnxruntime.
+- Verify matches geometrically: :class:`~kornia.geometry.ransac.RANSAC` fits a model and selects its inliers.
+- Build LAFs: :func:`laf_from_center_scale_ori`, :func:`ellipse_to_laf` or :func:`laf_from_three_points`.
+- Read LAFs: :func:`get_laf_center`, :func:`get_laf_scale`, :func:`get_laf_orientation`, :func:`laf_to_three_points`
+ or :func:`laf_to_boundary_points`.
+- Transform LAFs: :func:`scale_laf`, :func:`rotate_laf`, :func:`set_laf_orientation`, :func:`make_upright`,
+ :func:`perspective_transform_lafs`, :func:`normalize_laf` or :func:`denormalize_laf`.
+- Check LAFs: :func:`laf_is_filled` selects detections, :func:`laf_is_valid` checks finite nonsingular frames,
+ :func:`laf_is_inside_image` checks bounds, and :func:`KORNIA_CHECK_LAF` checks shape.
+- Extract patches: :func:`extract_patches_from_pyramid` limits aliasing; :func:`extract_patches_simple` samples
+ directly.
+- Process line segments: :class:`SOLD2` detects, describes and matches; :class:`SOLD2_detector` detects only.
+- Reuse network components: :class:`FilterResponseNorm2d` and :class:`TLU` from HyNet; :class:`XFeatModel` and
+ :class:`InterpolateSparse2d` from XFeat.
+- Deblur a fast-moving object: :class:`DeFMO` produces RGBA sub-frames.
+
+:class:`LocalFeatureMatcher` accepts descriptor-only matchers. To use :class:`LightGlueMatcher`, extract features
+first and pass their descriptors and LAFs to it directly. For learned keypoints, construct LAFs with
+:func:`laf_from_center_scale_ori`; subtract 0.5 from DeDoDe coordinates first and match XFeat outputs with gradients
+disabled. See the model and matcher docstrings for complete recipes.
Choosing an implementation by device. Kornia's local-feature pipelines run at their authors' speed or faster on
CUDA, x86 and Apple M1 CPUs and Apple MPS, and are as accurate on the cohorts measured. Choose differently here:
@@ -28,8 +89,8 @@ CUDA, x86 and Apple M1 CPUs and Apple MPS, and are as accurate on the cohorts me
gradients or batches; :class:`SIFTFeature` takes one image per call, :class:`SIFTFeatureScaleSpace` a batch.
- :func:`match_snn` and :func:`match_smnn` on CUDA or the Apple M1 CPU: faiss's exact k-nearest-neighbour search
returns the same matches up to 2.2x faster. On the x86 CPU, kornia is the fastest.
-- :meth:`XFeat.match_xfeat_star` departs from the authors' refinement on purpose: much more accurate on planar
- scenes, mixed on PhotoTourism (see :class:`XFeat`).
+- :meth:`~kornia.feature.XFeat.match_xfeat_star` departs from the authors' refinement on purpose: much more
+ accurate on planar scenes, mixed on PhotoTourism (see :class:`XFeat`).
Figures per device and the protocol (640 px images, 2,048 features, PyTorch 2.14):
https://kornia.readthedocs.io/en/latest/applications/image_matching.html#feature-speed-by-device
diff --git a/kornia/feature/adalam/adalam.py b/kornia/feature/adalam/adalam.py
index 5a8306b1f..37c66a510 100644
--- a/kornia/feature/adalam/adalam.py
+++ b/kornia/feature/adalam/adalam.py
@@ -58,9 +58,17 @@ def match_adalam(
hw2: Optional[Sequence[int]] = None,
dm: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
- """Perform descriptor matching, followed by AdaLAM filtering.
-
- See :cite:`AdaLAM2020` for more details.
+ """Match descriptors by nearest neighbour, filtered by local affine model support (AdaLAM).
+
+ ``dists, idxs = match_adalam(desc1, desc2, lafs1, lafs2, hw1=(H1, W1), hw2=(H2, W2))`` takes two descriptor sets
+ ``(B1, D)`` and ``(B2, D)``, their LAFs ``(1, B1, 2, 3)`` and ``(1, B2, 2, 3)`` and, optionally, the image sizes
+ in the units of the LAF centres, pixels for LAFs in pixels. It matches every row of ``desc1`` to its nearest
+ neighbour in ``desc2`` and returns the matches that the local RANSACs around confident seed matches accept, each
+ match once: the inverse RANSAC confidences ``(B3, 1)``, float32, and the index pairs ``(B3, 2)``. The local
+ models read the LAF orientations and scales as well as the centres, and need no global model of the scene, see
+ :cite:`AdaLAM2020` for more details. To keep the matches that one global model explains instead, pass the
+ matches of :func:`~kornia.feature.match_snn` or :func:`~kornia.feature.match_smnn` to
+ :class:`~kornia.geometry.ransac.RANSAC`.
Convention:
- See the Convention block on :func:`~kornia.feature.match_nn`. ``dists`` is the inverse of the confidence of
@@ -87,18 +95,21 @@ def match_adalam(
seed and minimal fitting pair. Unlike the reference implementation, equal tiny residuals alone do not
imply duplicate keypoints. Their confidence uses a conservative residual-area floor of ``2**-24`` in
normalized coordinates, so inverse confidence stays finite even for an exact fit.
+ - Known defect: more accurate keypoints can keep fewer correct matches. On large images, keypoints with
+ sub-pixel noise lose correct matches that noisier ones keep, and a neighbourhood that mixes exact and
+ slightly noisy correct matches keeps the exact ones and few of the others
+ (`#5943 <https://github.com/kornia/kornia/issues/5943>`_).
Args:
desc1: Batch of descriptors of a shape ``(B1, D)``.
desc2: Batch of descriptors of a shape ``(B2, D)``.
lafs1: LAFs of a shape ``(1, B1, 2, 3)``.
lafs2: LAFs of a shape ``(1, B2, 2, 3)``.
- config: dict with AdaLAM config
- dm: torch.Tensor containing the non-negative distances (not squared) from each descriptor in desc1
- to each descriptor in desc2, shape of ``(B1, B2)``. Smaller is better.
+ config: dict with AdaLAM config, merged into the defaults; see the Convention block.
hw1: size of the first image, ``(H, W)`` or ``(W, H)``.
hw2: size of the second image, ``(H, W)`` or ``(W, H)``.
-
+ dm: torch.Tensor containing the non-negative distances (not squared) from each descriptor in desc1
+ to each descriptor in desc2, shape of ``(B1, B2)``. Smaller is better.
Return:
- Inverse local RANSAC confidence of each match, float32, shape of ``(B3, 1)``; see the Convention
@@ -106,6 +117,12 @@ def match_adalam(
- Long torch.Tensor indexes of matching descriptors in desc1 and desc2. Shape: ``(B3, 2)``,
where 0 <= B3 <= B1.
+ See Also:
+ - :func:`match_fginn`: a ratio test that reads the LAF centres of desc2 only, with no local models.
+ - :class:`GeometryAwareDescriptorMatcher`: the module form, with ``match_mode="adalam"`` and no image sizes.
+ - :class:`~kornia.geometry.ransac.RANSAC`: one global model, such as a homography or a fundamental matrix, for
+ all the matches.
+
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.py
index 1c3806e97..50f11d33b 100644
--- a/kornia/feature/affine_shape.py
+++ b/kornia/feature/affine_shape.py
@@ -46,9 +46,13 @@ urls["affnet"] = [
class PatchAffineShapeEstimator(nn.Module):
- r"""Module, which estimates the second moment matrix of the patch gradients.
+ r"""Estimate the affine shape of patches from the second-moment matrix of their gradients.
- The method determines the affine shape of the local feature as in :cite:`baumberg2000`.
+ ``abc = PatchAffineShapeEstimator(patch_size)(patches)`` takes ``(B, 1, patch_size, patch_size)`` patches and
+ returns the second-moment matrix of each patch's Gaussian-weighted gradients as the ellipse coefficients
+ ``(a, b, c)`` that :func:`ellipse_to_laf` reads, ``(B, 1, 3)``, divided by the largest entry, as in
+ :cite:`baumberg2000`. It returns coefficients, not LAFs: to adapt LAFs on an image, use
+ :class:`LAFAffineShapeEstimator`, which runs it on each LAF's patch.
For float16 and bfloat16 inputs, the gradients, Gaussian weighting, moments, and normalization are computed
in float32.
@@ -69,6 +73,12 @@ class PatchAffineShapeEstimator(nn.Module):
patch_size: the input image patch size.
eps: for safe division.
+ See Also:
+ - :class:`LAFAffineShapeEstimator`: runs it on each LAF's patch and adapts the LAF's shape to the result.
+ - :class:`LAFAffNetShapeEstimator`: a learned shape, which AffNet predicts on each LAF's patch.
+ - :class:`PatchDominantGradientOrientation`: the orientation of a patch, from the same Sobel gradients.
+ - :func:`ellipse_to_laf`: turns a centre and these coefficients into a LAF.
+
"""
def __init__(self, patch_size: int = 19, eps: float = 1e-10) -> None:
@@ -188,10 +198,14 @@ def _finalize_laf(
class LAFAffineShapeEstimator(nn.Module):
- r"""Adapt local affine frames using the second-moment matrices of their image-patch gradients.
+ r"""Adapt the affine shape of LAFs to the second-moment matrix of each LAF's image patch.
- It extracts a patch per LAF and runs :class:`~kornia.feature.PatchAffineShapeEstimator` on it to estimate the
- shape.
+ ``lafs = LAFAffineShapeEstimator(patch_size)(laf, img)`` takes ``(B, N, 2, 3)`` LAFs in pixels and their
+ grayscale images ``(B, 1, H, W)``, samples each LAF's patch through its upright frame, estimates the shape with
+ ``affine_shape_detector`` (:class:`PatchAffineShapeEstimator` by default) and returns the ``(B, N, 2, 3)`` LAFs
+ with the adapted shape and the input's centres and scales. For the shape that AffNet predicts, use
+ :class:`LAFAffNetShapeEstimator` instead; to drop the rotation and the reflection and keep the shape, without
+ reading the image, use :func:`make_upright`.
Convention:
- Each patch is sampled through the upright form of its LAF (:func:`~kornia.feature.make_upright`), so the
@@ -204,12 +218,24 @@ class LAFAffineShapeEstimator(nn.Module):
- The centre and the scale of the input LAF are kept. With ``preserve_orientation=True`` (the default) its
orientation is kept too; otherwise the output is upright, and an orientation estimator such as
:class:`~kornia.feature.LAFOrienter` can be run after this module.
+ - An adapted LAF has a positive determinant: a mirrored input loses its reflection. A LAF that
+ :func:`~kornia.feature.laf_is_valid` rejects, such as the all-zero padding of a detector's unfilled slot,
+ comes back unchanged with ``preserve_orientation=True``, and with a zero ``A`` and its centre otherwise. A
+ valid LAF whose patch gives no finite, positive-definite shape is not adapted either: it comes back
+ unchanged with ``preserve_orientation=True``, and as :func:`~kornia.feature.make_upright` returns it
+ otherwise.
Args:
patch_size: the input image patch size.
affine_shape_detector: Patch affine shape estimator, :class:`~kornia.feature.PatchAffineShapeEstimator`.
preserve_orientation: if True, the original orientation is preserved.
+ See Also:
+ - :class:`LAFAffNetShapeEstimator`: the same adaptation, with the shape that AffNet predicts.
+ - :class:`PatchAffineShapeEstimator`: the default ``affine_shape_detector``, on patches.
+ - :func:`make_upright`: drops the rotation and the reflection of a LAF and keeps its shape, without the image.
+ - :class:`LAFOrienter`: estimates the orientation, run after this module with ``preserve_orientation=False``.
+
""" # pylint: disable
def __init__(
@@ -269,11 +295,16 @@ class LAFAffineShapeEstimator(nn.Module):
class LAFAffNetShapeEstimator(nn.Module):
- """Adapt local affine frames using affine shapes estimated by the AffNet CNN.
+ """Adapt the affine shape of LAFs to the shape the learned AffNet CNN predicts on each LAF's patch.
- It extracts a patch per LAF and runs AffNet on it to estimate the shape. This is based on the original code from
- the paper "Repeatability Is Not Enough: Learning Discriminative Affine Regions via Discriminability".
- See :cite:`AffNet2018` for more details.
+ ``lafs = LAFAffNetShapeEstimator()(laf, img)`` builds AffNet with its pretrained weights, in eval mode, and takes
+ ``(B, N, 2, 3)`` LAFs in pixels and their grayscale images ``(B, 1, H, W)``, predicts each LAF's shape on its
+ 32 x 32 patch, sampled through its upright frame, and returns the ``(B, N, 2, 3)`` LAFs with that shape and the
+ input's centres and scales. :class:`GFTTAffNetHardNet`, :class:`HesAffNetHardNet`, :class:`DoGAffNetHardNet` and
+ :class:`KeyNetAffNetHardNet` run it with ``preserve_orientation=False``, before their orientation step. For the
+ second-moment estimate, which needs no weights, use :class:`LAFAffineShapeEstimator` instead. This is based on the
+ original code from the paper "Repeatability Is Not Enough: Learning Discriminative Affine Regions via
+ Discriminability". See :cite:`AffNet2018` for more details.
Convention:
As :class:`~kornia.feature.LAFAffineShapeEstimator`, with AffNet's prediction on a 32 x 32 patch in place of
@@ -284,6 +315,11 @@ class LAFAffNetShapeEstimator(nn.Module):
pretrained: Download and set pretrained weights to the model.
preserve_orientation: if True, the original orientation is preserved.
+ See Also:
+ - :class:`LAFAffineShapeEstimator`: the same adaptation, with the second-moment matrix and no weights.
+ - :class:`OriNet`: the orientation network of the same paper.
+ - :class:`KeyNetAffNetHardNet`: a local feature that runs it on KeyNet detections, before OriNet and HardNet.
+
"""
def __init__(self, pretrained: bool = True, preserve_orientation: bool = True) -> None:
@@ -322,7 +358,7 @@ class LAFAffNetShapeEstimator(nn.Module):
@staticmethod
def _normalize_input(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
- """Normalize the input by batch."""
+ """Subtract each patch's mean and divide by its standard deviation plus ``eps``."""
# `torch.std_mean` decomposes to `prims.sum`, which has no ONNX lowering; the split form is equivalent.
mp = torch.mean(x, dim=(-3, -2, -1), keepdim=True)
sp = torch.std(x, dim=(-3, -2, -1), keepdim=True)
diff --git a/kornia/feature/aliked/aliked.py b/kornia/feature/aliked/aliked.py
index 28f413365..055014b71 100644
--- a/kornia/feature/aliked/aliked.py
+++ b/kornia/feature/aliked/aliked.py
@@ -77,10 +77,13 @@ from .deform_conv2d import deform_conv2d
@dataclass
class ALIKEDFeatures:
- r"""Keypoints, descriptors and scores detected by ALIKED for a single image.
+ r"""Hold the sub-pixel keypoints, descriptors and scores that ALIKED detects in one image.
- Since ALIKED detects a varying number of keypoints per image,
- ``ALIKEDFeatures`` is not batched.
+ ``features = aliked(images)[b]`` is what :class:`ALIKED` returns for image ``b``: ``features.keypoints``
+ ``(N, 2)``, sub-pixel ``(x, y)`` pixels, ``features.descriptors`` ``(N, D)``, L2-normalised, and
+ ``features.keypoint_scores`` ``(N,)``, with ``N = features.n``. It is not batched, because ALIKED detects a
+ different number of keypoints in each image; ``features.to(device)`` moves the three tensors. For the keypoints
+ of a whole batch as padded LAF tensors, use :meth:`ALIKED.forward_laf` instead.
Convention:
The keypoints, descriptors and scores that :class:`~kornia.feature.ALIKED` returns for one image; its
@@ -90,6 +93,11 @@ class ALIKEDFeatures:
keypoints: pixel coordinates ``(N, 2)`` as ``[x, y]``.
descriptors: L2-normalised descriptors ``(N, D)``.
keypoint_scores: detection confidence scores ``(N,)``.
+
+ See Also:
+ - :class:`ALIKED`: the detector, which returns one of these per image.
+ - :class:`DISKFeatures`: the same container for :class:`DISK`, whose keypoints are integer pixels.
+
"""
keypoints: torch.Tensor
@@ -440,7 +448,7 @@ class InputPadder:
self._pad = [pad_wd // 2, pad_wd - pad_wd // 2, pad_ht // 2, pad_ht - pad_ht // 2]
def pad(self, x: torch.Tensor) -> torch.Tensor:
- """Pad *x* (BCHW)."""
+ """Replicate-pad ``x`` ``(B, C, H, W)`` around its centre to multiples of ``divis_by``."""
return F.pad(x, self._pad, mode="replicate")
def unpad(self, x: torch.Tensor) -> torch.Tensor:
@@ -511,10 +519,10 @@ class DeformableConv2d(nn.Module):
r"""Run the module forward pass.
Args:
- x: Input feature map with shape :math:`(B, C_{\text{in}}, H, W)`.
+ x: Input feature map with shape ``(B, C_in, H, W)``.
Returns:
- Deformable convolution output with shape :math:`(B, C_{\text{out}}, H', W')`.
+ Deformable convolution output with shape ``(B, C_out, H', W')``.
"""
h, w = x.shape[2:]
max_offset = max(h, w) / 4.0
@@ -590,10 +598,10 @@ class ConvBlock(nn.Module):
r"""Run the module forward pass.
Args:
- x: Input feature map with shape :math:`(B, C_{\text{in}}, H, W)`.
+ x: Input feature map with shape ``(B, C_in, H, W)``.
Returns:
- Feature map with shape :math:`(B, C_{\text{out}}, H, W)` after two gated conv-BN layers.
+ Feature map with shape ``(B, C_out, H, W)`` after two gated conv-BN layers.
"""
x = self.gate(self.bn1(self.conv1(x)))
return self.gate(self.bn2(self.conv2(x)))
@@ -640,10 +648,10 @@ class ResBlock(nn.Module):
r"""Run the module forward pass.
Args:
- x: Input feature map with shape :math:`(B, C_{\text{in}}, H, W)`.
+ x: Input feature map with shape ``(B, C_in, H, W)``.
Returns:
- Feature map with shape :math:`(B, C_{\text{out}}, H', W')` after the residual block,
+ Feature map with shape ``(B, C_out, H', W')`` after the residual block,
where ``H'`` and ``W'`` may differ from the input if ``stride > 1``.
"""
identity = x
@@ -801,13 +809,21 @@ _CHECKPOINT_URLS = [
class ALIKED(nn.Module):
- r"""ALIKED local feature detector and descriptor.
-
- ALIKED (Adaptive Local Image KEypoint Detection) combines a multi-scale
- ResNet backbone with deformable descriptor sampling (SDDH) and a
- differentiable keypoint detector (DKD).
-
- See :cite:`zhao2023aliked` for details.
+ r"""Detect sub-pixel keypoints in images of any size, described by deformable sampling (ALIKED).
+
+ ``aliked = ALIKED.from_pretrained("aliked-n16")`` loads the trained weights in evaluation mode, and
+ ``features = aliked(images)`` takes RGB images ``(B, 3, H, W)`` in :math:`[0, 1]`, or grayscale ``(B, 1, H, W)``,
+ of any height and width, and returns a list of ``B`` :class:`ALIKEDFeatures`, one per image. Each holds sub-pixel
+ keypoints ``(N, 2)`` as ``(x, y)`` pixels, their scores ``(N,)`` and L2-normalised descriptors ``(N, D)``, with
+ ``D`` 128, or 64 for ``"aliked-t16"``, and ``N`` set by the image's score map. With
+ ``lafs, responses, descs = aliked.forward_laf(images)``, the same keypoints, scores and descriptors come as
+ tensors ``(B, N, 2, 3)``, ``(B, N, 1)`` and ``(B, N, D)``, padded to the largest ``N`` of the batch. To match two
+ images, pass the 128-D descriptors with ``laf_from_center_scale_ori(keypoints[None])`` to
+ :class:`LightGlueMatcher` in ``"aliked"`` mode; for the same number of keypoints in every image, use
+ :class:`DeDoDe` instead.
+
+ ALIKED (Adaptive Local Image KEypoint Detection) combines a multi-scale ResNet backbone with deformable
+ descriptor sampling (SDDH) and a differentiable keypoint detector (DKD); see :cite:`zhao2023aliked` for details.
Speed against the authors' Python code (640 px, 2,048 keypoints): on CUDA, compile the model for repeated
inference. Eager, it runs at 0.8x the authors' speed on an RTX 4090, because its PyTorch deformable convolution
@@ -821,12 +837,13 @@ class ALIKED(nn.Module):
- ``ALIKED()`` builds random weights in training mode, where BatchNorm normalises with the batch, updates its
running statistics on every call, and a single small image raises; call ``.eval()`` for inference.
:meth:`from_pretrained` returns the trained model in evaluation mode.
- - ``images`` are RGB in :math:`[0, 1]`, the range of the pretrained weights, and the network applies no
- normalisation; a ``(B, 1, H, W)`` image is repeated to three channels. Any ``H`` and ``W`` work: the
- image is replicate-padded around its centre to multiples of 32 and the maps are cropped back, so the padding
- does not move the keypoints.
- - :meth:`forward` returns one :class:`ALIKEDFeatures` per image. Its keypoints are sub-pixel ``(x, y)`` in the
- pixel frame of :func:`~kornia.feature.laf_from_center_scale_ori`
+ - The network applies no normalisation, so pass images in :math:`[0, 1]`, the range of the pretrained
+ weights; a ``(B, 1, H, W)`` image is repeated to three channels, and other channel counts raise. Any ``H``
+ and ``W`` work: the image is replicate-padded around its centre to multiples of 32 and the maps are cropped
+ back, so the padding does not move the keypoints. The image must have the model's dtype: a float16,
+ bfloat16 or float64 image raises on a float32 model, so cast the model first, ``aliked.to(images.dtype)``.
+ - The keypoints of :meth:`forward` are sub-pixel ``(x, y)`` in the pixel convention of
+ :func:`~kornia.feature.laf_from_center_scale_ori`
(see :ref:`Local features <local-features-conventions>`): a strict maximum of the score map in its
``2 * nms_radius + 1`` window (see the note), at least ``nms_radius`` pixels from the border, moved by a
soft-argmax over that window. Its score is the score map read bilinearly there, and the descriptors are
@@ -841,8 +858,9 @@ class ALIKED(nn.Module):
- ``image_size`` holds the valid ``(W, H)`` of each image of a batch padded at the bottom and right to a
common size: maxima closer than ``nms_radius`` pixels to that image's last valid row or column are dropped.
- :meth:`forward_laf` returns padded tensors like :class:`~kornia.feature.LocalFeature`, but ``N`` is the
- largest keypoint count in the batch and the responses are ``(B, N, 1)``. Its ``mask`` multiplies the
- score map, and it takes no ``image_size``.
+ largest keypoint count in the batch and the responses are ``(B, N, 1)``. Padded slots hold zero LAFs,
+ responses and descriptors; ``laf_is_filled(lafs)`` is true for detections, so index every output with it to
+ discard the padding. Its ``mask`` multiplies the score map, and it takes no ``image_size``.
- Known defects: on CPU, float16 and bfloat16 score and feature maps go to torch's ``grid_sample`` without
an upcast: the half-precision kernel can return wrong values, NaN or overflow, and where torch has none the
call raises (`#5810 <https://github.com/kornia/kornia/issues/5810>`_).
@@ -873,6 +891,17 @@ class ALIKED(nn.Module):
the mean score only when no image of the batch has a maximum above the threshold; kornia returns maxima only
and decides the fallback for each image, so an image's keypoints do not depend on the rest of the batch.
+ See Also:
+ - :class:`ALIKEDFeatures`: the per-image result of :meth:`forward`.
+ - :class:`DISK`: learned integer-pixel keypoints with 128-D descriptors, for RGB images whose sides are
+ multiples of 16.
+ - :class:`XFeat`: learned keypoints with 64-D descriptors, and its own mutual-nearest-neighbour and refined
+ matching of image pairs.
+ - :class:`DeDoDe`: separate learned detector and descriptor networks, with ``n`` keypoints in every image.
+ - :class:`LocalFeature`: a classical detector and LAF descriptor in one call; :meth:`forward_laf` returns
+ padded LAF tensors like it, with ``(B, N, 1)`` responses.
+ - :class:`LightGlueMatcher`: matches ALIKED's descriptors and keypoints with the ``"aliked"`` weights.
+
Example:
>>> aliked = ALIKED.from_pretrained('aliked-n16') # doctest: +SKIP
>>> images = torch.rand(1, 3, 256, 256) # doctest: +SKIP
@@ -1061,8 +1090,8 @@ class ALIKED(nn.Module):
With ``compute_affine=True`` the 2x2 block ``A`` of each LAF comes from
the covariance of the soft-argmax weights in the keypoint's
- ``2 * nms_radius + 1`` detection window, computed inside :class:`DKD`
- without any additional network parameters: ``A @ A.T`` is that
+ ``2 * nms_radius + 1`` detection window, computed by the keypoint detection
+ step (``DKD``) without any additional network parameters: ``A @ A.T`` is that
covariance, so the axes of the frame are its principal axes, and
``det A > 0`` (the frame is never mirrored). The frame describes how
sharply the score map peaks, not an image structure. Its scale
@@ -1076,7 +1105,8 @@ class ALIKED(nn.Module):
batched tensors.
Args:
- img: image to extract features with shape ``(B,C,H,W)``.
+ img: image to extract features with shape ``(B, 3, H, W)``, or ``(B, 1, H, W)``, repeated to three
+ channels.
mask: optional spatial mask ``(B, 1, H, W)`` with values in
``[0, 1]``; the score map is multiplied by this mask before
keypoint detection so that features are suppressed in masked
@@ -1084,13 +1114,13 @@ class ALIKED(nn.Module):
compute_affine: if ``True`` (default), estimate the 2x2 affine shape
of each LAF using ``torch.linalg.eigh`` on the soft-argmax
covariance. Set to ``False`` to skip the eigendecomposition and
- return identity affines, which is faster and avoids the linalg
- call entirely (useful when only keypoint positions are needed).
+ return identity affines, which avoids the linalg call entirely
+ (useful when only keypoint positions are needed).
Returns:
- - Detected local affine frames with shape ``(B,N,2,3)``.
- - Response function values for corresponding LAFs with shape ``(B,N,1)``.
- - Local descriptors of shape ``(B,N,D)``.
+ - Detected local affine frames with shape ``(B, N, 2, 3)``.
+ - Response function values for corresponding LAFs with shape ``(B, N, 1)``.
+ - Local descriptors of shape ``(B, N, D)``.
"""
if img.shape[1] == 1:
@@ -1164,7 +1194,7 @@ class ALIKED(nn.Module):
nms_radius: int = 2,
device: Optional[torch.device] = None,
) -> ALIKED:
- """Load a pretrained ALIKED model from the official checkpoint repository.
+ """Build an ALIKED model and load the pretrained checkpoint of ``model_name``, in evaluation mode.
Args:
model_name: one of ``'aliked-t16'``, ``'aliked-n16'``,
diff --git a/kornia/feature/dedode/dedode.py b/kornia/feature/dedode/dedode.py
index f78dc0d39..1e6b0b370 100644
--- a/kornia/feature/dedode/dedode.py
+++ b/kornia/feature/dedode/dedode.py
@@ -77,26 +77,37 @@ urls: Dict[str, Dict[str, str]] = {
class DeDoDe(nn.Module):
- r"""nn.Module which detects and/or describes local features in an image using the DeDode method.
+ r"""Detect the n best keypoints of each RGB image and describe them with two networks (DeDoDe).
+
+ ``dedode = DeDoDe.from_pretrained(detector_weights="L-C4-v2", descriptor_weights="B-upright")`` loads trained
+ weights in evaluation mode. ``keypoints, scores, descriptions = dedode(images, n=10_000)`` takes RGB images
+ ``(B, 3, H, W)`` in :math:`[0, 1]` and returns the best ``N = min(n, H W)`` keypoints per image.
+ Outputs are ``(x, y)`` pixel coordinates ``(B, N, 2)`` with pixel centres at ``i + 0.5``, scores ``(B, N)``
+ and unnormalised descriptors ``(B, N, 256)``. Use :class:`ALIKED` or :class:`DISK` when the keypoint count
+ should depend on image content.
See :cite:`edstedt2024dedode` for details.
Convention:
+ - :meth:`detect` and :meth:`describe` run the detector and descriptor separately. The default descriptor,
+ ``G``, combines VGG19 with a frozen DINOv2 ViT-L/14 backbone and loads the backbone's weights in the
+ constructor. Descriptor ``B`` uses VGG19 alone.
+ - For :class:`LightGlueMatcher`, construct LAFs centred on the keypoints minus 0.5 and pass them with the
+ descriptors in ``"dedodeb"`` or ``"dedodeg"`` mode, matching the descriptor variant.
- :meth:`forward`, :meth:`detect` and :meth:`describe` take RGB images in the range :math:`[0, 1]` and apply
the ImageNet normalization themselves; pass ``apply_imagenet_normalization=False`` for images that are
already normalized. ``pad_if_not_divisible`` zero-pads the normalized image at the bottom and right to
multiples of 14, so the padding is the ImageNet mean colour, and removes it from the maps again.
- - :meth:`forward` returns pixel ``i`` as ``i + 0.5``: subtract 0.5 for the pixel frame of
+ - :meth:`forward` returns pixel ``i`` as ``i + 0.5``: subtract 0.5 for the pixel convention of
:func:`~kornia.feature.laf_from_center_scale_ori` (see :ref:`Local features <local-features-conventions>`).
:meth:`detect` returns it normalized, as ``(2 i + 1) / (W, H) - 1`` in :math:`[-1, 1]`
(``align_corners=False``), the form :meth:`describe` takes; ``(k + 1) * (W, H) / 2 - 0.5`` converts such a
``k`` to kornia's frame. A description is read at the centre of pixel ``i``.
- - Each image gives its ``n`` best keypoints by score, in descending order: :math:`N = \min(n, H W)`, with no
- threshold and no padding. Keypoints, and the descriptions of :meth:`forward` and of
- ``describe(images, keypoints)``, are float32; descriptions are not normalized. The scoremap softmax and the
- keypoint sampling run in at least float32, so the scores are float32 for a half-precision model and float64
- for a float64 one. The dense map of ``describe(images)`` follows the network dtype: ``amp_dtype`` on CUDA,
- the dtype of the model on CPU and MPS.
+ - The keypoints of an image come in descending order of score, with no threshold and no padding. Keypoints,
+ and the descriptions of :meth:`forward` and of ``describe(images, keypoints)``, are float32. The scoremap
+ softmax and the keypoint sampling run in at least float32, so the scores are float32 for a half-precision
+ model and float64 for a float64 one. The dense map of ``describe(images)`` follows the network dtype:
+ ``amp_dtype`` on CUDA, the dtype of the model on CPU and MPS.
- kornia detects and describes at the size of the input. The authors resize every image to 784 x 784, without
keeping its aspect ratio, in ``detect_from_path`` and ``describe_keypoints_from_path``, and train the
detector and the ``B`` descriptor at 512 x 512 (``G`` at 560 x 560). The 51-pixel coverage window of the
@@ -108,10 +119,20 @@ class DeDoDe(nn.Module):
and MPS it has no effect, so the default argument runs there with float32 weights and images.
Args:
- detector_model: The detector model kind. Available options are: `L`.
- descriptor_model: The descriptor model kind. Available options are: `G` or `B`
+ detector_model: The detector model kind. Available options are: ``"L"``.
+ descriptor_model: The descriptor model kind. Available options are: ``"G"`` or ``"B"``.
amp_dtype: The dtype of the automatic mixed precision used on CUDA; it has no effect on other devices.
+ See Also:
+ - :class:`ALIKED`: learned sub-pixel keypoints whose count follows each image's score map, for RGB images of
+ any size.
+ - :class:`DISK`: learned integer-pixel keypoints with 128-D descriptors from one U-Net, for RGB images whose
+ sides are multiples of 16.
+ - :class:`XFeat`: learned keypoints with 64-D descriptors, and its own mutual-nearest-neighbour and refined
+ matching of image pairs.
+ - :class:`LightGlueMatcher`: matches the descriptions and keypoints with the ``"dedodeb"`` weights for the
+ ``B`` descriptor and the ``"dedodeg"`` weights for ``G``.
+
Example:
>>> dedode = DeDoDe.from_pretrained(detector_weights="L-C4-v2", descriptor_weights="B-upright")
>>> images = torch.rand(1, 3, 256, 256)
@@ -162,7 +183,7 @@ class DeDoDe(nn.Module):
Args:
images: A torch.Tensor of shape ``(B, 3, H, W)`` containing the RGB input images in the range
:math:`[0, 1]`.
- n: The number of keypoints to detect.
+ n: The number of keypoints to detect in each image, at most ``H W``; ``None`` keeps every pixel.
apply_imagenet_normalization: Whether to apply ImageNet normalization to the input images. Pass
``False`` if they are already ImageNet-normalized.
pad_if_not_divisible: Zero-pad the (normalised) image on the bottom and right so that H and W are
@@ -170,8 +191,8 @@ class DeDoDe(nn.Module):
keypoints are never reported in it.
Returns:
- keypoints: A torch.Tensor of shape ``(B, N, 2)`` containing the detected keypoints in the image range,
- unlike `.detect()` function.
+ keypoints: A torch.Tensor of shape ``(B, N, 2)`` containing the detected keypoints in pixels, with pixel
+ ``i`` at ``i + 0.5``, unlike :meth:`detect`, which normalises them.
scores: A torch.Tensor of shape ``(B, N)`` containing the scores of the detected keypoints.
diff --git a/kornia/feature/dedode/transformer/__init__.py b/kornia/feature/dedode/transformer/__init__.py
index 1532a738a..7eb0fa7f4 100644
--- a/kornia/feature/dedode/transformer/__init__.py
+++ b/kornia/feature/dedode/transformer/__init__.py
@@ -15,9 +15,16 @@
# limitations under the License.
#
-"""Kornia Feature DeDoDe Transformer — Transformer backbones for DeDoDe feature detector.
+"""Vision transformer backbones for DeDoDe: the frozen DINOv2 ViT-L of its G descriptor.
-This subpackage provides transformer models for DeDoDe feature extraction.
+The backbone takes images ``(B, 3, H, W)`` whose ``H`` and ``W`` are multiples of its patch size, 14 for the DINOv2
+weights, and none of its parameters requires gradients.
+
+Which function to use:
+
+- The DINOv2 ViT-L/14 architecture, to load the ``dinov2_vitl14_pretrain.pth`` weights into: :func:`vit_large`,
+ with the keyword arguments its docstring gives. For keypoints and their descriptions, use
+ :class:`~kornia.feature.DeDoDe`, which builds and loads it for its ``G`` descriptor.
"""
from .dinov2 import vit_large
diff --git a/kornia/feature/dedode/transformer/dinov2.py b/kornia/feature/dedode/transformer/dinov2.py
index 622744a69..5deba520f 100644
--- a/kornia/feature/dedode/transformer/dinov2.py
+++ b/kornia/feature/dedode/transformer/dinov2.py
@@ -214,7 +214,7 @@ class DinoVisionTransformer(nn.Module):
h: Image height in pixels.
Returns:
- Positional embedding tensor resized to match the current patch grid, shape :math:`(1, N'+1, D)`.
+ Positional embedding tensor resized to match the current patch grid, shape ``(1, N' + 1, D)``.
"""
previous_dtype = x.dtype
npatch = x.shape[1] - 1
@@ -353,7 +353,8 @@ class DinoVisionTransformer(nn.Module):
Returns:
During training: full feature dictionary from ``forward_features``.
- During inference: class token projection with shape :math:`(B, \text{out\_dim})`.
+ During inference: the normalised class token with shape ``(B, embed_dim)``, through the identity
+ ``head``.
"""
ret = self.forward_features(*args, **kwargs)
if is_training:
@@ -396,7 +397,26 @@ def vit_base(patch_size=16, **kwargs) -> DinoVisionTransformer:
def vit_large(patch_size=16, **kwargs) -> DinoVisionTransformer:
- """Return ViT Large."""
+ """Build the DINOv2 ViT-L vision transformer that DeDoDe's G descriptor runs as its frozen backbone.
+
+ ``backbone = vit_large(patch_size=14, img_size=518, init_values=1.0, ffn_layer="mlp", block_chunks=0)`` builds
+ the ViT-L architecture of the ``dinov2_vitl14_pretrain.pth`` checkpoint, 24 blocks of width 1024 with 16 heads,
+ with random weights and every parameter frozen (``requires_grad`` is ``False``); load the checkpoint with
+ ``backbone.load_state_dict``, as :class:`~kornia.feature.DeDoDe` does for its ``G`` descriptor. Then
+ ``backbone.forward_features(images)["x_norm_patchtokens"]`` takes images ``(B, 3, H, W)`` with ``H`` and ``W``
+ multiples of ``patch_size`` and returns one token per patch, ``(B, (H / patch_size) * (W / patch_size), 1024)``,
+ and ``backbone(images)`` returns the class token ``(B, 1024)``. The defaults, ``patch_size=16``,
+ ``img_size=224``, no layer scale (``init_values=None``) and ``block_chunks=1``, do not match that checkpoint.
+ The other keyword arguments go to ``DinoVisionTransformer``, except ``embed_dim``, ``depth``, ``num_heads``,
+ ``mlp_ratio`` and ``block_fn``, which this function sets.
+
+ See Also:
+ - :class:`~kornia.feature.DeDoDe`: builds this backbone for its ``G`` descriptor and loads the DINOv2 weights
+ into it.
+ - :class:`~kornia.models.vit.VisionTransformer`: kornia's general ViT encoder, which loads AugReg weights
+ rather than DINOv2's.
+
+ """
return DinoVisionTransformer(
patch_size=patch_size,
embed_dim=1024,
diff --git a/kornia/feature/defmo.py b/kornia/feature/defmo.py
index b02eedc8d..8076c2101 100644
--- a/kornia/feature/defmo.py
+++ b/kornia/feature/defmo.py
@@ -345,7 +345,7 @@ class RenderingDeFMO(nn.Module):
``(B, C, H, W)``.
Returns:
- Tensor with shape :math:`(B, T, 4, H_{out}, W_{out})`, where ``T`` is the
+ Tensor with shape ``(B, T, 4, H_out, W_out)``, where ``T`` is the
number of rendered time steps and 4 represents RGBA channels.
"""
# cast into a local rather than relying on the caller having matched dtype --
@@ -370,10 +370,14 @@ class RenderingDeFMO(nn.Module):
class DeFMO(nn.Module):
- """nn.Module that disentangle a fast-moving object from the background and performs deblurring.
+ """Deblur a fast-moving object into 24 RGBA sub-frames of the object alone (DeFMO).
- This is based on the original code from paper "DeFMO: Deblurring and Shape Recovery
- of Fast Moving Objects". See :cite:`DeFMO2021` for more details.
+ ``defmo = DeFMO()`` builds the network with its pretrained weights, in eval mode, and ``frames = defmo(x)`` takes
+ ``(B, 6, H, W)`` inputs, each a blurred RGB image followed by an RGB estimate of its background, and returns
+ ``(B, 24, 4, H, W)``, with ``H`` and ``W`` rounded up to multiples of 16: the object at 24 instants in time order,
+ each an RGBA image whose alpha channel separates it from the background, which is not rendered. It is an image
+ model, not a local feature: it detects and describes nothing. This is based on the original code from paper
+ "DeFMO: Deblurring and Shape Recovery of Fast Moving Objects". See :cite:`DeFMO2021` for more details.
Convention:
- The input is ``(B, 6, H, W)``: the RGB channels of the blurred image, then those of the background
@@ -383,13 +387,15 @@ class DeFMO(nn.Module):
``k / 23``, each with red, green, blue and alpha channels in :math:`[0, 1]` after a sigmoid.
Args:
- pretrained: Download and set pretrained weights to the model. Default: True.
+ pretrained: Download and set pretrained weights to the model, and return it in eval mode. Default: True.
+ With ``False`` the weights are random and the model is in training mode.
Returns:
Temporal super-resolution without background.
+
Shape:
- - Input: (B, 6, H, W)
- - Output: (B, S, 4, H, W), with H and W rounded up to multiples of 16
+ - Input: ``(B, 6, H, W)``
+ - Output: ``(B, 24, 4, H, W)``, with ``H`` and ``W`` rounded up to multiples of 16
Examples:
>>> import kornia
@@ -421,7 +427,7 @@ class DeFMO(nn.Module):
Returns:
Tensor with shape ``(B, T, 4, H, W)``, where ``T`` is the number of
- temporal sub-frames and 4 stores red, green, blue, and alpha channels.
+ temporal sub-frames, 24, and 4 stores red, green, blue, and alpha channels.
"""
latent = self.encoder(input_data)
return self.rendering(latent)
diff --git a/kornia/feature/disk/disk.py b/kornia/feature/disk/disk.py
index 8734e86a5..1a43c0891 100644
--- a/kornia/feature/disk/disk.py
+++ b/kornia/feature/disk/disk.py
@@ -42,13 +42,22 @@ urls: dict[str, list[str]] = {
class DISK(nn.Module):
- r"""nn.Module which detects and describes local features in an image using the DISK method.
+ r"""Detect integer-pixel keypoints and describe them with the dense maps of one U-Net (DISK).
+
+ ``disk = DISK.from_pretrained("depth")`` loads trained weights in evaluation mode.
+ ``features = disk(images, n=2048)`` takes RGB images ``(B, 3, H, W)`` and returns one :class:`DISKFeatures`
+ per image: up to ``n`` integer-pixel keypoints ``(N, 2)``, scores ``(N,)`` and L2-normalised descriptors
+ ``(N, 128)``. Image dimensions must be multiples of 16 unless ``pad_if_not_divisible=True``.
+ Use :class:`ALIKED` for subpixel keypoints or :class:`DeDoDe` for a fixed keypoint budget per image.
See :cite:`tyszkiewicz2020disk` for details.
.. image:: _static/img/disk_outdoor_depth.jpg
Convention:
+ - ``DISK()`` creates random weights in training mode. For matching, construct LAFs with
+ :func:`~kornia.feature.laf_from_center_scale_ori` on ``keypoints[None]`` and pass them with the descriptors
+ to :class:`LightGlueMatcher` in ``"disk"`` mode.
- ``images`` are RGB, ``(B, 3, H, W)``, which the U-Net sees as given, without normalisation. With the
default U-Net, a common positive gain of the input, such as :math:`[0, 255]` instead of :math:`[0, 1]`,
changes the outputs only through the instance norms' ``eps``, which weighs more the lower the image's
@@ -58,9 +67,11 @@ class DISK(nn.Module):
bark ``img1`` differ in 0 to 2 keypoints, in 2 to 6 % of them with the intensities multiplied by 0.1, and
in about 30 % multiplied by 0.01. ``H`` and ``W`` must be multiples of 16, unless
``pad_if_not_divisible=True`` zero-pads the bottom and right, in which case the maps are cropped back to the
- image before the suppression and no keypoint lies in the padding.
- - Each image gives a :class:`DISKFeatures`. Keypoints are the integer ``(x, y)`` pixels of the strict heatmap
- maxima (see the note), in the pixel frame of :func:`~kornia.feature.laf_from_center_scale_ori`
+ image before the suppression and no keypoint lies in the padding. The image must have the network's
+ dtype: a float16, bfloat16 or float64 image raises on a float32 model, so cast the model first,
+ ``disk.to(images.dtype)``.
+ - Keypoints are the integer ``(x, y)`` pixels of the strict heatmap
+ maxima (see the note), using the pixel convention of :func:`~kornia.feature.laf_from_center_scale_ori`
(see :ref:`Local features <local-features-conventions>`), listed in raster order (row by row, then column
by column) rather than by score, in float32 for a float16 or bfloat16 network and otherwise in the dtype
of the network's output. ``detection_scores`` are the heatmap values there, in the network's dtype, and
@@ -75,8 +86,7 @@ class DISK(nn.Module):
unet: The U-Net to use. If None, a default U-Net is used. Kornia doesn't provide the training code for DISK
so this is only useful when using a custom checkpoint trained using the code released with the paper.
The unet should take as input a torch.Tensor of shape ``(B, C, H, W)`` and output
- a torch.Tensor of shape
- :math:`(B, \mathrm{desc\_dim} + 1, H, W)`.
+ a torch.Tensor of shape ``(B, desc_dim + 1, H, W)``: the descriptors, then the heatmap.
Note:
Keypoints are the strict local maxima of the heatmap: :func:`~kornia.geometry.subpix.nms2d` keeps a position
@@ -91,6 +101,18 @@ class DISK(nn.Module):
``n`` maxima or fewer, and every maximum tied across the cut. kornia's ``n`` is an upper bound, so such an
image keeps every maximum, and a tie at the cut is filled in raster order.
+ See Also:
+ - :class:`DISKFeatures`: the per-image result of :meth:`forward`.
+ - :class:`ALIKED`: learned sub-pixel keypoints for RGB images of any size, also as padded LAF tensors.
+ - :class:`XFeat`: learned keypoints with 64-D descriptors, and its own mutual-nearest-neighbour and refined
+ matching of image pairs.
+ - :class:`DeDoDe`: separate learned detector and descriptor networks, with ``n`` keypoints in every image.
+ - :class:`LocalFeature`: a classical detector and LAF descriptor in one call, returning padded LAF tensors
+ instead of a list per image.
+ - :func:`laf_from_center_scale_ori`: turns the keypoints of one image into the LAFs that
+ :class:`LightGlueMatcher` and :class:`LAFDescriptor` take.
+ - :class:`LightGlueMatcher`: matches DISK's descriptors and keypoints with the ``"disk"`` weights.
+
Example:
>>> disk = DISK.from_pretrained('depth')
>>> images = torch.rand(1, 3, 256, 256)
@@ -118,7 +140,7 @@ class DISK(nn.Module):
Returns:
A tuple of dense detection scores and descriptors.
Shapes are ``(B, 1, H, W)`` and ``(B, D, H, W)``, where
- :math:`D` is the descriptor dimension.
+ ``D`` is the descriptor dimension; the descriptors are not normalised.
"""
unet_output = self.unet(images)
diff --git a/kornia/feature/disk/structs.py b/kornia/feature/disk/structs.py
index 654714d07..6d206d083 100644
--- a/kornia/feature/disk/structs.py
+++ b/kornia/feature/disk/structs.py
@@ -26,20 +26,27 @@ import torch.nn.functional as F
@dataclass
class DISKFeatures:
- r"""A data structure holding DISK keypoints, descriptors and detection scores for an image.
+ r"""Hold the integer-pixel keypoints, descriptors and detection scores that DISK detects in one image.
- Since DISK detects a varying number of keypoints per image, `DISKFeatures` is not batched.
+ ``features = disk(images)[b]`` is what :class:`DISK` returns for image ``b``: ``features.keypoints`` ``(N, 2)``,
+ integer ``(x, y)`` pixels, also read as :attr:`x` and :attr:`y`, ``features.descriptors`` ``(N, D)``,
+ L2-normalised, and ``features.detection_scores`` ``(N,)``, with ``N = features.n``. It is not batched, because
+ DISK detects a different number of keypoints in each image; ``features.to(device)`` moves the three tensors.
Convention:
The keypoints, scores and descriptors that :class:`~kornia.feature.DISK` returns for one image; its
Convention block gives their frame and order.
Args:
- keypoints: torch.Tensor of shape ``(N, 2)``, where :math:`N` is the number of keypoints.
- descriptors: torch.Tensor of shape ``(N, D)``, where :math:`D` is the descriptor dimension.
+ keypoints: torch.Tensor of shape ``(N, 2)``, where ``N`` is the number of keypoints.
+ descriptors: torch.Tensor of shape ``(N, D)``, where ``D`` is the descriptor dimension.
detection_scores: torch.Tensor of shape ``(N,)``, the detection heatmap value at each keypoint: a raw
logit of the network, not a log-probability.
+ See Also:
+ - :class:`DISK`: the detector, which returns one of these per image.
+ - :class:`ALIKEDFeatures`: the same container for :class:`ALIKED`, whose keypoints are sub-pixel.
+
"""
keypoints: torch.Tensor
@@ -75,17 +82,16 @@ class DISKFeatures:
return self.keypoints[:, 1]
def to(self, *args: Any, **kwargs: Any) -> DISKFeatures:
- """Call :func:`torch.Tensor.to` on each torch.tensor to move the keypoints, descriptors and detection scores to
- the specified device and/or data type.
+ """Return a copy whose keypoints, descriptors and detection scores went through :meth:`torch.Tensor.to`.
Args:
- *args: Arguments passed to :func:`torch.Tensor.to`.
- **kwargs: Keyword arguments passed to :func:`torch.Tensor.to`.
+ *args: Arguments passed to :meth:`torch.Tensor.to`.
+ **kwargs: Keyword arguments passed to :meth:`torch.Tensor.to`.
Returns:
A new DISKFeatures object with tensors of appropriate type and location.
- """ # noqa:D205
+ """
return DISKFeatures(
self.keypoints.to(*args, **kwargs),
self.descriptors.to(*args, **kwargs),
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
index 9c126d365..56fbb6e1d 100644
--- a/kornia/feature/hardnet.py
+++ b/kornia/feature/hardnet.py
@@ -41,10 +41,15 @@ urls["hardnet8v2"] = [
class HardNet(nn.Module):
- r"""Module, which computes HardNet descriptors of given grayscale patches of 32x32.
+ r"""Describe 32 x 32 grayscale patches with the learned 128-D HardNet CNN.
- This is based on the original code from paper "Working hard to know your neighbor's
- margins: Local descriptor learning loss". See :cite:`HardNet2017` for more details.
+ ``hardnet = HardNet()`` builds the network with its pretrained weights, in eval mode, and
+ ``descs = hardnet(patches)`` takes grayscale patches ``(B, 1, 32, 32)`` and returns unit-norm descriptors
+ ``(B, 128)``. Each patch is standardised first, so its intensity range does not matter. To describe LAFs on an
+ image, use :class:`LAFDescriptor`, which holds a pretrained HardNet by default; the HardNet local features such as
+ :class:`DoGHardNet` and :class:`KeyNetHardNet` use it that way. :class:`HardNet8` is the wider follow-up network,
+ with the same patches and output size. This is based on the original code from paper "Working hard to know your
+ neighbor's margins: 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
@@ -76,6 +81,14 @@ class HardNet(nn.Module):
- Input: ``(B, 1, 32, 32)``
- Output: ``(B, 128)``
+ See Also:
+ - :class:`HardNet8`: the follow-up network, wider, with a PCA from 512 to 128 dimensions.
+ - :class:`SOSNet`: the same convolution stack, trained with second-order similarity regularisation.
+ - :class:`HyNet`: a descriptor of the same patches, with FRN layers that subtract no mean.
+ - :class:`TFeat`: a shallow network for the same patches, without L2 normalisation.
+ - :class:`SIFTDescriptor`: handcrafted SIFT histograms of patches, with no weights.
+ - :class:`LAFDescriptor`: runs this network, by default, on a patch per LAF of an image.
+
Examples:
>>> input = torch.rand(16, 1, 32, 32)
>>> hardnet = HardNet(pretrained=False).eval()
@@ -150,10 +163,14 @@ class HardNet(nn.Module):
class HardNet8(nn.Module):
- r"""Module, which computes HardNet8 descriptors of given grayscale patches of 32x32.
+ r"""Describe 32 x 32 grayscale patches with HardNet8, a wider HardNet with a PCA to 128-D.
- This is based on the original code from paper "Improving the HardNet Descriptor".
- See :cite:`HardNet2020` for more details.
+ ``hardnet8 = HardNet8()`` builds the network with its pretrained ``hardnet8v2`` weights, in eval mode, and
+ ``descs = hardnet8(patches)`` takes grayscale patches ``(B, 1, 32, 32)`` and returns unit-norm descriptors
+ ``(B, 128)``: the 512 L2-normalised features of the network, projected by the PCA stored with the weights and
+ normalised again. It takes the patches of :class:`HardNet` and returns descriptors of the same size, but they are
+ not interchangeable with HardNet's; pass it to :class:`LAFDescriptor` to describe LAFs on an image. 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`.
@@ -169,6 +186,12 @@ class HardNet8(nn.Module):
- Input: ``(B, 1, 32, 32)``
- Output: ``(B, 128)``
+ See Also:
+ - :class:`HardNet`: the original, narrower network, the default descriptor of :class:`LAFDescriptor`.
+ - :class:`SOSNet`: HardNet's convolution stack, trained with second-order similarity regularisation.
+ - :class:`HyNet`: a descriptor of the same patches, with FRN layers that subtract no mean.
+ - :class:`LAFDescriptor`: runs a patch descriptor such as this one on a patch per LAF of an image.
+
Examples:
>>> input = torch.rand(16, 1, 32, 32)
>>> hardnet = HardNet8(pretrained=False).eval()
diff --git a/kornia/feature/hynet.py b/kornia/feature/hynet.py
index 1bdde8686..f5f7a1d65 100644
--- a/kornia/feature/hynet.py
+++ b/kornia/feature/hynet.py
@@ -41,8 +41,17 @@ urls["yosemite"] = [
class FilterResponseNorm2d(nn.Module):
- r"""Filter Response Normalization layer from 'Filter Response Normalization Layer: Eliminating Batch Dependence
- in the Training of Deep Neural Networks', see :cite:`FRN2019` for more details.
+ r"""Normalise each channel map by its root mean square, without batch statistics (FRN).
+
+ ``frn = FilterResponseNorm2d(C)``, then ``y = frn(x)`` takes feature maps ``(B, C, H, W)`` and returns them in the
+ same shape, each map divided by the root of its mean square plus ``|eps|``, then, by default, scaled and shifted per
+ channel. It subtracts no mean and uses no batch statistics, so it behaves the same in training and eval mode and for
+ any batch size. :class:`HyNet` applies it, followed by :class:`TLU`, after every convolution but the last, where
+ :class:`HardNet` uses BatchNorm and ReLU, and on the raw patch, which HardNet standardises instead. A float16 or
+ bfloat16 input is normalised in float32, and the output dtype is the promotion of the input's and the layer's, so a
+ float16 input to a float32 layer returns float32. This is the Filter Response Normalization layer from 'Filter
+ Response Normalization Layer: Eliminating Batch Dependence in the Training of Deep Neural Networks', see
+ :cite:`FRN2019` for more details.
.. math::
y = \gamma \frac{x}{\sqrt{\nu^2 + |\epsilon|}} + \beta
@@ -64,10 +73,14 @@ class FilterResponseNorm2d(nn.Module):
torch.Tensor: Normalized features
Shape:
- - Input: :math:`(B, \text{num_features}, H, W)`
- - Output: :math:`(B, \text{num_features}, H, W)`
+ - Input: ``(B, num_features, H, W)``
+ - Output: ``(B, num_features, H, W)``
- """ # noqa: D205
+ See Also:
+ - :class:`TLU`: the learned threshold that follows each of these layers in HyNet.
+ - :class:`HyNet`: the patch descriptor built from these layers.
+
+ """
def __init__(
self,
@@ -146,8 +159,14 @@ 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.
+ r"""Floor each channel at a learned threshold, the TLU activation that follows FRN in HyNet.
+
+ ``tlu = TLU(C)``, then ``y = tlu(x)`` takes feature maps ``(B, C, H, W)`` and returns
+ ``torch.max(x, tau)``, the input floored at a learned threshold ``tau`` per channel, in the same shape. It is the
+ activation that the FRN paper pairs with :class:`FilterResponseNorm2d`, which subtracts no mean, in place of a
+ ReLU. The output dtype is the promotion of the input's and the layer's. This is the TLU layer from 'Filter
+ Response Normalization Layer: Eliminating Batch Dependence in the Training of Deep Neural Networks', see
+ :cite:`FRN2019` for more details.
.. math::
y = \max(x, {\tau})
@@ -163,10 +182,14 @@ class TLU(nn.Module):
torch.Tensor
Shape:
- - Input: :math:`(B, \text{num_features}, H, W)`
- - Output: :math:`(B, \text{num_features}, H, W)`
+ - Input: ``(B, num_features, H, W)``
+ - Output: ``(B, num_features, H, W)``
- """ # noqa:D205
+ See Also:
+ - :class:`FilterResponseNorm2d`: the normalisation that each of these layers follows in HyNet.
+ - :class:`HyNet`: the patch descriptor built from these layers.
+
+ """
def __init__(self, num_features: int) -> None:
"""max(y, tau) = max(y - tau, 0) + tau = ReLU(y - tau) + tau."""
@@ -205,11 +228,15 @@ class TLU(nn.Module):
class HyNet(nn.Module):
- r"""nn.Module, which computes HyNet descriptors of given grayscale patches of 32x32.
+ r"""Describe 32 x 32 grayscale patches with the learned HyNet CNN, built on FRN layers.
- This is based on the original code from paper
- "HyNet: Learning Local Descriptor with Hybrid Similarity Measure and Triplet Loss".
- See :cite:`hynet2020` for more details.
+ ``hynet = HyNet()`` builds the network with its pretrained weights (trained on Liberty), in eval mode, and
+ ``descs = hynet(patches)`` takes grayscale patches ``(B, 1, 32, 32)`` and returns unit-norm descriptors
+ ``(B, dim_desc)``, ``(B, 128)`` by default. Its :class:`FilterResponseNorm2d` layers, each followed by
+ :class:`TLU`, subtract no mean, and the first runs on the raw patch, so unlike :class:`HardNet` its descriptor
+ changes with an intensity offset (see the Convention block). To describe LAFs on an image, pass it to
+ :class:`LAFDescriptor`. This is based on the original code from paper "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
@@ -235,7 +262,15 @@ class HyNet(nn.Module):
Shape:
- Input: ``(B, 1, 32, 32)``
- - Output: :math:`(B, \text{dim\_desc})`
+ - Output: ``(B, dim_desc)``
+
+ See Also:
+ - :class:`HardNet`: a descriptor of the same patches with BatchNorm, which standardises each patch first.
+ - :class:`SOSNet`: a descriptor of the same patches, trained with second-order similarity regularisation.
+ - :class:`HardNet8`: the wider follow-up of HardNet, with a PCA to 128 dimensions.
+ - :class:`FilterResponseNorm2d`: the normalisation layer of this network.
+ - :class:`TLU`: the learned-threshold activation that follows each of its FRN layers.
+ - :class:`LAFDescriptor`: runs a patch descriptor such as this one on a patch per LAF of an image.
Note:
With float16 weights, the final BatchNorm keeps its running statistics in float32.
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index d070a829d..98f179f91 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -64,8 +64,10 @@ def _lightglue_keypoint_scale_ori(lafs: torch.Tensor, feature_name: str) -> Tupl
r"""Return the keypoint scales and orientations, shape ``(1, N)``, that LightGlue takes for ``lafs``.
LightGlue's ``"sift"`` weights were trained on COLMAP keypoints, whose scale is the detection sigma and whose
- orientation is the image angle of the frame's x-axis in :math:`(-\pi, \pi]`: the negative of the LAF
- orientation. The scale is taken as a sixth of the LAF scale, which is sigma for 6-sigma DoG frames such as
+ orientation is, for the similarity frames ``A = s R`` of the SIFT features (nearly so for
+ :class:`SIFTFeatureScaleSpace`'s), the image angle of the frame's x-axis in :math:`(-\pi, \pi]`, which is the
+ negative of the LAF orientation; for another frame the two differ, and the negated LAF orientation is passed.
+ The scale is taken as a sixth of the LAF scale, which is sigma for 6-sigma DoG frames such as
:class:`SIFTFeatureScaleSpace`'s. Every other feature keeps the LAF scale and the LAF orientation in
:math:`[0, 2\pi)`. The ``"sift"`` scale is converted here rather than through :class:`LightGlue`'s
``scale_coef``, which the ``"doghardnet"`` configurations use, so that ``LightGlue("sift")`` itself keeps taking
@@ -136,13 +138,22 @@ def get_laf_descriptors(
patch_size: int = 32,
grayscale_descriptor: bool = True,
) -> torch.Tensor:
- r"""Get local descriptors, corresponding to LAFs (keypoints).
+ r"""Describe LAFs on an image by running a patch descriptor on one patch sampled per LAF.
+
+ ``descs = get_laf_descriptors(img, lafs, patch_descriptor, patch_size)`` takes images ``(B, C, H, W)``, their
+ LAFs ``(B, N, 2, 3)`` in pixels and a patch descriptor module, and returns one descriptor per LAF, ``(B, N, D)``.
+ The descriptor determines the output dtype. The function converts a 3-channel image to grayscale when
+ ``grayscale_descriptor`` is set, samples a ``patch_size`` x ``patch_size`` patch per LAF with
+ :func:`extract_patches_from_pyramid`, and runs the descriptor on the stack of the ``B * N`` patches.
+ The patch follows the LAF's scale and orientation, so orient the LAFs first, e.g. with :class:`LAFOrienter`,
+ unless upright descriptors are wanted. ``patch_size`` must be what the descriptor takes: 32 for :class:`HardNet`
+ and the other learned descriptors, 41 for a default :class:`SIFTDescriptor`. For the module form, use
+ :class:`LAFDescriptor`; for SIFT descriptors of LAFs without sampling patches, :class:`SIFTDescriptorFromPyramid`.
Convention:
- The descriptor sees the patches of :func:`~kornia.feature.extract_patches_from_pyramid` at ``patch_size``;
see its Convention block for how they are sampled. ``patch_size`` is this argument, 32 by default, and is
not read from the descriptor, so it has to be a size the descriptor accepts.
- - With ``grayscale_descriptor=True``, a 3-channel image is converted to grayscale first.
- The descriptor runs in eval mode, with its floating-point parameters and buffers cast to the device and
dtype of ``img`` for the call (a TorchScript module is called on a cast copy). SOSNet and HyNet retain their
final BatchNorm statistics in float32 for float16 images. The module keeps its device, dtype and
@@ -154,16 +165,25 @@ def get_laf_descriptors(
Args:
img: image features with shape ``(B,C,H,W)``.
- lafs: local affine frames ``(B,N,2,3)``.
+ lafs: local affine frames ``(B,N,2,3)`` in the pixels of ``img``, with its batch size.
patch_descriptor: patch descriptor module, e.g. :class:`~kornia.feature.SIFTDescriptor`
or :class:`~kornia.feature.HardNet`.
patch_size: patch size in pixels, which descriptor expects.
grayscale_descriptor: True if ``patch_descriptor`` expects single-channel image; a 3-channel ``img`` is
- then converted to grayscale.
+ then converted to grayscale. An image with another channel count is passed on unchanged.
Returns:
Local descriptors of shape ``(B,N,D)`` where :math:`D` is descriptor size.
+ See Also:
+ - :class:`LAFDescriptor`: the module form, which holds the descriptor, a pretrained :class:`HardNet` by
+ default.
+ - :func:`extract_patches_from_pyramid`: the patch sampler, for the patches themselves.
+ - :func:`laf_from_center_scale_ori`: LAFs from keypoint centres, scales and orientations, to describe here.
+ - :class:`SIFTDescriptorFromPyramid`: SIFT descriptors of LAFs, pooled from a gradient pyramid without
+ sampling patches.
+ - :class:`LAFOrienter`: orients LAFs from their patches, before they are described.
+
"""
KORNIA_CHECK_LAF(lafs)
timg: torch.Tensor = img
@@ -195,7 +215,17 @@ def get_laf_descriptors(
class LAFDescriptor(nn.Module):
- r"""nn.Module to get local descriptors, corresponding to LAFs (keypoints).
+ r"""Describe LAFs with a held patch descriptor, as a module (HardNet by default).
+
+ ``describer = LAFDescriptor()``, then ``descs = describer(img, lafs)`` takes images ``(B, C, H, W)`` and their
+ LAFs ``(B, N, 2, 3)`` in pixels and returns one descriptor per LAF, ``(B, N, D)``: ``forward`` calls
+ :func:`get_laf_descriptors` with the held descriptor, ``patch_size`` and ``grayscale_descriptor``, which samples a
+ patch per LAF with :func:`extract_patches_from_pyramid`. By default it holds a pretrained :class:`HardNet` on
+ 32 x 32 grayscale patches, converts an RGB image to grayscale and returns ``(B, N, 128)``; with another
+ descriptor, pass the patch size it takes, e.g. ``LAFDescriptor(SIFTDescriptor(41), patch_size=41)``. It is the
+ descriptor of the HardNet local features, such as :class:`DoGHardNet`, and of the ``"patch"`` backend of
+ :class:`SIFTFeature` and :class:`SIFTFeatureScaleSpace`. For SIFT descriptors of LAFs without sampling patches,
+ use :class:`SIFTDescriptorFromPyramid` instead.
Convention:
See the Convention block on :func:`~kornia.feature.get_laf_descriptors`, which ``forward`` calls with this
@@ -210,6 +240,16 @@ class LAFDescriptor(nn.Module):
grayscale_descriptor: ``True`` if patch_descriptor expects single-channel image; a 3-channel image is then
converted to grayscale.
+ See Also:
+ - :func:`get_laf_descriptors`: the function form, which takes the descriptor in each call.
+ - :class:`HardNet`: the default descriptor; :class:`SIFTDescriptor`, :class:`HardNet8`, :class:`HyNet`,
+ :class:`SOSNet`, :class:`TFeat` and :class:`MKDDescriptor` fit as well.
+ - :func:`extract_patches_from_pyramid`: the patch sampler, for the patches themselves.
+ - :func:`laf_from_center_scale_ori`: LAFs from keypoint centres, scales and orientations, to describe here.
+ - :class:`SIFTDescriptorFromPyramid`: SIFT descriptors of LAFs, pooled from a gradient pyramid without
+ sampling patches.
+ - :class:`LocalFeature`: runs a detector and a descriptor such as this module in one call.
+
"""
def __init__(
@@ -248,38 +288,52 @@ class LAFDescriptor(nn.Module):
class LocalFeature(nn.Module):
- """nn.Module, which combines local feature detector and descriptor.
+ """Detect and describe LAFs in one call with a given detector and LAF descriptor module.
+
+ ``feature = LocalFeature(detector, descriptor)``, then ``lafs, responses, descs = feature(img, mask)`` runs a
+ detector and descriptor as one pipeline. It takes images ``(B, C, H, W)`` and an optional mask. The detector
+ returns LAFs ``(B, N, 2, 3)`` in pixels and responses ``(B, N)``. The descriptor returns one descriptor per LAF,
+ ``(B, N, D)``. ``scaling_coef`` changes the LAF shape before description. Use :class:`LAFDescriptor` to adapt a
+ patch descriptor such as :class:`HardNet`; :class:`SIFTDescriptorFromPyramid` already takes images and LAFs.
+ The detector and descriptor define accepted batch sizes, channels and intensity ranges. To match features from two
+ images, use :class:`LocalFeatureMatcher`. For learned features, use :class:`DISK`, :class:`ALIKED`, :class:`XFeat`
+ or :class:`DeDoDe`.
Convention:
- - ``forward`` runs the detector, multiplies the shape ``A`` of every LAF by ``scaling_coef``
- (:func:`~kornia.feature.scale_laf`) and describes the scaled LAFs. It returns ``(lafs, responses, descs)``
- with shapes ``(B, N, 2, 3)``, ``(B, N)`` and ``(B, N, D)``: the scaled LAFs, in the frame of
- :func:`~kornia.feature.laf_from_center_scale_ori` (see :ref:`Local features <local-features-conventions>`),
- the detector's responses and one descriptor per LAF. ``scaling_coef`` leaves the centres and the responses
+ - The returned LAFs use the pixel convention of :func:`~kornia.feature.laf_from_center_scale_ori`
+ (see :ref:`Local features <local-features-conventions>`). ``scaling_coef`` multiplies their shape ``A``
+ (:func:`~kornia.feature.scale_laf`) before the description and leaves the centres and the responses
unchanged.
- - ``N`` comes from the detector. The detectors of every preset (:class:`~kornia.feature.ScaleSpaceDetector`,
- :class:`~kornia.feature.MultiResolutionDetector`, :class:`~kornia.feature.KeyNetDetector` and the dedicated
- detector of ``SIFTFeatureScaleSpace(descriptor_backend="pyramid")``) return ``num_features`` slots for every
- image, not the largest count in the batch.
- - A slot that the detector did not fill holds a zero LAF and a zero response, and all such slots of an image
- share one descriptor: with :class:`~kornia.feature.LAFDescriptor`, that of a patch sampled at the origin.
- :class:`LocalFeatureMatcher` drops these slots before matching. Drop them yourself before any other
- matcher, including :func:`~kornia.feature.match_nn`, :func:`~kornia.feature.match_mnn`,
- :func:`~kornia.feature.match_fginn`, :func:`~kornia.feature.match_adalam` and
- :class:`~kornia.feature.LightGlueMatcher`, since identical descriptors match each other at zero distance and
- a mutual test does not reject a pair of them: keep the slots where :func:`~kornia.feature.laf_is_filled` is
- true, ``descs[b][laf_is_filled(lafs)[b]]`` for image ``b``, rather than testing the response (see the
- Convention block of :func:`~kornia.feature.laf_is_filled`). The ratio tests of
- :func:`~kornia.feature.match_snn` and :func:`~kornia.feature.match_smnn` do not replace this filtering: when
- the other image has exactly one padded slot, the padded slots of the two images can match each other at zero
- distance.
+ - Cast the module to the image dtype before calling it, for example ``feature.to(img.dtype)``. See each preset
+ for its supported dtypes.
+ - A detector can return zero-LAF padding when fewer than ``N`` features are found. ``laf_is_filled(lafs)`` is
+ ``True`` for detections; index LAFs, responses and descriptors with it to discard padding before matching.
+ :class:`LocalFeatureMatcher` does this automatically.
Args:
- detector: the detection module.
- descriptor: the descriptor module.
+ detector: the detection module, called as ``detector(img, mask)`` and returning ``(lafs, responses)``, such
+ as :class:`~kornia.feature.ScaleSpaceDetector`.
+ descriptor: the descriptor module, called as ``descriptor(img, lafs)`` and returning ``(B, N, D)``, such as
+ :class:`~kornia.feature.LAFDescriptor`.
scaling_coef: the multiplier of the detector's LAFs before the description, see the Convention block. An
``int`` is converted to ``float``. Must be positive.
+ Raises:
+ ValueError: if ``scaling_coef`` is not positive.
+
+ See Also:
+ - :class:`ScaleSpaceDetector`: a scale-space detector for a batch of images.
+ - :class:`MultiResolutionDetector`: a detector for one image per call.
+ - :func:`laf_is_filled`: returns the detection slots to keep and discard padding.
+ - :class:`LocalFeatureMatcher`: runs a local feature on two images and matches the descriptors.
+ - :class:`SIFTFeatureScaleSpace`: the SIFT preset for a batch of images.
+
+ Example:
+ >>> feature = LocalFeature(ScaleSpaceDetector(10), LAFDescriptor(SIFTDescriptor(32), patch_size=32))
+ >>> lafs, responses, descs = feature(torch.rand(2, 1, 64, 64))
+ >>> lafs.shape, responses.shape, descs.shape
+ (torch.Size([2, 10, 2, 3]), torch.Size([2, 10]), torch.Size([2, 10, 128]))
+
"""
def __init__(self, detector: nn.Module, descriptor: nn.Module, scaling_coef: float = 1.0) -> None:
@@ -353,10 +407,14 @@ class _SIFTFeature(LocalFeature):
class SIFTFeature(_SIFTFeature):
- """Multiresolution DoG detection followed by a (Root)SIFT descriptor.
+ """Detect per-level DoG keypoints and describe them with SIFT, one image per call.
- For new scale-space SIFT pipelines, start with :class:`SIFTFeatureScaleSpace` and explicitly select
- ``descriptor_backend="pyramid"``; see :ref:`sift-pipelines`.
+ ``sift = SIFTFeature(2048)`` loads a per-level DoG detector and SIFT descriptor. ``lafs, responses, descs =
+ sift(img)`` takes one grayscale image ``(1, 1, H, W)``; a batch or color image raises. It returns LAFs
+ ``(1, N, 2, 3)``, DoG-response magnitudes ``(1, N)``, strongest first, and RootSIFT descriptors
+ ``(1, N, 128)`` in kornia's layout. Use :func:`laf_is_filled` to keep detections and discard padding.
+ ``descriptor_backend`` chooses patches (``"patch"``, the default) or a gradient pyramid (``"pyramid"``). For
+ scale-space extrema or batches, use :class:`SIFTFeatureScaleSpace` with ``descriptor_backend="pyramid"``.
For CPU throughput use OpenCV's SIFT: on an Apple M1 CPU, a matching pipeline on it ran 11x faster than one on
this module (640 px, 2,048 features). This module takes one image per call; for batches use
@@ -364,17 +422,15 @@ class SIFTFeature(_SIFTFeature):
<https://kornia.readthedocs.io/en/latest/applications/image_matching.html#feature-speed-by-device>`_.
Convention:
- - A :class:`~kornia.feature.LocalFeature`, whose Convention block gives the output contract, of one grayscale
- image per call, ``(1, 1, H, W)``. The detector is a :class:`~kornia.feature.MultiResolutionDetector` on
- the magnitude of a single-scale :class:`~kornia.feature.BlobDoGSingle` response. With
- ``descriptor_backend="patch"``, the default, ``LAFOrienter(19)`` orients the LAFs unless ``upright`` and
- :class:`~kornia.feature.SIFTDescriptor` describes 41 x 41 patches. ``"pyramid"`` keeps the detector and
- orients and describes its LAFs with :class:`SIFTDescriptorFromPyramid`, which integrates smoothed image
- gradients without extracting patches.
- - The detector applies the response independently at each image resolution, with 2-D non-maximum
- suppression. It does not select extrema across scale or refine positions and scales to subpixel precision,
- and it does not apply classical SIFT's contrast or Hessian edge rejection. One orientation is assigned per
- detection unless ``upright=True``.
+ - A :class:`~kornia.feature.LocalFeature`, whose Convention block gives the output contract. The detector is
+ a :class:`~kornia.feature.MultiResolutionDetector` on the magnitude of a single-scale
+ :class:`~kornia.feature.BlobDoGSingle` response. With ``descriptor_backend="patch"``, the default,
+ ``LAFOrienter(19)`` orients the LAFs unless ``upright`` and :class:`~kornia.feature.SIFTDescriptor`
+ describes 41 x 41 patches. ``"pyramid"`` keeps the detector and orients and describes its LAFs with
+ :class:`SIFTDescriptorFromPyramid`, which integrates smoothed image gradients without extracting patches.
+ - The detector applies the response independently at each image resolution. It does not apply classical
+ SIFT's contrast or Hessian edge rejection. One orientation is assigned per detection unless
+ ``upright=True``.
- Extrema of both polarities are kept: dark blobs are DoG maxima and bright blobs are DoG minima. On each
image-pyramid level, a keypoint is a strict maximum of the response magnitude in its ``config["nms_size"]``
window (15 pixels by default), so a stronger extremum of either polarity suppresses a weaker one.
@@ -382,13 +438,48 @@ class SIFTFeature(_SIFTFeature):
- The frames are those of :class:`~kornia.feature.MultiResolutionDetector`: a pixel of a pyramid level, with a
scale of ``config["s_mult"]`` (22 by default) times that level's pixel size whatever the size of the blob.
Unlike the 6-sigma frames of :class:`SIFTFeatureScaleSpace`, their scale is not a fixed multiple of the
- detection sigma.
+ detection sigma: a sixth of it, which ``LightGlueMatcher("sift")`` takes as the detection sigma, is not that
+ sigma here (see :ref:`sift-pipelines`).
- Descriptors come in kornia's SIFT layout; ``descriptor_layout="opencv"`` returns them in OpenCV's, which
:class:`~kornia.feature.LightGlueMatcher` expects with ``"sift"``.
:func:`~kornia.feature.convert_sift_descriptor_layout` converts between the two.
- Known defects: ``descriptor_backend="pyramid"`` is less accurate than the patch backend on Oxford
homographies at 2048 features, and not faster on CPU at 1024 features
(`#5748 <https://github.com/kornia/kornia/issues/5748>`_).
+
+ Args:
+ num_features: the number of slots per image; the strongest detections fill them, the rest are padding.
+ upright: if ``True``, skip the orientation estimation and return upright frames.
+ rootsift: if ``True``, the default, return RootSIFT descriptors, otherwise SIFT.
+ device: the device of the detector and descriptor modules. Default: CPU.
+ config: the pyramid and suppression settings of :class:`~kornia.feature.MultiResolutionDetector`, whose
+ ``config`` argument lists them with their defaults.
+ compile_model: wrap the DoG response and the non-maxima suppression with :func:`torch.compile`, see
+ :class:`~kornia.feature.MultiResolutionDetector`.
+ score_threshold: the response magnitude a detection has to exceed. Must be non-negative.
+ descriptor_backend: ``"patch"`` or ``"pyramid"``, see the Convention block.
+ descriptor_layout: ``"kornia"`` or ``"opencv"``, the order of the descriptor values.
+
+ Raises:
+ ValueError: for a ``descriptor_backend`` or ``descriptor_layout`` other than those listed, or a negative
+ ``score_threshold``.
+
+ See Also:
+ - :class:`SIFTFeatureScaleSpace`: SIFT on a DoG scale space, with extrema across scale, sub-pixel refinement
+ and 6-sigma frames, for a batch of images.
+ - :class:`MultiResolutionDetector`: its detector, on the magnitude of the DoG.
+ - :class:`BlobDoGSingle`: the single-scale DoG response whose magnitude it detects on.
+ - :class:`SIFTDescriptor`: the descriptor of the ``"patch"`` backend, run on 41 x 41 patches through
+ :class:`LAFDescriptor`.
+ - :class:`SIFTDescriptorFromPyramid`: the orientation and descriptor of the ``"pyramid"`` backend.
+ - :func:`convert_sift_descriptor_layout`: the reordering that ``descriptor_layout="opencv"`` applies.
+ - :class:`LocalFeature`: its base class, which gives the output contract.
+
+ Example:
+ >>> lafs, responses, descs = SIFTFeature(100)(torch.rand(1, 1, 64, 64))
+ >>> lafs.shape, responses.shape, descs.shape
+ (torch.Size([1, 100, 2, 3]), torch.Size([1, 100]), torch.Size([1, 100, 128]))
+
"""
def __init__(
@@ -433,9 +524,15 @@ class SIFTFeature(_SIFTFeature):
class SIFTFeatureScaleSpace(LocalFeature):
- """DoG scale-space detection, position/scale refinement and (Root)SIFT description.
+ """Detect refined DoG scale-space extrema and describe them with SIFT, for a batch.
- For new scale-space SIFT pipelines, explicitly select ``descriptor_backend="pyramid"``; see :ref:`sift-pipelines`.
+ ``sift = SIFTFeatureScaleSpace(2048, descriptor_backend="pyramid")`` builds a DoG scale-space SIFT pipeline.
+ ``lafs, responses, descs = sift(img)`` takes grayscale images ``(B, 1, H, W)``. It returns six-sigma LAFs
+ ``(B, N, 2, 3)``, absolute DoG responses ``(B, N)``, strongest first, and RootSIFT descriptors ``(B, N, 128)``.
+ Use :func:`laf_is_filled` to keep detections and discard padding. The ``"pyramid"`` backend reuses Gaussian
+ images and accepts RGB input; ``"patch"`` samples patches and requires grayscale input. Use
+ ``descriptor_layout="opencv"`` with ``LightGlueMatcher("sift")``; use :class:`DoGHardNet` for HardNet
+ descriptors on the ``"patch"`` detections.
For CPU throughput use OpenCV's SIFT: on an Apple M1 CPU, a matching pipeline on it ran 8x faster than one on this
module with ``descriptor_backend="pyramid"``, and 14x faster with ``"patch"`` (640 px, 2,048 features). See the
@@ -451,10 +548,9 @@ class SIFTFeatureScaleSpace(LocalFeature):
41 patches. ``"pyramid"`` runs a dedicated DoG detector and reuses its Gaussian images and the octave and
layer of each detection for orientation and description: it refines only sparse extrema, ranks all valid
candidates by absolute response, and computes image gradients once per used layer.
- - Both backends search 3-D DoG extrema and refine position and scale. Neither applies classical SIFT's contrast
- or Hessian edge rejection, and each assigns one orientation per detection unless ``upright=True``. The
- backend selects a different detector as well as different orientation and description stages, so the
- backends can return different detections as well as different descriptors; the feature budget is the same.
+ - Each backend assigns one orientation per detection unless ``upright=True``. The backend selects a different
+ detector as well as different orientation and description stages, so the backends can return different
+ detections as well as different descriptors; the feature budget is the same.
- On both backends the LAF scale is 6 times the detection sigma, and ``responses`` is the absolute DoG, the
same for a bright blob as for a dark one. The LAF centres are in the frame of
:func:`~kornia.feature.laf_from_center_scale_ori` (see :ref:`Local features <local-features-conventions>`) on
@@ -463,6 +559,41 @@ class SIFTFeatureScaleSpace(LocalFeature):
- Descriptors come in kornia's SIFT layout; ``descriptor_layout="opencv"`` returns them in OpenCV's, which
:class:`~kornia.feature.LightGlueMatcher` expects with ``"sift"``.
:func:`~kornia.feature.convert_sift_descriptor_layout` converts between the two.
+
+ Args:
+ num_features: the number of slots per image; the strongest detections fill them, the rest are padding.
+ upright: if ``True``, skip the orientation estimation and return upright frames.
+ rootsift: if ``True``, the default, return RootSIFT descriptors, otherwise SIFT.
+ device: the device of the detector and descriptor modules. Default: CPU.
+ compile_modules: the detector sub-modules to wrap with :func:`torch.compile`. With ``"patch"``, the
+ ``compile_modules`` of :class:`~kornia.feature.ScaleSpaceDetector`; with ``"pyramid"``, ``"scale_pyr"``
+ and ``"subpix"`` only, both for ``True``, while the orientation and description run eagerly.
+ descriptor_backend: ``"patch"`` or ``"pyramid"``, see the Convention block.
+ descriptor_layout: ``"kornia"`` or ``"opencv"``, the order of the descriptor values.
+
+ Raises:
+ ValueError: for a ``descriptor_backend`` or ``descriptor_layout`` other than those listed, or a
+ ``compile_modules`` name the selected backend does not have.
+
+ See Also:
+ - :class:`SIFTFeature`: a per-level DoG approximation of SIFT, without selection across scale or sub-pixel
+ refinement, one image per call.
+ - :class:`ScaleSpaceDetector`: the detector of the ``"patch"`` backend, on a :class:`BlobDoG` response.
+ - :class:`BlobDoG`: the scale-space DoG response of the ``"patch"`` backend.
+ - :class:`SIFTDescriptor`: the descriptor of the ``"patch"`` backend, run on 41 x 41 patches through
+ :class:`LAFDescriptor`.
+ - :func:`convert_sift_descriptor_layout`: the reordering that ``descriptor_layout="opencv"`` applies.
+ - :class:`LightGlueMatcher`: its ``"sift"`` weights match these features, in the ``"opencv"`` layout.
+ - :class:`DoGHardNet`: the detections of the ``"patch"`` backend described by HardNet, at twice the frame
+ scale.
+ - :class:`LocalFeature`: its base class, which gives the output contract.
+
+ Example:
+ >>> sift = SIFTFeatureScaleSpace(100, descriptor_backend="pyramid")
+ >>> lafs, responses, descs = sift(torch.rand(2, 1, 64, 64))
+ >>> lafs.shape, responses.shape, descs.shape
+ (torch.Size([2, 100, 2, 3]), torch.Size([2, 100]), torch.Size([2, 100, 128]))
+
"""
def __init__(
@@ -523,7 +654,7 @@ class SIFTFeatureScaleSpace(LocalFeature):
def forward(
self, img: torch.Tensor, mask: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
- """Detect and describe sparse SIFT features, sharing scale space when selected."""
+ """Detect and describe SIFT features; the ``"pyramid"`` backend reuses the detector's Gaussian images."""
if self.descriptor_backend == "patch":
lafs, responses, descriptors = super().forward(img, mask)
return lafs, responses, _in_sift_layout(descriptors, self.descriptor_layout)
@@ -537,7 +668,13 @@ class SIFTFeatureScaleSpace(LocalFeature):
class GFTTAffNetHardNet(LocalFeature):
- """Convenience module, which implements GFTT detector + AffNet-HardNet descriptor.
+ """Detect GFTT corners over scale with AffNet shapes and HardNet descriptors.
+
+ ``feature = GFTTAffNetHardNet(2048)`` loads pretrained AffNet and HardNet in evaluation mode. ``lafs, responses,
+ descs = feature(img)`` takes grayscale images ``(B, 1, H, W)``; convert color images with
+ :func:`~kornia.color.rgb_to_grayscale` first. It returns affine LAFs ``(B, N, 2, 3)``, Shi-Tomasi responses
+ ``(B, N)``, strongest first, and unit-norm HardNet descriptors ``(B, N, 128)``. Use :func:`laf_is_filled` to keep
+ detections and discard padding. For blobs, use :class:`HesAffNetHardNet` or :class:`DoGAffNetHardNet`.
Convention:
A :class:`~kornia.feature.LocalFeature`, whose Convention block gives the output contract, of grayscale
@@ -545,6 +682,24 @@ class GFTTAffNetHardNet(LocalFeature):
:class:`~kornia.feature.CornerGFTT` response, its maxima only and ``mr_size=6``, whose LAFs get their affine
shape from :class:`~kornia.feature.LAFAffNetShapeEstimator`, then their orientation from ``LAFOrienter(19)``
unless ``upright``, and are described by :class:`~kornia.feature.HardNet` on 32 x 32 patches.
+
+ Args:
+ num_features: the number of slots per image; the strongest detections fill them, the rest are padding.
+ upright: if ``True``, skip the orientation estimation and return upright frames.
+ device: the device of the detector and descriptor modules. Default: CPU.
+ compile_modules: the detector sub-modules to wrap with :func:`torch.compile`, see
+ :class:`~kornia.feature.ScaleSpaceDetector`.
+
+ See Also:
+ - :class:`HesAffNetHardNet`: the same pipeline on Hessian blobs, 2048 slots by default.
+ - :class:`DoGAffNetHardNet`: the same shapes and descriptors on DoG blobs, which
+ ``LightGlueMatcher("dog_affnet_hardnet")`` matches.
+ - :class:`CornerGFTT`: the corner response it detects on.
+ - :class:`ScaleSpaceDetector`: its detector.
+ - :class:`LAFAffNetShapeEstimator`: the AffNet shape estimation it runs before the orientation.
+ - :class:`HardNet`: its descriptor, run on 32 x 32 patches through :class:`LAFDescriptor`.
+ - :class:`LocalFeature`: its base class, which gives the output contract.
+
"""
def __init__(
@@ -574,7 +729,14 @@ class GFTTAffNetHardNet(LocalFeature):
class HesAffNetHardNet(LocalFeature):
- """Convenience module, which implements Hessian detector + AffNet-HardNet descriptor.
+ """Detect Hessian blobs over scale with AffNet shapes and HardNet descriptors.
+
+ ``feature = HesAffNetHardNet(2048)`` loads pretrained AffNet and HardNet in evaluation mode. ``lafs, responses,
+ descs = feature(img)`` takes grayscale images ``(B, 1, H, W)``; convert color images with
+ :func:`~kornia.color.rgb_to_grayscale` first. It returns affine LAFs ``(B, N, 2, 3)``, Hessian responses
+ ``(B, N)``, strongest first, and unit-norm HardNet descriptors ``(B, N, 128)``. Use :func:`laf_is_filled` to keep
+ detections and discard padding. For corners use :class:`GFTTAffNetHardNet`; for LightGlue-compatible DoG blobs,
+ use :class:`DoGAffNetHardNet`.
Convention:
A :class:`~kornia.feature.LocalFeature`, whose Convention block gives the output contract, of grayscale
@@ -582,6 +744,24 @@ class HesAffNetHardNet(LocalFeature):
:class:`~kornia.feature.BlobHessian` response, its maxima only and ``mr_size=6``, whose LAFs get their affine
shape from :class:`~kornia.feature.LAFAffNetShapeEstimator`, then their orientation from ``LAFOrienter(19)``
unless ``upright``, and are described by :class:`~kornia.feature.HardNet` on 32 x 32 patches.
+
+ Args:
+ num_features: the number of slots per image; the strongest detections fill them, the rest are padding.
+ upright: if ``True``, skip the orientation estimation and return upright frames.
+ device: the device of the detector and descriptor modules. Default: CPU.
+ compile_modules: the detector sub-modules to wrap with :func:`torch.compile`, see
+ :class:`~kornia.feature.ScaleSpaceDetector`.
+
+ See Also:
+ - :class:`GFTTAffNetHardNet`: the same pipeline on Shi-Tomasi corners, 8000 slots by default.
+ - :class:`DoGAffNetHardNet`: the same shapes and descriptors on DoG blobs, which
+ ``LightGlueMatcher("dog_affnet_hardnet")`` matches.
+ - :class:`BlobHessian`: the blob response it detects on.
+ - :class:`ScaleSpaceDetector`: its detector, with this response by default.
+ - :class:`LAFAffNetShapeEstimator`: the AffNet shape estimation it runs before the orientation.
+ - :class:`HardNet`: its descriptor, run on 32 x 32 patches through :class:`LAFDescriptor`.
+ - :class:`LocalFeature`: its base class, which gives the output contract.
+
"""
def __init__(
@@ -633,7 +813,13 @@ def _dog_detector(
class DoGHardNet(LocalFeature):
- """Convenience module, which implements DoG detector + HardNet descriptor.
+ """Detect DoG blobs over scale and describe them with HardNet, without affine adaptation.
+
+ ``feature = DoGHardNet(2048)`` loads pretrained HardNet in evaluation mode. ``lafs, responses, descs =
+ feature(img)`` takes grayscale images ``(B, 1, H, W)``. It returns 12-sigma DoG LAFs ``(B, N, 2, 3)``, absolute
+ DoG responses ``(B, N)``, strongest first, and unit-norm HardNet descriptors ``(B, N, 128)``. Use
+ :func:`laf_is_filled` to keep detections and discard padding before calling ``LightGlueMatcher("doghardnet")``.
+ Choose :class:`DoGAffNetHardNet` for affine shapes or :class:`SIFTFeatureScaleSpace` for SIFT descriptors.
Convention:
- A :class:`~kornia.feature.LocalFeature`, whose Convention block gives the output contract. The detector is
@@ -641,18 +827,27 @@ class DoGHardNet(LocalFeature):
``"patch"`` backend, and the orientation is estimated on its 6-sigma frames. The returned LAFs are those
frames scaled by two (``scaling_coef=2``), to 12 sigma or six times OpenCV's ``KeyPoint.size``, and
:class:`~kornia.feature.HardNet` describes them on 32 x 32 patches.
- - These are the frames the ``"doghardnet"`` weights of :class:`~kornia.feature.LightGlueMatcher` expect: pass
- the LAFs and descriptors, without the padded slots, to ``LightGlueMatcher("doghardnet")``.
- The image must have one channel, ``(B, 1, H, W)``: convert a color image with
:func:`~kornia.color.rgb_to_grayscale` first.
Args:
- num_features: the number of features to detect.
+ num_features: the number of slots per image; the strongest detections fill them, the rest are padding.
upright: if ``True``, skip the orientation estimation and return upright frames.
device: the device of the detector and descriptor modules. Default: CPU.
compile_modules: the detector sub-modules to wrap with :func:`torch.compile`, see
:class:`~kornia.feature.ScaleSpaceDetector`.
+ See Also:
+ - :class:`DoGAffNetHardNet`: the same detections with AffNet shapes, estimated before the orientation.
+ - :class:`SIFTFeatureScaleSpace`: the same detections with SIFT descriptors, at 6 sigma, with its
+ ``"patch"`` backend.
+ - :class:`ScaleSpaceDetector`: its detector, on a :class:`BlobDoG` response.
+ - :class:`BlobDoG`: the scale-space DoG response it detects on.
+ - :class:`HardNet`: its descriptor, run on 32 x 32 patches through :class:`LAFDescriptor`.
+ - :class:`LightGlueMatcher`: its ``"doghardnet"`` weights match these features.
+ - :class:`KeyNetHardNet`: HardNet descriptors of KeyNet detections, one image per call.
+ - :class:`LocalFeature`: its base class, which gives the output contract.
+
"""
def __init__(
@@ -671,21 +866,37 @@ class DoGHardNet(LocalFeature):
class DoGAffNetHardNet(LocalFeature):
- """Convenience module, which implements DoG detector + AffNet-HardNet descriptor.
+ """Detect DoG blobs over scale with AffNet shapes and HardNet descriptors.
+
+ ``feature = DoGAffNetHardNet(2048)`` loads pretrained AffNet and HardNet in evaluation mode. ``lafs, responses,
+ descs = feature(img)`` takes grayscale images ``(B, 1, H, W)``. It returns the outputs of :class:`DoGHardNet`,
+ with affine LAF shapes adapted by AffNet before orientation. Use :func:`laf_is_filled` to keep detections and
+ discard padding before calling ``LightGlueMatcher("dog_affnet_hardnet")``. Choose :class:`GFTTAffNetHardNet` or
+ :class:`HesAffNetHardNet` for corners or Hessian blobs.
Convention:
As :class:`~kornia.feature.DoGHardNet`, with the affine shape of each 6-sigma DoG frame estimated by
:class:`~kornia.feature.LAFAffNetShapeEstimator` before its orientation. The scale of the returned LAFs, the
- square root of their determinant, is again 12 sigma. Pass the LAFs and descriptors, without the padded slots,
- to ``LightGlueMatcher("dog_affnet_hardnet")``. The image must have one channel, ``(B, 1, H, W)``.
+ square root of their determinant, is again 12 sigma. The image must have one channel, ``(B, 1, H, W)``.
Args:
- num_features: the number of features to detect.
+ num_features: the number of slots per image; the strongest detections fill them, the rest are padding.
upright: if ``True``, skip the orientation estimation and return upright frames.
device: the device of the detector and descriptor modules. Default: CPU.
compile_modules: the detector sub-modules to wrap with :func:`torch.compile`, see
:class:`~kornia.feature.ScaleSpaceDetector`.
+ See Also:
+ - :class:`DoGHardNet`: the same detections and descriptors without affine adaptation.
+ - :class:`LAFAffNetShapeEstimator`: the AffNet shape estimation it runs before the orientation.
+ - :class:`ScaleSpaceDetector`: its detector, on a :class:`BlobDoG` response.
+ - :class:`HardNet`: its descriptor, run on 32 x 32 patches through :class:`LAFDescriptor`.
+ - :class:`LightGlueMatcher`: its ``"dog_affnet_hardnet"`` mode matches these features.
+ - :class:`GFTTAffNetHardNet`: the same shapes and descriptors on Shi-Tomasi corners.
+ - :class:`HesAffNetHardNet`: the same shapes and descriptors on Hessian blobs.
+ - :class:`KeyNetAffNetHardNet`: the same shapes and descriptors on KeyNet detections, one image per call.
+ - :class:`LocalFeature`: its base class, which gives the output contract.
+
"""
def __init__(
@@ -705,7 +916,13 @@ class DoGAffNetHardNet(LocalFeature):
class KeyNetHardNet(LocalFeature):
- """Convenience module, which implements KeyNet detector + HardNet descriptor.
+ """Detect KeyNet keypoints and describe them with HardNet, without affine adaptation.
+
+ ``feature = KeyNetHardNet(2048)`` loads pretrained KeyNet, OriNet and HardNet in evaluation mode. ``lafs,
+ responses, descs = feature(img)`` takes one grayscale image ``(1, 1, H, W)`` in ``[0, 1]``; a batch or color image
+ raises. It returns LAFs ``(1, N, 2, 3)``, KeyNet responses ``(1, N)``, strongest first, and unit-norm HardNet
+ descriptors ``(1, N, 128)``. Use :func:`laf_is_filled` to keep detections and discard padding. Choose
+ :class:`KeyNetAffNetHardNet` for AffNet shapes and its LightGlue weights. For batches, use :class:`DoGHardNet`.
Convention:
A :class:`~kornia.feature.LocalFeature`, whose Convention block gives the output contract, of one grayscale
@@ -713,6 +930,28 @@ class KeyNetHardNet(LocalFeature):
orientation from :class:`~kornia.feature.OriNet` on 32 x 32 patches unless ``upright``, and are described by
:class:`~kornia.feature.HardNet` on 32 x 32 patches. ``scale_laf`` is the ``scaling_coef`` of
:class:`~kornia.feature.LocalFeature`: it multiplies the detector's LAFs before the description.
+
+ Args:
+ num_features: the number of slots; the strongest detections fill them, the rest are padding.
+ upright: if ``True``, skip the orientation estimation and return upright frames.
+ device: the device of the detector and descriptor modules. Default: CPU.
+ scale_laf: the multiplier of the detector's LAFs before the description. Must be positive.
+ compile_model: wrap the KeyNet response and the non-maxima suppression with :func:`torch.compile`, see
+ :class:`~kornia.feature.KeyNetDetector`.
+ score_threshold: the KeyNet response a detection has to exceed. Must be non-negative.
+
+ Raises:
+ ValueError: if ``scale_laf`` is not positive or ``score_threshold`` is negative.
+
+ See Also:
+ - :class:`KeyNetAffNetHardNet`: the same detections with AffNet shapes, estimated before the orientation.
+ - :class:`KeyNetDetector`: its detector.
+ - :class:`KeyNet`: the learned response it detects on.
+ - :class:`OriNet`: the learned orientation, run on each LAF's patch through :class:`LAFOrienter`.
+ - :class:`HardNet`: its descriptor, run on 32 x 32 patches through :class:`LAFDescriptor`.
+ - :class:`DoGHardNet`: HardNet descriptors of DoG detections, for a batch of images.
+ - :class:`LocalFeature`: its base class, which gives the output contract.
+
"""
def __init__(
@@ -740,13 +979,42 @@ class KeyNetHardNet(LocalFeature):
class KeyNetAffNetHardNet(LocalFeature):
- """Convenience module, which implements KeyNet detector + AffNet + HardNet descriptor.
+ """Detect KeyNet keypoints with AffNet shapes and HardNet descriptors.
+
+ ``feature = KeyNetAffNetHardNet(2048)`` loads pretrained KeyNet, AffNet, OriNet and HardNet in evaluation mode.
+ ``lafs, responses, descs = feature(img)`` takes one grayscale image ``(1, 1, H, W)`` in ``[0, 1]``. It returns
+ the outputs of :class:`KeyNetHardNet`, with affine LAF shapes adapted by AffNet before orientation. Use
+ :func:`laf_is_filled` to keep detections and discard padding before calling
+ ``LightGlueMatcher("keynet_affnet_hardnet")``. For batches, use :class:`DoGAffNetHardNet`.
.. image:: _static/img/keynet_affnet.jpg
Convention:
As :class:`~kornia.feature.KeyNetHardNet`, with the affine shape of each frame estimated by
:class:`~kornia.feature.LAFAffNetShapeEstimator` before its orientation.
+
+ Args:
+ num_features: the number of slots; the strongest detections fill them, the rest are padding.
+ upright: if ``True``, skip the orientation estimation and return upright frames.
+ device: the device of the detector and descriptor modules. Default: CPU.
+ scale_laf: the multiplier of the detector's LAFs before the description. Must be positive.
+ compile_model: wrap the KeyNet response and the non-maxima suppression with :func:`torch.compile`, see
+ :class:`~kornia.feature.KeyNetDetector`.
+ score_threshold: the KeyNet response a detection has to exceed. Must be non-negative.
+
+ Raises:
+ ValueError: if ``scale_laf`` is not positive or ``score_threshold`` is negative.
+
+ See Also:
+ - :class:`KeyNetHardNet`: the same detections and descriptors without affine adaptation.
+ - :class:`KeyNetDetector`: its detector.
+ - :class:`LAFAffNetShapeEstimator`: the AffNet shape estimation it runs before the orientation.
+ - :class:`OriNet`: the learned orientation, run on each LAF's patch through :class:`LAFOrienter`.
+ - :class:`HardNet`: its descriptor, run on 32 x 32 patches through :class:`LAFDescriptor`.
+ - :class:`LightGlueMatcher`: its ``"keynet_affnet_hardnet"`` weights match these features.
+ - :class:`DoGAffNetHardNet`: the same shapes and descriptors on DoG detections, for a batch of images.
+ - :class:`LocalFeature`: its base class, which gives the output contract.
+
"""
def __init__(
@@ -775,7 +1043,17 @@ class KeyNetAffNetHardNet(LocalFeature):
class LocalFeatureMatcher(nn.Module):
- r"""nn.Module, which finds correspondences between two images based on local features.
+ r"""Detect, describe and match the local features of two images with a descriptor matcher.
+
+ ``matcher = LocalFeatureMatcher(local_feature, DescriptorMatcher("snn", 0.8))`` builds the module and
+ ``out = matcher({"image0": img0, "image1": img1})`` runs ``local_feature`` on both batches of images, which the
+ :class:`LocalFeature` presets take as grayscale ``(B, 1, H, W)``, except :class:`SIFTFeature`,
+ :class:`KeyNetHardNet` and :class:`KeyNetAffNetHardNet`, which take one image per call, ``(1, 1, H, W)``. It
+ matches the descriptors of each pair of images and returns a dict of the matches of all pairs: ``keypoints0``
+ and ``keypoints1`` ``(NC, 2)``, ``lafs0`` and ``lafs1`` ``(1, NC, 2, 3)``, ``confidence`` ``(NC,)`` and the pair
+ of each match, ``batch_indexes`` ``(NC,)``. Features already computed for an image can be passed instead of
+ running ``local_feature`` on it. For a matcher that reads the LAFs, such as :class:`LightGlueMatcher`, call it on
+ the outputs of the local feature yourself; for matching without a detector, use :class:`LoFTR`.
Convention:
- ``keypoints0`` and ``keypoints1`` are the centres ``(x, y)`` of the returned LAF tensors ``lafs0`` and
@@ -790,12 +1068,22 @@ class LocalFeatureMatcher(nn.Module):
need LAFs and do not fit.
Args:
- local_feature: Local feature detector. See :class:`~kornia.feature.GFTTAffNetHardNet`.
+ local_feature: Local feature detector and descriptor, called as ``local_feature(image, mask)`` and returning
+ ``(lafs, responses, descriptors)`` like :class:`~kornia.feature.LocalFeature`. See
+ :class:`~kornia.feature.GFTTAffNetHardNet`.
matcher: Descriptor matcher, see :class:`~kornia.feature.DescriptorMatcher`.
Returns:
Dict[str, torch.Tensor]: Dictionary with image correspondences and confidence scores.
+ See Also:
+ - :class:`LocalFeature`: the detector and descriptor pipeline that ``local_feature`` usually is.
+ - :class:`DescriptorMatcher`: the descriptor-only matcher it takes.
+ - :class:`LightGlueMatcher`: a learned matcher, which takes the LAFs and the image sizes as well.
+ - :class:`LoFTR`: matches two images directly, without a detector.
+ - :class:`~kornia.geometry.ransac.RANSAC`: the next step, which keeps the matches one geometric model
+ explains.
+
Example:
>>> img1 = torch.rand(1, 1, 320, 200)
>>> img2 = torch.rand(1, 1, 128, 128)
@@ -847,8 +1135,10 @@ class LocalFeatureMatcher(nn.Module):
data: dictionary containing the input data in the following format:
Keyword Args:
- image0: left image with shape ``(N, 1, H1, W1)``.
- image1: right image with shape ``(N, 1, H2, W2)``.
+ image0: left image with shape ``(N, 1, H1, W1)``. Required also with ``lafs0`` and ``descriptors0``:
+ its first dimension gives the number of image pairs.
+ image1: right image with shape ``(N, 1, H2, W2)``; not read when ``lafs1`` and ``descriptors1`` are
+ given.
mask0 (optional): left image mask. '0' suppresses detection, with shape
``(N, H1, W1)`` or ``(N, 1, H1, W1)``.
mask1 (optional): right image mask. '0' suppresses detection, with shape
@@ -862,14 +1152,14 @@ class LocalFeatureMatcher(nn.Module):
Returns:
- ``keypoints0``, matching keypoints from image0 ``(NC, 2)``.
- ``keypoints1``, matching keypoints from image1 ``(NC, 2)``.
- - ``confidence``, ``1 - descriptor distance`` ``(NC)``. This lies in :math:`[0, 1]`
+ - ``confidence``, ``1 - descriptor distance`` ``(NC,)``. This lies in :math:`[0, 1]`
only for the ratio-based ``DescriptorMatcher`` modes (``snn``, ``smnn``); ``nn`` and
``mnn`` return raw distances, which are unbounded for an arbitrary descriptor, so the
confidence has no lower bound in general -- it goes at least down to -1, the value
reached by unit-norm descriptors, whose distance tops out at 2.0.
- ``lafs0``, matching LAFs from image0 ``(1, NC, 2, 3)``.
- ``lafs1``, matching LAFs from image1 ``(1, NC, 2, 3)``.
- - ``batch_indexes``, batch indexes for the keypoints and lafs ``(NC)``.
+ - ``batch_indexes``, batch indexes for the keypoints and lafs ``(NC,)``.
"""
num_image_pairs: int = data["image0"].shape[0]
@@ -975,38 +1265,56 @@ class LocalFeatureMatcher(nn.Module):
class LightGlueMatcher(GeometryAwareDescriptorMatcher):
- r"""LightGlue-based matcher in kornia API.
-
- This is based on the original code from paper "LightGlue: Local Feature Matching at Light Speed".
- See :cite:`LightGlue2023` for more details.
+ r"""Match descriptors and LAFs with LightGlue, called like GeometryAwareDescriptorMatcher.
+
+ ``matcher = LightGlueMatcher("disk")`` loads the LightGlue weights trained for that local feature, and
+ ``scores, idxs = matcher(desc1, desc2, lafs1, lafs2, hw1, hw2)`` takes the descriptors ``(B1, D)`` and
+ ``(B2, D)`` of two images (or ``(1, B1, D)`` and ``(1, B2, D)``), their LAFs ``(1, B1, 2, 3)`` and
+ ``(1, B2, 2, 3)`` in pixels and, optionally, the image sizes ``(H, W)``, and returns LightGlue's matching scores
+ ``(B3, 1)``, higher for better matches, and the index pairs ``(B3, 2)``, in the format of
+ :class:`GeometryAwareDescriptorMatcher`. The descriptors must come from the feature the weights were trained for,
+ see ``feature_name`` in the Convention block. To pass batches of
+ keypoints in dicts and read every output of the network, use :class:`LightGlue`; for an exported ONNX model, use
+ :class:`OnnxLightGlue`. It is based on the original code of "LightGlue: Local Feature Matching at Light Speed",
+ see :cite:`LightGlue2023` for more details.
Convention:
- - ``lafs1`` and ``lafs2`` are LAFs in the pixel frame of :func:`~kornia.feature.laf_from_center_scale_ori`
+ - ``lafs1`` and ``lafs2`` use the pixel convention of :func:`~kornia.feature.laf_from_center_scale_ori`
(see :ref:`Local features <local-features-conventions>`), and their centres go to LightGlue unchanged as
the keypoints. ``hw1`` and ``hw2`` are the ``(H, W)`` of each image, which become LightGlue's
``image_size`` ``(W, H)``; without them, the image size is taken as the largest keypoint coordinates of
that image, ``(max x, max y)``.
- - What the network gets besides the keypoints depends on ``feature_name`` (case-insensitive):
-
- - ``"aliked"``, ``"dedodeb"``, ``"dedodeg"``, ``"disk"``, ``"raco-aliked"``, ``"superpoint"``, ``"xfeat"``:
- nothing else. For ``"xfeat"``, the LighterGlue weights of :class:`~kornia.feature.XFeat`, pass the 64-D
+ - Choose ``feature_name`` for the source of the descriptors (case-insensitive). The network receives the
+ following data besides keypoints:
+
+ - ``"aliked"``: use the 128-D descriptors of :class:`ALIKED`. The 64-D ``"aliked-t16"`` descriptors are
+ incompatible with these weights.
+ - ``"dedodeb"``, ``"dedodeg"``: use the ``B``, respectively ``G``, descriptors of :class:`DeDoDe`. Build
+ the LAFs at keypoints minus 0.5, because DeDoDe puts pixel ``i`` at ``i + 0.5``.
+ - ``"disk"``, ``"raco-aliked"``, ``"superpoint"``, ``"xfeat"``: use descriptors from the named feature and
+ no additional LAF attributes. For ``"xfeat"``, pass the 64-D
descriptors of :meth:`~kornia.feature.XFeat.detectAndCompute` and LAFs centred on its keypoints, such as
- ``laf_from_center_scale_ori(keypoints[None])``.
- - ``"sift"``: the scale and orientation of the COLMAP keypoints the weights were trained on: the negated
+ ``laf_from_center_scale_ori(keypoints[None])``, and call the matcher under ``torch.no_grad()`` or
+ ``torch.inference_mode()``: it raises on XFeat's inference tensors with gradients enabled
+ (`#6533 <https://github.com/kornia/kornia/issues/6533>`_).
+ - ``"sift"``: use :class:`SIFTFeatureScaleSpace` with ``descriptor_layout="opencv"``. The weights expect
+ the scale and orientation of the COLMAP keypoints they were trained on: the negated
LAF orientation in :math:`(-\pi, \pi]`, and a sixth of the LAF scale, which is the detection sigma for
6-sigma DoG frames such as :class:`~kornia.feature.SIFTFeatureScaleSpace`'s. The descriptors must be in
OpenCV's SIFT layout, which these weights expect, while kornia's SIFT descriptors use another order of the
same values: create the feature with ``descriptor_layout="opencv"``, or convert the descriptors with
``convert_sift_descriptor_layout(descs, "kornia", "opencv")``
(:func:`~kornia.feature.convert_sift_descriptor_layout`).
- - ``"doghardnet"``, ``"dog_affnet_hardnet"``: pass the LAFs the HardNet descriptors were computed on, at
+ - ``"doghardnet"``, ``"dog_affnet_hardnet"``: use :class:`DoGHardNet` or :class:`DoGAffNetHardNet`.
+ Pass the LAFs the HardNet descriptors were computed on, at
the scale the weights were trained with: 12 sigma, six times OpenCV's ``KeyPoint.size`` and twice the
6-sigma DoG frames of :class:`~kornia.feature.SIFTFeatureScaleSpace`. :class:`~kornia.feature.DoGHardNet`
and :class:`~kornia.feature.DoGAffNetHardNet` return such LAFs and their descriptors; with another
6-sigma DoG detector, apply :func:`~kornia.feature.scale_laf` with ``2.0`` to its LAFs before describing
them. The network takes a sixth of the LAF scale, which is ``KeyPoint.size`` for these frames, and the
LAF orientation in :math:`[0, 2\pi)`.
- - ``"keynet_affnet_hardnet"``: the ends of the two LAF axes, ``c + A[:, 0]`` and ``c + A[:, 1]``,
+ - ``"keynet_affnet_hardnet"``: use :class:`KeyNetAffNetHardNet`. The network receives the ends of the two
+ LAF axes, ``c + A[:, 0]`` and ``c + A[:, 1]``,
normalised like the keypoints.
- The first returned value is LightGlue's matching score, not a distance: higher is better, and only matches
scoring above ``filter_threshold`` (0.1 by default) are returned. The index rows are ``(index in desc1,
@@ -1018,6 +1326,13 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
feature_name: type of feature for matching, one of ``known_modes``.
params: keyword arguments of :class:`~kornia.feature.LightGlue`, such as ``filter_threshold``.
+ See Also:
+ - :class:`LightGlue`: takes batches of keypoints in dictionaries and returns all network outputs.
+ - :class:`OnnxLightGlue`: runs an exported LightGlue model for one image pair.
+ - :class:`LocalFeatureMatcher`: matches local features with a descriptor-only matcher.
+ - :class:`LoFTR`: matches images directly, without a detector.
+ - :class:`GeometryAwareDescriptorMatcher`: offers FGINN and AdaLAM with the same call.
+
"""
known_modes: ClassVar[List[str]] = [
diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.py
index ef0a5ca21..4ea0e9d43 100644
--- a/kornia/feature/keynet.py
+++ b/kornia/feature/keynet.py
@@ -34,6 +34,8 @@ class KeyNet_conf(TypedDict):
Attributes:
num_filters: The number of filters in the convolutional layers.
num_levels: The number of levels in the image pyramid.
+ kernel_size: The kernel size of the last convolution, which merges the levels' features.
+ Detector_conf: The configuration of the :class:`MultiResolutionDetector` that :class:`KeyNetDetector` builds.
"""
num_filters: int
@@ -136,24 +138,33 @@ def _KeyNetConvBlock(
class KeyNet(nn.Module):
- """Key.Net model definition -- local feature detector (response function).
+ """Compute the learned Key.Net keypoint response map of a grayscale image, at the input's size.
- This is based on the original code
- from paper "Key.Net: Keypoint Detection by Handcrafted and Learned CNN Filters". See :cite:`KeyNet2019` for
- more details.
+ ``response = KeyNet()(img)`` takes grayscale images ``(B, 1, H, W)`` in ``[0, 1]`` and returns their Key.Net
+ response, a non-negative ``(B, 1, H, W)`` map, without non-maxima suppression: handcrafted first- and second-order
+ derivative filters and a small CNN run on the image and on ``num_levels - 1`` successive 1.2x downscales of it (two
+ by default), and a last convolution merges their features, resized back to the input size. The pretrained weights,
+ the default, come back in evaluation mode; a random model (``pretrained=False``) stays in training mode, so call
+ ``.eval()`` before inference (see :ref:`pretrained-models-conventions`). For keypoints, use
+ :class:`KeyNetDetector`, which finds the maxima of this response on an image pyramid.
+
+ This is based on the original code from the paper "Key.Net: Keypoint Detection by Handcrafted and Learned CNN
+ Filters". See :cite:`KeyNet2019` for more details.
.. image:: _static/img/KeyNet.png
Convention:
- The input is a grayscale image, and the pretrained weights expect it in ``[0, 1]``, as the Key.Net
reference scales its images. The response is not proportional to the intensity, so an image in
- ``[0, 255]`` gives other detections.
- - The response is a non-negative map of the input's size.
+ ``[0, 255]`` gives other detections. A multi-channel image raises ``RuntimeError``.
+ - The response is a non-negative map of the input's size when ``kernel_size`` is odd. With ``pretrained=False``
+ and an even ``kernel_size``, the final convolution returns a map one pixel larger on each axis.
Args:
pretrained: Download and set pretrained weights to the model.
keynet_conf: Dict with initialization parameters. Do not pass it, unless you know what you are doing. A
- ``num_filters``, ``num_levels`` or ``kernel_size`` other than the default changes the architecture: pass
+ ``num_filters``, ``num_levels`` or an odd ``kernel_size`` other than the default changes the architecture.
+ Pass
``pretrained=False`` with it, since the strict load of the weights raises ``RuntimeError``.
Returns:
@@ -163,6 +174,11 @@ class KeyNet(nn.Module):
- Input: ``(B, 1, H, W)``
- Output: ``(B, 1, H, W)``
+ See Also:
+ - :class:`KeyNetDetector`: detects LAFs at the maxima of this response on an image pyramid.
+ - :class:`BlobHessian`: a handcrafted blob response, with no weights to load.
+ - :class:`KeyNetHardNet`: KeyNet detection with OriNet orientation and HardNet descriptors.
+
"""
def __init__(self, pretrained: bool = True, keynet_conf: Optional[KeyNet_conf] = None) -> None:
@@ -201,23 +217,32 @@ class KeyNet(nn.Module):
class KeyNetDetector(MultiResolutionDetector):
- """Multi-scale feature detector based on KeyNet.
+ """Detect LAFs at the maxima of the learned Key.Net response on an image pyramid, one image per call.
+
+ ``detector = KeyNetDetector(num_features=2048)``, then ``lafs, responses = detector(img)`` takes one grayscale
+ image ``(1, 1, H, W)`` in ``[0, 1]`` and returns ``(1, num_features, 2, 3)`` LAFs in input pixels and their
+ ``(1, num_features)`` KeyNet responses, strongest first. ``laf_is_filled(lafs)`` is true for detections; index
+ every output with it to discard padded slots. It is a :class:`MultiResolutionDetector` on the :class:`KeyNet`
+ response with the default ``config``: maxima at the integer pixels of six pyramid levels, in upright frames unless
+ ``ori_module`` or ``aff_module`` change them. For KeyNet detections with orientation and HardNet descriptors, use
+ :class:`KeyNetAffNetHardNet` instead.
- This is based on the original code from paper
- "Key.Net: Keypoint Detection by Handcrafted and Learned CNN Filters".
- See :cite:`KeyNet2019` for more details.
+ This is based on the original code from the paper "Key.Net: Keypoint Detection by Handcrafted and Learned CNN
+ Filters". See :cite:`KeyNet2019` for more details.
.. image:: _static/img/keynet.jpg
Convention:
A :class:`~kornia.feature.MultiResolutionDetector` with :class:`~kornia.feature.KeyNet` as its response; see
- their Convention blocks for the frame of the detections and for the input range.
+ their Convention blocks for the pixel convention and input range. Only KeyNet is in evaluation mode after
+ construction, so this detector reports ``training=True``; calling ``.train()`` changes its detections.
Args:
pretrained: Download and set pretrained weights to the model.
num_features: Number of features to detect.
keynet_conf: Dict with initialization parameters. Do not pass it, unless you know what you are doing. A
- ``num_filters``, ``num_levels`` or ``kernel_size`` other than the default changes the architecture: pass
+ ``num_filters``, ``num_levels`` or an odd ``kernel_size`` other than the default changes the architecture.
+ Pass
``pretrained=False`` with it, since the strict load of the weights raises ``RuntimeError``.
ori_module: for local feature orientation estimation. Default: :class:`~kornia.feature.PassLAF`,
which does nothing. See :class:`~kornia.feature.LAFOrienter` for details.
@@ -226,7 +251,18 @@ class KeyNetDetector(MultiResolutionDetector):
compile_model: wrap the response function and the non-maxima suppression with :func:`torch.compile`.
score_threshold: minimum response for a position to count as a detection. Must be non-negative:
non-maxima suppression writes an exact zero at every suppressed position, so a negative
- threshold would admit all of them.
+ threshold would admit all of them; it raises ``ValueError``.
+
+ See Also:
+ - :class:`KeyNet`: the response network alone, a dense ``(B, 1, H, W)`` map.
+ - :class:`MultiResolutionDetector`: the same detector on another response function.
+ - :class:`ScaleSpaceDetector`: batched detection at the sub-pixel scale-space extrema of a pluggable response,
+ the Hessian determinant by default.
+ - :class:`KeyNetHardNet`: this detector with OriNet orientation and HardNet descriptors.
+ - :class:`KeyNetAffNetHardNet`: the same, with AffNet affine shapes before the orientation.
+ - :class:`LAFOrienter`: an ``ori_module`` that orients each frame from its image patch.
+ - :class:`LAFAffineShapeEstimator`: an ``aff_module`` that adapts each frame to its patch's second moments.
+ - :func:`laf_is_filled`: is true for detections; use it to discard padded slots.
"""
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index fb1326ecb..cabd22083 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -42,10 +42,17 @@ def _laf_product_dtype(dtype: torch.dtype) -> torch.dtype:
def get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:
- """Return a scale of the LAFs.
+ r"""Read the scale of each LAF, the square root of the absolute determinant of its shape.
+
+ ``scale = get_laf_scale(laf)`` takes ``(B, N, 2, 3)`` LAFs and returns their scales :math:`\sqrt{|\det A|}` as a
+ ``(B, N, 1, 1)`` tensor, in pixels for LAFs in pixels: the radius of a circular LAF's region, and the geometric
+ mean of the two semi-axes of an elliptical one. The result broadcasts against the shape ``A``, so use
+ ``scale_laf(laf, 1.0 / scale)`` to normalize an ordinary LAF. For the orientation and centre, use
+ :func:`get_laf_orientation` and :func:`get_laf_center`.
Convention:
- See the Convention block on :func:`~kornia.feature.laf_from_center_scale_ori`, which defines the scale.
+ - The ``1e-10`` added to the determinant makes frames smaller than about ``1e-4`` px read too large.
- The determinant of a float16 LAF is formed in float32, so that a LAF whose entry products leave the float16
range does not overflow; the scale is returned in the LAF dtype.
@@ -55,6 +62,12 @@ def get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:
Returns:
scale ``(B, N, 1, 1)``
+ See Also:
+ - :func:`scale_laf`: multiplies the scale by a coefficient, keeping the centre.
+ - :func:`get_laf_orientation`: the orientation of the same LAFs.
+ - :func:`get_laf_center`: the centre of the same LAFs.
+ - :func:`laf_from_center_scale_ori`: LAFs of given scales, built from keypoint centres.
+
Example:
>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3
>>> output = get_laf_scale(input) # BxNx1x1
@@ -73,6 +86,12 @@ def get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:
def laf_is_valid(laf: torch.Tensor) -> torch.Tensor:
"""Check that each LAF is finite and has a finite, nonzero determinant.
+ ``valid = laf_is_valid(laf)`` takes ``(B, N, 2, 3)`` LAFs and returns a boolean ``(B, N)`` mask, true where every
+ entry is finite and the shape ``A`` has a finite, nonzero determinant, so that it maps the patch onto a region of
+ nonzero area. It does not check where the LAF lies: for the LAFs whose region lies inside the image, use
+ :func:`laf_is_inside_image`, and to drop only the padding of a detector's unfilled slots, use
+ :func:`laf_is_filled` instead.
+
Convention:
- A LAF with a negative determinant, a mirrored frame, is valid. The all-zero padding LAF (see
:func:`~kornia.feature.laf_is_filled`), a rank-1 ``A`` and an ``A`` whose determinant overflows are not.
@@ -87,6 +106,11 @@ def laf_is_valid(laf: torch.Tensor) -> torch.Tensor:
Returns:
validity mask ``(B, N)``.
+ See Also:
+ - :func:`laf_is_filled`: rejects only the all-zero padding, and accepts singular and non-finite frames.
+ - :func:`laf_is_inside_image`: checks where the region lies, not whether the frame is regular.
+ - :func:`KORNIA_CHECK_LAF`: checks only the ``(B, N, 2, 3)`` shape, not the values.
+
Example:
>>> laf = torch.eye(2, 3).view(1, 1, 2, 3)
>>> laf_is_valid(laf)
@@ -102,8 +126,13 @@ def laf_is_valid(laf: torch.Tensor) -> torch.Tensor:
def laf_is_filled(laf: torch.Tensor) -> torch.Tensor:
"""Check which slots hold a detection rather than the zero-LAF padding.
+ ``filled = laf_is_filled(lafs)`` takes the ``(B, N, 2, 3)`` LAFs of a detector and returns a boolean ``(B, N)``
+ mask, false for all-zero padded frames: index the LAFs, responses and
+ descriptors of image ``b`` with ``laf_is_filled(lafs)[b]`` to keep its detections. A filled frame need not be
+ usable; to also drop singular and non-finite frames, use :func:`laf_is_valid` instead.
+
Convention:
- - kornia's LAF detectors pad the slots no detection filled with an all-zero LAF and a zero response, so that a
+ - kornia's LAF detectors pad unused slots with an all-zero LAF and a zero response, so that a
batch is one tensor. Drop those slots before matching: the padding frames are identical to one another, so a
mutual nearest-neighbour test does not reject them and they match each other at zero distance.
- Only an all-zero frame is padding. Any other frame is filled: a detection at the image origin, which has a
@@ -118,6 +147,12 @@ def laf_is_filled(laf: torch.Tensor) -> torch.Tensor:
Returns:
mask of the slots a detection filled ``(B, N)``.
+ See Also:
+ - :func:`laf_is_valid`: rejects singular and non-finite frames as well as the padding.
+ - :func:`laf_is_inside_image`: counts the padding as inside the image at the default border, so combine the
+ two masks.
+ - :class:`LocalFeatureMatcher`: drops the padded slots itself before matching.
+
Example:
>>> laf = torch.tensor([[[[2., 0., 5.], [0., 3., 7.]], [[0., 0., 0.], [0., 0., 0.]]]])
>>> laf_is_filled(laf)
@@ -129,7 +164,11 @@ def laf_is_filled(laf: torch.Tensor) -> torch.Tensor:
def get_laf_center(LAF: torch.Tensor) -> torch.Tensor:
- """Return a center (keypoint) of the LAFs.
+ """Read the centre of each LAF, its keypoint position ``(x, y)``.
+
+ ``xy = get_laf_center(laf)`` takes ``(B, N, 2, 3)`` LAFs and returns their centres ``c = (x, y)``, the last column
+ of each LAF, as a ``(B, N, 2)`` tensor in the LAF's units and dtype. The result is a view of ``laf``, not a copy.
+ To build LAFs from keypoints, use :func:`laf_from_center_scale_ori`.
Convention:
The centre is ``(x, y)`` in pixels, with pixel centres at integers; see
@@ -141,6 +180,12 @@ def get_laf_center(LAF: torch.Tensor) -> torch.Tensor:
Returns:
xy ``(B, N, 2)``
+ See Also:
+ - :func:`laf_from_center_scale_ori`: LAFs built from centres, with optional scales and orientations.
+ - :func:`get_laf_scale`: the scale of the same LAFs.
+ - :func:`get_laf_orientation`: the orientation of the same LAFs.
+ - :func:`laf_to_three_points`: the centre together with the tips of the patch's two axes.
+
Example:
>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3
>>> output = get_laf_center(input) # BxNx2
@@ -151,7 +196,15 @@ def get_laf_center(LAF: torch.Tensor) -> torch.Tensor:
def get_laf_orientation(LAF: torch.Tensor) -> torch.Tensor:
- """Return orientation of the LAFs, in degrees.
+ """Read the orientation of each LAF in degrees, from the first row of its shape.
+
+ ``ori = get_laf_orientation(laf)`` takes ``(B, N, 2, 3)`` LAFs and returns their orientations ``atan2(a12, a11)``
+ in degrees, within ``[-180, 180]``, as a ``(B, N, 1)`` tensor. It reads only the first row of the shape ``A``,
+ which for ``A = U R``, an upright factor times the rotation matrix of an angle, gives that angle whatever the shear
+ of ``U``. For a circular similarity frame ``A = s R``, OpenCV's ``KeyPoint.angle`` is ``(-ori) mod 360``. For a
+ general affine frame, use ``atan2(a21, a11)`` in degrees modulo 360; an OpenCV keypoint cannot
+ retain its affine shape or reflection. To change the orientation, use :func:`set_laf_orientation` or
+ :func:`rotate_laf`.
Convention:
See the Convention block on :func:`~kornia.feature.laf_from_center_scale_ori`, which defines the orientation.
@@ -162,6 +215,14 @@ def get_laf_orientation(LAF: torch.Tensor) -> torch.Tensor:
Returns:
angle in degrees ``(B, N, 1)``
+ See Also:
+ - :func:`set_laf_orientation`: sets the orientation to given angles.
+ - :func:`rotate_laf`: adds angles to the orientation.
+ - :func:`make_upright`: removes the rotation, so that the orientation reads 0.
+ - :func:`laf_from_center_scale_ori`: LAFs of given orientations, built from keypoint centres.
+ - :func:`get_laf_scale`: the scale of the same LAFs.
+ - :func:`get_laf_center`: the centre of the same LAFs.
+
Example:
>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3
>>> output = get_laf_orientation(input) # BxNx1
@@ -173,7 +234,12 @@ def get_laf_orientation(LAF: torch.Tensor) -> torch.Tensor:
def rotate_laf(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torch.Tensor:
- """Apply additional rotation to the LAFs.
+ """Rotate each LAF's patch frame by an angle in degrees, adding it to the orientation.
+
+ ``rotated = rotate_laf(laf, angles)`` takes ``(B, N, 2, 3)`` LAFs and angles ``(B, N, 1)`` in degrees and returns
+ the ``(B, N, 2, 3)`` LAFs whose orientation is the input's plus ``angles``. Only the patch frame turns: the
+ centre, scale and region, the ellipse ``c + A u`` over unit vectors ``u``, stay the same. To set given
+ orientations instead, use :func:`set_laf_orientation`.
Convention:
- The result is ``[A @ R | c]``, with ``R`` the rotation matrix of ``angles_degrees`` from
@@ -188,6 +254,11 @@ def rotate_laf(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torch.Tensor:
Returns:
LAF oriented with angles ``(B, N, 2, 3)``
+ See Also:
+ - :func:`set_laf_orientation`: rotates to given orientations rather than by given angles.
+ - :func:`get_laf_orientation`: reads the orientation that this adds to.
+ - :class:`LAFOrienter`: rotates each LAF by the angle estimated on its image patch.
+
"""
KORNIA_CHECK_LAF(LAF)
B, N = LAF.shape[:2]
@@ -198,7 +269,13 @@ def rotate_laf(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torch.Tensor:
def set_laf_orientation(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torch.Tensor:
- """Change the orientation of the LAFs.
+ """Set the orientation of each LAF to an angle in degrees, keeping its region.
+
+ ``oriented = set_laf_orientation(laf, angles)`` takes ``(B, N, 2, 3)`` LAFs and orientations ``(B, N, 1)`` in
+ degrees and returns the ``(B, N, 2, 3)`` LAFs rotated to them, as :func:`rotate_laf` rotates: the centre, the
+ scale and region are kept. With angles of 0, a LAF of positive determinant becomes the upright LAF of
+ :func:`make_upright`, up to its ``eps``. To add angles to the current orientation, use :func:`rotate_laf`
+ instead.
Convention:
See the Convention block on :func:`~kornia.feature.rotate_laf`. This rotates by ``angles_degrees`` minus the
@@ -211,6 +288,12 @@ def set_laf_orientation(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torc
Returns:
LAF oriented with angles ``(B, N, 2, 3)``
+ See Also:
+ - :func:`rotate_laf`: adds angles to the current orientation instead.
+ - :func:`get_laf_orientation`: reads the orientation back.
+ - :func:`make_upright`: sets the orientation to 0 and drops a reflection too.
+ - :func:`laf_from_center_scale_ori`: new LAFs with given orientations, built from their centres.
+
"""
KORNIA_CHECK_LAF(LAF)
_B, _N = LAF.shape[:2]
@@ -221,7 +304,14 @@ def set_laf_orientation(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torc
def laf_from_center_scale_ori(
xy: torch.Tensor, scale: Optional[torch.Tensor] = None, ori: Optional[torch.Tensor] = None
) -> torch.Tensor:
- r"""Create a LAF from keypoint center, scale and orientation.
+ r"""Build circular LAFs from keypoint centres, scales and orientations.
+
+ ``laf = laf_from_center_scale_ori(xy, scale, ori)`` takes keypoint centres ``xy`` ``(B, N, 2)``, scales
+ ``(B, N, 1, 1)`` (1 when omitted) and orientations ``(B, N, 1)`` in degrees (0 when omitted), and returns the
+ ``(B, N, 2, 3)`` LAFs ``[scale * R(ori) | xy]``, whose regions are circles of radius ``scale`` around ``xy``.
+ This turns the keypoints of a detector that returns no LAFs, such as :class:`DISK` or :class:`XFeat`, into the
+ LAFs that :class:`LAFDescriptor` and the LAF matchers take, e.g. ``laf_from_center_scale_ori(keypoints[None])``.
+ For an elliptical region, use :func:`ellipse_to_laf` instead.
Convention:
- A LAF is a ``(B, N, 2, 3)`` tensor ``[A | c]``, with the centre ``c = (x, y)`` and ``A`` in pixels.
@@ -238,6 +328,8 @@ def laf_from_center_scale_ori(
back ``-179``. For :math:`\det A > 0`, ``A = U R`` with ``U`` the upright ``A`` that
:func:`~kornia.feature.make_upright` returns, up to its stabilizers, and ``R`` the rotation matrix of that
orientation.
+ - A negative determinant mirrors the patch frame. Increasing its orientation turns its x axis clockwise on
+ screen. With a nonzero scale, this constructor produces a positive determinant.
Args:
xy: ``(B, N, 2)``.
@@ -247,6 +339,13 @@ def laf_from_center_scale_ori(
Returns:
LAF ``(B, N, 2, 3)``
+ See Also:
+ - :func:`get_laf_center`: reads the centres back.
+ - :func:`get_laf_scale`: reads the scales back.
+ - :func:`get_laf_orientation`: reads the orientations back, within ``[-180, 180]``.
+ - :func:`ellipse_to_laf`: LAFs of elliptical regions, given by their ellipse coefficients.
+ - :func:`laf_from_three_points`: LAFs from the images of three patch points.
+
Example:
>>> xy = torch.tensor([[[5.0, 7.0]]])
>>> laf_from_center_scale_ori(xy, torch.full((1, 1, 1, 1), 2.0), torch.tensor([[[30.0]]]))
@@ -269,7 +368,12 @@ def laf_from_center_scale_ori(
def scale_laf(laf: torch.Tensor, scale_coef: Union[float, torch.Tensor]) -> torch.Tensor:
- """Multiplies region part of LAF ([:, :, :2, :2]) by a scale_coefficient.
+ """Multiply the shape of each LAF by a coefficient, keeping its centre.
+
+ ``scaled = scale_laf(laf, k)`` takes ``(B, N, 2, 3)`` LAFs and a coefficient ``k``, a float or a tensor such as one
+ coefficient per LAF in ``(B, N, 1, 1)``, and returns the ``(B, N, 2, 3)`` LAFs ``[k A | c]``, whose regions are
+ scaled by ``|k|`` about the same centres. A descriptor then sees a larger or smaller area around each keypoint, as
+ with the ``scaling_coef`` of :class:`LocalFeature`. To read the scale, use :func:`get_laf_scale`.
Convention:
- The result is ``[k A | c]`` for ``k = scale_coef``, a product taken elementwise: the centre is kept. With one
@@ -288,6 +392,11 @@ def scale_laf(laf: torch.Tensor, scale_coef: Union[float, torch.Tensor]) -> torc
Raises:
TypeError: if ``scale_coef`` is neither a ``float`` nor a tensor.
+ See Also:
+ - :func:`get_laf_scale`: reads the scale that this multiplies.
+ - :func:`laf_from_center_scale_ori`: new LAFs of given scales, built from their centres.
+ - :class:`LocalFeature`: applies this with its ``scaling_coef`` to the detector's LAFs before describing them.
+
Example:
>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3
>>> scale = 0.5
@@ -302,7 +411,12 @@ def scale_laf(laf: torch.Tensor, scale_coef: Union[float, torch.Tensor]) -> torc
def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
- r"""Rectify the affine matrix, so that it becomes upright.
+ r"""Remove the rotation and reflection of LAFs, keeping their regions, centres and scales.
+
+ ``upright = make_upright(laf)`` takes ``(B, N, 2, 3)`` LAFs and returns the ``(B, N, 2, 3)`` LAFs of the same
+ regions and centres with an orientation of 0 and no reflection: the shape ``A`` becomes the lower-triangular ``U``
+ of the Convention block. To set another orientation, use :func:`set_laf_orientation`; to
+ re-estimate the shape from the image instead, use :class:`LAFAffineShapeEstimator`.
Convention:
- The result is ``[U | c]``: the centre is kept, and ``U`` is the lower-triangular matrix with a positive
@@ -327,6 +441,13 @@ def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
Returns:
laf: ``(B, N, 2, 3)``
+ See Also:
+ - :func:`set_laf_orientation`: with angles of 0, the same LAFs for a positive determinant, but a reflection
+ is kept.
+ - :class:`LAFAffineShapeEstimator`: re-estimates the shape from the image patch; with
+ ``preserve_orientation=False`` its output is upright too.
+ - :func:`ellipse_to_laf`: the same upright LAF, built from the coefficients of the region's ellipse.
+
Example:
>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3
>>> output = make_upright(input) # BxNx2x3
@@ -364,7 +485,11 @@ def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:
- r"""Convert ellipse regions to LAF format.
+ r"""Convert ellipses in the Oxford ``[x, y, a, b, c]`` format to upright LAFs.
+
+ ``laf = ellipse_to_laf(ells)`` takes ``(B, N, 5)`` ellipses ``[x, y, a, b, c]``, as the Oxford affine-region files
+ write them, and returns the upright ``(B, N, 2, 3)`` LAFs of those regions: centred on ``(x, y)``, with an
+ orientation of 0. To draw the region of a LAF, use :func:`laf_to_boundary_points`.
Convention:
- An ellipse ``[x, y, a, b, c]`` is the region :math:`a u^2 + 2 b u v + c v^2 \le 1` in the coordinates
@@ -391,6 +516,11 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:
Returns:
LAF ``(B, N, 2, 3)``
+ See Also:
+ - :func:`laf_to_boundary_points`: points on the outline of a LAF's region, to draw it.
+ - :func:`make_upright`: the same upright LAF, from any LAF of the region.
+ - :func:`laf_from_center_scale_ori`: circular LAFs from keypoint centres, scales and orientations.
+
Example:
>>> input = torch.ones(1, 10, 5) # BxNx5
>>> output = ellipse_to_laf(input) # BxNx2x3
@@ -421,7 +551,12 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:
def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:
- r"""Convert LAFs to boundary points of the regions + center.
+ r"""Sample points on the outline of each LAF's region, after its centre, to draw it.
+
+ ``pts = laf_to_boundary_points(laf, n_pts)`` takes ``(B, N, 2, 3)`` LAFs and returns ``(B, N, n_pts, 2)`` points
+ ``(x, y)`` in the LAF's units: the centre, then ``n_pts - 1`` points around the ellipse ``c + A u`` over the unit
+ vectors ``u``. Drawn as one line, the points of a LAF show its region and a radius from the centre to the tip of
+ the patch's y axis. For the centre and the tips of both axes only, use :func:`laf_to_three_points`.
Convention:
- The first point is the centre ``c``. The other ``n_pts - 1`` points are ``c + A @ (sin t, cos t)`` for ``t``
@@ -433,7 +568,11 @@ def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:
n_pts: number of points to output, the centre included.
Returns:
- torch.Tensor of boundary points LAF: :math:`(B, N, n_pts, 2)`
+ torch.Tensor of boundary points LAF: ``(B, N, n_pts, 2)``
+
+ See Also:
+ - :func:`laf_to_three_points`: only the centre and the tips of the patch's two axes.
+ - :func:`ellipse_to_laf`: the LAF of an ellipse given by its coefficients.
"""
KORNIA_CHECK_LAF(LAF)
@@ -464,10 +603,11 @@ def get_laf_pts_to_draw(LAF: torch.Tensor, img_idx: int = 0) -> Tuple[List[int],
Args:
LAF: ``(B, N, 2, 3)``
- img_idx: which points to output.
+ img_idx: the index of the image whose LAFs are drawn.
Returns:
- List of boundary points x, y`
+ the lists ``x`` and ``y`` of the boundary points of ``laf_to_boundary_points`` for that image, each 50 lists
+ of ``N`` coordinates, so that ``plt.plot(x, y)`` draws one line per LAF.
Examples:
x, y = get_laf_pts_to_draw(LAF, img_idx)
@@ -485,18 +625,14 @@ def get_laf_pts_to_draw(LAF: torch.Tensor, img_idx: int = 0) -> Tuple[List[int],
def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
- """Denormalize LAFs from the [0, 1] scale to image (pixel) scale.
+ """Convert LAFs from the frame of normalize_laf back to the pixels of an image.
- B,CH,H,W = images.size()
- MIN_SIZE = min(H - 1, W -1)
- [a11 a12 x]
- [a21 a22 y]
- becomes
- [a11*MIN_SIZE a12*MIN_SIZE x*(W-1)]
- [a21*MIN_SIZE a22*MIN_SIZE y*(H-1)]
-
- A singleton axis (``H == 1`` or ``W == 1``) has no spatial extent and counts as one pixel, so
- the conversion stays finite and round-trips with :func:`normalize_laf`.
+ ``laf = denormalize_laf(nlaf, images)`` takes ``(B, N, 2, 3)`` LAFs in the frame of :func:`normalize_laf` and an
+ image tensor ``(B, CH, H, W)``, read for its height and width only, and returns the ``(B, N, 2, 3)`` LAFs in that
+ image's pixels: the centre multiplied by ``(max(W - 1, 1), max(H - 1, 1))`` and ``A`` by the smaller of the two.
+ A singleton axis (``H == 1`` or ``W == 1``) has no spatial extent and counts as one pixel, so the conversion stays
+ finite and round-trips with :func:`normalize_laf`. An image of another size than the one the LAFs were normalized
+ on moves them to its resolution.
Convention:
See the Convention block on :func:`~kornia.feature.normalize_laf`, which this inverts.
@@ -508,6 +644,11 @@ def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
Returns:
the denormalized LAF: ``(B, N, 2, 3)``, scale in pixels
+ See Also:
+ - :func:`normalize_laf`: the inverse, from pixels to this frame.
+ - :func:`extract_patches_from_pyramid`: takes LAFs in the normalized frame with
+ ``normalize_lafs_before_extraction=False``.
+
"""
KORNIA_CHECK_LAF(LAF)
_, _, h, w = images.size()
@@ -525,19 +666,13 @@ def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
def normalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
- """Normalize LAFs to [0,1] scale from pixel scale.
+ """Normalize pixel LAFs by the image size: centre to [0, 1], shape by min(W - 1, H - 1).
- See below:
- B,CH,H,W = images.size()
- MIN_SIZE = min(H - 1, W -1)
- [a11 a12 x]
- [a21 a22 y]
- becomes:
- [a11/MIN_SIZE a12/MIN_SIZE x/(W-1)]
- [a21/MIN_SIZE a22/MIN_SIZE y/(H-1)]
-
- A singleton axis (``H == 1`` or ``W == 1``) has no spatial extent and counts as one pixel, so
- the conversion stays finite instead of dividing by zero.
+ ``nlaf = normalize_laf(laf, images)`` takes ``(B, N, 2, 3)`` LAFs in pixels and an image tensor ``(B, CH, H, W)``,
+ read for its height and width only, and returns the ``(B, N, 2, 3)`` LAFs with the centre divided by
+ ``(max(W - 1, 1), max(H - 1, 1))`` and ``A`` by the smaller of the two. A singleton axis (``H == 1`` or ``W == 1``)
+ has no spatial extent and counts as one pixel, so the conversion stays finite instead of dividing by zero.
+ :func:`denormalize_laf` on an image of another size then moves the LAFs to that resolution.
Convention:
- The centre becomes ``(x / max(W - 1, 1), y / max(H - 1, 1))``, which lies in ``[0, 1]`` for
@@ -555,6 +690,11 @@ def normalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
Returns:
the normalized LAF: ``(B, N, 2, 3)``
+ See Also:
+ - :func:`denormalize_laf`: the inverse, back to the pixels of an image of any size.
+ - :func:`extract_patches_from_pyramid`: takes LAFs in this frame with
+ ``normalize_lafs_before_extraction=False``.
+
"""
KORNIA_CHECK_LAF(LAF)
_, _, h, w = images.size()
@@ -686,7 +826,7 @@ def _pyramid_atlas_fits(atlas_bytes: int, budget: int = 128 * 1024 * 1024) -> bo
def _sample_patches(img: torch.Tensor, grid: torch.Tensor, h: int, w: int) -> torch.Tensor:
r"""Sample one patch per LAF with a single ``grid_sample`` call.
- The per-LAF grids ``(B, N, PS, PS, 2)`` are folded to :math:`(B, N \cdot PS, PS, 2)` so
+ The per-LAF grids ``(B, N, PS, PS, 2)`` are folded to ``(B, N * PS, PS, 2)`` so
one call covers the whole batch, without a Python loop over B or a ``(B*N, CH, H, W)`` input
copy. ``grid`` must already live on ``img``'s device: the extractors move a cross-device LAF
to the image's device up front, so the grid is built there.
@@ -799,7 +939,14 @@ def _empty_patches(img: torch.Tensor, laf: torch.Tensor, B: int, N: int, PS: int
def extract_patches_simple(
img: torch.Tensor, laf: torch.Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True
) -> torch.Tensor:
- """Extract (B, N, CH, PS, PS) patches defined by LAFs from the full-resolution image only, without anti-aliasing.
+ """Sample a patch per LAF from the full-resolution image only, without anti-aliasing.
+
+ ``patches = extract_patches_simple(img, laf, PS)`` takes images ``(B, CH, H, W)`` and their LAFs ``(B, N, 2, 3)``
+ in pixels and returns one ``PS x PS`` patch per LAF, ``(B, N, CH, PS, PS)`` in the image dtype, sampled
+ bilinearly from ``img`` at the positions that :func:`extract_patches_from_pyramid` samples. For LAFs of a scale
+ below ``PS`` the two return the same patches up to rounding; a larger LAF is not smoothed first, so its patch
+ aliases. For patches to describe, orient or adapt, use :func:`extract_patches_from_pyramid` instead, as
+ :class:`LAFDescriptor`, :class:`LAFOrienter` and the affine shape estimators do.
Convention:
See the Convention block on :func:`~kornia.feature.extract_patches_from_pyramid`. This function samples the
@@ -815,6 +962,10 @@ def extract_patches_simple(
Returns:
patches with shape ``(B, N, CH, PS,PS)``.
+ See Also:
+ - :func:`extract_patches_from_pyramid`: samples each LAF from a pyramid level chosen by its scale to limit
+ aliasing.
+
"""
KORNIA_CHECK_LAF(laf)
KORNIA_CHECK(img.size(0) == laf.size(0), "img and laf must have the same batch size")
@@ -853,9 +1004,15 @@ def extract_patches_simple(
def extract_patches_from_pyramid(
img: torch.Tensor, laf: torch.Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True
) -> torch.Tensor:
- """Extract (B, N, CH, PS, PS) patches defined by LAFs, each sampled from the pyramid level that matches its scale.
+ """Sample a patch per LAF from the image pyramid level that matches its scale.
- Patches are extracted from the appropriate pyramid level.
+ ``patches = extract_patches_from_pyramid(img, laf, PS)`` takes images ``(B, CH, H, W)`` and their LAFs
+ ``(B, N, 2, 3)`` in pixels and returns one ``PS x PS`` patch per LAF, ``(B, N, CH, PS, PS)`` in the image dtype:
+ the square ``c + A [-1, 1]^2`` resampled from the level of a Gaussian pyramid of ``img`` that matches the LAF's
+ scale, which limits aliasing. It is the sampler of :func:`get_laf_descriptors`,
+ :class:`LAFOrienter` and the affine shape estimators. With ``normalize_lafs_before_extraction=False``, ``laf`` is
+ read in the frame of :func:`normalize_laf`. To sample the full-resolution image only, use
+ :func:`extract_patches_simple`.
Convention:
- Cell ``(i, j)`` of a ``PS x PS`` patch samples the image at ``c + A @ (u_j, u_i)``, with
@@ -867,7 +1024,8 @@ def extract_patches_from_pyramid(
that exist: :func:`~kornia.geometry.transform.pyrdown` builds them while the shorter side stays at least
``PS``, so a larger LAF is sampled from the coarsest level that can still provide a full patch. Level 0,
the image itself, always exists: an image whose shorter side is below ``PS`` has only that level, so even a
- large LAF is sampled from it. A level samples the same image positions as level 0, in its own pixels.
+ large LAF is sampled from it. The level uses the geometric-mean scale, so a highly anisotropic LAF can
+ still alias along its long axis. A level samples the same image positions as level 0, in its own pixels.
- A cell outside the image reads the nearest border pixel of the level it samples.
- The patches have the image's dtype. The sampling runs in the promoted dtype of the image and the LAF, and
in at least ``float32``. A LAF with a non-finite entry gives a zero patch.
@@ -882,6 +1040,12 @@ def extract_patches_from_pyramid(
Returns:
patches with shape ``(B, N, CH, PS,PS)``.
+ See Also:
+ - :func:`extract_patches_simple`: the same positions, always sampled from the full-resolution image.
+ - :func:`get_laf_descriptors`: describes the patches that this samples with a patch descriptor.
+ - :func:`laf_is_inside_image`: keeps the LAFs whose region lies inside the image, though the corners of
+ their patches can reach beyond it.
+
"""
KORNIA_CHECK_LAF(laf)
KORNIA_CHECK(img.size(0) == laf.size(0), "img and laf must have the same batch size")
@@ -1012,7 +1176,13 @@ def extract_patches_from_pyramid(
def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor, border: int = 0) -> torch.Tensor:
- """Check which LAFs lie fully inside the image.
+ """Check which LAFs have their elliptical region fully inside the image, within a border.
+
+ ``inside = laf_is_inside_image(laf, images, border)`` takes ``(B, N, 2, 3)`` LAFs in pixels and an image tensor
+ ``(B, CH, H, W)``, read for its height and width only, and returns a boolean ``(B, N)`` mask, true where the
+ elliptical region of the LAF lies at least ``border`` pixels inside the outer pixel centres. The patch of
+ :func:`extract_patches_from_pyramid` covers the square ``c + A [-1, 1]^2``, which reaches beyond the region, so a
+ LAF that is inside can still have patch cells that read the image border.
Convention:
- The region of a LAF ``[A | c]`` is the ellipse ``c + A u`` over the unit vectors ``u``. Along image axis
@@ -1030,6 +1200,10 @@ def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor, border: int = 0
Returns:
mask with shape ``(B, N)``.
+ See Also:
+ - :func:`laf_is_filled`: tells detections from the padding, which this counts as inside.
+ - :func:`laf_is_valid`: checks that the frame is finite and regular, wherever it lies.
+
"""
KORNIA_CHECK_LAF(laf)
_, _, h, w = images.size()
@@ -1045,7 +1219,12 @@ def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor, border: int = 0
def laf_to_three_points(laf: torch.Tensor) -> torch.Tensor:
- """Convert local affine frames (LAFs) to three points: the tips of the patch's x and y axes, and the centre.
+ """Convert LAFs to three points: the tips of the patch's x and y axes, then the centre.
+
+ ``pts = laf_to_three_points(laf)`` takes ``(B, N, 2, 3)`` LAFs and returns ``(B, N, 2, 3)`` tensors whose columns
+ are the image points ``c + A[:, 0]``, ``c + A[:, 1]`` and ``c``. Mapping the three columns through a point
+ transformation and converting them back with :func:`laf_from_three_points` transforms the LAFs, as
+ :func:`perspective_transform_lafs` does for a homography.
Convention:
- The columns of the result are the points ``c + A[:, 0]``, ``c + A[:, 1]`` and ``c``, in that order: the
@@ -1058,13 +1237,23 @@ def laf_to_three_points(laf: torch.Tensor) -> torch.Tensor:
Returns:
threepts ``(B, N, 2, 3)``.
+ See Also:
+ - :func:`laf_from_three_points`: the inverse.
+ - :func:`perspective_transform_lafs`: maps these three points through a homography and converts them back.
+ - :func:`laf_to_boundary_points`: points on the whole outline of the region.
+
"""
KORNIA_CHECK_LAF(laf)
return torch.stack([laf[..., 2] + laf[..., 0], laf[..., 2] + laf[..., 1], laf[..., 2]], dim=-1)
def laf_from_three_points(threepts: torch.Tensor) -> torch.Tensor:
- """Convert three points to local affine frame.
+ """Build LAFs from three points each: the tips of the patch's x and y axes, then the centre.
+
+ ``laf = laf_from_three_points(pts)`` takes ``(B, N, 2, 3)`` tensors whose columns are three points ``p0``, ``p1``
+ and ``c`` and returns the ``(B, N, 2, 3)`` LAFs ``[p0 - c, p1 - c | c]``, whose patch x and y axes end at ``p0``
+ and ``p1``. Collinear points give a singular shape ``A``. For LAFs from centres, scales and orientations, use
+ :func:`laf_from_center_scale_ori` instead.
Convention:
See the Convention block on :func:`~kornia.feature.laf_to_three_points`, which this inverts: the columns of
@@ -1076,6 +1265,10 @@ def laf_from_three_points(threepts: torch.Tensor) -> torch.Tensor:
Returns:
laf ``(B, N, 2, 3)``.
+ See Also:
+ - :func:`laf_to_three_points`: the inverse.
+ - :func:`laf_from_center_scale_ori`: circular LAFs from centres, scales and orientations.
+
"""
KORNIA_CHECK_SHAPE(threepts, ["B", "N", "2", "3"])
return torch.stack(
@@ -1084,7 +1277,12 @@ def laf_from_three_points(threepts: torch.Tensor) -> torch.Tensor:
def perspective_transform_lafs(trans_01: torch.Tensor, lafs_1: torch.Tensor) -> torch.Tensor:
- r"""Apply perspective transformations to a set of local affine frames (LAFs).
+ r"""Map the LAFs of one image into another through a homography, by mapping three points of each.
+
+ ``lafs_0 = perspective_transform_lafs(trans_01, lafs_1)`` takes ``(B, 3, 3)`` homographies from the pixels of
+ image 1 to those of image 0 and ``(B, N, 2, 3)`` LAFs of image 1, and returns the ``(B, N, 2, 3)`` LAFs of the
+ same regions in image 0: the centres mapped exactly and the shapes approximated through the mapped tips of the
+ patch axes. To map points, such as the LAF centres alone, use :func:`~kornia.geometry.linalg.transform_points`.
Convention:
- ``trans_01`` maps pixels of frame 1 to pixels of frame 0, as in
@@ -1101,6 +1299,14 @@ def perspective_transform_lafs(trans_01: torch.Tensor, lafs_1: torch.Tensor) ->
Returns:
the transformed LAFs in frame 0, of shape ``(B, N, 2, 3)``.
+ Raises:
+ TypeError: if ``trans_01`` is not a tensor or is on another device than ``lafs_1``.
+ ValueError: if the batch sizes differ or ``trans_01`` is not ``3 x 3``.
+
+ See Also:
+ - :func:`~kornia.geometry.linalg.transform_points`: maps points through the same homographies.
+ - :func:`laf_to_three_points`: the three points of each LAF that this maps.
+
Examples:
>>> rng = torch.manual_seed(0)
>>> lafs_1 = torch.rand(2, 4, 2, 3) # BxNx2x3
diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.py
index 52b3da2f9..39b2e86ee 100644
--- a/kornia/feature/lightglue.py
+++ b/kornia/feature/lightglue.py
@@ -467,10 +467,17 @@ def _select_pair(image: Dict[str, Any], k: int, b: int) -> Dict[str, Any]:
class LightGlue(nn.Module):
- """Implement the LightGlue matcher for sparse local features.
-
- LightGlue is a deep network that matches local features across image pairs
- using a series of transformer layers and an adaptive pruning mechanism.
+ """Match the keypoints and descriptors of image pairs with the LightGlue transformer, given as dicts.
+
+ ``lightglue = LightGlue("disk")`` loads the weights trained for that local feature and
+ ``out = lightglue({"image0": feats0, "image1": feats1})`` takes, for each image, a dict of ``keypoints``
+ ``(B, M, 2)`` as ``(x, y)`` pixels, ``descriptors`` ``(B, M, D)`` and ``image_size`` ``(B, 2)`` as ``(W, H)``,
+ and returns a dict whose ``matches0`` ``(B, M)`` holds the index in image1 of the match of each keypoint of
+ image0, ``-1`` for an unmatched one, with its score in ``matching_scores0`` ``(B, M)``; ``matches`` and
+ ``scores`` list the matched index pairs ``(S, 2)`` and scores ``(S,)`` of each pair of images. The network is a
+ series of transformer layers, with early stopping and point pruning unless the configuration turns them off.
+ For the call of the other kornia matchers, on descriptors and LAFs, use :class:`LightGlueMatcher`; for an
+ exported ONNX model run by onnxruntime, use :class:`OnnxLightGlue`.
Convention:
- Complete learned weights return the model in evaluation mode, even if derived buffers are absent from
@@ -496,20 +503,23 @@ class LightGlue(nn.Module):
float64 scores for float64 descriptors, as on CPU, because autocast does not cast float64. An image without
descriptors runs no layer, and its zero scores keep the descriptor dtype, also with ``mp=True``.
- Each pair of a batch gives the matches and scores it gives on its own when point pruning can run, that is
- with ``width_confidence > 0``, no padding to the static lengths of :meth:`compile`, and an image with more
- keypoints than :meth:`pruning_min_kpts` of the device. Pruning keeps a different number of points in each
+ with ``width_confidence > 0``, no padding to the ``static_lengths`` of ``LightGlue.compile`` (which wraps
+ the transformer layers in :func:`torch.compile`), and an image with more keypoints than
+ ``pruning_min_kpts(device)`` returns: any number on CPU and MPS, more than 1536 on CUDA with the default
+ ``flash=True`` and more than 1024 without. Pruning keeps a different number of points in each
pair, so then the pairs run one at a time: ``matches0``, ``matches1``, ``matching_scores0``,
``matching_scores1``, ``prune0`` and ``prune1`` stack the rows of the pairs, ``matches`` and ``scores`` list
them, ``stop`` is the largest number of layers that a pair ran, and there is no ``log_assignment``.
Otherwise a batch runs as one, and early stopping (``depth_confidence``) ends it at a layer only when every
pair meets its own criterion. A pair can therefore run more layers in a batch than on its own, and its
- matches can differ. Early stopping counts the real keypoints only, so padding to the static lengths of
- :meth:`compile` does not change the layer at which a pair stops.
+ matches can differ. Early stopping counts the real keypoints only, so padding to the ``static_lengths`` of
+ ``LightGlue.compile`` does not change the layer at which a pair stops.
Args:
- features: The type of local features to match (e.g., 'superpoint', 'disk'), whose configuration and
- pretrained weights are loaded. ``None`` builds the model from ``default_conf`` and the keyword arguments
- and downloads no weights.
+ features: The type of local features to match, whose configuration and pretrained weights are loaded: one of
+ ``"aliked"``, ``"dedodeb"``, ``"dedodeg"``, ``"disk"``, ``"dog_affnet_hardnet"``, ``"doghardnet"``,
+ ``"keynet_affnet_hardnet"``, ``"raco-aliked"``, ``"sift"``, ``"superpoint"`` and ``"xfeat"``. ``None``
+ builds the model from ``default_conf`` and the keyword arguments and downloads no weights.
**conf: keyword arguments that override entries of ``default_conf`` and of the configuration of
``features``, such as ``filter_threshold`` or ``depth_confidence``. The configuration of ``features`` sets
the defaults, and an explicit keyword argument always wins, except ``weights``, which must name the
@@ -517,6 +527,12 @@ class LightGlue(nn.Module):
counts as not given. This departs on purpose from cvg/LightGlue, which applies the configuration of
``features`` after the keyword arguments, so that the tuning knobs a preset sets, such as ``"xfeat"``'s
``width_confidence``, can be changed.
+
+ See Also:
+ - :class:`LightGlueMatcher`: the same network on descriptors and LAFs, returning scores and index pairs like
+ the other kornia matchers.
+ - :class:`OnnxLightGlue`: an exported LightGlue model run by onnxruntime, for one image pair on CPU or CUDA.
+ - :class:`LoFTR`: a transformer matcher that takes the images themselves, without a detector.
"""
default_conf: ClassVar[Dict[str, Any]] = {
diff --git a/kornia/feature/lightglue_onnx/lightglue.py b/kornia/feature/lightglue_onnx/lightglue.py
index 42537028b..a1f542ea5 100644
--- a/kornia/feature/lightglue_onnx/lightglue.py
+++ b/kornia/feature/lightglue_onnx/lightglue.py
@@ -39,10 +39,15 @@ __all__ = ["OnnxLightGlue"]
class OnnxLightGlue:
- r"""Wrapper for loading LightGlue-ONNX models and running inference via ONNXRuntime.
+ r"""Match the keypoints and descriptors of one image pair with an exported LightGlue ONNX model.
- LightGlue :cite:`LightGlue2023` performs fast descriptor-based deep keypoint matching.
- This module requires `onnxruntime` to be installed.
+ ``matcher = OnnxLightGlue("disk", device="cpu")`` downloads an exported LightGlue :cite:`LightGlue2023` model,
+ or loads your own ONNX file, into an onnxruntime session, and ``out = matcher(data)`` takes the dicts of
+ :class:`LightGlue` for a batch of one: float32 ``keypoints`` ``(1, M, 2)`` in pixels and ``descriptors``
+ ``(1, M, D)`` on that device, with ``image_size`` ``(1, 2)`` as ``(W, H)`` or an ``image``. It returns the
+ matched index pairs ``matches`` ``(S, 2)`` and their ``scores`` ``(S,)``. It needs ``onnxruntime`` and runs on
+ CPU or CUDA only. For batches, other devices or dtypes, scales, orientations or LAFs, or the full outputs of the
+ network, use :class:`LightGlue` instead.
If you have trained your own LightGlue model, see https://github.com/fabio-sim/LightGlue-ONNX
for how to export the model to ONNX and optimize it.
@@ -52,13 +57,21 @@ class OnnxLightGlue:
with ``image_size`` in the order ``(W, H)``, and the same range check applies. Unlike
:class:`~kornia.feature.LightGlue`, it takes float32 inputs with a batch of one and no scales, orientations
or LAFs, and it runs on CPU or CUDA only.
+ - Known defect: the session and its inputs are bound to GPU 0 for every CUDA ``device``, so
+ ``device="cuda:1"`` does not run on GPU 1 (`#6427 <https://github.com/kornia/kornia/issues/6427>`_).
Args:
weights: Pretrained weights, or a path to your own exported ONNX model. Available pretrained weights
are ``'disk'``, ``'superpoint'``, ``'disk_fp16'``, and ``'superpoint_fp16'``. `Note that FP16 requires CUDA.`
Defaults to ``'disk_fp16'`` if ``device`` is CUDA, and ``'disk'`` if CPU.
- device: ``'cpu'`` or ``'cuda'`` to run inference on; another device raises ``ValueError``. ``None`` means
- ``'cpu'``, as in the other kornia feature constructors, not torch's current default device.
+ device: ``'cpu'`` or ``'cuda'`` to run inference on; another device type raises ``ValueError``. ``None``
+ means ``'cpu'``, as in the other kornia feature constructors, not torch's current default device.
+
+ See Also:
+ - :class:`LightGlue`: the PyTorch network, which also runs batches, on MPS, and in float16, bfloat16 or
+ float64 (see its Convention block), and returns every output.
+ - :class:`LightGlueMatcher`: LightGlue on descriptors and LAFs, returning scores and index pairs like the
+ other kornia matchers.
"""
@@ -145,7 +158,7 @@ class OnnxLightGlue:
``output`` (``dict``):
``matches`` (`int64`): ``(S, 2)``
- ``scores`` (`float32`): ``(S)``
+ ``scores`` (`float32`): ``(S,)``
"""
# Input validation.
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index 9b78dcbd3..58586d4ba 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -78,10 +78,20 @@ default_cfg = {
class LoFTR(nn.Module):
- r"""nn.Module, which finds correspondences between two images.
+ r"""Match two grayscale images without a detector, by transformer-matched dense features (LoFTR).
- This is based on the original code from paper "LoFTR: Detector-Free Local
- Feature Matching with Transformers". See :cite:`LoFTR2021` for more details.
+ ``loftr = LoFTR("outdoor")`` loads pretrained weights and ``out = loftr({"image0": img0, "image1": img1})`` takes
+ two batches of ``N`` grayscale images ``(N, 1, H, W)`` in :math:`[0, 1]`, the two possibly of different sizes, and
+ returns a dict of the matches of all pairs: the pixel positions ``keypoints0`` and ``keypoints1`` ``(NC, 2)``, as
+ ``(x, y)`` in the frame of the reference implementation, half a pixel off kornia's (see the Convention block),
+ their ``confidence`` ``(NC,)`` and the pair of each match, ``batch_indexes`` ``(NC,)``. It needs no keypoints or
+ descriptors: the matches of image0 lie on a grid of 8-pixel cells, not at detected keypoints. To match one image
+ against many, compute its backbone features, which do not depend on the other image, once with
+ :meth:`extract_features` and pass them as ``features0`` or ``features1``. For matching detected keypoints and
+ their descriptors, use :class:`LightGlueMatcher` or :class:`LocalFeatureMatcher` instead.
+
+ This is based on the original code of "LoFTR: Detector-Free Local Feature Matching with Transformers", see
+ :cite:`LoFTR2021` for more details.
Convention:
- ``image0`` and ``image1`` are grayscale ``(N, 1, H, W)`` images in :math:`[0, 1]`, the input of the
@@ -99,10 +109,12 @@ class LoFTR(nn.Module):
- ``confidence`` is the coarse matching score of the match, a dual-softmax score with the default
``match_type``; only matches above ``max(thr, 0)`` are returned, with the ``thr`` of
``config["match_coarse"]``, 0.2 by default.
+ - Known defect: with ``mask0`` or ``mask1``, the border strip in which coarse matches are dropped
+ (``border_rm`` coarse cells, 16 pixels by default) is measured from the edges of the padded image, not of
+ its valid region, so matches next to the padding are kept
+ (`#5888 <https://github.com/kornia/kornia/issues/5888>`_).
Args:
- config: Dict with initialization parameters. Do not pass it, unless you know what you are doing.
- The model works on its own deep copy, so the dict you pass is never modified.
pretrained: Download and set pretrained weights to the model. Options: 'outdoor', 'indoor', 'indoor_new'.
'outdoor' is trained on the MegaDepth dataset and 'indoor' and 'indoor_new'
on the ScanNet. 'indoor_new' also switches the positional encoding of the copy
@@ -110,12 +122,17 @@ class LoFTR(nn.Module):
comes back in evaluation mode. ``None`` builds random weights in training mode, where
``CoarseMatching`` runs its supervised training branch and needs ground-truth data; call
``.eval()`` for inference, also after loading your own weights.
+ config: Dict with initialization parameters. Do not pass it, unless you know what you are doing.
+ The model works on its own deep copy, so the dict you pass is never modified.
Returns:
Dictionary with image correspondences and confidence scores.
- The backbone features of an image do not depend on the image it is matched with. To match one image against
- many, compute them once with :meth:`extract_features` and pass them as ``features0`` / ``features1``.
+ See Also:
+ - :class:`LightGlueMatcher`: a transformer matcher for the keypoints and descriptors of a detector.
+ - :class:`LocalFeatureMatcher`: detects, describes and matches two images with a descriptor matcher.
+ - :class:`~kornia.geometry.ransac.RANSAC`: the next step, which keeps the matches one geometric model
+ explains, such as a :func:`~kornia.geometry.epipolar.find_fundamental` matrix.
Example:
>>> img1 = torch.rand(1, 1, 320, 200)
@@ -164,10 +181,9 @@ class LoFTR(nn.Module):
image: grayscale images with shape ``(N, 1, H, W)``.
Returns:
- - ``coarse``, position-encoded 1/8-resolution features
- :math:`(N, C_c, \lceil H/8 \rceil, \lceil W/8 \rceil)`.
- - ``fine``, 1/2-resolution features :math:`(N, C_f, \lceil H/2 \rceil, \lceil W/2 \rceil)`. With the
- default config this is 128 channels, about 96 MB in float32 for a 1024 x 736 image.
+ - ``coarse``, position-encoded 1/8-resolution features ``(N, C_c, ceil(H / 8), ceil(W / 8))``.
+ - ``fine``, 1/2-resolution features ``(N, C_f, ceil(H / 2), ceil(W / 2))``. With the default config this
+ is 128 channels, about 96 MB in float32 for a 1024 x 736 image.
Example:
>>> loftr = LoFTR(None).eval()
@@ -219,8 +235,8 @@ class LoFTR(nn.Module):
Returns:
- ``keypoints0``, matching keypoints from image0 ``(NC, 2)``.
- ``keypoints1``, matching keypoints from image1 ``(NC, 2)``.
- - ``confidence``, the coarse matching score, see the Convention block ``(NC)``.
- - ``batch_indexes``, batch index of each match ``(NC)``.
+ - ``confidence``, the coarse matching score, see the Convention block ``(NC,)``.
+ - ``batch_indexes``, batch index of each match ``(NC,)``.
"""
# Pixel strides of the coarse and the fine feature map, (8, 2) by default. Every stride-2 stage of the backbone
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 82676d2cb..c2d0ebe35 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -303,12 +303,18 @@ def match_nn(
) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Match each descriptor in desc1 to its nearest neighbor in desc2, with no filtering.
+ ``dists, idxs = match_nn(desc1, desc2)`` takes two descriptor sets ``(B1, D)`` and ``(B2, D)`` and returns, for
+ every row of ``desc1`` in order, the L2 distance ``(B1, 1)`` to its nearest row of ``desc2`` and the index pair
+ ``(B1, 2)`` of the two rows; a precomputed ``dm`` ``(B1, B2)`` replaces the L2 distances. Every row is matched,
+ however ambiguous its nearest neighbour, and several rows can match the same row of ``desc2``. To keep only the
+ reliable matches, use :func:`match_mnn` (mutual nearest neighbours), :func:`match_snn` (Lowe's ratio test) or
+ :func:`match_smnn` (both) instead.
+
Convention:
- Every ``match_*`` function returns ``(dists, idxs)``, one row per match. ``idxs`` is an int64
- ``(M, 2)`` tensor of ``(index in desc1, index in desc2)`` rows (:func:`match_smnn_batched` adds the
- batch index as a first column). ``dists`` is ``(M, 1)``, in the dtype of ``dm`` when it is given and in
- the descriptor dtype otherwise, except that :func:`match_adalam` returns float32. Lower values are better,
- and what they are depends on the function:
+ ``(M, 2)`` tensor of ``(index in desc1, index in desc2)`` rows; :func:`match_smnn_batched` adds the batch
+ index as a first column. ``dists`` is ``(M, 1)``. Without ``dm``, it has the descriptor dtype, except that
+ :func:`match_adalam` returns float32. Lower values are better, and their meaning depends on the function:
- :func:`match_nn`, :func:`match_mnn`: the distance, the entry of ``dm`` when it is given.
- :func:`match_snn`: the ratio of the nearest to the second-nearest distance, not a distance.
@@ -323,13 +329,10 @@ def match_nn(
``1 - dists`` as ``confidence``.
- The ratio tests of :func:`match_snn`, :func:`match_smnn`, :func:`match_smnn_batched` and
:func:`match_fginn` keep ``ratio <= th``: a ratio equal to ``th`` passes.
- - Without ``dm``, the L2 distances between the descriptors are used. On the CPU and CUDA, for inputs that
- need no gradient, the matchers select on the squared distances and take the square roots of the selected
- ones. The returned values are those of ``torch.cdist``, but two distances that round to the same value only
- after the square root are not tied, and the nearer one is returned. A given ``dm`` is read as it is:
- :func:`match_nn` and :func:`match_mnn` accept any matrix in which smaller is better and return its
- entries, while the ratio tests divide its entries, so they need non-negative values, and squared
- distances need ``th ** 2``.
+ - Without ``dm``, the functions use L2 distances. A given ``dm`` replaces them: :func:`match_nn` and
+ :func:`match_mnn` require only that smaller entries are better, while ratio tests require non-negative
+ distances. Use ``th ** 2`` for squared distances.
+ - Of tied nearest neighbours, :func:`match_nn` and :func:`match_mnn` take the one with the lower index.
- An empty desc1 or desc2 gives a ``(0, 1)`` and a ``(0, 2)`` tensor (``(0, 3)`` for
:func:`match_smnn_batched`). The ratio tests need a second neighbour: :func:`match_snn` and
:func:`match_fginn` return no match unless desc2 has two rows, and :func:`match_smnn`,
@@ -343,8 +346,14 @@ def match_nn(
to each descriptor in desc2, shape of ``(B1, B2)``.
Returns:
- - Descriptor distance of matching descriptors, shape of ``(B1, 1)``.
- - Long torch.Tensor indexes of matching descriptors in desc1 and desc2, shape of ``(B1, 2)``.
+ - Descriptor distance of matching descriptors, shape of ``(B1, 1)``, or ``(0, 1)`` when desc2 is empty.
+ - Long torch.Tensor indexes of matching descriptors in desc1 and desc2, shape of ``(B1, 2)``, or
+ ``(0, 2)`` when desc2 is empty.
+
+ See Also:
+ - :func:`match_mnn`: keeps only the pairs that are each other's nearest neighbours.
+ - :func:`match_snn`: keeps only the nearest neighbours that pass Lowe's ratio test.
+ - :class:`DescriptorMatcher`: the module form, with ``match_mode="nn"``.
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
@@ -367,11 +376,18 @@ def match_nn(
def match_mnn(
desc1: torch.Tensor, desc2: torch.Tensor, dm: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor]:
- """Match the descriptors of desc1 and desc2 that are each other's nearest neighbors (mutual nearest neighbors).
+ """Match the descriptors of desc1 and desc2 that are each other's nearest neighbors.
+
+ ``dists, idxs = match_mnn(desc1, desc2)`` takes two descriptor sets ``(B1, D)`` and ``(B2, D)`` and returns the
+ pairs whose two descriptors are each other's nearest neighbour, the mutual nearest neighbours: their L2
+ distances ``(B3, 1)`` and index pairs ``(B3, 2)``, with ``B3 <= min(B1, B2)``. Each row of either set is matched
+ at most once, but a distinctive descriptor and an ambiguous one are kept alike; to also require Lowe's ratio
+ test, use :func:`match_smnn` instead.
Convention:
See the Convention block on :func:`match_nn`. A pair is kept only when each of the two descriptors is the
- nearest neighbour of the other.
+ nearest neighbour of the other. Ties go to the lower index in both directions, so of several identical
+ rows of desc2 only the first can be matched.
Args:
desc1: Batch of descriptors of a shape ``(B1, D)``.
@@ -384,6 +400,12 @@ def match_mnn(
- Long torch.Tensor indexes of matching descriptors in desc1 and desc2, shape of ``(B3, 2)``,
where 0 <= B3 <= min(B1, B2)
+ See Also:
+ - :func:`match_nn`: the nearest neighbour of every row of desc1, mutual or not.
+ - :func:`match_smnn`: mutual nearest neighbours that also pass the ratio test in both directions.
+ - :func:`match_snn`: the ratio test in one direction, without the mutual check.
+ - :class:`DescriptorMatcher`: the module form, with ``match_mode="mnn"``.
+
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])
@@ -463,9 +485,13 @@ def _nearest_neighbour_ratio(distance_matrix: torch.Tensor, squared: bool = Fals
def match_snn(
desc1: torch.Tensor, desc2: torch.Tensor, th: float = 0.8, dm: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor]:
- """Match each descriptor in desc1 to its nearest neighbor in desc2 if it passes Lowe's second-nearest ratio test.
+ """Match each descriptor in desc1 to its nearest neighbor in desc2 if it passes Lowe's ratio test.
- The ratio of the first to the second nearest neighbor distance must be <= th.
+ ``dists, idxs = match_snn(desc1, desc2, th)`` takes two descriptor sets ``(B1, D)`` and ``(B2, D)``, keeps the
+ rows of ``desc1`` whose nearest neighbour in ``desc2`` is at most ``th`` times as far as the second-nearest, and
+ returns their ratios ``(B3, 1)``, not distances, and index pairs ``(B3, 2)``, with ``B3 <= B1``, in the order of
+ the rows of ``desc1``. Several rows of ``desc1`` can match the same row of ``desc2``; to keep only mutual
+ nearest neighbours that pass the test in both directions, use :func:`match_smnn` instead.
Speed, with the same matches, on 1,024 to 8,192 RootSIFT descriptors: on an x86 CPU this is faster than faiss and
OpenCV's ``BFMatcher``, while faiss's exact k-nearest-neighbour search runs this ratio test up to 2.2x faster on
@@ -488,6 +514,13 @@ def match_snn(
- Long torch.Tensor indexes of matching descriptors in desc1 and desc2. Shape: ``(B3, 2)``,
where 0 <= B3 <= B1.
+ See Also:
+ - :func:`match_nn`: the nearest neighbour of every row of desc1, without the ratio test.
+ - :func:`match_mnn`: mutual nearest neighbours, without the ratio test.
+ - :func:`match_smnn`: the ratio test in both directions, on mutual nearest neighbours.
+ - :func:`match_fginn`: the same ratio test, with a second neighbour that lies elsewhere in the image.
+ - :class:`DescriptorMatcher`: the module form, with ``match_mode="snn"``.
+
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])
@@ -516,9 +549,13 @@ def match_snn(
def match_smnn(
desc1: torch.Tensor, desc2: torch.Tensor, th: float = 0.95, dm: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor]:
- """Match mutual nearest neighbors of desc1 and desc2 that also pass the second-nearest ratio test both ways.
+ """Match mutual nearest neighbors that also pass Lowe's ratio test in both directions.
- The ratio of the first to the second nearest neighbor distance must be <= th in both directions.
+ ``dists, idxs = match_smnn(desc1, desc2, th)`` takes two descriptor sets ``(B1, D)`` and ``(B2, D)``, keeps the
+ mutual nearest neighbours whose nearest-to-second-nearest distance ratio is at most ``th`` both from ``desc1``
+ to ``desc2`` and back, and returns the larger of their two ratios ``(B3, 1)`` and their index pairs ``(B3, 2)``,
+ with ``B3 <= min(B1, B2)``, in the order of the rows of ``desc1``. For many pairs of descriptor sets, padded to
+ common sizes, use :func:`match_smnn_batched` instead of a loop.
Speed, with the same matches, on 1,024 to 8,192 RootSIFT descriptors: on an x86 CPU this is faster than faiss and
OpenCV's ``BFMatcher``, while faiss's exact k-nearest-neighbour search, run both ways, is up to 1.6x faster on
@@ -543,6 +580,14 @@ def match_smnn(
- Long torch.Tensor indexes of matching descriptors in desc1 and desc2,
shape of ``(B3, 2)`` where 0 <= B3 <= B1.
+ See Also:
+ - :func:`match_snn`: the ratio test from desc1 to desc2 only, without the mutual check.
+ - :func:`match_mnn`: mutual nearest neighbours without the ratio test.
+ - :func:`match_smnn_batched`: the same matches for a batch of padded descriptor-set pairs, in one call.
+ - :class:`DescriptorMatcher`: the module form, with ``match_mode="smnn"`` and a default ``th`` of 0.8.
+ - :class:`~kornia.geometry.ransac.RANSAC`: the next step, which keeps the matches one geometric model
+ explains.
+
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])
@@ -582,18 +627,22 @@ def match_smnn_batched(
mask1: Optional[torch.Tensor] = None,
mask2: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
- r"""Match independent descriptor pairs with a batched symmetric nearest-neighbor ratio test.
+ r"""Match a batch of padded descriptor-set pairs in one call, each as match_smnn matches one pair.
- Like :func:`match_smnn`, each match must pass Lowe's first/second L2 distance
- ratio test in both directions and have mutual nearest neighbors. The returned
- quality is the larger of the two ratios. Pairs are processed together with
- batched distance computation and top-k reductions, without a per-pair loop.
+ ``ratios, idxs = match_smnn_batched(desc1, desc2, th)`` takes ``B`` pairs of descriptor sets, ``(B, N, D)`` and
+ ``(B, M, D)``, padded to common sizes, with optional boolean masks ``mask1`` ``(B, N)`` and ``mask2`` ``(B, M)``
+ of the valid rows, and returns the matches of every pair at once, without a loop over the pairs: the larger of
+ the two ratios ``(K, 1)`` and index rows ``(K, 3)`` of ``(batch index, index in desc1, index in desc2)``, which
+ index the padded tensors and come sorted by batch index, then index in desc1. For a single pair, use
+ :func:`match_smnn`.
Convention:
See the Convention blocks on :func:`match_nn` and :func:`match_smnn`. For each batch item it returns the
- pairs and ratios that :func:`match_smnn` returns for the valid descriptors of that item, with the batch
- index as the first column of the indices. For float16 and bfloat16 descriptors these are the results of
- :func:`match_smnn` on float32 copies, with the ratios rounded back, and a few pairs and ratios can differ
+ pairs and ratios that :func:`match_smnn` returns for finite distances between the valid descriptors of that
+ item, with the batch index as the first column of the indices. Unlike :func:`match_smnn`, it rejects a match
+ when the nearest or second-nearest distance in either direction is non-finite. Without ``dm``, float16 and
+ bfloat16 descriptors give the results
+ of :func:`match_smnn` on float32 copies, with the ratios rounded back, and a few pairs and ratios can differ
slightly from those of :func:`match_smnn` on the half-precision descriptors.
Args:
@@ -622,6 +671,10 @@ def match_smnn_batched(
undefined ratio and that ambiguous match is rejected. Ties follow
:func:`torch.topk` and do not have a guaranteed cross-device ordering.
+ See Also:
+ - :func:`match_smnn`: the same test for one pair of descriptor sets of any sizes, with no padding.
+ - :func:`match_snn`: the ratio test in one direction for one pair, without the mutual check.
+
Example:
>>> a = torch.tensor([[[0., 0.], [1., 1.], [2., 2.]]])
>>> ratios, indices = match_smnn_batched(a, a.flip(1))
@@ -716,10 +769,17 @@ def match_fginn(
mutual: bool = False,
dm: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
- """Match desc1 to desc2 by a ratio test against the first geometrically inconsistent nearest neighbor (FGINN).
-
- The ratio test compares the nearest distance with that of the nearest candidate whose ``lafs2`` centre lies at
- least ``spatial_th`` from the first one's; closer candidates are skipped (see :cite:`MODS2015` for more details).
+ """Match desc1 to desc2 by a ratio test against the first geometrically inconsistent neighbor (FGINN).
+
+ ``dists, idxs = match_fginn(desc1, desc2, lafs1, lafs2, th, spatial_th)`` takes two descriptor sets ``(B1, D)``
+ and ``(B2, D)`` and the LAFs ``(1, B2, 2, 3)`` of ``desc2``, keeps the rows of ``desc1`` whose nearest neighbour
+ in ``desc2`` passes the ratio test of :func:`match_snn` against the nearest candidate whose ``lafs2`` centre
+ lies at least ``spatial_th`` from the nearest one's, and returns their ratios ``(B3, 1)`` and index pairs
+ ``(B3, 2)``, in the order of the rows of ``desc1``. Closer candidates are skipped (see :cite:`MODS2015` for more
+ details), so a near-duplicate detection of the same structure, such as another scale or orientation at one
+ place, does not reject the match as it can in :func:`match_snn`. ``lafs1`` is not read, and ``mutual=True`` adds
+ the mutual nearest-neighbour check. To test the local affine consistency of the matches in both images, use
+ :func:`match_adalam` instead.
Convention:
- See the Convention block on :func:`match_nn`. ``dists`` is a ratio: the nearest distance over the distance
@@ -752,6 +812,11 @@ def match_fginn(
- Long torch.Tensor indexes of matching descriptors in desc1 and desc2. Shape: ``(B3, 2)``,
where 0 <= B3 <= B1.
+ See Also:
+ - :func:`match_snn`: the plain ratio test, whose second neighbour can lie on the same structure.
+ - :func:`match_adalam`: keeps the nearest-neighbour matches that local affine models of both images support.
+ - :class:`GeometryAwareDescriptorMatcher`: the module form, with ``match_mode="fginn"``.
+
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])
@@ -794,13 +859,14 @@ def match_fginn(
class DescriptorMatcher(nn.Module):
- """nn.Module version of descriptor-only matching functions.
+ """Match two descriptor sets by nearest neighbours, mutual ones or a ratio test, as a module.
- This matcher only requires descriptors (no LAFs). For geometry-aware matching that uses LAFs,
- see :class:`~kornia.feature.GeometryAwareDescriptorMatcher`.
-
- See :func:`~kornia.feature.match_nn`, :func:`~kornia.feature.match_snn`,
- :func:`~kornia.feature.match_mnn` or :func:`~kornia.feature.match_smnn` for more details.
+ ``matcher = DescriptorMatcher("snn", th=0.8)`` builds the module and ``dists, idxs = matcher(desc1, desc2)``
+ takes two descriptor sets ``(B1, D)`` and ``(B2, D)`` and returns what :func:`match_nn`, :func:`match_mnn`,
+ :func:`match_snn` or :func:`match_smnn` returns for them, by ``match_mode``: ``(B3, 1)`` qualities and
+ ``(B3, 2)`` index pairs. It holds no parameters and reads no LAFs, which makes it a matcher for
+ :class:`LocalFeatureMatcher`. For matchers that also read the LAFs, use :class:`GeometryAwareDescriptorMatcher`
+ instead, and for a learned one, :class:`LightGlueMatcher`.
Convention:
See the Convention block on :func:`~kornia.feature.match_nn`. ``forward`` returns what the function of
@@ -812,6 +878,20 @@ class DescriptorMatcher(nn.Module):
match_mode: type of matching, can be `nn`, `snn`, `mnn`, `smnn`.
th: distance ratio threshold of the `snn` and `smnn` modes.
+ Raises:
+ NotImplementedError: for another ``match_mode``.
+
+ See Also:
+ - :func:`match_nn`: the function of ``match_mode="nn"``, which also takes a precomputed ``dm``; so do the
+ other three.
+ - :func:`match_mnn`: the function of ``match_mode="mnn"``.
+ - :func:`match_snn`: the function of the default ``match_mode="snn"``.
+ - :func:`match_smnn`: the function of ``match_mode="smnn"``, whose own ``th`` defaults to 0.95.
+ - :class:`GeometryAwareDescriptorMatcher`: the module form of :func:`match_fginn` and :func:`match_adalam`,
+ which also take LAFs.
+ - :class:`LocalFeatureMatcher`: detects and describes the features of two images, then matches them with a
+ module like this one.
+
"""
def __init__(self, match_mode: str = "snn", th: float = 0.8) -> None:
@@ -1018,10 +1098,14 @@ class DescriptorMatcherWithSteerer(nn.Module):
class GeometryAwareDescriptorMatcher(nn.Module):
- """nn.Module version of geometry-aware matching functions that use LAFs (Local Affine Frames).
+ """Match two descriptor sets that come with their LAFs, by FGINN or AdaLAM, as a module.
- Unlike :class:`~kornia.feature.DescriptorMatcher`, this matcher requires both descriptors and LAFs.
- See :func:`~kornia.feature.match_fginn` or :func:`~kornia.feature.match_adalam` for more details.
+ ``matcher = GeometryAwareDescriptorMatcher("fginn", params)`` builds the module and
+ ``dists, idxs = matcher(desc1, desc2, lafs1, lafs2)`` takes two descriptor sets ``(B1, D)`` and ``(B2, D)`` and
+ their LAFs ``(1, B1, 2, 3)`` and ``(1, B2, 2, 3)``, and returns what :func:`match_fginn` or :func:`match_adalam`
+ returns for them, by ``match_mode``: ``(B3, 1)`` ratios or inverse confidences and ``(B3, 2)`` index pairs. It
+ passes no ``dm``, and no image sizes to AdaLAM; to give them, call the functions directly. For descriptors
+ without LAFs, use :class:`DescriptorMatcher` instead.
Convention:
See the Convention block on :func:`~kornia.feature.match_nn`. ``forward`` returns what the function of
@@ -1036,6 +1120,15 @@ class GeometryAwareDescriptorMatcher(nn.Module):
match_mode: type of matching, can be `fginn` or `adalam`.
params: dictionary of parameters for the matching function.
+ Raises:
+ NotImplementedError: for another ``match_mode``.
+
+ See Also:
+ - :func:`match_fginn`: the function of the default ``match_mode="fginn"``, whose own ``th`` defaults to 0.8.
+ - :func:`match_adalam`: the function of ``match_mode="adalam"``, which also takes the image sizes.
+ - :class:`DescriptorMatcher`: the module form of the matchers that read descriptors only.
+ - :class:`LightGlueMatcher`: a learned matcher with the same call, which also takes the image sizes.
+
"""
known_modes: ClassVar[List[str]] = ["fginn", "adalam"]
diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.py
index 2a357ecdd..76d257a1b 100644
--- a/kornia/feature/mkd.py
+++ b/kornia/feature/mkd.py
@@ -426,8 +426,8 @@ class Whitening(nn.Module):
l2-normalized, whitened descriptors.
Shape:
- - Input: :math:`(N, in_{dims})`.
- - Output: :math:`(N, output_{dims})`.
+ - Input: ``(N, in_dims)``.
+ - Output: ``(N, output_dims)``.
Examples:
>>> descs = torch.rand(23, 238)
@@ -552,10 +552,17 @@ class Whitening(nn.Module):
class MKDDescriptor(nn.Module):
- r"""nn.Module that computes Multiple Kernel local descriptors.
-
- This is based on the paper "Understanding and Improving Kernel Local Descriptors".
- See :cite:`mukundan2019understanding` for more details.
+ r"""Describe square grayscale patches with handcrafted Multiple Kernel Descriptors (MKD).
+
+ ``mkd = MKDDescriptor()``, then ``descs = mkd(patches)`` takes grayscale patches
+ ``(B, 1, patch_size, patch_size)``, 32 pixels square by default, and returns unit-norm descriptors ``(B, D)``,
+ ``(B, 128)`` with the defaults: the gradient magnitudes and orientations of each patch embedded in polar and
+ Cartesian spatial kernels (``kernel_type="concat"``), then whitened by ``whitening="pcawt"`` and reduced to
+ ``output_dims``. It has no CNN; only the whitening is learned, on ``training_set``, and the module is in eval mode
+ when built. To describe LAFs on an image, wrap it in :class:`LAFDescriptor` with the same ``patch_size``; for SIFT
+ histograms, use :class:`SIFTDescriptor`, and for a learned descriptor, :class:`HardNet`. 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
@@ -581,9 +588,14 @@ class MKDDescriptor(nn.Module):
Descriptors of the patches, of unit norm except as stated in the Convention block.
Shape:
- - Input: :math:`(B, 1, \text{patch\_size}, \text{patch\_size})`.
+ - Input: ``(B, 1, patch_size, patch_size)``.
- Output: ``(B, D)``, with :math:`D` as in the Convention block.
+ See Also:
+ - :class:`SIFTDescriptor`: the handcrafted SIFT histograms of gradient orientation of a patch.
+ - :class:`HardNet`: a learned descriptor of 32 x 32 patches.
+ - :class:`LAFDescriptor`: runs this module on a patch per LAF of an image.
+
Examples:
>>> patches = torch.rand(23, 1, 32, 32)
>>> mkd = MKDDescriptor(patch_size=32,
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
index 64b4801b6..58ddf6711 100644
--- a/kornia/feature/orientation.py
+++ b/kornia/feature/orientation.py
@@ -39,10 +39,19 @@ urls["orinet"] = [
class PassLAF(nn.Module):
- """Dummy module to use instead of local feature orientation or affine shape estimator.
+ """Return LAFs unchanged, in place of an orientation or affine shape estimator.
+
+ ``out = PassLAF()(laf, img)`` takes ``(B, N, 2, 3)`` LAFs and an image and returns its ``laf`` argument itself, not
+ a copy, without reading ``img``. It is the default ``ori_module`` and ``aff_module`` of
+ :class:`ScaleSpaceDetector`, :class:`MultiResolutionDetector` and :class:`KeyNetDetector`, and the ``ori_module``
+ that keeps features upright. To estimate the orientation, use :class:`LAFOrienter`; to estimate the affine shape,
+ :class:`LAFAffineShapeEstimator` or :class:`LAFAffNetShapeEstimator`.
+
+ See Also:
+ - :class:`LAFOrienter`: rotates each LAF by the orientation estimated on its image patch.
+ - :class:`LAFAffineShapeEstimator`: adapts each LAF's shape to the second-moment matrix of its patch.
+ - :class:`LAFAffNetShapeEstimator`: adapts each LAF's shape with the learned AffNet.
- Convention:
- Returns its ``laf`` argument itself, not a copy, and does not use ``img``.
"""
def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:
@@ -60,9 +69,14 @@ class PassLAF(nn.Module):
class PatchDominantGradientOrientation(nn.Module):
- r"""Module, which estimates the direction of the dominant gradient of the given patches, as an angle in radians.
+ r"""Estimate the orientation of patches from the peak of their histogram of gradient directions.
- Zero angle points towards right.
+ ``angles = PatchDominantGradientOrientation(patch_size)(patches)`` takes ``(B, 1, patch_size, patch_size)``
+ patches and returns the direction of each patch's dominant gradient, ``(B,)`` in radians, 0 for a gradient that
+ points to the right: the peak, refined between bins, of a ``num_angular_bins``-bin histogram of the gradient
+ directions, each pixel weighted by its gradient magnitude and a Gaussian centred on the patch, as in SIFT's
+ orientation assignment. It returns one angle per patch, that of the highest peak. To orient LAFs on an image, run
+ it through :class:`LAFOrienter`, whose default it is; for a learned estimate, use :class:`OriNet` instead.
Convention:
- The angle is that of the dominant gradient, which points toward brighter values, counter-clockwise on
@@ -71,6 +85,13 @@ class PatchDominantGradientOrientation(nn.Module):
LAF orientation.
- The angle is not wrapped into :math:`(-\pi, \pi]`: it can exceed :math:`\pi` by up to
``pi / num_angular_bins``.
+ - A patch whose Sobel gradients are all exactly zero, such as an all-zero patch, gets the angle
+ :math:`\pi` from its empty histogram. A nearly flat patch gets an arbitrary angle set by rounding noise: a
+ constant float64 patch can have nonzero rounding-level gradients, and so does a patch sampled from a flat
+ image region by :func:`~kornia.feature.extract_patches_from_pyramid`.
+ - Known defect: in float16 the gradients with respect to a textured patch and to the smoothing weights are
+ NaN, because the histogram is cast back to float16 before the peak is refined
+ (`#6455 <https://github.com/kornia/kornia/issues/6455>`_).
Args:
patch_size: size of the (square) input patch.
@@ -84,6 +105,12 @@ class PatchDominantGradientOrientation(nn.Module):
return the neighbouring peak. ``torch.use_deterministic_algorithms(True)`` selects the
deterministic kernel and restores run-to-run reproducibility.
+ See Also:
+ - :class:`OriNet`: a learned orientation of 32 x 32 patches.
+ - :class:`LAFOrienter`: samples each LAF's patch, runs this module on it by default and rotates the LAF.
+ - :class:`PatchAffineShapeEstimator`: the affine shape of a patch, from the second moments of the same Sobel
+ gradients.
+
"""
def __init__(self, patch_size: int = 32, num_angular_bins: int = 36, eps: float = 1e-8) -> None:
@@ -112,10 +139,10 @@ class PatchDominantGradientOrientation(nn.Module):
"""Run forward.
Args:
- patch: ``(B, 1, H, W)``
+ patch: ``(B, 1, patch_size, patch_size)``; another size raises ``TypeError``.
Returns:
- angle in radians: ``(B)``
+ angle in radians: ``(B,)``
"""
KORNIA_CHECK_SHAPE(patch, ["B", "1", "H", "W"])
@@ -198,11 +225,16 @@ class PatchDominantGradientOrientation(nn.Module):
class OriNet(nn.Module):
- """Network, which estimates the canonical orientation of the given 32x32 patches, in radians.
+ """Estimate the orientation of 32 x 32 patches with the learned OriNet CNN.
- Zero angle points towards right. This is based on the original code from paper
- "Repeatability Is Not Enough: Learning Discriminative Affine Regions via Discriminability"".
- See :cite:`AffNet2018` for more details.
+ ``angles = OriNet()(patches)`` builds the network with its pretrained weights, in eval mode, and takes
+ ``(B, 1, 32, 32)`` patches and returns a learned canonical orientation per patch, ``(B,)`` in radians, in the
+ sense of the angle of :class:`PatchDominantGradientOrientation`; its zero is learned, so on a patch it need not
+ match the dominant gradient direction. ``pretrained=False`` leaves the weights random. To orient LAFs, pass it to
+ :class:`LAFOrienter` as ``angle_detector``, as :class:`KeyNetHardNet` and :class:`KeyNetAffNetHardNet` do. For an
+ estimate that needs no weights, use :class:`PatchDominantGradientOrientation` instead. This is based on the
+ original code from the paper "Repeatability Is Not Enough: Learning Discriminative Affine Regions via
+ Discriminability". See :cite:`AffNet2018` for more details.
Convention:
- With the pretrained weights, the angle turns with the patch content, in the sense of
@@ -221,8 +253,13 @@ class OriNet(nn.Module):
Angle in radians.
Shape:
- - Input: (B, 1, 32, 32)
- - Output: (B)
+ - Input: ``(B, 1, 32, 32)``
+ - Output: ``(B,)``
+
+ See Also:
+ - :class:`PatchDominantGradientOrientation`: the hand-crafted dominant gradient direction, with no weights.
+ - :class:`LAFOrienter`: runs it on each LAF's patch, as ``angle_detector``, and rotates the LAF.
+ - :class:`LAFAffNetShapeEstimator`: AffNet, the affine shape network of the same paper.
Examples:
>>> input = torch.rand(16, 1, 32, 32)
@@ -266,7 +303,7 @@ class OriNet(nn.Module):
@staticmethod
def _normalize_input(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
- """Normalize the input by batch."""
+ """Subtract each patch's mean and divide by its standard deviation plus ``eps``."""
# `torch.std_mean` decomposes to `prims.sum`, which has no ONNX lowering; the split form is equivalent.
mp = torch.mean(x, dim=(-3, -2, -1), keepdim=True)
sp = torch.std(x, dim=(-3, -2, -1), keepdim=True)
@@ -279,10 +316,10 @@ class OriNet(nn.Module):
"""Run forward.
Args:
- patch: ``(B, 1, H, W)``
+ patch: ``(B, 1, 32, 32)``, the patch size the weights were trained on.
Returns:
- angle in radians: ``(B)``
+ angle in radians: ``(B,)``
"""
xy = self.features(_patch_conv_layout(self._normalize_input(patch))).view(-1, 2)
@@ -290,27 +327,40 @@ class OriNet(nn.Module):
class LAFOrienter(nn.Module):
- """Estimate the orientation of (B, N, 2, 3) LAFs from their image patches and rotate the LAFs by it.
+ """Orient LAFs by the angle that a patch orientation estimator finds in each LAF's patch.
- It extracts a patch per LAF, runs :class:`~kornia.feature.PatchDominantGradientOrientation` or
- :class:`~kornia.feature.OriNet` on it and rotates the LAF by the estimated angle.
+ ``lafs = LAFOrienter(patch_size)(laf, img)`` takes ``(B, N, 2, 3)`` LAFs in pixels and their grayscale images
+ ``(B, 1, H, W)``, samples each LAF's ``patch_size`` patch with :func:`extract_patches_from_pyramid`, runs
+ ``angle_detector`` on it, :class:`PatchDominantGradientOrientation` with ``num_angular_bins`` bins by default, and
+ returns the ``(B, N, 2, 3)`` LAFs rotated by the angles found. Passed to a detector as ``ori_module``, it runs after
+ the ``aff_module``. To keep the LAFs upright, pass :class:`PassLAF` instead; to rotate them by known angles, use
+ :func:`rotate_laf`.
Convention:
- Each LAF's patch (:func:`~kornia.feature.extract_patches_from_pyramid`) gives an angle, measured in the
patch, and the output orientation is the input orientation plus that angle, converted to degrees, modulo
360 degrees. :func:`~kornia.feature.get_laf_orientation` reads it back in ``[-180, 180]``. The centre, the
scale and the upright shape (:func:`~kornia.feature.make_upright`) of the LAF are kept.
- - For an isotropic LAF, the default angle detector therefore turns the LAF's x axis onto the dominant
+ - For an isotropic LAF with positive determinant, the default angle detector turns the LAF's x axis onto the
+ dominant
gradient, whatever the input orientation: content turned 30 degrees counter-clockwise on screen turns the
output orientation by +30, the sign of :func:`~kornia.feature.laf_from_center_scale_ori`
- (see :ref:`Local features <local-features-conventions>`).
+ (see :ref:`Local features <local-features-conventions>` for the orientation convention).
Args:
patch_size: side of the square patch sampled for each LAF.
num_angular_bins: number of histogram bins of the default angle detector; not used when ``angle_detector``
is given.
angle_detector: Patch orientation estimator, e.g. :class:`~kornia.feature.PatchDominantGradientOrientation`
- or OriNet.
+ or :class:`~kornia.feature.OriNet`.
+
+ See Also:
+ - :class:`PatchDominantGradientOrientation`: the default ``angle_detector``, the dominant gradient direction.
+ - :class:`OriNet`: a learned ``angle_detector`` for 32 x 32 patches.
+ - :class:`PassLAF`: keeps the input orientation, for upright features.
+ - :func:`rotate_laf`: rotates LAFs by known angles, as this module does with the estimated ones.
+ - :class:`LAFAffineShapeEstimator`: estimates the affine shape, which a detector runs before this module.
+ - :class:`LAFDescriptor`: describes the oriented LAFs, from patches that follow their orientation.
""" # pylint: disable
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
index a0ea39855..d0a8ac35a 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -43,12 +43,17 @@ def harris_response(
grads_mode: str = "sobel",
sigmas: Optional[torch.Tensor] = None,
) -> torch.Tensor:
- r"""Compute the Harris cornerness function.
+ r"""Compute the Harris corner response det(M) - k trace(M)^2 of the windowed structure tensor M.
+
+ ``R = harris_response(img, k)`` takes images ``(B, C, H, W)`` and returns the Harris response of every pixel of
+ every channel, ``(B, C, H, W)``, without non-maxima suppression: positive at a corner, negative along an edge and
+ zero on a constant image. ``k`` defaults to ``0.04``. To pass it to a detector as ``resp_module``, use its module
+ form :class:`CornerHarris`; for a corner response with no ``k`` to tune and no negative values up to roundoff,
+ use :func:`gftt_response`; for blobs, :func:`hessian_response`.
.. image:: _static/img/harris_response.png
- The function does no non-maxima suppression. The response map is computed according to the following
- formulation:
+ The response map is computed according to the following formulation:
.. math::
R = det(M) - k \cdot trace(M)^2
@@ -74,18 +79,30 @@ def harris_response(
multiplies the response by ``c ** 4``, and an offset does not change it, so a threshold tuned on images in
``[0, 1]`` does not carry over to ``[0, 255]``.
- ``k`` is not validated.
+ - Each channel is processed independently. ``H`` and ``W`` must be at least 4: a smaller image raises
+ ``RuntimeError`` from the reflect padding of the window.
Args:
input: input image with shape ``(B, C, H, W)``.
- k: the Harris detector free parameter.
+ k: the Harris detector free parameter, a number or a tensor that broadcasts against ``(B, C, H, W)``, such as
+ ``(B, 1, 1, 1)`` for one value per image.
grads_mode: can be ``'sobel'`` for standalone use or ``'diff'`` for use on Gaussian pyramid.
- sigmas: per-image scales with shape ``(B)``. The response of image ``b`` is multiplied by
+ sigmas: per-image scales with shape ``(B,)``. The response of image ``b`` is multiplied by
``sigmas[b] ** 4``, so that non-maxima suppression can compare the levels of a scale pyramid, as in
- `vlfeat <https://github.com/vlfeat/vlfeat/blob/master/vl/covdet.c>`_.
+ `vlfeat <https://github.com/vlfeat/vlfeat/blob/master/vl/covdet.c>`_. Another type raises ``TypeError``
+ and another shape ``ValueError``.
Return:
the response map per channel with shape ``(B, C, H, W)``.
+ See Also:
+ - :class:`CornerHarris`: the module form, with ``k`` and ``grads_mode`` fixed at construction.
+ - :func:`gftt_response`: the smaller eigenvalue of the same structure tensor, with no ``k`` and not negative
+ up to roundoff.
+ - :func:`hessian_response`: a blob response from second derivatives, positive at blobs of both polarities.
+ - :class:`ScaleSpaceDetector`: detects LAFs at the scale-space maxima of a response module such as
+ :class:`CornerHarris`.
+
Example:
>>> input = torch.tensor([[[
... [0., 0., 0., 0., 0., 0., 0.],
@@ -140,12 +157,17 @@ def harris_response(
def gftt_response(
input: torch.Tensor, grads_mode: str = "sobel", sigmas: Optional[torch.Tensor] = None
) -> torch.Tensor:
- r"""Compute the Shi-Tomasi cornerness function.
+ r"""Compute the Shi-Tomasi corner response, the smaller eigenvalue of the windowed structure tensor.
+
+ ``R = gftt_response(img)`` takes images ``(B, C, H, W)`` and returns the Shi-Tomasi ("good features to track")
+ response of every pixel of every channel, ``(B, C, H, W)``, without non-maxima suppression: large at a corner, near
+ zero along an edge and zero on a constant image. Unlike :func:`harris_response`, from the same structure tensor, it
+ has no ``k`` to tune. To pass it to a detector as ``resp_module``, use its module form :class:`CornerGFTT`; for
+ blobs, use :func:`hessian_response`.
.. image:: _static/img/gftt_response.png
- The function does no non-maxima suppression. The response map is computed according to the following
- formulation:
+ The response map is computed according to the following formulation:
.. math::
R = min(eig(M))
@@ -154,23 +176,33 @@ def gftt_response(
gradients and window.
Convention:
- - :math:`R` is not negative, up to roundoff. It is large at a corner and near zero along an edge, where the
- Harris response is negative.
+ - :math:`R` is not negative, up to roundoff. Along an edge, where it is near zero, the Harris response is
+ negative.
- Multiplying the image by ``c`` multiplies the response by ``c ** 2``, and an offset does not change it.
- ``sigmas`` multiplies the response by ``sigmas ** 4``, the same power used by
:func:`~kornia.feature.harris_response`. This is the function's scale-weighting convention, not a guarantee
of scale invariance. The integration window :math:`W` stays fixed as the image blur changes; the response's
decay with blur depends on the image structure, including the corner geometry.
+ - Each channel is processed independently. ``H`` and ``W`` must be at least 4: a smaller image raises
+ ``RuntimeError`` from the reflect padding of the window.
Args:
input: input image with shape ``(B, C, H, W)``.
grads_mode: can be ``'sobel'`` for standalone use or ``'diff'`` for use on Gaussian pyramid.
- sigmas: per-image scales with shape ``(B)``. The response of image ``b`` is multiplied by
- ``sigmas[b] ** 4``, so that non-maxima suppression can compare the levels of a scale pyramid.
+ sigmas: per-image scales with shape ``(B,)``. The response of image ``b`` is multiplied by
+ ``sigmas[b] ** 4``, so that non-maxima suppression can compare the levels of a scale pyramid. Another type
+ raises ``TypeError`` and another shape ``ValueError``.
Return:
the response map per channel with shape ``(B, C, H, W)``.
+ See Also:
+ - :class:`CornerGFTT`: the module form, with ``grads_mode`` fixed at construction.
+ - :func:`harris_response`: the signed Harris measure of the same structure tensor, with a free ``k``.
+ - :func:`hessian_response`: a blob response from second derivatives, without a window.
+ - :class:`GFTTAffNetHardNet`: a :class:`ScaleSpaceDetector` on this response, with AffNet shapes and HardNet
+ descriptors.
+
Example:
>>> input = torch.tensor([[[
... [0., 0., 0., 0., 0., 0., 0.],
@@ -227,12 +259,17 @@ def gftt_response(
def hessian_response(
input: torch.Tensor, grads_mode: str = "sobel", sigmas: Optional[torch.Tensor] = None
) -> torch.Tensor:
- r"""Compute the determinant of the Hessian matrix.
+ r"""Compute the blob response det(H) of the per-pixel Hessian, positive at bright and dark blobs alike.
+
+ ``R = hessian_response(img)`` takes images ``(B, C, H, W)`` and returns the determinant of the Hessian of every
+ pixel of every channel, ``(B, C, H, W)``, without non-maxima suppression. Its module form :class:`BlobHessian` is
+ the default ``resp_module`` of :class:`ScaleSpaceDetector`. For a Difference-of-Gaussian response, which tells a
+ bright blob (a minimum) from a dark one (a maximum), use :func:`dog_response`; for corners,
+ :func:`harris_response` or :func:`gftt_response`.
.. image:: _static/img/hessian_response.png
- The function does no non-maxima suppression. The response map is computed according to the following
- formulation:
+ The response map is computed according to the following formulation:
.. math::
R = det(H)
@@ -251,12 +288,14 @@ def hessian_response(
blobs alike, negative at a saddle. The second derivatives come from
:func:`~kornia.filters.spatial_gradient` with ``mode=grads_mode`` and ``order=2``.
- Multiplying the image by ``c`` multiplies the response by ``c ** 2``, and an offset does not change it.
+ - Each channel is processed independently.
Args:
input: input image with shape ``(B, C, H, W)``.
grads_mode: can be ``'sobel'`` for standalone use or ``'diff'`` for use on Gaussian pyramid.
- sigmas: per-image scales with shape ``(B)``. The response of image ``b`` is multiplied by
- ``sigmas[b] ** 4``, so that non-maxima suppression can compare the levels of a scale pyramid.
+ sigmas: per-image scales with shape ``(B,)``. The response of image ``b`` is multiplied by
+ ``sigmas[b] ** 4``, so that non-maxima suppression can compare the levels of a scale pyramid. Another type
+ raises ``TypeError`` and another shape ``ValueError``.
Return:
the response map per channel with shape ``(B, C, H, W)``.
@@ -265,6 +304,12 @@ def hessian_response(
- Input: ``(B, C, H, W)``
- Output: ``(B, C, H, W)``
+ See Also:
+ - :class:`BlobHessian`: the module form, with ``grads_mode`` fixed at construction.
+ - :func:`dog_response`: a signed blob response of a scale stack, a minimum at a bright blob.
+ - :func:`harris_response`: a corner response from first derivatives in a window.
+ - :class:`ScaleSpaceDetector`: detects LAFs at the scale-space maxima of this response, its default.
+
Examples:
>>> input = torch.tensor([[[
... [0., 0., 0., 0., 0., 0., 0.],
@@ -309,7 +354,13 @@ def hessian_response(
def dog_response(input: torch.Tensor) -> torch.Tensor:
- r"""Compute the Difference-of-Gaussian response between adjacent levels of a (B, C, D, H, W) Gaussian scale stack.
+ r"""Compute Difference-of-Gaussian responses between adjacent levels of a (B, C, D, H, W) scale stack.
+
+ ``R = dog_response(stack)`` takes a Gaussian scale stack ``(B, C, D, H, W)``, with its ``D`` levels along dim 2, and
+ returns the differences of adjacent levels, ``(B, C, D - 1, H, W)``. An octave of
+ :class:`~kornia.geometry.transform.ScalePyramid` is such a stack; to detect at the extrema, pass the module form
+ :class:`BlobDoG` to :class:`ScaleSpaceDetector` with ``scale_space_response=True`` and
+ ``minima_are_also_good=True``. For the DoG of one image at two given blurs, use :func:`dog_response_single`.
Convention:
- Output level ``i`` is ``input[:, :, i + 1] - input[:, :, i]`` along the level axis ``D`` (dim 2), so ``D``
@@ -317,10 +368,17 @@ def dog_response(input: torch.Tensor) -> torch.Tensor:
:math:`L(k\sigma) - L(\sigma)`: negative at a bright blob, positive at a dark one.
Args:
- input: a given the gaussian 5d torch.Tensor ``(B, C, D, H, W)``.
+ input: a Gaussian scale stack ``(B, C, D, H, W)``, its levels along ``D``.
Return:
- the response map per channel with shape ``(B, C, D-1, H, W)``.
+ the response map per channel with shape ``(B, C, D - 1, H, W)``.
+
+ See Also:
+ - :class:`BlobDoG`: the module form, to pass to :class:`ScaleSpaceDetector` as ``resp_module``.
+ - :func:`dog_response_single`: the DoG of a ``(B, C, H, W)`` image, blurred at two given sigmas.
+ - :func:`hessian_response`: a blob response of one image, positive at blobs of both polarities.
+ - :class:`~kornia.geometry.transform.ScalePyramid`: builds the scale stacks, one ``(B, C, L, H_o, W_o)`` per
+ octave.
"""
KORNIA_CHECK_SHAPE(input, ["B", "C", "L", "H", "W"])
@@ -331,6 +389,12 @@ def dog_response(input: torch.Tensor) -> torch.Tensor:
def dog_response_single(input: torch.Tensor, sigma1: float = 1.0, sigma2: float = 1.6) -> torch.Tensor:
r"""Compute the Difference-of-Gaussian response of a (B, C, H, W) image, its sigma2 blur minus its sigma1 blur.
+ ``R = dog_response_single(img, sigma1, sigma2)`` takes images ``(B, C, H, W)`` and returns, per channel, their
+ Gaussian blur of ``sigma2`` minus their blur of ``sigma1``, ``(B, C, H, W)``: for ``sigma2 > sigma1``, negative at
+ a bright blob and positive at a dark one. It blurs the image itself, so it needs no scale stack; for the
+ differences of adjacent levels of a precomputed stack, use :func:`dog_response`. Its module form is
+ :class:`BlobDoGSingle`.
+
.. image:: _static/img/dog_response_single.png
Convention:
@@ -338,15 +402,23 @@ def dog_response_single(input: torch.Tensor, sigma1: float = 1.0, sigma2: float
:func:`~kornia.feature.dog_response`; see its Convention block. Each kernel has the size
``int(8 * sigma + 1)``, rounded up to an odd number. The order of ``sigma1`` and ``sigma2`` is not checked:
swapping them flips the sign.
+ - ``H`` and ``W`` must be larger than half the larger kernel, at least 7 for the default ``sigma2=1.6``: a
+ smaller image raises ``RuntimeError`` from the reflect padding of the blur.
Args:
- input: a given the gaussian 4d torch.Tensor ``(B, C, H, W)``.
+ input: images ``(B, C, H, W)``.
sigma1: lower gaussian sigma
sigma2: bigger gaussian sigma
Return:
the response map per channel with shape ``(B, C, H, W)``.
+ See Also:
+ - :class:`BlobDoGSingle`: the module form, with ``sigma1`` and ``sigma2`` fixed at construction.
+ - :func:`dog_response`: the differences of adjacent levels of a ``(B, C, D, H, W)`` scale stack.
+ - :func:`hessian_response`: a blob response that is positive at blobs of both polarities.
+ - :class:`SIFTFeature`: detects at the maxima of this response's magnitude on each level of an image pyramid.
+
"""
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
ks1 = _get_kernel_size(sigma1)
@@ -359,9 +431,23 @@ def dog_response_single(input: torch.Tensor, sigma1: float = 1.0, sigma2: float
class BlobDoG(nn.Module):
r"""Compute Difference-of-Gaussian responses of a (B, C, D, H, W) scale stack; the module form of dog_response.
+ ``R = BlobDoG()(stack, sigmas)`` returns ``dog_response(stack)``, the ``(B, C, D - 1, H, W)`` differences of
+ adjacent levels, and ignores ``sigmas``. It is the ``resp_module`` that :class:`ScaleSpaceDetector` takes with
+ ``scale_space_response=True``; since a bright blob is a DoG minimum, pass ``minima_are_also_good=True`` too, as
+ :class:`DoGHardNet` and the ``"patch"`` backend of :class:`SIFTFeatureScaleSpace` do. For the DoG of one image at
+ two given blurs, use :class:`BlobDoGSingle` instead.
+
Convention:
Returns :func:`~kornia.feature.dog_response` of the ``(B, C, D, H, W)`` scale stack; see its Convention
- block. ``sigmas`` is ignored.
+ block.
+
+ See Also:
+ - :func:`dog_response`: the function form.
+ - :class:`BlobDoGSingle`: the DoG of a ``(B, C, H, W)`` image at two sigmas fixed at construction.
+ - :class:`BlobHessian`: a per-level blob response, positive at blobs of both polarities.
+ - :class:`ScaleSpaceDetector`: detects LAFs at the extrema of this response over its scale pyramid.
+ - :class:`SIFTFeatureScaleSpace`: a SIFT preset whose ``"patch"`` backend is that detector on this response.
+
"""
def __init__(self) -> None:
@@ -386,11 +472,22 @@ class BlobDoG(nn.Module):
class BlobDoGSingle(nn.Module):
r"""Compute the Difference-of-Gaussian response of a (B, C, H, W) image; the module form of dog_response_single.
+ ``R = BlobDoGSingle(sigma1, sigma2)(img, sigmas)`` returns ``dog_response_single(img, sigma1, sigma2)``, the
+ ``(B, C, H, W)`` blur of ``sigma2`` minus the blur of ``sigma1``, and ignores ``sigmas``. Passed to
+ :class:`MultiResolutionDetector`, which keeps maxima only, it misses the centres of bright blobs, the DoG minima:
+ :class:`SIFTFeature` passes its magnitude instead. For the DoG of a whole scale stack, use :class:`BlobDoG`.
+
.. image:: _static/img/dog_response_single.png
Convention:
Returns :func:`~kornia.feature.dog_response_single` with the constructor's ``sigma1`` and ``sigma2``; see its
- Convention block. ``sigmas`` is ignored.
+ Convention block.
+
+ See Also:
+ - :func:`dog_response_single`: the function form, with the sigmas passed on each call.
+ - :class:`BlobDoG`: the DoG between adjacent levels of a ``(B, C, D, H, W)`` scale stack.
+ - :class:`MultiResolutionDetector`: detects LAFs at the maxima of a per-image response on an image pyramid.
+
"""
def __init__(self, sigma1: float = 1.0, sigma2: float = 1.6) -> None:
@@ -416,13 +513,26 @@ class BlobDoGSingle(nn.Module):
class CornerHarris(nn.Module):
- r"""nn.Module that calculates Harris corners.
+ r"""Compute the Harris corner response with a fixed k; the module form of harris_response.
+
+ ``R = CornerHarris(k)(img, sigmas)`` returns ``harris_response(img, k, grads_mode, sigmas)``, the ``(B, C, H, W)``
+ Harris response of ``(B, C, H, W)`` images, positive at a corner. ``k`` is stored as a buffer, so it moves with
+ :meth:`torch.nn.Module.to`. Pass it to :class:`ScaleSpaceDetector` as ``resp_module`` to detect corners over
+ scale; for a response with no ``k`` to choose, use :class:`CornerGFTT` instead.
.. image:: _static/img/harris_response.png
Convention:
Returns :func:`~kornia.feature.harris_response` with the constructor's ``k`` and ``grads_mode``; see its
- Convention block. Unlike the function's, this ``k`` has no default.
+ Convention block. Unlike the function's, this ``k`` has no default. A ``float``, ``int`` or NumPy scalar
+ ``k`` becomes a 0-dimensional tensor; a tensor is stored as it is.
+
+ See Also:
+ - :func:`harris_response`: the function form, with ``k`` defaulting to ``0.04``.
+ - :class:`CornerGFTT`: the Shi-Tomasi corner response of the same structure tensor, without ``k``.
+ - :class:`BlobHessian`: the Hessian-determinant blob response.
+ - :class:`ScaleSpaceDetector`: detects LAFs at the scale-space maxima of a response module such as this one.
+
"""
k: torch.Tensor
@@ -456,12 +566,25 @@ class CornerHarris(nn.Module):
class CornerGFTT(nn.Module):
- r"""nn.Module that calculates Shi-Tomasi corners.
+ r"""Compute the Shi-Tomasi corner response; the module form of gftt_response.
+
+ ``R = CornerGFTT()(img, sigmas)`` returns ``gftt_response(img, grads_mode, sigmas)``, the ``(B, C, H, W)``
+ smaller structure-tensor eigenvalue of ``(B, C, H, W)`` images, large at a corner. Pass it to
+ :class:`ScaleSpaceDetector` as ``resp_module`` to detect corners over scale, as :class:`GFTTAffNetHardNet` does;
+ for the signed Harris measure, use :class:`CornerHarris` instead.
.. image:: _static/img/gftt_response.png
Convention:
Returns :func:`~kornia.feature.gftt_response` with the constructor's ``grads_mode``; see its Convention block.
+
+ See Also:
+ - :func:`gftt_response`: the function form.
+ - :class:`CornerHarris`: the Harris corner response of the same structure tensor, with a free ``k``.
+ - :class:`BlobHessian`: the Hessian-determinant blob response.
+ - :class:`GFTTAffNetHardNet`: a :class:`ScaleSpaceDetector` on this response, with AffNet shapes and HardNet
+ descriptors.
+
"""
def __init__(self, grads_mode: str = "sobel") -> None:
@@ -486,13 +609,26 @@ class CornerGFTT(nn.Module):
class BlobHessian(nn.Module):
- r"""nn.Module that calculates Hessian blobs.
+ r"""Compute the Hessian-determinant blob response; the module form of hessian_response.
+
+ ``R = BlobHessian()(img, sigmas)`` returns ``hessian_response(img, grads_mode, sigmas)``, the ``(B, C, H, W)``
+ Hessian determinant of ``(B, C, H, W)`` images, positive at bright and dark blobs alike. It is the default
+ ``resp_module`` of :class:`ScaleSpaceDetector`, which passes each level's sigma so that the levels compare. For a
+ DoG response over a scale stack, use :class:`BlobDoG`; for corners, :class:`CornerGFTT` or :class:`CornerHarris`.
.. image:: _static/img/hessian_response.png
Convention:
Returns :func:`~kornia.feature.hessian_response` with the constructor's ``grads_mode``; see its Convention
block.
+
+ See Also:
+ - :func:`hessian_response`: the function form.
+ - :class:`BlobDoG`: the DoG blob response of a scale stack, a minimum at a bright blob.
+ - :class:`CornerGFTT`: a corner response, the smaller structure-tensor eigenvalue.
+ - :class:`ScaleSpaceDetector`: detects LAFs at the scale-space maxima of this response, its default.
+ - :class:`HesAffNetHardNet`: that detector on this response, with AffNet shapes and HardNet descriptors.
+
"""
def __init__(self, grads_mode: str = "sobel") -> None:
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 5873cf332..795760d18 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -164,7 +164,7 @@ def _check_mask(mask: torch.Tensor, img: torch.Tensor) -> None:
def _zero_unfilled(lafs: torch.Tensor, filled: torch.Tensor) -> torch.Tensor:
- r"""Replace the LAFs of the slots no detection filled with the zero LAF.
+ r"""Replace unused detection slots with zero LAFs.
``filled`` is a ``(B, N)`` boolean mask of the slots a detection actually filled. The
affine-shape and orientation modules may normalise or propagate invalid padding frames
@@ -201,14 +201,20 @@ def _subpix_dispatch(module: nn.Module) -> Tuple[bool, bool]:
class ScaleSpaceDetector(nn.Module):
- r"""nn.Module for differentiable local feature detection.
+ r"""Detect LAFs at the sub-pixel scale-space maxima of a pluggable response, for a batch of images.
- It has 5 modules inside: scale pyramid generator, response ("cornerness") function,
- sub-pixel localization, affine shape estimator and patch orientation estimator.
- Each of those modules could be replaced with a learned custom one, as long as
- they respect output shape.
+ ``detector = ScaleSpaceDetector(num_features)`` builds a detector with a Hessian response by default.
+ ``lafs, responses = detector(img)`` takes grayscale images ``(B, 1, H, W)`` and returns LAFs
+ ``(B, num_features, 2, 3)`` in input pixels and responses ``(B, num_features)``, strongest first.
+ Use :func:`laf_is_filled` to keep detected features and discard padded slots in both outputs.
+ For per-level 2D maxima, use :class:`MultiResolutionDetector`; for SIFT detection and description,
+ use :class:`SIFTFeatureScaleSpace`.
Convention:
+ - The modules run in this order: ``scale_pyr_module``, ``resp_module``, ``subpix_module``, ``aff_module``,
+ then ``ori_module``. The last two default to :class:`PassLAF`, which leaves frames unchanged.
+ ``detector.detect(img, num_feats)`` returns ``(responses, lafs)`` before shape and orientation estimation;
+ note the reversed output order compared with ``detector(img)``.
- The candidates are the strict :math:`3 \times 3 \times 3` maxima of the response over level, row and column
(:func:`~kornia.geometry.subpix.nms3d_minmax`) on the levels given under ``scale_pyr_module``, whatever their
sign. With ``minima_are_also_good`` a strict minimum is a candidate too when its negated response after
@@ -217,11 +223,12 @@ class ScaleSpaceDetector(nn.Module):
refinement extrapolates it below minus its sampled value. There is no response threshold. The
``num_features`` strongest candidates of all octaves are kept; a minimum is ranked and returned with its
refined response negated.
- - The default Hessian response is a maximum at bright and dark blobs alike. A DoG response
+ - The default Hessian response is a maximum at bright and dark blobs alike. It keeps the channels, so a
+ multi-channel image needs a ``resp_module`` that returns one map. A DoG response
(:class:`~kornia.feature.BlobDoG`) is a maximum at a dark blob and a minimum at a bright one, which only
``minima_are_also_good=True`` detects.
- A LAF centre is the refined sub-pixel position, mapped to input pixels as given under
- ``scale_pyr_module``, in the frame of :func:`~kornia.feature.laf_from_center_scale_ori`
+ ``scale_pyr_module``, using the pixel convention of :func:`~kornia.feature.laf_from_center_scale_ori`
(see :ref:`Local features <local-features-conventions>`). Before ``aff_module`` and ``ori_module`` run, the
frame is diagonal: ``mr_size`` times the detection scale, mapped to input pixels along each axis like the
centre.
@@ -232,6 +239,7 @@ class ScaleSpaceDetector(nn.Module):
- The LAFs are float32 for a float16 or bfloat16 image and float64 for a float64 one; the responses keep the
response function's dtype. Non-maximum suppression and sub-pixel refinement run on the response promoted to
at least float32.
+ - With the default modules the responses, centres and scales carry gradients to the image.
- A batch of zero images returns empty outputs of the documented shapes, after the checks a non-empty batch
runs.
- Known defects: an octave passes only its ``num_features`` strongest candidates to the border test and to the
@@ -243,11 +251,11 @@ class ScaleSpaceDetector(nn.Module):
output would always have num_features output, even for completely homogeneous images.
mr_size: multiplier from the detection scale to the LAF scale. The default 6.0 gives a frame of about six
times the :math:`\sigma` of a detected Gaussian blob.
- scale_pyr_module: generates scale pyramid. See :class:`~kornia.geometry.ScalePyramid` for details.
+ scale_pyr_module: generates scale pyramid. See :class:`~kornia.geometry.transform.ScalePyramid` for details.
Default: ``ScalePyramid(3, 1.6, 16, extra_levels=3)`` with a scale-space response,
``extra_levels=2`` without. A detection at octave pixel :math:`(u, v)` is reported at
:math:`(u (W - 1) / (W_o - 1), v (H - 1) / (H_o - 1))` in the input, the map of
- :class:`~kornia.geometry.ScalePyramid`'s ``align_corners=True`` resizes; a custom pyramid has to
+ :class:`~kornia.geometry.transform.ScalePyramid`'s ``align_corners=True`` resizes; a custom pyramid has to
resize the same way. Each octave searches ``n_levels`` response levels, levels
``1..n_levels``; the levels below and above them are NMS neighbours only, and any further
level is ignored. A per-level response therefore needs ``extra_levels >= 2``, and DoG,
@@ -262,20 +270,30 @@ class ScaleSpaceDetector(nn.Module):
which does nothing. See :class:`~kornia.feature.LAFAffineShapeEstimator` for details.
minima_are_also_good: if True, then both response function minima and maxima are detected.
A DoG response needs it to detect bright blobs. Default is False.
- With a built-in ``subpix_module`` both signs are refined in one stacked call, which
- roughly doubles the peak memory of the refinement step: the response volume and its
- three coordinate maps are materialised for ``2B`` images at once.
+ Refining both signs can use roughly twice the peak memory of refining maxima alone.
scale_space_response: if True, ``resp_module`` gets each whole octave ``(B, C, L, H, W)`` with its
- sigmas :math:`(B \cdot L)` and returns a :math:`(B, 1, L', H, W)` scale-space response, as
+ sigmas ``(B * L,)`` and returns a ``(B, 1, L', H, W)`` scale-space response, as
:class:`~kornia.feature.BlobDoG` does. If False (the default), it gets the octave's levels
- ``0 .. n_levels + 1`` as :math:`(B \cdot L, C, H, W)` images, :math:`L = n_{levels} + 2`, with their sigmas
- and returns :math:`(B \cdot L, 1, H, W)`.
+ ``0 .. n_levels + 1`` as ``(B * L, C, H, W)`` images, ``L = n_levels + 2``, with their sigmas
+ and returns ``(B * L, 1, H, W)``.
compile_modules: selects which sub-modules to wrap with :func:`torch.compile`.
Pass ``True`` to compile every sub-module, ``False`` (default) for none, or a list
containing any subset of ``["scale_pyr", "resp", "subpix", "ori", "aff"]``.
- Compiling ``subpix`` fuses the iteration loop of :func:`~kornia.geometry.subpix.conv_quad_interp3d`, which
- the default :class:`~kornia.geometry.subpix.AdaptiveQuadInterp3d` runs on CUDA.
- The first call incurs a one-time compilation cost; subsequent calls are fast.
+ The first call compiles, and a new input shape, such as another batch size, can compile again.
+
+ See Also:
+ - :class:`MultiResolutionDetector`: one image per call, the 2D maxima of a response on each level of an image
+ pyramid, at integer level pixels and without scale selection.
+ - :class:`KeyNetDetector`: that detector on the learned KeyNet response.
+ - :class:`SIFTFeatureScaleSpace`: SIFT, whose ``"patch"`` backend is this detector on a DoG response.
+ - :class:`DoGHardNet`: this detector on a DoG response, with HardNet descriptors.
+ - :class:`~kornia.geometry.subpix.ConvSoftArgmax3d`: a ``subpix_module`` that takes the soft-argmax of a
+ window instead of a quadratic fit.
+
+ Example:
+ >>> lafs, responses = ScaleSpaceDetector(num_features=100)(torch.rand(2, 1, 64, 64))
+ >>> lafs.shape, responses.shape
+ (torch.Size([2, 100, 2, 3]), torch.Size([2, 100]))
"""
@@ -685,23 +703,24 @@ class ScaleSpaceDetector(nn.Module):
"""Detect local features in an image batch.
Args:
- img: Input image tensor with shape `(B, C, H, W)`.
+ img: Input image tensor with shape ``(B, C, H, W)``.
num_feats: Number of features requested from the detector.
- mask: Optional mask with shape `(1 or B, 1, H, W)` saying where a detection may be. A boolean or integer
+ mask: Optional mask with shape ``(1 or B, 1, H, W)`` saying where a detection may be. A boolean or integer
mask is binary (any non-zero value keeps a position), a floating-point mask is used as weights on the
- detection scores: a weight in `(0, 1]` scales a score toward the worst (a non-negative score is
+ detection scores: a weight in ``(0, 1]`` scales a score toward the worst (a non-negative score is
multiplied by it, a negative one divided), so a down-weighted candidate never outranks a full-weight
one, and a zero or negative weight suppresses. Weights above one are clamped to one, so a float
- 0/255 mask means what the integer one means. The weights are cast to the image dtype. The mask is
+ 0/255 mask means what the integer one means. The weights are cast to the response's dtype. The mask is
resampled onto every octave conservatively, so a zero region suppresses every candidate within one
octave pixel of it.
Returns:
- Tuple containing detection scores and local affine frames, shaped `(B, num_feats)` and `(B, num_feats,
- 2, 3)`. A slot that no detection filled -- there were fewer candidates than requested, or the border or
- mask test rejected a candidate -- carries a zero response and a zero LAF, and sorts after every real
- detection. The converse does not hold: a signed response function can peak at exactly zero, and that
- slot keeps its frame. A batch of zero images returns empty outputs of these shapes.
+ Tuple containing detection scores and local affine frames, shaped ``(B, num_feats)`` and
+ ``(B, num_feats, 2, 3)``, in that order, the reverse of ``forward``'s. A slot that no detection filled --
+ there were fewer candidates than requested, or the border or mask test rejected a candidate -- carries a
+ zero response and a zero LAF, and sorts after every real detection. The converse does not hold: a signed
+ response function can peak at exactly zero, and that slot keeps its frame. A batch of zero images returns
+ empty outputs of these shapes.
"""
responses, lafs, _ = self._detect(img, num_feats, mask)
return responses, lafs
@@ -713,15 +732,15 @@ class ScaleSpaceDetector(nn.Module):
Then affine shape and orientation.
Args:
- img: image to extract features with shape [BxCxHxW]
- mask: a mask saying where a detection may be, shape [1x1xHxW] or [Bx1xHxW]. A boolean or integer mask
- is binary, a floating-point mask weights the detection scores; see :meth:`detect`.
+ img: image to extract features with shape ``(B, C, H, W)``.
+ mask: a mask saying where a detection may be, shape ``(1, 1, H, W)`` or ``(B, 1, H, W)``. A boolean or
+ integer mask is binary, a floating-point mask weights the detection scores; see :meth:`detect`.
Returns:
- Tuple of ``lafs`` with shape [BxNx2x3], the detected local affine frames, and ``responses`` with shape
- [BxN], the response function values for the corresponding lafs. When an image yields fewer maxima than
- ``num_features``, the remaining slots hold a zero response and a zero LAF, whichever affine-shape and
- orientation modules are configured.
+ Tuple of ``lafs`` with shape ``(B, N, 2, 3)``, the detected local affine frames, and ``responses`` with
+ shape ``(B, N)``, the response function values for the corresponding lafs, with ``N = num_features``.
+ When fewer detections than ``num_features`` survive for an image, the remaining slots hold a zero
+ response and a zero LAF, whichever affine-shape and orientation modules are configured.
"""
# `detect` is the public extension point used by subclasses. Infer occupancy from its
@@ -736,11 +755,14 @@ class ScaleSpaceDetector(nn.Module):
class Detector_config(TypedDict):
- """Configuration for the Scale Space Detector.
+ """Configuration for the multi-resolution detector, the ``config`` of :class:`MultiResolutionDetector`.
Attributes:
- nms_size: The size of the Non-Maximum Suppression window.
- pyramid_levels: The number of levels in the image pyramid.
+ nms_size: The size of the Non-Maximum Suppression window, in level pixels.
+ pyramid_levels: The number of image-pyramid levels below the input.
+ up_levels: The number of image-pyramid levels above the input, upscaled.
+ scale_factor_levels: The scale factor between adjacent levels.
+ s_mult: The LAF scale, in level pixels.
"""
nms_size: int
@@ -757,11 +779,18 @@ def get_default_detector_config() -> Detector_config:
class MultiResolutionDetector(nn.Module):
- """Multi-scale feature detector, based on KeyNet, for a response function that returns one map of its input's size.
+ """Detect LAFs at the 2D maxima of a response on each level of an image pyramid, one image per call.
- This is based on the original code from paper
- "Key.Net: Keypoint Detection by Handcrafted and Learned CNN Filters".
- See :cite:`KeyNet2019` for more details.
+ ``detector = MultiResolutionDetector(model, num_features)`` builds an image pyramid detector from a response
+ model. ``lafs, responses = detector(img)`` takes one image ``(1, C, H, W)`` and returns LAFs
+ ``(1, num_features, 2, 3)`` in input pixels and responses ``(1, num_features)``, strongest first.
+ Use :func:`laf_is_filled` to keep detected features and discard padded slots in both outputs.
+ Detections lie at integer pixels of each pyramid level, without scale selection or subpixel refinement.
+ For a batch or refined centres and scales, use :class:`ScaleSpaceDetector`; for KeyNet responses,
+ use :class:`KeyNetDetector`.
+
+ This is based on the original code from the paper "Key.Net: Keypoint Detection by Handcrafted and Learned CNN
+ Filters". See :cite:`KeyNet2019` for more details.
The Key.Net reference code zeroes a 15 px strip along each side of a level before the non-maxima
suppression, which reports a "maximum" beside the strip wherever the response rises into it. This
@@ -769,14 +798,22 @@ class MultiResolutionDetector(nn.Module):
see :meth:`detect_features_on_single_level`.
Convention:
+ - ``model`` maps each pyramid level ``(1, C, H_l, W_l)`` to a response ``(1, 1, H_l, W_l)``.
+ Only responses carry gradients; the selected centres and scales do not.
+ ``aff_module`` and then ``ori_module`` modify the upright frames; both default to :class:`PassLAF`.
+ ``detector.detect(img)`` returns ``(responses, lafs)`` before those two modules run, reversing the output
+ order of ``detector(img)``.
- Detections are maxima of the response above ``score_threshold``. For a signed response whose minima are
features as well, such as a difference of Gaussians, pass its magnitude, as
:class:`~kornia.feature.SIFTFeature` does.
- A detection is an integer pixel :math:`(u, v)` of a pyramid level of size ``(H_l, W_l)``, without a
sub-pixel step. It is reported at :math:`(u W / W_l, v H / H_l)` of the ``(H, W)`` input, in the frame
- of :func:`~kornia.feature.laf_from_center_scale_ori` (see :ref:`Local features <local-features-conventions>`),
- and not at the level pixel's centre :math:`((u + 0.5) W / W_l - 0.5, (v + 0.5) H / H_l - 0.5)`; the Key.Net
- reference maps it the same way.
+ of :func:`~kornia.feature.laf_from_center_scale_ori` (see :ref:`Local features <local-features-conventions>`).
+ That is the centre of the level pixel only on a level of the input's size; otherwise that centre is at
+ :math:`((u + 0.5) W / W_l - 0.5, (v + 0.5) H / H_l - 0.5)`. The Key.Net reference maps it the same way.
+ The reported point minus that centre, :math:`-0.5 (f - 1)` px along x for :math:`f = W / W_l` and likewise
+ along y, is a known defect (`#6536 <https://github.com/kornia/kornia/issues/6536>`_): about +0.15 px on the
+ default up level, and increasingly below centre at lower levels.
- Before ``aff_module`` and ``ori_module`` run, the frame is upright and isotropic, with the scale
``s_mult * (W / W_l + H / H_l) / 2`` whatever the response; ``s_mult`` of ``config`` is 22 by default.
@@ -788,7 +825,11 @@ class MultiResolutionDetector(nn.Module):
of the vector for any larger one. Which detection carries a given response is not pinned
when responses tie: ``topk`` breaks a tie by position, and the positions it ranks over
depend on ``num_features``.
- config: Dict with initialization parameters. Do not pass it, unless you know what you are doing.
+ config: Dict with initialization parameters. Do not pass it, unless you know what you are doing. The
+ pyramid has ``up_levels`` levels (1 by default) upscaled by successive powers of ``scale_factor_levels``
+ (``sqrt(2)``), the input, and ``pyramid_levels`` levels (4) below it, each the previous one downscaled by
+ ``scale_factor_levels`` with :func:`~kornia.geometry.transform.pyrdown`; ``nms_size`` (15) is the side of
+ the suppression window in level pixels, and ``s_mult`` (22) the frame scale, in level pixels.
ori_module: for local feature orientation estimation. Default: :class:`~kornia.feature.PassLAF`,
which does nothing. See :class:`~kornia.feature.LAFOrienter` for details.
aff_module: for local feature affine shape estimation. Default: :class:`~kornia.feature.PassLAF`,
@@ -796,7 +837,19 @@ class MultiResolutionDetector(nn.Module):
compile_model: wrap the response function and the non-maxima suppression with :func:`torch.compile`.
score_threshold: minimum response for a position to count as a detection. Must be non-negative:
non-maxima suppression writes an exact zero at every suppressed position, so a negative
- threshold would admit all of them.
+ threshold would admit all of them; it raises ``ValueError``.
+
+ See Also:
+ - :class:`ScaleSpaceDetector`: a batch of images, the sub-pixel maxima of a response over a Gaussian scale
+ space, with scale selection across levels.
+ - :class:`KeyNetDetector`: this detector on the learned KeyNet response.
+ - :class:`SIFTFeature`: this detector on the magnitude of a DoG response, with SIFT descriptors.
+
+ Example:
+ >>> detector = MultiResolutionDetector(BlobHessian(), num_features=50)
+ >>> lafs, responses = detector(torch.rand(1, 1, 64, 64))
+ >>> lafs.shape, responses.shape
+ (torch.Size([1, 50, 2, 3]), torch.Size([1, 50]))
"""
@@ -889,8 +942,8 @@ class MultiResolutionDetector(nn.Module):
Returns:
Tuple containing scores and local affine frames detected at the requested pyramid level, with
- ``min(num_kp, H * W)`` slots. When the level holds fewer above-threshold maxima than that, the remaining
- slots are padded with a zero response and a zero LAF.
+ ``min(num_kp, H_l * W_l)`` slots for a level of size ``(H_l, W_l)``. When the level holds fewer
+ above-threshold maxima than that, the remaining slots are padded with a zero response and a zero LAF.
"""
resp_map = self.model(level_img)
KORNIA_CHECK(
@@ -962,25 +1015,25 @@ class MultiResolutionDetector(nn.Module):
return self.detect_features_on_single_level(level_img, num_kp, factor, mask=mask)
def detect(self, img: torch.Tensor, mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
- """Detect local features in an image batch.
+ """Detect local features in one image, a batch of one.
Args:
- img: Input image tensor with shape `(1, C, H, W)`.
- mask: Optional mask with shape `(1, 1, H, W)` saying where a detection may be. A boolean or integer
+ img: Input image tensor with shape ``(1, C, H, W)``.
+ mask: Optional mask with shape ``(1, 1, H, W)`` saying where a detection may be. A boolean or integer
mask is binary (any non-zero value keeps a position), a floating-point mask is used as weights on
- the detection scores: a weight in `(0, 1]` scales a score toward the worst, so a down-weighted
+ the detection scores: a weight in ``(0, 1]`` scales a score toward the worst, so a down-weighted
maximum never outranks a full-weight one, and a zero or negative weight suppresses. Weights above
one are clamped to one, so a float 0/255 mask means what the integer one means. The weights are
- cast to the image dtype. The mask is resampled onto every pyramid level conservatively, so a zero
- region suppresses every maximum within one level pixel of it.
+ cast to the response's dtype. The mask is resampled onto every pyramid level conservatively, so a
+ zero region suppresses every maximum within one level pixel of it.
Returns:
- Tuple containing detection scores and local affine frames, shaped `(1, num_features)` and
- `(1, num_features, 2, 3)`, holding the `num_features` highest responses in the image and sorted by
- response, descending. The shape holds even when the image yields fewer above-threshold maxima
- than requested: those slots carry a zero response and a zero LAF, and sort after every real detection.
- The LAFs are float32 for a float16 or bfloat16 image and float64 for a float64 one; the responses keep
- the response function's dtype.
+ Tuple containing detection scores and local affine frames, shaped ``(1, num_features)`` and
+ ``(1, num_features, 2, 3)``, in that order, the reverse of ``forward``'s, holding the ``num_features``
+ highest responses in the image and sorted by response, descending. The shape holds even when the image
+ yields fewer above-threshold maxima than requested: those slots carry a zero response and a zero LAF,
+ and sort after every real detection. The LAFs are float32 for a float16 or bfloat16 image and float64
+ for a float64 one; the responses keep the response function's dtype.
"""
KORNIA_CHECK_SHAPE(img, ["1", "C", "H", "W"])
if mask is not None:
@@ -1052,15 +1105,16 @@ class MultiResolutionDetector(nn.Module):
Then affine shape and orientation.
Args:
- img: image to extract features with shape [1xCxHxW]. Only a batch of one image is accepted.
- mask: a mask saying where a detection may be, shape [1x1xHxW]. A boolean or integer mask is binary, a
- floating-point mask weights the detection scores; see :meth:`detect`.
+ img: image to extract features with shape ``(1, C, H, W)``. Only a batch of one image is accepted.
+ mask: a mask saying where a detection may be, shape ``(1, 1, H, W)``. A boolean or integer mask is
+ binary, a floating-point mask weights the detection scores; see
+ :meth:`~kornia.feature.MultiResolutionDetector.detect`.
Returns:
- Tuple of ``lafs`` with shape [1xNx2x3], the detected local affine frames, and ``responses`` with shape
- [1xN], the response function values for the corresponding lafs. When the image yields fewer
- above-threshold maxima than ``num_features``, the remaining slots hold a zero response and a zero LAF,
- whichever affine-shape and orientation modules are configured.
+ Tuple of ``lafs`` with shape ``(1, N, 2, 3)``, the detected local affine frames, and ``responses`` with
+ shape ``(1, N)``, the response function values for the corresponding lafs, with ``N = num_features``.
+ When the image yields fewer above-threshold maxima than ``num_features``, the remaining slots hold a zero
+ response and a zero LAF, whichever affine-shape and orientation modules are configured.
"""
KORNIA_CHECK_SHAPE(img, ["1", "C", "H", "W"])
diff --git a/kornia/feature/sift/pyramid.py b/kornia/feature/sift/pyramid.py
index 21a8000ac..057b407a3 100644
--- a/kornia/feature/sift/pyramid.py
+++ b/kornia/feature/sift/pyramid.py
@@ -45,13 +45,19 @@ from kornia.geometry.transform import pyrdown
class SIFTDescriptorFromPyramid(nn.Module):
- """Extract sparse SIFT descriptors from a shared image-gradient pyramid.
-
- This module does not detect keypoints or return a dense descriptor map.
- ``forward(image, lafs)`` describes the supplied, already oriented LAFs.
- :meth:`orient_and_describe` additionally assigns their orientation while
- sharing one pyramid between orientation assignment and description. The
- pyramid belongs to this descriptor; it is not reused from the detector.
+ """Describe given LAFs with SIFT from a shared gradient pyramid, without sampling patches.
+
+ ``sift = SIFTDescriptorFromPyramid()``, then ``descs = sift(image, lafs)`` takes grayscale images
+ ``(B, 1, H, W)`` and their already oriented LAFs ``(B, N, 2, 3)`` in pixels and returns one descriptor per LAF,
+ ``(B, N, num_ang_bins * num_spatial_bins ** 2)``: ``(B, N, 128)`` by default, in the image dtype, RootSIFT by
+ default, in kornia's angle-major layout. ``lafs, descs = sift.orient_and_describe(image, lafs)`` also gives each
+ LAF the orientation of its dominant gradient first, sharing one pyramid between the two steps. Each LAF reads
+ histograms pooled at one octave of a pyramid that this module builds from ``image``, not reused from a detector:
+ it describes the square ``c + A [-1, 1]^2`` that :class:`SIFTDescriptor` sees in the patch of
+ :func:`extract_patches_from_pyramid`, without sampling that patch, so its values approximate those of
+ :class:`SIFTDescriptor` without equalling them. For the patch descriptors themselves, use
+ ``LAFDescriptor(SIFTDescriptor(41), patch_size=41)`` (:class:`LAFDescriptor`) instead. :class:`SIFTFeature`'s
+ ``"patch"`` backend uses that descriptor, and its ``"pyramid"`` backend uses this module.
The performance and accuracy acceptance criteria of its automatic
orientation are tracked in
@@ -78,7 +84,7 @@ class SIFTDescriptorFromPyramid(nn.Module):
image pyramid before the affine footprint is sampled.
Convention:
- - ``lafs`` are in the pixel frame of ``image``, with the layout of
+ - ``lafs`` use the pixel convention 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
@@ -111,7 +117,25 @@ class SIFTDescriptorFromPyramid(nn.Module):
Shape:
- image: ``(B, 1, H, W)``
- lafs: ``(B, N, 2, 3)`` in image pixel coordinates
- - descriptors: :math:`(B, N, num_ang_bins * num_spatial_bins^2)`
+ - descriptors: ``(B, N, num_ang_bins * num_spatial_bins ** 2)``
+
+ See Also:
+ - :class:`SIFTDescriptor`: SIFT descriptors of given patches, such as those sampled from LAFs.
+ - :class:`LAFDescriptor`: the patch alternative for the same image and LAFs, with the exact values of a
+ :class:`SIFTDescriptor` on a patch sampled per LAF, as in the ``"patch"`` backend of :class:`SIFTFeature`.
+ - :class:`DenseSIFTDescriptor`: a SIFT descriptor at every position of an image, at one scale.
+ - :func:`convert_sift_descriptor_layout`: reorders the descriptors into OpenCV's layout.
+ - :class:`LAFOrienter`: orients LAFs from their patches, before a patch descriptor.
+ - :class:`SIFTFeature`: detects DoG keypoints and, with ``descriptor_backend="pyramid"``, orients and
+ describes them with :meth:`orient_and_describe`.
+
+ Example:
+ >>> image = torch.rand(1, 1, 64, 64)
+ >>> xy, scale = torch.tensor([[[32.0, 32.0]]]), torch.full((1, 1, 1, 1), 8.0)
+ >>> lafs = kornia.feature.laf_from_center_scale_ori(xy, scale)
+ >>> SIFTDescriptorFromPyramid()(image, lafs).shape
+ torch.Size([1, 1, 128])
+
"""
def __init__(
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index b7b44296b..b8ddc19f7 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -108,7 +108,7 @@ def get_sift_pooling_kernel(ksize: int = 25) -> torch.Tensor:
ksize: kernel_size.
Returns:
- the pooling kernel with shape :math:`(ksize, ksize)`.
+ the pooling kernel with shape ``(ksize, ksize)``.
"""
ks_2: float = float(ksize) / 2.0
@@ -154,7 +154,15 @@ def get_sift_bin_ksize_stride_pad(patch_size: int, num_spatial_bins: int) -> Tup
class SIFTDescriptor(nn.Module):
- r"""nn.Module which computes SIFT descriptors of given patches.
+ r"""Describe square grayscale patches with SIFT histograms of gradient orientation.
+
+ ``sift = SIFTDescriptor(patch_size)``, then ``descs = sift(patches)`` takes grayscale patches
+ ``(B, 1, patch_size, patch_size)``, 41 pixels square by default, and returns one descriptor per patch,
+ ``(B, num_ang_bins * num_spatial_bins ** 2)``: ``(B, 128)`` with the default 8 angle bins and 4 x 4 spatial
+ cells, RootSIFT by default, in kornia's angle-major layout. The patches must already be sampled, scaled and
+ oriented; to describe LAFs on an image, wrap it in :class:`LAFDescriptor` with the same ``patch_size``. For a
+ descriptor at every position of an image, use :class:`DenseSIFTDescriptor` instead, and to describe or orient
+ LAFs without extracting patches, :class:`SIFTDescriptorFromPyramid`.
Convention:
- The input is a stack of grayscale patches, ``patch_size`` pixels square (41 by default; another size
@@ -179,9 +187,10 @@ class SIFTDescriptor(nn.Module):
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.
+ patch_size: Input patch size in pixels. Some sizes cannot hold a centred grid of ``num_spatial_bins`` cells,
+ such as 7 with 4 bins, and raise ``ValueError`` when the module is built.
num_ang_bins: Number of angular bins.
- num_spatial_bins: Number of spatial bins.
+ num_spatial_bins: Number of spatial bins per side.
clipval: clipping value to reduce single-bin dominance
rootsift: if ``True``, RootSIFT (Arandjelović et. al, 2012) is computed.
@@ -189,8 +198,19 @@ class SIFTDescriptor(nn.Module):
SIFT descriptor of the patches.
Shape:
- - Input: :math:`(B, 1, \text{patch_size}, \text{patch_size})`
- - Output: :math:`(B, \text{num_ang_bins * num_spatial_bins ** 2})`
+ - Input: ``(B, 1, patch_size, patch_size)``
+ - Output: ``(B, num_ang_bins * num_spatial_bins ** 2)``
+
+ See Also:
+ - :class:`DenseSIFTDescriptor`: a descriptor at every position of an image, as a map, with no Gaussian
+ weighting of the cells.
+ - :class:`SIFTDescriptorFromPyramid`: describes, and can orient, LAFs on an image without extracting patches.
+ - :func:`convert_sift_descriptor_layout`: reorders the descriptors into OpenCV's layout.
+ - :class:`LAFDescriptor`: runs this module on a patch per LAF of an image.
+ - :class:`SIFTFeature`: detects DoG keypoints and, with the default ``"patch"`` backend, describes them with
+ this module.
+ - :class:`MKDDescriptor`: another handcrafted patch descriptor, from kernel embeddings of the gradients.
+ - :class:`HardNet`: a learned descriptor of 32 x 32 patches.
Example:
>>> input = torch.rand(23, 1, 32, 32)
@@ -291,12 +311,10 @@ class SIFTDescriptor(nn.Module):
r"""Compute SIFT descriptors for square grayscale patches.
Args:
- input: Patch tensor shaped
- :math:`(B, 1, \text{patch\_size}, \text{patch\_size})`.
+ input: Patch tensor shaped ``(B, 1, patch_size, patch_size)``.
Returns:
- Descriptor tensor of size
- :math:`(B, \text{num\_ang\_bins} \times \text{num\_spatial\_bins}^2)`.
+ Descriptor tensor of size ``(B, num_ang_bins * num_spatial_bins ** 2)``.
"""
KORNIA_CHECK_SHAPE(input, ["B", "1", f"{self.patch_size}", f"{self.patch_size}"])
pk_weight = self.pk.weight.to(input.dtype).to(input.device)
@@ -384,6 +402,13 @@ def convert_sift_descriptor_layout(
) -> torch.Tensor:
r"""Reorder SIFT descriptors between kornia's layout and OpenCV's.
+ ``opencv_descs = convert_sift_descriptor_layout(descs, "kornia", "opencv")`` takes SIFT descriptors with the
+ descriptor dimension last, ``(*, A * S ** 2)``, and returns the same values reordered into the ``target``
+ layout, with the input's shape, dtype and device. For the ``(B, A * S ** 2, H_out, W_out)`` map of
+ :class:`DenseSIFTDescriptor`, move the channels last first and back afterwards:
+ ``convert_sift_descriptor_layout(dense.movedim(1, -1), "kornia", "opencv").movedim(-1, 1)``. A reordering does
+ not make descriptors sampled by different methods equal.
+
Both layouts hold the same histogram values, one per angle bin :math:`a` and spatial cell :math:`(y, x)`
of the frame, with :math:`A` = ``num_ang_bins`` and :math:`S` = ``num_spatial_bins``:
@@ -403,7 +428,7 @@ def convert_sift_descriptor_layout(
equally to SIFT and RootSIFT descriptors and keeps their scale; converting back restores the input exactly.
Args:
- descriptors: SIFT descriptors of shape :math:`(*, A S^2)`.
+ descriptors: SIFT descriptors of shape ``(*, A * S ** 2)``.
source: layout of ``descriptors``, ``"kornia"`` or ``"opencv"``.
target: layout to return, ``"kornia"`` or ``"opencv"``.
num_ang_bins: number of angle bins :math:`A`.
@@ -412,6 +437,16 @@ def convert_sift_descriptor_layout(
Returns:
The descriptors in the ``target`` layout, with the input's shape, dtype and device.
+ Raises:
+ ValueError: for a layout other than ``"kornia"`` and ``"opencv"``, or a bin count below 1.
+ BaseError: if the last dimension of ``descriptors`` is not ``A * S ** 2``.
+
+ See Also:
+ - :class:`SIFTDescriptor`: SIFT descriptors of patches, in the ``"kornia"`` layout.
+ - :class:`DenseSIFTDescriptor`: a map of SIFT descriptors, with the ``"kornia"`` layout along its channels.
+ - :class:`SIFTDescriptorFromPyramid`: SIFT descriptors of LAFs, in the ``"kornia"`` layout.
+ - :class:`LightGlueMatcher`: its ``"sift"`` weights expect the ``"opencv"`` layout.
+
Example:
>>> descs = SIFTDescriptor(32)(torch.rand(4, 1, 32, 32))
>>> opencv_descs = convert_sift_descriptor_layout(descs, "kornia", "opencv")
@@ -455,14 +490,21 @@ def sift_describe(
) -> torch.Tensor:
r"""Compute the sift descriptor.
- See
- :class: `~kornia.feature.SIFTDescriptor` for details.
+ See :class:`~kornia.feature.SIFTDescriptor` for details.
"""
return SIFTDescriptor(patch_size, num_ang_bins, num_spatial_bins, rootsift, clipval)(input)
class DenseSIFTDescriptor(nn.Module):
- """nn.Module, which computes SIFT descriptor densely over the image.
+ """Compute a SIFT descriptor at every position of a grayscale image, as a dense map.
+
+ ``dsift = DenseSIFTDescriptor()``, then ``descs = dsift(image)`` takes grayscale images ``(B, 1, H, W)`` and
+ returns a descriptor map ``(B, num_ang_bins * num_spatial_bins ** 2, H_out, W_out)``, ``(B, 128, H_out, W_out)``
+ with the default bins: ``descs[b, :, i, j]`` is the SIFT descriptor of an upright square of
+ ``num_spatial_bins * spatial_bin_size`` pixels (16 by default) placed as the Convention block gives, so every
+ output describes one fixed scale and orientation, and ``stride`` sets the spacing of the output grid. To describe
+ patches you have already sampled, use :class:`SIFTDescriptor` instead, and to describe LAFs at their own scale and
+ orientation, :class:`SIFTDescriptorFromPyramid`.
Convention:
- Every output pixel is a SIFT descriptor of the image around the input position given below. Its
@@ -497,12 +539,18 @@ class DenseSIFTDescriptor(nn.Module):
torch.Tensor: DenseSIFT descriptor of the image
Shape:
- - Input: (B, 1, H, W)
- - Output: (B, num_ang_bins * num_spatial_bins ** 2, H_out, W_out), with
+ - Input: ``(B, 1, H, W)``
+ - Output: ``(B, num_ang_bins * num_spatial_bins ** 2, H_out, W_out)``, with
``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.
+ ``W_out`` likewise, where ``e`` is 1 for an even ``spatial_bin_size`` and 0 for an odd one. An image for
+ which either would be below 1 raises ``RuntimeError``.
+
+ See Also:
+ - :class:`SIFTDescriptor`: one descriptor per given patch, with the cells weighted by a Gaussian window.
+ - :class:`SIFTDescriptorFromPyramid`: descriptors of given LAFs, each at its own scale and orientation.
+ - :func:`convert_sift_descriptor_layout`: reorders the channels into OpenCV's layout, once moved last.
- Examples::
+ Example:
>>> input = torch.rand(2, 1, 200, 300)
>>> SIFT = DenseSIFTDescriptor()
>>> descs = SIFT(input) # 2x128x191x291
diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.py
index c637a2a65..bc5543685 100644
--- a/kornia/feature/sold2/sold2.py
+++ b/kornia/feature/sold2/sold2.py
@@ -32,10 +32,18 @@ from .sold2_detector import LineSegmentDetectionModule, line_map_to_segments, pr
class SOLD2(nn.Module):
- r"""nn.Module, which detects and describe line segments in an image.
-
- This is based on the original code from the paper "SOLD²: Self-supervised
- Occlusion-aware Line Detector and Descriptor". See :cite:`SOLD22021` for more details.
+ r"""Detect, describe and match line segments in grayscale images with SOLD2.
+
+ ``sold2 = SOLD2()`` builds the network with its pretrained weights, in eval mode, and ``outputs = sold2(images)``
+ takes grayscale images ``(B, 1, H, W)`` in :math:`[0, 1]`, with ``H`` and ``W`` multiples of 8, and returns a dict:
+ ``"line_segments"``, one ``(N, 2, 2)`` tensor of ``(row, col)`` endpoints in pixels per image, the
+ ``"junction_heatmap"`` and ``"line_heatmap"``, ``(B, H, W)`` each, and the ``"dense_desc"`` map
+ ``(B, 128, H / 4, W / 4)``. ``matches = sold2.match(line_seg1, line_seg2, desc1, desc2)`` then matches the
+ segments of two images by their descriptors sampled along each segment, with ``desc1`` and ``desc2`` the
+ ``(1, 128, H / 4, W / 4)`` maps of one image each, and returns for each segment of ``line_seg1`` the index of its
+ match in ``line_seg2``, or ``-1``. To detect segments only, use :class:`SOLD2_detector` instead, which builds no
+ descriptor head. This is based on the original code from the paper "SOLD²: Self-supervised Occlusion-aware Line
+ Detector and Descriptor". See :cite:`SOLD22021` for more details.
Convention:
- :meth:`forward` takes the input and returns the heatmaps and the ``(row, col)`` line segments of
@@ -50,15 +58,19 @@ class SOLD2(nn.Module):
none the call raises (`#5810 <https://github.com/kornia/kornia/issues/5810>`_).
Args:
- config: :class:`~kornia.feature.sold2.structures.DetectorCfg`, or a dict of its fields, specifying
- parameters. None will load the default parameters, which are tuned for images in the range 400~800 px.
+ pretrained: If True, download and set pretrained weights to the model, and return it in eval mode; otherwise
+ the weights are random and the model is in training mode.
+ config: a ``kornia.feature.sold2.structures.DetectorCfg``, or a dict of its fields, specifying parameters.
+ None will load the default parameters, which are tuned for images in the range 400~800 px.
The model works on a copy with ``use_descriptor`` set to True; the object passed in is not modified.
- pretrained: If True, download and set pretrained weights to the model.
Returns:
The raw junction and line heatmaps, the semi-dense descriptor map,
as well as the list of detected line segments (ij coordinates convention).
+ See Also:
+ - :class:`SOLD2_detector`: the same line detection, without the descriptor map or matching.
+
Example:
>>> images = torch.rand(2, 1, 64, 64)
>>> sold2 = SOLD2()
@@ -105,7 +117,7 @@ class SOLD2(nn.Module):
img: batched images with shape ``(B, 1, H, W)``.
Returns:
- line_segments: list of N line segments in each of the B images :math:`List[(N, 2, 2)]`.
+ line_segments: a list of ``B`` tensors ``(N, 2, 2)``, the N line segments of each image.
junction_heatmap: raw junction heatmap of shape ``(B, H, W)``.
line_heatmap: raw line heatmap of shape ``(B, H, W)``.
dense_desc: the semi-dense descriptor map of shape ``(B, 128, H/4, W/4)``.
@@ -353,7 +365,7 @@ def keypoints_to_grid(keypoints: torch.Tensor, img_size: Tuple[int, int]) -> tor
It is also not the half-pixel mapping ``(2p + 1) / S - 1``, from which it differs by a constant
half image pixel at every ``p``. Changing either the formula or the ``align_corners`` of the
sampler would break compatibility with the pretrained weights (compare
- :meth:`kornia.feature.xfeat.XFeat` and its ``normgrid``, which keep their own trained pairing).
+ :class:`~kornia.feature.XFeat` and its ``normgrid``, which keep their own trained pairing).
Args:
keypoints: a torch.Tensor [N, 2] of N keypoints (ij coordinates convention).
@@ -366,7 +378,7 @@ def keypoints_to_grid(keypoints: torch.Tensor, img_size: Tuple[int, int]) -> tor
def batched_linspace(start: torch.Tensor, end: torch.Tensor, step: int, dim: int) -> torch.Tensor:
- """Batch version of torch.F.normalize (similar to the numpy one)."""
+ """Batch version of torch.linspace (similar to the numpy one)."""
intervals = ((end - start) / (step - 1)).unsqueeze(dim)
broadcast_size = [1] * len(intervals.shape)
broadcast_size[dim] = step
diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.py
index f8f2fc4fd..f69a7fac6 100644
--- a/kornia/feature/sold2/sold2_detector.py
+++ b/kornia/feature/sold2/sold2_detector.py
@@ -37,31 +37,39 @@ urls["wireframe"] = [
class SOLD2_detector(nn.Module):
- r"""nn.Module, which detects line segments in an image.
+ r"""Detect line segments in grayscale images with SOLD2, without describing or matching them.
- This is based on the original code from the paper "SOLD²: Self-supervised
- Occlusion-aware Line Detector and Descriptor". See :cite:`SOLD22021` for more details.
+ ``detector = SOLD2_detector()`` builds the network with its pretrained weights, in evaluation mode, and
+ ``outputs = detector(images)`` takes grayscale images ``(B, 1, H, W)`` in :math:`[0, 1]`, with ``H`` and ``W``
+ multiples of 8, and returns a dict: ``"line_segments"``, one ``(N, 2, 2)`` tensor of ``(row, col)`` endpoints in
+ pixels per image, and the ``"junction_heatmap"`` and ``"line_heatmap"``, ``(B, H, W)`` each. With the same weights
+ and ``config``, these are the segments and heatmaps of :class:`SOLD2`; to also describe the segments and match them
+ between images, use :class:`SOLD2` instead. This is based on the original code from the paper "SOLD²:
+ Self-supervised Occlusion-aware Line Detector and Descriptor". See :cite:`SOLD22021` for more details.
Convention:
- - The input is a grayscale image ``(B, 1, H, W)``, in :math:`[0, 1]` for the pretrained weights, with
- ``H`` and ``W`` multiples of 8; other sizes raise an error or give heatmaps of another size.
- ``junction_heatmap`` and ``line_heatmap`` are ``(B, H, W)``.
+ - Sizes that are not multiples of 8 raise an error or give heatmaps of another size.
- ``line_segments`` holds one ``(N, 2, 2)`` tensor per image: the two endpoints of each segment as
- ``(row, col)`` in the pixel frame of :func:`~kornia.feature.laf_from_center_scale_ori`
+ ``(row, col)`` in the pixel convention of :func:`~kornia.feature.laf_from_center_scale_ori`
(see :ref:`Local features <local-features-conventions>`), so ``flip(-1)`` gives ``(x, y)``. The endpoints
of a segment, and the segments by their first endpoint, are in raster order: the smaller row first or, on
the same row, the smaller column, whatever the junction scores.
- - The endpoints are junction pixels. The default junction refinement (``use_junction_refinement`` of
- ``LineDetectorCfg``) moves each of them by at most 1 pixel per axis, in 0.25 pixel steps.
+ - The endpoints are junction coordinates. The default junction refinement (``use_junction_refinement`` of
+ ``LineDetectorCfg``) can produce sub-pixel endpoints in 0.25-pixel steps, up to one pixel per axis.
Args:
config (DetectorCfg): Configuration object containing all parameters, or a dict of its fields. None will load
- the default parameters, which are tuned for images in the range 400~800 px.
- pretrained (bool): If True, download and set pretrained weights to the model.
+ the default parameters, which are tuned for images in the range 400~800 px. A ``config`` with
+ ``use_descriptor=True`` builds the descriptor head, which the outputs do not use.
+ pretrained (bool): If True, download and set pretrained weights to the model, and return it in eval mode;
+ otherwise the weights are random and the model is in training mode.
Returns:
The raw junction and line heatmaps, as well as the list of detected line segments (ij coordinates convention).
+ See Also:
+ - :class:`SOLD2`: the same line detection plus the descriptor map and line matching.
+
Example:
>>> img = torch.rand(1, 1, 128, 128)
>>> sold2_detector = SOLD2_detector(pretrained=False).eval()
@@ -117,7 +125,7 @@ class SOLD2_detector(nn.Module):
img: batched images with shape ``(B, 1, H, W)``.
Returns:
- line_segments: list of N line segments in each of the B images :math:`List[(N, 2, 2)]`.
+ line_segments: a list of ``B`` tensors ``(N, 2, 2)``, the ``(row, col)`` segment endpoints per image.
junction_heatmap: raw junction heatmap of shape ``(B, H, W)``.
line_heatmap: raw line heatmap of shape ``(B, H, W)``.
diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.py
index 734a2f166..538e7b749 100644
--- a/kornia/feature/sosnet.py
+++ b/kornia/feature/sosnet.py
@@ -36,10 +36,14 @@ urls["hp_a"] = [
class SOSNet(nn.Module):
- r"""128-dimensional SOSNet model definition for 32x32 patches.
+ r"""Describe 32 x 32 grayscale patches with SOSNet, trained with second-order similarity.
- This is based on the original code from paper
- "SOSNet:Second Order Similarity Regularization for Local Descriptor Learning".
+ ``sosnet = SOSNet()`` builds the network with its pretrained weights (trained on Liberty), in eval mode, and
+ ``descs = sosnet(patches)`` takes grayscale patches ``(B, 1, 32, 32)`` and returns unit-norm descriptors
+ ``(B, 128)``. It has the convolution stack of :class:`HardNet`, preceded by an ``InstanceNorm2d``, and was trained
+ with a second-order similarity regularisation. To describe LAFs on an image, pass it to :class:`LAFDescriptor`.
+ 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`.
@@ -51,6 +55,14 @@ class SOSNet(nn.Module):
- Input: ``(B, 1, 32, 32)``
- Output: ``(B, 128)``
+ See Also:
+ - :class:`HardNet`: the same convolution stack, trained without the second-order regularisation.
+ - :class:`HyNet`: a descriptor of the same patches with FRN layers, which subtract no mean.
+ - :class:`HardNet8`: the wider follow-up of HardNet, with a PCA to 128 dimensions.
+ - :class:`TFeat`: a shallow network for the same patches that also starts with an ``InstanceNorm2d``, without
+ L2 normalisation.
+ - :class:`LAFDescriptor`: runs a patch descriptor such as this one on a patch per LAF of an image.
+
Note:
With float16 weights, the final BatchNorm keeps its running statistics in float32.
Convert the model to float16 before calling ``torch.jit.script``.
diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.py
index 0f927c030..f9e3703b7 100644
--- a/kornia/feature/tfeat.py
+++ b/kornia/feature/tfeat.py
@@ -40,11 +40,14 @@ urls["yosemite"] = [
class TFeat(nn.Module):
- r"""Module, which computes TFeat descriptors of given grayscale patches of 32x32.
+ r"""Describe 32 x 32 grayscale patches with the shallow TFeat CNN, without L2 normalisation.
- This is based on the original code from paper "Learning local feature descriptors
- with triplets and shallow convolutional neural networks".
- See :cite:`TFeat2016` for more details
+ ``tfeat = TFeat()`` builds the network with its pretrained weights (trained on Liberty), in eval mode, and
+ ``descs = tfeat(patches)`` takes grayscale patches ``(B, 1, 32, 32)`` and returns ``(B, 128)`` descriptors with
+ entries in ``[-1, 1]``, not unit vectors (see the Convention block). It has two convolutions and one linear layer.
+ For unit-norm descriptors of the same patches, use :class:`HardNet` instead; to describe LAFs on an image, pass it
+ to :class:`LAFDescriptor`. This is based on the original code from paper "Learning local feature descriptors
+ 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
@@ -62,6 +65,11 @@ class TFeat(nn.Module):
- Input: ``(B, 1, 32, 32)``
- Output: ``(B, 128)``
+ See Also:
+ - :class:`HardNet`: a deeper network for the same patches, with unit-norm descriptors.
+ - :class:`SOSNet`: a deeper network for the same patches that also starts with an ``InstanceNorm2d``.
+ - :class:`LAFDescriptor`: runs a patch descriptor such as this one on a patch per LAF of an image.
+
Examples:
>>> input = torch.rand(16, 1, 32, 32)
>>> tfeat = TFeat(pretrained=False).eval()
diff --git a/kornia/feature/xfeat.py b/kornia/feature/xfeat.py
index 95b8dfe4e..9801cceec 100644
--- a/kornia/feature/xfeat.py
+++ b/kornia/feature/xfeat.py
@@ -78,32 +78,31 @@ class BasicLayer(nn.Module):
r"""Run the module forward pass.
Args:
- x: Input feature map with shape :math:`(B, C_{\text{in}}, H, W)`.
+ x: Input feature map with shape ``(B, C_in, H, W)``.
Returns:
- Output feature map with shape :math:`(B, C_{\text{out}}, H', W')`.
+ Output feature map with shape ``(B, C_out, H', W')``.
"""
return self.layer(x)
class XFeatModel(nn.Module):
- """XFeat backbone: CNN feature extractor, keypoint and reliability heads.
+ """Compute the dense descriptors, keypoint logits and reliability map of XFeat at 1/8 resolution.
- Implements the architecture from
- "XFeat: Accelerated Features for Lightweight Image Matching", CVPR 2024.
-
- Input: float image tensor ``(B, C, H, W)`` (grayscale or RGB, any channel count).
- Output:
-
- - ``feats``: dense descriptors ``(B, 64, H/8, W/8)``.
- - ``keypoints``: keypoint logits ``(B, 65, H/8, W/8)``.
- - ``heatmap``: reliability map ``(B, 1, H/8, W/8)``.
+ ``net = XFeatModel().eval()`` builds the random-weight network for inference (``XFeat.from_pretrained().net``
+ is trained), and ``feats, keypoints, heatmap = net(images)`` takes float images ``(B, C, H, W)`` with any
+ channel count and ``H`` and ``W`` multiples of 8, and returns the dense descriptors ``(B, 64, H/8, W/8)``, not
+ normalised, the keypoint logits ``(B, 65, H/8, W/8)`` and the reliability map ``(B, 1, H/8, W/8)``, a sigmoid. It
+ finds no keypoints itself: for keypoints, descriptors and matches, use :class:`XFeat` instead. It implements the
+ architecture of "XFeat: Accelerated Features for Lightweight Image Matching", CVPR 2024.
Convention:
- The channels are averaged and the result is instance-normalised, so any channel count is accepted and an
affine change ``a x + b`` of the intensities with ``a > 0`` changes the outputs only through the norm's
``eps`` (``1e-5``): negligibly while the variance of the channel mean is much larger than ``eps``, and
substantially for a low-contrast image, whose variance is close to it (see :class:`XFeat`).
+ - A new ``XFeatModel`` is in training mode. A single ``32 x 32`` image reaches BatchNorm with one value per
+ channel and raises; call ``.eval()`` for inference.
- ``H`` and ``W`` must be multiples of 8; other sizes raise an error or give maps of mismatched sizes.
:class:`XFeat` resizes its input to multiples of 32.
- ``keypoints`` holds 65 logits per 8 x 8 cell: channel ``(y % 8) * 8 + x % 8`` of cell ``(y // 8, x // 8)``
@@ -112,6 +111,11 @@ class XFeatModel(nn.Module):
Note:
Image normalisation (``InstanceNorm2d``) is wrapped in ``torch.no_grad()``
following the original design; backpropagating through it is not supported.
+
+ See Also:
+ - :class:`XFeat`: runs this network and detects, describes and matches keypoints from its maps.
+ - :class:`InterpolateSparse2d`: samples the descriptor map at sparse keypoints, as :class:`XFeat` does.
+
"""
def __init__(self) -> None:
@@ -228,14 +232,22 @@ class XFeatModel(nn.Module):
class InterpolateSparse2d(nn.Module):
- """Bilinearly or bicubically sample a dense feature map at sparse 2-D positions.
+ """Sample a feature map at sparse (x, y) pixels with the XFeat weights' coordinate scaling.
+
+ ``interp = InterpolateSparse2d("bicubic")`` and ``out = interp(x, pos, H, W)`` take a feature map ``(B, C, h, w)``
+ and positions ``(B, N, 2)`` as ``(x, y)`` pixels of an image of height ``H`` and width ``W``, and return the
+ features ``(B, N, C)`` that :func:`torch.nn.functional.grid_sample` reads there with ``mode``, in the dtype of
+ ``x``. The positions are divided by ``W - 1`` and ``H - 1`` but sampled with ``align_corners=False``, as the
+ pretrained XFeat weights expect, so ``H`` and ``W`` must be greater than 1, and a map of the image's own size is
+ not read at ``pos`` itself (see the Convention block). To read a map of the image's own size at the pixel itself,
+ normalise the positions with :func:`~kornia.geometry.conversions.normalize_pixel_coordinates` and pass
+ ``align_corners=True`` to ``grid_sample`` instead.
Convention:
- ``pos`` holds ``(x, y)`` pixels of an image of height ``H`` and width ``W`` whose feature map has height
``h`` and width ``w``. A position ``(px, py)`` is read at ``px * w / (W - 1) - 0.5`` and
``py * h / (H - 1) - 0.5`` in the map's pixel frame: ``normgrid``'s ``2 p / (W - 1) - 1`` sampled with
- ``align_corners=False``, the convention the pretrained XFeat weights use. So a map of the image's own size is
- not read at ``p`` itself.
+ ``align_corners=False``, the convention the pretrained XFeat weights use.
- Known defects: on CPU, float16 and bfloat16 maps go to torch's ``grid_sample`` without an upcast: the
half-precision kernel can return wrong values, NaN or overflow, and where torch has none the call raises
(`#5810 <https://github.com/kornia/kornia/issues/5810>`_).
@@ -247,9 +259,17 @@ class InterpolateSparse2d(nn.Module):
``False``.
Shape:
- - Input ``x``: ``(B, C, H, W)``.
+ - Input ``x``: ``(B, C, h, w)``.
- Input ``pos``: ``(B, N, 2)`` integer or float (x, y) coordinates.
- Output: ``(B, N, C)``.
+
+ See Also:
+ - :class:`XFeat`: samples its dense descriptors at its keypoints with this module.
+ - :class:`XFeatModel`: the network whose descriptor map :class:`XFeat` samples with this module.
+ - :func:`~kornia.geometry.conversions.normalize_pixel_coordinates`: the same division by ``W - 1`` and
+ ``H - 1``, meant for ``grid_sample`` with ``align_corners=True``, which reads a map of the image's size at
+ the pixel itself.
+
"""
def __init__(self, mode: str = "bicubic", align_corners: bool = False) -> None:
@@ -271,10 +291,10 @@ class InterpolateSparse2d(nn.Module):
"""Sample ``x`` at positions ``pos``.
Args:
- x: feature map ``(B, C, H, W)``.
+ x: feature map ``(B, C, h, w)``.
pos: sampling positions ``(B, N, 2)`` in pixel coordinates.
- H: height used for coordinate normalisation.
- W: width used for coordinate normalisation.
+ H: height used for coordinate normalisation, greater than 1.
+ W: width used for coordinate normalisation, greater than 1.
Returns:
Sampled features ``(B, N, C)``.
@@ -288,10 +308,14 @@ class InterpolateSparse2d(nn.Module):
class XFeat(nn.Module):
- """XFeat sparse and semi-dense local feature extractor and matcher.
+ """Detect and describe keypoints with XFeat, and match image pairs, sparse or refined (XFeat*).
- Wraps :class:`XFeatModel` with NMS keypoint detection, descriptor
- interpolation, and mutual nearest-neighbour matching helpers.
+ ``xfeat = XFeat.from_pretrained()`` loads trained weights in evaluation mode.
+ ``out = xfeat.detectAndCompute(images)`` takes images ``(B, C, H, W)`` with any channel count and returns one
+ dictionary per image. Each contains up to ``top_k`` keypoints ``(N, 2)`` in ``(x, y)`` pixels, scores ``(N,)``
+ in descending order and L2-normalised descriptors ``(N, 64)``.
+ Use :meth:`match_xfeat` to extract and match sparse features, or :meth:`match_xfeat_star` for refined matches
+ from semi-dense features. For subpixel keypoint detection, use :class:`ALIKED` instead.
Reference:
"XFeat: Accelerated Features for Lightweight Image Matching", CVPR 2024.
@@ -300,40 +324,48 @@ class XFeat(nn.Module):
.. image:: _static/img/XFeat.png
Convention:
- - XFeat defines no ``forward``: call :meth:`detectAndCompute` or :meth:`detectAndComputeDense`.
- - ``XFeat()`` builds random weights in training mode, where BatchNorm normalises with the batch, updates its
- running statistics on every call, and matching a single small image pair raises; call ``.eval()`` for
- inference. :meth:`from_pretrained` returns the trained model in evaluation mode. The inference methods
- run under ``torch.inference_mode``.
+ - Use the named extraction and matching methods: XFeat has no ``forward``. Its network, ``xfeat.net``,
+ is an :class:`XFeatModel` that produces dense maps. To match with LighterGlue, construct LAFs with
+ :func:`~kornia.feature.laf_from_center_scale_ori` on ``keypoints[None]`` and pass them with the descriptors
+ to :class:`LightGlueMatcher` in ``"xfeat"`` mode, with gradients disabled.
+ - ``XFeat()`` builds random weights in training mode. Batch normalisation can raise on a single small image;
+ call ``.eval()`` for inference. :meth:`from_pretrained` returns the trained model in evaluation mode.
+ - :meth:`detectAndCompute`, :meth:`detectAndComputeDense`, :meth:`match_xfeat` and :meth:`match_xfeat_star`
+ run under ``torch.inference_mode``, so they return inference tensors.
- The image is ``(B, C, H, W)`` with any channel count. Each extraction resizes the image it gets
- bilinearly to :math:`(H', W')`: ``H`` and ``W`` rounded down to multiples of 32, with a minimum of 32.
+ bilinearly to ``(H', W')``: ``H`` and ``W`` rounded down to multiples of 32, with a minimum of 32.
:class:`XFeatModel` then averages the channels and instance-normalises the result, so an affine change of the
intensities with a positive gain changes its maps only through the norm's ``eps``, which weighs more the
lower the image's contrast. With the pretrained weights and ``top_k=2048``, the :math:`[0, 1]` and
:math:`[0, 255]` versions of Oxford graf and wall ``img1`` differ in at most 1 keypoint, in 1 to 2 % of them
with the intensities multiplied by 0.1, and in 35 to 40 % multiplied by 0.01. Every output is float32.
- - :meth:`detectAndCompute` keypoints are integer pixels ``i`` of the resized image, strict maxima of the
- keypoint heatmap in their 5 x 5 window (see the note), reported at ``i * (W / W', H / H')``. That is the
- pixel frame of :func:`~kornia.feature.laf_from_center_scale_ori`
- (see :ref:`Local features <local-features-conventions>`) when ``H`` and ``W`` are multiples of 32;
- otherwise the centre of the resized pixel is at ``(i + 0.5) * (W / W', H / H') - 0.5``.
+ - :meth:`detectAndCompute` keypoints are integer pixels of the resized image, strict maxima of the keypoint
+ heatmap in their 5 x 5 window (see the note), reported in the pixel convention of
+ :func:`~kornia.feature.laf_from_center_scale_ori` (see :ref:`Local features <local-features-conventions>`).
+ Their reported position is offset after resizing; see `#6537 <https://github.com/kornia/kornia/issues/6537>`_.
- The heatmap value must be strictly above ``detection_threshold``. ``scores`` is that value times the
reliability map, and the ``top_k`` best keypoints come sorted by it. Each descriptor is 64-D, sampled
bicubically from the dense map at the keypoint by :class:`InterpolateSparse2d`, and L2-normalised.
- With ``multiscale=False``, :meth:`detectAndComputeDense` reports cell ``(j, i)`` of the 1/8-resolution map
- at ``8 * (j, i)``, times the same ratio: the top-left pixel of the cell, not its centre. It keeps the
- ``top_k`` cells of highest reliability, or every cell when there are fewer or ``top_k`` is below 1. With
- the default ``multiscale=True``, it rescales the image bilinearly by 0.6 and by 1.3, runs that extraction
+ at ``8 * (j, i)``, scaled by the input-to-resized image ratio: the top-left pixel of the cell, not its centre.
+ It keeps up to ``top_k`` cells by reliability; ``top_k < 1`` keeps every cell.
+ With the default ``multiscale=True``, it rescales the image bilinearly by 0.6 and by 1.3, runs that extraction
on each with ``int(0.2 * top_k)`` and the remaining ``top_k - int(0.2 * top_k)`` cells, and divides each
- keypoint by its factor; ``scales`` is ``1 / 0.6`` or ``1 / 1.3`` for each keypoint. A share of 0 yields no
- cell from its scale, and a scale with fewer cells than its share returns all of them, so there are never
- more than ``top_k`` keypoints, and exactly ``top_k`` when both scales have enough cells. A ``top_k`` below
- 1 keeps every cell of both scales. Its descriptors are not normalised. The reference implementation gives
- the 1.3 scale ``int(0.8 * top_k)`` and reads a share of 0 as "every cell"; kornia does not, because that
- returns more keypoints than ``top_k`` asks for.
+ keypoint by its factor; ``scales`` is ``1 / 0.6`` or ``1 / 1.3`` for each keypoint. Their reported positions
+ are offset after resizing; see `#6537 <https://github.com/kornia/kornia/issues/6537>`_. A share of 0 yields
+ no cell from its scale, and a scale with fewer
+ cells than its share returns all of them, so there are never more than ``top_k`` keypoints, and exactly
+ ``top_k`` when both scales have enough cells. A ``top_k`` below 1 keeps every cell of both scales. Its
+ descriptors are not normalised. The reference implementation gives the 1.3 scale ``int(0.8 * top_k)`` and
+ reads a share of 0 as "every cell"; kornia does not, because that returns more keypoints than ``top_k`` asks
+ for.
- Known defects: converting the model to float16 or bfloat16 makes every extraction raise, because
``_preprocess_tensor`` passes float32 input to the half-precision weights
- (`#5957 <https://github.com/kornia/kornia/issues/5957>`_).
+ (`#5957 <https://github.com/kornia/kornia/issues/5957>`_). Autograd cannot save the inference tensors of
+ the four methods above for a backward pass, so :class:`~kornia.feature.LightGlueMatcher`, whose parameters
+ require gradients, raises on them with gradients enabled, the default grad mode: call it under
+ ``torch.no_grad()`` or ``torch.inference_mode()``, or ``clone()`` the outputs first
+ (`#6533 <https://github.com/kornia/kornia/issues/6533>`_).
Args:
top_k: maximum number of keypoints to keep per image. Default: ``4096``.
@@ -362,6 +394,18 @@ class XFeat(nn.Module):
the true sub-cell offset has a slope of about 0.5, so bin 3 removes the constant part of the error, not that
shrinkage.
+ See Also:
+ - :class:`XFeatModel`: the network it runs, which returns the dense maps at 1/8 resolution.
+ - :class:`InterpolateSparse2d`: samples the dense descriptors at the keypoints.
+ - :class:`ALIKED`: learned sub-pixel keypoints with 128-D descriptors, for RGB images of any size.
+ - :class:`DISK`: learned integer-pixel keypoints with 128-D descriptors, for RGB images whose sides are
+ multiples of 16.
+ - :class:`DeDoDe`: separate learned detector and descriptor networks, with ``n`` keypoints in every image.
+ - :func:`laf_from_center_scale_ori`: turns the keypoints of one image into the LAFs that
+ :class:`LightGlueMatcher` takes.
+ - :class:`LightGlueMatcher`: matches the descriptors and keypoints with the LighterGlue ``"xfeat"`` weights
+ instead of mutual nearest neighbours.
+
Example:
>>> model = XFeat.from_pretrained()
>>> img = torch.rand(1, 3, 256, 256)
@@ -692,7 +736,8 @@ class XFeat(nn.Module):
img1: first images ``(B, C, H, W)``.
img2: second images ``(B, C, H, W)``, with the same ``B`` as ``img1``.
top_k: number of top keypoints to use.
- min_cossim: minimum cosine similarity threshold. Use ``-1`` to disable.
+ min_cossim: the cosine similarity a match must exceed; a value of 0 or below, such as the default
+ ``-1``, disables the check.
Returns:
If ``B != 1``: list of ``(N, 4)`` tensors with ``(x1, y1, x2, y2)`` matches, one per pair; an empty
@@ -726,7 +771,7 @@ class XFeat(nn.Module):
Args:
im_set1: batch of images ``(B, C, H, W)``.
- im_set2: batch of images ``(B, C, H, W)``.
+ im_set2: batch of images ``(B, C, H, W)``, with the same ``B`` as ``im_set1``.
top_k: number of top features to use.
Returns:
diff --git a/testing/docstring_rollout.py b/testing/docstring_rollout.py
index 04bc91310..51ab773aa 100644
--- a/testing/docstring_rollout.py
+++ b/testing/docstring_rollout.py
@@ -53,6 +53,8 @@ EXCLUDED_PACKAGES: dict[str, str] = {
"""Top-level packages left out of the rollout, with the reason."""
CATALOG_NAMESPACES: tuple[str, ...] = (
+ "kornia.feature",
+ "kornia.feature.dedode.transformer",
"kornia.geometry.bbox",
"kornia.geometry.boxes",
"kornia.geometry.calibration",
@@ -88,6 +90,32 @@ CATALOG_NAMESPACES: tuple[str, ...] = (
"""Namespaces whose module docstring must name every export in ``__all__``."""
DOCSTRING_MODULES: tuple[str, ...] = (
+ "kornia.feature.adalam",
+ "kornia.feature.affine_shape",
+ "kornia.feature.aliked",
+ "kornia.feature.dedode",
+ "kornia.feature.defmo",
+ "kornia.feature.disk",
+ "kornia.feature.hardnet",
+ "kornia.feature.hynet",
+ "kornia.feature.integrated",
+ "kornia.feature.keynet",
+ "kornia.feature.laf",
+ "kornia.feature.lightglue",
+ "kornia.feature.lightglue_onnx",
+ "kornia.feature.loftr",
+ "kornia.feature.matching",
+ "kornia.feature.mkd",
+ "kornia.feature.orientation",
+ "kornia.feature.responses",
+ "kornia.feature.scale_space_detector",
+ "kornia.feature.sift",
+ "kornia.feature.siftdesc",
+ "kornia.feature.sold2.sold2",
+ "kornia.feature.sold2.sold2_detector",
+ "kornia.feature.sosnet",
+ "kornia.feature.tfeat",
+ "kornia.feature.xfeat",
"kornia.geometry.bbox",
"kornia.geometry.boxes",
"kornia.geometry.calibration",
@@ -113,7 +141,9 @@ DOCSTRING_MODULES: tuple[str, ...] = (
)
"""Prefixes of the defining modules whose public objects carry the converted docstring style."""
-SEE_ALSO_EXCEPTIONS: dict[str, str] = {}
+SEE_ALSO_EXCEPTIONS: dict[str, str] = {
+ "kornia.feature.defmo.DeFMO": "the only deblurring model in kornia; no other object serves a nearby task",
+}
"""Qualified name of a converted object that needs no ``See Also:`` section, with the reason."""
MATH_NON_SHAPES: dict[str, dict[str, str]] = {