Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(ransac): use verify()'s selected best model in local-optimization loop (#3991)

Dharshika Pugalenthia19111913a90
diff --git a/changelog.d/3991.fixed.md b/changelog.d/3991.fixed.md
new file mode 100644
index 000000000..cee222f6f
--- /dev/null
+++ b/changelog.d/3991.fixed.md
@@ -0,0 +1,4 @@
+`RANSAC`'s local-optimization step now keeps the polished model that `verify()` scores best, instead of always
+taking the first candidate the polisher returns, so the returned model agrees with the returned inliers.
+Every built-in polisher returns a single candidate, so results are unchanged for them; the fix matters for custom
+`polisher_solver`s that return several candidates.
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.py
index 6b4644627..4c52ca561 100644
--- a/kornia/geometry/ransac.py
+++ b/kornia/geometry/ransac.py
@@ -391,9 +391,11 @@ class RANSAC(nn.Module):
model_lo = self.polish_model(kp1, kp2, inliers)
if (model_lo is None) or (len(model_lo) == 0):
continue
- _, inliers_lo, score_lo, num_inliers_lo = self.verify(kp1, kp2, model_lo, self.inl_th**2)
+ model_lo_best, inliers_lo, score_lo, num_inliers_lo = self.verify(
+ kp1, kp2, model_lo, self.inl_th**2
+ )
if (score_lo > model_score) and (num_inliers_lo >= self.polisher_sample_size):
- model = model_lo.clone()[0]
+ model = model_lo_best
inliers = inliers_lo.clone()
model_score = score_lo
else:
diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.py
index 996874d36..fe93d0efc 100644
--- a/tests/geometry/test_ransac.py
+++ b/tests/geometry/test_ransac.py
@@ -20,7 +20,7 @@ import pytest
import torch
from kornia.geometry import RANSAC, transform_points
-from kornia.geometry.epipolar import project_to_essential, sampson_epipolar_distance
+from kornia.geometry.epipolar import find_fundamental, project_to_essential, sampson_epipolar_distance
from testing.base import BaseTester
from testing.casts import dict_to
@@ -270,6 +270,49 @@ class TestRANSACFundamental(BaseTester):
self.gradcheck(gradfun, (points1, points2), fast_mode=False, requires_grad=(True, False, False))
+class TestRANSACLocalOptimization(BaseTester):
+ @pytest.mark.parametrize("good_idx", [1, 2])
+ def test_polish_step_uses_verify_best_model(self, device, dtype, good_idx):
+ """Regression test for RANSAC.forward()'s local-optimization loop.
+
+ It must adopt the model verify() actually selects as best-scoring, not blindly take a fixed index of whatever
+ the polisher solver returns. This is only observable when a polisher returns more than one candidate, so the
+ polisher is patched to return three: two deliberately bad matrices and the least-squares fit of the data, placed
+ at ``good_idx`` so that neither the first nor the last position alone satisfies the test. The minimal solver is
+ patched to a plausible but worse fit, so the local-optimization branch adopts a candidate by construction
+ rather than depending on how the random minimal samples fall.
+ """
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("find_fundamental needs linalg_eigh, which has no float16/bfloat16 kernel")
+ torch.random.manual_seed(0)
+ points1 = torch.rand(60, 2, device=device, dtype=dtype) * 100.0
+ H = torch.tensor([[1.0, 0.05, 3.0], [-0.03, 1.0, -2.0], [1e-4, 1e-4, 1.0]], device=device, dtype=dtype)
+ ph = torch.cat([points1, torch.ones(60, 1, device=device, dtype=dtype)], 1) @ H.T
+ points2 = ph[:, :2] / ph[:, 2:] + 0.3 * torch.randn(60, 2, device=device, dtype=dtype)
+
+ good_fit = find_fundamental(points1[None], points2[None])
+ # A plausible but worse starting model: the least-squares fit to a much noisier copy of the data.
+ worse_fit = find_fundamental(points1[None], points2[None] + torch.randn_like(points2[None]))
+ bad_fits = [
+ torch.eye(3, device=device, dtype=dtype)[None],
+ torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype)[None],
+ ]
+ candidates = torch.cat([*bad_fits[:good_idx], good_fit, *bad_fits[good_idx:]], dim=0)
+ calls = []
+
+ def fake_polisher(kp1, kp2, weights):
+ calls.append(1)
+ return candidates
+
+ ransac = RANSAC("fundamental", inl_th=1.0, batch_size=4, max_iter=1, max_lo_iters=1, score_type="msac")
+ ransac.minimal_solver = lambda kp1, kp2, w: worse_fit.expand(kp1.shape[0], 3, 3).clone()
+ ransac.polisher_solver = fake_polisher
+
+ Fm, _ = ransac(points1, points2)
+ assert len(calls) > 0, "the local-optimization step never ran"
+ self.assert_close(Fm, good_fit[0])
+
+
class TestRansacMethods:
def test_max_samples_by_conf(self):
"""Test max_samples_by_conf with realistic scenarios."""