Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Feat] add epipolar geometry package (#569)

Edgar Ribacdc5689991f3
diff --git a/docs/source/data/epipolar_geometry.svg.png b/docs/source/data/epipolar_geometry.svg.png
new file mode 100644
index 000000000..dd4f11382
Binary files /dev/null and b/docs/source/data/epipolar_geometry.svg.png differ
diff --git a/docs/source/geometry.epipolar.rst b/docs/source/geometry.epipolar.rst
new file mode 100644
index 000000000..30a6a6e53
--- /dev/null
+++ b/docs/source/geometry.epipolar.rst
@@ -0,0 +1,57 @@
+kornia.geometry.epipolar
+========================
+
+.. currentmodule:: kornia.geometry.epipolar
+
+Module to with useful functionalities for epipolar geometry used by Structure from Motion
+
+.. image:: data/epipolar_geometry.svg.png
+
+
+Essential
+---------
+
+.. autofunction:: essential_from_fundamental
+.. autofunction:: essential_from_Rt
+.. autofunction:: decompose_essential_matrix
+.. autofunction:: motion_from_essential
+.. autofunction:: motion_from_essential_choose_solution
+.. autofunction:: relative_camera_motion
+
+Fundamental
+-----------
+
+.. autofunction:: find_fundamental
+.. autofunction:: fundamental_from_essential
+.. autofunction:: fundamental_from_projections
+.. autofunction:: compute_correspond_epilines
+.. autofunction:: normalize_points
+.. autofunction:: normalize_transformation
+
+Metrics
+-------
+
+.. autofunction:: sampson_epipolar_distance
+.. autofunction:: symmetrical_epipolar_distance
+
+Projection
+----------
+
+.. autofunction:: projection_from_KRt
+.. autofunction:: projections_from_fundamental
+.. autofunction:: scale_intrinsics
+.. autofunction:: intrinsics_like
+.. autofunction:: scale_intrinsics
+.. autofunction:: random_intrinsics
+
+Numeric
+-------
+
+.. autofunction:: cross_product_matrix
+.. autofunction:: eye_like
+.. autofunction:: vec_like
+
+Triangulation
+-------------
+
+.. autofunction:: triangulate_points
diff --git a/docs/source/geometry.rst b/docs/source/geometry.rst
index 35abe745d..5a03c7c9d 100644
--- a/docs/source/geometry.rst
+++ b/docs/source/geometry.rst
@@ -9,6 +9,7 @@ kornia.geometry
geometry.camera
geometry.conversions
geometry.depth
+ geometry.epipolar
geometry.linalg
geometry.transform
geometry.warp
diff --git a/kornia/color/normalize.py b/kornia/color/normalize.py
index 612dae52b..fb8467c0f 100644
--- a/kornia/color/normalize.py
+++ b/kornia/color/normalize.py
@@ -20,6 +20,7 @@ class Normalize(nn.Module):
std (torch.Tensor or float): Standard deviations for each channel.
"""
+
def __init__(self, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> None:
super(Normalize, self).__init__()
@@ -109,6 +110,7 @@ class Denormalize(nn.Module):
std (torch.Tensor or float): Standard deviations for each channel.
"""
+
def __init__(self, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> None:
super(Denormalize, self).__init__()
diff --git a/kornia/geometry/__init__.py b/kornia/geometry/__init__.py
index 2bff65407..e19690eb7 100644
--- a/kornia/geometry/__init__.py
+++ b/kornia/geometry/__init__.py
@@ -6,3 +6,4 @@ from kornia.geometry.warp import *
from kornia.geometry.depth import *
from kornia.geometry.dsnt import *
from kornia.geometry.spatial_soft_argmax import *
+from kornia.geometry.epipolar import *
diff --git a/kornia/geometry/epipolar/__init__.py b/kornia/geometry/epipolar/__init__.py
new file mode 100644
index 000000000..50ba0ae00
--- /dev/null
+++ b/kornia/geometry/epipolar/__init__.py
@@ -0,0 +1,7 @@
+from .numeric import *
+from .fundamental import *
+from .projection import *
+from .essential import *
+from .triangulation import *
+from .metrics import *
+from .scene import *
diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.py
new file mode 100644
index 000000000..211f92495
--- /dev/null
+++ b/kornia/geometry/epipolar/essential.py
@@ -0,0 +1,238 @@
+"""Module containing functionalities for the Essential matrix."""
+from typing import Tuple
+
+import torch
+
+from kornia.geometry.epipolar import numeric
+from kornia.geometry.epipolar import projection
+from kornia.geometry.epipolar import triangulation
+
+
+def essential_from_fundamental(F_mat: torch.Tensor, K1: torch.Tensor, K2: torch.Tensor) -> torch.Tensor:
+ r"""Get Essential matrix from Fundamental and Camera matrices.
+
+ Uses the method from Hartley/Zisserman 9.6 pag 257 (formula 9.12).
+
+ Args:
+ F_mat (torch.Tensor): The fundamental matrix with shape of :math:`(*, 3, 3)`.
+ K1 (torch.Tensor): The camera matrix from first camera with shape :math:`(*, 3, 3)`.
+ K2 (torch.Tensor): The camera matrix from second camera with shape :math:`(*, 3, 3)`.
+
+ Returns:
+ torch.Tensor: The essential matrix with shape :math:`(*, 3, 3)`.
+
+ """
+ assert len(F_mat.shape) >= 2 and F_mat.shape[-2:] == (3, 3), F_mat.shape
+ assert len(K1.shape) >= 2 and K1.shape[-2:] == (3, 3), K1.shape
+ assert len(K2.shape) >= 2 and K2.shape[-2:] == (3, 3), K2.shape
+ assert len(F_mat.shape[:-2]) == len(K1.shape[:-2]) == len(K2.shape[:-2])
+
+ return K2.transpose(-2, -1) @ F_mat @ K1
+
+
+def decompose_essential_matrix(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ r"""Decompose an essential matrix to possible rotations and translation.
+
+ This function decomposes the essential matrix E using svd decomposition [96]
+ and give the possible solutions: :math:`R1, R2, t`.
+
+ Args:
+ E_mat (torch.Tensor): The essential matrix in the form of :math:`(*, 3, 3)`.
+
+ Returns:
+ Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 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)]`.
+
+ """
+ assert len(E_mat.shape) >= 2 and E_mat.shape[-2:], E_mat.shape
+
+ # decompose matrix by its singular values
+ U, S, V = torch.svd(E_mat)
+ Vt = V.transpose(-2, -1)
+
+ mask = torch.ones_like(E_mat)
+ mask[..., -1:] *= -1. # fill last column with negative values
+
+ maskt = mask.transpose(-2, -1)
+
+ # avoid singularities
+ U = torch.where((torch.det(U) < 0.)[..., None, None], U * mask, U)
+ Vt = torch.where((torch.det(Vt) < 0.)[..., None, None], Vt * maskt, Vt)
+
+ W = numeric.cross_product_matrix(torch.tensor([[0., 0., 1.]]).type_as(E_mat))
+ W[..., 2, 2] += 1.
+
+ # reconstruct rotations and retrieve translation vector
+ U_W_Vt = U @ W @ Vt
+ U_Wt_Vt = U @ W.transpose(-2, -1) @ Vt
+
+ # return values
+ R1 = U_W_Vt
+ R2 = U_Wt_Vt
+ T = U[..., -1:]
+ return (R1, R2, T)
+
+
+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).
+
+ Reference: Hartley/Zisserman 9.6 pag 257 (formula 9.12)
+
+ Args:
+ R1 (torch.Tensor): The first camera rotation matrix with shape :math:`(*, 3, 3)`.
+ t1 (torch.Tensor): The first camera translation vector with shape :math:`(*, 3, 1)`.
+ R2 (torch.Tensor): The second camera rotation matrix with shape :math:`(*, 3, 3)`.
+ t2 (torch.Tensor): The second camera translation vector with shape :math:`(*, 3, 1)`.
+
+ Returns:
+ torch.Tensor: The Essential matrix with the shape :math:`(*, 3, 3)`.
+
+ """
+ assert len(R1.shape) >= 2 and R1.shape[-2:] == (3, 3), R1.shape
+ assert len(t1.shape) >= 2 and t1.shape[-2:] == (3, 1), t1.shape
+ assert len(R2.shape) >= 2 and R2.shape[-2:] == (3, 3), R2.shape
+ assert len(t2.shape) >= 2 and t2.shape[-2:] == (3, 1), t2.shape
+
+ # first compute the camera relative motion
+ R, t = relative_camera_motion(R1, t1, R2, t2)
+
+ # get the cross product from relative translation vector
+ Tx = numeric.cross_product_matrix(t[..., 0])
+
+ return (Tx @ R)
+
+
+def motion_from_essential(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ r"""Get Motion (R's and t's ) from Essential matrix.
+
+ Computes and return four possible poses exist for the decomposition of the Essential
+ matrix. The posible solutions are :math:`[R1,t], [R1,βˆ’t], [R2,t], [R2,βˆ’t]`.
+
+ Args:
+ E_mat (torch.Tensor): The essential matrix in the form of :math:`(*, 3, 3)`.
+
+ Returns:
+ Tuple[torch.Tensor, torch.Tensor]: The rotation and translation containing the four
+ possible combination for the retrieved motion. The tuple is as following :math:`[(*, 4, 3, 3), (*, 4, 3, 1)]`.
+
+ """
+ assert len(E_mat.shape) >= 2 and E_mat.shape[-2:], E_mat.shape
+
+ # decompose the essential matrix by its possible poses
+ R1, R2, t = decompose_essential_matrix(E_mat)
+
+ # compbine and returns the four possible solutions
+ Rs = torch.stack([R1, R1, R2, R2], dim=-3)
+ Ts = torch.stack([t, -t, t, -t], dim=-3)
+
+ return (Rs, Ts)
+
+
+def motion_from_essential_choose_solution(
+ E_mat: torch.Tensor,
+ K1: torch.Tensor,
+ K2: torch.Tensor,
+ x1: torch.Tensor,
+ x2: torch.Tensor
+) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ r"""Recovers the relative camera rotation and the translation from an estimated essential matrix.
+
+ The method check the corresponding points in two images and also returns the triangulated
+ 3d points. Internally uses :py:meth:`~kornia.geometry.epipolar.decompose_essential_matrix` and then chooses
+ the best solution based on the combination that gives more 3d points in front of the camera plane from
+ :py:meth:`~kornia.geometry.epipolar.triangulate_points`.
+
+ Args:
+ E_mat (torch.Tensor): The essential matrix in the form of :math:`(*, 3, 3)`.
+ K1 (torch.Tensor): The camera matrix from first camera with shape :math:`(*, 3, 3)`.
+ K2 (torch.Tensor): The camera matrix from second camera with shape :math:`(*, 3, 3)`.
+ x1 (torch.Tensor): The set of points seen from the first camera frame in the camera plane
+ coordinates with shape :math:`(*, N, 2)`.
+ x2 (torch.Tensor): The set of points seen from the first camera frame in the camera plane
+ coordinates with shape :math:`(*, N, 2)`.
+
+ Returns:
+ Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: The rotation and translation plus the
+ 3d triangulated points. The tuple is as following :math:`[(*, 3, 3), (*, 3, 1), (*, N, 3)]`.
+
+ """
+ assert len(E_mat.shape) >= 2 and E_mat.shape[-2:], E_mat.shape
+ assert len(K1.shape) >= 2 and K1.shape[-2:] == (3, 3), K1.shape
+ assert len(K2.shape) >= 2 and K2.shape[-2:] == (3, 3), K2.shape
+ assert len(x1.shape) >= 2 and x1.shape[-1] == 2, x1.shape
+ assert len(x2.shape) >= 2 and x2.shape[-1] == 2, x2.shape
+ assert len(E_mat.shape[:-2]) == len(K1.shape[:-2]) == len(K2.shape[:-2])
+
+ # compute four possible pose solutions
+ Rs, ts = motion_from_essential(E_mat)
+
+ # set reference view pose and compute projection matrix
+ R1 = numeric.eye_like(3, E_mat) # Bx3x3
+ t1 = numeric.vec_like(3, E_mat) # Bx3x1
+
+ # compute the projection matrices for first camera
+ R1 = R1[:, None].expand(-1, 4, -1, -1)
+ t1 = t1[:, None].expand(-1, 4, -1, -1)
+ K1 = K1[:, None].expand(-1, 4, -1, -1)
+ P1 = projection.projection_from_KRt(K1, R1, t1) # 1x4x4x4
+
+ # compute the projection matrices for second camera
+ R2 = Rs
+ t2 = ts
+ K2 = K2[:, None].expand(-1, 4, -1, -1)
+ P2 = projection.projection_from_KRt(K2, R2, t2) # Bx4x4x4
+
+ # triangulate the points
+ x1 = x1[:, None].expand(-1, 4, -1, -1)
+ x2 = x2[:, None].expand(-1, 4, -1, -1)
+ X = triangulation.triangulate_points(P1, P2, x1, x2) # Bx4xNx3
+
+ # project points and compute their depth values
+ d1 = projection.depth(R1, t1, X)
+ d2 = projection.depth(R2, t2, X)
+
+ # verify the point values that have a postive depth value
+ mask = ((d1 > 0.) & (d2 > 0.))
+ mask_indices = torch.max(mask.sum(-1), dim=-1, keepdim=True)[1]
+
+ # get pose and points 3d and return
+ R_out = Rs[:, mask_indices][:, 0, 0]
+ t_out = ts[:, mask_indices][:, 0, 0]
+ points3d_out = X[:, mask_indices][:, 0, 0]
+
+ return R_out, t_out, points3d_out
+
+
+def relative_camera_motion(
+ R1: torch.Tensor, t1: torch.Tensor, R2: torch.Tensor, t2: torch.Tensor
+) -> Tuple[torch.Tensor, torch.Tensor]:
+ r"""Computes the relative camera motion between two cameras.
+
+ Given the motion parameters of two cameras, computes the motion parameters of the second
+ one assuming the first one to be at the origin. If :math:`T1` and :math:`T2` are the camera motions,
+ the computed relative motion is :math:`T = T_{2}T^{βˆ’1}_{1}`.
+
+ Args:
+ R1 (torch.Tensor): The first camera rotation matrix with shape :math:`(*, 3, 3)`.
+ t1 (torch.Tensor): The first camera translation vector with shape :math:`(*, 3, 1)`.
+ R2 (torch.Tensor): The second camera rotation matrix with shape :math:`(*, 3, 3)`.
+ t2 (torch.Tensor): The second camera translation vector with shape :math:`(*, 3, 1)`.
+
+ Returns:
+ Tuple[torch.Tensor, torch.Tensor]: A tuple with the relatice rotation matrix and
+ translation vector with the shape of :math:`[(*, 3, 3), (*, 3, 1)]`.
+
+ """
+ assert len(R1.shape) >= 2 and R1.shape[-2:] == (3, 3), R1.shape
+ assert len(t1.shape) >= 2 and t1.shape[-2:] == (3, 1), t1.shape
+ assert len(R2.shape) >= 2 and R2.shape[-2:] == (3, 3), R2.shape
+ assert len(t2.shape) >= 2 and t2.shape[-2:] == (3, 1), t2.shape
+
+ # compute first the relative rotation
+ R = R2 @ R1.transpose(-2, -1)
+
+ # compute the relative translation vector
+ t = t2 - R @ t1
+
+ return (R, t)
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
new file mode 100644
index 000000000..c22911782
--- /dev/null
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -0,0 +1,212 @@
+"""Module containing the functionalities for computing the Fundamental Matrix."""
+
+from typing import Tuple
+
+import torch
+import kornia
+
+
+def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]:
+ r"""Normalizes points (isotropic).
+
+ Computes the transformation matrix such that the two principal moments of the set of points
+ are equal to unity, forming an approximately symmetric circular cloud of points of radius 1
+ about the origin. Reference: Hartley/Zisserman 4.4.4 pag.107
+
+ This operation is an essential step before applying the DLT algorithm in order to consider
+ the result as optimal.
+
+ Args:
+ points (torch.Tensor): Tensor containing the points to be normalized with shape :math:`(B, N, 2)`.
+ eps (float): epsilon value to avoid numerical unstabilities. Default: 1e-8.
+
+ Returns:
+ Tuple[torch.Tensor, torch.Tensor]: tuple containing the normalized points in the
+ shape :math:`(B, N, 2)` and the transformation matrix in the shape :math:`(B, 3, 3)`.
+
+ """
+ assert len(points.shape) == 3, points.shape
+ assert points.shape[-1] == 2, points.shape
+
+ x_mean = torch.mean(points, dim=1, keepdim=True) # Bx1x2
+
+ scale = (points - x_mean).norm(dim=-1).mean(dim=-1) # B
+ scale = torch.sqrt(torch.tensor(2.)) / (scale + eps) # B
+
+ ones, zeros = torch.ones_like(scale), torch.zeros_like(scale)
+
+ transform = torch.stack([
+ scale, zeros, -scale * x_mean[..., 0, 0],
+ zeros, scale, -scale * x_mean[..., 0, 1],
+ zeros, zeros, ones], dim=-1) # Bx9
+
+ transform = transform.view(-1, 3, 3) # Bx3x3
+ points_norm = kornia.transform_points(transform, points) # BxNx2
+
+ return (points_norm, transform)
+
+
+def normalize_transformation(M: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
+ r"""Normalizes a given transformation matrix.
+
+ The function trakes the transformation matrix and normalize so that the value in
+ the last row and column is one.
+
+ Args:
+ M (torch.Tensor): The transformation to be normalized of any shape with a minimum size of 2x2.
+ eps (float): small value to avoid unstabilities during the backpropagation.
+
+ Returns:
+ torch.Tensor: the normalized transformation matrix with same shape as the input.
+
+ """
+ assert len(M.shape) >= 2, M.shape
+ norm_val: torch.Tensor = M[..., -1:, -1:]
+ return torch.where(norm_val.abs() > eps, M / (norm_val + eps), M)
+
+
+def find_fundamental(points1: torch.Tensor, points2: torch.Tensor, weights: torch.Tensor) -> torch.Tensor:
+ r"""Computes 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 (torch.Tensor): A set of points in the first image with a tensor shape :math:`(B, N, 2)`.
+ points2 (torch.Tensor): A set of points in the second image with a tensor shape :math:`(B, N, 2)`.
+ weights (torch.Tensor): Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.
+
+ Returns:
+ torch.Tensor: the computed fundamental matrix with shape :math:`(B, 3, 3)`.
+
+ """
+ assert points1.shape == points2.shape, (points1.shape, points2.shape)
+ assert len(weights.shape) == 2 and weights.shape[1] == points1.shape[1], weights.shape
+
+ points1_norm, transform1 = normalize_points(points1)
+ points2_norm, transform2 = normalize_points(points2)
+
+ x1, y1 = torch.chunk(points1_norm, dim=-1, chunks=2) # Bx1xN
+ x2, y2 = torch.chunk(points2_norm, dim=-1, chunks=2) # Bx1xN
+
+ ones = torch.ones_like(x1)
+
+ # build equations system and solve DLT
+ # https://www.cc.gatech.edu/~afb/classes/CS4495-Fall2013/slides/CS4495-09-TwoViews-2.pdf
+ # [x * x', x * y', x, y * x', y * y', y, x', y', 1]
+
+ X = 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
+
+ # compute eigevectors and retrieve the one with the smallest eigenvalue
+ _, _, V = torch.svd(X)
+ F_mat = V[..., -1].view(-1, 3, 3)
+
+ # reconstruct and force the matrix to have rank2
+ U, S, V = torch.svd(F_mat)
+ rank_mask = torch.tensor([1., 1., 0]).to(F_mat.device)
+
+ F_projected = U @ (torch.diag_embed(S * rank_mask) @ V.transpose(-2, -1))
+ F_est = transform2.transpose(-2, -1) @ (F_projected @ transform1)
+
+ return normalize_transformation(F_est)
+
+
+def compute_correspond_epilines(points: torch.Tensor, F_mat: torch.Tensor) -> torch.Tensor:
+ r"""Computes the corresponding epipolar line for a given set of points.
+
+ Args:
+ points (torch.Tensor): tensor containing the set of points to project in
+ the shape of :math:`(B, N, 2)`.
+ F_mat (torch.Tensor): the fundamental to use for projection the points in
+ the shape of :math:`(B, 3, 3)`.
+
+ Returns:
+ torch.Tensor: a tensor with shape :math:`(B, N, 3)` containing a vector of the epipolar
+ lines corresponding to the points to the other image. Each line is described as
+ :math:`ax + by + c = 0` and encoding the vectors as :math:`(a, b, c)`.
+
+ """
+ assert len(points.shape) == 3 and points.shape[2] == 2, points.shape
+ assert len(F_mat.shape) == 3 and F_mat.shape[-2:] == (3, 3), F_mat.shape
+
+ points_h: torch.Tensor = kornia.convert_points_to_homogeneous(points)
+
+ # project points and retrieve lines components
+ a, b, c = torch.chunk(F_mat @ points_h.permute(0, 2, 1), dim=1, chunks=3)
+
+ # compute normal and compose equation line
+ nu: torch.Tensor = a * a + b * b
+ nu = torch.where(nu > 0., 1. / torch.sqrt(nu), torch.ones_like(nu))
+
+ line = torch.cat([a * nu, b * nu, c * nu], dim=1) # Bx3xN
+ return line.permute(0, 2, 1) # BxNx3
+
+
+def fundamental_from_essential(E_mat: torch.Tensor, K1: torch.Tensor, K2: torch.Tensor) -> torch.Tensor:
+ r"""Get the Fundamental matrix from Essential and camera matrices.
+
+ Uses the method from Hartley/Zisserman 9.6 pag 257 (formula 9.12).
+
+ Args:
+ E_mat (torch.Tensor): The essential matrix with shape of :math:`(*, 3, 3)`.
+ K1 (torch.Tensor): The camera matrix from first camera with shape :math:`(*, 3, 3)`.
+ K2 (torch.Tensor): The camera matrix from second camera with shape :math:`(*, 3, 3)`.
+
+ Returns:
+ torch.Tensor: The fundamental matrix with shape :math:`(*, 3, 3)`.
+
+ """
+ assert len(E_mat.shape) >= 2 and E_mat.shape[-2:] == (3, 3), E_mat.shape
+ assert len(K1.shape) >= 2 and K1.shape[-2:] == (3, 3), K1.shape
+ assert len(K2.shape) >= 2 and K2.shape[-2:] == (3, 3), K2.shape
+ assert len(E_mat.shape[:-2]) == len(K1.shape[:-2]) == len(K2.shape[:-2])
+
+ return K2.inverse().transpose(-2, -1) @ E_mat @ K1.inverse()
+
+
+# adapted from:
+# https://github.com/opencv/opencv_contrib/blob/master/modules/sfm/src/fundamental.cpp#L109
+# https://github.com/openMVG/openMVG/blob/160643be515007580086650f2ae7f1a42d32e9fb/src/openMVG/multiview/projection.cpp#L134
+
+def fundamental_from_projections(P1: torch.Tensor, P2: torch.Tensor) -> torch.Tensor:
+ r"""Get the Fundamental matrix from Projection matrices.
+
+ Args:
+ P1 (torch.Tensor): The projection matrix from first camera with shape :math:`(*, 3, 4)`.
+ P2 (torch.Tensor): The projection matrix from second camera with shape :math:`(*, 3, 4)`.
+
+ Returns:
+ torch.Tensor: The fundamental matrix with shape :math:`(*, 3, 3)`.
+
+ """
+ assert len(P1.shape) >= 2 and P1.shape[-2:] == (3, 4), P1.shape
+ assert len(P2.shape) >= 2 and P2.shape[-2:] == (3, 4), P2.shape
+ assert P1.shape[:-2] == P2.shape[:-2] # this function does not support broadcasting
+
+ def vstack(x, y):
+ return torch.cat([x, y], dim=-2)
+
+ X1 = P1[..., 1:, :]
+ X2 = vstack(P1[..., 2:3, :], P1[..., 0:1, :])
+ X3 = P1[..., :2, :]
+
+ Y1 = P2[..., 1:, :]
+ Y2 = vstack(P2[..., 2:3, :], P2[..., 0:1, :])
+ Y3 = P2[..., :2, :]
+
+ X1Y1, X2Y1, X3Y1 = vstack(X1, Y1), vstack(X2, Y1), vstack(X3, Y1)
+ X1Y2, X2Y2, X3Y2 = vstack(X1, Y2), vstack(X2, Y2), vstack(X3, Y2)
+ X1Y3, X2Y3, X3Y3 = vstack(X1, Y3), vstack(X2, Y3), vstack(X3, Y3)
+
+ F_vec = torch.cat([
+ X1Y1.det(), X2Y1.det(), X3Y1.det(),
+ X1Y2.det(), X2Y2.det(), X3Y2.det(),
+ X1Y3.det(), X2Y3.det(), X3Y3.det(),
+ ], dim=-1)
+
+ return F_vec.view(*P1.shape[:-2], 3, 3)
diff --git a/kornia/geometry/epipolar/metrics.py b/kornia/geometry/epipolar/metrics.py
new file mode 100644
index 000000000..bdcd777be
--- /dev/null
+++ b/kornia/geometry/epipolar/metrics.py
@@ -0,0 +1,120 @@
+"""Module including useful metrics for Structure from Motion."""
+
+import torch
+import kornia
+
+
+def sampson_epipolar_distance(pts1: torch.Tensor,
+ pts2: torch.Tensor,
+ Fm: torch.Tensor,
+ squared: bool = True,
+ eps: float = 1e-8) -> torch.Tensor:
+ r"""Returns Sampson distance for correspondences given the fundamental matrix.
+
+ Args:
+ pts1 (torch.Tensor): correspondences from the left images with shape
+ (B, N, 2 or 3). If they are not homogenuous, converted automatically.
+ pts2 (torch.Tensor): correspondences from the right images with shape
+ (B, N, 2 or 3). If they are not homogenuous, converted automatically.
+ Fm (torch.Tensor): Fundamental matrices with shape :math:`(B, 3, 3)`. Called Fm to
+ avoid ambiguity with torch.nn.functional.
+ squared (bool): if True (default), the squared distance is returned.
+ eps (float): Small constant for safe sqrt. Default 1e-9.
+
+ Returns:
+ torch.Tensor: the computed Sampson distance with shape :math:`(B, N)`.
+
+ """
+ if not isinstance(Fm, torch.Tensor):
+ raise TypeError("Fm type is not a torch.Tensor. Got {}".format(
+ type(Fm)))
+
+ if (len(Fm.shape) != 3) or not Fm.shape[-2:] == (3, 3):
+ raise ValueError(
+ "Fm must be a (*, 3, 3) tensor. Got {}".format(
+ Fm.shape))
+
+ if pts1.size(-1) == 2:
+ pts1 = kornia.convert_points_to_homogeneous(pts1)
+
+ if pts2.size(-1) == 2:
+ pts2 = kornia.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)
+ # 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
+
+ # numerator = (x'^T F x) ** 2
+ numerator: torch.Tensor = (pts2 * line1_in_2).sum(2).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
+ 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:
+ r"""Returns symmetrical epipolar distance for correspondences given the fundamental matrix.
+
+ Args:
+ pts1 (torch.Tensor): correspondences from the left images with shape
+ (B, N, 2 or 3). If they are not homogenuous, converted automatically.
+ pts2 (torch.Tensor): correspondences from the right images with shape
+ (B, N, 2 or 3). If they are not homogenuous, converted automatically.
+ Fm (torch.Tensor): Fundamental matrices with shape :math:`(B, 3, 3)`. Called Fm to
+ avoid ambiguity with torch.nn.functional.
+ squared (bool): if True (default), the squared distance is returned.
+ eps (float): Small constant for safe sqrt. Default 1e-9.
+
+ Returns:
+ torch.Tensor: the computed Symmetrical distance with shape :math:`(B, N)`.
+
+ """
+ if not isinstance(Fm, torch.Tensor):
+ raise TypeError("Fm type is not a torch.Tensor. Got {}".format(
+ type(Fm)))
+
+ if (len(Fm.shape) != 3) or not Fm.shape[-2:] == (3, 3):
+ raise ValueError(
+ "Fm must be a (*, 3, 3) tensor. Got {}".format(
+ Fm.shape))
+
+ if pts1.size(-1) == 2:
+ pts1 = kornia.convert_points_to_homogeneous(pts1)
+
+ if pts2.size(-1) == 2:
+ pts2 = kornia.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)
+
+ # 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
+
+ # numerator = (x'^T F x) ** 2
+ numerator: torch.Tensor = (pts2 * line1_in_2).sum(2).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. / (line1_in_2[..., :2].norm(2, dim=2).pow(2)) +
+ 1. / (line2_in_1[..., :2].norm(2, dim=2).pow(2)))
+ out: torch.Tensor = numerator * denominator_inv
+ if squared:
+ return out
+ return (out + eps).sqrt()
diff --git a/kornia/geometry/epipolar/numeric.py b/kornia/geometry/epipolar/numeric.py
new file mode 100644
index 000000000..1f36f8276
--- /dev/null
+++ b/kornia/geometry/epipolar/numeric.py
@@ -0,0 +1,68 @@
+"""Module containing numerical functionalities for SfM"""
+
+import torch
+
+
+# TODO: this should go to `kornia.geometry.linalg`
+
+def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:
+ r"""Returns the cross_product_matrix symmetric matrix of a vector.
+
+ Args:
+ x (torch.Tensor): The input vector to construct the matrix in the shape :math:`(B, 3)`.
+
+ Returns:
+ torch.Tensor: The constructed cross_product_matrix symmetric matrix with shape :math:`(B, 3, 3)`.
+
+ """
+ assert len(x.shape) == 2 and x.shape[1] == 3, x.shape
+ # get vector compononens
+ x0 = x[..., 0]
+ x1 = x[..., 1]
+ x2 = x[..., 2]
+
+ # construct the matrix, reshape to 3x3 and return
+ zeros = torch.zeros_like(x0)
+ cross_product_matrix_flat = torch.stack([
+ zeros, -x2, x1,
+ x2, zeros, -x0,
+ -x1, x0, zeros], dim=-1)
+ return cross_product_matrix_flat.view(-1, 3, 3)
+
+
+def eye_like(n: int, input: torch.Tensor) -> torch.Tensor:
+ r"""Returns a 2-D tensor with ones on the diagonal and zeros elsewhere with same size as the input.
+
+ Args:
+ n (int): the number of rows :math:`(N)`.
+ input (torch.Tensor): image tensor that will determine the batch size of the output matrix.
+ The expected shape is :math:`(B, *)`.
+
+ Returns:
+ torch.Tensor: The identity matrix with same size as input :math:`(*, N, N)`.
+
+ """
+ assert n > 0, (type(n), n)
+ assert len(input.shape) >= 1, input.shape
+
+ identity = torch.eye(n, device=input.device, dtype=input.dtype)
+ return identity[None].repeat(input.shape[0], 1, 1)
+
+
+def vec_like(n, tensor):
+ r"""Returns a 2-D tensor with a vector containing zeros with same size as the input.
+
+ Args:
+ n (int): the number of rows :math:`(N)`.
+ input (torch.Tensor): image tensor that will determine the batch size of the output matrix.
+ The expected shape is :math:`(B, *)`.
+
+ Returns:
+ torch.Tensor: The vector with same size as input :math:`(*, N, 1)`.
+
+ """
+ assert n > 0, (type(n), n)
+ assert len(tensor.shape) >= 1, tensor.shape
+
+ vec = torch.zeros(n, 1, device=tensor.device, dtype=tensor.dtype)
+ return vec[None].repeat(tensor.shape[0], 1, 1)
diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.py
new file mode 100644
index 000000000..1c2fe051f
--- /dev/null
+++ b/kornia/geometry/epipolar/projection.py
@@ -0,0 +1,167 @@
+"""Module for image projections."""
+from typing import Union
+
+import torch
+
+from kornia.geometry.epipolar import numeric
+
+
+def intrinsics_like(focal: float, input: torch.Tensor) -> torch.Tensor:
+ r"""Returns a 3x3 instrinsics matrix, with same size as the input.
+
+ The center of projection will be based in the input image size.
+
+ Args:
+ focal (float): the focal length for tha camera matrix.
+ input (torch.Tensor): image tensor that will determine the batch size and image height
+ and width. It is assumed to be a tensor in the shape of :math:`(B, C, H, W)`.
+
+ Returns:
+ torch.Tensor: The camera matrix with the shape of :math:`(B, 3, 3)`.
+
+ """
+ assert len(input.shape) == 4, input.shape
+ assert focal > 0, focal
+
+ B, _, H, W = input.shape
+
+ intrinsics = numeric.eye_like(3, input)
+ intrinsics[..., 0, 0] *= focal
+ intrinsics[..., 1, 1] *= focal
+ intrinsics[..., 0, 2] += 1. * W / 2
+ intrinsics[..., 1, 2] += 1. * H / 2
+ return intrinsics
+
+
+def random_intrinsics(low: Union[float, torch.Tensor],
+ high: Union[float, torch.Tensor]) -> torch.Tensor:
+ r"""Generates a random camera matrix based on a given uniform distribution.
+
+ Args:
+ low (Union[float, torch.Tensor]): lower range (inclusive).
+ high (Union[float, torch.Tensor]): upper range (exclusive).
+
+ Returns:
+ torch.Tensor: The random camera matrix with the shape of :math:`(1, 3, 3)`.
+
+ """
+ sampler = torch.distributions.Uniform(low, high)
+ fx, fy, cx, cy = [sampler.sample((1,)) for _ in range(4)]
+ zeros, ones = torch.zeros_like(fx), torch.ones_like(fx)
+ camera_matrix: torch.Tensor = torch.cat([
+ fx, zeros, cx,
+ zeros, fy, cy,
+ zeros, zeros, ones,
+ ])
+ return camera_matrix.view(1, 3, 3)
+
+
+def scale_intrinsics(
+ camera_matrix: torch.Tensor, scale_factor: Union[float, torch.Tensor]) -> torch.Tensor:
+ r"""Scale a camera matrix containing the intrinsics.
+
+ Applies the scaling factor to the focal length and center of projection.
+
+ Args:
+ camera_matrix (torch.Tensor): the camera calibration matrix containing the intrinsic
+ parameters. The expected shape for the tensor is :math:`(B, 3, 3)`.
+ scale_factor (Union[float, torch.Tensor]): the scaling factor to be applied.
+
+ Returns:
+ torch.Tensor: The scaled camera matrix with shame shape as input :math:`(B, 3, 3)`.
+
+ """
+ K_scale = camera_matrix.clone()
+ K_scale[..., 0, 0] *= scale_factor
+ K_scale[..., 1, 1] *= scale_factor
+ K_scale[..., 0, 2] *= scale_factor
+ K_scale[..., 1, 2] *= scale_factor
+ return K_scale
+
+
+def projection_from_KRt(K: torch.Tensor, R: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
+ r"""Get the projection matrix P from K, R and t.
+
+ This function estimate the projection matrix by solving the following equation: :math:`P = K * [R|t]`.
+
+ Args:
+ K (torch.Tensor): the camera matrix with the instrinsics with shape :math:`(B, 3, 3)`.
+ R (torch.Tensor): The rotation matrix with shape :math:`(B, 3, 3)`.
+ t (torch.Tensor): The translation vector with shape :math:`(B, 3, 1)`.
+
+ Returns:
+ torch.Tensor: The projection matrix P with shape :math:`(B, 4, 4)`.
+
+ """
+ assert K.shape[-2:] == (3, 3), K.shape
+ assert R.shape[-2:] == (3, 3), R.shape
+ assert t.shape[-2:] == (3, 1), t.shape
+ assert len(K.shape) == len(R.shape) == len(t.shape)
+
+ Rt: torch.Tensor = torch.cat([R, t], dim=-1) # 3x4
+ Rt_h = torch.nn.functional.pad(Rt, [0, 0, 0, 1], "constant", 0.) # 4x4
+ Rt_h[..., -1, -1] += 1.
+
+ K_h: torch.Tensor = torch.nn.functional.pad(K, [0, 1, 0, 1], "constant", 0.) # 4x4
+ K_h[..., -1, -1] += 1.
+
+ return K @ Rt
+
+
+def depth(R: torch.Tensor, t: torch.Tensor, X: torch.Tensor) -> torch.Tensor:
+ r"""Returns the depth of a point transformed by a rigid transform.
+
+ Args:
+ R (torch.Tensor): The rotation matrix with shape :math:`(*, 3, 3)`.
+ t (torch.Tensor): The translation vector with shape :math:`(*, 3, 1)`.
+ X (torch.Tensor): The 3d points with shape :math:`(*, 3)`.
+
+ Returns:
+ torch.Tensor: The depth value per point with shape :math:`(*, 1)`.
+
+ """
+ X_tmp = R @ X.transpose(-2, -1)
+ X_out = X_tmp[..., 2, :] + t[..., 2, :]
+ return X_out
+
+
+# adapted from:
+# https://github.com/opencv/opencv_contrib/blob/master/modules/sfm/src/fundamental.cpp#L61
+# https://github.com/mapillary/OpenSfM/blob/master/opensfm/multiview.py#L14
+
+
+def _nullspace(A):
+ '''Compute the null space of A.
+ Return the smallest singular value and the corresponding vector.
+ '''
+ u, s, vh = torch.svd(A)
+ return s[..., -1], vh[..., -1]
+
+
+def projections_from_fundamental(F_mat: torch.Tensor) -> torch.Tensor:
+ r"""Get the projection matrices from the Fundamenal Matrix.
+
+ Args:
+ F_mat (torch.Tensor): the fundamenal matrix with the shape :math:`(*, 3, 3)`.
+
+ Returns:
+ torch.Tensor: The projection matrices with shape :math:`(*, 4, 4, 2)`.
+
+ """
+ assert len(F_mat.shape) >= 2, F_mat.shape
+ assert F_mat.shape[-2:] == (3, 3), F_mat.shape
+
+ R1 = numeric.eye_like(3, F_mat) # Bx3x3
+ t1 = numeric.vec_like(3, F_mat) # Bx3
+
+ Ft_mat = F_mat.transpose(-2, -1)
+
+ _, e2 = _nullspace(Ft_mat)
+
+ R2 = numeric.cross_product_matrix(e2) @ F_mat # Bx3x3
+ t2 = e2[..., :, None] # Bx3x1
+
+ P1 = torch.cat([R1, t1], dim=-1) # Bx3x4
+ P2 = torch.cat([R2, t2], dim=-1) # Bx3x4
+
+ return torch.stack([P1, P2], dim=-1)
diff --git a/kornia/geometry/epipolar/scene.py b/kornia/geometry/epipolar/scene.py
new file mode 100644
index 000000000..b0afd4e05
--- /dev/null
+++ b/kornia/geometry/epipolar/scene.py
@@ -0,0 +1,42 @@
+"""Module to generate synthetic 3d scenes."""
+from typing import Dict
+
+import torch
+import kornia
+
+from kornia.geometry import epipolar
+
+
+def generate_scene(num_views: int, num_points: int) -> Dict[str, torch.Tensor]:
+ # Generate the 3d points
+ points3d = torch.rand(1, num_points, 3) # NxMx3
+
+ # Create random camera matrix
+ K = epipolar.random_intrinsics(0., 100.) # 1x3x3
+
+ # Create random rotation per view
+ ang = torch.rand(num_views, 1) * kornia.pi * 2.
+
+ rvec = torch.rand(num_views, 3)
+ rvec = ang * rvec / torch.norm(rvec, dim=1, keepdim=True) # Nx3
+ rot_mat = kornia.angle_axis_to_rotation_matrix(rvec) # Nx3x3
+ # matches with cv2.Rodrigues -> yay !
+
+ # Create random translation per view
+ tx = torch.empty(num_views).uniform_(-0.5, 0.5)
+ ty = torch.empty(num_views).uniform_(-0.5, 0.5)
+ tz = torch.empty(num_views).uniform_(-1.0, 2.0)
+ tvec = torch.stack([tx, ty, tz], dim=1)[..., None]
+
+ # Make sure the shape is in front of the camera
+ points3d_trans = (rot_mat @ points3d.transpose(-2, -1)) + tvec
+ min_dist = torch.min(points3d_trans[:, 2], dim=1)[0]
+ tvec[:, 2, 0] = torch.where(min_dist < 0, tz - min_dist + 1., tz)
+
+ # compute projection matrices
+ P = epipolar.projection_from_KRt(K, rot_mat, tvec)
+
+ # project points3d and backproject to image plane
+ points2d = kornia.transform_points(P, points3d.expand(num_views, -1, -1))
+
+ return dict(K=K, R=rot_mat, t=tvec, P=P, points3d=points3d, points2d=points2d)
diff --git a/kornia/geometry/epipolar/triangulation.py b/kornia/geometry/epipolar/triangulation.py
new file mode 100644
index 000000000..2d8b6b34e
--- /dev/null
+++ b/kornia/geometry/epipolar/triangulation.py
@@ -0,0 +1,56 @@
+"""Module with the functionalites for triangulation."""
+
+import torch
+import kornia
+
+
+# https://github.com/opencv/opencv_contrib/blob/master/modules/sfm/src/triangulation.cpp#L68
+
+def triangulate_points(P1: torch.Tensor, P2: torch.Tensor, points1: torch.Tensor,
+ points2: torch.Tensor) -> torch.Tensor:
+ r"""Reconstructs a bunch of points by triangulation.
+
+ Triangulates the 3d position of 2d correspondences between several images.
+ Reference: Internally it uses DLT method from Hartley/Zisserman 12.2 pag.312
+
+ The input points are assumend to be in homogeneous coordinate system and being inliers
+ correspondences. The method does not perform any robust estimation.
+
+ Args:
+ P1 (torch.Tensor): The projection matrix for the first camera with shape :math:`(*, 3, 4)`.
+ P2 (torch.Tensor): The projection matrix for the second camera with shape :math:`(*, 3, 4)`.
+ points1 (torch.Tensor): The set of points seen from the first camera frame in the camera plane
+ coordinates with shape :math:`(*, N, 2)`.
+ points2 (torch.Tensor): The set of points seen from the second camera frame in the camera plane
+ coordinates with shape :math:`(*, N, 2)`.
+
+ Returns:
+ torch.Tensor: The reconstructed 3d points in the world frame with shape :math:`(*, N, 3)`.
+
+ """
+ assert len(P1.shape) >= 2 and P1.shape[-2:] == (3, 4), P1.shape
+ assert len(P2.shape) >= 2 and P2.shape[-2:] == (3, 4), P2.shape
+ assert len(P1.shape[:-2]) == len(P2.shape[:-2]), (P1.shape, P2.shape)
+ assert len(points1.shape) >= 2 and points1.shape[-1] == 2, points1.shape
+ assert len(points2.shape) >= 2 and points2.shape[-1] == 2, points2.shape
+ assert len(points1.shape[:-2]) == len(points2.shape[:-2]), (points1.shape, points2.shape)
+ assert len(P1.shape[:-2]) == len(points1.shape[:-2]), (P1.shape, points1.shape)
+
+ # allocate and construct the equations matrix with shape (*, 4, 4)
+ points_shape = max(points1.shape, points2.shape) # this allows broadcasting
+ X = torch.zeros(points_shape[:-1] + (4, 4)).type_as(points1)
+
+ for i in range(4):
+ X[..., 0, i] = points1[..., 0] * P1[..., 2:3, i] - P1[..., 0:1, i]
+ X[..., 1, i] = points1[..., 1] * P1[..., 2:3, i] - P1[..., 1:2, i]
+ X[..., 2, i] = points2[..., 0] * P2[..., 2:3, i] - P2[..., 0:1, i]
+ X[..., 3, i] = points2[..., 1] * P2[..., 2:3, i] - P2[..., 1:2, i]
+
+ # 1. Solve the system Ax=0 with smallest eigenvalue
+ # 2. Return homogeneous coordinates
+
+ U, S, V = torch.svd(X)
+
+ points3d_h = V[..., -1]
+ points3d: torch.Tensor = kornia.convert_points_from_homogeneous(points3d_h)
+ return points3d
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index 0f7226882..31b830193 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -52,3 +52,22 @@ def check_is_tensor(obj):
"""
if not isinstance(obj, torch.Tensor):
raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(obj)))
+
+
+def create_rectified_fundamental_matrix(batch_size):
+ """Creates a batch of rectified fundamental matrices of shape Bx3x3
+ """
+ F_rect = torch.tensor([[0., 0., 0.],
+ [0., 0., -1.],
+ [0., 1., 0.]]).view(1, 3, 3)
+ F_repeat = F_rect.repeat(batch_size, 1, 1)
+ return F_repeat
+
+
+def create_random_fundamental_matrix(batch_size, std_val=1e-3):
+ """Creates a batch of random fundamental matrices of shape Bx3x3
+ """
+ F_rect = create_rectified_fundamental_matrix(batch_size)
+ H_left = create_random_homography(batch_size, 3, std_val)
+ H_right = create_random_homography(batch_size, 3, std_val)
+ return H_left.permute(0, 2, 1) @ F_rect @ H_right
diff --git a/test/color/test_luv.py b/test/color/test_luv.py
index bbf467c8c..90658773e 100644
--- a/test/color/test_luv.py
+++ b/test/color/test_luv.py
@@ -74,7 +74,7 @@ class TestRgbToLuv:
rgb = kornia.color.RgbToLuv()
data_out = luv(rgb(data))
- assert_allclose(data_out, data)
+ assert_allclose(data_out, data, rtol=1e-4, atol=1e-4)
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device):
diff --git a/test/geometry/epipolar/test_common.py b/test/geometry/epipolar/test_common.py
new file mode 100644
index 000000000..c8681f75a
--- /dev/null
+++ b/test/geometry/epipolar/test_common.py
@@ -0,0 +1,46 @@
+from typing import Dict
+
+import torch
+import kornia.geometry.epipolar as epi
+
+
+def generate_two_view_random_scene(
+ device: torch.device = torch.device("cpu"),
+ dtype: torch.dtype = torch.float32
+) -> Dict[str, torch.Tensor]:
+
+ num_views: int = 2
+ num_points: int = 30
+
+ scene: Dict[str, torch.Tensor] = epi.generate_scene(num_views, num_points)
+
+ # internal parameters (same K)
+ K1 = scene['K'].to(device, dtype)
+ K2 = K1.clone()
+
+ # rotation
+ R1 = scene['R'][0:1].to(device, dtype)
+ R2 = scene['R'][1:2].to(device, dtype)
+
+ # translation
+ t1 = scene['t'][0:1].to(device, dtype)
+ t2 = scene['t'][1:2].to(device, dtype)
+
+ # projection matrix, P = K(R|t)
+ P1 = scene['P'][0:1].to(device, dtype)
+ P2 = scene['P'][1:2].to(device, dtype)
+
+ # fundamental matrix
+ F_mat = epi.fundamental_from_projections(
+ P1[..., :3, :], P2[..., :3, :])
+
+ F_mat = epi.normalize_transformation(F_mat)
+
+ # points 3d
+ X = scene['points3d'].to(device, dtype)
+
+ # projected points
+ x1 = scene['points2d'][0:1].to(device, dtype)
+ x2 = scene['points2d'][1:2].to(device, dtype)
+
+ return dict(K1=K1, K2=K2, R1=R1, R2=R2, t1=t1, t2=t2, P1=P1, P2=P2, F=F_mat, X=X, x1=x1, x2=x2)
diff --git a/test/geometry/epipolar/test_epipolar_metrics.py b/test/geometry/epipolar/test_epipolar_metrics.py
new file mode 100644
index 000000000..1c04fb200
--- /dev/null
+++ b/test/geometry/epipolar/test_epipolar_metrics.py
@@ -0,0 +1,58 @@
+import pytest
+
+import torch
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+import kornia.geometry.epipolar as epi
+import kornia.testing as utils
+
+
+class TestSymmetricalEpipolarDistance:
+
+ 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.symmetrical_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.symmetrical_epipolar_distance(pts1, pts2, Fm).shape == (5, 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.symmetrical_epipolar_distance, (points1, points2, Fm),
+ raise_exception=True)
+
+
+class TestSampsonEpipolarDistance:
+
+ 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.sampson_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.sampson_epipolar_distance(pts1, pts2, Fm).shape == (5, 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.sampson_epipolar_distance, (points1, points2, Fm),
+ raise_exception=True)
diff --git a/test/geometry/epipolar/test_essential.py b/test/geometry/epipolar/test_essential.py
new file mode 100644
index 000000000..6703916d7
--- /dev/null
+++ b/test/geometry/epipolar/test_essential.py
@@ -0,0 +1,317 @@
+import pytest
+
+import torch
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+import kornia.geometry.epipolar as epi
+
+import test_common as utils
+
+
+class TestEssentialFromFundamental:
+ def test_smoke(self, device, dtype):
+ F_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ K1 = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ K2 = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ E_mat = epi.essential_from_fundamental(F_mat, K1, K2)
+ assert E_mat.shape == (1, 3, 3)
+
+ @pytest.mark.parametrize("batch_size", [1, 2, 4, 7])
+ def test_shape(self, batch_size, device, dtype):
+ B: int = batch_size
+ F_mat = torch.rand(B, 3, 3, device=device, dtype=dtype)
+ K1 = torch.rand(B, 3, 3, device=device, dtype=dtype)
+ K2 = torch.rand(1, 3, 3, device=device, dtype=dtype) # check broadcasting
+ E_mat = epi.essential_from_fundamental(F_mat, K1, K2)
+ assert E_mat.shape == (B, 3, 3)
+
+ def test_from_to_fundamental(self, device, dtype):
+ F_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ K1 = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ K2 = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ E_mat = epi.essential_from_fundamental(F_mat, K1, K2)
+ F_hat = epi.fundamental_from_essential(E_mat, K1, K2)
+ assert_allclose(F_mat, F_hat, atol=1e-4, rtol=1e-4)
+
+ def test_shape_large(self, device, dtype):
+ F_mat = torch.rand(1, 2, 3, 3, device=device, dtype=dtype)
+ K1 = torch.rand(1, 2, 3, 3, device=device, dtype=dtype)
+ K2 = torch.rand(1, 1, 3, 3, device=device, dtype=dtype) # check broadcasting
+ E_mat = epi.essential_from_fundamental(F_mat, K1, K2)
+ assert E_mat.shape == (1, 2, 3, 3)
+
+ def test_from_fundamental(self, device, dtype):
+
+ scene = utils.generate_two_view_random_scene(device, dtype)
+
+ F_mat = scene['F']
+
+ K1 = scene['K1']
+ K2 = scene['K2']
+
+ E_mat = epi.essential_from_fundamental(F_mat, K1, K2)
+ F_hat = epi.fundamental_from_essential(E_mat, K1, K2)
+
+ F_mat_norm = epi.normalize_transformation(F_mat)
+ F_hat_norm = epi.normalize_transformation(F_hat)
+ assert_allclose(F_mat_norm, F_hat_norm)
+
+ def test_gradcheck(self, device):
+ F_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
+ K1 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
+ K2 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
+ assert gradcheck(epi.essential_from_fundamental,
+ (F_mat, K1, K2,), raise_exception=True)
+
+
+class TestRelativeCameraMotion:
+ def test_smoke(self, device, dtype):
+ R1 = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ t1 = torch.rand(1, 3, 1, device=device, dtype=dtype)
+ R2 = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ t2 = torch.rand(1, 3, 1, device=device, dtype=dtype)
+ R, t = epi.relative_camera_motion(R1, t1, R2, t2)
+ assert R.shape == (1, 3, 3)
+ assert t.shape == (1, 3, 1)
+
+ @pytest.mark.parametrize("batch_size", [1, 3, 5, 8, ])
+ def test_shape(self, batch_size, device, dtype):
+ B: int = batch_size
+ R1 = torch.rand(B, 3, 3, device=device, dtype=dtype)
+ t1 = torch.rand(B, 3, 1, device=device, dtype=dtype)
+ R2 = torch.rand(1, 3, 3, device=device, dtype=dtype) # check broadcasting
+ t2 = torch.rand(B, 3, 1, device=device, dtype=dtype)
+ R, t = epi.relative_camera_motion(R1, t1, R2, t2)
+ assert R.shape == (B, 3, 3)
+ assert t.shape == (B, 3, 1)
+
+ def test_translation(self, device, dtype):
+ R1 = torch.tensor([[
+ [1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.],
+ ]], device=device, dtype=dtype)
+
+ t1 = torch.tensor([[[10.], [0.], [0.]]]).type_as(R1)
+
+ R2 = epi.eye_like(3, R1)
+ t2 = epi.vec_like(3, t1)
+
+ R_expected = R1.clone()
+ t_expected = -t1
+
+ R, t = epi.relative_camera_motion(R1, t1, R2, t2)
+ assert_allclose(R_expected, R)
+ assert_allclose(t_expected, t)
+
+ def test_rotate_z(self, device, dtype):
+ R1 = torch.tensor([[
+ [1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.],
+ ]], device=device, dtype=dtype)
+
+ R2 = torch.tensor([[
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 1.],
+ ]], device=device, dtype=dtype)
+
+ t1 = epi.vec_like(3, R1)
+ t2 = epi.vec_like(3, R2)
+
+ R_expected = R2.clone()
+ t_expected = t1
+
+ R, t = epi.relative_camera_motion(R1, t1, R2, t2)
+ assert_allclose(R_expected, R)
+ assert_allclose(t_expected, t)
+
+ def test_gradcheck(self, device):
+ R1 = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
+ R2 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
+ t1 = torch.rand(1, 3, 1, device=device, dtype=torch.float64)
+ t2 = torch.rand(1, 3, 1, device=device, dtype=torch.float64)
+ assert gradcheck(epi.relative_camera_motion,
+ (R1, t1, R2, t2,), raise_exception=True)
+
+
+class TestEssentalFromRt:
+ def test_smoke(self, device, dtype):
+ R1 = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ t1 = torch.rand(1, 3, 1, device=device, dtype=dtype)
+ R2 = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ t2 = torch.rand(1, 3, 1, device=device, dtype=dtype)
+ E_mat = epi.essential_from_Rt(R1, t1, R2, t2)
+ assert E_mat.shape == (1, 3, 3)
+
+ @pytest.mark.parametrize("batch_size", [1, 3, 5, 8, ])
+ def test_shape(self, batch_size, device, dtype):
+ B: int = batch_size
+ R1 = torch.rand(B, 3, 3, device=device, dtype=dtype)
+ t1 = torch.rand(B, 3, 1, device=device, dtype=dtype)
+ R2 = torch.rand(1, 3, 3, device=device, dtype=dtype) # check broadcasting
+ t2 = torch.rand(B, 3, 1, device=device, dtype=dtype)
+ E_mat = epi.essential_from_Rt(R1, t1, R2, t2)
+ assert E_mat.shape == (B, 3, 3)
+
+ def test_from_fundamental_Rt(self, device, dtype):
+
+ scene = utils.generate_two_view_random_scene(device, dtype)
+
+ E_from_Rt = epi.essential_from_Rt(
+ scene['R1'], scene['t1'], scene['R2'], scene['t2'])
+
+ E_from_F = epi.essential_from_fundamental(
+ scene['F'], scene['K1'], scene['K2'])
+
+ E_from_Rt_norm = epi.normalize_transformation(E_from_Rt)
+ E_from_F_norm = epi.normalize_transformation(E_from_F)
+ assert_allclose(E_from_Rt_norm, E_from_F_norm, rtol=1e-3, atol=1e-3)
+
+ def test_gradcheck(self, device):
+ R1 = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
+ R2 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
+ t1 = torch.rand(1, 3, 1, device=device, dtype=torch.float64)
+ t2 = torch.rand(1, 3, 1, device=device, dtype=torch.float64)
+ assert gradcheck(epi.essential_from_Rt,
+ (R1, t1, R2, t2,), raise_exception=True)
+
+
+class TestDecomposeEssentialMatrix:
+ def test_smoke(self, device, dtype):
+ E_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ R1, R2, t = epi.decompose_essential_matrix(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", [
+ (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(E_mat)
+ 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(input)[0]
+
+ def eval_rot2(input):
+ return epi.decompose_essential_matrix(input)[1]
+
+ def eval_vec(input):
+ return epi.decompose_essential_matrix(input)[2]
+
+ assert gradcheck(eval_rot1, (E_mat,), raise_exception=True)
+ assert gradcheck(eval_rot2, (E_mat,), raise_exception=True)
+ assert gradcheck(eval_vec, (E_mat,), raise_exception=True)
+
+
+class TestMotionFromEssential:
+ def test_smoke(self, device, dtype):
+ E_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ Rs, Ts = epi.motion_from_essential(E_mat)
+ assert Rs.shape == (1, 4, 3, 3)
+ assert Ts.shape == (1, 4, 3, 1)
+
+ @pytest.mark.parametrize("batch_shape", [
+ (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)
+ Rs, Ts = epi.motion_from_essential(E_mat)
+ assert Rs.shape == batch_shape[:-2] + (4, 3, 3)
+ assert Ts.shape == batch_shape[:-2] + (4, 3, 1)
+
+ def test_two_view(self, device, dtype):
+ scene = utils.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)
+
+ R, t = epi.relative_camera_motion(R1, t1, R2, t2)
+ t = torch.nn.functional.normalize(t, dim=1)
+
+ Rs, ts = epi.motion_from_essential(E_mat)
+
+ rot_error = (Rs - R).abs().sum((-2, -1))
+ vec_error = (ts - t).abs().sum((-1))
+
+ rtol: float = 1e-4
+ assert (rot_error < rtol).any() & (vec_error < rtol).any()
+
+ def test_gradcheck(self, device):
+ E_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
+
+ def eval_rot(input):
+ return epi.motion_from_essential(input)[0]
+
+ def eval_vec(input):
+ return epi.motion_from_essential(input)[1]
+
+ assert gradcheck(eval_rot, (E_mat,), raise_exception=True)
+ assert gradcheck(eval_vec, (E_mat,), raise_exception=True)
+
+
+class TestMotionFromEssentialChooseSolution:
+ def test_smoke(self, device, dtype):
+ E_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ K1 = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ K2 = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ x1 = torch.rand(1, 1, 2, device=device, dtype=dtype)
+ x2 = torch.rand(1, 1, 2, device=device, dtype=dtype)
+ R, t, X = epi.motion_from_essential_choose_solution(E_mat, K1, K2, x1, x2)
+ assert R.shape == (1, 3, 3)
+ assert t.shape == (1, 3, 1)
+ assert X.shape == (1, 1, 3)
+
+ @pytest.mark.parametrize("batch_size, num_points", [
+ (1, 3), (2, 3), (2, 8), (3, 2),
+ ])
+ def test_shape(self, batch_size, num_points, device, dtype):
+ B, N = batch_size, num_points
+ E_mat = torch.rand(B, 3, 3, device=device, dtype=dtype)
+ K1 = torch.rand(B, 3, 3, device=device, dtype=dtype)
+ K2 = torch.rand(1, 3, 3, device=device, dtype=dtype) # check for broadcasting
+ x1 = torch.rand(B, N, 2, device=device, dtype=dtype)
+ x2 = torch.rand(B, 1, 2, device=device, dtype=dtype) # check for broadcasting
+ R, t, X = epi.motion_from_essential_choose_solution(E_mat, K1, K2, x1, x2)
+ assert R.shape == (B, 3, 3)
+ assert t.shape == (B, 3, 1)
+ assert X.shape == (B, N, 3)
+
+ def test_two_view(self, device, dtype):
+
+ scene = utils.generate_two_view_random_scene(device, dtype)
+
+ E_mat = epi.essential_from_Rt(
+ scene['R1'], scene['t1'], scene['R2'], scene['t2'])
+
+ R, t = epi.relative_camera_motion(
+ scene['R1'], scene['t1'], scene['R2'], scene['t2'])
+ t = torch.nn.functional.normalize(t, dim=1)
+
+ R_hat, t_hat, X_hat = epi.motion_from_essential_choose_solution(
+ E_mat, scene['K1'], scene['K2'], scene['x1'], scene['x2'])
+
+ assert_allclose(t, t_hat)
+ assert_allclose(R, R_hat, rtol=1e-4, atol=1e-4)
+
+ def test_gradcheck(self, device):
+ E_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
+ K1 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
+ K2 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
+ x1 = torch.rand(1, 2, 2, device=device, dtype=torch.float64)
+ x2 = torch.rand(1, 2, 2, device=device, dtype=torch.float64)
+
+ assert gradcheck(epi.motion_from_essential_choose_solution,
+ (E_mat, K1, K2, x1, x2,), raise_exception=True)
diff --git a/test/geometry/epipolar/test_fundamental.py b/test/geometry/epipolar/test_fundamental.py
new file mode 100644
index 000000000..9311f9866
--- /dev/null
+++ b/test/geometry/epipolar/test_fundamental.py
@@ -0,0 +1,319 @@
+import pytest
+
+import torch
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+import kornia.geometry.epipolar as epi
+
+import test_common as utils
+
+
+class TestNormalizePoints:
+ def test_smoke(self, device, dtype):
+ points = torch.rand(1, 1, 2, device=device, dtype=dtype)
+ output = epi.normalize_points(points)
+ assert len(output) == 2
+ assert output[0].shape == (1, 1, 2)
+ assert output[1].shape == (1, 3, 3)
+
+ @pytest.mark.parametrize(
+ "batch_size, num_points", [(1, 2), (2, 3), (3, 2)],
+ )
+ def test_shape(self, batch_size, num_points, device, dtype):
+ B, N = batch_size, num_points
+ points = torch.rand(B, N, 2, device=device, dtype=dtype)
+ output = epi.normalize_points(points)
+ assert output[0].shape == (B, N, 2)
+ assert output[1].shape == (B, 3, 3)
+
+ def test_mean_std(self, device, dtype):
+ points = torch.tensor([[
+ [0., 0.], [0., 2.], [1., 1.], [1., 3.]
+ ]], device=device, dtype=dtype)
+
+ points_norm, trans = epi.normalize_points(points)
+ points_std, points_mean = torch.std_mean(points_norm, dim=1)
+
+ assert_allclose(points_mean, torch.zeros_like(points_mean))
+ assert (points_std < 2.).all()
+
+ def test_gradcheck(self, device):
+ points = torch.rand(2, 3, 2,
+ device=device, requires_grad=True, dtype=torch.float64)
+ assert gradcheck(epi.normalize_points, (points,), raise_exception=True)
+
+
+class TestNormalizeTransformation:
+ def test_smoke(self, device, dtype):
+ trans = torch.rand(2, 2, device=device, dtype=dtype)
+ trans_norm = epi.normalize_transformation(trans)
+ assert trans_norm.shape == (2, 2)
+
+ @pytest.mark.parametrize(
+ "batch_size, rows, cols", [(1, 2, 2), (2, 3, 3), (3, 4, 4), (2, 1, 2)],
+ )
+ def test_shape(self, batch_size, rows, cols, device, dtype):
+ B, N, M = batch_size, rows, cols
+ trans = torch.rand(B, N, M, device=device, dtype=dtype)
+ trans_norm = epi.normalize_transformation(trans)
+ assert trans_norm.shape == (B, N, M)
+
+ def test_check_last_val(self, device, dtype):
+ trans = torch.tensor([[
+ [0.0, 0.0, 1.0],
+ [0.0, 2.0, 0.0],
+ [0.5, 0.0, 0.5]
+ ]], device=device, dtype=dtype)
+
+ trans_expected = torch.tensor([[
+ [0.0, 0.0, 2.0],
+ [0.0, 4.0, 0.0],
+ [1.0, 0.0, 1.0]
+ ]], device=device, dtype=dtype)
+
+ trans_norm = epi.normalize_transformation(trans)
+ assert_allclose(trans_norm, trans_expected)
+
+ def test_check_corner_case(self, device, dtype):
+ trans = torch.tensor([[
+ [0.0, 0.0, 1.0],
+ [0.0, 2.0, 0.0],
+ [0.5, 0.0, 0.0]
+ ]], device=device, dtype=dtype)
+
+ trans_expected = trans.clone()
+
+ trans_norm = epi.normalize_transformation(trans)
+ assert_allclose(trans_norm, trans_expected)
+
+ def test_gradcheck(self, device):
+ trans = torch.rand(2, 3, 3,
+ device=device, requires_grad=True, dtype=torch.float64)
+ assert gradcheck(epi.normalize_transformation, (trans,), raise_exception=True)
+
+
+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)
+ 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)],
+ )
+ def test_shape(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 = torch.ones(B, N, device=device, dtype=dtype)
+ F_mat = epi.find_fundamental(points1, points2, weights)
+ assert F_mat.shape == (B, 3, 3)
+
+ def test_opencv(self, device, dtype):
+ points1 = torch.tensor([[
+ [0.8569, 0.5982],
+ [0.0059, 0.9649],
+ [0.1968, 0.8846],
+ [0.6084, 0.3467],
+ [0.9633, 0.5274],
+ [0.8941, 0.8939],
+ [0.0863, 0.5133],
+ [0.2645, 0.8882],
+ [0.2411, 0.3045],
+ [0.8199, 0.4107]]], device=device, dtype=dtype)
+
+ points2 = torch.tensor([[
+ [0.0928, 0.3013],
+ [0.0989, 0.9649],
+ [0.0341, 0.4827],
+ [0.8294, 0.4469],
+ [0.2230, 0.2998],
+ [0.1722, 0.8182],
+ [0.5264, 0.8869],
+ [0.8908, 0.1233],
+ [0.2338, 0.7663],
+ [0.4466, 0.5696]]], device=device, dtype=dtype)
+
+ weights = torch.ones(1, 10, device=device, dtype=dtype)
+
+ # generated with OpenCV using above points
+ # import cv2
+ # Fm_expected, _ = cv2.findFundamentalMat(
+ # points1.detach().numpy().reshape(-1, 1, 2),
+ # points2.detach().numpy().reshape(-1, 1, 2), cv2.FM_8POINT)
+
+ Fm_expected = torch.tensor([[
+ [-0.47408533, 0.22033807, -0.00346677],
+ [0.54935973, 1.31080955, -1.25028275],
+ [-0.36690215, -1.08143769, 1.]]], device=device, dtype=dtype)
+
+ F_mat = epi.find_fundamental(points1, points2, weights)
+ assert_allclose(F_mat, Fm_expected, rtol=1e-4, atol=1e-4)
+
+ def test_synthetic_sampson(self, device, dtype):
+
+ scene: Dict[str, torch.Tensor] = utils.generate_two_view_random_scene(device, dtype)
+
+ x1 = scene['x1']
+ x2 = scene['x2']
+
+ weights = torch.ones_like(x1)[..., 0]
+ F_est = epi.find_fundamental(x1, x2, weights)
+
+ error = epi.sampson_epipolar_distance(x1, x2, F_est)
+ assert_allclose(error, torch.tensor(0., device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
+
+ def test_gradcheck(self, device):
+ points1 = torch.rand(1, 10, 2, device=device, dtype=torch.float64, requires_grad=True)
+ points2 = torch.rand(1, 10, 2, device=device, dtype=torch.float64)
+ weights = torch.ones(1, 10, device=device, dtype=torch.float64)
+ assert gradcheck(epi.find_fundamental,
+ (points1, points2, weights,), raise_exception=True)
+
+
+class TestComputeCorrespondEpilimes:
+ def test_smoke(self, device, dtype):
+ point = torch.rand(1, 1, 2, device=device, dtype=dtype)
+ F_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ lines = epi.compute_correspond_epilines(point, F_mat)
+ assert lines.shape == (1, 1, 3)
+
+ @pytest.mark.parametrize(
+ "batch_size, num_points", [(1, 2), (2, 3), (3, 2)],
+ )
+ def test_shape(self, batch_size, num_points, device, dtype):
+ B, N = batch_size, num_points
+ point = torch.rand(B, N, 2, device=device, dtype=dtype)
+ F_mat = torch.rand(B, 3, 3, device=device, dtype=dtype)
+ lines = epi.compute_correspond_epilines(point, F_mat)
+ assert lines.shape == (B, N, 3)
+
+ def test_opencv(self, device, dtype):
+ point = torch.rand(1, 2, 2, device=device, dtype=dtype)
+ F_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
+
+ point = torch.tensor([[
+ [0.9794, 0.7994],
+ [0.8163, 0.8500],
+ ]], device=device, dtype=dtype)
+
+ F_mat = torch.tensor([[
+ [0.1185, 0.4438, 0.9869],
+ [0.5670, 0.9447, 0.4100],
+ [0.1546, 0.2554, 0.4485],
+ ]], device=device, dtype=dtype)
+
+ # generated with OpenCV using above points
+ # import cv2
+ # lines_expected = cv2.computeCorrespondEpilines(
+ # point.detach().numpy().reshape(-1, 1, 2), 0,
+ # F_mat.detach().numpy()[0]).transpose(1, 0, 2)
+
+ lines_expected = torch.tensor([[
+ [0.64643687, 0.7629675, 0.35658622],
+ [0.65710586, 0.7537983, 0.35616538],
+ ]], device=device, dtype=dtype)
+
+ lines_est = epi.compute_correspond_epilines(point, F_mat)
+ assert_allclose(lines_est, lines_expected, rtol=1e-4, atol=1e-4)
+
+ def test_gradcheck(self, device):
+ point = torch.rand(1, 4, 2, device=device, dtype=torch.float64, requires_grad=True)
+ F_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
+ assert gradcheck(epi.compute_correspond_epilines,
+ (point, F_mat,), raise_exception=True)
+
+
+class TestFundamentlFromEssential:
+ def test_smoke(self, device, dtype):
+ E_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ K1 = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ K2 = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ F_mat = epi.fundamental_from_essential(E_mat, K1, K2)
+ assert F_mat.shape == (1, 3, 3)
+
+ @pytest.mark.parametrize("batch_size", [1, 2, 4, 7])
+ def test_shape(self, batch_size, device, dtype):
+ B: int = batch_size
+ E_mat = torch.rand(B, 3, 3, device=device, dtype=dtype)
+ K1 = torch.rand(B, 3, 3, device=device, dtype=dtype)
+ K2 = torch.rand(1, 3, 3, device=device, dtype=dtype) # check broadcasting
+ F_mat = epi.fundamental_from_essential(E_mat, K1, K2)
+ assert F_mat.shape == (B, 3, 3)
+
+ def test_shape_large(self, device, dtype):
+ E_mat = torch.rand(1, 2, 3, 3, device=device, dtype=dtype)
+ K1 = torch.rand(1, 2, 3, 3, device=device, dtype=dtype)
+ K2 = torch.rand(1, 1, 3, 3, device=device, dtype=dtype) # check broadcasting
+ F_mat = epi.fundamental_from_essential(E_mat, K1, K2)
+ assert F_mat.shape == (1, 2, 3, 3)
+
+ def test_from_to_essential(self, device, dtype):
+ scene = utils.generate_two_view_random_scene(device, dtype)
+
+ F_mat = scene['F']
+ E_mat = epi.essential_from_fundamental(F_mat, scene['K1'], scene['K2'])
+ F_hat = epi.fundamental_from_essential(E_mat, scene['K1'], scene['K2'])
+
+ F_mat_norm = epi.normalize_transformation(F_mat)
+ F_hat_norm = epi.normalize_transformation(F_hat)
+ assert_allclose(F_mat_norm, F_hat_norm)
+
+ def test_gradcheck(self, device):
+ E_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
+ K1 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
+ K2 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
+ assert gradcheck(epi.fundamental_from_essential,
+ (E_mat, K1, K2,), raise_exception=True)
+
+
+class TestFundamentalFromProjections:
+ def test_smoke(self, device, dtype):
+ P1 = torch.rand(1, 3, 4, device=device, dtype=dtype)
+ P2 = torch.rand(1, 3, 4, device=device, dtype=dtype)
+ F_mat = epi.fundamental_from_projections(P1, P2)
+ assert F_mat.shape == (1, 3, 3)
+
+ @pytest.mark.parametrize("batch_size", [1, 2, 4, 7])
+ def test_shape(self, batch_size, device, dtype):
+ B: int = batch_size
+ P1 = torch.rand(B, 3, 4, device=device, dtype=dtype)
+ P2 = torch.rand(B, 3, 4, device=device, dtype=dtype)
+ F_mat = epi.fundamental_from_projections(P1, P2)
+ assert F_mat.shape == (B, 3, 3)
+
+ def test_shape_large(self, device, dtype):
+ P1 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
+ P2 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
+ F_mat = epi.fundamental_from_projections(P1, P2)
+ assert F_mat.shape == (1, 2, 3, 3)
+
+ def test_from_to_projections(self, device, dtype):
+ P1 = torch.tensor([[
+ [1., 0., 0., 0.],
+ [0., 1., 0., 0.],
+ [1., 0., 1., 0.],
+ ]], device=device, dtype=dtype)
+
+ P2 = torch.tensor([[
+ [1., 1., 1., 3.],
+ [0., 2., 0., 3.],
+ [0., 1., 1., 0.],
+ ]], device=device, dtype=dtype)
+
+ F_mat = epi.fundamental_from_projections(P1, P2)
+ P_mat = epi.projections_from_fundamental(F_mat)
+ F_hat = epi.fundamental_from_projections(P_mat[..., 0], P_mat[..., 1])
+
+ F_mat_norm = epi.normalize_transformation(F_mat)
+ F_hat_norm = epi.normalize_transformation(F_hat)
+ assert_allclose(F_mat_norm, F_hat_norm)
+
+ def test_gradcheck(self, device):
+ P1 = torch.rand(1, 3, 4, device=device, dtype=torch.float64, requires_grad=True)
+ P2 = torch.rand(1, 3, 4, device=device, dtype=torch.float64)
+ assert gradcheck(epi.fundamental_from_projections,
+ (P1, P2,), raise_exception=True)
diff --git a/test/geometry/epipolar/test_numeric.py b/test/geometry/epipolar/test_numeric.py
new file mode 100644
index 000000000..0ccf4084d
--- /dev/null
+++ b/test/geometry/epipolar/test_numeric.py
@@ -0,0 +1,72 @@
+import pytest
+
+import torch
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+import kornia.geometry.epipolar as epi
+
+
+class TestSkewSymmetric:
+ def test_smoke(self, device, dtype):
+ vec = torch.rand(1, 3, device=device, dtype=dtype)
+ cross_product_matrix = epi.cross_product_matrix(vec)
+ assert cross_product_matrix.shape == (1, 3, 3)
+
+ @pytest.mark.parametrize("batch_size", [1, 2, 4, 7])
+ def test_shape(self, batch_size, device, dtype):
+ B = batch_size
+ vec = torch.rand(B, 3, device=device, dtype=dtype)
+ cross_product_matrix = epi.cross_product_matrix(vec)
+ assert cross_product_matrix.shape == (B, 3, 3)
+
+ def test_mean_std(self, device, dtype):
+ vec = torch.tensor([[1., 2., 3.]], device=device, dtype=dtype)
+ cross_product_matrix = epi.cross_product_matrix(vec)
+ assert_allclose(cross_product_matrix[..., 0, 1], -cross_product_matrix[..., 1, 0])
+ assert_allclose(cross_product_matrix[..., 0, 2], -cross_product_matrix[..., 2, 0])
+ assert_allclose(cross_product_matrix[..., 1, 2], -cross_product_matrix[..., 2, 1])
+
+ def test_gradcheck(self, device):
+ vec = torch.ones(2, 3, device=device, requires_grad=True, dtype=torch.float64)
+ assert gradcheck(epi.cross_product_matrix, (vec,), raise_exception=True)
+
+
+class TestEyeLike:
+ def test_smoke(self, device, dtype):
+ image = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
+ identity = epi.eye_like(3, image)
+ assert identity.shape == (1, 3, 3)
+ assert identity.device == image.device
+ assert identity.dtype == image.dtype
+
+ @pytest.mark.parametrize(
+ "batch_size, eye_size", [(1, 2), (2, 3), (3, 3), (2, 4)],
+ )
+ def test_shape(self, batch_size, eye_size, device, dtype):
+ B, N = batch_size, eye_size
+ image = torch.rand(B, 3, 4, 4, device=device, dtype=dtype)
+ identity = epi.eye_like(N, image)
+ assert identity.shape == (B, N, N)
+ assert identity.device == image.device
+ assert identity.dtype == image.dtype
+
+
+class TestVecLike:
+ def test_smoke(self, device, dtype):
+ image = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
+ vec = epi.vec_like(3, image)
+ assert vec.shape == (1, 3, 1)
+ assert vec.device == image.device
+ assert vec.dtype == image.dtype
+
+ @pytest.mark.parametrize(
+ "batch_size, eye_size", [(1, 2), (2, 3), (3, 3), (2, 4)],
+ )
+ def test_shape(self, batch_size, eye_size, device, dtype):
+ B, N = batch_size, eye_size
+ image = torch.rand(B, 3, 4, 4, device=device, dtype=dtype)
+ vec = epi.vec_like(N, image)
+ assert vec.shape == (B, N, 1)
+ assert vec.device == image.device
+ assert vec.dtype == image.dtype
diff --git a/test/geometry/epipolar/test_projection.py b/test/geometry/epipolar/test_projection.py
new file mode 100644
index 000000000..bdb74eead
--- /dev/null
+++ b/test/geometry/epipolar/test_projection.py
@@ -0,0 +1,140 @@
+import pytest
+
+import torch
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+import kornia.geometry.epipolar as epi
+
+
+class TestIntrinsicsLike:
+ def test_smoke(self, device, dtype):
+ image = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
+ focal = torch.rand(1, device=device, dtype=dtype)
+ camera_matrix = epi.intrinsics_like(focal, image)
+ assert camera_matrix.shape == (1, 3, 3)
+
+ @pytest.mark.parametrize("batch_size", [1, 2, 4, 9])
+ def test_shape(self, batch_size, device, dtype):
+ B: int = batch_size
+ focal: float = 100.0
+ image = torch.rand(B, 3, 4, 4, device=device, dtype=dtype)
+ camera_matrix = epi.intrinsics_like(focal, image)
+ assert camera_matrix.shape == (B, 3, 3)
+ assert camera_matrix.device == image.device
+ assert camera_matrix.dtype == image.dtype
+
+
+class TestScaleIntrinsics:
+ def test_smoke_float(self, device, dtype):
+ scale_factor: float = 1.0
+ camera_matrix = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ camera_matrix_scale = epi.scale_intrinsics(camera_matrix, scale_factor)
+ assert camera_matrix_scale.shape == (1, 3, 3)
+
+ def test_smoke_tensor(self, device, dtype):
+ scale_factor = torch.tensor(1.0)
+ camera_matrix = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ camera_matrix_scale = epi.scale_intrinsics(camera_matrix, scale_factor)
+ assert camera_matrix_scale.shape == (1, 3, 3)
+
+ @pytest.mark.parametrize("batch_size", [1, 2, 4, 9])
+ def test_shape(self, batch_size, device, dtype):
+ B: int = batch_size
+ scale_factor = torch.rand(B, device=device, dtype=dtype)
+ camera_matrix = torch.rand(B, 3, 3, device=device, dtype=dtype)
+ camera_matrix_scale = epi.scale_intrinsics(camera_matrix, scale_factor)
+ assert camera_matrix_scale.shape == (B, 3, 3)
+
+ def test_scale_double(self, device, dtype):
+ scale_factor = torch.tensor(0.5)
+ camera_matrix = torch.tensor([[
+ [100., 0., 50.],
+ [0., 100., 50.],
+ [0., 0., 1.],
+ ]], device=device, dtype=dtype)
+
+ camera_matrix_expected = torch.tensor([[
+ [50., 0., 25.],
+ [0., 50., 25.],
+ [0., 0., 1.],
+ ]], device=device, dtype=dtype)
+
+ camera_matrix_scale = epi.scale_intrinsics(camera_matrix, scale_factor)
+ assert_allclose(camera_matrix_scale, camera_matrix_expected)
+
+ def test_gradcheck(self, device):
+ scale_factor = torch.ones(1, device=device, dtype=torch.float64, requires_grad=True)
+ camera_matrix = torch.ones(1, 3, 3, device=device, dtype=torch.float64)
+ assert gradcheck(epi.scale_intrinsics,
+ (camera_matrix, scale_factor,), raise_exception=True)
+
+
+class TestProjectionFromKRt:
+ def test_smoke(self, device, dtype):
+ K = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ R = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ t = torch.rand(1, 3, 1, device=device, dtype=dtype)
+ P = epi.projection_from_KRt(K, R, t)
+ assert P.shape == (1, 3, 4)
+
+ @pytest.mark.parametrize("batch_size", [1, 2, 4])
+ def test_shape(self, batch_size, device, dtype):
+ B: int = batch_size
+ K = torch.rand(B, 3, 3, device=device, dtype=dtype)
+ R = torch.rand(B, 3, 3, device=device, dtype=dtype)
+ t = torch.rand(B, 3, 1, device=device, dtype=dtype)
+ P = epi.projection_from_KRt(K, R, t)
+ assert P.shape == (B, 3, 4)
+
+ def test_simple(self, device, dtype):
+ K = torch.tensor([[
+ [10., 0., 30.],
+ [0., 20., 40.],
+ [0., 0., 1.],
+ ]], device=device, dtype=dtype)
+
+ R = torch.tensor([[
+ [1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.],
+ ]], device=device, dtype=dtype)
+
+ t = torch.tensor([
+ [[1.], [2.], [3.]],
+ ], device=device, dtype=dtype)
+
+ P_expected = torch.tensor([[
+ [10., 0., 30., 100.],
+ [0., 20., 40., 160.],
+ [0., 0., 1., 3.],
+ ]], device=device, dtype=dtype)
+
+ P_estimated = epi.projection_from_KRt(K, R, t)
+ assert_allclose(P_estimated, P_expected)
+
+ def test_gradcheck(self, device):
+ K = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
+ R = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
+ t = torch.rand(1, 3, 1, device=device, dtype=torch.float64)
+ assert gradcheck(epi.projection_from_KRt,
+ (K, R, t,), raise_exception=True)
+
+
+class TestProjectionsFromFundamental:
+ def test_smoke(self, device, dtype):
+ F_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ P = epi.projections_from_fundamental(F_mat)
+ assert P.shape == (1, 3, 4, 2)
+
+ @pytest.mark.parametrize("batch_size", [1, 2, 4])
+ def test_shape(self, batch_size, device, dtype):
+ B: int = batch_size
+ F_mat = torch.rand(B, 3, 3, device=device, dtype=dtype)
+ P = epi.projections_from_fundamental(F_mat)
+ assert P.shape == (B, 3, 4, 2)
+
+ def test_gradcheck(self, device):
+ F_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
+ assert gradcheck(epi.projections_from_fundamental,
+ (F_mat,), raise_exception=True)
diff --git a/test/geometry/epipolar/test_triangulation.py b/test/geometry/epipolar/test_triangulation.py
new file mode 100644
index 000000000..c5729db99
--- /dev/null
+++ b/test/geometry/epipolar/test_triangulation.py
@@ -0,0 +1,54 @@
+import pytest
+
+import torch
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+import kornia
+import kornia.geometry.epipolar as epi
+
+
+class TestTriangulation:
+ def test_smoke(self, device, dtype):
+ P1 = torch.rand(1, 3, 4, device=device, dtype=dtype)
+ P2 = torch.rand(1, 3, 4, device=device, dtype=dtype)
+ points1 = torch.rand(1, 1, 2, device=device, dtype=dtype)
+ points2 = torch.rand(1, 1, 2, device=device, dtype=dtype)
+ points3d = epi.triangulate_points(P1, P2, points1, points2)
+ assert points3d.shape == (1, 1, 3)
+
+ @pytest.mark.parametrize("batch_size, num_points", [(1, 3), (2, 4), (3, 5)])
+ def test_shape(self, batch_size, num_points, device, dtype):
+ B, N = batch_size, num_points
+ P1 = torch.rand(B, 3, 4, device=device, dtype=dtype)
+ P2 = torch.rand(1, 3, 4, device=device, dtype=dtype)
+ points1 = torch.rand(1, N, 2, device=device, dtype=dtype)
+ points2 = torch.rand(B, N, 2, device=device, dtype=dtype)
+ points3d = epi.triangulate_points(P1, P2, points1, points2)
+ assert points3d.shape == (B, N, 3)
+
+ def test_two_view(self, device, dtype):
+ num_views: int = 2
+ num_points: int = 10
+ scene: Dict[str, torch.Tensor] = epi.generate_scene(num_views, num_points)
+
+ P1 = scene['P'][0:1]
+ P2 = scene['P'][1:2]
+ x1 = scene['points2d'][0:1]
+ x2 = scene['points2d'][1:2]
+
+ X = epi.triangulate_points(P1, P2, x1, x2)
+ x_reprojected = kornia.transform_points(scene['P'], X.expand(num_views, -1, -1))
+
+ assert_allclose(scene['points3d'], X, rtol=1e-4, atol=1e-4)
+ assert_allclose(scene['points2d'], x_reprojected)
+
+ def test_gradcheck(self, device):
+ points1 = torch.rand(1, 8, 2, device=device, dtype=torch.float64, requires_grad=True)
+ points2 = torch.rand(1, 8, 2, device=device, dtype=torch.float64)
+ P1 = epi.eye_like(3, points1)
+ P1 = torch.nn.functional.pad(P1, [0, 1])
+ P2 = epi.eye_like(3, points2)
+ P2 = torch.nn.functional.pad(P2, [0, 1])
+ assert gradcheck(epi.triangulate_points,
+ (P1, P2, points1, points2,), raise_exception=True)