Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): retain exact AdaLAM correspondences (#5941)

Dmytro Mishkinb6c80a536fdd
diff --git a/changelog.d/5941.fixed.md b/changelog.d/5941.fixed.md
new file mode 100644
index 000000000..fa917f2f7
--- /dev/null
+++ b/changelog.d/5941.fixed.md
@@ -0,0 +1 @@
+AdaLAM now retains well-supported exact local affine correspondences, including self-matches and noise-free translations, while discounting repeated keypoints and the points used to fit each hypothesis.
diff --git a/kornia/feature/adalam/adalam.py b/kornia/feature/adalam/adalam.py
index e819fb648..bd00655d0 100644
--- a/kornia/feature/adalam/adalam.py
+++ b/kornia/feature/adalam/adalam.py
@@ -82,10 +82,10 @@ def match_adalam(
- ``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>`_).
+ - Exact local affine correspondences are retained when enough distinct keypoints support them beyond the
+ 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.
Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
diff --git a/kornia/feature/adalam/ransac.py b/kornia/feature/adalam/ransac.py
index 13896c289..8c3bc1164 100644
--- a/kornia/feature/adalam/ransac.py
+++ b/kornia/feature/adalam/ransac.py
@@ -28,13 +28,12 @@ def stable_sort_residuals(residuals: torch.Tensor, ransidx: torch.Tensor) -> Tup
minlogres = torch.min(logres)
maxlogres = torch.max(logres)
- sorting_score = ransidx.unsqueeze(0).float() + 0.99 * (logres - minlogres) / (maxlogres - minlogres)
+ span = (maxlogres - minlogres).clamp_min(torch.finfo(logres.dtype).eps)
+ sorting_score = ransidx.unsqueeze(0).float() + 0.99 * (logres - minlogres) / span
sorting_idxes = torch.argsort(sorting_score, dim=-1) # (niters, numsamples)
- iters_range = torch.arange(residuals.shape[0], device=residuals.device)
-
- return residuals[iters_range.unsqueeze(-1), sorting_idxes], sorting_idxes
+ return residuals.gather(1, sorting_idxes), sorting_idxes
def group_sum_and_cumsum(
@@ -67,10 +66,23 @@ def confidence_based_inlier_selection(
min_confidence: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Select inliers from confidence scores."""
+ sorted_res, sorting_idxes = stable_sort_residuals(residuals, ransidx)
+ return _confidence_from_sorted_residuals(sorted_res, sorting_idxes, ransidx, rdims, idxoffsets, dv, min_confidence)
+
+
+def _confidence_from_sorted_residuals(
+ sorted_res: torch.Tensor,
+ sorting_idxes: torch.Tensor,
+ ransidx: torch.Tensor,
+ rdims: torch.Tensor,
+ idxoffsets: torch.Tensor,
+ dv: torch.device,
+ min_confidence: torch.Tensor,
+) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Evaluate the original confidence heuristic without sorting the residuals again."""
numransacs = rdims.shape[0]
- numiters = residuals.shape[0]
+ numiters = sorted_res.shape[0]
- sorted_res, sorting_idxes = stable_sort_residuals(residuals, ransidx)
sorted_res_sqr = sorted_res**2
too_perfect_fits = sorted_res_sqr <= 1e-8
@@ -88,7 +100,9 @@ def confidence_based_inlier_selection(
if not isinstance(weights_cumsums, torch.Tensor):
raise TypeError("Expected the `weights_cumsums` to be a torch.Tensor!")
- progressive_inl_rates = weights_cumsums.float() / (balanced_rdims.repeat_interleave(rdims, dim=1)).float()
+ progressive_inl_rates = (
+ weights_cumsums.float() / balanced_rdims.repeat_interleave(rdims, dim=1, output_size=ransidx.numel()).float()
+ )
good_inl_mask = (sorted_res_sqr * min_confidence <= progressive_inl_rates) | too_perfect_fits
@@ -98,8 +112,11 @@ def confidence_based_inlier_selection(
inl_counts, inl_iters = torch.max(inlier_counts_matrix.long(), dim=0)
relative_inl_idxes = arange_sequence(inl_counts)
- inl_ransidx = torch.arange(numransacs, device=dv).repeat_interleave(inl_counts)
- inl_sampleidx = sorting_idxes[inl_iters.repeat_interleave(inl_counts), idxoffsets[inl_ransidx] + relative_inl_idxes]
+ num_inliers = relative_inl_idxes.numel()
+ inl_ransidx = torch.arange(numransacs, device=dv).repeat_interleave(inl_counts, output_size=num_inliers)
+ inl_sampleidx = sorting_idxes[
+ inl_iters.repeat_interleave(inl_counts, output_size=num_inliers), idxoffsets[inl_ransidx] + relative_inl_idxes
+ ]
highest_accepted_sqr_residuals = sorted_res_sqr[inl_iters, idxoffsets + inl_counts - 1]
expected_extra_inl = (
balanced_rdims[inl_iters, torch.arange(numransacs, device=dv)].float() * highest_accepted_sqr_residuals
@@ -107,6 +124,102 @@ def confidence_based_inlier_selection(
return inl_ransidx, inl_sampleidx, inl_counts, inl_iters, inl_counts.float() / expected_extra_inl
+def _select_inliers(
+ residuals: torch.Tensor,
+ xsamples: torch.Tensor,
+ ysamples: torch.Tensor,
+ ransidx: torch.Tensor,
+ rdims: torch.Tensor,
+ idxoffsets: torch.Tensor,
+ affinities: torch.Tensor,
+ config: Dict[str, Any],
+ valid_affinities: Union[torch.Tensor, None] = None,
+) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Recover well-supported near-exact correspondences missed by the original selection.
+
+ Unlike the reference AdaLAM heuristic, equal tiny residuals need not be duplicate
+ keypoints. Count distinct geometry instead, reserving three correspondences for
+ the seed and minimal pair. They may be returned, but supply no independent evidence.
+ """
+ dv = residuals.device
+ min_inliers, min_confidence = config["min_inliers"], config["min_confidence"]
+ sorted_res, sorting_idxes = stable_sort_residuals(residuals, ransidx)
+ # Ordinary noisy fits have only the seed and fitting pair near zero. Inspect one
+ # already-sorted residual per hypothesis/neighbourhood before scanning all samples.
+ # Use a loose gate because the log-based sort can tie close residuals in float32;
+ # the recovery below still applies the exact 2**-12 threshold.
+ # Skip the gate for very many groups, where adding the group ID to the sorting
+ # score can lose too much residual precision even for this loose threshold.
+ probe = idxoffsets + (rdims - 1).clamp(max=min_inliers + 2)
+ if len(rdims) <= 4096 and not ((sorted_res[:, probe] <= 2.0**-11) & (rdims >= min_inliers + 3)).any():
+ return _confidence_from_sorted_residuals(
+ sorted_res, sorting_idxes, ransidx, rdims, idxoffsets, dv, min_confidence
+ )
+ # Cover both the "too perfect" cutoff and the first float16 residual bin used
+ # by the original duplicate heuristic (2**-24 is the smallest float16 subnormal).
+ residual_area = 2.0**-24
+ near_exact = residuals <= 2.0**-12
+ ends = rdims.cumsum(0) - 1
+ raw_counts, _ = group_sum_and_cumsum(near_exact.float(), ends)
+ raw_counts = raw_counts.long()
+ candidates = raw_counts >= min_inliers + 3
+ if not candidates.any():
+ return _confidence_from_sorted_residuals(
+ sorted_res, sorting_idxes, ransidx, rdims, idxoffsets, dv, min_confidence
+ )
+
+ if valid_affinities is None:
+ eigenvals, _ = batch_2x2_ellipse(affinities)
+ scale_limit = config["detected_scale_rate_threshold"] ** 2
+ valid_affinities = (eigenvals[..., 1] >= 1 / scale_limit) & (eigenvals[..., 0] <= scale_limit)
+ candidates &= valid_affinities
+
+ # Use at most one occurrence of each source and target location in each neighbourhood.
+ # Stable scalar sorts avoid torch.unique(dim=0), unavailable on older MPS versions.
+ distinct = torch.ones_like(ransidx, dtype=torch.bool)
+ for points in (xsamples, ysamples):
+ order = torch.argsort(points[:, 1], stable=True)
+ order = order[torch.argsort(points[order, 0], stable=True)]
+ order = order[torch.argsort(ransidx[order], stable=True)]
+ repeated = (ransidx[order[1:]] == ransidx[order[:-1]]) & (points[order[1:]] == points[order[:-1]]).all(dim=-1)
+ distinct[order[1:][repeated]] = False
+
+ support, _ = group_sum_and_cumsum((near_exact & distinct.unsqueeze(0)).float(), ends)
+ support = support.long()
+ support = (support - 3).clamp_min(0)
+ support = torch.where(candidates, support, 0)
+ best_support, best_iters = support.max(dim=0)
+ best_counts = raw_counts[best_iters, torch.arange(len(rdims), device=dv)]
+ # The fixed residual-area floor makes confidence finite even for a zero residual.
+ # It is conservative: every recovered residual is bounded by this same area.
+ exact_confidence = best_support.float() / (rdims.float() * residual_area)
+ recover = (best_support >= min_inliers) & (exact_confidence >= min_confidence)
+ # When every neighbourhood is fully explained, no larger consensus exists.
+ # Avoid evaluating the residual-duplicate heuristic that rejects these exact fits.
+ if (recover & (best_counts == rdims)).all():
+ return ransidx, torch.arange(len(ransidx), device=dv), rdims, best_iters, exact_confidence
+
+ inl_ransidx, inl_sampleidx, counts, iters, confidence = _confidence_from_sorted_residuals(
+ sorted_res, sorting_idxes, ransidx, rdims, idxoffsets, dv, min_confidence
+ )
+ accepted = (confidence >= min_confidence) & (counts * (1 - 1 / confidence) >= min_inliers)
+ recover &= ~accepted | (best_counts > counts)
+ if not recover.any():
+ return inl_ransidx, inl_sampleidx, counts, iters, confidence
+
+ recovered_samples = torch.where(
+ recover[ransidx] & near_exact[best_iters[ransidx], torch.arange(len(ransidx), device=dv)]
+ )[0]
+ keep = ~recover[inl_ransidx]
+ inl_sampleidx = torch.cat([inl_sampleidx[keep], recovered_samples])
+ inl_ransidx = torch.cat([inl_ransidx[keep], ransidx[recovered_samples]])
+ order = torch.argsort(inl_ransidx, stable=True)
+ counts = torch.where(recover, best_counts, counts)
+ iters = torch.where(recover, best_iters, iters)
+ confidence = torch.where(recover, exact_confidence, confidence)
+ return inl_ransidx[order], inl_sampleidx[order], counts, iters, confidence
+
+
def sample_padded_inliers(
xsamples: torch.Tensor,
ysamples: torch.Tensor,
@@ -138,11 +251,10 @@ def ransac(
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Run ransac."""
DET_THR = config["detected_scale_rate_threshold"]
- MIN_CONFIDENCE = config["min_confidence"]
dv: torch.device = config["device"]
numransacs = rdims.shape[0]
- ransidx = torch.arange(numransacs, device=dv).repeat_interleave(rdims)
+ ransidx = torch.arange(numransacs, device=dv).repeat_interleave(rdims, output_size=xsamples.shape[0])
idxoffsets = torch.cat([torch.tensor([0], device=dv), torch.cumsum(rdims[:-1], dim=0)], dim=0)
rand_samples_rel = draw_first_k_couples(iters, rdims, dv)
@@ -154,16 +266,17 @@ def ransac(
# minimal fit for sampled_x @ A^T = sampled_y
affinities_fit = torch.transpose(batch_2x2_inv(sampled_x, check_dets=True) @ sampled_y, -1, -2)
+ valid_affinities = None
if not refit:
eigenvals, _eigenvecs = batch_2x2_ellipse(affinities_fit)
- bad_ones = (eigenvals[..., 1] < 1 / DET_THR**2) | (eigenvals[..., 0] > DET_THR**2)
- affinities_fit[bad_ones] = torch.eye(2, device=dv)
+ valid_affinities = (eigenvals[..., 1] >= 1 / DET_THR**2) & (eigenvals[..., 0] <= DET_THR**2)
+ affinities_fit[~valid_affinities] = torch.eye(2, device=dv, dtype=affinities_fit.dtype)
y_pred = (affinities_fit[:, ransidx] @ xsamples.unsqueeze(-1)).squeeze(-1)
residuals = torch.norm(y_pred - ysamples, dim=-1) # (niters, numsamples)
- inl_ransidx, inl_sampleidx, inl_counts, inl_iters, inl_confidence = confidence_based_inlier_selection(
- residuals, ransidx, rdims, idxoffsets, dv=dv, min_confidence=MIN_CONFIDENCE
+ inl_ransidx, inl_sampleidx, inl_counts, inl_iters, inl_confidence = _select_inliers(
+ residuals, xsamples, ysamples, ransidx, rdims, idxoffsets, affinities_fit, config, valid_affinities
)
if len(inl_sampleidx) == 0:
@@ -200,7 +313,15 @@ def ransac(
residuals = torch.norm(y_pred - ysamples, dim=-1)
- inl_ransidx, inl_sampleidx, inl_counts, inl_iters, inl_confidence = confidence_based_inlier_selection(
- residuals.unsqueeze(0), ransidx, rdims, idxoffsets, dv=dv, min_confidence=MIN_CONFIDENCE
+ inl_ransidx, inl_sampleidx, inl_counts, inl_iters, inl_confidence = _select_inliers(
+ residuals.unsqueeze(0),
+ xsamples,
+ ysamples,
+ ransidx,
+ rdims,
+ idxoffsets,
+ refit_affinity.unsqueeze(0),
+ config,
+ ~bad_ones.unsqueeze(0),
)
return inl_sampleidx, refit_affinity, inl_confidence, inl_counts
diff --git a/tests/feature/test_adalam.py b/tests/feature/test_adalam.py
new file mode 100644
index 000000000..2dc499b49
--- /dev/null
+++ b/tests/feature/test_adalam.py
@@ -0,0 +1,219 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+import pytest
+import torch
+
+from kornia.feature import GeometryAwareDescriptorMatcher, laf_from_center_scale_ori, match_adalam
+from kornia.feature.adalam import AdalamFilter, get_adalam_default_config
+from kornia.feature.adalam.ransac import (
+ _select_inliers,
+ confidence_based_inlier_selection,
+ ransac,
+ stable_sort_residuals,
+)
+
+from testing.base import BaseTester
+
+
+class TestAdalamExact(BaseTester):
+ @pytest.mark.parametrize("seed", [0, 1, 2])
+ @pytest.mark.parametrize("sigma", [0.0, 0.001, 0.01, 0.02, 0.05, 0.5])
+ def test_translation_5866(self, device, dtype, seed, sigma):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("filter_matches requires full-precision coordinates")
+ g = torch.Generator().manual_seed(seed)
+ n = 200
+ xy = torch.rand(n, 2, generator=g, dtype=torch.float64) * torch.tensor([639.0, 479.0])
+ scores = 0.5 * torch.rand(n, generator=g, dtype=torch.float64)
+ noise = torch.randn(n, 2, generator=g, dtype=torch.float64)
+ moved = (xy + torch.tensor([20.0, 10.0]) + sigma * noise).to(device, dtype)
+ xy, scores = xy.to(device, dtype), scores.to(device, dtype)
+ zero, scale = torch.zeros(n, device=device, dtype=dtype), torch.full((n,), 10.0, device=device, dtype=dtype)
+ indices = torch.arange(n, device=device)
+ config = get_adalam_default_config()
+ config["device"] = device
+ matches, quality = AdalamFilter(config).filter_matches(
+ xy, moved, indices, scores, None, (480, 640), (480, 640), zero, zero, scale, scale, return_dist=True
+ )
+ if sigma <= 0.001:
+ self.assert_close(matches, torch.stack([indices, indices], dim=-1))
+ else:
+ assert len(matches) >= 0.9 * n
+ self.assert_close(matches[:, 0], matches[:, 1])
+ assert torch.isfinite(quality).all()
+ assert (quality <= 1 / config["min_confidence"]).all()
+
+ @pytest.mark.parametrize("api", ["functional", "module"])
+ @pytest.mark.parametrize("translated", [False, True])
+ def test_public_matchers_5866(self, device, dtype, api, translated):
+ g = torch.Generator().manual_seed(4)
+ n = 200
+ # Even coordinates below 512 stay exact in bfloat16 after the +16 shift; odd values in [240, 256) do not.
+ xy = (2 * torch.randint(0, 200, (1, n, 2), generator=g)).to(device, dtype)
+ desc = torch.randn(n, 32, generator=g).to(device, dtype)
+ lafs = laf_from_center_scale_ori(xy, torch.full((1, n, 1, 1), 10.0, device=device, dtype=dtype))
+ moved = lafs.clone()
+ if translated:
+ moved[..., 2] += 16
+ if api == "functional":
+ quality, matches = match_adalam(desc, desc, lafs, moved, hw1=(480, 640), hw2=(480, 640))
+ else:
+ quality, matches = GeometryAwareDescriptorMatcher("adalam")(desc, desc, lafs, moved)
+ indices = torch.arange(n, device=device)
+ self.assert_close(matches, torch.stack([indices, indices], dim=-1))
+ assert torch.isfinite(quality).all()
+
+ @pytest.mark.parametrize("refit", [False, True])
+ @pytest.mark.parametrize("n_inliers,n_outliers,seed", [(40, 8, 9), (9, 0, 0)])
+ def test_affine_with_outliers(self, device, dtype, refit, n_inliers, n_outliers, seed):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("local RANSAC uses full-precision coordinates")
+ g = torch.Generator().manual_seed(seed)
+ x = torch.rand(n_inliers + n_outliers, 2, generator=g).to(device, dtype) - 0.5
+ x[0] = 0
+ affine = torch.tensor([[1.1, -0.2], [0.1, 0.9]], device=device, dtype=dtype)
+ y = x @ affine.T
+ y[n_inliers:] += 10
+ config = get_adalam_default_config()
+ config["device"] = device
+ indices, fitted, confidence, counts = ransac(x, y, torch.tensor([len(x)], device=device), config, refit=refit)
+ self.assert_close(indices.sort().values, torch.arange(n_inliers, device=device))
+ self.assert_close(fitted[0], affine)
+ assert counts.tolist() == [n_inliers]
+ assert torch.isfinite(confidence).all()
+ assert (confidence >= config["min_confidence"]).all()
+
+ @pytest.mark.parametrize("case", ["duplicates", "minimal", "collinear", "bad_scale", "one_target"])
+ @pytest.mark.parametrize("refit", [False, True])
+ def test_no_manufactured_support(self, device, dtype, case, refit):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("local RANSAC uses full-precision coordinates")
+ g = torch.Generator().manual_seed(17)
+ x = torch.rand(40, 2, generator=g).to(device, dtype) - 0.5
+ x[0] = 0
+ if case == "duplicates":
+ x = x[:5].repeat(8, 1)
+ elif case == "collinear":
+ x[:, 1] = 0
+ y = x.clone()
+ if case == "minimal":
+ y[3:] = 10 + torch.rand(37, 2, generator=g).to(device, dtype)
+ elif case == "bad_scale":
+ y *= 10
+ elif case == "one_target":
+ y[:] = 0
+ config = get_adalam_default_config()
+ config["device"] = device
+ _, _, confidence, counts = ransac(x, y, torch.tensor([len(x)], device=device), config, refit=refit)
+ accepted = (confidence >= config["min_confidence"]) & (counts * (1 - 1 / confidence) >= config["min_inliers"])
+ assert not accepted.any()
+
+ def test_neighbourhood_isolation(self, device, dtype):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("local RANSAC uses full-precision coordinates")
+ n = 20
+ g = torch.Generator().manual_seed(7)
+ # The same source/target geometry occurs in both groups and must count separately.
+ xy = torch.rand(n, 2, generator=g).to(device, dtype).repeat(2, 1)
+ residuals = torch.zeros(1, 2 * n, device=device, dtype=dtype)
+ residuals[0, n:] = torch.linspace(0.001, 0.01, n, device=device, dtype=dtype)
+ groups = torch.arange(2, device=device).repeat_interleave(n)
+ dims = torch.full((2,), n, device=device, dtype=torch.long)
+ offsets = torch.tensor([0, n], device=device)
+ config = get_adalam_default_config()
+ legacy = confidence_based_inlier_selection(residuals, groups, dims, offsets, device, config["min_confidence"])
+ result = _select_inliers(
+ residuals,
+ xy,
+ xy,
+ groups,
+ dims,
+ offsets,
+ torch.eye(2, device=device, dtype=dtype).expand(1, 2, 2, 2),
+ config,
+ )
+ self.assert_close(result[1][result[0] == 0], torch.arange(n, device=device))
+ self.assert_close(result[1][result[0] == 1], legacy[1][legacy[0] == 1])
+ for actual, expected in zip(result[2:], legacy[2:]):
+ self.assert_close(actual[1:], expected[1:], atol=0, rtol=0)
+ residuals.zero_()
+ result = _select_inliers(
+ residuals,
+ xy,
+ xy,
+ groups,
+ dims,
+ offsets,
+ torch.eye(2, device=device, dtype=dtype).expand(1, 2, 2, 2),
+ config,
+ )
+ self.assert_close(result[1], torch.arange(2 * n, device=device))
+ assert result[2].tolist() == [n, n]
+
+ def test_equal_residual_sort(self, device, dtype):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("local RANSAC uses full-precision coordinates")
+ groups = torch.tensor([1, 0, 1, 0], device=device)
+ residuals = torch.zeros(1, 4, device=device, dtype=dtype)
+ sorted_residuals, order = stable_sort_residuals(residuals, groups)
+ self.assert_close(groups[order[0]], groups.sort().values)
+ self.assert_close(sorted_residuals, residuals)
+
+ def test_noisy_fits_skip_recovery_scan(self, device, dtype, monkeypatch):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("local RANSAC uses full-precision coordinates")
+ dims = torch.tensor([6, 8, 20], device=device)
+ offsets = torch.tensor([0, 6, 14], device=device)
+ groups = torch.arange(3, device=device).repeat_interleave(dims)
+ residuals = torch.full((1, 34), 0.01, device=device, dtype=dtype)
+ residuals[:, offsets[:, None] + torch.arange(3, device=device)] = 0
+ points = torch.zeros(34, 2, device=device, dtype=dtype)
+ config = get_adalam_default_config()
+ expected = confidence_based_inlier_selection(residuals, groups, dims, offsets, device, config["min_confidence"])
+
+ def no_recovery_scan(*args, **kwargs):
+ pytest.fail("Ordinary fits must not scan all residuals again for near-exact support")
+
+ monkeypatch.setattr("kornia.feature.adalam.ransac.group_sum_and_cumsum", no_recovery_scan)
+ monkeypatch.setattr("kornia.feature.adalam.ransac._confidence_from_sorted_residuals", lambda *args: expected)
+ result = _select_inliers(
+ residuals, points, points, groups, dims, offsets, torch.eye(2, device=device, dtype=dtype), config
+ )
+ assert result is expected
+
+ def test_complete_exact_fits_skip_legacy_confidence(self, device, dtype, monkeypatch):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("local RANSAC uses full-precision coordinates")
+
+ def no_legacy_confidence(*args, **kwargs):
+ pytest.fail("Fully supported exact fits must not run the residual-duplicate heuristic")
+
+ monkeypatch.setattr("kornia.feature.adalam.ransac._confidence_from_sorted_residuals", no_legacy_confidence)
+ dims = torch.tensor([9, 20], device=device)
+ offsets = torch.tensor([0, 9], device=device)
+ groups = torch.arange(2, device=device).repeat_interleave(dims)
+ residuals = torch.zeros(1, 29, device=device, dtype=dtype)
+ points = torch.rand(29, 2, generator=torch.Generator().manual_seed(11)).to(device, dtype)
+ affinities = torch.eye(2, device=device, dtype=dtype).expand(1, 2, 2, 2)
+ result = _select_inliers(
+ residuals, points, points, groups, dims, offsets, affinities, get_adalam_default_config()
+ )
+ self.assert_close(result[1], torch.arange(29, device=device))
+ self.assert_close(result[2], dims)
diff --git a/tests/feature/test_matching.py b/tests/feature/test_matching.py
index cd05a42f6..ab3b87394 100644
--- a/tests/feature/test_matching.py
+++ b/tests/feature/test_matching.py
@@ -1801,15 +1801,13 @@ class TestConventionsMatching(BaseTester):
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):
+ def test_convention_match_adalam_keeps_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 matches must survive the local verification as well as the no-seed fallback.
exact = match_adalam(desc, desc, lafs, lafs, hw1=hw, hw2=hw)[1]
- assert len(exact) == 0
+ assert exact.tolist() == [[i, i] for i in range(len(desc))]
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)