Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(epipolar): Convention blocks and pins for projection and triangulation (batch 8b) (#4889)

Dmytro Mishkin07e98452e7c8
diff --git a/changelog.d/4889.added.md b/changelog.d/4889.added.md
new file mode 100644
index 000000000..c34c42362
--- /dev/null
+++ b/changelog.d/4889.added.md
@@ -0,0 +1 @@
+Convention blocks for the projection and structure functions of `kornia.geometry.epipolar` (`projection_from_KRt`, `KRt_from_projection`, `projections_from_fundamental`, `depth_from_point`, `scale_intrinsics`, `intrinsics_like`, `random_intrinsics`, `triangulate_points`, `generate_scene`), three functions added to the rendered API reference, and 16 convention and wart pins; the warts are documented and linked (#4263, #4863, #4864, #4865, #4900), not fixed.
diff --git a/docs/source/geometry.epipolar.rst b/docs/source/geometry.epipolar.rst
index 9b2400a2e..e688b47c7 100644
--- a/docs/source/geometry.epipolar.rst
+++ b/docs/source/geometry.epipolar.rst
@@ -49,6 +49,8 @@ Projection
----------
.. autofunction:: projection_from_KRt
+.. autofunction:: KRt_from_projection
+.. autofunction:: depth_from_point
.. autofunction:: projections_from_fundamental
.. autofunction:: intrinsics_like
.. autofunction:: scale_intrinsics
@@ -64,3 +66,4 @@ Triangulation
-------------
.. autofunction:: triangulate_points
+.. autofunction:: generate_scene
diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.py
index 7078f68b1..da9582378 100644
--- a/kornia/geometry/epipolar/projection.py
+++ b/kornia/geometry/epipolar/projection.py
@@ -30,14 +30,21 @@ from .numeric import cross_product_matrix
def intrinsics_like(focal: float, input: torch.Tensor) -> torch.Tensor:
- r"""Return a 3x3 intrinsics matrix, with same size as the input.
+ r"""Return a 3x3 intrinsics matrix per batch element of the input.
- The center of projection will be based in the input image size.
+ Convention:
+ - ``fx = fy = focal`` and the principal point is ``(W / 2, H / 2)`` of the :math:`(B, C, H, W)` input;
+ dtype and device follow the input. ``focal`` must be positive and the input 4-D.
+ - The input must be floating point, like kornia's images: an integer input raises by design rather than
+ returning an integer ``K``.
+ - Known defects: ``(W / 2, H / 2)`` is the half-pixel centre, not the integer-pixel centre
+ ``((W - 1) / 2, (H - 1) / 2)`` of kornia's grids
+ (`#4263 <https://github.com/kornia/kornia/issues/4263>`_).
Args:
focal: the focal length for the camera matrix.
input: 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)`.
+ and width. It is assumed to be a floating-point tensor in the shape of :math:`(B, C, H, W)`.
Returns:
The camera matrix with the shape of :math:`(B, 3, 3)`.
@@ -61,6 +68,11 @@ def intrinsics_like(focal: float, input: torch.Tensor) -> torch.Tensor:
def random_intrinsics(low: Union[float, torch.Tensor], high: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Generate a random camera matrix based on a given uniform distribution.
+ Convention:
+ - ``fx``, ``fy``, ``cx`` and ``cy`` are four draws from :math:`U(low, high)` on torch's global generator.
+ The bounds are scalars; dtype and device follow tensor bounds, and Python floats give the default dtype
+ and device.
+
Args:
low: lower range (inclusive).
high: upper range (exclusive).
@@ -81,13 +93,21 @@ def scale_intrinsics(camera_matrix: torch.Tensor, scale_factor: Union[float, tor
Applies the scaling factor to the focal length and center of projection.
+ Convention:
+ - Applies the rule of :meth:`~kornia.geometry.camera.pinhole.PinholeCamera.scale` and returns a new tensor.
+ - Known defects: the principal-point rule of
+ :meth:`~kornia.geometry.camera.pinhole.PinholeCamera.scale`, and the skew ``K[0, 1]``, which is left
+ unscaled although resizing by ``scale_factor`` scales it
+ (`#4263 <https://github.com/kornia/kornia/issues/4263>`_).
+
Args:
camera_matrix: the camera calibration matrix containing the intrinsic
parameters. The expected shape for the tensor is :math:`(B, 3, 3)`.
- scale_factor: the scaling factor to be applied.
+ scale_factor: the scaling factor to be applied: a float, or a tensor of shape :math:`(B,)` that
+ scales each batch element by its own factor.
Returns:
- The scaled camera matrix with shame shape as input :math:`(B, 3, 3)`.
+ The scaled camera matrix with the same shape as the input :math:`(B, 3, 3)`.
"""
K_scale = camera_matrix.clone()
@@ -101,15 +121,22 @@ def scale_intrinsics(camera_matrix: torch.Tensor, scale_factor: Union[float, tor
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]`.
+ This function computes the product :math:`P = K [R|t]`.
+
+ Convention:
+ - ``R`` and ``t`` take world points into the camera frame, ``X_cam = R @ X + t``, and ``K`` takes the
+ camera frame to pixels. ``t`` is the extrinsic translation; the camera centre is ``-R.T @ t``.
+ - ``K``, ``R`` and ``t`` must have the same number of dimensions, and ``R`` and ``t`` the same batch shape;
+ ``K`` broadcasts against them. The inverse is
+ :func:`KRt_from_projection`, and :func:`depth_from_point` gives the depth of a point in this camera.
Args:
- K: the camera matrix with the intrinsics with shape :math:`(B, 3, 3)`.
- R: The rotation matrix with shape :math:`(B, 3, 3)`.
- t: The translation vector with shape :math:`(B, 3, 1)`.
+ K: the camera matrix with the intrinsics with shape :math:`(*, 3, 3)`.
+ R: The rotation matrix with shape :math:`(*, 3, 3)`.
+ t: The translation vector with shape :math:`(*, 3, 1)`.
Returns:
- The projection matrix P with shape :math:`(B, 4, 4)`.
+ The projection matrix P with shape :math:`(*, 3, 4)`.
"""
KORNIA_CHECK_SHAPE(K, ["*", "3", "3"])
@@ -129,16 +156,30 @@ def projection_from_KRt(K: torch.Tensor, R: torch.Tensor, t: torch.Tensor) -> to
def KRt_from_projection(P: torch.Tensor, eps: float = 1e-6) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
- r"""Decompose the Projection matrix into Camera-Matrix, Rotation Matrix and Translation vector.
+ r"""Decompose the Projection matrix into ``K``, ``R`` and ``t`` with :math:`P = K [R|t]`.
+
+ Convention:
+ - Inverse of :func:`projection_from_KRt`: returns ``K`` (upper triangular, positive diagonal), ``R``
+ and the translation ``t``, not the camera centre; :ref:`Two-view geometry <two-view-conventions>` maps
+ this onto OpenCV.
+ - ``K`` is not normalised to ``K[2, 2] = 1``: it carries the magnitude of the scale of ``P``, so ``2 * P``
+ doubles ``K``; divide by ``K[..., 2:, 2:]`` to normalise.
+ - ``P`` must have exactly one batch dimension. float16 and bfloat16 raise.
+ - Known defects: a ``P`` whose left :math:`3 \times 3` block has negative determinant returns a
+ reflection (``det R = -1``), the signs moved into rows of ``R`` and the matching entries of ``t``: all
+ three for ``-P``, which gives ``-R`` and ``-t``; and ``eps`` is added to the diagonal before its sign is
+ taken, so an entry in ``(-eps, 0)`` stays negative and the matching row of ``R`` and entry of ``t`` are
+ negated
+ (`#4864 <https://github.com/kornia/kornia/issues/4864>`_).
Args:
P: the projection matrix with shape :math:`(B, 3, 4)`.
- eps: epsilon for numerical stability.
+ eps: offset added to the diagonal of the triangular factor before its sign is taken.
Returns:
- The Camera matrix with shape :math:`(B, 3, 3)`.
- The Rotation matrix with shape :math:`(B, 3, 3)`.
- - The Translation vector with shape :math:`(B, 3)`.
+ - The Translation vector with shape :math:`(B, 3, 1)`.
"""
KORNIA_CHECK_SHAPE(P, ["*", "3", "4"])
@@ -167,13 +208,18 @@ def KRt_from_projection(P: torch.Tensor, eps: float = 1e-6) -> Tuple[torch.Tenso
def depth_from_point(R: torch.Tensor, t: torch.Tensor, X: torch.Tensor) -> torch.Tensor:
r"""Return the depth of a point transformed by a rigid transform.
+ Convention:
+ - Returns the ``z`` coordinate of ``R @ X + t``, the depth in the camera of :func:`projection_from_KRt`
+ with the same ``R`` and ``t``. The sign is not checked. An ``X`` of shape ``(B, 3)`` with a batched
+ ``R`` is read as ``B`` points seen by every camera and gives ``(B, B)``, not one point per camera.
+
Args:
R: The rotation matrix with shape :math:`(*, 3, 3)`.
t: The translation vector with shape :math:`(*, 3, 1)`.
- X: The 3d points with shape :math:`(*, 3)`.
+ X: The 3d points with shape :math:`(*, N, 3)`.
Returns:
- The depth value per point with shape :math:`(*, 1)`.
+ The depth value per point with shape :math:`(*, N)`.
"""
X_tmp = R @ X.transpose(-2, -1)
@@ -195,6 +241,13 @@ def _nullspace(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
def projections_from_fundamental(F_mat: torch.Tensor) -> torch.Tensor:
r"""Get the projection matrices from the Fundamental Matrix.
+ Convention:
+ - Returns the canonical pair for ``F`` in the ``x2^T F x1 = 0`` convention of
+ :func:`~kornia.geometry.epipolar.find_fundamental`, stacked on the last dimension:
+ ``[..., 0] = [I | 0]`` for the first image and ``[..., 1] = [[e2]_x F | e2]``, with ``e2`` the
+ left null vector of ``F``, the epipole in the second image (``e2^T F = 0``).
+ - ``F_mat`` must have exactly one batch dimension.
+
Args:
F_mat: the fundamental matrix with the shape :math:`(B, 3, 3)`.
diff --git a/kornia/geometry/epipolar/scene.py b/kornia/geometry/epipolar/scene.py
index 7c82d2c9d..63898781c 100644
--- a/kornia/geometry/epipolar/scene.py
+++ b/kornia/geometry/epipolar/scene.py
@@ -15,7 +15,7 @@
# limitations under the License.
#
-"""nn.Module to generate synthetic 3d scenes."""
+"""Generate synthetic 3d scenes."""
import math
from typing import Dict
@@ -29,7 +29,27 @@ from .projection import projection_from_KRt, random_intrinsics
def generate_scene(num_views: int, num_points: int) -> Dict[str, torch.Tensor]:
- """Generate 3d scene."""
+ """Generate a random 3d scene seen by ``num_views`` cameras that share one camera matrix.
+
+ Convention:
+ - Every point has positive depth in every view; depth and focal length are not bounded away from zero.
+ - Draws from torch's global generator.
+
+ Args:
+ num_views: the number of views :math:`V`.
+ num_points: the number of 3d points :math:`N`.
+
+ Returns:
+ A dictionary of tensors on torch's default device and in the default dtype:
+
+ - ``"K"``: the camera matrix shared by all views, with shape :math:`(1, 3, 3)`.
+ - ``"R"``: the rotation of each view, with shape :math:`(V, 3, 3)`.
+ - ``"t"``: the translation of each view, with shape :math:`(V, 3, 1)`.
+ - ``"P"``: the projection matrix :math:`K [R|t]` of each view, with shape :math:`(V, 3, 4)`.
+ - ``"points3d"``: the 3d points, in :math:`[0, 1)` per coordinate, with shape :math:`(1, N, 3)`.
+ - ``"points2d"``: the projection of ``points3d`` by each ``P``, with shape :math:`(V, N, 2)`.
+
+ """
# Generate the 3d points
points3d = torch.rand(1, num_points, 3) # NxMx3
diff --git a/kornia/geometry/epipolar/triangulation.py b/kornia/geometry/epipolar/triangulation.py
index 872f58202..276b4c1e7 100644
--- a/kornia/geometry/epipolar/triangulation.py
+++ b/kornia/geometry/epipolar/triangulation.py
@@ -65,35 +65,54 @@ def triangulate_points(
) -> 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 formulation from Hartley/Zisserman 12.2 pag.312
-
- The input points are assumed to be in homogeneous coordinate system and being inliers
- correspondences. The method does not perform any robust estimation.
+ Triangulates the 3d position of 2d correspondences between two images.
+ Reference: the ``"svd"`` and ``"eigh"`` solvers use the DLT formulation from Hartley/Zisserman 12.2 pag.312.
+
+ The input points are assumed to be inlier correspondences. The method does not perform any robust
+ estimation.
+
+ Convention:
+ - ``P1`` pairs with ``points1`` and ``P2`` with ``points2``. Input and output points are Euclidean;
+ :ref:`Two-view geometry <two-view-conventions>` maps this onto OpenCV. The leading
+ dimensions of ``P1`` and ``P2`` broadcast against those of the points.
+ - Cheirality and baseline are not checked: a point behind a camera is returned with negative depth, and with
+ zero baseline the depth is undefined and ``"svd"`` and ``"eigh"`` return an arbitrary point on the line of
+ sight, possibly behind the camera.
+ - ``"svd"`` and ``"eigh"`` solve in float64, or in float32 for float16 and bfloat16 input and on MPS, and
+ return the input dtype; ``solver`` below compares their accuracy.
+ - Known defects: a correspondence at infinity comes back unflagged, as a finite point at a distance set by
+ roundoff or as ``inf`` in float16 (`#4865 <https://github.com/kornia/kornia/issues/4865>`_);
+ ``solver="cofactor"`` returns NaN for pixel-scale float16 input
+ (`#4863 <https://github.com/kornia/kornia/issues/4863>`_) and can return a point unrelated to the input when a
+ :math:`3 \times 4` sub-system is rank-deficient or nearly so: with zero baseline, and for a point whose
+ row in the first image or column in the second passes through or near the epipole. Rectified stereo pairs
+ are susceptible with or without noise (`#4900 <https://github.com/kornia/kornia/issues/4900>`_).
Args:
P1: The projection matrix for the first camera with shape :math:`(*, 3, 4)`.
P2: The projection matrix for the second camera with shape :math:`(*, 3, 4)`.
- points1: The set of points seen from the first camera frame in the camera plane
- coordinates with shape :math:`(*, N, 2)`.
- points2: The set of points seen from the second camera frame in the camera plane
- coordinates with shape :math:`(*, N, 2)`.
+ points1: The set of points seen from the first camera, in the image coordinates of ``P1`` (pixels
+ for ``P1 = K [R | t]``), with shape :math:`(*, N, 2)`.
+ points2: The set of points seen from the second camera, in the image coordinates of ``P2`` (pixels
+ for ``P2 = K [R | t]``), with shape :math:`(*, N, 2)`.
solver: Back-end used to find the null vector of the :math:`4 \times 4` DLT
constraint matrix. One of:
- * ``"svd"`` β€” most numerically stable. Promotes to fp64 and uses a full
- SVD (via :func:`~kornia.core.utils._torch_svd_cast`). Suitable when
+ * ``"svd"`` β€” most numerically stable. Uses a full SVD. Suitable when
maximum accuracy is required regardless of speed.
* ``"eigh"`` *(default)* β€” forms :math:`X^\top X` and finds the eigenvector
for its smallest eigenvalue via :func:`torch.linalg.eigh`. Algebraically
- equivalent to the SVD solution; slightly less numerically stable because
- forming :math:`X^\top X` squares the singular values. Typically **10-26x
+ equivalent to the SVD solution, and equal to it to roundoff on well-conditioned
+ input; forming :math:`X^\top X` squares the singular values, so on ill-conditioned
+ rows, such as a baseline much shorter than the depth, it loses accuracy that
+ ``"svd"`` keeps. Typically **10-26x
faster** than ``"svd"`` on GPU for large batches.
* ``"cofactor"`` β€” solves two :math:`3 \times 4` sub-systems analytically
using :func:`~kornia.geometry.solvers.null_vector_3x4` (closed-form
cofactor expansion, no LAPACK call). The two solutions are averaged after
normalisation. This matches the full DLT solution when the constraint
- system is exactly consistent, but is only an approximation in the noisy
+ system is exactly consistent and both sub-systems have full rank (see the
+ known defects above), but is only an approximation in the noisy
inconsistent case. Fastest option for all batch sizes.
Returns:
@@ -102,6 +121,7 @@ def triangulate_points(
Example:
>>> P1 = torch.eye(3, 4)[None] # 1x3x4
>>> P2 = torch.eye(3, 4)[None]
+ >>> P2[..., 0, 3] = -1.0 # second camera shifted along x
>>> pts1 = torch.rand(1, 5, 2)
>>> pts2 = torch.rand(1, 5, 2)
>>> pts3d = triangulate_points(P1, P2, pts1, pts2)
diff --git a/tests/geometry/epipolar/test_projection.py b/tests/geometry/epipolar/test_projection.py
index a5ac0a08b..0d4108a61 100644
--- a/tests/geometry/epipolar/test_projection.py
+++ b/tests/geometry/epipolar/test_projection.py
@@ -20,8 +20,10 @@ import torch
from torch.autograd import gradcheck
import kornia.geometry.epipolar as epi
+from kornia.geometry.camera import PinholeCamera
from testing.base import BaseTester
+from testing.two_view import two_view_scene
class TestIntrinsicsLike:
@@ -225,3 +227,219 @@ class TestKRtFromProjection(BaseTester):
def test_gradcheck(self, device):
P_mat = torch.rand(1, 3, 4, device=device, dtype=torch.float64, requires_grad=True)
assert self.gradcheck(epi.KRt_from_projection, (P_mat,), raise_exception=True, fast_mode=True)
+
+
+_NO_HALF_QR = "KRt_from_projection does not upcast half input, and torch.linalg.qr has no float16/bfloat16 kernel"
+
+
+def _skip_half(dtype: torch.dtype, reason: str) -> None:
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip(reason)
+
+
+def _dehom(x: torch.Tensor) -> torch.Tensor:
+ return x[..., :2] / x[..., 2:]
+
+
+def _project(P: torch.Tensor, X: torch.Tensor) -> torch.Tensor:
+ """Pixels of the (B, N, 3) points X through the (B, 3, 4) camera P."""
+ return _dehom(torch.cat([X, torch.ones_like(X[..., :1])], -1) @ P.transpose(-2, -1))
+
+
+def _det3(M: torch.Tensor) -> torch.Tensor:
+ """Determinant of a (..., 3, 3) matrix from its rows, without an LU kernel."""
+ return (torch.linalg.cross(M[..., 0, :], M[..., 1, :]) * M[..., 2, :]).sum(-1)
+
+
+def _unit(M: torch.Tensor) -> torch.Tensor:
+ """(B, 3, 3) matrix scaled to unit Frobenius norm."""
+ return M / M.flatten(-2).norm(dim=-1)[..., None, None]
+
+
+class TestConventionProjection(BaseTester):
+ def test_convention_projection_from_KRt_is_K_R_t(self, device, dtype):
+ two_view = two_view_scene(device, dtype)
+ K1, K2, R, t, X = two_view["K1"], two_view["K2"], two_view["R"], two_view["t"], two_view["X"]
+ P = epi.projection_from_KRt(K2, R, t)
+ assert P.shape == (1, 3, 4)
+ self.assert_close(P, K2 @ torch.cat([R, t], -1))
+ # (R, t) is world-to-camera: a world point X projects like K (R X + t). The camera-to-world reading
+ # K R^T (X - t) is the control; on this fixture it is more than 100 px away.
+ atol = {torch.float16: 1.0, torch.bfloat16: 4.0, torch.float32: 1e-3}.get(dtype, 1e-8)
+ world_to_camera = _dehom((X @ R.transpose(-2, -1) + t.transpose(-2, -1)) @ K2.transpose(-2, -1))
+ camera_to_world = _dehom(((X - t.transpose(-2, -1)) @ R) @ K2.transpose(-2, -1))
+ self.assert_close(_project(P, X), world_to_camera, rtol=0.0, atol=atol)
+ assert (_project(P, X) - camera_to_world).abs().max() > 100.0
+ # Batched inputs give one camera per batch element.
+ eye = torch.eye(3, device=device, dtype=dtype)[None]
+ Pb = epi.projection_from_KRt(torch.cat([K1, K2]), torch.cat([eye, R]), torch.cat([torch.zeros_like(t), t]))
+ assert Pb.shape == (2, 3, 4)
+ self.assert_close(Pb[:1], torch.cat([K1, torch.zeros_like(t)], -1))
+ self.assert_close(Pb[1:], P)
+ # K, R and t must have the same number of dimensions.
+ with pytest.raises(AssertionError):
+ epi.projection_from_KRt(K2[0], R, t)
+
+ def test_convention_krt_from_projection_returns_extrinsic_t(self, device, dtype):
+ two_view = two_view_scene(device, dtype)
+ # P must have exactly one batch dimension.
+ for P_bad in (two_view["P2"][0], two_view["P2"][None]):
+ with pytest.raises(Exception):
+ epi.KRt_from_projection(P_bad)
+ if dtype in (torch.float16, torch.bfloat16):
+ # float16 and bfloat16 raise: the input is not upcast (projections_from_fundamental upcasts).
+ with pytest.raises(Exception):
+ epi.KRt_from_projection(two_view["P2"])
+ return
+ K_true, R_true, t_true = two_view["K2"], two_view["R"], two_view["t"]
+ K, R, t = epi.KRt_from_projection(two_view["P2"])
+ assert K.shape == (1, 3, 3) and R.shape == (1, 3, 3) and t.shape == (1, 3, 1)
+ # K is upper triangular with a positive diagonal; R is a rotation.
+ assert torch.tril(K, diagonal=-1).abs().max() <= 1e-6 * K.abs().max()
+ assert (K.diagonal(dim1=-2, dim2=-1) > 0).all()
+ # K's entries are in pixels, so its zero skew carries float32 roundoff at that scale.
+ self.assert_close(K, K_true, rtol=1e-4, atol=1e-3)
+ self.assert_close(R, R_true)
+ self.assert_close(R @ R.transpose(-2, -1), torch.eye(3, device=device, dtype=dtype)[None])
+ self.assert_close(_det3(R), torch.ones(1, device=device, dtype=dtype))
+ # t is the extrinsic translation of P = K [R | t], not the camera centre -R^T t (OpenCV's
+ # decomposeProjectionMatrix returns the centre); the two are about 1.0 apart on this fixture.
+ self.assert_close(t, t_true)
+ assert (t - (-R_true.transpose(-2, -1) @ t_true)).abs().max() > 0.5
+ # K is not normalised to K[2, 2] = 1: it carries the scale of P, while R and t do not.
+ K2x, R2x, t2x = epi.KRt_from_projection(2.0 * two_view["P2"])
+ self.assert_close(K2x[:, 2, 2], torch.full_like(K2x[:, 2, 2], 2.0))
+ self.assert_close(K2x / K2x[..., 2:, 2:], K_true, rtol=1e-4, atol=1e-3)
+ self.assert_close(R2x, R_true)
+ self.assert_close(t2x, t_true)
+
+ def test_convention_projections_from_fundamental_layout(self, device, dtype):
+ two_view = two_view_scene(device, dtype)
+ # F is the essential matrix of the fixture, the fundamental matrix of normalised image coordinates, so
+ # its entries stay inside the half-precision range; it satisfies x2^T F x1 = 0 like find_fundamental's F.
+ eye = torch.eye(3, device=device, dtype=dtype)[None]
+ F = epi.essential_from_Rt(eye, torch.zeros_like(two_view["t"]), two_view["R"], two_view["t"])
+ PP = epi.projections_from_fundamental(F)
+ # The pair is stacked on the last dimension, first image first: [..., 0] = [I | 0].
+ assert PP.shape == (1, 3, 4, 2)
+ self.assert_close(PP[..., 0], torch.eye(3, 4, device=device, dtype=dtype)[None])
+ # [..., 1] = [[e2]_x F | e2] with e2 the epipole in the second image, the left null vector of F.
+ # The right null vector (the epipole in the first image) is the control.
+ e2 = PP[:, :, 3, 1]
+ assert (e2[:, None] @ F).abs().max() < 1e-2 * (F @ e2[..., None]).abs().max()
+ self.assert_close(PP[:, :, :3, 1], epi.cross_product_matrix(e2) @ F)
+ # The pair reproduces F up to scale in the (first, second) order; the reversed order gives F^T.
+ F_pair = epi.fundamental_from_projections(PP[..., 0], PP[..., 1])
+ F_reversed = epi.fundamental_from_projections(PP[..., 1], PP[..., 0])
+ Ft = F.transpose(-2, -1)
+ self.assert_close(_unit(F_pair) * torch.sign((F_pair * F).sum()), _unit(F))
+ self.assert_close(_unit(F_reversed) * torch.sign((F_reversed * Ft).sum()), _unit(Ft))
+ assert (_unit(F_reversed) * torch.sign((F_reversed * F).sum()) - _unit(F)).abs().max() > 0.1
+ # F_mat must have exactly one batch dimension.
+ for F_bad in (F[0], F[None]):
+ with pytest.raises(Exception):
+ epi.projections_from_fundamental(F_bad)
+
+ def test_convention_depth_from_point_is_camera_z(self, device, dtype):
+ two_view = two_view_scene(device, dtype)
+ R, t, X = two_view["R"], two_view["t"], two_view["X"]
+ depth = epi.depth_from_point(R, t, X)
+ # The z coordinate of R X + t, one value per point.
+ assert depth.shape == (1, 12)
+ self.assert_close(depth, (X @ R.transpose(-2, -1) + t.transpose(-2, -1))[..., 2])
+ # Controls: the camera-to-world reading R^T (X - t) is about 0.58 away, and negating t moves every depth
+ # by 2 * t_z = 0.04.
+ assert (depth - ((X - t.transpose(-2, -1)) @ R)[..., 2]).abs().max() > 0.25
+ assert (epi.depth_from_point(R, -t, X) - depth).abs().min() > 0.02
+ # The sign is not checked: the fixture points are in front of the camera, and their negatives, behind it,
+ # get a negative depth instead of an error.
+ assert (depth > 0).all()
+ assert (epi.depth_from_point(R, t, -X) < 0).all()
+
+ def test_convention_scale_intrinsics_matches_pinhole_scale(self, device, dtype):
+ two_view = two_view_scene(device, dtype)
+ K = torch.cat([two_view["K1"], two_view["K2"]])
+ K_before = K.clone()
+ scale = torch.tensor([0.5, 3.0], device=device, dtype=dtype)
+ out = epi.scale_intrinsics(K, scale)
+ # A (B,) scale factor scales batch element b by scale[b]; the focal lengths show the pairing.
+ expected_f = torch.tensor([[400.0, 380.0], [2100.0, 2220.0]], device=device, dtype=dtype)
+ self.assert_close(out[:, [0, 1], [0, 1]], expected_f)
+ # It is the rule of PinholeCamera.scale, bit for bit, principal point included (its value is the #4263 wart
+ # pinned below).
+ bottom = torch.tensor([[[0.0, 0.0, 0.0, 1.0]]], device=device, dtype=dtype).expand(2, 1, 4)
+ K44 = torch.cat([torch.cat([K, torch.zeros_like(K[..., :1])], -1), bottom], -2)
+ E44 = torch.eye(4, device=device, dtype=dtype)[None].expand(2, 4, 4)
+ size = torch.tensor([480.0, 480.0], device=device, dtype=dtype)
+ pinhole = PinholeCamera(K44, E44, size, size.clone()).scale(scale)
+ assert torch.equal(out, pinhole.intrinsics[:, :3, :3])
+ # A new tensor is returned; the input is not modified.
+ assert torch.equal(K, K_before)
+
+ def test_convention_intrinsics_like_follows_input(self, device, dtype):
+ image = torch.zeros(2, 3, 4, 6, device=device, dtype=dtype) # H = 4, W = 6
+ K = epi.intrinsics_like(500.0, image)
+ assert K.shape == (2, 3, 3)
+ assert K.dtype == dtype and K.device == image.device
+ # fx = fy = focal, no skew, K[2] = [0, 0, 1].
+ self.assert_close(K[:, [0, 1], [0, 1]], torch.full((2, 2), 500.0, device=device, dtype=dtype))
+ zeros = torch.zeros(2, device=device, dtype=dtype)
+ self.assert_close(K[:, 0, 1], zeros)
+ self.assert_close(K[:, 1, 0], zeros)
+ self.assert_close(K[:, 2], torch.tensor([[0.0, 0.0, 1.0]], device=device, dtype=dtype).expand(2, 3))
+ # cx follows the width and cy the height: cx - cy = (W - H) / 2 whichever pixel-centre rule #4263 settles
+ # on; the transposed image is the control.
+ self.assert_close(K[:, 0, 2] - K[:, 1, 2], torch.full_like(zeros, 1.0))
+ K_t = epi.intrinsics_like(500.0, image.transpose(-2, -1))
+ self.assert_close(K_t[:, 0, 2] - K_t[:, 1, 2], torch.full_like(zeros, -1.0))
+ # The image must be floating point (a design choice): an integer image raises instead of returning an
+ # integer K.
+ with pytest.raises(Exception):
+ epi.intrinsics_like(500.0, torch.zeros(1, 3, 4, 6, device=device, dtype=torch.uint8))
+
+ def test_wart_krt_from_projection_negative_P_reflection_4864(self, device, dtype):
+ two_view = two_view_scene(device, dtype)
+ _skip_half(dtype, _NO_HALF_QR)
+ # #4864: -P is the same camera as P, but the result keeps K's diagonal positive and returns the reflection
+ # -R (det -1) with -t. Once fixed, R is a proper rotation and the sign moves into K.
+ P, R_true, t_true = two_view["P2"], two_view["R"], two_view["t"]
+ _, R_pos, _ = epi.KRt_from_projection(P)
+ self.assert_close(_det3(R_pos), torch.ones(1, device=device, dtype=dtype))
+ K, R, t = epi.KRt_from_projection(-P)
+ assert (K.diagonal(dim1=-2, dim2=-1) > 0).all()
+ self.assert_close(_det3(R), -torch.ones(1, device=device, dtype=dtype))
+ self.assert_close(R, -R_true)
+ self.assert_close(t, -t_true)
+ if device.type != "cpu":
+ # The sub-eps case depends on the QR backend's sign for an entry of magnitude ~eps (MPS returns +2e-8
+ # where CPU LAPACK returns a negative entry), so it is asserted on the CPU only.
+ return
+ # Same issue: eps is added to K's raw diagonal before its sign is taken, so 1e-7 * P (a positive scale)
+ # keeps a negative K[2, 2] and returns a reflection.
+ # The matching (last) row of R and entry of t are negated; the other two are R_true's and t_true's.
+ K_small, R_small, t_small = epi.KRt_from_projection(1e-7 * P)
+ assert K_small[0, 2, 2] < 0
+ self.assert_close(R_small[:, :2], R_true[:, :2])
+ self.assert_close(R_small[:, 2], -R_true[:, 2])
+ self.assert_close(t_small[:, :2], t_true[:, :2])
+ self.assert_close(t_small[:, 2], -t_true[:, 2])
+
+ def test_wart_scale_intrinsics_principal_point_rule_4263(self, device, dtype):
+ # #4263: the same rule as PinholeCamera.scale, pinned there by
+ # test_wart_scale_rescales_the_principal_point_by_the_half_pixel_rule_4263 on the same numbers: cx' = s * cx
+ # (2.0 for cx = 4, s = 0.5), the half-pixel rule, while kornia's integer pixel centres give
+ # cx' = s * cx + (s - 1) / 2 = 1.75. The skew K[0, 1] is not scaled (a full rescale gives 1.5).
+ K = torch.tensor([[[100.0, 3.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ out = epi.scale_intrinsics(K, torch.tensor([0.5], device=device, dtype=dtype))
+ self.assert_close(out[:, 0, 2], torch.tensor([2.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(out[:, 1, 2], torch.tensor([1.5], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(out[:, 0, 0], torch.tensor([50.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(out[:, 0, 1], torch.tensor([3.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+
+ def test_wart_intrinsics_like_principal_point_half_pixel_4263(self, device, dtype):
+ # #4263: the principal point is (W / 2, H / 2), (3.0, 2.0)
+ # for H = 4, W = 6, the half-pixel centre, while kornia's integer pixel centres put it at
+ # ((W - 1) / 2, (H - 1) / 2) = (2.5, 1.5).
+ K = epi.intrinsics_like(500.0, torch.zeros(1, 3, 4, 6, device=device, dtype=dtype))
+ self.assert_close(K[:, 0, 2], torch.tensor([3.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(K[:, 1, 2], torch.tensor([2.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
diff --git a/tests/geometry/epipolar/test_scene.py b/tests/geometry/epipolar/test_scene.py
new file mode 100644
index 000000000..e354a1684
--- /dev/null
+++ b/tests/geometry/epipolar/test_scene.py
@@ -0,0 +1,79 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import pytest
+import torch
+
+import kornia.geometry.epipolar as epi
+
+from testing.base import BaseTester
+
+_SCENE_SHAPES = {
+ "K": (1, 3, 3),
+ "R": (3, 3, 3),
+ "t": (3, 3, 1),
+ "P": (3, 3, 4),
+ "points3d": (1, 7, 3),
+ "points2d": (3, 7, 2),
+}
+
+
+class TestConventionScene(BaseTester):
+ def test_convention_random_intrinsics_global_generator(self, device, dtype):
+ # fx, fy, cx, cy are four consecutive draws of U(low, high) from the global generator, in the dtype and on
+ # the device of the bounds.
+ low = torch.tensor(10.0, device=device, dtype=dtype)
+ high = torch.tensor(20.0, device=device, dtype=dtype)
+ torch.manual_seed(0)
+ K = epi.random_intrinsics(low, high)
+ K_next = epi.random_intrinsics(low, high)
+ torch.manual_seed(0)
+ K_again = epi.random_intrinsics(low, high)
+ torch.manual_seed(0)
+ draws = torch.distributions.Uniform(low, high).sample((4,))
+ assert K.shape == (1, 3, 3) and K.dtype == dtype and K.device == low.device
+ assert torch.equal(K, K_again)
+ assert not torch.equal(K, K_next)
+ self.assert_close(K[0, [0, 1, 0, 1], [0, 1, 2, 2]], draws)
+ self.assert_close(K[0, 2], torch.tensor([0.0, 0.0, 1.0], device=device, dtype=dtype))
+
+ def test_convention_generate_scene_global_generator(self, device, dtype):
+ if device.type != "cpu":
+ pytest.skip("generate_scene takes no device argument and draws on torch's default device")
+ # The same global generator as random_intrinsics, tensors in the default dtype.
+ default_dtype = torch.get_default_dtype()
+ try:
+ torch.set_default_dtype(dtype)
+ torch.manual_seed(0)
+ scene = epi.generate_scene(3, 7)
+ scene_next = epi.generate_scene(3, 7)
+ torch.manual_seed(0)
+ scene_again = epi.generate_scene(3, 7)
+ finally:
+ torch.set_default_dtype(default_dtype)
+ assert {k: tuple(v.shape) for k, v in scene.items()} == _SCENE_SHAPES
+ assert all(v.dtype == dtype and v.device.type == "cpu" for v in scene.values())
+ assert all(torch.equal(scene[k], scene_again[k]) for k in _SCENE_SHAPES)
+ assert not any(torch.equal(scene[k], scene_next[k]) for k in _SCENE_SHAPES)
+ # One K for every view, P = K [R | t] per view, and points2d the pixels of points3d through each P, all
+ # in front of every camera.
+ K, R, t, P = scene["K"], scene["R"], scene["t"], scene["P"]
+ self.assert_close(P, K @ torch.cat([R, t], -1))
+ X = scene["points3d"].expand(3, -1, -1)
+ x = torch.cat([X, torch.ones_like(X[..., :1])], -1) @ P.transpose(-2, -1)
+ self.assert_close(x[..., :2] / x[..., 2:], scene["points2d"], low_tolerance=True)
+ assert ((X @ R.transpose(-2, -1) + t.transpose(-2, -1))[..., 2] > 0).all()
diff --git a/tests/geometry/epipolar/test_triangulation.py b/tests/geometry/epipolar/test_triangulation.py
index 744181543..706d9b3fd 100644
--- a/tests/geometry/epipolar/test_triangulation.py
+++ b/tests/geometry/epipolar/test_triangulation.py
@@ -25,6 +25,7 @@ import kornia
import kornia.geometry.epipolar as epi
from testing.base import BaseTester
+from testing.two_view import two_view_scene
SOLVERS = ["svd", "eigh", "cofactor"]
@@ -325,3 +326,149 @@ class TestTriangulation(BaseTester):
pts = torch.rand(1, 3, 2, device=device, dtype=dtype)
out = epi.triangulate_points(P1, P2, pts, pts)
assert out.shape == (1, 3, 3)
+
+
+def _dehom(x: torch.Tensor) -> torch.Tensor:
+ return x[..., :2] / x[..., 2:]
+
+
+# Error bound for svd/eigh on the exact two-view fixture: float16/bfloat16 build the DLT rows in the input dtype.
+_TRIANGULATION_ATOL = {torch.float16: 5e-2, torch.bfloat16: 0.5, torch.float32: 1e-3, torch.float64: 1e-9}
+# Bound on the distance from the line of sight, relative to |X|, at zero baseline (the rows carry the input dtype's
+# roundoff; a point off the line, such as the #4900 cofactor output, is at 9 or more in float32 and float64).
+_OFF_RAY_TOL = {torch.float16: 2e-2, torch.bfloat16: 0.3, torch.float32: 1e-2, torch.float64: 1e-2}
+
+
+class TestConventionTriangulation(BaseTester):
+ def test_convention_triangulate_points_argument_pairing(self, device, dtype):
+ two_view = two_view_scene(device, dtype)
+ P1, P2, x1, x2, X = two_view["P1"], two_view["P2"], two_view["x1"], two_view["x2"], two_view["X"]
+ atol = _TRIANGULATION_ATOL[dtype]
+ results = {}
+ for solver in ("svd", "eigh"):
+ # P1 pairs with points1 and P2 with points2; the output is Euclidean (B, N, 3) in the input dtype.
+ out = epi.triangulate_points(P1, P2, x1, x2, solver=solver)
+ assert out.shape == (1, 12, 3)
+ assert out.dtype == dtype
+ self.assert_close(out, X, rtol=0.0, atol=atol)
+ # Relabelling: swapping the two views as a whole recovers the same points; swapping only the cameras
+ # or only the points misplaces every point, by more than 1.0.
+ self.assert_close(epi.triangulate_points(P2, P1, x2, x1, solver=solver), X, rtol=0.0, atol=atol)
+ for wrong in (
+ epi.triangulate_points(P2, P1, x1, x2, solver=solver),
+ epi.triangulate_points(P1, P2, x2, x1, solver=solver),
+ ):
+ assert (wrong - X).norm(dim=-1).min() > 1.0
+ results[solver] = out
+ # svd and eigh agree to roundoff on this well-conditioned fixture.
+ self.assert_close(results["svd"], results["eigh"], rtol=0.0, atol=atol)
+
+ def test_convention_triangulate_points_unchecked_cheirality_and_baseline(self, device, dtype):
+ two_view = two_view_scene(device, dtype)
+ P1, P2, K2, R, t, X = (two_view[k] for k in ("P1", "P2", "K2", "R", "t", "X"))
+
+ def project(P: torch.Tensor, Y: torch.Tensor) -> torch.Tensor:
+ return _dehom(torch.cat([Y, torch.ones_like(Y[..., :1])], -1) @ P.transpose(-2, -1))
+
+ for solver in SOLVERS:
+ if solver == "cofactor" and dtype == torch.float16:
+ continue # the cofactor solver returns NaN for pixel-scale float16 input (#4863)
+ # A point behind both cameras is returned, not rejected: its depth is negative in both. The fixture
+ # points, in front, are the control.
+ front = epi.triangulate_points(P1, P2, two_view["x1"], two_view["x2"], solver=solver)
+ assert (front[..., 2] > 0).all()
+ assert (epi.depth_from_point(R, t, front) > 0).all()
+ behind = epi.triangulate_points(P1, P2, project(P1, -X), project(P2, -X), solver=solver)
+ assert (behind[..., 2] < 0).all()
+ assert (epi.depth_from_point(R, t, behind) < 0).all()
+ # Zero baseline raises nothing: svd and eigh return a finite point on the line of sight. Both cameras sit at
+ # C, away from the world origin, so that a solver collapsing to the origin cannot pass; the line of sight
+ # through X + C is the ray from C in the direction X. (cofactor is the #4900 wart pinned below.)
+ C = torch.tensor([[[1.0], [2.0], [-3.0]]], device=device, dtype=dtype)
+ P1_C = epi.projection_from_KRt(two_view["K1"], torch.eye(3, device=device, dtype=dtype)[None], -C)
+ P2_C = epi.projection_from_KRt(K2, R, -R @ C)
+ X_C = X + C.transpose(-2, -1)
+ for solver in ("svd", "eigh"):
+ out = epi.triangulate_points(P1_C, P2_C, project(P1_C, X_C), project(P2_C, X_C), solver=solver)
+ assert torch.isfinite(out).all()
+ # float64 on the CPU: MPS has no float64
+ v, X64 = (out - C.transpose(-2, -1)).cpu().double(), X.cpu().double()
+ assert (torch.linalg.cross(v, X64, dim=-1).norm(dim=-1) / X64.norm(dim=-1)).max() <= _OFF_RAY_TOL[dtype]
+ assert (v.norm(dim=-1) / X64.norm(dim=-1)).min() > 1e-3 # not the centre itself
+
+ def test_wart_triangulate_points_infinity_finite_4865(self, device, dtype):
+ two_view = two_view_scene(device, dtype)
+ # #4865: a correspondence at infinity (the images of a direction (x, y, z, 0)) comes back as a finite point
+ # along that direction, with nothing to tell it from a real point: its distance is set by roundoff in the
+ # homogeneous w (on this fixture it is finite in every dtype).
+ P1, P2, d = two_view["P1"], two_view["P2"], two_view["X"] # the fixture points read as directions
+ x1 = _dehom(d @ P1[..., :3].transpose(-2, -1))
+ x2 = _dehom(d @ P2[..., :3].transpose(-2, -1))
+ for solver in SOLVERS:
+ if solver == "cofactor" and dtype == torch.float16:
+ continue # the cofactor solver returns NaN for pixel-scale float16 input (#4863)
+ out = epi.triangulate_points(P1, P2, x1, x2, solver=solver)
+ assert torch.isfinite(out).all()
+ out64, d64 = out.cpu().double(), d.cpu().double() # float64 on the CPU: MPS has no float64
+ cos = (out64 * d64).sum(-1) / (out64.norm(dim=-1) * d64.norm(dim=-1))
+ assert cos.abs().min() > 0.999 # swapping the cameras or the points gives 0.975
+
+ def test_wart_triangulate_cofactor_float16_nan_4863(self, device, dtype):
+ two_view = two_view_scene(device, dtype)
+ if dtype != torch.float16:
+ pytest.skip("the overflow is float16's: bfloat16, float32 and float64 hold the unnormalised null vector")
+ # #4863: the cofactor null vector of pixel-scale rows is computed in float32 but cast back to float16 before
+ # it is normalised, overflows to inf, and every point comes back NaN. svd and eigh are finite on the same input.
+ P1, P2, x1, x2 = two_view["P1"], two_view["P2"], two_view["x1"], two_view["x2"]
+ out = epi.triangulate_points(P1, P2, x1, x2, solver="cofactor")
+ assert out.dtype == torch.float16
+ assert torch.isnan(out).all()
+ for solver in ("svd", "eigh"):
+ assert torch.isfinite(epi.triangulate_points(P1, P2, x1, x2, solver=solver)).all()
+
+ def test_wart_triangulate_cofactor_rank_deficient_4900(self, device, dtype):
+ two_view = two_view_scene(device, dtype)
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("float16 is #4863; in bfloat16 the rows' roundoff leaves the sub-systems full rank")
+ # #4900: when a 3x4 sub-system of the DLT matrix is rank-deficient, the cofactor null vector is roundoff
+ # normalised to unit length, and the point is unrelated to the input; when it is nearly rank-deficient, the
+ # noise takes the place of the roundoff. svd is the control on the same input.
+ K1, K2, R, X = two_view["K1"], two_view["K2"], two_view["R"], two_view["X"]
+ eye = torch.eye(3, device=device, dtype=dtype)[None]
+
+ def project(P: torch.Tensor, Y: torch.Tensor) -> torch.Tensor:
+ return _dehom(torch.cat([Y, torch.ones_like(Y[..., :1])], -1) @ P.transpose(-2, -1))
+
+ # Zero baseline: both cameras at C. The answer is any point on the ray from C in the direction X.
+ C = torch.tensor([[[1.0], [2.0], [-3.0]]], device=device, dtype=dtype)
+ P1, P2 = epi.projection_from_KRt(K1, eye, -C), epi.projection_from_KRt(K2, R, -R @ C)
+ x1, x2 = project(P1, X + C.transpose(-2, -1)), project(P2, X + C.transpose(-2, -1))
+ X64 = X.cpu().double() # float64 on the CPU: MPS has no float64
+ off_ray = {}
+ for solver in ("svd", "cofactor"):
+ v = (epi.triangulate_points(P1, P2, x1, x2, solver=solver) - C.transpose(-2, -1)).cpu().double()
+ off_ray[solver] = (torch.linalg.cross(v, X64, dim=-1).norm(dim=-1) / X64.norm(dim=-1)).max()
+ assert off_ray["svd"] <= 1e-2
+ assert off_ray["cofactor"] > 1.0
+ # A noise-free pure x translation with R = I and one K: y1 == y2 exactly, so DLT rows 1 and 3 coincide.
+ P1, P2 = (
+ epi.projection_from_KRt(K1, eye, torch.zeros_like(C)),
+ epi.projection_from_KRt(K1, eye, -0.5 * eye[:, :, :1]),
+ )
+ x1, x2 = project(P1, X), project(P2, X)
+ assert torch.equal(x1[..., 1], x2[..., 1])
+ err = {
+ s: (epi.triangulate_points(P1, P2, x1, x2, solver=s) - X).norm(dim=-1).max() for s in ("svd", "cofactor")
+ }
+ assert err["svd"] <= _TRIANGULATION_ATOL[dtype]
+ assert err["cofactor"] > 1.0
+ # The same rectified pair with 0.5 px of noise: the rows no longer coincide but stay nearly dependent, so
+ # dropping only an exactly rank-deficient sub-system does not fix it. svd stays within 0.1.
+ g = torch.Generator().manual_seed(0)
+ n1, n2 = (0.5 * torch.randn(x1.shape, generator=g, dtype=torch.float64).to(device, dtype) for _ in range(2))
+ err = {
+ s: (epi.triangulate_points(P1, P2, x1 + n1, x2 + n2, solver=s) - X).norm(dim=-1).max()
+ for s in ("svd", "cofactor")
+ }
+ assert err["svd"] <= 0.25
+ assert err["cofactor"] > 1.0