π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
RANSAC improvements (#1435)
Dmytro Mishkin4039ca2ade28
diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.pyindex 6045bd823..8bb216cf3 100644--- a/kornia/enhance/zca.py+++ b/kornia/enhance/zca.py@@ -3,8 +3,6 @@ from typing import List, Optional, Tupleimport torchimport torch.nn as nn-from kornia.utils.helpers import _torch_svd_cast-__all__ = ["zca_mean", "zca_whiten", "linear_transform", "ZCAWhitening"]@@ -246,7 +244,7 @@ def zca_mean(else:cov = cov / float(N)- U, S, _ = _torch_svd_cast(cov)+ U, S, _ = torch.linalg.svd(cov)S = S.reshape(-1, 1)S_inv_root: torch.Tensor = torch.rsqrt(S + eps)diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.pyindex 23759d1e4..fa47795f8 100644--- a/kornia/geometry/calibration/pnp.py+++ b/kornia/geometry/calibration/pnp.py@@ -194,7 +194,7 @@ def solve_pnp_dlt(# Checking if world_points_norm (of any element of the batch) has rank = 3. This# function cannot be used if all world points (of any element of the batch) lie# on a line or if all world points (of any element of the batch) lie on a plane.- _, s, _ = torch.svd(world_points_norm)+ s = torch.linalg.svdvals(world_points_norm)if torch.any(s[:, -1] < svd_eps):raise AssertionError(f"The last singular value of one/more of the elements of the batch is smaller "diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.pyindex 5888df9af..efd3e4fd1 100644--- a/kornia/geometry/epipolar/essential.py+++ b/kornia/geometry/epipolar/essential.py@@ -4,6 +4,7 @@ from typing import Optional, Tupleimport torchfrom kornia.utils import eye_like, vec_like+from kornia.utils.helpers import _torch_svd_castfrom .numeric import cross_product_matrixfrom .projection import depth_from_point, projection_from_KRt@@ -61,7 +62,7 @@ def decompose_essential_matrix(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torchraise AssertionError(E_mat.shape)# decompose matrix by its singular values- U, _, V = torch.svd(E_mat)+ U, _, V = _torch_svd_cast(E_mat)Vt = V.transpose(-2, -1)mask = torch.ones_like(E_mat)diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.pyindex e94848122..35f69ab2f 100644--- a/kornia/geometry/epipolar/fundamental.py+++ b/kornia/geometry/epipolar/fundamental.py@@ -1,6 +1,6 @@"""Module containing the functionalities for computing the Fundamental Matrix."""-from typing import Tuple+from typing import Optional, Tupleimport torch@@ -8,6 +8,7 @@ from kornia.core import Tensorfrom kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneousfrom kornia.geometry.linalg import transform_pointsfrom kornia.testing import KORNIA_CHECK_SHAPE+from kornia.utils.helpers import _torch_svd_castdef normalize_points(points: Tensor, eps: float = 1e-8) -> Tuple[Tensor, Tensor]:@@ -69,14 +70,17 @@ def normalize_transformation(M: Tensor, eps: float = 1e-8) -> Tensor:return torch.where(norm_val.abs() > eps, M / (norm_val + eps), M)-def find_fundamental(points1: Tensor, points2: Tensor, weights: Tensor) -> Tensor:+def find_fundamental(+ points1: torch.Tensor, points2: torch.Tensor, weights: Optional[torch.Tensor] = None+) -> torch.Tensor:+r"""Compute the fundamental matrix using the DLT formulation.The linear system is solved by using the Weighted Least Squares Solution for the 8 Points algorithm.Args:- points1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`.- points2: A set of points in the second image with a tensor shape :math:`(B, N, 2)`.+ points1: A set of points in the first image with a tensor shape :math:`(B, N, 2), N>=8`.+ points2: A set of points in the second image with a tensor shape :math:`(B, N, 2), N>=8`.weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.Returns:@@ -84,8 +88,11 @@ def find_fundamental(points1: Tensor, points2: Tensor, weights: Tensor) -> Tenso"""if points1.shape != points2.shape:raise AssertionError(points1.shape, points2.shape)- if not (len(weights.shape) == 2 and weights.shape[1] == points1.shape[1]):- raise AssertionError(weights.shape)+ if points1.shape[1] < 8:+ raise AssertionError(points1.shape)+ if not (weights is None):+ if not (len(weights.shape) == 2 and weights.shape[1] == points1.shape[1]):+ raise AssertionError(weights.shape)points1_norm, transform1 = normalize_points(points1)points2_norm, transform2 = normalize_points(points2)@@ -102,15 +109,18 @@ def find_fundamental(points1: Tensor, points2: Tensor, weights: Tensor) -> TensoX = torch.cat([x2 * x1, x2 * y1, x2, y2 * x1, y2 * y1, y2, x1, y1, ones], dim=-1) # BxNx9# apply the weights to the linear system- w_diag = torch.diag_embed(weights)- X = X.transpose(-2, -1) @ w_diag @ X-+ if weights is None:+ X = X.transpose(-2, -1) @ X+ else:+ w_diag = torch.diag_embed(weights)+ X = X.transpose(-2, -1) @ w_diag @ X# compute eigevectors and retrieve the one with the smallest eigenvalue- _, _, V = torch.svd(X)++ _, _, V = _torch_svd_cast(X)F_mat = V[..., -1].view(-1, 3, 3)# reconstruct and force the matrix to have rank2- U, S, V = torch.svd(F_mat)+ U, S, V = _torch_svd_cast(F_mat)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))diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.pyindex bff488c29..701b60d6f 100644--- a/kornia/geometry/epipolar/projection.py+++ b/kornia/geometry/epipolar/projection.py@@ -5,6 +5,7 @@ import torchfrom kornia.utils import eye_like, vec_likefrom kornia.utils._compat import linalg_qr+from kornia.utils.helpers import _torch_svd_castfrom .numeric import cross_product_matrix@@ -171,8 +172,8 @@ def _nullspace(A):Return the smallest singular value and the corresponding vector."""- _, s, vh = torch.svd(A)- return s[..., -1], vh[..., -1]+ _, s, v = _torch_svd_cast(A)+ return s[..., -1], v[..., -1]def projections_from_fundamental(F_mat: torch.Tensor) -> torch.Tensor:diff --git a/kornia/geometry/epipolar/triangulation.py b/kornia/geometry/epipolar/triangulation.pyindex 2cc834a63..956a11f71 100644--- a/kornia/geometry/epipolar/triangulation.py+++ b/kornia/geometry/epipolar/triangulation.py@@ -3,6 +3,7 @@import torchfrom kornia.geometry.conversions import convert_points_from_homogeneous+from kornia.utils.helpers import _torch_svd_cast# https://github.com/opencv/opencv_contrib/blob/master/modules/sfm/src/triangulation.cpp#L68@@ -57,7 +58,7 @@ def triangulate_points(# 1. Solve the system Ax=0 with smallest eigenvalue# 2. Return homogeneous coordinates- _, _, V = torch.svd(X)+ _, _, V = _torch_svd_cast(X)points3d_h = V[..., -1]points3d: torch.Tensor = convert_points_from_homogeneous(points3d_h)diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.pyindex b882ffeaf..988ca6d3e 100644--- a/kornia/geometry/homography.py+++ b/kornia/geometry/homography.py@@ -5,7 +5,8 @@ import torchfrom kornia.core import Tensorfrom kornia.testing import KORNIA_CHECK_SHAPE-from kornia.utils import _extract_device_dtype, safe_inverse_with_mask+from kornia.utils import _extract_device_dtype, safe_inverse_with_mask, safe_solve_with_mask+from kornia.utils.helpers import _torch_svd_castfrom .conversions import convert_points_from_homogeneous, convert_points_to_homogeneousfrom .epipolar import normalize_points@@ -117,7 +118,9 @@ def line_segment_transfer_error_one_way(ls1: Tensor, ls2: Tensor, H: Tensor, squreturn error-def find_homography_dlt(points1: Tensor, points2: Tensor, weights: Optional[Tensor] = None) -> Tensor:+def find_homography_dlt(+ points1: torch.Tensor, points2: torch.Tensor, weights: Optional[torch.Tensor] = None, solver: str = 'lu'+) -> torch.Tensor:r"""Compute the homography matrix using the DLT formulation.The linear system is solved by using the Weighted Least Squares Solution for the 4 Points algorithm.@@ -126,6 +129,8 @@ def find_homography_dlt(points1: Tensor, points2: Tensor, weights: Optional[Tenspoints1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`.points2: A set of points in the second image with a tensor shape :math:`(B, N, 2)`.weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.+ solver: variants: svd, lu.+Returns:the computed homography matrix with shape :math:`(B, 3, 3)`.@@ -162,13 +167,19 @@ def find_homography_dlt(points1: Tensor, points2: Tensor, weights: Optional[Tensw_diag = torch.diag_embed(weights.unsqueeze(dim=-1).repeat(1, 1, 2).reshape(weights.shape[0], -1))A = A.transpose(-2, -1) @ w_diag @ A- try:- _, _, V = torch.svd(A)- except RuntimeError:- warnings.warn('SVD did not converge', RuntimeWarning)- return torch.empty((points1_norm.size(0), 3, 3), device=device, dtype=dtype)-- H = V[..., -1].view(-1, 3, 3)+ if solver == 'svd':+ try:+ _, _, V = _torch_svd_cast(A)+ except RuntimeError:+ warnings.warn('SVD did not converge', RuntimeWarning)+ return torch.empty((points1_norm.size(0), 3, 3), device=device, dtype=dtype)+ H = V[..., -1].view(-1, 3, 3)+ elif solver == 'lu':+ B = torch.ones(A.shape[0], A.shape[1], device=device, dtype=dtype)+ sol, _, _ = safe_solve_with_mask(B, A)+ H = sol.reshape(-1, 3, 3)+ else:+ raise NotImplementedErrorH = transform2.inverse() @ (H @ transform1)H_norm = H / (H[..., -1:, -1:] + eps)return H_normdiff --git a/kornia/geometry/line.py b/kornia/geometry/line.pyindex 01c613bd3..14899818b 100644--- a/kornia/geometry/line.py+++ b/kornia/geometry/line.py@@ -7,6 +7,7 @@ import torchfrom kornia.core import Module, Parameter, Tensor, normalizefrom kornia.geometry.linalg import squared_normfrom kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE+from kornia.utils.helpers import _torch_svd_cast__all__ = ["ParametrizedLine", "fit_line"]@@ -174,7 +175,8 @@ def fit_line(points: Tensor, weights: Optional[Tensor] = None) -> ParametrizedLiA = A.transpose(-2, -1) @ A# NOTE: not optimal for 2d points, but for now works for other dimensions- _, _, V = torch.linalg.svd(A)+ _, _, V = _torch_svd_cast(A)+ V = V.transpose(-2, -1)# the first left eigenvector is the direction on the fited linedirection = V[..., 0, :] # BxDdiff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.pyindex 11c6ee444..22e2ece6d 100644--- a/kornia/geometry/ransac.py+++ b/kornia/geometry/ransac.py@@ -25,9 +25,7 @@ __all__ = ["RANSAC"]class RANSAC(nn.Module):- """Module for robust geometry estimation with RANSAC.-- https://en.wikipedia.org/wiki/Random_sample_consensus+ """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".diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.pyindex 496833d90..1894378a6 100644--- a/kornia/utils/helpers.py+++ b/kornia/utils/helpers.py@@ -124,8 +124,11 @@ def _torch_svd_cast(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, toif dtype not in (torch.float32, torch.float64):dtype = torch.float32- out1, out2, out3 = torch.svd(input.to(dtype))-+ out1, out2, out3H = torch.linalg.svd(input.to(dtype))+ if torch_version_geq(1, 11):+ out3 = out3H.mH+ else:+ out3 = out3H.transpose(-1, -2)return (out1.to(input.dtype), out2.to(input.dtype), out3.to(input.dtype))@@ -158,9 +161,21 @@ def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensordtype: torch.dtype = B.dtypeif dtype not in (torch.float32, torch.float64):dtype = torch.float32- A_LU, pivots, info = torch.lu(A.to(dtype), get_infos=True)+ if not torch_version_geq(1, 13):+ A_LU, pivots, info = torch.lu(A.to(dtype), True, get_infos=True)+ else:+ A_LU, pivots, info = torch.linalg.lu_factor_ex(A.to(dtype))+valid_mask: torch.Tensor = info == 0- X = torch.lu_solve(B.to(dtype), A_LU, pivots)+ n_dim_B = len(B.shape)+ n_dim_A = len(A.shape)+ if n_dim_A - n_dim_B == 1:+ B = B.unsqueeze(-1)++ if not torch_version_geq(1, 13):+ X = torch.lu_solve(B.to(dtype), A_LU, pivots)+ else:+ X = torch.linalg.lu_solve(A_LU, pivots, B.to(dtype))return X.to(B.dtype), A_LU.to(A.dtype), valid_maskdiff --git a/test/geometry/epipolar/test_fundamental.py b/test/geometry/epipolar/test_fundamental.pyindex 33ba68925..9e2c4d13f 100644--- a/test/geometry/epipolar/test_fundamental.py+++ b/test/geometry/epipolar/test_fundamental.py@@ -76,13 +76,13 @@ class TestNormalizeTransformation:class TestFindFundamental:def test_smoke(self, device, dtype):- points1 = torch.rand(1, 1, 2, device=device, dtype=dtype)- points2 = torch.rand(1, 1, 2, device=device, dtype=dtype)- weights = torch.ones(1, 1, device=device, dtype=dtype)+ points1 = torch.rand(1, 8, 2, device=device, dtype=dtype)+ points2 = torch.rand(1, 8, 2, device=device, dtype=dtype)+ weights = torch.ones(1, 8, device=device, dtype=dtype)F_mat = epi.find_fundamental(points1, points2, weights)assert F_mat.shape == (1, 3, 3)- @pytest.mark.parametrize("batch_size, num_points", [(1, 2), (2, 3), (3, 2)])+ @pytest.mark.parametrize("batch_size, num_points", [(1, 8), (2, 9), (3, 10)])def test_shape(self, batch_size, num_points, device, dtype):B, N = batch_size, num_pointspoints1 = torch.rand(B, N, 2, device=device, dtype=dtype)@@ -91,7 +91,16 @@ class TestFindFundamental:F_mat = epi.find_fundamental(points1, points2, weights)assert F_mat.shape == (B, 3, 3)- def test_opencv(self, device, dtype):+ @pytest.mark.parametrize("batch_size, num_points", [(1, 8), (2, 8), (3, 10)])+ def test_shape_noweights(self, batch_size, num_points, device, dtype):+ B, N = batch_size, num_points+ points1 = torch.rand(B, N, 2, device=device, dtype=dtype)+ points2 = torch.rand(B, N, 2, device=device, dtype=dtype)+ weights = None+ F_mat = epi.find_fundamental(points1, points2, weights)+ assert F_mat.shape == (B, 3, 3)++ def test_opencv_svd(self, device, dtype):points1 = torch.tensor([[diff --git a/test/geometry/test_homography.py b/test/geometry/test_homography.pyindex e41975587..0caa555d2 100644--- a/test/geometry/test_homography.py+++ b/test/geometry/test_homography.py@@ -153,6 +153,14 @@ class TestFindHomographyDLT:H = find_homography_dlt(points1, points2, weights)assert H.shape == (1, 3, 3)+ def test_nocrash_lu(self, device, dtype):+ points1 = torch.rand(1, 4, 2, device=device, dtype=dtype)+ points2 = torch.rand(1, 4, 2, device=device, dtype=dtype)+ weights = torch.ones(1, 4, device=device, dtype=dtype)+ points1[0, 0, 0] = float('nan')+ H = find_homography_dlt(points1, points2, weights, 'lu')+ assert H.shape == (1, 3, 3)+@pytest.mark.parametrize("batch_size, num_points", [(1, 4), (2, 5), (3, 6)])def test_shape(self, batch_size, num_points, device, dtype):B, N = batch_size, num_points@@ -182,7 +190,7 @@ class TestFindHomographyDLT:assert_close(H_noweights, H_withweights, rtol=1e-3, atol=1e-4)@pytest.mark.parametrize("batch_size", [1, 2, 5])- def test_clean_points(self, batch_size, device, dtype):+ def test_clean_points_svd(self, batch_size, device, dtype):# generate input datapoints_src = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)H = kornia.eye_like(3, points_src)@@ -193,7 +201,23 @@ class TestFindHomographyDLT:weights = torch.ones(batch_size, 10, device=device, dtype=dtype)# compute transform from source to target- dst_homo_src = find_homography_dlt(points_src, points_dst, weights)+ dst_homo_src = find_homography_dlt(points_src, points_dst, weights, 'svd')++ assert_close(kornia.geometry.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)++ @pytest.mark.parametrize("batch_size", [1, 2, 5])+ def test_clean_points_lu(self, batch_size, device, dtype):+ # generate input data+ points_src = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)+ H = kornia.eye_like(3, points_src)+ H = H * 0.3 * torch.rand_like(H)+ H = H / H[:, 2:3, 2:3]++ points_dst = kornia.geometry.transform_points(H, points_src)+ weights = torch.ones(batch_size, 10, device=device, dtype=dtype)++ # compute transform from source to target+ dst_homo_src = find_homography_dlt(points_src, points_dst, weights, 'lu')assert_close(kornia.geometry.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)@@ -237,6 +261,50 @@ class TestFindHomographyDLT:torch.manual_seed(initial_seed)return+ @pytest.mark.grad+ @pytest.mark.skipif(torch.__version__ < '1.7', reason="pytorch bug of incopatible types: #33546 fixed in v1.7")+ def test_gradcheck_lu(self, device):+ # Save initial seed+ initial_seed = torch.random.initial_seed()+ max_number_of_checks = 10++ # Test gradients for a max_number_of_checks times+ current_seed = initial_seed+ for i in range(max_number_of_checks):+ torch.manual_seed(current_seed)+ points_src = torch.rand(1, 10, 2, device=device, dtype=torch.float64, requires_grad=True)+ points_dst = torch.rand_like(points_src)+ weights = torch.ones_like(points_src)[..., 0]+ try:+ gradcheck(+ find_homography_dlt,+ (points_src, points_dst, weights, 'lu'),+ rtol=1e-6,+ atol=1e-6,+ raise_exception=True,+ )++ # Gradcheck failed+ except RuntimeError:++ # All iterations failed+ if i == max_number_of_checks - 1:+ assert gradcheck(+ find_homography_dlt,+ (points_src, points_dst, weights, 'lu'),+ rtol=1e-6,+ atol=1e-6,+ raise_exception=True,+ )+ # Next iteration+ else:+ current_seed = random.randrange(0xFFFFFFFFFFFFFFFF)+ continue++ # Gradcheck succeed+ torch.manual_seed(initial_seed)+ return+class TestFindHomographyFromLinesDLT:def test_smoke(self, device, dtype):diff --git a/test/geometry/test_ransac.py b/test/geometry/test_ransac.pyindex 5ab87770e..706fad9bc 100644--- a/test/geometry/test_ransac.py+++ b/test/geometry/test_ransac.py@@ -38,7 +38,6 @@ class TestRANSACHomography:assert_close(transform_points(dst_homo_src[None], points_src[:, :-1]), points_dst[:, :-1], rtol=1e-3, atol=1e-3)- @pytest.mark.xfail(reason="might slightly and randomly imprecise due to RANSAC randomness")@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)def test_real_clean(self, device, dtype, data):# generate input data@@ -52,9 +51,8 @@ class TestRANSACHomography:# compute transform from source to targetdst_homo_src, _ = ransac(pts_src, pts_dst)- assert_close(transform_points(dst_homo_src[None], pts_src[None]), pts_dst[None], rtol=1e-3, atol=1e-3)+ assert_close(transform_points(dst_homo_src[None], pts_src[None]), pts_dst[None], rtol=1e-2, atol=1.0)- @pytest.mark.xfail(reason="might slightly and randomly imprecise due to RANSAC randomness")@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)def test_real_dirty(self, device, dtype, data):# generate input data@@ -73,7 +71,7 @@ class TestRANSACHomography:dst_homo_src, _ = ransac(kp1, kp2)# Reprojection error of 5px is OK- assert_close(transform_points(dst_homo_src[None], pts_src[None]), pts_dst[None], rtol=5, atol=0.15)+ assert_close(transform_points(dst_homo_src[None], pts_src[None]), pts_dst[None], rtol=0.15, atol=5)@pytest.mark.skip(reason="find_homography_dlt is using try/except block")def test_jit(self, device, dtype):@@ -178,6 +176,7 @@ class TestRANSACFundamental:)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)points1 = torch.rand(8, 2, device=device, dtype=dtype)diff --git a/test/utils/test_helpers.py b/test/utils/test_helpers.pyindex 69ac74fc8..cd86c2ac1 100644--- a/test/utils/test_helpers.py+++ b/test/utils/test_helpers.py@@ -131,7 +131,7 @@ class TestSolveWithMask:)def test_all_bad(self, device, dtype):A = torch.ones(10, 3, 3, device=device, dtype=dtype)- B = torch.ones(3, 10, device=device, dtype=dtype)+ B = torch.ones(10, 3, device=device, dtype=dtype)X, _, mask = safe_solve_with_mask(B, A)assert torch.equal(mask, torch.zeros_like(mask))