π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
more epipolar metrics (+`linalg` utility) (#1674)
nitaifingerhuta4d2a1df1139
diff --git a/docs/source/geometry.epipolar.rst b/docs/source/geometry.epipolar.rstindex 5eeafbb45..615ddf663 100644--- a/docs/source/geometry.epipolar.rst+++ b/docs/source/geometry.epipolar.rst@@ -33,6 +33,8 @@ Metrics.. autofunction:: sampson_epipolar_distance.. autofunction:: symmetrical_epipolar_distance+.. autofunction:: left_to_right_epipolar_distance+.. autofunction:: right_to_left_epipolar_distanceProjection----------diff --git a/docs/source/geometry.linalg.rst b/docs/source/geometry.linalg.rstindex 2e24e51e6..392661019 100644--- a/docs/source/geometry.linalg.rst+++ b/docs/source/geometry.linalg.rst@@ -8,3 +8,4 @@ kornia.geometry.linalg.. autofunction:: compose_transformations.. autofunction:: inverse_transformation.. autofunction:: transform_points+.. autofunction:: points_lines_distancesdiff --git a/kornia/geometry/epipolar/__init__.py b/kornia/geometry/epipolar/__init__.pyindex 0984e3e3f..e243f8170 100644--- a/kornia/geometry/epipolar/__init__.py+++ b/kornia/geometry/epipolar/__init__.py@@ -1,4 +1,9 @@-from ._metrics import sampson_epipolar_distance, symmetrical_epipolar_distance+from ._metrics import (+ left_to_right_epipolar_distance,+ right_to_left_epipolar_distance,+ sampson_epipolar_distance,+ symmetrical_epipolar_distance,+)from .essential import (decompose_essential_matrix,essential_from_fundamental,@@ -32,6 +37,8 @@ __all__ = ["cross_product_matrix","sampson_epipolar_distance","symmetrical_epipolar_distance",+ "left_to_right_epipolar_distance",+ "right_to_left_epipolar_distance","essential_from_fundamental","decompose_essential_matrix","essential_from_Rt",diff --git a/kornia/geometry/epipolar/_metrics.py b/kornia/geometry/epipolar/_metrics.pyindex b2ff6d6b8..abfcadb5c 100644--- a/kornia/geometry/epipolar/_metrics.py+++ b/kornia/geometry/epipolar/_metrics.py@@ -3,6 +3,8 @@from torch import Tensorfrom kornia.geometry.conversions import convert_points_to_homogeneous+from kornia.geometry.linalg import point_line_distance+from kornia.testing import KORNIA_CHECK_IS_TENSORdef sampson_epipolar_distance(@@ -111,3 +113,70 @@ def symmetrical_epipolar_distance(if squared:return outreturn (out + eps).sqrt()+++def left_to_right_epipolar_distance(pts1: Tensor, pts2: Tensor, Fm: Tensor) -> Tensor:+ r"""Return one-sided epipolar distance for correspondences given the fundamental+ matrix.++ This method measures the distance from points in the right images to the epilines+ of the corresponding points in the left images as they reflect in the right images.++ Args:+ pts1: correspondences from the left images with shape+ :math:`(*, N, 2 or 3)`. If they are not homogeneous, converted automatically.+ pts2: correspondences from the right images with shape+ :math:`(*, N, 2 or 3)`. If they are not homogeneous, converted automatically.+ Fm: Fundamental matrices with shape :math:`(*, 3, 3)`. Called Fm to+ avoid ambiguity with torch.nn.functional.++ Returns:+ the computed Symmetrical distance with shape :math:`(*, N)`.+ """+ KORNIA_CHECK_IS_TENSOR(pts1)+ KORNIA_CHECK_IS_TENSOR(pts2)+ KORNIA_CHECK_IS_TENSOR(Fm)++ if (len(Fm.shape) < 3) or not Fm.shape[-2:] == (3, 3):+ raise ValueError(f"Fm must be a (*, 3, 3) tensor. Got {Fm.shape}")++ if pts1.shape[-1] == 2:+ pts1 = convert_points_to_homogeneous(pts1)++ F_t: Tensor = Fm.transpose(dim0=-2, dim1=-1)+ line1_in_2: Tensor = pts1 @ F_t++ return point_line_distance(pts2, line1_in_2)+++def right_to_left_epipolar_distance(pts1: Tensor, pts2: Tensor, Fm: Tensor) -> Tensor:+ r"""Return one-sided epipolar distance for correspondences given the fundamental+ matrix.++ This method measures the distance from points in the left images to the epilines+ of the corresponding points in the right images as they reflect in the left images.++ Args:+ pts1: correspondences from the left images with shape+ :math:`(*, N, 2 or 3)`. If they are not homogeneous, converted automatically.+ pts2: correspondences from the right images with shape+ :math:`(*, N, 2 or 3)`. If they are not homogeneous, converted automatically.+ Fm: Fundamental matrices with shape :math:`(*, 3, 3)`. Called Fm to+ avoid ambiguity with torch.nn.functional.++ Returns:+ the computed Symmetrical distance with shape :math:`(*, N)`.+ """+ KORNIA_CHECK_IS_TENSOR(pts1)+ KORNIA_CHECK_IS_TENSOR(pts2)+ KORNIA_CHECK_IS_TENSOR(Fm)++ if (len(Fm.shape) < 3) or not Fm.shape[-2:] == (3, 3):+ raise ValueError(f"Fm must be a (*, 3, 3) tensor. Got {Fm.shape}")++ if pts2.shape[-1] == 2:+ pts2 = convert_points_to_homogeneous(pts2)++ line2_in_1: Tensor = pts2 @ Fm++ return point_line_distance(pts1, line2_in_1)diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.pyindex 1ccb643d6..38661a8f7 100644--- a/kornia/geometry/linalg.py+++ b/kornia/geometry/linalg.py@@ -1,6 +1,7 @@import torch+from torch import Tensor-from kornia.testing import check_is_tensor+from kornia.testing import KORNIA_CHECK_IS_TENSOR, check_is_tensorfrom .conversions import convert_points_from_homogeneous, convert_points_to_homogeneous@@ -9,6 +10,7 @@ __all__ = ["relative_transformation","inverse_transformation","transform_points",+ "point_line_distance",]@@ -172,14 +174,10 @@ def transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Techeck_is_tensor(points_1)if not trans_01.shape[0] == points_1.shape[0] and trans_01.shape[0] != 1:raise ValueError(- "Input batch size must be the same for both tensors or 1."- f"Got {trans_01.shape} and {points_1.shape}"+ "Input batch size must be the same for both tensors or 1." f"Got {trans_01.shape} and {points_1.shape}")if not trans_01.shape[-1] == (points_1.shape[-1] + 1):- raise ValueError(- "Last input dimensions must differ by one unit"- f"Got{trans_01} and {points_1}"- )+ raise ValueError("Last input dimensions must differ by one unit" f"Got{trans_01} and {points_1}")# We reshape to BxNxD in case we get more dimensions, e.g., MxBxNxDshape_inp = list(points_1.shape)@@ -200,5 +198,32 @@ def transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Tepoints_0 = points_0.reshape(shape_inp)return points_0++def point_line_distance(point: Tensor, line: Tensor, eps: float = 1e-9) -> Tensor:+ r"""Return the distance from points to lines.++ Args:+ point: (possibly homogeneous) points :math:`(*, N, 2 or 3)`.+ line: lines coefficients :math:`(a, b, c)` with shape :math:`(*, N, 3)`, where :math:`ax + by + c = 0`.+ eps: Small constant for safe sqrt.++ Returns:+ the computed distance with shape :math:`(*, N)`.+ """+ KORNIA_CHECK_IS_TENSOR(point)+ KORNIA_CHECK_IS_TENSOR(line)++ if not point.shape[-1] in (2, 3):+ raise ValueError(f"pts must be a (*, 2 or 3) tensor. Got {point.shape}")++ if not line.shape[-1] == 3:+ raise ValueError(f"lines must be a (*, 3) tensor. Got {line.shape}")++ numerator = (line[..., 0] * point[..., 0] + line[..., 1] * point[..., 1] + line[..., 2]).abs()+ denominator = line[..., :2].norm(dim=-1)++ return numerator / (denominator + eps)++# TODO:# - project_points: from opencvdiff --git a/test/geometry/epipolar/test_epipolar_metrics.py b/test/geometry/epipolar/test_epipolar_metrics.pyindex bd536dc0a..32b8d1a9d 100644--- a/test/geometry/epipolar/test_epipolar_metrics.py+++ b/test/geometry/epipolar/test_epipolar_metrics.py@@ -91,3 +91,93 @@ class TestSampsonEpipolarDistance:points2 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64)Fm = utils.create_random_fundamental_matrix(batch_size).type_as(points2)assert gradcheck(epi.sampson_epipolar_distance, (points1, points2, Fm), raise_exception=True)+++class TestLeftToRightEpipolarDistance:+ def test_smoke(self, device, dtype):+ pts1 = torch.rand(1, 4, 3, device=device, dtype=dtype)+ pts2 = torch.rand(1, 4, 3, device=device, dtype=dtype)+ Fm = utils.create_random_fundamental_matrix(1).type_as(pts1)+ assert epi.left_to_right_epipolar_distance(pts1, pts2, Fm).shape == (1, 4)++ def test_batch(self, device, dtype):+ batch_size = 5+ pts1 = torch.rand(batch_size, 4, 3, device=device, dtype=dtype)+ pts2 = torch.rand(batch_size, 4, 3, device=device, dtype=dtype)+ Fm = utils.create_random_fundamental_matrix(1).type_as(pts1)+ assert epi.left_to_right_epipolar_distance(pts1, pts2, Fm).shape == (5, 4)++ def test_frames(self, device, dtype):+ batch_size, num_frames, num_points = 5, 3, 4+ pts1 = torch.rand(batch_size, num_frames, num_points, 3)+ pts2 = torch.rand(batch_size, num_frames, num_points, 3)+ Fm = torch.stack([utils.create_random_fundamental_matrix(1).type_as(pts1) for _ in range(num_frames)], dim=1)+ dist_frame_by_frame = torch.stack(+ [+ epi.left_to_right_epipolar_distance(pts1[:, t, ...], pts2[:, t, ...], Fm[:, t, ...])+ for t in range(num_frames)+ ],+ dim=1,+ )+ dist_all_frames = epi.left_to_right_epipolar_distance(pts1, pts2, Fm)+ assert_close(dist_frame_by_frame, dist_all_frames, atol=1e-6, rtol=1e-6)++ def test_shift(self, device, dtype):+ pts1 = torch.zeros(3, 2, device=device, dtype=dtype)[None]+ pts2 = torch.tensor([[2, 0.0], [2, 1], [2, 2.0]], device=device, dtype=dtype)[None]+ Fm = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], dtype=dtype, device=device)[None]+ expected = torch.tensor([0.0, 1.0, 2.0], device=device, dtype=dtype)[None]+ assert_close(epi.left_to_right_epipolar_distance(pts1, pts2, Fm), expected, atol=1e-4, rtol=1e-4)++ def test_gradcheck(self, device):+ # generate input data+ batch_size, num_points, num_dims = 2, 3, 2+ points1 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64, requires_grad=True)+ points2 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64)+ Fm = utils.create_random_fundamental_matrix(batch_size).type_as(points2)+ assert gradcheck(epi.left_to_right_epipolar_distance, (points1, points2, Fm), raise_exception=True)+++class TestRightToLeftEpipolarDistance:+ def test_smoke(self, device, dtype):+ pts1 = torch.rand(1, 4, 3, device=device, dtype=dtype)+ pts2 = torch.rand(1, 4, 3, device=device, dtype=dtype)+ Fm = utils.create_random_fundamental_matrix(1).type_as(pts1)+ assert epi.right_to_left_epipolar_distance(pts1, pts2, Fm).shape == (1, 4)++ def test_batch(self, device, dtype):+ batch_size = 5+ pts1 = torch.rand(batch_size, 4, 3, device=device, dtype=dtype)+ pts2 = torch.rand(batch_size, 4, 3, device=device, dtype=dtype)+ Fm = utils.create_random_fundamental_matrix(1).type_as(pts1)+ assert epi.right_to_left_epipolar_distance(pts1, pts2, Fm).shape == (5, 4)++ def test_frames(self, device, dtype):+ batch_size, num_frames, num_points = 5, 3, 4+ pts1 = torch.rand(batch_size, num_frames, num_points, 3)+ pts2 = torch.rand(batch_size, num_frames, num_points, 3)+ Fm = torch.stack([utils.create_random_fundamental_matrix(1).type_as(pts1) for _ in range(num_frames)], dim=1)+ dist_frame_by_frame = torch.stack(+ [+ epi.right_to_left_epipolar_distance(pts1[:, t, ...], pts2[:, t, ...], Fm[:, t, ...])+ for t in range(num_frames)+ ],+ dim=1,+ )+ dist_all_frames = epi.right_to_left_epipolar_distance(pts1, pts2, Fm)+ assert_close(dist_frame_by_frame, dist_all_frames, atol=1e-6, rtol=1e-6)++ def test_shift(self, device, dtype):+ pts1 = torch.zeros(3, 2, device=device, dtype=dtype)[None]+ pts2 = torch.tensor([[2, 0.0], [2, 1], [2, 2.0]], device=device, dtype=dtype)[None]+ Fm = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], dtype=dtype, device=device)[None]+ expected = torch.tensor([0.0, 1.0, 2.0], device=device, dtype=dtype)[None]+ assert_close(epi.right_to_left_epipolar_distance(pts1, pts2, Fm), expected, atol=1e-4, rtol=1e-4)++ def test_gradcheck(self, device):+ # generate input data+ batch_size, num_points, num_dims = 2, 3, 2+ points1 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64, requires_grad=True)+ points2 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64)+ Fm = utils.create_random_fundamental_matrix(batch_size).type_as(points2)+ assert gradcheck(epi.right_to_left_epipolar_distance, (points1, points2, Fm), raise_exception=True)diff --git a/test/geometry/test_linalg.py b/test/geometry/test_linalg.pyindex 4892ffc0b..852ec28ec 100644--- a/test/geometry/test_linalg.py+++ b/test/geometry/test_linalg.py@@ -3,6 +3,7 @@ import torchfrom torch.autograd import gradcheckimport kornia+import kornia.geometry.linalg as kglimport kornia.testing as utils # test utilsfrom kornia.testing import assert_close@@ -93,11 +94,11 @@ class TestTransformPoints:dst_homo_src = dst_homo_src.to(device)# transform the points from dst to ref- points_dst = kornia.geometry.linalg.transform_points(dst_homo_src, points_src)+ points_dst = kgl.transform_points(dst_homo_src, points_src)# transform the points from ref to dstsrc_homo_dst = torch.inverse(dst_homo_src)- points_dst_to_src = kornia.geometry.linalg.transform_points(src_homo_dst, points_dst)+ points_dst_to_src = kgl.transform_points(src_homo_dst, points_dst)# projected should be equal as initialassert_close(points_src, points_dst_to_src, atol=1e-4, rtol=1e-4)@@ -166,7 +167,7 @@ class TestComposeTransforms:trans_12 = identity_matrix(batch_size=1, device=device, dtype=dtype)[0]trans_12[..., :3, -1] += offset # add offset to translation vector- trans_02 = kornia.geometry.linalg.compose_transformations(trans_01, trans_12)+ trans_02 = kgl.compose_transformations(trans_01, trans_12)assert_close(trans_02, trans_12, atol=1e-4, rtol=1e-4)@pytest.mark.parametrize("batch_size", [1, 2, 5])@@ -176,7 +177,7 @@ class TestComposeTransforms:trans_12 = identity_matrix(batch_size, device=device, dtype=dtype)trans_12[..., :3, -1] += offset # add offset to translation vector- trans_02 = kornia.geometry.linalg.compose_transformations(trans_01, trans_12)+ trans_02 = kgl.compose_transformations(trans_01, trans_12)assert_close(trans_02, trans_12, atol=1e-4, rtol=1e-4)@pytest.mark.parametrize("batch_size", [1, 2, 5])@@ -186,7 +187,7 @@ class TestComposeTransforms:trans_01 = utils.tensor_to_gradcheck_var(trans_01) # to vartrans_12 = utils.tensor_to_gradcheck_var(trans_12) # to var- assert gradcheck(kornia.geometry.linalg.compose_transformations, (trans_01, trans_12), raise_exception=True)+ assert gradcheck(kgl.compose_transformations, (trans_01, trans_12), raise_exception=True)class TestInverseTransformation:@@ -222,8 +223,8 @@ class TestInverseTransformation:trans_01 = identity_matrix(batch_size=1, device=device, dtype=dtype)[0]trans_01[..., :3, -1] += offset # add offset to translation vector- trans_10 = kornia.geometry.linalg.inverse_transformation(trans_01)- trans_01_hat = kornia.geometry.linalg.inverse_transformation(trans_10)+ trans_10 = kgl.inverse_transformation(trans_01)+ trans_01_hat = kgl.inverse_transformation(trans_10)assert_close(trans_01, trans_01_hat, atol=1e-4, rtol=1e-4)@pytest.mark.parametrize("batch_size", [1, 2, 5])@@ -232,8 +233,8 @@ class TestInverseTransformation:trans_01 = identity_matrix(batch_size, device=device, dtype=dtype)trans_01[..., :3, -1] += offset # add offset to translation vector- trans_10 = kornia.geometry.linalg.inverse_transformation(trans_01)- trans_01_hat = kornia.geometry.linalg.inverse_transformation(trans_10)+ trans_10 = kgl.inverse_transformation(trans_01)+ trans_01_hat = kgl.inverse_transformation(trans_10)assert_close(trans_01, trans_01_hat, atol=1e-4, rtol=1e-4)@pytest.mark.parametrize("batch_size", [1, 2, 5])@@ -247,15 +248,15 @@ class TestInverseTransformation:trans_01[..., :3, -1] += offset # add offset to translation vectortrans_01[..., :3, :3] = rmat_01[..., :3, :3]- trans_10 = kornia.geometry.linalg.inverse_transformation(trans_01)- trans_01_hat = kornia.geometry.linalg.inverse_transformation(trans_10)+ trans_10 = kgl.inverse_transformation(trans_01)+ trans_01_hat = kgl.inverse_transformation(trans_10)assert_close(trans_01, trans_01_hat, atol=1e-4, rtol=1e-4)@pytest.mark.parametrize("batch_size", [1, 2, 5])def test_gradcheck(self, batch_size, device, dtype):trans_01 = identity_matrix(batch_size, device=device, dtype=dtype)trans_01 = utils.tensor_to_gradcheck_var(trans_01) # to var- assert gradcheck(kornia.geometry.linalg.inverse_transformation, (trans_01,), raise_exception=True)+ assert gradcheck(kgl.inverse_transformation, (trans_01,), raise_exception=True)class TestRelativeTransformation:@@ -301,8 +302,8 @@ class TestRelativeTransformation:trans_02 = identity_matrix(batch_size=1, device=device, dtype=dtype)[0]trans_02[..., :3, -1] += offset # add offset to translation vector- trans_12 = kornia.geometry.linalg.relative_transformation(trans_01, trans_02)- trans_02_hat = kornia.geometry.linalg.compose_transformations(trans_01, trans_12)+ trans_12 = kgl.relative_transformation(trans_01, trans_02)+ trans_02_hat = kgl.compose_transformations(trans_01, trans_12)assert_close(trans_02_hat, trans_02, atol=1e-4, rtol=1e-4)@pytest.mark.parametrize("batch_size", [1, 2, 5])@@ -317,8 +318,8 @@ class TestRelativeTransformation:trans_02[..., :3, -1] += offset # add offset to translation vectortrans_02[..., :3, :3] = rmat_02[..., :3, :3]- trans_12 = kornia.geometry.linalg.relative_transformation(trans_01, trans_02)- trans_02_hat = kornia.geometry.linalg.compose_transformations(trans_01, trans_12)+ trans_12 = kgl.relative_transformation(trans_01, trans_02)+ trans_02_hat = kgl.compose_transformations(trans_01, trans_12)assert_close(trans_02_hat, trans_02, atol=1e-4, rtol=1e-4)@pytest.mark.parametrize("batch_size", [1, 2, 5])@@ -328,4 +329,64 @@ class TestRelativeTransformation:trans_01 = utils.tensor_to_gradcheck_var(trans_01) # to vartrans_02 = utils.tensor_to_gradcheck_var(trans_02) # to var- assert gradcheck(kornia.geometry.linalg.relative_transformation, (trans_01, trans_02), raise_exception=True)+ assert gradcheck(kgl.relative_transformation, (trans_01, trans_02), raise_exception=True)+++class TestPointsLinesDistances:+ def test_smoke(self, device, dtype):+ pts = torch.rand(1, 1, 2, device=device, dtype=dtype)+ lines = torch.rand(1, 1, 3, device=device, dtype=dtype)+ distances = kgl.point_line_distance(pts, lines)+ assert distances.shape == (1, 1)++ # homogeneous+ pts = torch.rand(1, 1, 3, device=device, dtype=dtype)+ lines = torch.rand(1, 1, 3, device=device, dtype=dtype)+ distances = kgl.point_line_distance(pts, lines)+ assert distances.shape == (1, 1)++ @pytest.mark.parametrize(+ "batch_size, sample_size", [(1, 1), (2, 1), (4, 1), (7, 1), (1, 3), (2, 3), (4, 3), (7, 3)]+ )+ def test_shape(self, batch_size, sample_size, device, dtype):+ B, N = batch_size, sample_size+ pts = torch.rand(B, N, 2, device=device, dtype=dtype)+ lines = torch.rand(B, N, 3, device=device, dtype=dtype)+ distances = kgl.point_line_distance(pts, lines)+ assert distances.shape == (B, N)++ @pytest.mark.parametrize(+ "batch_size, extra_dim_size", [(1, 1), (2, 1), (4, 1), (7, 1), (1, 3), (2, 3), (4, 3), (7, 3)]+ )+ def test_shapes(self, batch_size, extra_dim_size, device, dtype):+ B, T, N = batch_size, extra_dim_size, 3+ pts = torch.rand(B, T, N, 2, device=device, dtype=dtype)+ lines = torch.rand(B, T, N, 3, device=device, dtype=dtype)+ distances = kgl.point_line_distance(pts, lines)+ assert distances.shape == (B, T, N)++ def test_functional(self, device):+ pts = torch.tensor([1.0, 0], device=device, dtype=torch.float64).view(1, 1, 2).tile(1, 6, 1)+ lines = torch.tensor(+ [[0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0], [1.0, 1.0, 0.0], [1.0, 1.0, 1.0], ],+ device=device,+ dtype=torch.float64,+ ).view(1, 6, 3)+ distances = kgl.point_line_distance(pts, lines)+ distances_expected = torch.tensor(+ [+ 0.0,+ 1.0,+ 1.0,+ 2.0,+ torch.sqrt(torch.tensor(2, dtype=torch.float64)) / 2,+ torch.sqrt(torch.tensor(2, dtype=torch.float64)),+ ],+ device=device,+ ).view(1, 6)+ assert_close(distances, distances_expected, rtol=1e-6, atol=1e-6)++ def test_gradcheck(self, device):+ pts = torch.rand(2, 3, 2, device=device, requires_grad=True, dtype=torch.float64)+ lines = torch.rand(2, 3, 3, device=device, requires_grad=True, dtype=torch.float64)+ assert gradcheck(kgl.point_line_distance, (pts, lines), raise_exception=True)