Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

More fixes for triangulate and docs (#3661)

Dmytro Mishkin915b6b47cdb8
diff --git a/CLAUDE.md b/CLAUDE.md
index a53dd6e19..30b7d4c8e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -122,6 +122,8 @@ Scripts under `benchmarks/` measure the speed and/or quality of existing kornia
Install hooks with `pre-commit install`. CI enforces ruff formatting, linting, and docformatter.
+**Always run `pixi run lint` before pushing** to catch ruff errors (formatting, style, ambiguous Unicode characters, etc.) that will cause CI to fail. Fix any reported issues before committing.
+
## Documentation and Visualizations
**Every public class or function added to a `kornia/` submodule must also be listed in the corresponding `docs/source/*.rst` file** β€” otherwise it will not appear in the rendered docs. Check the relevant `.rst` after adding any public API symbol and add an `.. autoclass::` or `.. autofunction::` directive if it is missing.
diff --git a/docs/source/geometry.solvers.rst b/docs/source/geometry.solvers.rst
index 29ead344e..841a57091 100644
--- a/docs/source/geometry.solvers.rst
+++ b/docs/source/geometry.solvers.rst
@@ -9,6 +9,11 @@ kornia.geometry.solvers
Module containing various geometrical solvers/optimizers.
+Homogeneous Solvers
+-------------------
+
+.. autofunction:: null_vector_3x4
+
Polynomial Solvers
------------------
diff --git a/docs/source/references.bib b/docs/source/references.bib
index 466c0b81e..2c083dfeb 100644
--- a/docs/source/references.bib
+++ b/docs/source/references.bib
@@ -1,4 +1,14 @@
+@article{zhao2023aliked,
+ author={Zhao, Xiaoming and Wu, Xingming and Chen, Weihai and Chen, Peter C. Y. and Xu, Qingsong and Li, Zhengguo},
+ journal={IEEE Transactions on Instrumentation and Measurement},
+ title={ALIKED: A Lighter Keypoint and Descriptor Extraction Network via Deformable Transformation},
+ year={2023},
+ volume={72},
+ pages={1-16},
+ doi={10.1109/TIM.2023.3271000},
+}
+
@article{dosovitskiy2020vit,
title={An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale},
author={Dosovitskiy, Alexey and Beyer, Lucas and Kolesnikov, Alexander and Weissenborn, Dirk and Zhai, Xiaohua and Unterthiner, Thomas and Dehghani, Mostafa and Minderer, Matthias and Heigold, Georg and Gelly, Sylvain and Uszkoreit, Jakob and Houlsby, Neil},
diff --git a/kornia/geometry/epipolar/triangulation.py b/kornia/geometry/epipolar/triangulation.py
index 867ca96e6..872f58202 100644
--- a/kornia/geometry/epipolar/triangulation.py
+++ b/kornia/geometry/epipolar/triangulation.py
@@ -152,29 +152,44 @@ def triangulate_points(
else:
compute_dtype = _normalize_to_float32_or_float64(X.dtype)
batch_shape = X.shape[:-2] # (*, N)
- XTX = X.to(compute_dtype).mT @ X.to(compute_dtype) # (*, N, 4, 4) symmetric PSD
+ X_cast = X.to(compute_dtype)
+ XTX = X_cast.mT @ X_cast # (*, N, 4, 4) symmetric PSD
flat = XTX.flatten(0, -3) # (M, 4, 4)
v_flat = _eigh_smallest_vec(flat).to(X.dtype) # (M, 4)
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 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 inconsistent case.
+ # 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.
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_013 = torch.stack([r0, r1, r3], 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_013 = null_vector_3x4(A_013).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)
- n013 = h_013.norm(dim=-1, keepdim=True).clamp(min=1e-8)
- points3d_h = h_012 / n012 + h_013 / n013 # (*, N, 4)
+ 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)
else:
raise NotImplementedError(f"Unknown solver '{solver}'. Choose from: 'svd', 'eigh', 'cofactor'.")
diff --git a/kornia/geometry/solvers/homogeneous.py b/kornia/geometry/solvers/homogeneous.py
index 2126ef83c..c2a38f6ec 100644
--- a/kornia/geometry/solvers/homogeneous.py
+++ b/kornia/geometry/solvers/homogeneous.py
@@ -21,7 +21,7 @@ from __future__ import annotations
import torch
-from kornia.core.check import KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
def _det3(
@@ -100,8 +100,8 @@ def null_vector_3x4(A: torch.Tensor) -> torch.Tensor:
Null vector of shape :math:`(*, 4)`.
Raises:
- TypeError: if ``A`` is not a tensor.
- ValueError: if the last two dimensions of ``A`` are not ``(3, 4)``.
+ TypeCheckError: if ``A`` is not a :class:`torch.Tensor`.
+ ShapeError: if the last two dimensions of ``A`` are not ``(3, 4)``.
Example:
>>> A = torch.tensor([[[1., 0., 0., 0.],
@@ -112,6 +112,7 @@ def null_vector_3x4(A: torch.Tensor) -> torch.Tensor:
tensor([[0., 0., 0.]])
"""
+ KORNIA_CHECK_IS_TENSOR(A)
KORNIA_CHECK_SHAPE(A, ["*", "3", "4"])
a = A[..., 0, :] # (*, 4)
diff --git a/tests/geometry/epipolar/test_triangulation.py b/tests/geometry/epipolar/test_triangulation.py
index 710d55f54..744181543 100644
--- a/tests/geometry/epipolar/test_triangulation.py
+++ b/tests/geometry/epipolar/test_triangulation.py
@@ -40,6 +40,14 @@ def _make_scene(device, dtype, num_views: int = 2, num_points: int = 10):
return {k: v.to(device=device, dtype=dtype) for k, v in scene.items()}
+def _project(P: torch.Tensor, X: torch.Tensor) -> torch.Tensor:
+ """Project (B, N, 3) points through a (B, 3, 4) camera matrix β†’ (B, N, 2)."""
+ B, N = X.shape[:2]
+ Xh = torch.cat([X, torch.ones(B, N, 1, device=X.device, dtype=X.dtype)], dim=-1)
+ px = (P @ Xh.mT).mT
+ return px[..., :2] / px[..., 2:3]
+
+
class TestTriangulation(BaseTester):
# ------------------------------------------------------------------
# Smoke β€” verify all three solvers produce the right output shape
@@ -126,13 +134,8 @@ class TestTriangulation(BaseTester):
[0.0, 0.0, 3.0], device=device, dtype=dtype
)
- def project(P, X):
- Xh = torch.cat([X, torch.ones(B, N, 1, device=device, dtype=dtype)], dim=-1)
- px = (P @ Xh.mT).mT
- return px[..., :2] / px[..., 2:3]
-
- pts1 = project(P1, X_true)
- pts2 = project(P2, X_true)
+ pts1 = _project(P1, X_true)
+ pts2 = _project(P2, X_true)
results = {s: epi.triangulate_points(P1, P2, pts1, pts2, solver=s) for s in SOLVERS}
@@ -143,6 +146,53 @@ class TestTriangulation(BaseTester):
atol = {torch.float16: 1e-2, torch.bfloat16: 1e-2, torch.float32: 1e-3}.get(dtype, 1e-6)
self.assert_close(cos.abs(), torch.ones_like(cos), atol=atol, rtol=0.0)
+ # ------------------------------------------------------------------
+ # Cofactor sign-alignment regression
+ # ------------------------------------------------------------------
+
+ def test_cofactor_sign_alignment(self, device, dtype):
+ """Cofactor solver must not produce NaN/Inf due to sign cancellation.
+
+ Before the sign-alignment fix, the two 3x4 sub-systems could yield
+ opposite-signed null vectors whose sum cancelled to ~0, producing NaN
+ after dehomogenisation. This test constructs a noise-free two-view
+ scene with a modest baseline, triangulates with both the cofactor and
+ SVD solvers, and checks that the cofactor output is finite and
+ directionally consistent with the SVD result.
+ """
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("cofactor sign test only runs for float32/float64")
+
+ torch.manual_seed(3)
+ B, N = 1, 8
+
+ P1 = torch.eye(3, 4, device=device, dtype=dtype).unsqueeze(0).expand(B, -1, -1)
+ R2 = torch.tensor(
+ [[0.9998, -0.0175, 0.0], [0.0175, 0.9998, 0.0], [0.0, 0.0, 1.0]],
+ device=device,
+ dtype=dtype,
+ )
+ t2 = torch.tensor([[-1.0], [0.0], [0.0]], device=device, dtype=dtype)
+ P2 = torch.cat([R2, t2], dim=-1).unsqueeze(0).expand(B, -1, -1)
+
+ X_true = torch.rand(B, N, 3, device=device, dtype=dtype) + torch.tensor(
+ [0.0, 0.0, 3.0], device=device, dtype=dtype
+ )
+
+ pts1 = _project(P1, X_true)
+ pts2 = _project(P2, X_true)
+
+ X_cofactor = epi.triangulate_points(P1, P2, pts1, pts2, solver="cofactor")
+ X_svd = epi.triangulate_points(P1, P2, pts1, pts2, solver="svd")
+
+ # Output must be finite β€” NaN would indicate the pre-fix cancellation bug.
+ assert torch.isfinite(X_cofactor).all(), "cofactor solver produced non-finite values"
+
+ # Numerical closeness to SVD (noise-free β†’ both solvers recover the same 3-D point).
+ # This also catches incorrect scale/depth, unlike a direction-only check.
+ atol = 1e-3 if dtype == torch.float32 else 1e-6
+ self.assert_close(X_cofactor, X_svd, atol=atol, rtol=0.0)
+
# ------------------------------------------------------------------
# Gradcheck β€” default solver
# ------------------------------------------------------------------