Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

making epipolar metrics work with volumetric tensors (#1656)

nitaifingerhut7a49fd98436c
diff --git a/kornia/geometry/epipolar/_metrics.py b/kornia/geometry/epipolar/_metrics.py
index 6077e1bac..b2ff6d6b8 100644
--- a/kornia/geometry/epipolar/_metrics.py
+++ b/kornia/geometry/epipolar/_metrics.py
@@ -1,112 +1,113 @@
"""Module including useful metrics for Structure from Motion."""
-import torch
+from torch import Tensor
from kornia.geometry.conversions import convert_points_to_homogeneous
def sampson_epipolar_distance(
- pts1: torch.Tensor, pts2: torch.Tensor, Fm: torch.Tensor, squared: bool = True, eps: float = 1e-8
-) -> torch.Tensor:
+ pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool = True, eps: float = 1e-8
+) -> Tensor:
r"""Return Sampson distance for correspondences given the fundamental matrix.
Args:
pts1: correspondences from the left images with shape
- (B, N, 2 or 3). If they are not homogeneous, converted automatically.
+ (*, N, 2 or 3). If they are not homogeneous, converted automatically.
pts2: correspondences from the right images with shape
- (B, N, 2 or 3). If they are not homogeneous, converted automatically.
- Fm: Fundamental matrices with shape :math:`(B, 3, 3)`. Called Fm to
+ (*, 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.
squared: if True (default), the squared distance is returned.
eps: Small constant for safe sqrt.
Returns:
- the computed Sampson distance with shape :math:`(B, N)`.
+ the computed Sampson distance with shape :math:`(*, N)`.
"""
- if not isinstance(Fm, torch.Tensor):
+ if not isinstance(Fm, Tensor):
raise TypeError(f"Fm type is not a torch.Tensor. Got {type(Fm)}")
- if (len(Fm.shape) != 3) or not Fm.shape[-2:] == (3, 3):
+ 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.size(-1) == 2:
+ if pts1.shape[-1] == 2:
pts1 = convert_points_to_homogeneous(pts1)
- if pts2.size(-1) == 2:
+ if pts2.shape[-1] == 2:
pts2 = convert_points_to_homogeneous(pts2)
# From Hartley and Zisserman, Sampson error (11.9)
# sam = (x'^T F x) ** 2 / ( (((Fx)_1**2) + (Fx)_2**2)) + (((F^Tx')_1**2) + (F^Tx')_2**2)) )
- # line1_in_2: torch.Tensor = (F @ pts1.permute(0,2,1)).permute(0,2,1)
- # line2_in_1: torch.Tensor = (F.permute(0,2,1) @ pts2.permute(0,2,1)).permute(0,2,1)
+ # line1_in_2 = (F @ pts1.transpose(dim0=-2, dim1=-1)).transpose(dim0=-2, dim1=-1)
+ # line2_in_1 = (F.transpose(dim0=-2, dim1=-1) @ pts2.transpose(dim0=-2, dim1=-1)).transpose(dim0=-2, dim1=-1)
+
# Instead we can just transpose F once and switch the order of multiplication
- F_t: torch.Tensor = Fm.permute(0, 2, 1)
- line1_in_2: torch.Tensor = pts1 @ F_t
- line2_in_1: torch.Tensor = pts2 @ Fm
+ F_t: Tensor = Fm.transpose(dim0=-2, dim1=-1)
+ line1_in_2: Tensor = pts1 @ F_t
+ line2_in_1: Tensor = pts2 @ Fm
# numerator = (x'^T F x) ** 2
- numerator: torch.Tensor = (pts2 * line1_in_2).sum(2).pow(2)
+ numerator: Tensor = (pts2 * line1_in_2).sum(dim=-1).pow(2)
# denominator = (((Fx)_1**2) + (Fx)_2**2)) + (((F^Tx')_1**2) + (F^Tx')_2**2))
- denominator: torch.Tensor = line1_in_2[..., :2].norm(2, dim=2).pow(2) + line2_in_1[..., :2].norm(2, dim=2).pow(2)
- out: torch.Tensor = numerator / denominator
+ denominator: Tensor = line1_in_2[..., :2].norm(2, dim=-1).pow(2) + line2_in_1[..., :2].norm(2, dim=-1).pow(2)
+ out: Tensor = numerator / denominator
if squared:
return out
return (out + eps).sqrt()
def symmetrical_epipolar_distance(
- pts1: torch.Tensor, pts2: torch.Tensor, Fm: torch.Tensor, squared: bool = True, eps: float = 1e-8
-) -> torch.Tensor:
+ pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool = True, eps: float = 1e-8
+) -> Tensor:
r"""Return symmetrical epipolar distance for correspondences given the fundamental matrix.
Args:
pts1: correspondences from the left images with shape
- (B, N, 2 or 3). If they are not homogeneous, converted automatically.
+ (*, N, 2 or 3). If they are not homogeneous, converted automatically.
pts2: correspondences from the right images with shape
- (B, N, 2 or 3). If they are not homogeneous, converted automatically.
- Fm: Fundamental matrices with shape :math:`(B, 3, 3)`. Called Fm to
+ (*, 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.
squared: if True (default), the squared distance is returned.
eps: Small constant for safe sqrt.
Returns:
- the computed Symmetrical distance with shape :math:`(B, N)`.
+ the computed Symmetrical distance with shape :math:`(*, N)`.
"""
- if not isinstance(Fm, torch.Tensor):
+ if not isinstance(Fm, Tensor):
raise TypeError(f"Fm type is not a torch.Tensor. Got {type(Fm)}")
- if (len(Fm.shape) != 3) or not Fm.shape[-2:] == (3, 3):
+ 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.size(-1) == 2:
+ if pts1.shape[-1] == 2:
pts1 = convert_points_to_homogeneous(pts1)
- if pts2.size(-1) == 2:
+ if pts2.shape[-1] == 2:
pts2 = convert_points_to_homogeneous(pts2)
# From Hartley and Zisserman, symmetric epipolar distance (11.10)
# sed = (x'^T F x) ** 2 / (((Fx)_1**2) + (Fx)_2**2)) + 1/ (((F^Tx')_1**2) + (F^Tx')_2**2))
- # line1_in_2: torch.Tensor = (F @ pts1.permute(0,2,1)).permute(0,2,1)
- # line2_in_1: torch.Tensor = (F.permute(0,2,1) @ pts2.permute(0,2,1)).permute(0,2,1)
+ # line1_in_2 = (F @ pts1.transpose(dim0=-2, dim1=-1)).transpose(dim0=-2, dim1=-1)
+ # line2_in_1 = (F.transpose(dim0=-2, dim1=-1) @ pts2.transpose(dim0=-2, dim1=-1)).transpose(dim0=-2, dim1=-1)
# Instead we can just transpose F once and switch the order of multiplication
- F_t: torch.Tensor = Fm.permute(0, 2, 1)
- line1_in_2: torch.Tensor = pts1 @ F_t
- line2_in_1: torch.Tensor = pts2 @ Fm
+ F_t: Tensor = Fm.transpose(dim0=-2, dim1=-1)
+ line1_in_2: Tensor = pts1 @ F_t
+ line2_in_1: Tensor = pts2 @ Fm
# numerator = (x'^T F x) ** 2
- numerator: torch.Tensor = (pts2 * line1_in_2).sum(2).pow(2)
+ numerator: Tensor = (pts2 * line1_in_2).sum(dim=-1).pow(2)
# denominator_inv = 1/ (((Fx)_1**2) + (Fx)_2**2)) + 1/ (((F^Tx')_1**2) + (F^Tx')_2**2))
- denominator_inv: torch.Tensor = 1.0 / (line1_in_2[..., :2].norm(2, dim=2).pow(2)) + 1.0 / (
- line2_in_1[..., :2].norm(2, dim=2).pow(2)
+ denominator_inv: Tensor = 1.0 / (line1_in_2[..., :2].norm(2, dim=-1).pow(2)) + 1.0 / (
+ line2_in_1[..., :2].norm(2, dim=-1).pow(2)
)
- out: torch.Tensor = numerator * denominator_inv
+ out: Tensor = numerator * denominator_inv
if squared:
return out
return (out + eps).sqrt()
diff --git a/test/geometry/epipolar/test_epipolar_metrics.py b/test/geometry/epipolar/test_epipolar_metrics.py
index 71500790c..bd536dc0a 100644
--- a/test/geometry/epipolar/test_epipolar_metrics.py
+++ b/test/geometry/epipolar/test_epipolar_metrics.py
@@ -20,6 +20,21 @@ class TestSymmetricalEpipolarDistance:
Fm = utils.create_random_fundamental_matrix(1).type_as(pts1)
assert epi.symmetrical_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.symmetrical_epipolar_distance(pts1[:, t, ...], pts2[:, t, ...], Fm[:, t, ...])
+ for t in range(num_frames)
+ ],
+ dim=1,
+ )
+ dist_all_frames = epi.symmetrical_epipolar_distance(pts1, pts2, Fm)
+ assert_close(dist_frame_by_frame, dist_all_frames, atol=1e-6, rtol=1e-6)
+
def test_gradcheck(self, device):
# generate input data
batch_size, num_points, num_dims = 2, 3, 2
@@ -50,6 +65,18 @@ class TestSampsonEpipolarDistance:
Fm = utils.create_random_fundamental_matrix(1).type_as(pts1)
assert epi.sampson_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.sampson_epipolar_distance(pts1[:, t, ...], pts2[:, t, ...], Fm[:, t, ...]) for t in range(num_frames)],
+ dim=1,
+ )
+ dist_all_frames = epi.sampson_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]