π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Adds 7pt solver to RANSAC (#2595)
Dmytro Mishkinf95519735dc4
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.pyindex 3a666b1bb..6b146d106 100644--- a/kornia/geometry/ransac.py+++ b/kornia/geometry/ransac.py@@ -1,5 +1,6 @@"""Module containing RANSAC modules."""import math+from functools import partialfrom typing import Callable, Optional, Tupleimport torch@@ -27,7 +28,8 @@ class RANSAC(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".+ model_type: type of model to estimate: "homography", "fundamental", "fundamental_7pt",+ "homography_from_linesegments".inliers_threshold: threshold for the correspondence to be an inlier.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``.@@ -45,7 +47,7 @@ class RANSAC(Module):max_lo_iters: int = 5,) -> None:super().__init__()- self.supported_models = ['homography', 'fundamental', 'homography_from_linesegments']+ self.supported_models = ['homography', 'fundamental', 'fundamental_7pt', 'homography_from_linesegments']self.inl_th = inl_thself.max_iter = max_iterself.batch_size = batch_size@@ -72,8 +74,11 @@ class RANSAC(Module):self.error_fn = symmetrical_epipolar_distanceself.minimal_solver = find_fundamentalself.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+ elif model_type == 'fundamental_7pt':+ self.error_fn = symmetrical_epipolar_distance+ self.minimal_solver = partial(find_fundamental, method='7POINT')+ self.minimal_sample_size = 7self.polisher_solver = find_fundamentalelse:raise NotImplementedError(f"{model_type} is unknown. Try one of {self.supported_models}")diff --git a/test/geometry/test_ransac.py b/test/geometry/test_ransac.pyindex cd2202a3d..f4a7f3d32 100644--- a/test/geometry/test_ransac.py+++ b/test/geometry/test_ransac.py@@ -143,7 +143,7 @@ class TestRANSACFundamental:@pytest.mark.xfail(reason="might slightly and randomly imprecise due to RANSAC randomness")@pytest.mark.parametrize("data", ["loftr_fund"], indirect=True)- def test_real_clean(self, device, dtype, data):+ def test_real_clean_8pt(self, device, dtype, data):torch.random.manual_seed(0)# generate input datadata_dev = utils.dict_to(data, device, dtype)@@ -157,9 +157,24 @@ class TestRANSACFundamental:)assert gross_errors.sum().item() == 0- @pytest.mark.xfail(reason="might fail, because out F-RANSAC is not yet 7pt")@pytest.mark.parametrize("data", ["loftr_fund"], indirect=True)- def test_real_dirty(self, device, dtype, data):+ def test_real_clean_7pt(self, device, dtype, data):+ torch.random.manual_seed(0)+ # generate input data+ data_dev = utils.dict_to(data, device, dtype)+ pts_src = data_dev['pts0']+ pts_dst = data_dev['pts1']+ # compute transform from source to target+ ransac = RANSAC('fundamental_7pt', inl_th=1.0, max_iter=100, max_lo_iters=10).to(device=device, dtype=dtype)+ fundamental_matrix, _ = ransac(pts_src, pts_dst)+ gross_errors = (+ sampson_epipolar_distance(pts_src[None], pts_dst[None], fundamental_matrix[None], squared=False) > 1.0+ )+ assert gross_errors.sum().item() == 0++ @pytest.mark.xfail(reason="might fail, because this F-RANSAC is not 7pt")+ @pytest.mark.parametrize("data", ["loftr_fund"], indirect=True)+ def test_real_dirty_8pt(self, device, dtype, data):torch.random.manual_seed(0)# generate input datadata_dev = utils.dict_to(data, device, dtype)@@ -177,6 +192,25 @@ class TestRANSACFundamental:)assert gross_errors.sum().item() < 2+ @pytest.mark.parametrize("data", ["loftr_fund"], indirect=True)+ def test_real_dirty_7pt(self, device, dtype, data):+ torch.random.manual_seed(0)+ # generate input data+ data_dev = utils.dict_to(data, device, dtype)+ pts_src = data_dev['pts0']+ pts_dst = data_dev['pts1']++ kp1 = data_dev['loftr_indoor_tentatives0']+ kp2 = data_dev['loftr_indoor_tentatives1']++ ransac = RANSAC('fundamental_7pt', inl_th=1.0, max_iter=20, max_lo_iters=10).to(device=device, dtype=dtype)+ # compute transform from source to target+ fundamental_matrix, _ = ransac(kp1, kp2)+ gross_errors = (+ sampson_epipolar_distance(pts_src[None], pts_dst[None], fundamental_matrix[None], squared=False) > 10.0+ )+ assert gross_errors.sum().item() < 2+@pytest.mark.skip(reason="try except block in python version")def test_jit(self, device, dtype):torch.random.manual_seed(0)