Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

:triangular_flag_on_post: Add vanilla LO-RANSAC (#1335)

Dmytro Mishkinf05ec3a3edb3
diff --git a/docs/source/geometry.ransac.rst b/docs/source/geometry.ransac.rst
new file mode 100644
index 000000000..05d3328c4
--- /dev/null
+++ b/docs/source/geometry.ransac.rst
@@ -0,0 +1,8 @@
+kornia.geometry.ransac
+======================
+
+.. currentmodule:: kornia.geometry.ransac
+
+Module with RANSAC
+
+.. autoclass:: RANSAC
diff --git a/docs/source/geometry.rst b/docs/source/geometry.rst
index b5bd0afef..63d6d48b6 100644
--- a/docs/source/geometry.rst
+++ b/docs/source/geometry.rst
@@ -55,3 +55,4 @@ transforms, camera, conversions, linalg and depth. We next describe each of them
geometry.subpix
geometry.transform
geometry.warp
+ geometry.ransac
diff --git a/kornia/geometry/__init__.py b/kornia/geometry/__init__.py
index 03d1eb528..6054209f6 100644
--- a/kornia/geometry/__init__.py
+++ b/kornia/geometry/__init__.py
@@ -6,5 +6,6 @@ from kornia.geometry.depth import *
from kornia.geometry.epipolar import *
from kornia.geometry.homography import *
from kornia.geometry.linalg import *
+from kornia.geometry.ransac import *
from kornia.geometry.subpix import *
from kornia.geometry.transform import *
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index 961324a03..b9a734ad8 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -33,7 +33,7 @@ def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Ten
x_mean = torch.mean(points, dim=1, keepdim=True) # Bx1x2
- scale = (points - x_mean).norm(dim=-1).mean(dim=-1) # B
+ scale = (points - x_mean).norm(dim=-1, p=2).mean(dim=-1) # B
scale = torch.sqrt(torch.tensor(2.0)) / (scale + eps) # B
ones, zeros = torch.ones_like(scale), torch.zeros_like(scale)
@@ -111,7 +111,9 @@ def find_fundamental(points1: torch.Tensor, points2: torch.Tensor, weights: torc
# reconstruct and force the matrix to have rank2
U, S, V = torch.svd(F_mat)
- rank_mask = torch.tensor([1.0, 1.0, 0]).to(F_mat.device)
+ rank_mask = torch.tensor([1.0, 1.0, 0.0],
+ device=F_mat.device,
+ dtype=F_mat.dtype)
F_projected = U @ (torch.diag_embed(S * rank_mask) @ V.transpose(-2, -1))
F_est = transform2.transpose(-2, -1) @ (F_projected @ transform1)
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.py
new file mode 100644
index 000000000..0e24c1713
--- /dev/null
+++ b/kornia/geometry/ransac.py
@@ -0,0 +1,227 @@
+"""Module containing RANSAC modules."""
+import math
+from typing import Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from kornia.geometry import (
+ find_fundamental,
+ find_homography_dlt,
+ find_homography_dlt_iterated,
+ symmetrical_epipolar_distance,
+)
+from kornia.geometry.homography import symmetric_transfer_error
+
+__all__ = ["RANSAC"]
+
+
+class RANSAC(nn.Module):
+ """Module for robust geometry estimation with RANSAC.
+
+ https://en.wikipedia.org/wiki/Random_sample_consensus
+
+ Args:
+ model_type: type of model to estimate, e.g. "homography" or "fundamental".
+ batch_size: number of generated samples at once.
+ max_iterations: maximum batches to generate. Actual number of models to try is ``batch_size * max_iterations``.
+ inliers_threshold: threshold for the correspondence to be an inlier.
+ confidence: desired confidence of the result, used for the early stopping.
+ max_local_iterations: number of local optimization (polishing) iterations.
+
+ Returns:
+ - estimated model, shape of :math:`(3, 3)`.
+ - the inlier/outlier mask, shape of :math:`(1, N), where N is number of input correspondences`.
+ """
+ supported_models = ['homography', 'fundamental']
+
+ def __init__(self,
+ model_type: str = 'homography',
+ batch_size: int = 2048,
+ max_iter: int = 10,
+ inl_th: float = 2.0,
+ confidence: float = 0.99,
+ max_lo_iters: int = 5):
+ super().__init__()
+ self.inl_th = inl_th
+ self.max_iter = max_iter
+ self.batch_size = batch_size
+ self.model_type = model_type
+ self.confidence = confidence
+ self.max_lo_iters = max_lo_iters
+ if model_type == 'homography':
+ self.error_fn = symmetric_transfer_error # type: ignore
+ self.minimal_solver = find_homography_dlt # type: ignore
+ self.polisher_solver = find_homography_dlt_iterated # type: ignore
+ self.minimal_sample_size = 4
+ elif model_type == 'fundamental':
+ self.error_fn = symmetrical_epipolar_distance # type: ignore
+ self.minimal_solver = find_fundamental # type: ignore
+ self.minimal_sample_size = 8
+ # ToDo: implement 7pt solver instead of 8pt minimal_solver
+ # https://github.com/opencv/opencv/blob/master/modules/calib3d/src/fundam.cpp#L498
+ self.polisher_solver = find_fundamental # type: ignore
+ else:
+ raise NotImplementedError(f"{model_type} is unknown. Try one of {self.supported_models}")
+ return
+
+ def sample(self,
+ sample_size: int,
+ pop_size: int,
+ batch_size: int,
+ device: torch.device = torch.device('cpu')) -> torch.Tensor:
+ """Minimal sampler, but unlike traditional RANSAC we sample in batches to get benefit of the parallel
+ processing, esp.
+
+ on GPU
+ """
+ rand = torch.rand(batch_size, pop_size, device=device)
+ _, out = rand.topk(k=sample_size, dim=1)
+ return out
+
+ @staticmethod
+ def max_samples_by_conf(n_inl: int, num_tc: int, sample_size: int, conf: float) -> float:
+ """Formula to update max_iter in order to stop iterations earlier
+ https://en.wikipedia.org/wiki/Random_sample_consensus."""
+ if n_inl == num_tc:
+ return 1.0
+ return math.log(1.0 - conf) / math.log(1. - math.pow(n_inl / num_tc, sample_size))
+
+ def estimate_model_from_minsample(self,
+ kp1: torch.Tensor,
+ kp2: torch.Tensor) -> torch.Tensor:
+ batch_size, sample_size = kp1.shape[:2]
+ H = self.minimal_solver(kp1,
+ kp2,
+ torch.ones(batch_size,
+ sample_size,
+ dtype=kp1.dtype,
+ device=kp1.device))
+ return H
+
+ def verify(self,
+ kp1: torch.Tensor,
+ kp2: torch.Tensor,
+ models: torch.Tensor, inl_th: float) -> Tuple[torch.Tensor, torch.Tensor, float]:
+ if len(kp1.shape) == 2:
+ kp1 = kp1[None]
+ if len(kp2.shape) == 2:
+ kp2 = kp2[None]
+ batch_size = models.shape[0]
+ errors = self.error_fn(kp1.expand(batch_size, -1, 2),
+ kp2.expand(batch_size, -1, 2),
+ models)
+ inl = (errors <= inl_th)
+ models_score = inl.to(kp1).sum(dim=1)
+ best_model_idx = models_score.argmax()
+ best_model_score = models_score[best_model_idx].item()
+ model_best = models[best_model_idx].clone()
+ inliers_best = inl[best_model_idx]
+ return model_best, inliers_best, best_model_score
+
+ def remove_bad_samples(self, kp1: torch.Tensor, kp2: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ """"""
+ # ToDo: add (model-specific) verification of the samples,
+ # E.g. constraints on not to be a degenerate sample
+ return kp1, kp2
+
+ def remove_bad_models(self, models: torch.Tensor) -> torch.Tensor:
+ # ToDo: add more and better degenerate model rejection
+ # For now it is simple and hardcoded
+ main_diagonal = torch.diagonal(models,
+ dim1=1,
+ dim2=2)
+ mask = main_diagonal.abs().min(dim=1)[0] > 1e-6
+ return models[mask]
+
+ def polish_model(self,
+ kp1: torch.Tensor,
+ kp2: torch.Tensor,
+ inliers: torch.Tensor) -> torch.Tensor:
+ # ToDo: Replace this with MAGSAC++ polisher
+ kp1_inl = kp1[inliers][None]
+ kp2_inl = kp2[inliers][None]
+ num_inl = kp1_inl.size(1)
+ model = self.polisher_solver(kp1_inl,
+ kp2_inl,
+ torch.ones(1,
+ num_inl,
+ dtype=kp1_inl.dtype,
+ device=kp1_inl.device))
+ return model
+
+ def forward(self,
+ kp1: torch.Tensor,
+ kp2: torch.Tensor,
+ weights: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Main forward method to execute the RANSAC algorithm.
+ Args:
+ kp1 (torch.Tensor): source image keypoints :math:`(N, 2)`.
+ kp2 (torch.Tensor): distance image keypoints :math:`(N, 2)`.
+ weights (torch.Tensor): optional correspondences weights. Not used now
+
+ Returns:
+ - estimated model, shape of :math:`(1, 3, 3)`.
+ - the inlier/outlier mask, shape of :math:`(1, N), where N is number of input correspondences`.
+ """
+ if not isinstance(kp1, torch.Tensor):
+ raise TypeError(f"Input kp1 is not torch.Tensor. Got {type(kp1)}")
+ if not isinstance(kp2, torch.Tensor):
+ raise TypeError(f"Input kp2 is not torch.Tensor. Got {type(kp2)}")
+ if not len(kp1.shape) == 2:
+ raise ValueError(f"Invalid kp1 shape, we expect Nx2 Got: {kp1.shape}")
+ if not len(kp2.shape) == 2:
+ raise ValueError(f"Invalid kp2 shape, we expect Nx2 Got: {kp2.shape}")
+ if not (kp1.shape[0] == kp2.shape[0]) or (kp1.shape[0] < self.minimal_sample_size):
+ raise ValueError(f"kp1 and kp2 should be \
+ equal shape at at least [{self.minimal_sample_size}, 2], \
+ got {kp1.shape}, {kp2.shape}")
+
+ best_score_total: float = 1.0
+ num_tc: int = len(kp1)
+ best_model_total = torch.zeros(3, 3, dtype=kp1.dtype, device=kp1.device)
+ inliers_best_total: torch.Tensor = torch.zeros(num_tc, 1, device=kp1.device, dtype=torch.bool)
+ for i in range(self.max_iter):
+ # Sample minimal samples in batch to estimate models
+ idxs = self.sample(self.minimal_sample_size, num_tc, self.batch_size, kp1.device)
+ kp1_sampled = kp1[idxs]
+ kp2_sampled = kp2[idxs]
+
+ kp1_sampled, kp2_sampled = self.remove_bad_samples(kp1_sampled, kp2_sampled)
+ # Estimate models
+ models = self.estimate_model_from_minsample(kp1_sampled, kp2_sampled)
+ models = self.remove_bad_models(models)
+ if models is None:
+ continue
+ # Score the models and select the best one
+ model, inliers, model_score = self.verify(kp1, kp2, models, self.inl_th)
+ # Store far-the-best model and (optionally) do a local optimization
+ if model_score > best_score_total:
+ # Local optimization
+ for lo_step in range(self.max_lo_iters):
+ model_lo = self.polish_model(kp1, kp2, inliers)
+ _, inliers_lo, score_lo = self.verify(kp1, kp2, model_lo, self.inl_th)
+ # print (f"Orig score = {best_model_score}, LO score = {score_lo} TC={num_tc}")
+ if score_lo > model_score:
+ model = model_lo.clone()[0]
+ inliers = inliers_lo.clone()
+ model_score = score_lo
+ else:
+ break
+ # Now storing the best model
+ best_model_total = model.clone()
+ inliers_best_total = inliers.clone()
+ best_score_total = model_score
+
+ # Should we already stop?
+ new_max_iter = int(self.max_samples_by_conf(int(best_score_total),
+ num_tc,
+ self.minimal_sample_size,
+ self.confidence))
+ # print (f"New max_iter = {new_max_iter}")
+ # Stop estimation, if the model is very good
+ if (i + 1) * self.batch_size >= new_max_iter:
+ break
+ # local optimization with all inliers for better precision
+ return best_model_total, inliers_best_total
diff --git a/test/geometry/test_ransac.py b/test/geometry/test_ransac.py
new file mode 100644
index 000000000..1c04281c1
--- /dev/null
+++ b/test/geometry/test_ransac.py
@@ -0,0 +1,143 @@
+import random
+
+import pytest
+import torch
+from torch.autograd import gradcheck
+
+import kornia
+import kornia.testing as utils
+from kornia.geometry import RANSAC
+from kornia.testing import assert_close
+
+
+class TestRANSACHomography:
+ def test_smoke(self, device, dtype):
+ points1 = torch.rand(4, 2, device=device, dtype=dtype)
+ points2 = torch.rand(4, 2, device=device, dtype=dtype)
+ ransac = RANSAC('homography').to(device=device, dtype=dtype)
+ H, inliers = ransac(points1, points2)
+ assert H.shape == (3, 3)
+
+ @pytest.mark.xfail(reason="might slightly and randomly imprecise due to RANSAC randomness")
+ def test_dirty_points(self, device, dtype):
+ # generate input data
+
+ H = torch.eye(3, dtype=dtype, device=device)
+ H[:2] = H[:2] + 0.1 * torch.rand_like(H[:2])
+ H[2:, :2] = H[2:, :2] + 0.001 * torch.rand_like(H[2:, :2])
+
+ points_src = 100.0 * torch.rand(1, 20, 2, device=device, dtype=dtype)
+ points_dst = kornia.geometry.transform_points(H[None], points_src)
+
+ # making last point an outlier
+ points_dst[:, -1, :] += 800
+ ransac = RANSAC('homography', inl_th=0.5, max_iter=20).to(device=device, dtype=dtype)
+ # compute transform from source to target
+ dst_homo_src, inliers = ransac(points_src[0], points_dst[0])
+
+ assert_close(
+ kornia.geometry.transform_points(dst_homo_src[None], points_src[:, :-1]),
+ points_dst[:, :-1],
+ rtol=1e-3,
+ atol=1e-3)
+
+ @pytest.mark.jit
+ @pytest.mark.skip(reason="find_homography_dlt is using try/except block")
+ def test_jit(self, device, dtype):
+ points1 = torch.rand(4, 2, device=device, dtype=dtype)
+ points2 = torch.rand(4, 2, device=device, dtype=dtype)
+ model = RANSAC('homography').to(device=device, dtype=dtype)
+ model_jit = torch.jit.script(RANSAC('homography').to(device=device,
+ dtype=dtype))
+ assert_close(model(points1, points2)[0],
+ model_jit(points1, points2)[0],
+ rtol=1e-4,
+ atol=1e-4)
+
+
+class TestRANSACFundamental:
+ def test_smoke(self, device, dtype):
+ points1 = torch.rand(8, 2, device=device, dtype=dtype)
+ points2 = torch.rand(8, 2, device=device, dtype=dtype)
+ ransac = RANSAC('fundamental').to(device=device, dtype=dtype)
+ Fm, inliers = ransac(points1, points2)
+ assert Fm.shape == (3, 3)
+
+ def test_dirty_points(self, device, dtype):
+ points1 = torch.tensor(
+ [
+ [
+ [0.8569, 0.5982],
+ [0.0059, 0.9649],
+ [0.1968, 0.8846],
+ [0.6084, 0.3467],
+ [0.9633, 0.5274],
+ [0.8941, 0.8939],
+ [0.0863, 0.5133],
+ [0.2645, 0.8882]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ points2 = torch.tensor(
+ [
+ [
+ [0.0928, 0.3013],
+ [0.0989, 0.9649],
+ [0.0341, 0.4827],
+ [0.8294, 0.4469],
+ [0.2230, 0.2998],
+ [0.1722, 0.8182],
+ [0.5264, 0.8869],
+ [0.8908, 0.1233]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ # generated with OpenCV using above points
+ # import cv2
+ # Fm_expected, _ = cv2.findFundamentalMat(
+ # points1.detach().numpy().reshape(-1, 1, 2),
+ # points2.detach().numpy().reshape(-1, 1, 2), cv2.FM_8POINT)
+
+ Fm_expected = torch.tensor(
+ [
+ [
+ [0.2019, 0.6860, -0.6610],
+ [0.5520, 0.8154, -0.8044],
+ [-0.5002, -1.0254, 1.]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ ransac = RANSAC('fundamental',
+ max_iter=1,
+ inl_th=1.0).to(device=device, dtype=dtype)
+ F_mat, inliers = ransac(points1[0], points2[0])
+ assert_close(F_mat, Fm_expected[0], rtol=1e-3, atol=1e-3)
+
+ @pytest.mark.jit
+ def test_jit(self, device, dtype):
+ points1 = torch.rand(8, 2, device=device, dtype=dtype)
+ points2 = torch.rand(8, 2, device=device, dtype=dtype)
+ model = RANSAC('fundamental').to(device=device, dtype=dtype)
+ model_jit = torch.jit.script(RANSAC('fundamental').to(device=device,
+ dtype=dtype))
+ assert_close(model(points1, points2)[0],
+ model_jit(points1, points2)[0],
+ rtol=1e-3,
+ atol=1e-3)
+
+ @pytest.mark.skip(reason="RANSAC is random algorithm, so Jacobian is not defined")
+ def test_gradcheck(self, device):
+ points1 = torch.rand(8, 2, device=device, dtype=torch.float64, requires_grad=True)
+ points2 = torch.rand(8, 2, device=device, dtype=torch.float64)
+ model = RANSAC('fundamental').to(device=device, dtype=torch.float64)
+
+ def gradfun(p1, p2):
+ return model(p1, p2)[0]
+ assert gradcheck(gradfun, (points1, points2), raise_exception=True)