Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

More speed opts (#3660)

Dmytro Mishkin90209959ce13
diff --git a/CLAUDE.md b/CLAUDE.md
index 8844fe43e..a53dd6e19 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -124,7 +124,10 @@ Install hooks with `pre-commit install`. CI enforces ruff formatting, linting, a
## 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.
+
When adding a new feature detector or descriptor to `kornia/feature/`:
+- Add an `.. autoclass::` entry to `docs/source/feature.rst` in the appropriate section (Detectors, Descriptors, or Local Features).
- Add an entry to the `responses` list in `docs/generate_examples.py` with a corresponding `elif` block that produces a heatmap/score visualization (`(B, 3, H, W)` BGR image in `img_in`, `(B, 3, H, W)` response map in `out`).
- See existing entries (`DISK`, `ALIKED`, `XFeat`) for the expected pattern.
@@ -137,4 +140,32 @@ All PRs must:
**Comments**: No redundant or ghost comments (e.g., "this returns the input tensor", or comments explaining deleted code). Violation triggers mandatory manual rewrite request.
+## Test-First Debugging
+
+**Always run the relevant tests before answering a question about a bug or test failure.**
+Do not assume a failure is pre-existing or unrelated to recent changes without running it:
+
+```bash
+# Run the failing test(s) first, then investigate
+pixi run -e default uv run pytest <failing_test_file> -q --dtype=float32,float64
+```
+
+If the test passes on the current branch, verify on `main` with `git stash` before concluding it is pre-existing.
+
+## Hardcoded Reference Values in Tests
+
+**Never use `pytest.importorskip` to gate correctness tests on optional third-party libraries** (OpenCV, scipy, etc.). Instead, compute the expected output once offline and embed it as a hardcoded tensor literal, following the pattern used in `tests/geometry/epipolar/test_fundamental.py`:
+
+```python
+# Snippet used to generate expected (requires numpy only):
+# import numpy as np
+# ... run the reference algorithm ...
+# expected = result # <-- print and paste below
+
+expected = torch.tensor([[...]], dtype=dtype, device=device)
+self.assert_close(actual, expected, atol=1e-4, rtol=1e-4)
+```
+
+Leave a comment above the literal showing the generation snippet so it can be reproduced. This makes tests self-contained, deterministic, and runnable without optional dependencies.
+
See `AI_POLICY.md` for the full contribution policy, including AI usage disclosure requirements.
diff --git a/benchmarks/geometry/linalg_epipolar_distort.py b/benchmarks/geometry/linalg_epipolar_distort.py
new file mode 100644
index 000000000..e42b7f583
--- /dev/null
+++ b/benchmarks/geometry/linalg_epipolar_distort.py
@@ -0,0 +1,203 @@
+# 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.
+#
+"""Benchmark for linalg, epipolar projection/triangulation, and calibration distortion functions.
+
+Usage:
+ python benchmarks/geometry/linalg_epipolar_distort.py
+ python benchmarks/geometry/linalg_epipolar_distort.py --cuda
+"""
+
+from __future__ import annotations
+
+import argparse
+import datetime
+import platform
+import shutil
+import subprocess
+import time
+
+import torch
+
+from kornia.geometry.calibration.distort import distort_points, tilt_projection
+from kornia.geometry.epipolar.projection import (
+ KRt_from_projection,
+ depth_from_point,
+ projection_from_KRt,
+ projections_from_fundamental,
+ scale_intrinsics,
+)
+from kornia.geometry.epipolar.triangulation import triangulate_points
+from kornia.geometry.linalg import (
+ batched_dot_product,
+ compose_transformations,
+ euclidean_distance,
+ inverse_transformation,
+ point_line_distance,
+ relative_transformation,
+ transform_points,
+)
+
+# ─────────────────────────────────────────────────────────────────────────────
+# Helpers
+# ─────────────────────────────────────────────────────────────────────────────
+
+
+def _sync(device: str) -> None:
+ if device == "cuda":
+ torch.cuda.synchronize()
+
+
+def bench(fn, *args, warmup: int = 10, reps: int = 50, device: str = "cpu", label: str = "") -> float:
+ for _ in range(warmup):
+ fn(*args)
+ _sync(device)
+ t0 = time.perf_counter()
+ for _ in range(reps):
+ fn(*args)
+ _sync(device)
+ ms = (time.perf_counter() - t0) / reps * 1000
+ print(f" {label:<60s}: {ms:8.4f} ms")
+ return ms
+
+
+def _print_env() -> None:
+ date = datetime.datetime.now(tz=datetime.UTC).strftime("%Y-%m-%d %H:%M:%S UTC")
+ git = shutil.which("git") or "git"
+ try:
+ commit = subprocess.check_output([git, "rev-parse", "--short", "HEAD"], text=True).strip()
+ except Exception:
+ commit = "unknown"
+ cpu = platform.processor() or platform.machine()
+ print(f" date : {date}")
+ print(f" commit : {commit}")
+ print(f" cpu : {cpu}")
+ if torch.cuda.is_available():
+ print(f" gpu : {torch.cuda.get_device_name(0)}")
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# Benchmarks
+# ─────────────────────────────────────────────────────────────────────────────
+
+
+def bench_linalg(device: str) -> None:
+ print(f"\n--- linalg device={device} ---")
+
+ configs = [
+ ("B=1 ", 1),
+ ("B=16 ", 16),
+ ("B=256", 256),
+ ]
+
+ for label, B in configs:
+ T = torch.eye(4, device=device).unsqueeze(0).expand(B, -1, -1).contiguous()
+ pts = torch.rand(B, 1000, 3, device=device)
+ pts_flat = torch.rand(B, 1000, 4, device=device)
+ lines = torch.rand(B, 1000, 3, device=device)
+ x = torch.rand(B, 1000, 8, device=device)
+ y = torch.rand(B, 1000, 8, device=device)
+
+ print(f"\n {label}")
+ bench(compose_transformations, T, T, device=device, label="compose_transformations")
+ bench(inverse_transformation, T, device=device, label="inverse_transformation")
+ bench(relative_transformation, T, T, device=device, label="relative_transformation")
+ bench(transform_points, T, pts, device=device, label="transform_points")
+ bench(point_line_distance, pts_flat[..., :3], lines, device=device, label="point_line_distance")
+ bench(batched_dot_product, x, y, device=device, label="batched_dot_product")
+ bench(euclidean_distance, x, y, device=device, label="euclidean_distance")
+
+
+def bench_epipolar(device: str) -> None:
+ print(f"\n--- epipolar projection / triangulation device={device} ---")
+
+ configs = [
+ ("B=1 N=100 ", 1, 100),
+ ("B=8 N=1K ", 8, 1000),
+ ("B=32 N=1K ", 32, 1000),
+ ]
+
+ K_base = torch.eye(3, device=device)
+ K_base[0, 0] = K_base[1, 1] = 500.0
+ K_base[0, 2] = K_base[1, 2] = 320.0
+
+ for label, B, N in configs:
+ K = K_base.unsqueeze(0).expand(B, -1, -1).contiguous()
+ R = torch.eye(3, device=device).unsqueeze(0).expand(B, -1, -1).contiguous()
+ t = torch.zeros(B, 3, 1, device=device)
+ X = torch.rand(B, N, 3, device=device).add_(1.0)
+ P1 = torch.cat([R, t], dim=-1) # B x 3 x 4
+ P2 = torch.cat([R, t + 0.1], dim=-1)
+ pts1 = torch.rand(B, N, 2, device=device)
+ pts2 = torch.rand(B, N, 2, device=device)
+ F = torch.rand(B, 3, 3, device=device)
+ P_proj = torch.rand(B, 3, 4, device=device)
+
+ print(f"\n {label}")
+ bench(projection_from_KRt, K, R, t, device=device, label="projection_from_KRt")
+ bench(scale_intrinsics, K, 2.0, device=device, label="scale_intrinsics")
+ bench(depth_from_point, R, t, X, device=device, label="depth_from_point")
+ bench(projections_from_fundamental, F, device=device, label="projections_from_fundamental")
+ bench(triangulate_points, P1, P2, pts1, pts2, device=device, label="triangulate_points")
+ bench(KRt_from_projection, P_proj, device=device, label="KRt_from_projection")
+
+
+def bench_distort(device: str) -> None:
+ print(f"\n--- calibration distortion device={device} ---")
+
+ K_base = torch.eye(3, device=device)
+ K_base[0, 0] = K_base[1, 1] = 500.0
+ K_base[0, 2] = K_base[1, 2] = 320.0
+ dist_base = torch.tensor([0.1, -0.05, 0.001, 0.001, 0.02, 0.01, -0.005, 0.002], device=device)
+
+ configs = [
+ ("B=1 N=1K ", 1, 1_000),
+ ("B=1 N=100K", 1, 100_000),
+ ("B=32 N=10K ", 32, 10_000),
+ ]
+
+ for label, B, N in configs:
+ K_b = K_base.unsqueeze(0).expand(B, -1, -1).contiguous()
+ dist_b = dist_base.unsqueeze(0).expand(B, -1).contiguous()
+ pts2 = torch.rand(B, N, 2, device=device).mul_(640.0)
+ taux = torch.zeros(B, device=device)
+ tauy = torch.zeros(B, device=device)
+
+ print(f"\n {label}")
+ bench(distort_points, pts2, K_b, dist_b, device=device, label="distort_points")
+ bench(tilt_projection, taux, tauy, device=device, label="tilt_projection")
+
+
+def run(device: str) -> None:
+ sep = "=" * 72
+ print(f"\n{sep}\n DEVICE: {device.upper()}\n{sep}")
+ bench_linalg(device)
+ bench_epipolar(device)
+ bench_distort(device)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--cuda", action="store_true")
+ args = parser.parse_args()
+
+ _print_env()
+ run("cpu")
+ if args.cuda:
+ if torch.cuda.is_available():
+ run("cuda")
+ else:
+ print("\nWarning: --cuda requested but CUDA is not available.")
diff --git a/docs/source/feature.rst b/docs/source/feature.rst
index c28db500a..070117c0a 100644
--- a/docs/source/feature.rst
+++ b/docs/source/feature.rst
@@ -159,12 +159,28 @@ Local Features (Detector and Descriptors together)
.. autoclass:: SOLD2_detector
:members: forward
+.. autoclass:: ALIKED
+ :members: forward, from_pretrained, forward_laf
+
+.. autoclass:: ALIKEDFeatures
+ :undoc-members:
+ :members: n, to
+
.. autoclass:: DeDoDe
:members: forward, from_pretrained, describe, detect
.. autoclass:: DISK
:members: forward, from_pretrained, heatmap_and_dense_descriptors
+.. autoclass:: XFeat
+ :members: forward, from_pretrained, detectAndCompute, detectAndComputeDense, match_xfeat, match_xfeat_star
+
+.. autoclass:: XFeatModel
+ :members: forward
+
+.. autoclass:: InterpolateSparse2d
+ :members: forward
+
.. autoclass:: DISKFeatures
:undoc-members:
:members: x, y, to
diff --git a/kornia/geometry/calibration/distort.py b/kornia/geometry/calibration/distort.py
index 57757cd9f..e0383f000 100644
--- a/kornia/geometry/calibration/distort.py
+++ b/kornia/geometry/calibration/distort.py
@@ -133,23 +133,25 @@ def distort_points(
# Distort points
r2 = x * x + y * y
+ r4 = r2 * r2
+ r6 = r4 * r2
- rad_poly = (1 + dist[..., 0:1] * r2 + dist[..., 1:2] * r2 * r2 + dist[..., 4:5] * r2**3) / (
- 1 + dist[..., 5:6] * r2 + dist[..., 6:7] * r2 * r2 + dist[..., 7:8] * r2**3
+ rad_poly = (1 + dist[..., 0:1] * r2 + dist[..., 1:2] * r4 + dist[..., 4:5] * r6) / (
+ 1 + dist[..., 5:6] * r2 + dist[..., 6:7] * r4 + dist[..., 7:8] * r6
)
xd = (
x * rad_poly
+ 2 * dist[..., 2:3] * x * y
+ dist[..., 3:4] * (r2 + 2 * x * x)
+ dist[..., 8:9] * r2
- + dist[..., 9:10] * r2 * r2
+ + dist[..., 9:10] * r4
)
yd = (
y * rad_poly
+ dist[..., 2:3] * (r2 + 2 * y * y)
+ 2 * dist[..., 3:4] * x * y
+ dist[..., 10:11] * r2
- + dist[..., 11:12] * r2 * r2
+ + dist[..., 11:12] * r4
)
# Compensate for tilt distortion
diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.py
index 241596f17..580f8e61d 100644
--- a/kornia/geometry/epipolar/projection.py
+++ b/kornia/geometry/epipolar/projection.py
@@ -159,7 +159,7 @@ def KRt_from_projection(P: torch.Tensor, eps: float = 1e-6) -> Tuple[torch.Tenso
K = torch.matmul(upper_mat, signs_mat)
R = torch.matmul(signs_mat, ortho_mat)
- t = torch.matmul(torch.inverse(K), last_column)
+ t = torch.linalg.solve(K, last_column)
return K, R, t
diff --git a/kornia/geometry/epipolar/triangulation.py b/kornia/geometry/epipolar/triangulation.py
index ac5bfce58..867ca96e6 100644
--- a/kornia/geometry/epipolar/triangulation.py
+++ b/kornia/geometry/epipolar/triangulation.py
@@ -17,22 +17,56 @@
"""Module with the functionalities for triangulation."""
+from __future__ import annotations
+
import torch
from kornia.core.check import KORNIA_CHECK_SHAPE
-from kornia.core.utils import _torch_svd_cast
+from kornia.core.utils import _normalize_to_float32_or_float64, _torch_svd_cast, is_mps_tensor_safe
from 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
+# cuSOLVER's batched symmetric eigenvalue solver crashes above this many 4x4 matrices
+# in a single call (empirically observed at >=32 K on current CUDA/PyTorch versions).
+_CUSOLVER_EIGH_BATCH_LIMIT: int = 28_000
+
+
+def _eigh_smallest_vec(M: torch.Tensor) -> torch.Tensor:
+ """Return the eigenvector for the smallest eigenvalue of each symmetric matrix.
+
+ Handles cuSOLVER's batch-size limit by chunking when necessary.
+
+ Args:
+ M: batch of symmetric PSD matrices, shape ``(N, k, k)``.
+
+ Returns:
+ Eigenvectors of shape ``(N, k)``.
+ """
+ N = M.shape[0]
+ if N <= _CUSOLVER_EIGH_BATCH_LIMIT:
+ _, V = torch.linalg.eigh(M)
+ return V[..., 0]
+
+ parts = [
+ torch.linalg.eigh(M[i : i + _CUSOLVER_EIGH_BATCH_LIMIT])[1][..., 0]
+ for i in range(0, N, _CUSOLVER_EIGH_BATCH_LIMIT)
+ ]
+ return torch.cat(parts, dim=0)
+
def triangulate_points(
- P1: torch.Tensor, P2: torch.Tensor, points1: torch.Tensor, points2: torch.Tensor
+ P1: torch.Tensor,
+ P2: torch.Tensor,
+ points1: torch.Tensor,
+ points2: torch.Tensor,
+ solver: str = "eigh",
) -> torch.Tensor:
r"""Reconstructs a bunch of points by triangulation.
Triangulates the 3d position of 2d correspondences between several images.
- Reference: Internally it uses DLT method from Hartley/Zisserman 12.2 pag.312
+ 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.
@@ -44,31 +78,106 @@ def triangulate_points(
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)`.
+ 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
+ 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
+ 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
+ inconsistent case. Fastest option for all batch sizes.
Returns:
The reconstructed 3d points in the world frame with shape :math:`(*, N, 3)`.
+ Example:
+ >>> P1 = torch.eye(3, 4)[None] # 1x3x4
+ >>> P2 = torch.eye(3, 4)[None]
+ >>> pts1 = torch.rand(1, 5, 2)
+ >>> pts2 = torch.rand(1, 5, 2)
+ >>> pts3d = triangulate_points(P1, P2, pts1, pts2)
+ >>> pts3d.shape
+ torch.Size([1, 5, 3])
+
"""
KORNIA_CHECK_SHAPE(P1, ["*", "3", "4"])
KORNIA_CHECK_SHAPE(P2, ["*", "3", "4"])
KORNIA_CHECK_SHAPE(points1, ["*", "N", "2"])
KORNIA_CHECK_SHAPE(points2, ["*", "N", "2"])
- # allocate and construct the equations matrix with shape (*, 4, 4)
- points_shape = max(points1.shape, points2.shape) # this allows broadcasting
- X = torch.zeros(points_shape[:-1] + (4, 4)).type_as(points1)
-
- for i in range(4):
- X[..., 0, i] = points1[..., 0] * P1[..., 2:3, i] - P1[..., 0:1, i]
- X[..., 1, i] = points1[..., 1] * P1[..., 2:3, i] - P1[..., 1:2, i]
- X[..., 2, i] = points2[..., 0] * P2[..., 2:3, i] - P2[..., 0:1, i]
- X[..., 3, i] = points2[..., 1] * P2[..., 2:3, i] - P2[..., 1:2, i]
-
- # 1. Solve the system Ax=0 with smallest eigenvalue
- # 2. Return homogeneous coordinates
-
- _, _, V = _torch_svd_cast(X)
+ # Build the four DLT constraint rows (each (*, N, 4)) via vectorized broadcasting.
+ # P[..., r:r+1, :] broadcasts with points[..., c:c+1] β†’ (*, N, 4).
+ row0 = points1[..., 0:1] * P1[..., 2:3, :] - P1[..., 0:1, :] # (*, N1, 4)
+ row1 = points1[..., 1:2] * P1[..., 2:3, :] - P1[..., 1:2, :] # (*, N1, 4)
+ row2 = points2[..., 0:1] * P2[..., 2:3, :] - P2[..., 0:1, :] # (*, N2, 4)
+ row3 = points2[..., 1:2] * P2[..., 2:3, :] - P2[..., 1:2, :] # (*, N2, 4)
+ # 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)
+
+ 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.
+ # _torch_svd_cast promotes to fp64 for numerical stability and returns V
+ # with singular vectors as columns; the last column corresponds to the
+ # smallest singular value.
+ _, _, V = _torch_svd_cast(X)
+ points3d_h = V[..., -1] # (*, N, 4)
+
+ elif solver == "eigh":
+ X = torch.stack([row0, row1, row2, row3], dim=-2) # (*, N, 4, 4)
+ # Solve the homogeneous least-squares problem min ||Ax|| s.t. ||x||=1.
+ # The minimiser is the eigenvector of X^T X associated with its smallest
+ # eigenvalue. This is algebraically equivalent to the last right singular
+ # vector of X used in SVD-based DLT, though forming X^T X can be less
+ # numerically stable than a direct SVD. The result is defined up to sign,
+ # 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)
+ XTX = X.to(compute_dtype).mT @ X.to(compute_dtype) # (*, 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.
+ # 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)
+ A_012 = torch.stack([r0, r1, r2], dim=-2) # (*, N, 3, 4)
+ A_013 = torch.stack([r0, r1, 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)
+ 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)
+
+ else:
+ raise NotImplementedError(f"Unknown solver '{solver}'. Choose from: 'svd', 'eigh', 'cofactor'.")
- points3d_h = V[..., -1]
points3d: torch.Tensor = convert_points_from_homogeneous(points3d_h)
return points3d
diff --git a/kornia/geometry/solvers/__init__.py b/kornia/geometry/solvers/__init__.py
index 09ce29815..641c1fbad 100644
--- a/kornia/geometry/solvers/__init__.py
+++ b/kornia/geometry/solvers/__init__.py
@@ -20,6 +20,7 @@
This subpackage provides polynomial solvers and related utilities for geometry tasks.
"""
+from .homogeneous import null_vector_3x4
from .polynomial_solver import (
determinant_to_polynomial,
multiply_deg_one_poly,
@@ -33,6 +34,7 @@ __all__ = [
"determinant_to_polynomial",
"multiply_deg_one_poly",
"multiply_deg_two_one_poly",
+ "null_vector_3x4",
"solve_cubic",
"solve_quadratic",
"solve_quartic",
diff --git a/kornia/geometry/solvers/homogeneous.py b/kornia/geometry/solvers/homogeneous.py
new file mode 100644
index 000000000..2126ef83c
--- /dev/null
+++ b/kornia/geometry/solvers/homogeneous.py
@@ -0,0 +1,167 @@
+# 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.
+#
+
+"""Closed-form solvers for homogeneous linear systems."""
+
+from __future__ import annotations
+
+import torch
+
+from kornia.core.check import KORNIA_CHECK_SHAPE
+
+
+def _det3(
+ a0: torch.Tensor,
+ a1: torch.Tensor,
+ a2: torch.Tensor,
+ b0: torch.Tensor,
+ b1: torch.Tensor,
+ b2: torch.Tensor,
+ c0: torch.Tensor,
+ c1: torch.Tensor,
+ c2: torch.Tensor,
+) -> torch.Tensor:
+ """Compute a batch of 3x3 determinants via Sarrus' rule.
+
+ Given three rows (each split into their three scalar components), returns::
+
+ | a0 a1 a2 |
+ | b0 b1 b2 |
+ | c0 c1 c2 |
+
+ All inputs must be broadcastable to the same shape.
+
+ Args:
+ a0: first element of the first row.
+ a1: second element of the first row.
+ a2: third element of the first row.
+ b0: first element of the second row.
+ b1: second element of the second row.
+ b2: third element of the second row.
+ c0: first element of the third row.
+ c1: second element of the third row.
+ c2: third element of the third row.
+
+ Returns:
+ Scalar determinant (or batch of scalars) with the broadcasted shape.
+ """
+ return a0 * (b1 * c2 - b2 * c1) - a1 * (b0 * c2 - b2 * c0) + a2 * (b0 * c1 - b1 * c0)
+
+
+def null_vector_3x4(A: torch.Tensor) -> torch.Tensor:
+ r"""Return the null vector of a rank-3 matrix of shape :math:`(*, 3, 4)`.
+
+ The null vector :math:`\mathbf{v} \in \mathbb{R}^4` satisfies
+ :math:`A\,\mathbf{v} = \mathbf{0}`. For a matrix of rank 3 this solution
+ is unique up to scale.
+
+ The computation uses the **4-D cross-product** (cofactor expansion):
+ each component of :math:`\mathbf{v}` is a :math:`3 \times 3` determinant of
+ the submatrix obtained by dropping the corresponding column of :math:`A`.
+ This is equivalent to computing the last right singular vector of :math:`A`
+ via SVD but replaces the SVD with 48 scalar multiplications and 20
+ additions β€” no LAPACK or cuSOLVER call is made.
+
+ .. math::
+
+ v_j = (-1)^j \det\!\bigl(A_{[0,1,2],\,\widehat{j}}\bigr), \quad j = 0, 1, 2, 3
+
+ where :math:`A_{[0,1,2],\,\widehat{j}}` denotes the :math:`3 \times 3`
+ submatrix formed by deleting column :math:`j`.
+
+ .. note::
+
+ The returned vector is **not** normalised. Divide by its norm if a
+ unit null vector is required.
+
+ .. note::
+
+ The function is only correct when :math:`A` has rank exactly 3. For
+ rank-deficient inputs (rank < 3) the result is the zero vector.
+
+ Args:
+ A: matrix of shape :math:`(*, 3, 4)`.
+
+ Returns:
+ 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)``.
+
+ Example:
+ >>> A = torch.tensor([[[1., 0., 0., 0.],
+ ... [0., 1., 0., 0.],
+ ... [0., 0., 1., 0.]]]) # null vector is [0,0,0,1]
+ >>> v = null_vector_3x4(A) # shape (1, 4)
+ >>> (A @ v.unsqueeze(-1)).squeeze(-1) # should be near zero
+ tensor([[0., 0., 0.]])
+
+ """
+ KORNIA_CHECK_SHAPE(A, ["*", "3", "4"])
+
+ a = A[..., 0, :] # (*, 4)
+ b = A[..., 1, :] # (*, 4)
+ c = A[..., 2, :] # (*, 4)
+
+ # Each component of the null vector is a signed 3x3 cofactor determinant.
+ v0 = _det3(
+ a[..., 1],
+ a[..., 2],
+ a[..., 3],
+ b[..., 1],
+ b[..., 2],
+ b[..., 3],
+ c[..., 1],
+ c[..., 2],
+ c[..., 3],
+ )
+ v1 = -_det3(
+ a[..., 0],
+ a[..., 2],
+ a[..., 3],
+ b[..., 0],
+ b[..., 2],
+ b[..., 3],
+ c[..., 0],
+ c[..., 2],
+ c[..., 3],
+ )
+ v2 = _det3(
+ a[..., 0],
+ a[..., 1],
+ a[..., 3],
+ b[..., 0],
+ b[..., 1],
+ b[..., 3],
+ c[..., 0],
+ c[..., 1],
+ c[..., 3],
+ )
+ v3 = -_det3(
+ a[..., 0],
+ a[..., 1],
+ a[..., 2],
+ b[..., 0],
+ b[..., 1],
+ b[..., 2],
+ c[..., 0],
+ c[..., 1],
+ c[..., 2],
+ )
+
+ return torch.stack([v0, v1, v2, v3], dim=-1)
diff --git a/tests/geometry/epipolar/test_triangulation.py b/tests/geometry/epipolar/test_triangulation.py
index ae89a6dc4..710d55f54 100644
--- a/tests/geometry/epipolar/test_triangulation.py
+++ b/tests/geometry/epipolar/test_triangulation.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+import functools
from typing import Dict
import pytest
@@ -25,31 +26,69 @@ import kornia.geometry.epipolar as epi
from testing.base import BaseTester
+SOLVERS = ["svd", "eigh", "cofactor"]
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_scene(device, dtype, num_views: int = 2, num_points: int = 10):
+ """Return a consistent synthetic two-view scene in float64 then cast."""
+ scene: Dict[str, torch.Tensor] = epi.generate_scene(num_views, num_points)
+ return {k: v.to(device=device, dtype=dtype) for k, v in scene.items()}
+
class TestTriangulation(BaseTester):
- def test_smoke(self, device, dtype):
+ # ------------------------------------------------------------------
+ # Smoke β€” verify all three solvers produce the right output shape
+ # ------------------------------------------------------------------
+
+ @pytest.mark.parametrize("solver", SOLVERS)
+ def test_smoke(self, solver, device, dtype):
P1 = torch.rand(1, 3, 4, device=device, dtype=dtype)
P2 = torch.rand(1, 3, 4, device=device, dtype=dtype)
points1 = torch.rand(1, 1, 2, device=device, dtype=dtype)
points2 = torch.rand(1, 1, 2, device=device, dtype=dtype)
- points3d = epi.triangulate_points(P1, P2, points1, points2)
- assert points3d.shape == (1, 1, 3)
+ pts3d = epi.triangulate_points(P1, P2, points1, points2, solver=solver)
+ assert pts3d.shape == (1, 1, 3)
+
+ # ------------------------------------------------------------------
+ # Shape / cardinality
+ # ------------------------------------------------------------------
@pytest.mark.parametrize("batch_size, num_points", [(1, 3), (2, 4), (3, 5)])
- def test_shape(self, batch_size, num_points, device, dtype):
+ @pytest.mark.parametrize("solver", SOLVERS)
+ def test_shape(self, batch_size, num_points, solver, device, dtype):
B, N = batch_size, num_points
P1 = torch.rand(B, 3, 4, device=device, dtype=dtype)
P2 = torch.rand(1, 3, 4, device=device, dtype=dtype)
points1 = torch.rand(1, N, 2, device=device, dtype=dtype)
points2 = torch.rand(B, N, 2, device=device, dtype=dtype)
- points3d = epi.triangulate_points(P1, P2, points1, points2)
- assert points3d.shape == (B, N, 3)
+ pts3d = epi.triangulate_points(P1, P2, points1, points2, solver=solver)
+ assert pts3d.shape == (B, N, 3)
+
+ # ------------------------------------------------------------------
+ # Exception: unknown solver
+ # ------------------------------------------------------------------
+
+ def test_exception_unknown_solver(self, device, dtype):
+ P1 = torch.rand(1, 3, 4, device=device, dtype=dtype)
+ P2 = torch.rand(1, 3, 4, device=device, dtype=dtype)
+ pts = torch.rand(1, 4, 2, device=device, dtype=dtype)
+ with pytest.raises(NotImplementedError, match="Unknown solver"):
+ epi.triangulate_points(P1, P2, pts, pts, solver="unknown")
+
+ # ------------------------------------------------------------------
+ # Two-view accuracy on a noise-free synthetic scene
+ # ------------------------------------------------------------------
- @pytest.mark.xfail()
def test_two_view(self, device, dtype):
+ torch.manual_seed(0)
num_views: int = 2
num_points: int = 10
- scene: Dict[str, torch.Tensor] = epi.generate_scene(num_views, num_points)
+ scene = _make_scene(device, dtype, num_views, num_points)
P1 = scene["P"][0:1]
P2 = scene["P"][1:2]
@@ -59,8 +98,54 @@ class TestTriangulation(BaseTester):
X = epi.triangulate_points(P1, P2, x1, x2)
x_reprojected = kornia.geometry.transform_points(scene["P"], X.expand(num_views, -1, -1))
- self.assert_close(scene["points3d"], X, rtol=1e-4, atol=1e-4)
- self.assert_close(scene["points2d"], x_reprojected, rtol=1e-4, atol=1e-4)
+ atol = {torch.float16: 1e-2, torch.bfloat16: 0.25, torch.float32: 1e-4}.get(dtype, 1e-4)
+ self.assert_close(scene["points3d"], X, rtol=atol, atol=atol)
+ self.assert_close(scene["points2d"], x_reprojected, rtol=atol, atol=atol)
+
+ # ------------------------------------------------------------------
+ # All solvers produce collinear results for noise-free data
+ # ------------------------------------------------------------------
+
+ def test_solver_consistency(self, device, dtype):
+ """All three solvers should agree (up to sign) on noise-free data."""
+ torch.manual_seed(0)
+ B, N = 2, 20
+
+ # Build a pair of cameras and project known 3-D points.
+ 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([[-0.5], [0.0], [0.0]], device=device, dtype=dtype)
+
+ P1 = torch.eye(3, 4, device=device, dtype=dtype).unsqueeze(0).expand(B, -1, -1)
+ 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
+ )
+
+ 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)
+
+ results = {s: epi.triangulate_points(P1, P2, pts1, pts2, solver=s) for s in SOLVERS}
+
+ ref = results["svd"]
+ for _name, pts in results.items():
+ # Check that the recovered direction matches (cosine similarity β‰ˆ 1).
+ cos = (pts * ref).sum(-1) / (pts.norm(dim=-1).clamp(min=1e-8) * ref.norm(dim=-1).clamp(min=1e-8))
+ 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)
+
+ # ------------------------------------------------------------------
+ # Gradcheck β€” default solver
+ # ------------------------------------------------------------------
def test_gradcheck(self, device):
points1 = torch.rand(1, 8, 2, device=device, dtype=torch.float64, requires_grad=True)
@@ -70,3 +155,123 @@ class TestTriangulation(BaseTester):
P2 = kornia.core.ops.eye_like(3, points2)
P2 = torch.nn.functional.pad(P2, [0, 1])
assert self.gradcheck(epi.triangulate_points, (P1, P2, points1, points2), raise_exception=True, fast_mode=True)
+
+ @pytest.mark.parametrize("solver", SOLVERS)
+ def test_gradcheck_all_solvers(self, solver, device):
+ points1 = torch.rand(1, 4, 2, device=device, dtype=torch.float64, requires_grad=True)
+ points2 = torch.rand(1, 4, 2, device=device, dtype=torch.float64)
+ P1 = kornia.core.ops.eye_like(3, points1)
+ P1 = torch.nn.functional.pad(P1, [0, 1])
+ P2 = kornia.core.ops.eye_like(3, points2)
+ P2 = torch.nn.functional.pad(P2, [0, 1])
+ fn = functools.partial(epi.triangulate_points, solver=solver)
+ assert self.gradcheck(fn, (P1, P2, points1, points2), raise_exception=True, fast_mode=True)
+
+ # ------------------------------------------------------------------
+ # Noisy correspondences β€” compare against OpenCV DLT reference
+ # ------------------------------------------------------------------
+
+ @pytest.mark.parametrize("solver", ["svd", "eigh"])
+ def test_noisy_correspondences_dlt(self, solver, device, dtype):
+ """Triangulation from noisy correspondences matches the numpy DLT reference.
+
+ Two-view setup: camera 1 at [I|0], camera 2 with ~5.7-degree rotation and
+ 1-unit rightward translation, 8 points at depth 3-4, Gaussian noise sigma=0.05.
+
+ Expected output was pre-computed once with a point-by-point numpy SVD
+ implementation identical to ``cv2.triangulatePoints`` (seed 7).
+
+ # Snippet used to generate X_expected (requires numpy only):
+ # import numpy as np, torch
+ # torch.manual_seed(7)
+ # ... (see test body for the full scene construction)
+ # for i in range(N):
+ # A = np.array([pts1[0,i]*P1[2]-P1[0], pts1[1,i]*P1[2]-P1[1],
+ # pts2[0,i]*P2[2]-P2[0], pts2[1,i]*P2[2]-P2[1]])
+ # _, _, V = np.linalg.svd(A)
+ # X_expected[i] = V[-1, :3] / V[-1, 3]
+ """
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("noisy-correspondence test only runs for float32/float64")
+
+ # Hardcoded inputs (torch.manual_seed(7), noise sigma=0.05)
+ P1 = torch.tensor(
+ [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]],
+ dtype=dtype,
+ device=device,
+ )
+ P2 = torch.tensor(
+ [
+ [0.9950041770935059, 0.0, 0.0998334214091301, -1.0],
+ [0.0, 1.0, 0.0, 0.0],
+ [-0.0998334214091301, 0.0, 0.9950041770935059, 0.0],
+ ],
+ dtype=dtype,
+ device=device,
+ )
+ pts1 = torch.tensor(
+ [
+ [-0.024943894271020096, 0.023484865267389687],
+ [0.0284050326736405, 0.22463705371976522],
+ [0.05363684307356541, 0.1995784905718564],
+ [0.1202179211117687, -0.002082513366088421],
+ [-0.05603666748438946, -0.07320451037059378],
+ [0.2234642952593915, 0.03488261645314251],
+ [0.04132917198453165, 0.19063330422731778],
+ [0.07586561872234336, 0.12222851867867218],
+ ],
+ dtype=dtype,
+ device=device,
+ )
+ pts2 = torch.tensor(
+ [
+ [-0.2005761556307751, 0.08063633664743011],
+ [-0.05218266808824606, 0.09602012894912612],
+ [-0.14514520805453554, 0.11014017584343802],
+ [-0.14273667377657795, 0.051925094545445555],
+ [-0.2219682806714787, -0.09313464409688944],
+ [-0.061311792967568134, 0.04181839051261021],
+ [-0.1400088642080817, 0.12810430456996066],
+ [-0.16590968636404868, 0.08471239170067128],
+ ],
+ dtype=dtype,
+ device=device,
+ )
+ # Expected: numpy DLT (same algorithm as cv2.triangulatePoints)
+ X_expected = torch.tensor(
+ [
+ [-0.08818743120343768, 0.188334626330844, 3.6220817756133172],
+ [0.16144758240818913, 0.8807090389866558, 5.4844829932547015],
+ [0.18216324334542242, 0.517464929751309, 3.3477856439676588],
+ [0.3350949547897918, 0.06786420490996858, 2.770735605435314],
+ [-0.20989477003241103, -0.3123833872441908, 3.754403690255068],
+ [0.5852768065399436, 0.0989402354921456, 2.6188660940360844],
+ [0.1480216292032729, 0.5668535581804692, 3.5667031501090993],
+ [0.22379169128122922, 0.3033298174456883, 2.9457656267879586],
+ ],
+ dtype=dtype,
+ device=device,
+ )
+
+ X_kornia = epi.triangulate_points(
+ P1.unsqueeze(0),
+ P2.unsqueeze(0),
+ pts1.unsqueeze(0),
+ pts2.unsqueeze(0),
+ solver=solver,
+ ).squeeze(0)
+
+ atol = 1e-4 if dtype == torch.float64 else 1e-3
+ self.assert_close(X_kornia, X_expected, atol=atol, rtol=0.0)
+
+ # ------------------------------------------------------------------
+ # Module-level import check
+ # ------------------------------------------------------------------
+
+ def test_module(self, device, dtype):
+ assert hasattr(epi, "triangulate_points")
+ P1 = torch.rand(1, 3, 4, device=device, dtype=dtype)
+ P2 = torch.rand(1, 3, 4, device=device, dtype=dtype)
+ pts = torch.rand(1, 3, 2, device=device, dtype=dtype)
+ out = epi.triangulate_points(P1, P2, pts, pts)
+ assert out.shape == (1, 3, 3)
diff --git a/tests/geometry/solvers/test_homogeneous.py b/tests/geometry/solvers/test_homogeneous.py
new file mode 100644
index 000000000..5eb94b3f2
--- /dev/null
+++ b/tests/geometry/solvers/test_homogeneous.py
@@ -0,0 +1,248 @@
+# 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
+
+from kornia.geometry import solvers
+
+from testing.base import BaseTester
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_rank3_matrix(null_vec: torch.Tensor, device, dtype) -> torch.Tensor:
+ """Build a 3x4 matrix whose null space is spanned by *null_vec*.
+
+ Strategy: start from the 4x4 identity, set the last row to *null_vec* so
+ it becomes linearly dependent, then take the first three rows scaled by
+ small random factors. The result has rank 3 and its null vector is
+ proportional to *null_vec*.
+ """
+ # Build the 4x4 matrix whose columns span the orthogonal complement of null_vec.
+ # We use a Gram-Schmidt orthonormalisation relative to null_vec.
+ n = null_vec.to(device=device, dtype=torch.float64)
+ n = n / n.norm()
+
+ # Start from the standard basis and remove the component along n.
+ basis = torch.eye(4, device=device, dtype=torch.float64)
+ vecs = []
+ for i in range(4):
+ v = basis[i] - (basis[i] @ n) * n
+ if v.norm() > 1e-6:
+ # Orthogonalise against already accepted vectors.
+ for u in vecs:
+ v = v - (v @ u) * u
+ if v.norm() > 1e-6:
+ vecs.append(v / v.norm())
+ if len(vecs) == 3:
+ break
+
+ A = torch.stack(vecs, dim=0).to(dtype) # (3, 4)
+ return A.unsqueeze(0) # (1, 3, 4)
+
+
+class TestNullVector3x4(BaseTester):
+ # ------------------------------------------------------------------
+ # Smoke
+ # ------------------------------------------------------------------
+
+ def test_smoke(self, device, dtype):
+ A = torch.rand(1, 3, 4, device=device, dtype=dtype)
+ v = solvers.null_vector_3x4(A)
+ assert v.shape == (1, 4)
+
+ # ------------------------------------------------------------------
+ # Cardinality / shape
+ # ------------------------------------------------------------------
+
+ @pytest.mark.parametrize("batch", [1, 2, 4, 8])
+ def test_cardinality_batch(self, batch, device, dtype):
+ A = torch.rand(batch, 3, 4, device=device, dtype=dtype)
+ v = solvers.null_vector_3x4(A)
+ assert v.shape == (batch, 4)
+
+ @pytest.mark.parametrize("extra", [(2, 3), (5,)])
+ def test_cardinality_leading_dims(self, extra, device, dtype):
+ A = torch.rand(*extra, 3, 4, device=device, dtype=dtype)
+ v = solvers.null_vector_3x4(A)
+ assert v.shape == (*extra, 4)
+
+ def test_cardinality_unbatched(self, device, dtype):
+ A = torch.rand(3, 4, device=device, dtype=dtype)
+ v = solvers.null_vector_3x4(A)
+ assert v.shape == (4,)
+
+ # ------------------------------------------------------------------
+ # Exception / input validation
+ # ------------------------------------------------------------------
+
+ def test_exception_wrong_rows(self, device, dtype):
+ with pytest.raises(Exception):
+ solvers.null_vector_3x4(torch.rand(1, 4, 4, device=device, dtype=dtype))
+
+ def test_exception_wrong_cols(self, device, dtype):
+ with pytest.raises(Exception):
+ solvers.null_vector_3x4(torch.rand(1, 3, 3, device=device, dtype=dtype))
+
+ def test_exception_1d(self, device, dtype):
+ with pytest.raises(Exception):
+ solvers.null_vector_3x4(torch.rand(4, device=device, dtype=dtype))
+
+ def test_exception_not_tensor(self, device, dtype):
+ with pytest.raises(Exception):
+ solvers.null_vector_3x4([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])
+
+ # ------------------------------------------------------------------
+ # Known null vectors (hand-computed)
+ # ------------------------------------------------------------------
+
+ @pytest.mark.parametrize(
+ "A_data, expected_null",
+ [
+ # Standard basis: last column is free β†’ null vector is e4 = [0,0,0,1].
+ (
+ [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]],
+ [0.0, 0.0, 0.0, -1.0], # sign comes from cofactor; direction only
+ ),
+ # A = [[1,0,0,1],[0,1,0,1],[0,0,1,1]] β†’ null = [1,1,1,-1].
+ (
+ [[1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]],
+ [1.0, 1.0, 1.0, -1.0],
+ ),
+ # A = [[2,0,0,0],[0,3,0,0],[0,0,5,0]] β†’ null = [0,0,0,1] (up to sign/scale).
+ (
+ [[2.0, 0.0, 0.0, 0.0], [0.0, 3.0, 0.0, 0.0], [0.0, 0.0, 5.0, 0.0]],
+ [0.0, 0.0, 0.0, -30.0],
+ ),
+ ],
+ )
+ def test_known_null_vectors(self, A_data, expected_null, device, dtype):
+ A = torch.tensor([A_data], device=device, dtype=dtype) # (1, 3, 4)
+ expected = torch.tensor([expected_null], device=device, dtype=dtype) # (1, 4)
+ v = solvers.null_vector_3x4(A)
+ # Compare direction (ratio of corresponding components, ignoring global sign).
+ # Normalise both and check |cos ΞΈ| β‰ˆ 1.
+ v_n = v / v.norm(dim=-1, keepdim=True).clamp(min=1e-8)
+ e_n = expected / expected.norm(dim=-1, keepdim=True).clamp(min=1e-8)
+ cos_theta = (v_n * e_n).sum(dim=-1).abs()
+ self.assert_close(cos_theta, torch.ones_like(cos_theta), atol=1e-4, rtol=1e-4)
+
+ # ------------------------------------------------------------------
+ # Residual: A @ v must be (close to) zero
+ # ------------------------------------------------------------------
+
+ @pytest.mark.parametrize(
+ "null_vec",
+ [
+ [1.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 1.0],
+ [1.0, 1.0, 1.0, 1.0],
+ [1.0, -2.0, 3.0, -4.0],
+ [0.5, 0.5, -0.5, 0.5],
+ ],
+ )
+ def test_residual_near_zero(self, null_vec, device, dtype):
+ """A @ null_vector_3x4(A) must be (close to) zero for any rank-3 A."""
+ nv = torch.tensor(null_vec, dtype=torch.float64)
+ A = _make_rank3_matrix(nv, device=device, dtype=dtype) # (1, 3, 4)
+ v = solvers.null_vector_3x4(A) # (1, 4)
+ residual = (A @ v.unsqueeze(-1)).squeeze(-1) # (1, 3)
+ atol = {torch.float16: 1e-1, torch.bfloat16: 1e-1, torch.float32: 1e-4}.get(dtype, 1e-8)
+ self.assert_close(residual, torch.zeros_like(residual), atol=atol, rtol=0.0)
+
+ def test_residual_random_batch(self, device, dtype):
+ """Batch of random rank-3 matrices: residual should vanish."""
+ torch.manual_seed(42)
+ B = 16
+ null_vecs = torch.randn(B, 4)
+ As = torch.cat([_make_rank3_matrix(null_vecs[i], device=device, dtype=dtype) for i in range(B)], dim=0)
+ vs = solvers.null_vector_3x4(As)
+ residuals = (As @ vs.unsqueeze(-1)).squeeze(-1) # (B, 3)
+ atol = {torch.float16: 5e-1, torch.bfloat16: 5e-1, torch.float32: 1e-3}.get(dtype, 1e-7)
+ self.assert_close(residuals, torch.zeros_like(residuals), atol=atol, rtol=0.0)
+
+ # ------------------------------------------------------------------
+ # Direction recovery: null vector matches the known one up to scale
+ # ------------------------------------------------------------------
+
+ @pytest.mark.parametrize("seed", [0, 7, 42])
+ def test_direction_recovery(self, seed, device, dtype):
+ """The returned vector must be collinear with the true null vector."""
+ torch.manual_seed(seed)
+ null_vec = torch.randn(4)
+ A = _make_rank3_matrix(null_vec, device=device, dtype=dtype)
+ v = solvers.null_vector_3x4(A).squeeze(0) # (4,)
+
+ v_n = v / v.norm().clamp(min=1e-8)
+ nv_t = null_vec.to(device=device, dtype=dtype)
+ nv_n = nv_t / nv_t.norm().clamp(min=1e-8)
+
+ cos_theta = (v_n * nv_n).sum().abs()
+ atol = {torch.float16: 1e-1, torch.bfloat16: 1e-1, torch.float32: 5e-4}.get(dtype, 1e-8)
+ self.assert_close(cos_theta, cos_theta.new_ones(()), atol=atol, rtol=0.0)
+
+ # ------------------------------------------------------------------
+ # Dtype and device consistency
+ # ------------------------------------------------------------------
+
+ def test_output_dtype_matches_input(self, device, dtype):
+ A = torch.rand(2, 3, 4, device=device, dtype=dtype)
+ v = solvers.null_vector_3x4(A)
+ assert v.dtype == dtype
+
+ def test_output_device_matches_input(self, device, dtype):
+ A = torch.rand(2, 3, 4, device=device, dtype=dtype)
+ v = solvers.null_vector_3x4(A)
+ assert v.device == A.device
+
+ # ------------------------------------------------------------------
+ # Gradcheck
+ # ------------------------------------------------------------------
+
+ def test_gradcheck(self, device):
+ # Use a well-conditioned rank-3 matrix to keep gradients stable.
+ nv = torch.tensor([1.0, -2.0, 3.0, -4.0])
+ A = _make_rank3_matrix(nv, device=device, dtype=torch.float64)
+ A = A.detach().requires_grad_(True)
+ self.gradcheck(solvers.null_vector_3x4, (A,), raise_exception=True, fast_mode=True)
+
+ # ------------------------------------------------------------------
+ # Dynamo / torch.compile
+ # ------------------------------------------------------------------
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ A = torch.rand(4, 3, 4, device=device, dtype=dtype)
+ op = solvers.null_vector_3x4
+ op_compiled = torch_optimizer(op)
+ self.assert_close(op_compiled(A), op(A), atol=1e-5, rtol=1e-5)
+
+ # ------------------------------------------------------------------
+ # Module (no nn.Module wrapper β€” use function call form)
+ # ------------------------------------------------------------------
+
+ def test_module(self, device, dtype):
+ # null_vector_3x4 is a plain function; verify it is importable from the
+ # top-level kornia.geometry.solvers namespace.
+ import kornia.geometry.solvers as s
+
+ assert hasattr(s, "null_vector_3x4")
+ A = torch.rand(1, 3, 4, device=device, dtype=dtype)
+ v = s.null_vector_3x4(A)
+ assert v.shape == (1, 4)
diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.py
index 2b7058f81..593566628 100644
--- a/tests/geometry/test_homography.py
+++ b/tests/geometry/test_homography.py
@@ -348,7 +348,13 @@ class TestFindHomographyFromLinesDLT(BaseTester):
H_withweights = find_homography_lines_dlt(ls1, ls2, weights)
assert H_noweights.shape == (B, 3, 3)
assert H_withweights.shape == (B, 3, 3)
- self.assert_close(H_noweights, H_withweights, rtol=1e-3, atol=1e-4)
+ # On CUDA with float32, A^T A and A^T diag(1) A use different cuBLAS call sequences,
+ # so TF32 rounding accumulates differently. Use the same relaxed tolerance as
+ # test_clean_points does for this device+dtype combination.
+ rtol, atol = 1e-3, 1e-4
+ if device.type == "cuda" and dtype == torch.float32:
+ rtol, atol = 5e-3, 5e-3
+ self.assert_close(H_noweights, H_withweights, rtol=rtol, atol=atol)
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_clean_points(self, batch_size, device, dtype):