Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add get_perpendicular and get_closest_point_on_epipolar_line (#1915)

Dmytro Mishkin2f514e428bcf
diff --git a/docs/source/geometry.epipolar.rst b/docs/source/geometry.epipolar.rst
index 615ddf663..04db58b40 100644
--- a/docs/source/geometry.epipolar.rst
+++ b/docs/source/geometry.epipolar.rst
@@ -27,6 +27,9 @@ Fundamental
.. autofunction:: compute_correspond_epilines
.. autofunction:: normalize_points
.. autofunction:: normalize_transformation
+.. autofunction:: get_perpendicular
+.. autofunction:: get_closest_point_on_epipolar_line
+
Metrics
-------
diff --git a/kornia/geometry/epipolar/__init__.py b/kornia/geometry/epipolar/__init__.py
index e243f8170..a521a9c6a 100644
--- a/kornia/geometry/epipolar/__init__.py
+++ b/kornia/geometry/epipolar/__init__.py
@@ -17,6 +17,8 @@ from .fundamental import (
find_fundamental,
fundamental_from_essential,
fundamental_from_projections,
+ get_closest_point_on_epipolar_line,
+ get_perpendicular,
normalize_points,
normalize_transformation,
)
@@ -60,4 +62,6 @@ __all__ = [
"projections_from_fundamental",
"generate_scene",
"triangulate_points",
+ "get_perpendicular",
+ "get_closest_point_on_epipolar_line",
]
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index 4cdd224e6..e94848122 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -4,11 +4,13 @@ from typing import Tuple
import torch
-from kornia.geometry.conversions import convert_points_to_homogeneous
+from kornia.core import Tensor
+from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
from kornia.geometry.linalg import transform_points
+from kornia.testing import KORNIA_CHECK_SHAPE
-def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]:
+def normalize_points(points: Tensor, eps: float = 1e-8) -> Tuple[Tensor, Tensor]:
r"""Normalizes points (isotropic).
Computes the transformation matrix such that the two principal moments of the set of points
@@ -48,7 +50,7 @@ def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Ten
return (points_norm, transform)
-def normalize_transformation(M: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
+def normalize_transformation(M: Tensor, eps: float = 1e-8) -> Tensor:
r"""Normalize a given transformation matrix.
The function trakes the transformation matrix and normalize so that the value in
@@ -63,11 +65,11 @@ def normalize_transformation(M: torch.Tensor, eps: float = 1e-8) -> torch.Tensor
"""
if len(M.shape) < 2:
raise AssertionError(M.shape)
- norm_val: torch.Tensor = M[..., -1:, -1:]
+ norm_val: 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:
+def find_fundamental(points1: Tensor, points2: Tensor, weights: Tensor) -> Tensor:
r"""Compute the fundamental matrix using the DLT formulation.
The linear system is solved by using the Weighted Least Squares Solution for the 8 Points algorithm.
@@ -117,11 +119,11 @@ def find_fundamental(points1: torch.Tensor, points2: torch.Tensor, weights: torc
return normalize_transformation(F_est)
-def compute_correspond_epilines(points: torch.Tensor, F_mat: torch.Tensor) -> torch.Tensor:
+def compute_correspond_epilines(points: Tensor, F_mat: Tensor) -> Tensor:
r"""Compute the corresponding epipolar line for a given set of points.
Args:
- points: tensor containing the set of points to project in the shape of :math:`(*, N, 2)`.
+ points: tensor containing the set of points to project in the shape of :math:`(*, N, 2)` or :math:`(*, N, 3)`.
F_mat: the fundamental to use for projection the points in the shape of :math:`(*, 3, 3)`.
Returns:
@@ -129,26 +131,80 @@ def compute_correspond_epilines(points: torch.Tensor, F_mat: torch.Tensor) -> to
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)`.
"""
- if not (len(points.shape) >= 2 and points.shape[-1] == 2):
+ KORNIA_CHECK_SHAPE(points, ["*", "N", "DIM"])
+ if points.shape[-1] == 2:
+ points_h: Tensor = convert_points_to_homogeneous(points)
+ elif points.shape[-1] == 3:
+ points_h = points
+ else:
raise AssertionError(points.shape)
- if not (len(F_mat.shape) >= 2 and F_mat.shape[-2:] == (3, 3)):
- raise AssertionError(F_mat.shape)
-
- points_h: torch.Tensor = convert_points_to_homogeneous(points)
-
+ KORNIA_CHECK_SHAPE(F_mat, ["*", "3", "3"])
# project points and retrieve lines components
points_h = torch.transpose(points_h, dim0=-2, dim1=-1)
a, b, c = torch.chunk(F_mat @ points_h, dim=-2, chunks=3)
# compute normal and compose equation line
- nu: torch.Tensor = a * a + b * b
+ nu: Tensor = a * a + b * b
nu = torch.where(nu > 0.0, 1.0 / torch.sqrt(nu), torch.ones_like(nu))
line = torch.cat([a * nu, b * nu, c * nu], dim=-2) # *x3xN
return torch.transpose(line, dim0=-2, dim1=-1) # *xNx3
-def fundamental_from_essential(E_mat: torch.Tensor, K1: torch.Tensor, K2: torch.Tensor) -> torch.Tensor:
+def get_perpendicular(lines: Tensor, points: Tensor) -> Tensor:
+ r"""Compute the perpendicular to a line, through the point.
+
+ Args:
+ lines: tensor containing the set of lines :math:`(*, N, 3)`.
+ points: tensor containing the set of points :math:`(*, N, 2)`.
+
+ Returns:
+ a tensor with shape :math:`(*, N, 3)` containing a vector of the epipolar
+ perpenducular lines. Each line is described as
+ :math:`ax + by + c = 0` and encoding the vectors as :math:`(a, b, c)`.
+ """
+ KORNIA_CHECK_SHAPE(lines, ["*", "N", "3"])
+ KORNIA_CHECK_SHAPE(points, ["*", "N", "two"])
+ if points.shape[2] == 2:
+ points_h: Tensor = convert_points_to_homogeneous(points)
+ elif points.shape[2] == 3:
+ points_h = points
+ else:
+ raise AssertionError(points.shape)
+ infinity_point = lines * torch.tensor([1, 1, 0], dtype=lines.dtype, device=lines.device).view(1, 1, 3)
+ perp: Tensor = points_h.cross(infinity_point, dim=2)
+ return perp
+
+
+def get_closest_point_on_epipolar_line(pts1: Tensor, pts2: Tensor, Fm: Tensor) -> Tensor:
+ r"""Return closest point on the epipolar line to the correspondence, given the fundamental matrix.
+
+ Args:
+ pts1: correspondences from the left images with shape
+ (*, N, 2 or 3). If they are not homogeneous, converted automatically.
+ pts2: correspondences from the right images with shape
+ (*, 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:
+ point on epipolar line :math:`(*, N, 2)`.
+ """
+ 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):
+ raise ValueError(f"Fm must be a (*, 3, 3) tensor. Got {Fm.shape}")
+ if pts1.shape[-1] == 2:
+ pts1 = convert_points_to_homogeneous(pts1)
+ if pts2.shape[-1] == 2:
+ pts2 = convert_points_to_homogeneous(pts2)
+ line1in2 = compute_correspond_epilines(pts1, Fm)
+ perp = get_perpendicular(line1in2, pts2)
+ points1_in_2 = convert_points_from_homogeneous(line1in2.cross(perp, dim=2))
+ return points1_in_2
+
+
+def fundamental_from_essential(E_mat: Tensor, K1: Tensor, K2: Tensor) -> Tensor:
r"""Get the Fundamental matrix from Essential and camera matrices.
Uses the method from Hartley/Zisserman 9.6 pag 257 (formula 9.12).
@@ -178,7 +234,7 @@ def fundamental_from_essential(E_mat: torch.Tensor, K1: torch.Tensor, K2: torch.
# 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:
+def fundamental_from_projections(P1: Tensor, P2: Tensor) -> Tensor:
r"""Get the Fundamental matrix from Projection matrices.
Args:
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index 8e61caafe..01c613bd3 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -145,12 +145,12 @@ def fit_line(points: Tensor, weights: Optional[Tensor] = None) -> ParametrizedLi
Args:
points: tensor containing a batch of sets of n-dimensional points. The expected
- shape of the tensor is :math:`(B,N,D)`.
+ shape of the tensor is :math:`(B, N, D)`.
weights: weights to use to solve the equations system. The expected
- shape of the tensor is :math:`(B,N)`.
+ shape of the tensor is :math:`(B, N)`.
Return:
- A tensor containing the direction of the fited line of shape :math:`(B,D)`.
+ A tensor containing the direction of the fited line of shape :math:`(B, D)`.
Example:
>>> points = torch.rand(2, 10, 3)
@@ -167,7 +167,7 @@ def fit_line(points: Tensor, weights: Optional[Tensor] = None) -> ParametrizedLi
if weights is not None:
KORNIA_CHECK_IS_TENSOR(weights, "weights must be a tensor")
- KORNIA_CHECK_SHAPE(weights, ["B"])
+ KORNIA_CHECK_SHAPE(weights, ["B", "N"])
KORNIA_CHECK(points.shape[0] == weights.shape[0])
A = A.transpose(-2, -1) @ torch.diag_embed(weights) @ A
else:
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index adf6137b7..6b291a8ef 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -5,7 +5,7 @@ import math
from abc import ABC, abstractmethod
from copy import deepcopy
from itertools import product
-from typing import Any, Iterable, List, Optional, Tuple, Type, TypeVar, Union, cast
+from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, TypeVar, Union, cast
import torch
from torch import Tensor
@@ -148,6 +148,47 @@ class BaseTester(ABC):
return assert_close(actual, expected, rtol=rtol, atol=atol)
+def generate_two_view_random_scene(
+ device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.float32
+) -> Dict[str, torch.Tensor]:
+ from kornia.geometry import epipolar as epi
+
+ 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)
+
+
def cartesian_product_of_parameters(**possible_parameters):
"""Create cartesian product of given parameters."""
parameter_names = possible_parameters.keys()
@@ -236,12 +277,15 @@ def KORNIA_CHECK_SHAPE(x, shape: List[str]) -> None:
KORNIA_CHECK_IS_TENSOR(x)
if '*' == shape[0]:
start_idx: int = 1
- x_shape_to_check = x.shape[-len(shape) - 1 :]
+ x_shape_to_check = x.shape[-len(shape) + 1 :]
+ elif '*' == shape[-1]:
+ start_idx: int = 0
+ x_shape_to_check = x.shape[: len(shape) - 1]
else:
start_idx = 0
x_shape_to_check = x.shape
- for i in range(start_idx, len(shape)):
+ for i in range(start_idx, len(x_shape_to_check)):
# The voodoo below is because torchscript does not like
# that dim can be both int and str
dim_: str = shape[i]
diff --git a/test/geometry/epipolar/test_fundamental.py b/test/geometry/epipolar/test_fundamental.py
index fa78823bd..33ba68925 100644
--- a/test/geometry/epipolar/test_fundamental.py
+++ b/test/geometry/epipolar/test_fundamental.py
@@ -6,6 +6,7 @@ import torch
from torch.autograd import gradcheck
import kornia.geometry.epipolar as epi
+import kornia.testing as utils2
from kornia.testing import assert_close
@@ -377,3 +378,47 @@ class TestFundamentalFromProjections:
F_batch = epi.fundamental_from_projections(P1_batch, P2_batch)
F = epi.fundamental_from_projections(P1, P2)
assert (F_batch[0] == F[0]).all()
+
+
+class TestPerpendicular:
+ def test_shape(self, device, dtype):
+ lines = torch.rand(2, 4, 3, device=device, dtype=dtype)
+ points = torch.rand(2, 4, 2, device=device, dtype=dtype)
+ perp = epi.get_perpendicular(lines, points)
+ assert perp.shape == (2, 4, 3)
+
+ def test_result(self, device, dtype):
+ points = torch.tensor([[[1.0, 0.0], [0.0, 1.0]]], device=device, dtype=dtype)
+
+ lines = torch.tensor([[[1.0, -1.0, 0.0], [0.0, 1.0, 1.0]]], device=device, dtype=dtype)
+ perp = epi.get_perpendicular(lines, points)
+ expected = torch.tensor([[[1.0, 1.0, -1.0], [-1.0, 0.0, 0.0]]], device=device, dtype=dtype)
+ assert_close(perp, expected)
+
+ def test_gradcheck(self, device):
+ pt = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
+ line = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
+ assert gradcheck(epi.get_perpendicular, (pt, line), raise_exception=True)
+
+
+class TestGetClosestPointOnEpipolarLine:
+ def test_shape(self, device, dtype):
+ pts1 = torch.rand(2, 4, 2, device=device, dtype=dtype)
+ pts2 = torch.rand(2, 4, 2, device=device, dtype=dtype)
+ Fm = utils2.create_random_fundamental_matrix(1).type_as(pts1)
+ perp = epi.get_closest_point_on_epipolar_line(pts1, pts2, Fm)
+ assert perp.shape == (2, 4, 2)
+
+ def test_shift(self, device, dtype):
+ pts1 = torch.zeros(3, 2, device=device, dtype=dtype)[None]
+ pts2 = torch.tensor([[2, 4.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]
+ cp = epi.get_closest_point_on_epipolar_line(pts1, pts2, Fm)
+ expected = torch.tensor([[[2.0, 0.0], [2.0, 0.0], [2.0, 0.0]]], device=device, dtype=dtype)
+ assert_close(cp, expected)
+
+ def test_gradcheck(self, device):
+ pts1 = torch.rand(2, 4, 2, device=device, dtype=torch.float64, requires_grad=True)
+ pts2 = torch.rand(2, 4, 2, device=device, dtype=torch.float64)
+ Fm = utils2.create_random_fundamental_matrix(1).type_as(pts1)
+ assert gradcheck(epi.get_closest_point_on_epipolar_line, (pts1, pts2, Fm), raise_exception=True)