π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): AdaLAM reports the best confidence of duplicated matches; LightGlueMatcher xfeat and raco-aliked modes (#6428)
Dmytro Mishkin37aa6b7f480f
diff --git a/changelog.d/6428.added.md b/changelog.d/6428.added.mdnew file mode 100644index 000000000..dfe2d6422--- /dev/null+++ b/changelog.d/6428.added.md@@ -0,0 +1 @@+`LightGlueMatcher` accepts the `"xfeat"` and `"raco-aliked"` modes, whose weights `LightGlue` already loads. With `"xfeat"`, pass the descriptors of `XFeat.detectAndCompute` and LAFs centred on its keypoints.diff --git a/changelog.d/6428.fixed.md b/changelog.d/6428.fixed.mdnew file mode 100644index 000000000..2bb13f5e2--- /dev/null+++ b/changelog.d/6428.fixed.md@@ -0,0 +1 @@+`match_adalam` and `AdalamFilter` report, for a match accepted by several overlapping local verifications, the inverse confidence of its most confident one; they used to report the value of whichever copy came first, which depended on the order of the neighbourhoods and the device's sort.diff --git a/kornia/feature/adalam/adalam.py b/kornia/feature/adalam/adalam.pyindex 373e28ab0..5a8306b1f 100644--- a/kornia/feature/adalam/adalam.py+++ b/kornia/feature/adalam/adalam.py@@ -63,10 +63,11 @@ def match_adalam(See :cite:`AdaLAM2020` for more details.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.+ - See the Convention block on :func:`~kornia.feature.match_nn`. ``dists`` is the inverse of the confidence of+ the most confident local RANSAC that accepted the match (overlapping neighbourhoods often accept a match+ several times), 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 thetwo smallest distances; with ``force_seed_mnn`` only mutual nearest neighbours can be seeds. ``dm`` holdsplain distances, like the ``dm`` of :func:`~kornia.feature.match_nn` and the other matchers: AdaLAMdiff --git a/kornia/feature/adalam/core.py b/kornia/feature/adalam/core.pyindex 5a2d277cb..36e09147a 100644--- a/kornia/feature/adalam/core.py+++ b/kornia/feature/adalam/core.py@@ -267,6 +267,25 @@ def extract_local_patterns(return im1loc[sorting_perm], im2loc[sorting_perm], ransidx, tokp1[sorting_perm], tokp2[sorting_perm]+def _merge_duplicate_matches(matches: torch.Tensor, dists: torch.Tensor, n2: int) -> Tuple[torch.Tensor, torch.Tensor]:+ """Keep each match once, with the smallest distance ratio of its copies.++ Overlapping neighbourhoods accept the same match in several local RANSACs, each with its own confidence; the best+ one is reported. The unique rows come sorted lexicographically, through a 1-D key: torch.unique(dim=0) has no MPS+ kernel on torch 2.5 (https://stackoverflow.com/a/72005790).+ """+ keys, inverse = torch.unique(matches[:, 0] * n2 + matches[:, 1], return_inverse=True)+ unique_matches = torch.stack([torch.div(keys, n2, rounding_mode="floor"), keys % n2], dim=1)+ # The copies ordered by match, then by ratio, and the first of each match kept: scatter_reduce, the direct way to+ # take a minimum per match, has no MPS kernel on torch 2.5.+ by_ratio = torch.sort(dists, stable=True).indices+ order = by_ratio[torch.sort(inverse[by_ratio], stable=True).indices]+ grouped = inverse[order]+ first = torch.ones_like(grouped, dtype=torch.bool)+ first[1:] = grouped[1:] != grouped[:-1]+ return unique_matches, dists[order][first]++def adalam_core(k1: torch.Tensor,k2: torch.Tensor,@@ -414,18 +433,7 @@ def adalam_core(final_matches = torch.stack([absolute_im1idx, absolute_im2idx], dim=1)if final_matches.shape[0] > 1:- # Unique rows, sorted lexicographically, through a 1-D key: torch.unique(dim=0) has no MPS kernel on torch 2.5.- # https://stackoverflow.com/a/72005790- n2 = k2.shape[0]- keys, idxs, counts = torch.unique(- final_matches[:, 0] * n2 + final_matches[:, 1], return_inverse=True, return_counts=True- )- final_matches = torch.stack([torch.div(keys, n2, rounding_mode="floor"), keys % n2], dim=1)- _, ind_sorted = torch.sort(idxs)- cum_sum = counts.cumsum(0)- cum_sum = torch.cat((torch.tensor([0], dtype=cum_sum.dtype, device=cum_sum.device), cum_sum[:-1]))- first_indicies = ind_sorted[cum_sum]- accepted_dist = accepted_dist[first_indicies]+ final_matches, accepted_dist = _merge_duplicate_matches(final_matches, accepted_dist, k2.shape[0])if return_dist:return final_matches, accepted_dist.reshape(-1, 1)return final_matchesdiff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.pyindex a57a25ad3..5096a2020 100644--- a/kornia/feature/integrated.py+++ b/kornia/feature/integrated.py@@ -978,7 +978,10 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):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.+ - ``"aliked"``, ``"dedodeb"``, ``"dedodeg"``, ``"disk"``, ``"raco-aliked"``, ``"superpoint"``, ``"xfeat"``:+ nothing else. For ``"xfeat"``, the LighterGlue weights of :class:`~kornia.feature.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 negatedLAF orientation in :math:`(-\pi, \pi]`, and a sixth of the LAF scale, which is the detection sigma for6-sigma DoG frames such as :class:`~kornia.feature.SIFTFeatureScaleSpace`'s. The descriptors must be in@@ -1015,8 +1018,10 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):"dog_affnet_hardnet","doghardnet","keynet_affnet_hardnet",+ "raco-aliked","sift","superpoint",+ "xfeat",]def __init__(self, feature_name: str = "disk", params: Optional[Dict] = None) -> None:diff --git a/tests/feature/test_adalam.py b/tests/feature/test_adalam.pyindex 44cbacfd4..c3dbe16a2 100644--- a/tests/feature/test_adalam.py+++ b/tests/feature/test_adalam.py@@ -22,6 +22,7 @@ import torchfrom kornia.feature import GeometryAwareDescriptorMatcher, laf_from_center_scale_ori, match_adalamfrom kornia.feature.adalam import AdalamFilter, get_adalam_default_config+from kornia.feature.adalam.core import _merge_duplicate_matchesfrom kornia.feature.adalam.ransac import (_select_inliers,confidence_based_inlier_selection,@@ -236,3 +237,26 @@ class TestDrawFirstKCouples(BaseTester):couples = draw_first_k_couples(4, torch.tensor([1000, 3], device=device), device)self.assert_close(couples[:, :, 0], torch.tensor([[1, 0], [2, 0], [2, 1], [3, 0]], device=device))self.assert_close(couples[:, :, 1], torch.tensor([[1, 0], [2, 0], [2, 1], [0, 0]], device=device))+++class TestMergeDuplicateMatches(BaseTester):+ def test_keeps_each_match_once_with_its_smallest_distance_ratio(self, device, dtype):+ # overlapping neighbourhoods accept a match in several local RANSACs; the most confident copy is reported, in+ # whatever order the copies come+ matches = torch.tensor([[0, 1], [2, 3], [0, 1], [0, 1], [2, 0]], device=device)+ dists = torch.tensor([0.5, 0.2, 0.1, 0.9, 0.4], device=device, dtype=dtype)+ for order in ([0, 1, 2, 3, 4], [3, 4, 1, 2, 0]):+ unique, best = _merge_duplicate_matches(matches[order], dists[order], 5)+ assert unique.tolist() == [[0, 1], [2, 0], [2, 3]]+ self.assert_close(best, torch.tensor([0.1, 0.4, 0.2], device=device, dtype=dtype))++ def test_many_copies_and_ties_give_the_minimum_of_each_match(self, device, dtype):+ g = torch.Generator().manual_seed(0)+ matches = torch.randint(0, 6, (300, 2), generator=g)+ dists = torch.randint(0, 10, (300,), generator=g) / 10 # ties within and across matches+ unique, best = _merge_duplicate_matches(matches.to(device), dists.to(device, dtype), 6)+ expected = {}+ for (i, j), d in zip(matches.tolist(), dists.tolist()):+ expected[(i, j)] = min(d, expected.get((i, j), d))+ assert unique.tolist() == [list(key) for key in sorted(expected)]+ self.assert_close(best, torch.tensor([expected[key] for key in sorted(expected)], device=device, dtype=dtype))