π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(epipolar): rotation for every scale of P, NaN at infinity, robust cofactor solver (#4901)
Dmytro Mishkin3a8d24cf4d69
diff --git a/changelog.d/4889.added.md b/changelog.d/4889.added.mdindex c34c42362..5858708ce 100644--- a/changelog.d/4889.added.md+++ b/changelog.d/4889.added.md@@ -1 +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.+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 #4263 wart is documented and linked, not fixed; #4863, #4864, #4865 and #4900 are fixed by #4901.diff --git a/changelog.d/4901.fixed.md b/changelog.d/4901.fixed.mdnew file mode 100644index 000000000..4db881e06--- /dev/null+++ b/changelog.d/4901.fixed.md@@ -0,0 +1 @@+`KRt_from_projection` returns a proper rotation and the same `K`, `R`, `t` for every nonzero scale of `P`, including `-P` and a `P` scaled below the old `eps`, which is now unused (#4864). `triangulate_points` returns NaN for a correspondence at infinity instead of a finite point at a roundoff-set distance (#4865); `solver="cofactor"` normalises in the compute dtype, so pixel-scale float16 input is finite (#4863), and returns the `svd` point instead of averaging two normalised sub-system null vectors: it refines the longest of the four through the adjugate of the DLT matrix. The average was up to 3.5 units off on a noise-free rectified pair and 144 on a pair rolled by 90 degrees, 3 to 6 units off on every point of a rectified, vertical or rolled pair with 0.5 px of noise (0.1 for `svd`), and a roundoff direction for zero baseline, which now gives NaN (#4900).diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex 9fac7ba53..e58c95b9f 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -508,8 +508,8 @@ normalised camera coordinates, and :func:`~kornia.geometry.homography.find_homogkornia's, so a candidate index does not port; ``recoverPose`` selects the same pose and also returns theinlier count* - projection matrix- - ``KRt_from_projection`` returns the translation ``t`` of ``P = K [R | t]``; for ``det P[:, :3] < 0`` it- returns a reflection (`#4864 <https://github.com/kornia/kornia/issues/4864>`_)+ - ``KRt_from_projection`` returns the translation ``t`` of ``P = K [R | t]``; ``P`` and ``-P`` give the same+ positive-diagonal ``K``, rotation ``R`` and ``t``- ``decomposeProjectionMatrix`` returns the homogeneous camera centre :math:`C = -R^\top t`; for``det P[:, :3] < 0`` it keeps ``det R = 1`` and returns ``K[2, 2] < 0``* - triangulationdiff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.pyindex da9582378..f77dfe764 100644--- a/kornia/geometry/epipolar/projection.py+++ b/kornia/geometry/epipolar/projection.py@@ -156,25 +156,22 @@ def projection_from_KRt(K: torch.Tensor, R: torch.Tensor, t: torch.Tensor) -> todef KRt_from_projection(P: torch.Tensor, eps: float = 1e-6) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:- r"""Decompose the Projection matrix into ``K``, ``R`` and ``t`` with :math:`P = K [R|t]`.+ r"""Decompose the Projection matrix into ``K``, ``R`` and ``t`` with :math:`K [R|t] = \pm P`.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.+ - Inverse of :func:`projection_from_KRt`: returns ``K`` (upper triangular, positive diagonal), a+ rotation ``R`` (``det R = 1``) and the translation ``t``, not the camera centre;+ :ref:`Two-view geometry <two-view-conventions>` maps this onto OpenCV.+ - ``P`` is defined up to a nonzero scale, sign included: ``s * P`` gives the same ``R`` and ``t`` for+ every nonzero ``s`` and ``|s| * K``. So :math:`K [R|t]` is ``P`` when ``P[:, :3, :3]`` has positive+ determinant and ``-P`` when it has negative determinant (``-P`` gives the factors of ``P``). ``K`` is+ not normalised to ``K[2, 2] = 1``; 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: offset added to the diagonal of the triangular factor before its sign is taken.+ eps: unused; kept for backward compatibility. The sign of the triangular factor's diagonal is taken+ exactly.Returns:- The Camera matrix with shape :math:`(B, 3, 3)`.@@ -193,15 +190,23 @@ def KRt_from_projection(P: torch.Tensor, eps: float = 1e-6) -> Tuple[torch.Tensoortho_mat = torch.matmul(reverse, ortho_mat.permute(0, 2, 1))upper_mat = torch.matmul(reverse, torch.matmul(upper_mat.permute(0, 2, 1), reverse))- # Turning the `upper_mat's` diagonal elements to positive.- diagonals = torch.diagonal(upper_mat, dim1=-2, dim2=-1) + eps- signs = torch.sign(diagonals)+ # Turning the `upper_mat's` diagonal elements to positive (a zero entry keeps its sign: rank-deficient P).+ diagonals = torch.diagonal(upper_mat, dim1=-2, dim2=-1)+ signs = torch.where(diagonals < 0, -torch.ones_like(diagonals), torch.ones_like(diagonals))signs_mat = torch.diag_embed(signs)K = torch.matmul(upper_mat, signs_mat)R = torch.matmul(signs_mat, ortho_mat)t = torch.linalg.solve(K, last_column)+ # P and -P are the same camera. With a positive-diagonal K, a left block of negative determinant leaves+ # det R = -1; negating R and t decomposes -P instead, so R is a rotation. The sign comes from the orthogonal+ # factor, whose determinant is +-1 at any scale of P, not from det(P[:, :3, :3]), which scales as s**3 and+ # underflows to -0.0 for a small negative s.+ flip = torch.linalg.det(R)[:, None, None] < 0+ R = torch.where(flip, -R, R)+ t = torch.where(flip, -t, t)+return K, R, tdiff --git a/kornia/geometry/epipolar/triangulation.py b/kornia/geometry/epipolar/triangulation.pyindex 276b4c1e7..8bf8654e4 100644--- a/kornia/geometry/epipolar/triangulation.py+++ b/kornia/geometry/epipolar/triangulation.py@@ -24,7 +24,6 @@ import torchfrom kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.core.utils import _normalize_to_float32_or_float64, _torch_svd_cast, is_mps_tensor_safefrom kornia.geometry.conversions import convert_points_from_homogeneous-from kornia.geometry.solvers import null_vector_3x4# https://github.com/opencv/opencv_contrib/blob/master/modules/sfm/src/triangulation.cpp#L68@@ -56,6 +55,44 @@ def _eigh_smallest_vec(M: torch.Tensor) -> torch.Tensor:return torch.cat(parts, dim=0)+def _sub_system_null_vectors(A: torch.Tensor) -> torch.Tensor:+ r"""Return the null vectors of the four :math:`3 \times 4` sub-systems of each :math:`4 \times 4` matrix.++ Row ``j`` of the result is orthogonal to every row of ``A`` but row ``3 - j`` (sub-systems ``{0, 1, 2}``,+ ``{0, 1, 3}``, ``{0, 2, 3}``, ``{1, 2, 3}``); up to sign it is the column of the adjugate of ``A`` for the+ row left out, the vector of :math:`3 \times 3` minors that :func:`~kornia.geometry.solvers.null_vector_3x4`+ returns. The minors are expanded along the ``2 x 2`` minors of the row pairs ``(0, 1)`` and ``(2, 3)``, which+ all four share: the Hodge dual of one pair's bivector applied to each row of the other pair. These are the+ columns of :func:`kornia.core._small_linalg._adjugate_4x4` in fewer, wider kernels, about half its time for a+ million matrices on the CPU and on MPS.++ Args:+ A: batch of matrices, shape ``(*, 4, 4)``.++ Returns:+ The four null vectors, shape ``(*, 4, 4)``, not normalised: a sub-system of rank below 3 gives zero.+ """+ P = A[..., 0::2, None, :] # rows 0 and 2, (*, 2, 1, 4)+ Q = A[..., 1::2, None, :] # rows 1 and 3++ def minor(p: int, q: int) -> torch.Tensor:+ return P[..., p] * Q[..., q] - P[..., q] * Q[..., p] # (*, 2, 1)++ s01, s02, s03, s12, s13, s23 = minor(0, 1), minor(0, 2), minor(0, 3), minor(1, 2), minor(1, 3), minor(2, 3)+ # The bivector of rows (0, 1) meets rows 2 and 3; that of rows (2, 3) meets rows 0 and 1.+ x0, x1, x2, x3 = torch.stack([A[..., 2:, :], A[..., :2, :]], dim=-3).unbind(-1) # each (*, 2, 2)+ h = torch.stack(+ [+ s23 * x1 - s13 * x2 + s12 * x3,+ -s23 * x0 + s03 * x2 - s02 * x3,+ s13 * x0 - s03 * x1 + s01 * x3,+ -s12 * x0 + s02 * x1 - s01 * x2,+ ],+ dim=-1,+ ) # (*, 2, 2, 4)+ return h.flatten(-3, -2)++def triangulate_points(P1: torch.Tensor,P2: torch.Tensor,@@ -76,17 +113,15 @@ def triangulate_points(:ref:`Two-view geometry <two-view-conventions>` maps this onto OpenCV. The leadingdimensions 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>`_).+ zero baseline the depth is undefined: ``"svd"`` and ``"eigh"`` return an arbitrary point on the line of+ sight, possibly behind the camera or at infinity (NaN), and ``"cofactor"`` returns NaN.+ - A correspondence at infinity, whose homogeneous ``w`` is at the roundoff of the input and compute dtypes,+ returns NaN. In float16 and bfloat16 that roundoff also covers a point a few tens of units away in the+ scale of ``t``. Mask those rows before a loss (``out[~out.isnan().any(-1)]``); the gradients with respect+ to the cameras and the other points stay finite.+ - ``"svd"`` and ``"eigh"`` solve in float64, or in float32 for float16 and bfloat16 input and on MPS;+ ``"cofactor"`` solves in float32, or in float64 for float64 input. All return the input dtype;+ ``solver`` below compares their accuracy.Args:P1: The projection matrix for the first camera with shape :math:`(*, 3, 4)`.@@ -107,13 +142,16 @@ def triangulate_points(rows, such as a baseline much shorter than the depth, it loses accuracy that``"svd"`` keeps. Typically **10-26xfaster** 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 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.+ * ``"cofactor"`` β closed form, no LAPACK call. The null vectors of the four+ :math:`3 \times 4` sub-systems (the cofactors, as in+ :func:`~kornia.geometry.solvers.null_vector_3x4`) form the adjugate of the+ DLT matrix; the longest one, refined by one step of inverse iteration through+ the adjugate, gives the ``"svd"`` point to roundoff without noise and nearly+ the same point with noise, also for rectified and vertical stereo pairs, where+ a sub-system is nearly rank-deficient. When the noise is comparable to the+ parallax, so that the DLT point itself is far off, one step does not converge+ and the two can differ. The point is NaN when every sub-system is+ rank-deficient (zero baseline). Fastest option for large batches.Returns:The reconstructed 3d points in the world frame with shape :math:`(*, N, 3)`.@@ -143,6 +181,15 @@ def triangulate_points(# Unify N1 and N2: one may be 1 when points1/points2 are broadcast-compatible.row0, row1, row2, row3 = torch.broadcast_tensors(row0, row1, row2, row3)+ # svd and eigh mirror _torch_svd_cast's promotion: fp32 -> fp64 for stability, fp16/bf16 -> fp32, fp64+ # stays, MPS capped at fp32 (no fp64 support there). cofactor uses arithmetic only and keeps fp32.+ if is_mps_tensor_safe(row0):+ compute_dtype = torch.float32+ elif row0.dtype == torch.float32:+ compute_dtype = torch.float64+ else:+ compute_dtype = _normalize_to_float32_or_float64(row0.dtype)+if solver == "svd":X = torch.stack([row0, row1, row2, row3], dim=-2) # (*, N, 4, 4)# SVD: last right singular vector minimises ||Ax|| s.t. ||x||=1.@@ -162,15 +209,6 @@ def triangulate_points(# which is fine for homogeneous coordinates.# The approach is valid in both the noise-free (rank-3) and the noisy# inconsistent case, where the rows do not share an exact nullspace.- # Mirror _torch_svd_cast's promotion rules so numerical behaviour is- # comparable to the "svd" solver: fp32 β fp64 for stability, fp16/bf16 β- # fp32, fp64 stays, MPS capped at fp32 (no fp64 support there).- if is_mps_tensor_safe(X):- compute_dtype = torch.float32- elif X.dtype == torch.float32:- compute_dtype = torch.float64- else:- compute_dtype = _normalize_to_float32_or_float64(X.dtype)batch_shape = X.shape[:-2] # (*, N)X_cast = X.to(compute_dtype)XTX = X_cast.mT @ X_cast # (*, N, 4, 4) symmetric PSD@@ -179,40 +217,47 @@ def triangulate_points(points3d_h = v_flat.reshape(*batch_shape, 4) # (*, N, 4)elif solver == "cofactor":- # Solve two 3x4 sub-systems analytically via cofactor expansion and- # average the sign-aligned normalised results. This matches the full- # DLT solution when the constraint system is exactly consistent- # (noise-free), but is only an approximation in the noisy case.- # null_vector_3x4 uses only arithmetic ops, so promote fp16/bf16 β fp32.+ # The null vectors of the four 3x4 sub-systems (each DLT row left out once) are, up to sign, the columns+ # of adj(A) = det(A) A^-1 = det(A) V S^-1 U^T. Each leans towards the DLT solution v4 (the svd one), and+ # all are parallel to it when A has rank 3 (noise-free). With noise, a sub-system whose three rows are+ # nearly dependent (a rectified or vertical stereo pair, a camera rolled by 90 degrees, a row through the+ # epipole) has a null vector set by the noise, and no fixed choice or average of two of them avoids it.+ # So take the longest one and apply one step of inverse iteration with+ # adj(A) adj(A)^T = det(A)^2 (A^T A)^-1, which suppresses v3 against v4 by a further (s4 / s3)^2: the+ # svd solution without a LAPACK call, still defined at rank 3, where A^-1 is not.+ # The minors use only arithmetic ops, so promote fp16/bf16 -> fp32 and stay there until the null vector+ # is normalised: the unnormalised minors of pixel-scale rows overflow float16.compute_dtype = _normalize_to_float32_or_float64(row0.dtype)- r0 = row0.to(compute_dtype)- r1 = row1.to(compute_dtype)- r2 = row2.to(compute_dtype)- r3 = row3.to(compute_dtype)- # Both sub-systems include row2 (from camera 2's x-projection equation),- # which carries the camera-2 translation and is therefore well-conditioned- # for any camera pair with a non-zero baseline in x. Using rows {0,1,2}- # and {1,2,3} rather than {0,1,2} and {0,1,3} avoids the degenerate case- # that arises when camera 2 has zero last-column entries in its y- and- # z-projection rows (e.g. [R|t] with t = (-T,0,0)).- A_012 = torch.stack([r0, r1, r2], dim=-2) # (*, N, 3, 4)- A_123 = torch.stack([r1, r2, r3], dim=-2) # (*, N, 3, 4)- h_012 = null_vector_3x4(A_012).to(row0.dtype) # (*, N, 4)- h_123 = null_vector_3x4(A_123).to(row0.dtype) # (*, N, 4)- n012 = h_012.norm(dim=-1, keepdim=True).clamp(min=1e-8)- n123 = h_123.norm(dim=-1, keepdim=True).clamp(min=1e-8)- v012 = h_012 / n012- v123 = h_123 / n123- # Null vectors are defined up to a global sign; align signs before- # averaging in homogeneous space to prevent cancellation when the two- # sub-system solutions point in opposite directions (which would yield a- # near-zero homogeneous vector and NaN after dehomogenisation).- dot = (v012 * v123).sum(dim=-1, keepdim=True)- v123 = torch.where(dot < 0, -v123, v123)- points3d_h = v012 + v123 # (*, N, 4)+ tiny = torch.finfo(compute_dtype).tiny+ A = torch.stack([row0, row1, row2, row3], dim=-2).to(compute_dtype) # (*, N, 4, 4)+ # A common scale of the rows leaves the solution unchanged and keeps the cubic minors in range.+ row_norms = A.norm(dim=-1) # (*, N, 4)+ scale = row_norms.amax(dim=-1, keepdim=True).clamp_min(tiny)+ A, row_norms = A / scale[..., None], row_norms / scale+ H = _sub_system_null_vectors(A) # (*, N, 4, 4); row j leaves out DLT row 3 - j+ # A sub-system of rank below 3 has minors at roundoff, and every one has when A has rank 2 (zero+ # baseline): judge each against the product of its row norms, and return NaN when none has full rank.+ h_norms = H.norm(dim=-1) # (*, N, 4)+ sub_row_norms = row_norms.prod(dim=-1, keepdim=True) / row_norms.flip(-1).clamp_min(tiny)+ full_rank = (h_norms > 8.0 * torch.finfo(compute_dtype).eps * sub_row_norms).any(dim=-1, keepdim=True)+ longest = h_norms.argmax(dim=-1, keepdim=True)[..., None].expand(*H.shape[:-2], 1, 4)+ c = H.gather(-2, longest).squeeze(-2) / h_norms.amax(dim=-1, keepdim=True).clamp_min(tiny)+ w = (H @ c[..., None]).squeeze(-1) # adj(A)^T c, up to the signs of its entries+ w = w / w.norm(dim=-1, keepdim=True).clamp_min(tiny)+ v = (H.mT @ w[..., None]).squeeze(-1) # adj(A) adj(A)^T c: the signs cancel+ v = v / v.norm(dim=-1, keepdim=True).clamp_min(tiny)+ points3d_h = torch.where(full_rank, v, torch.full_like(v, float("nan"))).to(row0.dtype)else:raise NotImplementedError(f"Unknown solver '{solver}'. Choose from: 'svd', 'eigh', 'cofactor'.")+ # A correspondence at infinity (parallel rays) has w = 0 up to roundoff: the rows carry the input dtype's+ # roundoff and the solver the compute dtype's, which eigh amplifies by squaring the conditioning (about 25+ # epsilons on the two-view fixture against 2 for svd). Flag it as NaN instead of dividing by that roundoff.+ w_scale = 128.0 if solver == "eigh" else 16.0+ w_tol = w_scale * torch.finfo(compute_dtype).eps + 4.0 * torch.finfo(points3d_h.dtype).eps+ at_infinity = points3d_h[..., 3:].abs() <= w_tol * points3d_h.norm(dim=-1, keepdim=True)+ points3d_h = torch.where(at_infinity, torch.full_like(points3d_h, float("nan")), points3d_h)+points3d: torch.Tensor = convert_points_from_homogeneous(points3d_h)return points3ddiff --git a/tests/geometry/epipolar/test_projection.py b/tests/geometry/epipolar/test_projection.pyindex 0d4108a61..b79f05b04 100644--- a/tests/geometry/epipolar/test_projection.py+++ b/tests/geometry/epipolar/test_projection.py@@ -187,13 +187,15 @@ class TestKRtFromProjection(BaseTester):dtype=dtype,)+ # This P has a negative-determinant left block, so it is -K [R | t] for the camera below: R is a rotation+ # (det +1) and t its translation; the reflection -R with -t that the decomposition used to return is #4864.R_expected = torch.tensor(- [[[0.396559, 0.511023, -0.762625], [0.743249, -0.666318, -0.060006], [0.538815, 0.543024, 0.644052]]],+ [[[-0.396559, -0.511023, 0.762625], [-0.743249, 0.666318, 0.060006], [-0.538815, -0.543024, -0.644052]]],device=device,dtype=dtype,)- t_expected = torch.tensor([[[-6.477699], [1.129624], [0.143123]]], device=device, dtype=dtype)+ t_expected = torch.tensor([[[6.477699], [-1.129624], [-0.143123]]], device=device, dtype=dtype)K_estimated, R_estimated, t_estimated = epi.KRt_from_projection(P)self.assert_close(K_estimated, K_expected, atol=1e-4, rtol=1e-4)@@ -397,32 +399,35 @@ class TestConventionProjection(BaseTester):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):+ def test_convention_krt_from_projection_scale_and_sign_of_P(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)+ P, K_true, R_true, t_true = two_view["P2"], two_view["K2"], two_view["R"], two_view["t"]+ ones = torch.ones(1, device=device, dtype=dtype)+ # s * P is the same camera for every nonzero s, sign included: R stays a rotation, t the translation, and+ # K carries |s|. -P and a scale below the former eps = 1e-6 used to return a reflection (#4864). The+ # smallest negative scale makes det(s * P[:, :3, :3]), which scales as s**3, underflow to -0.0, so the sign+ # cannot be read from it. The small scales run on the CPU only: the MPS QR of a matrix with entries near+ # 1e-5 is off by a factor.+ tiny = {torch.float32: -1e-17, torch.float64: -1e-110}[dtype]+ scales = (-1.0, 2.0) + ((1e-7, -1e-7, tiny) if device.type == "cpu" else ())+ for s in scales:+ K, R, t = epi.KRt_from_projection(s * P)+ assert (K.diagonal(dim1=-2, dim2=-1) > 0).all()+ self.assert_close(_det3(R), ones)+ self.assert_close(R, R_true)+ self.assert_close(t, t_true)+ self.assert_close(K[:, 2, 2], torch.full_like(K[:, 2, 2], abs(s)))+ self.assert_close(K / K[..., 2:, 2:], K_true, rtol=1e-4, atol=1e-3)+ # A negative focal length also gives a negative-determinant left block: R is still a rotation, and+ # K [R | t] reproduces P up to its sign.+ K_neg = K_true.clone()+ K_neg[:, 0, 0] = -K_neg[:, 0, 0]+ P_neg = epi.projection_from_KRt(K_neg, R_true, t_true)+ K, R, t = epi.KRt_from_projection(P_neg)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])+ self.assert_close(_det3(R), ones)+ self.assert_close(epi.projection_from_KRt(K, R, t), -P_neg, rtol=1e-4, atol=1e-3)def test_wart_scale_intrinsics_principal_point_rule_4263(self, device, dtype):# #4263: the same rule as PinholeCamera.scale, pinned there bydiff --git a/tests/geometry/epipolar/test_triangulation.py b/tests/geometry/epipolar/test_triangulation.pyindex 706d9b3fd..84dc28429 100644--- a/tests/geometry/epipolar/test_triangulation.py+++ b/tests/geometry/epipolar/test_triangulation.py@@ -16,6 +16,7 @@#import functools+import mathfrom typing import Dictimport pytest@@ -23,6 +24,7 @@ import torchimport korniaimport kornia.geometry.epipolar as epi+from kornia.geometry.conversions import axis_angle_to_rotation_matrixfrom testing.base import BaseTesterfrom testing.two_view import two_view_scene@@ -335,8 +337,11 @@ def _dehom(x: torch.Tensor) -> torch.Tensor:# 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).+# roundoff; a point off the line, such as a roundoff direction normalised to unit length, is at 9 or more)._OFF_RAY_TOL = {torch.float16: 2e-2, torch.bfloat16: 0.3, torch.float32: 1e-2, torch.float64: 1e-2}+# Distance, in the scale of t (|t| = 0.5), at which a point still reads as finite: the rows' roundoff puts a point+# beyond a few tens of units at infinity in half precision.+_FAR_BUT_FINITE = {torch.float16: 20.0, torch.bfloat16: 8.0, torch.float32: 1e4, torch.float64: 1e6}class TestConventionTriangulation(BaseTester):@@ -371,8 +376,6 @@ class TestConventionTriangulation(BaseTester):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)@@ -381,58 +384,83 @@ class TestConventionTriangulation(BaseTester):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.)+ # Zero baseline raises nothing: svd and eigh return a point on the line of sight, or NaN when their arbitrary+ # choice in the 2-D null space lands at infinity (one bfloat16 point here), and cofactor NaN (every 3x4+ # sub-system is rank-deficient). 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.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()+ finite = torch.isfinite(out).all(-1)+ assert finite.sum() >= 10 # of 12: the line-of-sight check below is not vacuous# float64 on the CPU: MPS has no float64- v, X64 = (out - C.transpose(-2, -1)).cpu().double(), X.cpu().double()+ finite = finite.cpu()+ v, X64 = (out - C.transpose(-2, -1)).cpu().double()[finite], X.cpu().double()[finite]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+ if dtype in (torch.float32, torch.float64): # in half precision the rows' roundoff leaves the rank+ out = epi.triangulate_points(P1_C, P2_C, project(P1_C, X_C), project(P2_C, X_C), solver="cofactor")+ assert torch.isnan(out).all()- def test_wart_triangulate_points_infinity_finite_4865(self, device, dtype):+ def test_convention_triangulate_points_infinity_is_nan(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).+ # A correspondence at infinity (the images of a direction (x, y, z, 0)) has a homogeneous w at roundoff+ # and comes back as NaN, in every solver and dtype; it used to be a finite point at a roundoff-set+ # distance. The fixture points, at depth 4 to 6, and points a few tens of units away are the control.P1, P2, d = two_view["P1"], two_view["P2"], two_view["X"] # the fixture points read as directionsx1 = _dehom(d @ P1[..., :3].transpose(-2, -1))x2 = _dehom(d @ P2[..., :3].transpose(-2, -1))+ far = _FAR_BUT_FINITE[dtype] * d / d.norm(dim=-1, keepdim=True)+ far_h = torch.cat([far, torch.ones_like(far[..., :1])], -1)+ x1_far, x2_far = _dehom(far_h @ P1.transpose(-2, -1)), _dehom(far_h @ P2.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+ assert torch.isnan(epi.triangulate_points(P1, P2, x1, x2, solver=solver)).all()+ assert torch.isfinite(epi.triangulate_points(P1, P2, two_view["x1"], two_view["x2"], solver=solver)).all()+ assert torch.isfinite(epi.triangulate_points(P1, P2, x1_far, x2_far, solver=solver)).all()- def test_wart_triangulate_cofactor_float16_nan_4863(self, device, dtype):+ def test_convention_triangulate_points_masked_infinity_keeps_gradients_finite(self, device, dtype):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("the gradient check of the NaN mask runs in float32 and float64")+ two_view = two_view_scene(device, dtype)+ # A point at infinity is NaN, but masking its row before the loss leaves every gradient finite, including+ # the cameras' gradients, which sum over all rows: the NaN is substituted, not produced by the solve.+ P1, P2, d = two_view["P1"], two_view["P2"], two_view["X"]+ x1_inf = _dehom(d[..., :1, :] @ P1[..., :3].transpose(-2, -1))+ x2_inf = _dehom(d[..., :1, :] @ P2[..., :3].transpose(-2, -1))+ for solver in SOLVERS:+ p1, p2 = P1.clone().requires_grad_(), P2.clone().requires_grad_()+ x1 = torch.cat([two_view["x1"], x1_inf], -2).requires_grad_()+ x2 = torch.cat([two_view["x2"], x2_inf], -2).requires_grad_()+ out = epi.triangulate_points(p1, p2, x1, x2, solver=solver)+ finite = ~out.isnan().any(-1)+ assert not finite[..., -1].any() and finite[..., :-1].all()+ for grad in torch.autograd.grad(out[finite].sum(), (p1, p2, x1, x2)):+ assert torch.isfinite(grad).all()++ def test_convention_triangulate_cofactor_half_precision_is_finite(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"]+ if dtype not in (torch.float16, torch.bfloat16):+ pytest.skip("the half-precision overflow of the unnormalised cofactor null vector")+ # The cofactor null vector of pixel-scale rows is normalised in float32 before the cast back to the input+ # dtype; cast first, it overflowed float16 and every point was NaN. bfloat16 keeps float32's exponent range+ # but only 8 bits of mantissa, hence its looser bound.+ P1, P2, x1, x2, X = (two_view[k] for k in ("P1", "P2", "x1", "x2", "X"))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()+ assert out.dtype == dtype+ assert torch.isfinite(out).all()+ self.assert_close(out, X, rtol=0.0, atol={torch.float16: 5e-2, torch.bfloat16: 1.0}[dtype])- def test_wart_triangulate_cofactor_rank_deficient_4900(self, device, dtype):+ def test_convention_triangulate_cofactor_rank_deficient_sub_system(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.+ pytest.skip("in half precision the rows' roundoff leaves the sub-systems full rank")+ # A 3x4 sub-system of the DLT matrix that is rank-deficient, or nearly so with noise, has a null vector set+ # by roundoff or noise; cofactor used to average a fixed pair of them after normalising (#4900). It now+ # refines the longest sub-system null vector through the adjugate and returns the svd point: NaN when every+ # sub-system is rank-deficient (zero baseline), and svd's point for a rectified, vertical or rolled pair.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]@@ -444,31 +472,29 @@ class TestConventionTriangulation(BaseTester):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.+ v = (epi.triangulate_points(P1, P2, x1, x2, solver="svd") - C.transpose(-2, -1)).cpu().double()+ assert (torch.linalg.cross(v, X64, dim=-1).norm(dim=-1) / X64.norm(dim=-1)).max() <= 1e-2+ assert torch.isnan(epi.triangulate_points(P1, P2, x1, x2, solver="cofactor")).all()+ # One K, R = I and a pure x (rectified) or y (vertical) translation: DLT rows 1 and 3 (0 and 2) coincide+ # without noise, so sub-system {1, 2, 3} ({0, 1, 2}) is rank-deficient. Camera 2 rolled by 90 degrees+ # about its axis with an x baseline makes rows 1 and 2 coincide, so {0, 1, 2} and {1, 2, 3} both are.+ # With 0.5 px of noise the rows stay nearly dependent; the old average was 5 to 6 units off on every+ # point of all three pairs and NaN on every point of the exact rolled pair.+ roll = axis_angle_to_rotation_matrix(torch.tensor([[0.0, 0.0, math.pi / 2]], device=device, dtype=dtype))+ b = 0.5 * eye[:, :, :1]+ pairs = {"rectified": (eye, -b), "vertical": (eye, -0.5 * eye[:, :, 1:2]), "rolled": (roll, -roll @ b)}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+ noise = [0.5 * torch.randn(X.shape[:-1] + (2,), generator=g, dtype=torch.float64) for _ in range(2)]+ n1, n2 = (n.to(device, dtype) for n in noise)+ for name, (R2, t2) in pairs.items():+ P1, P2 = epi.projection_from_KRt(K1, eye, torch.zeros_like(C)), epi.projection_from_KRt(K1, R2, t2)+ x1, x2 = project(P1, X), project(P2, X)+ if name == "rectified":+ assert torch.equal(x1[..., 1], x2[..., 1])+ for solver in ("svd", "cofactor"):+ out = epi.triangulate_points(P1, P2, x1, x2, solver=solver)+ assert (out - X).norm(dim=-1).max() <= _TRIANGULATION_ATOL[dtype], (name, solver)+ svd = epi.triangulate_points(P1, P2, x1 + n1, x2 + n2, solver="svd")+ cofactor = epi.triangulate_points(P1, P2, x1 + n1, x2 + n2, solver="cofactor")+ assert (svd - X).norm(dim=-1).max() <= 0.25, name+ assert (cofactor - svd).norm(dim=-1).max() <= 1e-4, name