π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
new E decomposition without svd (#2920)
Tong Wei9866eef8654e
diff --git a/kornia/geometry/epipolar/__init__.py b/kornia/geometry/epipolar/__init__.pyindex 886367716..46f4ff6e2 100644--- a/kornia/geometry/epipolar/__init__.py+++ b/kornia/geometry/epipolar/__init__.py@@ -6,6 +6,7 @@ from ._metrics import ()from .essential import (decompose_essential_matrix,+ decompose_essential_matrix_no_svd,essential_from_fundamental,essential_from_Rt,find_essential,@@ -66,4 +67,5 @@ __all__ = ["get_perpendicular","get_closest_point_on_epipolar_line","find_essential",+ "decompose_essential_matrix_no_svd",]diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.pyindex 03fe92693..b00bab43e 100644--- a/kornia/geometry/epipolar/essential.py+++ b/kornia/geometry/epipolar/essential.py@@ -10,7 +10,7 @@ from kornia.geometry import solversfrom kornia.utils import eye_like, vec_likefrom kornia.utils.helpers import _torch_solve_cast, _torch_svd_cast-from .numeric import cross_product_matrix+from .numeric import cross_product_matrix, matrix_cofactor_tensorfrom .projection import depth_from_point, projection_from_KRtfrom .triangulation import triangulate_points@@ -22,6 +22,7 @@ __all__ = ["motion_from_essential","motion_from_essential_choose_solution","relative_camera_motion",+ "decompose_essential_matrix_no_svd",]@@ -327,6 +328,71 @@ def decompose_essential_matrix(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torchreturn (R1, R2, T)+def decompose_essential_matrix_no_svd(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ r"""Decompose the essential matrix to rotation and translation.++ Recover rotation and translation from essential matrices without SVD+ reference: Horn, Berthold KP. Recovering baseline and orientation from essential matrix[J].+ J. Opt. Soc. Am, 1990, 110.++ Args:+ E_mat: The essential matrix in the form of :math:`(*, 3, 3)`.++ Returns:+ A tuple containing the first and second possible rotation matrices and the translation vector.+ The shape of the tensors with be same input :math:`[(*, 3, 3), (*, 3, 3), (*, 3, 1)]`.+ """+ if not (len(E_mat.shape) >= 2 and E_mat.shape[-2:] == (3, 3)):+ raise AssertionError(E_mat.shape)+ elif len(E_mat.shape) != 3:+ E_mat = E_mat.view(-1, 3, 3)++ B = E_mat.shape[0]++ # Eq.18, choose the largest of the three possible pairwise cross-products+ e1, e2, e3 = E_mat[..., 0], E_mat[..., 1], E_mat[..., 2]++ # sqrt(1/2 trace(EE^T)), B+ scale_factor = torch.sqrt(0.5 * torch.diagonal(E_mat @ E_mat.transpose(-1, -2), dim1=-1, dim2=-2).sum(-1))++ # B, 3, 3+ cross_products = torch.stack([torch.cross(e1, e2), torch.cross(e2, e3), torch.cross(e3, e1)], dim=1)+ # B, 3, 1+ norms = torch.norm(cross_products, dim=-1, keepdim=True)++ # B, to select which b1+ largest = torch.argmax(norms, dim=-2)++ # B, 3, 3+ e_cross_products = scale_factor[:, None, None] * cross_products / norms++ # broadcast the index+ index_expanded = largest.unsqueeze(-1).expand(-1, -1, e_cross_products.size(-1))++ # slice at dim=1, select for each batch one b (e1*e2 or e2*e3 or e3*e1), B, 1, 3+ b1 = torch.gather(e_cross_products, dim=1, index=index_expanded).squeeze(1)+ # normalization+ b1_ = b1 / torch.norm(b1, dim=-1, keepdim=True)++ # skew-symmetric matrix+ B1 = torch.zeros((B, 3, 3), device=E_mat.device, dtype=E_mat.dtype)+ t0, t1, t2 = b1[:, 0], b1[:, 1], b1[:, 2]+ B1[:, 0, 1], B1[:, 1, 0] = -t2, t2+ B1[:, 0, 2], B1[:, 2, 0] = t1, -t1+ B1[:, 1, 2], B1[:, 2, 1] = -t0, t0++ # the second translation and rotation+ B2 = -B1+ b2 = -b1++ # Eq.24, recover R+ # (bb)R = Cofactors(E)^T - BE+ R1 = (matrix_cofactor_tensor(E_mat) - B1 @ E_mat) / (b1 * b1).sum().unsqueeze(-1)+ R2 = (matrix_cofactor_tensor(E_mat) - B2 @ E_mat) / (b2 * b2).sum().unsqueeze(-1)++ return (R1, R2, b1_.unsqueeze(-1))++def essential_from_Rt(R1: torch.Tensor, t1: torch.Tensor, R2: torch.Tensor, t2: torch.Tensor) -> torch.Tensor:r"""Get the Essential matrix from Camera motion (Rs and ts).diff --git a/kornia/geometry/epipolar/numeric.py b/kornia/geometry/epipolar/numeric.pyindex fd1dee0d0..6b17b7826 100644--- a/kornia/geometry/epipolar/numeric.py+++ b/kornia/geometry/epipolar/numeric.py@@ -26,3 +26,22 @@ def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:cross_product_matrix_flat = stack([zeros, -x2, x1, x2, zeros, -x0, -x1, x0, zeros], dim=-1)shape_ = x.shape[:-1] + (3, 3)return cross_product_matrix_flat.view(*shape_)+++def matrix_cofactor_tensor(matrix: torch.Tensor) -> torch.Tensor:+ """Cofactor matrix, refer to the numpy doc.++ Args:+ matrix: The input matrix in the shape :math:`(*, 3, 3)`.+ """+ det = torch.det(matrix)+ singular_mask = det != 0+ if singular_mask.sum() != 0:+ # B, 3, 3+ cofactor = torch.linalg.inv(matrix[singular_mask]).transpose(-2, -1) * det[:, None, None]+ # return cofactor matrix of the given matrix+ returned_cofactor = torch.zeros_like(matrix)+ returned_cofactor[singular_mask] = cofactor+ return returned_cofactor+ else:+ raise Exception("all singular matrices")diff --git a/tests/geometry/epipolar/test_essential.py b/tests/geometry/epipolar/test_essential.pyindex f95d4a37b..8eb80366f 100644--- a/tests/geometry/epipolar/test_essential.py+++ b/tests/geometry/epipolar/test_essential.py@@ -271,6 +271,96 @@ class TestDecomposeEssentialMatrix(BaseTester):self.gradcheck(eval_vec, (E_mat,))+class TestDecomposeEssentialMatrixNoSVD(BaseTester):+ def test_smoke(self, device, dtype):+ E_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)+ R1, R2, t = epi.decompose_essential_matrix_no_svd(E_mat)+ assert R1.shape == (1, 3, 3)+ assert R2.shape == (1, 3, 3)+ assert t.shape == (1, 3, 1)++ @pytest.mark.parametrize("batch_shape", [(3, 3), (1, 3, 3), (2, 3, 3), (2, 1, 3, 3), (3, 2, 1, 3, 3)])+ def test_shape(self, batch_shape, device, dtype):+ E_mat = torch.rand(batch_shape, device=device, dtype=dtype)+ R1, R2, t = epi.decompose_essential_matrix_no_svd(E_mat)+ if len(batch_shape) >= 2:+ batch_shape = E_mat.view(-1, 3, 3).shape+ assert R1.shape == batch_shape+ assert R2.shape == batch_shape+ assert t.shape == batch_shape[:-1] + (1,)++ def test_gradcheck(self, device):+ E_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)++ def eval_rot1(input):+ return epi.decompose_essential_matrix_no_svd(input)[0]++ def eval_rot2(input):+ return epi.decompose_essential_matrix_no_svd(input)[1]++ def eval_vec(input):+ return epi.decompose_essential_matrix_no_svd(input)[2]++ self.gradcheck(eval_rot1, (E_mat,))+ self.gradcheck(eval_rot2, (E_mat,))+ self.gradcheck(eval_vec, (E_mat,))++ def test_correct_decompose(self):+ E_mat = torch.tensor([[[0.2057, -3.8266, 3.1615], [4.5417, -1.0707, -2.2023], [-1.0975, 1.6386, -0.6590]]])+ R1, R2, t = epi.decompose_essential_matrix(E_mat)+ R1_1, R2_1, t_1 = epi.decompose_essential_matrix_no_svd(E_mat)+ # As the orders of two R solutions and t solutions might be different from epi.decompose_essential_matrix(),+ # we have to check on the correct ones+ rtol: float = 1e-4+ if (R1 - R1_1).abs().sum() < rtol:+ self.assert_close(R1, R1_1)+ self.assert_close(R2, R2_1)+ else:+ self.assert_close(R1, R2_1)+ self.assert_close(R2, R1_1)+ R1_1, R2_1 = R2_1, R1_1++ if (t - t_1).abs().sum() < rtol:+ self.assert_close(t, t_1)+ else:+ self.assert_close(t, -t_1)+ t_1 = -t_1.clone()+ self.assert_close(+ epi.essential_from_Rt(R1_1, t_1, R2_1, -t_1), epi.essential_from_Rt(R1, t, R2, -t), rtol=1e-3, atol=1e-3+ )++ @pytest.mark.xfail(reason="skip the tests where there are no solutions.")+ def test_consistency(self, device, dtype):+ scene = generate_two_view_random_scene(device, dtype)++ R1, t1 = scene["R1"], scene["t1"]+ R2, t2 = scene["R2"], scene["t2"]++ E_mat = epi.essential_from_Rt(R1, t1, R2, t2)++ # compare the decomposed R and t to the method with svd+ R1, R2, t = epi.decompose_essential_matrix(E_mat)+ R1_1, R2_1, t_1 = epi.decompose_essential_matrix_no_svd(E_mat)+ # As the orders of two R solutions and t solutions might be different from epi.decompose_essential_matrix(),+ # we have to check on the correct ones+ rtol: float = 1e-4+ if (R1 - R1_1).abs().sum() < rtol:+ self.assert_close(R1, R1_1)+ self.assert_close(R2, R2_1)+ else:+ self.assert_close(R1, R2_1)+ self.assert_close(R2, R1_1)+ R1_1, R2_1 = R2_1, R1_1++ if (t - t_1).abs().sum() < rtol:+ self.assert_close(t, t_1)+ else:+ self.assert_close(t, -t_1)+ t_1 = -t_1.clone()++ self.assert_close(epi.essential_from_Rt(R1_1, t_1, R2_1, -t_1), epi.essential_from_Rt(R1, t, R2, -t))++class TestMotionFromEssential(BaseTester):def test_smoke(self, device, dtype):E_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)