Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(feature): convention blocks and pins for the matchers (#5856)

Dmytro Mishkin1341769ba076
diff --git a/changelog.d/5856.added.md b/changelog.d/5856.added.md
new file mode 100644
index 000000000..093990862
--- /dev/null
+++ b/changelog.d/5856.added.md
@@ -0,0 +1 @@
+Document the conventions of the `kornia.feature` matchers (`match_nn`, `match_mnn`, `match_snn`, `match_smnn`, `match_smnn_batched`, `match_fginn`, `match_adalam`, `DescriptorMatcher`, `GeometryAwareDescriptorMatcher`, `LocalFeatureMatcher`, `LightGlueMatcher`, `LightGlue`, `OnnxLightGlue` and `LoFTR`) as Convention blocks and pointers: what the returned values and index pairs hold for each matcher, the inclusive ratio thresholds and a given distance matrix, the keypoints, image size and extra inputs each LightGlue feature type takes, the dtype of LightGlue's matching scores, the LoFTR keypoint frame, and the known defects of `match_adalam`, `LightGlue` and `OnnxLightGlue`.
diff --git a/kornia/feature/adalam/adalam.py b/kornia/feature/adalam/adalam.py
index fa5d872f4..e819fb648 100644
--- a/kornia/feature/adalam/adalam.py
+++ b/kornia/feature/adalam/adalam.py
@@ -62,13 +62,30 @@ def match_adalam(
See :cite:`AdaLAM2020` for more details.
- The putative matches are the nearest neighbours in the distance matrix ``dm``, scored by the ratio of the two
- smallest distances; with ``force_seed_mnn`` only mutual nearest neighbours can be seeds. ``dm`` holds plain
- distances, like the ``dm`` of :func:`~kornia.feature.match_nn` and the other matchers: AdaLAM squares it
- internally (its thresholds are tuned for squared distances), so ``dm=torch.cdist(desc1, desc2)`` gives the
- matches of ``dm=None``, where the squared L2 distances between the descriptors are used.
-
- The computation runs on the device of ``desc1`` unless ``config`` sets ``"device"``.
+ Convention:
+ - See the Convention block on :func:`~kornia.feature.match_nn`. ``dists`` is the inverse of the confidence
+ of the local RANSAC that accepted the match, in float32 whatever the descriptor dtype, so at most
+ ``1 / min_confidence`` (``1 / 200`` by default). If no seed survives, for example with very few keypoints,
+ the matches of a ratio test on squared distances, ``ratio <= 0.95``, are returned with that ratio instead.
+ - The putative matches are the nearest neighbours in the distance matrix ``dm``, scored by the ratio of the
+ two smallest distances; with ``force_seed_mnn`` only mutual nearest neighbours can be seeds. ``dm`` holds
+ plain distances, like the ``dm`` of :func:`~kornia.feature.match_nn` and the other matchers: AdaLAM
+ squares it internally (its thresholds are tuned for squared distances), so ``dm=torch.cdist(desc1, desc2)``
+ gives the matches of ``dm=None``, where the squared L2 distances between the descriptors are used.
+ - The LAFs give each keypoint's centre, orientation in degrees and scale. Orientations and scales are read
+ only through how their change between the two images varies from match to match: adding an angle to the
+ orientations of one image or both, negating both, or scaling the LAFs of one image or both alike changes
+ nothing.
+ - ``hw1`` and ``hw2`` enter only through the area of their image, which sets the neighbourhood radius in that
+ image, so ``(H, W)`` and ``(W, H)`` give the same matches. Without them, the extent of each image's
+ keypoints is used.
+ - ``config`` is merged into the defaults of ``kornia.feature.adalam.get_adalam_default_config()``; an
+ unknown key warns and is ignored. The computation runs on the device of ``desc1`` unless ``config`` sets
+ ``"device"``.
+ - Known defects: exact correspondences are rejected, because the local RANSACs give residuals at or near zero
+ no inlier weight. An image matched against itself gets no match whenever a seed survives; when none does,
+ as with very few keypoints, the ratio-test fallback above returns the identity matches instead
+ (`#5866 <https://github.com/kornia/kornia/issues/5866>`_).
Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
@@ -78,12 +95,13 @@ def match_adalam(
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 :math:`(B1, B2)`. Smaller is better.
- hw1: Height/width of image.
- hw2: Height/width of image.
+ hw1: size of the first image, ``(H, W)`` or ``(W, H)``.
+ hw2: size of the second image, ``(H, W)`` or ``(W, H)``.
Return:
- - Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
+ - Inverse local RANSAC confidence of each match, float32, shape of :math:`(B3, 1)`; see the Convention
+ block.
- Long torch.Tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
where 0 <= B3 <= B1.
diff --git a/kornia/feature/adalam/core.py b/kornia/feature/adalam/core.py
index 167790e53..6592227b9 100644
--- a/kornia/feature/adalam/core.py
+++ b/kornia/feature/adalam/core.py
@@ -46,7 +46,8 @@ class AdalamConfig(TypedDict):
force_seed_mnn: Whether to consider only MNN for the purpose of selecting seeds. Generally improves accuracy
at the cost of runtime
device: Union[str, torch.device, None] to be used for running AdaLAM. Use GPU if available.
- mnn: Default None. You can provide a MNN mask in input to skip MNN computation and still get the improvement.
+ mnn: not read from the configuration: :func:`~kornia.feature.match_adalam` warns about this key and ignores it.
+ A mutual-nearest-neighbour mask goes to ``AdalamFilter.filter_matches`` as its ``mnn`` argument.
"""
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index d01f6b1d8..f44d73283 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -716,6 +716,17 @@ class KeyNetAffNetHardNet(LocalFeature):
class LocalFeatureMatcher(nn.Module):
r"""nn.Module, which finds correspondences between two images based on local features.
+ Convention:
+ - ``keypoints0`` and ``keypoints1`` are the centres ``(x, y)`` of the matched LAFs, which ``lafs0`` and
+ ``lafs1`` return; see :func:`~kornia.feature.laf_from_center_scale_ori` for the LAF frame.
+ ``confidence`` is ``1 - dists`` of the matcher (see :func:`~kornia.feature.match_nn`).
+ - All-zero LAFs, the padding slots of kornia's detectors (see :func:`~kornia.feature.laf_is_filled`), are
+ dropped before matching.
+ - ``matcher`` is called as ``matcher(descriptors0, descriptors1)`` for each image pair, so it has to be a
+ descriptor-only matcher such as :class:`~kornia.feature.DescriptorMatcher`;
+ :class:`~kornia.feature.GeometryAwareDescriptorMatcher` and :class:`~kornia.feature.LightGlueMatcher`
+ need LAFs and do not fit.
+
Args:
local_feature: Local feature detector. See :class:`~kornia.feature.GFTTAffNetHardNet`.
matcher: Descriptor matcher, see :class:`~kornia.feature.DescriptorMatcher`.
@@ -780,6 +791,11 @@ class LocalFeatureMatcher(nn.Module):
:math:`(N, H1, W1)` or :math:`(N, 1, H1, W1)`.
mask1 (optional): right image mask. '0' suppresses detection, with shape
:math:`(N, H2, W2)` or :math:`(N, 1, H2, W2)`.
+ lafs0 (optional): pre-extracted LAFs of image0, :math:`(N, M0, 2, 3)`. When ``lafs0`` and
+ ``descriptors0`` are both given, they are matched and ``local_feature`` does not run on image0.
+ descriptors0 (optional): pre-extracted descriptors of image0, :math:`(N, M0, D)`.
+ lafs1 (optional): pre-extracted LAFs of image1, :math:`(N, M1, 2, 3)`; with ``descriptors1``, as for image0.
+ descriptors1 (optional): pre-extracted descriptors of image1, :math:`(N, M1, D)`.
Returns:
- ``keypoints0``, matching keypoints from image0 :math:`(NC, 2)`.
@@ -898,28 +914,39 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
This is based on the original code from paper "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`,
+ 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"``, ``"superpoint"``: nothing else.
+ - ``"sift"``: the scale and orientation of the COLMAP keypoints the weights 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
+ 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]``,
+ 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,
+ index in desc2)``. Fewer than two descriptors on either side give no match.
+ - All-zero padding LAFs are not filtered out: such a slot reaches the network as a keypoint at ``(0, 0)``.
+ Drop them with :func:`~kornia.feature.laf_is_filled` first.
+
Args:
feature_name: type of feature for matching, one of ``known_modes``.
- params: LightGlue params.
-
- With ``"sift"``, the descriptors must be in OpenCV's SIFT layout, which LightGlue's SIFT weights expect. kornia's
- SIFT descriptors use another order of the same values: create the feature with ``descriptor_layout="opencv"``,
- or convert them first with :func:`~kornia.feature.convert_sift_descriptor_layout`::
-
- descs = convert_sift_descriptor_layout(descs, "kornia", "opencv")
-
- The keypoint scale and orientation taken from the LAFs are converted to the convention of the COLMAP keypoints
- the ``"sift"`` weights were trained on: the orientation is the negated LAF orientation in :math:`(-\pi, \pi]`,
- and the scale is a sixth of the LAF scale, which is the detection sigma for 6-sigma DoG frames such as
- :class:`~kornia.feature.SIFTFeatureScaleSpace`'s.
-
- With ``"doghardnet"`` and ``"dog_affnet_hardnet"``, 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)`.
+ params: keyword arguments of :class:`~kornia.feature.LightGlue`, such as ``filter_threshold``.
"""
@@ -960,11 +987,11 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
desc2: Batch of descriptors of a shape :math:`(B2, D)`.
lafs1: LAFs of a shape :math:`(1, B1, 2, 3)`.
lafs2: LAFs of a shape :math:`(1, B2, 2, 3)`.
- hw1: Height/width of image.
- hw2: Height/width of image.
+ hw1: ``(H, W)`` of the first image; see the Convention block.
+ hw2: ``(H, W)`` of the second image; see the Convention block.
Return:
- - Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
+ - LightGlue's matching score of each match, higher is better, shape of :math:`(B3, 1)`.
- Long torch.Tensor indexes of matching descriptors in desc1 and desc2,
shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`.
diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.py
index 522aaffb2..ea53c584f 100644
--- a/kornia/feature/lightglue.py
+++ b/kornia/feature/lightglue.py
@@ -466,9 +466,29 @@ class LightGlue(nn.Module):
LightGlue is a deep network that matches local features across image pairs
using a series of transformer layers and an adaptive pruning mechanism.
+ Convention:
+ - The ``keypoints`` of each image are ``(x, y)`` pixels and ``image_size`` is ``(W, H)``; an ``image``
+ tensor gives the size from its last two dimensions instead. ``forward`` normalises the keypoints to
+ ``(k - size / 2) / (max(size) / 2)``, as the reference implementation does, and raises for a keypoint
+ outside :math:`[-1, 1]` after that.
+ - The ``"sift"``, ``"doghardnet"`` and ``"dog_affnet_hardnet"`` configurations, which set ``add_scale_ori``,
+ also read ``scales`` and ``oris`` (radians) of each image; the last two multiply ``scales`` by their
+ ``scale_coef`` of 1/6 first, so they take the LAF scale. ``"keynet_affnet_hardnet"``, which sets ``add_laf``,
+ reads ``lafs``. :class:`~kornia.feature.LightGlueMatcher` builds them from LAFs.
+ - The matching scores, ``matching_scores0``, ``matching_scores1`` and ``scores``, are in the dtype of the
+ descriptors. With ``mp=True``, float32 descriptors give scores in the dtype autocast computes them in
+ instead: bfloat16 on CPU, float32 on CUDA and MPS. An image without descriptors runs no layer, and its zero
+ scores keep the descriptor dtype, also with ``mp=True``.
+ - Known defects: with ``mp=True`` on CPU, a configuration whose ``input_dim`` equals ``descriptor_dim``, such
+ as ``"superpoint"``, ``"dedodeb"`` and ``"dedodeg"``, gives float32 zero scores when point pruning removes
+ every point, and bfloat16 scores otherwise (`#5877 <https://github.com/kornia/kornia/issues/5877>`_).
+
Args:
- features: The type of local features to match (e.g., 'superpoint', 'disk').
- conf: A configuration dictionary to override default parameters.
+ 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.
+ **conf: keyword arguments that override entries of ``default_conf``, such as ``filter_threshold``; the
+ configuration of ``features`` is applied after them and wins where both set a key.
"""
default_conf: ClassVar[Dict[str, Any]] = {
@@ -685,10 +705,14 @@ class LightGlue(nn.Module):
keypoints: [B x M x 2]
descriptors: [B x M x D]
image: [B x C x H x W] or image_size: [B x 2]
+ scales, oris: [B x M], with add_scale_ori
+ lafs: [B x M x 2 x 3], with add_laf
image1: dict
keypoints: [B x N x 2]
descriptors: [B x N x D]
image: [B x C x H x W] or image_size: [B x 2]
+ scales, oris: [B x N], with add_scale_ori
+ lafs: [B x N x 2 x 3], with add_laf
Output (dict):
log_assignment: [B x M+1 x N+1]
matches0: [B x M]
@@ -696,6 +720,7 @@ class LightGlue(nn.Module):
matches1: [B x N]
matching_scores1: [B x N]
matches: List[[Si x 2]], scores: List[[Si]]
+ stop, prune0, prune1: diagnostics of early stopping and point pruning
"""
device_type = data["image0"]["keypoints"].device.type
with torch.autocast(enabled=self.conf.mp, device_type=device_type):
@@ -931,8 +956,8 @@ class LightGlue(nn.Module):
device: Torch device on which descriptors are processed.
Returns:
- Minimum number of keypoints required for width pruning on that device.
- A negative value disables pruning for the device.
+ With point pruning enabled, it runs on an image while the image has more keypoints than this number,
+ so ``-1`` means always.
"""
if self.conf.flash and device.type == "cuda":
return self.pruning_keypoint_thresholds["flash"]
diff --git a/kornia/feature/lightglue_onnx/lightglue.py b/kornia/feature/lightglue_onnx/lightglue.py
index 0821fb711..c585faa27 100644
--- a/kornia/feature/lightglue_onnx/lightglue.py
+++ b/kornia/feature/lightglue_onnx/lightglue.py
@@ -47,11 +47,19 @@ class OnnxLightGlue:
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.
+ Convention:
+ - See the Convention block on :class:`~kornia.feature.LightGlue`: the keypoints are normalised the same way,
+ 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 defects: ``device=None`` raises a ``TypeError``, although the signature allows ``None``
+ (`#5850 <https://github.com/kornia/kornia/issues/5850>`_).
+
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: Union[str, torch.device, None] to run inference on.
+ device: ``'cpu'`` or ``'cuda'`` to run inference on; another device raises ``ValueError``.
"""
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index cdfbffd33..b1daa8c04 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -83,15 +83,20 @@ class LoFTR(nn.Module):
This is based on the original code from paper "LoFTR: Detector-Free Local
Feature Matching with Transformers". See :cite:`LoFTR2021` for more details.
- With the default ``config``, whose ``resolution`` (8, 2) every pretrained model uses, the two images can differ in
- size, and their heights and widths do not need to be multiples of 8 (the reference implementation expects
- multiples of 8). ``keypoints0`` lie on the grid of the 1/8-resolution coarse feature map, at ``8 * (column, row)``
- of a coarse cell, and ``keypoints1`` are refined to sub-pixel positions. Both are :math:`(x, y)` in the frame where
- the centre of pixel :math:`(x, y)` is at :math:`(x + 0.5, y + 0.5)`, as in the reference implementation: subtract
- 0.5 to get kornia's frame, in which pixel centres have integer coordinates. With ``resolution`` (16, 4) in
- ``config``, ``keypoints0`` lie on a 16-pixel grid, and most sizes that are not multiples of 16 raise an error.
-
- If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.
+ Convention:
+ - ``image0`` and ``image1`` are grayscale :math:`(N, 1, H, W)` images in :math:`[0, 1]`, the input of the
+ pretrained models. With the default ``config``, whose ``resolution`` (8, 2) every pretrained model uses,
+ the two images can differ in size, and their heights and widths do not need to be multiples of 8 (the
+ reference implementation expects multiples of 8).
+ - With that ``resolution``, ``keypoints0`` lie on the grid of the 1/8-resolution coarse feature map, at
+ ``8 * (column, row)`` of a coarse cell, and ``keypoints1`` at ``8 * (column, row)`` of the matching cell of
+ image1 plus the offset found by the fine stage, at most 4 pixels along each axis. Both are :math:`(x, y)` in
+ the frame of the reference implementation, in which the pretrained models put the centre of pixel
+ :math:`(x, y)` at :math:`(x + 0.5, y + 0.5)`: subtract 0.5 to get kornia's frame
+ (:func:`~kornia.feature.laf_from_center_scale_ori`), in which pixel centres have integer coordinates.
+ - ``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.
Args:
config: Dict with initialization parameters. Do not pass it, unless you know what you are doing.
@@ -99,7 +104,8 @@ class LoFTR(nn.Module):
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
- to ``temp_bug_fix=True``, which is what its checkpoint was trained with.
+ to ``temp_bug_fix=True``, which is what its checkpoint was trained with. ``None`` loads no
+ weights.
Returns:
Dictionary with image correspondences and confidence scores.
@@ -155,8 +161,8 @@ class LoFTR(nn.Module):
Returns:
- ``keypoints0``, matching keypoints from image0 :math:`(NC, 2)`.
- ``keypoints1``, matching keypoints from image1 :math:`(NC, 2)`.
- - ``confidence``, confidence score [0, 1] :math:`(NC)`.
- - ``batch_indexes``, batch indexes for the keypoints and lafs :math:`(NC)`.
+ - ``confidence``, the coarse matching score, see the Convention block :math:`(NC)`.
+ - ``batch_indexes``, batch index of each match :math:`(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 4ff4161a5..9871f5b27 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -102,7 +102,35 @@ def match_nn(
) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Find nearest neighbors in desc2 for each vector in desc1.
- If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.
+ Convention:
+ - Every ``match_*`` function returns ``(dists, idxs)``, one row per match. ``idxs`` is an int64
+ :math:`(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 :math:`(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:
+
+ - :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.
+ - :func:`match_smnn`, :func:`match_smnn_batched`: the larger of the two ratios, desc1 to desc2 and back.
+ - :func:`match_fginn`: the ratio of the nearest distance to that of a second neighbour, taken among the 10
+ nearest, whose ``lafs2`` centre lies at least ``spatial_th`` from the nearest one's, and 0 without one;
+ see its Convention block.
+ - :func:`match_adalam`: the inverse of the local RANSAC confidence; see its Convention block.
+
+ :class:`~kornia.feature.LightGlueMatcher` returns LightGlue's matching score in the place of ``dists``,
+ which is higher for better matches, and :class:`~kornia.feature.LocalFeatureMatcher` reports
+ ``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. 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``.
+ - An empty desc1 or desc2 gives a :math:`(0, 1)` and a :math:`(0, 2)` tensor (:math:`(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`,
+ :func:`match_smnn_batched` and :func:`match_adalam`, which scores its putative matches by the same ratio,
+ need two rows in both.
Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
@@ -131,7 +159,9 @@ def match_mnn(
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Find mutual nearest neighbors in desc2 for each vector in desc1.
- If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.
+ 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.
Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
@@ -140,7 +170,7 @@ def match_mnn(
to each descriptor in desc2, shape of :math:`(B1, B2)`.
Return:
- - Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)`.
+ - Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- Long torch.Tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B3, 2)`,
where 0 <= B3 <= min(B1, B2)
@@ -173,7 +203,9 @@ def match_snn(
The method satisfies first to second nearest neighbor distance <= th.
- If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.
+ Convention:
+ See the Convention block on :func:`match_nn`; ``dists`` is the ratio of the nearest to the second-nearest
+ distance.
Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
@@ -183,7 +215,7 @@ def match_snn(
to each descriptor in desc2, shape of :math:`(B1, B2)`.
Return:
- - Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
+ - Ratio of the nearest to the second-nearest distance of each match, shape of :math:`(B3, 1)`.
- Long torch.Tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
where 0 <= B3 <= B1.
@@ -213,7 +245,11 @@ def match_smnn(
the method satisfies first to second nearest neighbor distance <= th.
- If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.
+ Convention:
+ - See the Convention block on :func:`match_nn`. A pair is kept when the two descriptors are mutual nearest
+ neighbours and pass the ratio test, ``ratio <= th``, in both directions; ``dists`` is the larger of the
+ two ratios.
+ - ``th`` defaults to 0.95, where :func:`match_snn` and :func:`match_fginn` default to 0.8.
Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
@@ -223,7 +259,7 @@ def match_smnn(
to each descriptor in desc2, shape of :math:`(B1, B2)`.
Return:
- - Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)`.
+ - The larger of the two distance ratios of each match, shape of :math:`(B3, 1)`.
- Long torch.Tensor indexes of matching descriptors in desc1 and desc2,
shape of :math:`(B3, 2)` where 0 <= B3 <= B1.
@@ -268,6 +304,13 @@ def match_smnn_batched(
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.
+ 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
+ slightly from those of :func:`match_smnn` on the half-precision descriptors.
+
Args:
desc1: First descriptors, shape :math:`(B, N, D)`.
desc2: Second descriptors, shape :math:`(B, M, D)`.
@@ -288,10 +331,8 @@ def match_smnn_batched(
descriptor counts and limit batch size when matching large collections.
Half-precision descriptors use float32 distance computation before ratios
are converted back to the input dtype.
- Masked inputs use ``torch.cdist``'s direct Euclidean path to avoid the
- cancellation possible in its matrix-multiplication implementation. This
- can be slower for large masked descriptor sets; unmasked inputs retain
- the default small-input direct path and large-input matrix implementation.
+ Masked inputs compute the distances directly, without the matrix-multiplication
+ form, which avoids its cancellation but can be slower for large masked descriptor sets.
As in :func:`match_smnn`, a zero second-neighbor distance produces an
undefined ratio and that ambiguous match is rejected. Ties follow
:func:`torch.topk` and do not have a guaranteed cross-device ordering.
@@ -393,14 +434,16 @@ def match_fginn(
and assures 2nd nearest neighbor is geometrically inconsistent with the 1st one
(see :cite:`MODS2015` for more details)
- If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.
-
- .. note::
- The geometric check looks at the ``min(10, B2)`` nearest candidates and excludes every one of them
- that lies within ``spatial_th`` pixels of the query's own 1st nearest neighbor. When *all* of them do --
- a dense cluster of detections on one structure -- no candidate is left to be the 2nd nearest neighbor, the
- ratio is 0 and the match is **accepted**. That is the intended reading: no distinct competing structure among
- the candidates means the 1st nearest neighbor is unambiguous.
+ Convention:
+ - See the Convention block on :func:`match_nn`. ``dists`` is a ratio: the nearest distance over the distance
+ of the second neighbour, which is the nearest of the ``min(10, B2)`` nearest candidates, the first one
+ excluded, whose ``lafs2`` centre lies at least ``spatial_th`` from the centre of the first one. Candidates
+ closer than that count as the same structure, not as competitors, whatever their descriptor distance. When
+ all of them are -- a dense cluster of detections on one structure -- the ratio is 0 and the match is
+ **accepted**: no distinct competing structure among the candidates means the nearest neighbour is
+ unambiguous. A descriptor beyond the ``min(10, B2)`` nearest is never the second neighbour, even when every
+ candidate is excluded.
+ - Only the centres of ``lafs2`` are read, and ``spatial_th`` is in their units: pixels for LAFs in pixels.
Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
@@ -410,13 +453,15 @@ def match_fginn(
``lafs2`` feeds the geometric check.
lafs2: LAFs of a shape :math:`(1, B2, 2, 3)`.
th: distance ratio threshold.
- spatial_th: minimal distance in pixels to 2nd nearest neighbor.
+ spatial_th: minimal distance between the ``lafs2`` centres of the 1st and the 2nd nearest neighbor, in the
+ units of those centres.
mutual: also perform mutual nearest neighbor check.
dm: torch.Tensor containing the distances from each descriptor in desc1
to each descriptor in desc2, shape of :math:`(B1, B2)`.
Return:
- - Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
+ - Ratio of the nearest to the second-neighbour distance of each match, see the Convention block, shape of
+ :math:`(B3, 1)`.
- Long torch.Tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
where 0 <= B3 <= B1.
@@ -470,9 +515,15 @@ class DescriptorMatcher(nn.Module):
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.
+ Convention:
+ See the Convention block on :func:`~kornia.feature.match_nn`. ``forward`` returns what the function of
+ ``match_mode`` (case-insensitive) returns for the two descriptor sets, with the module's ``th`` for ``snn``
+ and ``smnn``. ``th`` defaults to 0.8 for both, while :func:`~kornia.feature.match_smnn` defaults to 0.95,
+ and ``nn`` and ``mnn`` do not read it. There is no ``dm``.
+
Args:
match_mode: type of matching, can be `nn`, `snn`, `mnn`, `smnn`.
- th: threshold on distance ratio, or other quality measure.
+ th: distance ratio threshold of the `snn` and `smnn` modes.
"""
@@ -493,7 +544,7 @@ class DescriptorMatcher(nn.Module):
desc2: Batch of descriptors of a shape :math:`(B2, D)`.
Returns:
- - Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
+ - ``dists`` of the matching function, see :func:`~kornia.feature.match_nn`, shape of :math:`(B3, 1)`.
- Long torch.Tensor indexes of matching descriptors in desc1 and desc2,
shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`.
@@ -685,6 +736,15 @@ class GeometryAwareDescriptorMatcher(nn.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.
+ Convention:
+ See the Convention block on :func:`~kornia.feature.match_nn`. ``forward`` returns what the function of
+ ``match_mode`` (case-insensitive) returns:
+
+ - ``"fginn"`` reads the keys ``th``, ``spatial_th`` and ``mutual`` of ``params`` and ignores any other key.
+ ``th`` defaults to 0.85, while :func:`~kornia.feature.match_fginn` defaults to 0.8.
+ - ``"adalam"`` passes ``params`` as the AdaLAM ``config``, and no ``hw1`` or ``hw2``, so AdaLAM takes the
+ extent of each image's keypoints as the image size.
+
Args:
match_mode: type of matching, can be `fginn` or `adalam`.
params: dictionary of parameters for the matching function.
@@ -713,7 +773,7 @@ class GeometryAwareDescriptorMatcher(nn.Module):
lafs2: LAFs of a shape :math:`(1, B2, 2, 3)`.
Returns:
- - Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
+ - ``dists`` of the matching function, see :func:`~kornia.feature.match_nn`, shape of :math:`(B3, 1)`.
- Long torch.Tensor indexes of matching descriptors in desc1 and desc2,
shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`.
diff --git a/tests/feature/test_lightglue.py b/tests/feature/test_lightglue.py
index a3098de17..38691591a 100644
--- a/tests/feature/test_lightglue.py
+++ b/tests/feature/test_lightglue.py
@@ -20,6 +20,8 @@ import unittest.mock
import pytest
import torch
+from kornia.feature.integrated import LightGlueMatcher
+from kornia.feature.laf import laf_from_center_scale_ori
from kornia.feature.lightglue import (
Attention,
LearnableFourierPositionalEncoding,
@@ -667,3 +669,213 @@ class TestLightGluePruningDtype(BaseTester):
assert (out[key] == 0).all()
assert out["scores"][0].dtype == score_dtype
assert out["scores"][0].shape == (0,)
+
+
+class _PositionalEncodingInputs(Exception):
+ """Ends a forward pass once both images' keypoint encodings have been recorded."""
+
+
+class TestConventionsLightGlue(BaseTester):
+ # The positional-encoding inputs of image 0 and image 1 for the frames of `_matcher_lafs`, generated in float64
+ # from x' = (x - W / 2) / (max(H, W) / 2), y' = (y - H / 2) / (max(H, W) / 2), scale = sqrt(|det A|),
+ # orientation = atan2(a01, a00) (radians), and the normalised points c + A[:, 0] and c + A[:, 1] for keynet.
+ _XY = {
+ (200, 320): [[-0.625, -0.475], [0.5625, 0.4375], [-0.36875, -0.41875]],
+ (240, 300): [[-0.6, -0.64], [0.666667, 0.333333], [-0.326667, -0.58]],
+ }
+ _SIXTH_OF_SCALE = [2.0, 1.25, 1.683251]
+ _NEGATED_ORI = [-0.785398, 2.094395, -0.380506] # in (-pi, pi]
+ _ORI = [0.785398, 4.188790, 0.380506] # in [0, 2 pi)
+ _AXIS_POINTS = {
+ (200, 320): [
+ [-0.571967, -0.528033, -0.571967, -0.421967],
+ [0.539062, 0.478095, 0.521905, 0.414062],
+ [-0.30625, -0.4375, -0.34375, -0.3625],
+ ],
+ (240, 300): [
+ [-0.543431, -0.696569, -0.543431, -0.583431],
+ [0.641667, 0.376635, 0.623365, 0.308333],
+ [-0.26, -0.6, -0.3, -0.52],
+ ],
+ }
+
+ @staticmethod
+ def _record_positional_encoding_inputs(lightglue):
+ seen = []
+
+ def hook(module, args):
+ seen.append(args[0].detach().clone())
+ if len(seen) == 2:
+ raise _PositionalEncodingInputs
+
+ lightglue.posenc.register_forward_pre_hook(hook)
+ return seen
+
+ @staticmethod
+ def _matcher_lafs(device, dtype):
+ # two rotated frames (scale 12 at 45 degrees, 7.5 at -120 degrees) and a sheared one (a01 != a10), centres
+ # off the diagonal
+ rotated = laf_from_center_scale_ori(
+ torch.tensor([[[60.0, 24.0], [250.0, 170.0]]]),
+ torch.tensor([12.0, 7.5]).view(1, 2, 1, 1),
+ torch.tensor([45.0, -120.0]).view(1, 2, 1),
+ )
+ sheared = torch.tensor([[[[10.0, 4.0, 101.0], [-3.0, 9.0, 33.0]]]])
+ return torch.cat([rotated, sheared], 1).to(device, dtype)
+
+ def _expected_encoding_input(self, feature_name, hw, device, dtype):
+ columns = [torch.tensor(self._XY[hw])]
+ if feature_name == "sift":
+ columns += [torch.tensor(self._SIXTH_OF_SCALE)[:, None], torch.tensor(self._NEGATED_ORI)[:, None]]
+ elif feature_name in ("doghardnet", "dog_affnet_hardnet"):
+ columns += [torch.tensor(self._SIXTH_OF_SCALE)[:, None], torch.tensor(self._ORI)[:, None]]
+ elif feature_name == "keynet_affnet_hardnet":
+ columns += [torch.tensor(self._AXIS_POINTS[hw])]
+ return torch.cat(columns, 1)[None].to(device, dtype)
+
+ def test_convention_lightglue_image_size_is_width_height(self, device, dtype):
+ lg = LightGlue(None, input_dim=8, descriptor_dim=8, n_layers=1, num_heads=1, flash=False)
+ lg = lg.to(device, dtype).eval()
+ seen = self._record_positional_encoding_inputs(lg)
+ kpts = torch.tensor([[[300.0, 30.0], [20.0, 210.0], [160.0, 120.0]]], device=device, dtype=dtype)
+ desc = torch.rand(2, 3, 8, device=device, dtype=dtype)
+ # image 0: batch item 1 is item 0 transposed, keypoints and (W, H) size alike, so each item needs its own size
+ size = torch.tensor([[320, 240], [240, 320]], device=device)
+ # image 1: an image tensor gives the size (W, H) = (320, 240) from its last two dimensions
+ image = torch.zeros(2, 1, 240, 320, device=device, dtype=dtype)
+ with pytest.raises(_PositionalEncodingInputs):
+ lg(
+ {
+ "image0": {"keypoints": torch.cat([kpts, kpts.flip(-1)]), "descriptors": desc, "image_size": size},
+ "image1": {"keypoints": torch.cat([kpts, kpts]), "descriptors": desc, "image": image},
+ }
+ )
+ # (k - size / 2) / (max(size) / 2): x = (300 - 160) / 160, y = (30 - 120) / 160, and so on; the transposed item
+ # gives the swapped coordinates
+ expected = torch.tensor([[[0.875, -0.5625], [-0.875, 0.5625], [0.0, 0.0]]], device=device, dtype=dtype)
+ self.assert_close(seen[0], torch.cat([expected, expected.flip(-1)]))
+ self.assert_close(seen[1], torch.cat([expected, expected]))
+
+ @pytest.mark.parametrize("feature_name", LightGlueMatcher.known_modes)
+ def test_convention_lightglue_matcher_gives_each_feature_type_its_keypoint_convention(
+ self, device, dtype, feature_name, monkeypatch
+ ):
+ # A random-weight LightGlue with the feature type's configuration: the weights are not downloaded.
+ monkeypatch.setattr("kornia.feature.lightglue.load_state_dict_from_url", lambda *args, **kwargs: {})
+ matcher = LightGlueMatcher(feature_name, {"n_layers": 1}).to(device, dtype).eval()
+ seen = self._record_positional_encoding_inputs(matcher.matcher)
+ lafs = self._matcher_lafs(device, dtype)
+ perm = [2, 0, 1]
+ desc = torch.rand(3, matcher.matcher.conf.input_dim, device=device, dtype=dtype)
+ # hw1 and hw2 are (H, W) and apply to their own image; image 1 holds the frames in another order
+ with pytest.raises(_PositionalEncodingInputs):
+ matcher(desc, desc[perm], lafs, lafs[:, perm], hw1=(200, 320), hw2=(240, 300))
+ # Every type gets the normalised centres. sift adds sigma of a 6-sigma frame (LAF scale / 6) and the negated
+ # LAF orientation in (-pi, pi]; doghardnet and dog_affnet_hardnet add LAF scale / 6 and the LAF orientation
+ # in [0, 2 pi); keynet_affnet_hardnet adds the normalised ends of the LAF axes.
+ self.assert_close(seen[0], self._expected_encoding_input(feature_name, (200, 320), device, dtype))
+ self.assert_close(seen[1], self._expected_encoding_input(feature_name, (240, 300), device, dtype)[:, perm])
+
+ def test_convention_lightglue_matcher_without_hw_takes_the_largest_keypoint_coordinates(
+ self, device, dtype, monkeypatch
+ ):
+ monkeypatch.setattr("kornia.feature.lightglue.load_state_dict_from_url", lambda *args, **kwargs: {})
+ matcher = LightGlueMatcher("disk", {"n_layers": 1}).to(device, dtype).eval()
+ seen = self._record_positional_encoding_inputs(matcher.matcher)
+ lafs = self._matcher_lafs(device, dtype)
+ desc = torch.rand(3, 128, device=device, dtype=dtype)
+ with pytest.raises(_PositionalEncodingInputs):
+ matcher(desc, desc[[0, 2]], lafs, lafs[:, [0, 2]])
+ # The image size is (max x, max y) of each image's keypoints: (250, 170), then (101, 33).
+ expected0 = torch.tensor([[[-0.52, -0.488], [1.0, 0.68], [-0.192, -0.416]]], device=device, dtype=dtype)
+ expected1 = torch.tensor([[[0.188119, 0.148515], [1.0, 0.326733]]], device=device, dtype=dtype)
+ self.assert_close(seen[0], expected0)
+ self.assert_close(seen[1], expected1)
+
+ def test_convention_lightglue_matcher_returns_the_matching_score_and_index_pairs(self, device, dtype, monkeypatch):
+ calls = []
+
+ class _FixedLightGlue(torch.nn.Module):
+ # Stands in for the network: a fixed assignment from image 0 to image 1 and its matching scores.
+ def __init__(self, *args, **kwargs):
+ super().__init__()
+
+ def forward(self, data):
+ calls.append(data)
+ # 0 -> 3, 2 -> 0, 3 -> 2: no pair is its own inverse, so swapped columns give other pairs
+ matches0 = torch.tensor([[3, -1, 0, 2]], device=device)
+ scores0 = torch.tensor([[0.9, 0.0, 0.35, 0.6]], device=device, dtype=dtype)
+ return {"matches0": matches0, "matching_scores0": scores0}
+
+ monkeypatch.setattr("kornia.feature.integrated.LightGlue", _FixedLightGlue)
+ matcher = LightGlueMatcher("DISK")
+ assert matcher.feature_name == "disk" # modes are case-insensitive
+ lafs = laf_from_center_scale_ori(
+ torch.tensor([[[60.0, 24.0], [250.0, 170.0], [101.0, 33.0], [7.0, 140.0]]], device=device, dtype=dtype)
+ )
+ lafs1 = lafs.clone()
+ lafs1[:, 1] = 0.0 # a padding slot
+ desc = torch.rand(4, 128, device=device, dtype=dtype)
+ scores, idxs = matcher(desc, desc, lafs, lafs1, hw1=(200, 320), hw2=(200, 320))
+ # The first value is LightGlue's matching score (higher is better), not a distance; rows are
+ # (index in desc1, index in desc2), and unmatched keypoints (-1) are left out.
+ assert idxs.tolist() == [[0, 3], [2, 0], [3, 2]]
+ self.assert_close(scores, torch.tensor([[0.9], [0.35], [0.6]], device=device, dtype=dtype))
+ # Padding is not filtered: the zero LAF reaches the network as a keypoint at (0, 0).
+ assert calls[0]["image1"]["keypoints"][0, 1].tolist() == [0.0, 0.0]
+ # Fewer than two descriptors on a side give no match without running the network.
+ scores, idxs = matcher(desc[:1], desc, lafs[:, :1], lafs1)
+ assert scores.shape == (0, 1)
+ assert idxs.shape == (0, 2)
+ assert len(calls) == 1
+ # A name outside known_modes is rejected.
+ with pytest.raises(NotImplementedError, match="orb is not supported"):
+ LightGlueMatcher("orb")
+
+ def test_convention_lightglue_features_configuration_wins_over_keyword_arguments(self, device, dtype, monkeypatch):
+ # "disk" sets input_dim, so the keyword argument loses; filter_threshold is not in its configuration, so the
+ # keyword argument stays
+ monkeypatch.setattr("kornia.feature.lightglue.load_state_dict_from_url", lambda *args, **kwargs: {})
+ lg = LightGlue("disk", input_dim=64, filter_threshold=0.3, n_layers=1)
+ assert lg.conf.input_dim == 128
+ assert lg.conf.filter_threshold == 0.3
+
+ def test_wart_lightglue_mixed_precision_cpu_all_pruned_scores_are_float32_5877(self, device, dtype):
+ if device.type != "cpu" or dtype != torch.float32:
+ pytest.skip("mp=True on CPU autocasts a float32 model to bfloat16")
+
+ def score_dtypes(input_dim, matchability):
+ # A constant matchability of +-30 keeps every point or prunes every point at layer 0; no early stop.
+ torch.manual_seed(0)
+ lg = LightGlue(
+ None,
+ input_dim=input_dim,
+ descriptor_dim=16,
+ n_layers=2,
+ num_heads=1,
+ flash=False,
+ mp=True,
+ depth_confidence=-1,
+ )
+ with torch.no_grad():
+ for layer in lg.log_assignment:
+ layer.matchability.weight.zero_()
+ layer.matchability.bias.fill_(matchability)
+ g = torch.Generator().manual_seed(1)
+ data = {
+ "keypoints": torch.rand(1, 6, 2, generator=g) * 100,
+ "descriptors": torch.randn(1, 6, input_dim, generator=g),
+ "image_size": torch.tensor([[100, 100]]),
+ }
+ with torch.no_grad():
+ out = lg.eval()({"image0": data, "image1": dict(data)})
+ # the early return for every point pruned has no log assignment
+ assert ("log_assignment" in out) == (matchability > 0)
+ return {out["matching_scores0"].dtype, out["matching_scores1"].dtype, out["scores"][0].dtype}
+
+ # #5877: with input_dim == descriptor_dim, input_proj is an identity, the descriptors stay float32 through the
+ # layers, and the early return for every point pruned takes float32 from them, while the scores of a pass
+ # that keeps the points are bfloat16. With input_dim != descriptor_dim both paths give bfloat16.
+ assert score_dtypes(16, 30.0) == {torch.bfloat16}
+ assert score_dtypes(16, -30.0) == {torch.float32}
+ assert score_dtypes(8, 30.0) == score_dtypes(8, -30.0) == {torch.bfloat16}
diff --git a/tests/feature/test_lightglue_onnx.py b/tests/feature/test_lightglue_onnx.py
index 95a5a0ce9..552bed3ba 100644
--- a/tests/feature/test_lightglue_onnx.py
+++ b/tests/feature/test_lightglue_onnx.py
@@ -248,3 +248,55 @@ def test_onnx_lightglue_keypoint_range_message_5724():
side = {"keypoints": kpts, "descriptors": desc, "image_size": torch.tensor([[50, 50]])}
with pytest.raises(Exception, match=r"\[-1, 1\].*\(width, height\)"):
model({"image0": side, "image1": side})
+
+
[email protected](ort is None, reason="OnnxLightGlue requires onnxruntime")
+class TestConventionsOnnxLightGlue:
+ @staticmethod
+ def _echo_model(tmp_path):
+ """Write a graph whose scores are the normalised keypoints it receives, flattened, image 0 first."""
+ from onnx import TensorProto, helper, save
+
+ inputs = [
+ helper.make_tensor_value_info(name, TensorProto.FLOAT, [1, count, width])
+ for name, count, width in [("kpts0", "M", 2), ("kpts1", "N", 2), ("desc0", "M", 4), ("desc1", "N", 4)]
+ ]
+ outputs = [
+ helper.make_tensor_value_info("matches0", TensorProto.INT64, [1, 2]),
+ helper.make_tensor_value_info("mscores0", TensorProto.FLOAT, ["S"]),
+ ]
+ nodes = [
+ helper.make_node("Constant", [], ["flat"], value=helper.make_tensor("flat", TensorProto.INT64, [1], [-1])),
+ helper.make_node("Reshape", ["kpts0", "flat"], ["flat0"]),
+ helper.make_node("Reshape", ["kpts1", "flat"], ["flat1"]),
+ helper.make_node("Concat", ["flat0", "flat1"], ["mscores0"], axis=0),
+ helper.make_node(
+ "Constant", [], ["matches0"], value=helper.make_tensor("matches", TensorProto.INT64, [1, 2], [0, 0])
+ ),
+ ]
+ graph = helper.make_graph(nodes, "lightglue_keypoint_echo", inputs, outputs)
+ path = tmp_path / "echo.onnx"
+ save(helper.make_model(graph, opset_imports=[helper.make_opsetid("", 17)], ir_version=8), path)
+ return str(path)
+
+ @pytest.mark.device_agnostic
+ def test_convention_onnx_lightglue_normalises_keypoints_like_lightglue(self, tmp_path, dtype):
+ path = self._echo_model(tmp_path)
+ matcher = OnnxLightGlue(path, device="cpu")
+ kpts = torch.tensor([[[300.0, 30.0], [20.0, 210.0]]], dtype=dtype)
+ desc = torch.zeros(1, 2, 4, dtype=dtype)
+ image0 = {"keypoints": kpts, "descriptors": desc, "image_size": torch.tensor([[320, 240]])}
+ # image 1 is image 0 transposed, given as an image: (W, H) comes from its last two dimensions
+ image1 = {"keypoints": kpts.flip(-1), "descriptors": desc, "image": torch.zeros(1, 3, 320, 240)}
+ if dtype != torch.float32:
+ with pytest.raises(Exception, match="Wrong dtype"): # float32 only
+ matcher({"image0": image0, "image1": image1})
+ return
+ out = matcher({"image0": image0, "image1": image1})
+ # LightGlue's normalisation, (k - size / 2) / (max(size) / 2) with size = (W, H): x = (300 - 160) / 160,
+ # y = (30 - 120) / 160, ...; the transposed image swaps the coordinates
+ expected = torch.tensor([0.875, -0.5625, -0.875, 0.5625, -0.5625, 0.875, 0.5625, -0.875])
+ torch.testing.assert_close(out["scores"], expected)
+ # an unsupported device raises ValueError
+ with pytest.raises(ValueError, match="Unsupported device"):
+ OnnxLightGlue(path, device="meta")
diff --git a/tests/feature/test_loftr.py b/tests/feature/test_loftr.py
index 9881c194c..68e455846 100644
--- a/tests/feature/test_loftr.py
+++ b/tests/feature/test_loftr.py
@@ -774,3 +774,96 @@ class TestLinearAttention(BaseTester):
assert bool(torch.isfinite(grad).all()), grad
self.assert_close(grad.float(), grad32, rtol=0.0, atol=5e-2)
self.assert_close(grads[0][0, [1, 4]], torch.zeros_like(grads[0][0, [1, 4]]), rtol=0.0, atol=0.0)
+
+
+class TestConventionsLoFTR(BaseTester):
+ # Per batch item: a coarse cell (row, column) of image 0 (59 x 85 pixels, 8 x 11 coarse cells), its partner in
+ # image 1 (64 x 74 pixels, 8 x 10 cells), the feature amplitude, and the peak (x, y) of the fine heatmap in the
+ # 5 x 5 window of image 1, whose centre is (2, 2). The cells keep border_rm = 2 cells from the edges.
+ _PAIRS = {
+ 0: [((3, 7), (5, 3), 16.0, (3, 1)), ((5, 2), (2, 6), 16.0, (0, 4)), ((4, 4), (3, 4), 4.0, (2, 2))],
+ 1: [((2, 3), (4, 7), 16.0, (4, 2))],
+ }
+
+ def _hooked_loftr(self, device, dtype, swap):
+ """Return a random-weight LoFTR whose coarse and fine matching inputs are replaced by designed features."""
+ pairs = {
+ b: [((p1, p0, a, peak) if swap else (p0, p1, a, peak)) for p0, p1, a, peak in items]
+ for b, items in self._PAIRS.items()
+ }
+
+ def coarse_features(module, args):
+ # one-hot features: each designed cell is similar to its partner only
+ feat0, feat1, data = args
+ feat0, feat1 = torch.zeros_like(feat0), torch.zeros_like(feat1)
+ w0, w1 = data["hw0_c"][1], data["hw1_c"][1]
+ channel = 0
+ for b, items in pairs.items():
+ for (r0, c0), (r1, c1), amplitude, _ in items:
+ feat0[b, r0 * w0 + c0, channel] = amplitude
+ feat1[b, r1 * w1 + c1, channel] = amplitude
+ channel += 1
+ return feat0, feat1, data
+
+ def fine_features(module, args):
+ # a fine heatmap peaked on the designed cell of each match's window
+ feat0, feat1, data = args
+ feat0, feat1 = torch.zeros_like(feat0), torch.zeros_like(feat1)
+ feat0[:, feat0.shape[1] // 2, 0] = 30.0
+ w0 = data["hw0_c"][1]
+ peaks = {(b, r0 * w0 + c0): peak for b, items in pairs.items() for (r0, c0), _, _, peak in items}
+ for m, (b, i) in enumerate(zip(data["b_ids"].tolist(), data["i_ids"].tolist())):
+ x, y = peaks[(b, i)]
+ feat1[m, y * 5 + x, 0] = 30.0
+ return feat0, feat1, data
+
+ torch.manual_seed(0)
+ model = LoFTR(pretrained=None).to(device, dtype)
+ model.coarse_matching.register_forward_pre_hook(coarse_features)
+ model.fine_matching.register_forward_pre_hook(fine_features)
+ return model
+
+ def test_convention_loftr_keypoints_are_eight_times_the_coarse_cell_plus_the_fine_offset(self, device, dtype):
+ image0 = torch.rand(2, 1, 59, 85, device=device, dtype=dtype)
+ image1 = torch.rand(2, 1, 64, 74, device=device, dtype=dtype)
+ with torch.no_grad():
+ out = self._hooked_loftr(device, dtype, swap=False)({"image0": image0, "image1": image1})
+ # keypoints0 = 8 * (column, row) of the coarse cell. keypoints1 = 8 * (column, row) of the partner plus the
+ # fine offset, 2 px per fine cell: the peaks (3, 1), (0, 4), (4, 2) are (+1, -1), (-2, +2), (+2, 0) cells
+ # from the window centre. kornia converts neither: both stay in the reference implementation's frame, in which
+ # the pretrained models put pixel centres at +0.5 (subtract 0.5 for kornia's frame).
+ expected0 = [[56.0, 24.0], [16.0, 40.0], [24.0, 16.0]]
+ expected1 = [[24.0 + 2.0, 40.0 - 2.0], [48.0 - 4.0, 16.0 + 4.0], [56.0 + 4.0, 32.0]]
+ self.assert_close(out["keypoints0"], torch.tensor(expected0, device=device, dtype=dtype))
+ self.assert_close(out["keypoints1"], torch.tensor(expected1, device=device, dtype=dtype))
+ assert out["batch_indexes"].tolist() == [0, 0, 1]
+ # confidence is the coarse dual-softmax score: similarity 16 * 16 / 256 / 0.1 = 10 against the zero similarity
+ # of the 79 other cells of image 1 and the 87 other cells of image 0. The pair of amplitude 4 (similarity
+ # 0.625) scores about 5e-4, e**0.625 / (e**0.625 + 79) * e**0.625 / (e**0.625 + 87), below thr = 0.2, and is
+ # dropped.
+ confidence = 1.0 / ((1.0 + 79.0 * math.exp(-10.0)) * (1.0 + 87.0 * math.exp(-10.0)))
+ self.assert_close(out["confidence"], torch.full((3,), confidence, device=device, dtype=dtype))
+ # relabelling: with the images swapped the same cell pairs come out with their roles swapped
+ with torch.no_grad():
+ swapped = self._hooked_loftr(device, dtype, swap=True)({"image0": image1, "image1": image0})
+ expected0 = [[48.0, 16.0], [24.0, 40.0], [56.0, 32.0]]
+ expected1 = [[16.0 - 4.0, 40.0 + 4.0], [56.0 + 2.0, 24.0 - 2.0], [24.0 + 4.0, 16.0]]
+ self.assert_close(swapped["keypoints0"], torch.tensor(expected0, device=device, dtype=dtype))
+ self.assert_close(swapped["keypoints1"], torch.tensor(expected1, device=device, dtype=dtype))
+ assert swapped["batch_indexes"].tolist() == [0, 0, 1]
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
+ def test_convention_pretrained_loftr_puts_pixel_centres_at_one_half(self, device, dtype, data):
+ # A 2x bilinear upsampling (align_corners=False) maps x to 2x in the frame where pixel centres sit at i + 0.5,
+ # and to 2x + 0.5 in kornia's frame; the pretrained matches follow the first.
+ loftr = LoFTR("outdoor").to(device, dtype)
+ image0 = data["image0"][..., 60:263, 100:417].to(device, dtype) # 203 x 317, off-centre
+ image1 = F.interpolate(image0, scale_factor=2.0, mode="bilinear", align_corners=False)
+ with torch.no_grad():
+ out = loftr({"image0": image0, "image1": image1})
+ residual = out["keypoints1"].cpu().double() - 2 * out["keypoints0"].cpu().double()
+ inliers = residual.norm(dim=-1) < 3
+ assert inliers.double().mean() > 0.9
+ median = residual[inliers].median(0).values
+ assert median.abs().max() < 0.25, median
diff --git a/tests/feature/test_matching.py b/tests/feature/test_matching.py
index bcc500146..cd05a42f6 100644
--- a/tests/feature/test_matching.py
+++ b/tests/feature/test_matching.py
@@ -23,7 +23,7 @@ import torch
from kornia.core._compat import torch_version_le
from kornia.feature import matching
from kornia.feature.adalam import AdalamFilter, get_adalam_default_config
-from kornia.feature.integrated import LightGlueMatcher
+from kornia.feature.integrated import LightGlueMatcher, LocalFeatureMatcher
from kornia.feature.laf import get_laf_center, get_laf_orientation, get_laf_scale, laf_from_center_scale_ori
from kornia.feature.lightglue import LightGlue
from kornia.feature.matching import (
@@ -1367,3 +1367,452 @@ class TestMatchFGINNSecondNeighbour(BaseTester):
actual = op(desc[:2], desc, lafs1.expand(1, 2, 2, 3), lafs2, 0.8, 10.0, dm=dm)
self.assert_close(actual[0], expected[0])
self.assert_close(actual[1], expected[1])
+
+
+class TestConventionsMatching(BaseTester):
+ # Descriptors with x != y and no tie in any row or column of their distance matrix. Nearest neighbours in _D2:
+ # 0 -> 3, 1 -> 0, 2 -> 0, and row 0 of _D2 is nearest to row 1 of _D1, so 2 -> 0 is not mutual. Squared
+ # distances, torch.cdist(_D1, _D2) ** 2: [[85, 20, 40, 17], [13, 122, 130, 113], [40, 137, 85, 80]].
+ _D1 = ((9.0, 6.0), (0.0, 3.0), (0.0, 6.0))
+ _D2 = ((2.0, 0.0), (11.0, 2.0), (7.0, 12.0), (8.0, 10.0))
+
+ def _descriptors(self, device, dtype):
+ return (
+ torch.tensor(self._D1, device=device, dtype=dtype),
+ torch.tensor(self._D2, device=device, dtype=dtype),
+ )
+
+ @staticmethod
+ def _lafs(centres, device, dtype):
+ # frames with a non-zero orientation; the matchers read their centres only
+ xy = torch.tensor(centres, device=device, dtype=dtype)[None]
+ n = xy.shape[1]
+ ori = torch.tensor([30.0, -70.0, 110.0, 15.0, -160.0][:n], device=device, dtype=dtype).view(1, n, 1)
+ return laf_from_center_scale_ori(xy, torch.full((1, n, 1, 1), 4.0, device=device, dtype=dtype), ori)
+
+ def test_convention_match_snn_returns_the_distance_ratio(self, device, dtype):
+ d1 = torch.tensor([[0.0, 0.0], [10.0, 0.0]], device=device, dtype=dtype)
+ d2 = torch.tensor([[0.0, 0.75], [0.0, -1.0], [10.0, 3.0]], device=device, dtype=dtype)
+ # descriptor 0: nearest 0.75, second 1.0 -> ratio 0.75 (kept at th=0.8);
+ # descriptor 1: nearest 3.0 (index 2), second sqrt(100 + 0.75**2) -> ratio 0.29916
+ nn_dists, nn_idxs = match_nn(d1, d2)
+ snn_dists, snn_idxs = match_snn(d1, d2, 0.8)
+ self.assert_close(nn_dists.flatten(), torch.tensor([0.75, 3.0], device=device, dtype=dtype))
+ self.assert_close(
+ snn_dists.flatten(), torch.tensor([0.75, 3.0 / math.sqrt(100.5625)], device=device, dtype=dtype)
+ )
+ assert nn_idxs.tolist() == snn_idxs.tolist() == [[0, 0], [1, 2]]
+ assert snn_dists.dtype == dtype
+ assert snn_idxs.dtype == torch.long
+ # relabelling: row k of the permuted desc2 is row perm[k], so the second index follows and the ratios stay
+ perm = [2, 0, 1]
+ perm_dists, perm_idxs = match_snn(d1, d2[perm], 0.8)
+ assert perm_idxs.tolist() == [[0, 1], [1, 0]]
+ self.assert_close(perm_dists, snn_dists)
+
+ def test_convention_symmetric_ratio_matchers_return_the_larger_of_both_ratios(self, device, dtype):
+ d1, d2 = self._descriptors(device, dtype)
+ # pair (0, 3): ratio sqrt(17 / 20) from desc1 to desc2, sqrt(17 / 80) back -> the forward one;
+ # pair (1, 0): ratio sqrt(13 / 113) forward, sqrt(13 / 40) back -> the backward one.
+ expected = torch.tensor([[math.sqrt(17 / 20)], [math.sqrt(13 / 40)]], device=device, dtype=dtype)
+ dists, idxs = match_smnn(d1, d2, 0.95)
+ assert idxs.tolist() == [[0, 3], [1, 0]]
+ self.assert_close(dists, expected)
+ # swapping the inputs swaps the index columns and keeps each pair's ratio
+ swapped_dists, swapped_idxs = match_smnn(d2, d1, 0.95)
+ assert swapped_idxs.tolist() == [[0, 1], [3, 0]]
+ self.assert_close(swapped_dists, expected.flip(0))
+ # match_smnn_batched gives the same pairs and ratios per item; item 1 has desc2 permuted (old 3 -> new 0,
+ # old 0 -> new 2)
+ perm = [3, 1, 0, 2]
+ ratios, indices = matching.match_smnn_batched(torch.stack([d1, d1]), torch.stack([d2, d2[perm]]), 0.95)
+ assert indices.tolist() == [[0, 0, 3], [0, 1, 0], [1, 0, 0], [1, 1, 2]]
+ self.assert_close(ratios, torch.cat([expected, expected]))
+
+ @pytest.mark.parametrize("matcher", ["snn", "smnn", "smnn_batched", "fginn"])
+ def test_convention_ratio_thresholds_are_inclusive(self, device, dtype, matcher):
+ # Distance matrices whose ratios are exact in every dtype. First: row 0 has 1 / 2 = 0.5 to its nearest
+ # neighbour, column 0 has 1 / 4 = 0.25 back, row 1 has 3 / 4 = 0.75. Second: the 0.5 is the backward ratio
+ # of the same pair (column 0: 1 / 2) and the forward one is 1 / 4.
+ cases = [[[1.0, 2.0, 5.0], [4.0, 3.0, 6.0]], [[1.0, 4.0, 6.0], [2.0, 3.0, 5.0]]]
+ if matcher in ("snn", "fginn"):
+ cases = cases[:1] # one-directional: no backward ratio
+ desc1 = torch.zeros(2, 4, device=device, dtype=dtype)
+ desc2 = torch.zeros(3, 4, device=device, dtype=dtype)
+ lafs1 = self._lafs([[33.0, 21.0], [91.0, 57.0]], device, dtype)
+ # candidate centres far more than spatial_th apart, so the geometric check changes nothing
+ lafs2 = self._lafs([[30.0, 20.0], [90.0, 55.0], [140.0, 12.0]], device, dtype)
+
+ def run(dm, th):
+ if matcher == "snn":
+ return match_snn(desc1, desc2, th, dm)
+ if matcher == "smnn":
+ return match_smnn(desc1, desc2, th, dm)
+ if matcher == "fginn":
+ return match_fginn(desc1, desc2, lafs1, lafs2, th, 10.0, dm=dm)
+ ratios, indices = matching.match_smnn_batched(desc1[None], desc2[None], th, dm[None])
+ return ratios, indices[:, 1:]
+
+ for rows in cases:
+ dm = torch.tensor(rows, device=device, dtype=dtype)
+ dists, idxs = run(dm, 0.5)
+ assert idxs.tolist() == [[0, 0]] # a ratio equal to th is kept
+ self.assert_close(dists, torch.tensor([[0.5]], device=device, dtype=dtype))
+ assert run(dm, 0.49)[1].shape[0] == 0
+
+ def test_convention_match_mnn_keeps_mutual_nearest_neighbours_only(self, device, dtype):
+ d1, d2 = self._descriptors(device, dtype)
+ assert match_nn(d1, d2)[1].tolist() == [[0, 3], [1, 0], [2, 0]]
+ dists, idxs = match_mnn(d1, d2)
+ # row 0 of desc2 is nearest to row 1 of desc1, so the nearest neighbour 2 -> 0 is dropped
+ assert idxs.tolist() == [[0, 3], [1, 0]]
+ assert idxs.dtype == torch.long
+ self.assert_close(dists, torch.tensor([[math.sqrt(17.0)], [math.sqrt(13.0)]], device=device, dtype=dtype))
+ # relabelling: row k of the permuted desc2 is row perm[k] (old 3 -> new 2, old 0 -> new 1)
+ perm = [2, 0, 3, 1]
+ assert match_mnn(d1, d2[perm])[1].tolist() == [[0, 2], [1, 1]]
+ # swapping the inputs (now more rows in desc1 than in desc2) swaps the index columns; row order is not part
+ # of the contract
+ swapped_dists, swapped_idxs = match_mnn(d2, d1)
+ order = swapped_idxs[:, 0].argsort()
+ assert swapped_idxs[order].tolist() == [[0, 1], [3, 0]]
+ self.assert_close(
+ swapped_dists[order], torch.tensor([[math.sqrt(13.0)], [math.sqrt(17.0)]], device=device, dtype=dtype)
+ )
+
+ def test_convention_matchers_need_one_or_two_descriptors_per_side(self, device, dtype):
+ d1, d2 = self._descriptors(device, dtype)
+ lafs1 = self._lafs([[33.0, 21.0], [91.0, 57.0], [140.0, 70.0]], device, dtype)
+ lafs2 = self._lafs([[30.0, 20.0], [90.0, 55.0], [140.0, 12.0], [5.0, 60.0]], device, dtype)
+ # an empty side, first or second, gives (0, 1) values in the descriptor dtype (float32 for match_adalam) and
+ # (0, 2) int64 indices ((0, 3) for match_smnn_batched)
+ for a, b, lafs_a, lafs_b in ((d1[:0], d2, lafs1[:, :0], lafs2), (d1, d2[:0], lafs1, lafs2[:, :0])):
+ outputs = [(match(a, b), dtype) for match in (match_nn, match_mnn, match_snn, match_smnn)]
+ outputs.append((match_fginn(a, b, lafs_a, lafs_b), dtype))
+ outputs.append((match_adalam(a, b, lafs_a, lafs_b), torch.float32))
+ for (dists, idxs), dists_dtype in outputs:
+ assert dists.shape == (0, 1)
+ assert dists.dtype == dists_dtype
+ assert idxs.shape == (0, 2)
+ assert idxs.dtype == torch.long
+ ratios, indices = matching.match_smnn_batched(a[None], b[None])
+ assert ratios.shape == (0, 1)
+ assert ratios.dtype == dtype
+ assert indices.shape == (0, 3)
+ assert indices.dtype == torch.long
+ # one row in desc2: nn and mnn still match, the ratio tests have no second neighbour
+ assert match_nn(d1, d2[:1])[1].tolist() == [[0, 0], [1, 0], [2, 0]]
+ assert match_mnn(d1, d2[:1])[1].tolist() == [[1, 0]]
+ assert match_snn(d1, d2[:1], 0.95)[1].shape == (0, 2)
+ assert match_fginn(d1, d2[:1], lafs1, lafs2[:, :1], 0.95)[1].shape == (0, 2)
+ assert match_adalam(d1, d2[:1], lafs1, lafs2[:, :1])[1].shape == (0, 2)
+ # one row in desc1: match_snn keeps its match (ratio sqrt(17 / 20) = 0.92), the symmetric tests and AdaLAM
+ # need two rows on both sides
+ assert match_snn(d1[:1], d2, 0.95)[1].tolist() == [[0, 3]]
+ assert match_smnn(d1[:1], d2, 0.95)[1].shape == (0, 2)
+ assert matching.match_smnn_batched(d1[None, :1], d2[None], 0.95)[1].shape == (0, 3)
+ assert match_adalam(d1[:1], d2, lafs1[:, :1], lafs2)[1].shape == (0, 2)
+
+ def test_convention_matchers_read_a_given_distance_matrix_as_it_is(self, device, dtype):
+ d1, d2 = self._descriptors(device, dtype)
+ # squared L2 distances, exact in every dtype: torch.cdist(d1, d2) ** 2
+ dm = torch.tensor(
+ [[85.0, 20.0, 40.0, 17.0], [13.0, 122.0, 130.0, 113.0], [40.0, 137.0, 85.0, 80.0]],
+ device=device,
+ dtype=dtype,
+ )
+ # nn and mnn return the entries of dm
+ nn_dists, nn_idxs = match_nn(d1, d2, dm=dm)
+ assert nn_idxs.tolist() == match_nn(d1, d2)[1].tolist() == [[0, 3], [1, 0], [2, 0]]
+ self.assert_close(nn_dists.flatten(), torch.tensor([17.0, 13.0, 40.0], device=device, dtype=dtype))
+ self.assert_close(match_mnn(d1, d2, dm=dm)[0].flatten(), torch.tensor([17.0, 13.0], device=device, dtype=dtype))
+ # the ratio test takes the ratio of what dm holds: squared distances square the ratio, so th is squared too
+ snn_dists, snn_idxs = match_snn(d1, d2, 0.8**2, dm=dm)
+ assert snn_idxs.tolist() == match_snn(d1, d2, 0.8)[1].tolist() == [[1, 0], [2, 0]]
+ self.assert_close(snn_dists.flatten(), torch.tensor([13 / 113, 40 / 80], device=device, dtype=dtype))
+
+ def test_convention_matcher_modules_have_their_own_threshold_defaults(self, device, dtype):
+ # pair (0, 0): ratio 0.825 forward, 0.825 / sqrt(11.175**2 + 5**2) = 0.067 backward;
+ # pair (1, 2): ratio 4 / sqrt(11.175**2 + 5**2) = 0.32673 forward, 4 / sqrt(144 + 81) backward
+ d1 = torch.tensor([[0.0, 0.0], [12.0, 5.0]], device=device, dtype=dtype)
+ d2 = torch.tensor([[0.825, 0.0], [0.0, -1.0], [12.0, 9.0]], device=device, dtype=dtype)
+ lafs1 = self._lafs([[33.0, 21.0], [91.0, 57.0]], device, dtype)
+ lafs2 = self._lafs([[30.0, 20.0], [90.0, 55.0], [140.0, 12.0]], device, dtype)
+ # DescriptorMatcher uses th = 0.8 in every mode, match_smnn defaults to 0.95
+ assert DescriptorMatcher("smnn")(d1, d2)[1].tolist() == [[1, 2]]
+ assert match_smnn(d1, d2)[1].tolist() == [[0, 0], [1, 2]]
+ # match_snn defaults to 0.8 too, so the two agree
+ assert DescriptorMatcher("snn")(d1, d2)[1].tolist() == match_snn(d1, d2)[1].tolist() == [[1, 2]]
+ # GeometryAwareDescriptorMatcher("fginn") uses th = 0.85, match_fginn defaults to 0.8
+ dists, idxs = GeometryAwareDescriptorMatcher("fginn")(d1, d2, lafs1, lafs2)
+ assert idxs.tolist() == [[0, 0], [1, 2]]
+ self.assert_close(
+ dists.flatten(), torch.tensor([0.825, 4.0 / math.sqrt(149.880625)], device=device, dtype=dtype)
+ )
+ assert match_fginn(d1, d2, lafs1, lafs2)[1].tolist() == [[1, 2]]
+
+ @pytest.mark.parametrize("unit", [1.0, 3.0, 0.25])
+ def test_convention_match_fginn_spatial_th_is_in_the_units_of_the_lafs2_centres(self, device, dtype, unit):
+ # Query 0's candidates lie 5, 10, 25 and 40 away in descriptor space (3-4-5 triangles), so its ratio is
+ # 5 / 10 = 0.5 with candidate 1 as the 2nd neighbour and 5 / 25 = 0.2 when candidate 1 is discarded as a
+ # repeat of candidate 0. Query 1's nearest neighbour is candidate 4 (distance 2), the next candidate 2,
+ # sqrt(25**2 + 13**2) = sqrt(794) away.
+ d1 = torch.tensor([[0.0, 0.0], [40.0, 7.0]], device=device, dtype=dtype)
+ d2 = torch.tensor([[3.0, 4.0], [6.0, 8.0], [15.0, 20.0], [24.0, 32.0], [40.0, 9.0]], device=device, dtype=dtype)
+ # candidate 1's centre exactly spatial_th = 10 from candidate 0's competes; 9.6 away it is discarded
+ for centre1, ratio0 in (((36.0, 28.0), 0.5), ((36.0, 27.5), 0.2)):
+ centres2 = [[30.0, 20.0], list(centre1), [80.0, 50.0], [5.0, 60.0], [120.0, 90.0]]
+ lafs2 = self._lafs([[unit * x, unit * y] for x, y in centres2], device, dtype)
+ lafs1 = self._lafs([[33.0, 21.0], [91.0, 57.0]], device, dtype)
+ dists, idxs = match_fginn(d1, d2, lafs1, lafs2, 0.8, 10.0 * unit)
+ assert idxs.tolist() == [[0, 0], [1, 4]]
+ self.assert_close(
+ dists.flatten(), torch.tensor([ratio0, 2.0 / math.sqrt(794.0)], device=device, dtype=dtype)
+ )
+ # lafs1 is not read
+ other_lafs1 = self._lafs([[7.0, 150.0], [64.0, 3.0]], device, dtype)
+ assert match_fginn(d1, d2, other_lafs1, lafs2, 0.8, 10.0 * unit)[1].tolist() == idxs.tolist()
+ # relabelling: permuting desc2 together with lafs2 (old 0 -> new 2, old 4 -> new 0) moves the indices
+ perm = [4, 2, 0, 3, 1]
+ perm_dists, perm_idxs = match_fginn(d1, d2[perm], lafs1, lafs2[:, perm], 0.8, 10.0 * unit)
+ assert perm_idxs.tolist() == [[0, 2], [1, 0]]
+ self.assert_close(perm_dists, dists)
+
+ def test_convention_match_fginn_takes_the_second_neighbour_among_the_10_nearest(self, device, dtype):
+ # desc2 has 12 rows at distances 1 to 12 from the query. The 10 nearest lie within spatial_th = 10 of the
+ # nearest one's centre, the other two far from it.
+ centres2 = [[100.0 + 0.4 * i, 100.0] for i in range(10)] + [[400.0, 300.0], [10.0, 20.0]]
+ scale = torch.full((1, 12, 1, 1), 4.0, device=device, dtype=dtype)
+ lafs2 = laf_from_center_scale_ori(torch.tensor([centres2], device=device, dtype=dtype), scale)
+ lafs1 = self._lafs([[33.0, 21.0]], device, dtype)
+ desc1 = torch.zeros(1, 2, device=device, dtype=dtype)
+ desc2 = torch.zeros(12, 2, device=device, dtype=dtype)
+ dm = torch.arange(1.0, 13.0, device=device, dtype=dtype)[None]
+ # every candidate is excluded, and the two far rows are not candidates: the ratio is 0 and the match is kept
+ dists, idxs = match_fginn(desc1, desc2, lafs1, lafs2, 0.8, 10.0, dm=dm)
+ assert idxs.tolist() == [[0, 0]]
+ assert dists.tolist() == [[0.0]]
+ # a far row among the 10 nearest (distance 10) is the second neighbour: ratio 1 / 10
+ dm_far = dm.clone()
+ dm_far[0, 9], dm_far[0, 10] = 11.0, 10.0
+ dists, idxs = match_fginn(desc1, desc2, lafs1, lafs2, 0.8, 10.0, dm=dm_far)
+ assert idxs.tolist() == [[0, 0]]
+ self.assert_close(dists, torch.tensor([[0.1]], device=device, dtype=dtype))
+
+ @staticmethod
+ def _oriented_adalam_scene():
+ """``_adalam_scene`` with orientations (degrees) and scales.
+
+ The 400 inliers turn by 10 degrees and grow by 1.2 between the images; the outliers get random values.
+ """
+ d1, d2, lafs1, lafs2, hw = _adalam_scene(torch.device("cpu"))
+ g = torch.Generator().manual_seed(7)
+ n1, n2 = lafs1.shape[1], lafs2.shape[1]
+ ori1 = torch.rand(1, n1, 1, generator=g) * 360.0 - 180.0
+ ori2 = torch.rand(1, n2, 1, generator=g) * 360.0 - 180.0
+ ori2[:, :400] = ori1[:, :400] + 10.0
+ scale1 = torch.rand(1, n1, 1, 1, generator=g) * 12.0 + 4.0
+ scale2 = torch.rand(1, n2, 1, 1, generator=g) * 12.0 + 4.0
+ scale2[:, :400] = 1.2 * scale1[:, :400]
+ # a random per-keypoint scale factor in [1/4, 4]
+ jitter = torch.exp(torch.empty(1, n1, 1, 1).uniform_(-math.log(4.0), math.log(4.0), generator=g))
+ frames1 = (get_laf_center(lafs1), scale1, ori1)
+ frames2 = (get_laf_center(lafs2), scale2, ori2)
+ return d1, d2, frames1, frames2, jitter, hw
+
+ def test_convention_match_adalam_reads_the_orientation_and_scale_change_between_the_images(self, device, dtype):
+ d1, d2, (c1, s1, o1), (c2, s2, o2), jitter, hw = self._oriented_adalam_scene()
+ d1, d2 = d1.to(device, dtype), d2.to(device, dtype)
+
+ def run(frames1, frames2):
+ lafs1 = laf_from_center_scale_ori(*frames1).to(device, dtype)
+ lafs2 = laf_from_center_scale_ori(*frames2).to(device, dtype)
+ return match_adalam(d1, d2, lafs1, lafs2, hw1=hw, hw2=hw)
+
+ quality, idxs = run((c1, s1, o1), (c2, s2, o2))
+ assert len(idxs) > 350
+ # Only the changes between the images are read: negating or shifting both orientations, or scaling both
+ # LAF sets, keeps the inliers' common turn (-10 degrees after negation) and 1.2 scale ratio.
+ for frames1, frames2 in (
+ ((c1, s1, -o1), (c2, s2, -o2)),
+ ((c1, s1, o1 + 37.0), (c2, s2, o2 + 37.0)),
+ ((c1, 3.0 * s1, o1), (c2, 3.0 * s2, o2)),
+ ):
+ other_quality, other_idxs = run(frames1, frames2)
+ assert torch.equal(other_idxs, idxs)
+ self.assert_close(other_quality, quality)
+ # Negating one side breaks the inliers' common turn (orientation_difference_threshold 30 is in degrees),
+ # and per-keypoint scale changes break their common scale ratio.
+ assert len(run((c1, s1, -o1), (c2, s2, o2))[1]) < 0.6 * len(idxs)
+ assert len(run((c1, s1 * jitter, o1), (c2, s2, o2))[1]) < 0.9 * len(idxs)
+
+ def test_convention_match_adalam_returns_float32_inverse_confidences(self, device, dtype):
+ d1, d2, frames1, frames2, _, (h, w) = self._oriented_adalam_scene()
+ d1, d2 = d1.to(device, dtype), d2.to(device, dtype)
+ lafs1 = laf_from_center_scale_ori(*frames1).to(device, dtype)
+ lafs2 = laf_from_center_scale_ori(*frames2).to(device, dtype)
+ quality, idxs = match_adalam(d1, d2, lafs1, lafs2, hw1=(h, w), hw2=(h, w))
+ # the first value is 1 / (local RANSAC confidence) in float32 whatever the descriptor dtype, and a match
+ # needs a confidence of at least min_confidence (default 200)
+ assert quality.dtype == torch.float32
+ assert quality.shape == (len(idxs), 1)
+ assert len(idxs) > 350
+ assert quality.min() > 0
+ assert quality.max() <= 1 / 200
+ quality400, _ = match_adalam(d1, d2, lafs1, lafs2, config={"min_confidence": 400}, hw1=(h, w), hw2=(h, w))
+ assert len(quality400) > 350
+ assert quality400.max() <= 1 / 400
+ # hw1 and hw2 enter only as the image area (the seed radius): (H, W) and (W, H) agree, and sizes of 64 times
+ # the area agree with each other whatever their aspect ratio, while they change the matches
+ assert torch.equal(match_adalam(d1, d2, lafs1, lafs2, hw1=(w, h), hw2=(w, h))[1], idxs)
+ sizes = [(8 * h, 8 * w), (8 * w, 8 * h), (64 * h, w), (h, 64 * w)]
+ larger = [match_adalam(d1, d2, lafs1, lafs2, hw1=size, hw2=size)[1] for size in sizes]
+ assert len(larger[0]) < 0.6 * len(idxs)
+ assert all(torch.equal(other, larger[0]) for other in larger[1:])
+
+ def test_convention_local_feature_matcher_returns_laf_centres_and_one_minus_the_matcher_value(self, device, dtype):
+ class _NotCalled(torch.nn.Module):
+ def forward(self, *args):
+ raise AssertionError("the pre-extracted lafs and descriptors must be used")
+
+ d1, d2 = self._descriptors(device, dtype)
+ pad = torch.tensor([[50.0, 50.0]], device=device, dtype=dtype) # identical in both images
+ lafs_a = self._lafs([[12.5, 40.0], [70.0, 9.0], [33.0, 55.0]], device, dtype)[0]
+ lafs_b = self._lafs([[14.0, 41.0], [71.0, 11.0], [35.0, 52.0], [60.0, 30.0]], device, dtype)[0]
+
+ def slots(lafs, descs, order, pad_slot):
+ # the real features in `order` with an all-zero padding LAF inserted at `pad_slot`
+ lafs, descs = list(lafs[order]), list(descs[order])
+ lafs.insert(pad_slot, torch.zeros_like(lafs[0]))
+ descs.insert(pad_slot, pad[0])
+ return torch.stack(lafs), torch.stack(descs)
+
+ # pair 0: features in order, padding in slot 1 / slot 2; pair 1: image 0 reversed and image 1 permuted
+ lafs0, descs0 = zip(slots(lafs_a, d1, [0, 1, 2], 1), slots(lafs_a, d1, [2, 1, 0], 0))
+ lafs1, descs1 = zip(slots(lafs_b, d2, [0, 1, 2, 3], 2), slots(lafs_b, d2, [3, 0, 2, 1], 4))
+ images = torch.zeros(2, 1, 48, 64, device=device, dtype=dtype)
+ data = {
+ "image0": images,
+ "image1": images,
+ "lafs0": torch.stack(lafs0),
+ "descriptors0": torch.stack(descs0),
+ "lafs1": torch.stack(lafs1),
+ "descriptors1": torch.stack(descs1),
+ }
+ out = LocalFeatureMatcher(_NotCalled(), DescriptorMatcher("snn", 0.8))(data)
+ # On the real features snn keeps desc1 rows 1 and 2, both with desc2 row 0 (ratios sqrt(13 / 113) and
+ # sqrt(40 / 80)); the padding descriptors match each other at distance 0, but zero LAFs are dropped first.
+ r1, r2 = math.sqrt(13 / 113), math.sqrt(40 / 80)
+ expected0 = torch.tensor([[70.0, 9.0], [33.0, 55.0], [33.0, 55.0], [70.0, 9.0]], device=device, dtype=dtype)
+ self.assert_close(out["keypoints0"], expected0)
+ self.assert_close(out["keypoints1"], torch.tensor([[14.0, 41.0]] * 4, device=device, dtype=dtype))
+ self.assert_close(out["confidence"], 1.0 - torch.tensor([r1, r2, r2, r1], device=device, dtype=dtype))
+ assert out["batch_indexes"].tolist() == [0, 0, 1, 1]
+ self.assert_close(out["lafs0"][0], lafs_a[[1, 2, 2, 1]])
+ self.assert_close(out["lafs1"][0], lafs_b[[0, 0, 0, 0]])
+
+ def test_convention_matchers_return_dists_in_the_dtype_of_a_given_dm(self, device, dtype):
+ d1, d2 = self._descriptors(device, dtype)
+ other = torch.float16 if dtype == torch.float32 else torch.float32
+ # torch.cdist(d1, d2) ** 2, exact in every dtype, in a dtype other than that of the descriptors
+ dm = torch.tensor(
+ [[85.0, 20.0, 40.0, 17.0], [13.0, 122.0, 130.0, 113.0], [40.0, 137.0, 85.0, 80.0]],
+ device=device,
+ dtype=other,
+ )
+ for match in (match_nn, match_mnn, match_snn, match_smnn):
+ dists, idxs = match(d1, d2, dm=dm)
+ assert len(idxs) > 0
+ assert dists.dtype == other
+
+ def test_convention_match_adalam_without_seeds_returns_the_squared_ratio_test(self, device, dtype):
+ # 8 keypoints leave no AdaLAM seed, so the matches are those of a ratio test on squared distances,
+ # ratio <= 0.95, and the first value is that ratio (float32), not an inverse confidence
+ g = torch.Generator().manual_seed(9)
+ d1 = torch.nn.functional.normalize(torch.randn(8, 24, generator=g), dim=1)
+ noisy = d1 + 0.6 * torch.randn(8, 24, generator=g)
+ d2 = torch.nn.functional.normalize(noisy, dim=1)[torch.randperm(8, generator=g)]
+ frames = [
+ laf_from_center_scale_ori(
+ torch.rand(1, 8, 2, generator=g) * torch.tensor([300.0, 170.0]) + 5.0,
+ torch.full((1, 8, 1, 1), 5.0),
+ torch.rand(1, 8, 1, generator=g) * 90.0,
+ )
+ for _ in range(2)
+ ]
+ d1, d2 = d1.to(device, dtype), d2.to(device, dtype)
+ lafs1, lafs2 = (f.to(device, dtype) for f in frames)
+ quality, idxs = match_adalam(d1, d2, lafs1, lafs2, hw1=(180, 310), hw2=(180, 310))
+ vals, nearest = (torch.cdist(d1.float(), d2.float()) ** 2).topk(2, dim=1, largest=False)
+ ratio = vals[:, 0] / vals[:, 1]
+ keep = ratio <= 0.95
+ assert 0 < int(keep.sum()) < 8
+ assert idxs.tolist() == torch.stack([torch.where(keep)[0], nearest[keep, 0]], 1).tolist()
+ assert quality.dtype == torch.float32
+ self.assert_close(quality.flatten(), ratio[keep], rtol=1e-5, atol=1e-5)
+
+ def test_convention_match_adalam_ignores_a_common_rotation_or_scaling_of_one_image(self, device, dtype):
+ d1, d2, (c1, s1, o1), (c2, s2, o2), _, hw = self._oriented_adalam_scene()
+ d1, d2 = d1.to(device, dtype), d2.to(device, dtype)
+
+ def run(frames1, frames2):
+ lafs1 = laf_from_center_scale_ori(*frames1).to(device, dtype)
+ lafs2 = laf_from_center_scale_ori(*frames2).to(device, dtype)
+ return match_adalam(d1, d2, lafs1, lafs2, hw1=hw, hw2=hw)
+
+ quality, idxs = run((c1, s1, o1), (c2, s2, o2))
+ assert len(idxs) > 350
+ # Turning or scaling the LAFs of one image alike changes the orientation change or the scale ratio of every
+ # match by the same amount, so the inliers stay consistent with each other although their common turn of
+ # 10 degrees becomes -113 or -90 degrees and their scale ratio of 1.2 becomes 0.48 or 0.4.
+ for frames1, frames2 in (
+ ((c1, s1, o1), (c2, 0.4 * s2, o2 - 123.0)),
+ ((c1, 3.0 * s1, o1 + 100.0), (c2, s2, o2)),
+ ):
+ other_quality, other_idxs = run(frames1, frames2)
+ assert torch.equal(other_idxs, idxs)
+ self.assert_close(other_quality, quality)
+
+ def test_convention_match_adalam_warns_about_an_unknown_config_key_and_ignores_it(self, device, dtype):
+ d1, d2, frames1, frames2, _, hw = self._oriented_adalam_scene()
+ d1, d2 = d1.to(device, dtype), d2.to(device, dtype)
+ lafs1 = laf_from_center_scale_ori(*frames1).to(device, dtype)
+ lafs2 = laf_from_center_scale_ori(*frames2).to(device, dtype)
+ quality, idxs = match_adalam(d1, d2, lafs1, lafs2, hw1=hw, hw2=hw)
+ # "mnn" is not read from the configuration either
+ for key in ("foo", "mnn"):
+ with pytest.warns(UserWarning, match=rf"not recognized \({key}\)"):
+ other_quality, other_idxs = match_adalam(d1, d2, lafs1, lafs2, config={key: 1}, hw1=hw, hw2=hw)
+ assert torch.equal(other_idxs, idxs)
+ self.assert_close(other_quality, quality)
+
+ def test_convention_match_adalam_reads_each_image_size_for_its_own_image(self, device, dtype):
+ d1, d2, frames1, frames2, _, (h, w) = self._oriented_adalam_scene()
+ d1, d2 = d1.to(device, dtype), d2.to(device, dtype)
+ lafs1 = laf_from_center_scale_ori(*frames1).to(device, dtype)
+ lafs2 = laf_from_center_scale_ori(*frames2).to(device, dtype)
+ idxs = match_adalam(d1, d2, lafs1, lafs2, hw1=(h, w), hw2=(h, w))[1]
+ # The area of each image sets the neighbourhood radius in that image: a smaller second image alone, or a
+ # smaller first image alone, changes the matches, and (H, W) and (W, H) of that size agree.
+ smaller2 = match_adalam(d1, d2, lafs1, lafs2, hw1=(h, w), hw2=(h // 2, w // 2))[1]
+ assert 0 < len(smaller2) < 0.9 * len(idxs)
+ assert torch.equal(match_adalam(d1, d2, lafs1, lafs2, hw1=(h, w), hw2=(w // 2, h // 2))[1], smaller2)
+ smaller1 = match_adalam(d1, d2, lafs1, lafs2, hw1=(h // 3, w // 3), hw2=(h, w))[1]
+ assert 0 < len(smaller1) < 0.9 * len(idxs)
+ assert torch.equal(match_adalam(d1, d2, lafs1, lafs2, hw1=(w // 3, h // 3), hw2=(h, w))[1], smaller1)
+
+ def test_wart_match_adalam_rejects_exact_correspondences_5866(self, device, dtype):
+ d1, _, (c1, s1, o1), _, _, hw = self._oriented_adalam_scene()
+ desc = d1.to(device, dtype)
+ lafs = laf_from_center_scale_ori(c1, s1, o1).to(device, dtype)
+ # #5866: the local RANSACs give residuals at or near zero no inlier weight, so an image matched against itself
+ # keeps no match whenever a seed survives, while the same keypoints moved by about 0.1 px in the second image
+ # keep nearly all of them
+ exact = match_adalam(desc, desc, lafs, lafs, hw1=hw, hw2=hw)[1]
+ assert len(exact) == 0
+ shift = torch.randn(c1.shape, generator=torch.Generator().manual_seed(11)) * 0.1
+ moved = laf_from_center_scale_ori(c1 + shift, s1, o1).to(device, dtype)
+ assert len(match_adalam(desc, desc, lafs, moved, hw1=hw, hw2=hw)[1]) > 0.95 * len(desc)
+ # With 8 keypoints no seed survives, so the ratio-test fallback runs and matches each keypoint to itself.
+ few = match_adalam(desc[:8], desc[:8], lafs[:, :8], lafs[:, :8], hw1=hw, hw2=hw)[1]
+ assert few.tolist() == [[i, i] for i in range(8)]