Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(epipolar): zero the 7-point candidates of padded cubic roots (#5006)

Mohammad Hijjawi166f2a864598
diff --git a/changelog.d/5006.fixed.md b/changelog.d/5006.fixed.md
new file mode 100644
index 000000000..5bf35be8c
--- /dev/null
+++ b/changelog.d/5006.fixed.md
@@ -0,0 +1 @@
+`find_fundamental(..., method="7POINT")` / `run_7point` now return zero matrices for the two extra candidates when the 7-point cubic has one real root, instead of one rank-3 matrix repeated.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index f8a28d62a..bb4dc7d7b 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -544,8 +544,8 @@ normalised camera coordinates, and :func:`~kornia.geometry.homography.find_homog
- OpenCV
* - fundamental matrix
- ``find_fundamental(points1, points2)``, scaled to ``F[2, 2] = 1`` unless that entry is numerically zero;
- ``method="7POINT"`` returns three candidates ``(B, 3, 3, 3)`` in no particular order, padded when the cubic
- has one real root (`#4862 <https://github.com/kornia/kornia/issues/4862>`_)
+ ``method="7POINT"`` returns three candidates ``(B, 3, 3, 3)`` in no particular order, padded with zero
+ matrices when the cubic has one real root
- ``findFundamentalMat(points1, points2)``, the same ``F``; ``FM_7POINT`` stacks only the real solutions as
``(3k, 3)``
* - essential matrix
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index 963cda64a..52864b9e0 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -25,7 +25,7 @@ import torch
from kornia.core.check import KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPE
from kornia.core.utils import _torch_svd_cast, safe_inverse_with_mask
from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
-from kornia.geometry.solvers import solve_cubic
+from kornia.geometry.solvers.polynomial_solver import _solve_cubic_with_count
def normalize_points(
@@ -193,8 +193,7 @@ def run_7point(points1: torch.Tensor, points2: torch.Tensor) -> torch.Tensor:
Returns:
The computed fundamental matrices with shape :math:`(B, 3, 3, 3)`, always 3 candidates per batch
- element. A cubic with a single real root still gives 3: the two extra candidates are one rank-3 matrix
- repeated, not zeros (`#4862 <https://github.com/kornia/kornia/issues/4862>`_).
+ element. A cubic with a single real root gives one candidate followed by two zero matrices.
"""
KORNIA_CHECK_SHAPE(points1, ["B", "7", "2"])
@@ -232,11 +231,10 @@ def run_7point(points1: torch.Tensor, points2: torch.Tensor) -> torch.Tensor:
coeffs[:, 2] = torch.einsum("bii->b", f1 @ inv_f2) * f2_det
coeffs[:, 3] = f2_det
- roots = solve_cubic(coeffs) # (B,3)
+ roots, num_real = _solve_cubic_with_count(coeffs) # (B,3), (B,)
- # same "valid_root_mask" logic as your working version
- cnz = torch.count_nonzero(roots, dim=1) # (B,)
- valid_root_mask = (cnz < 3) | (cnz > 1) # (B,) bool
+ # The real roots fill the first num_real slots; the rest are solve_cubic's 0.0 padding, not roots.
+ valid_root_mask = torch.arange(3, device=device) < num_real.unsqueeze(1) # (B,3) bool
# --- compute lambda/mu for ALL batches (no compaction) ---
_lambda = roots.clone()
@@ -269,9 +267,8 @@ def run_7point(points1: torch.Tensor, points2: torch.Tensor) -> torch.Tensor:
f22 = torch.where(_s_non_zero_mask, torch.ones_like(_s, dtype=dtype), torch.zeros_like(_s, dtype=dtype))
fmatrix[:, :, 2, 2] = f22 # (B,3)
- # --- apply batch validity mask (no compaction) ---
- # If batch invalid -> zero all 3 candidates
- fmatrix = torch.where(valid_root_mask.view(B, 1, 1, 1), fmatrix, torch.zeros_like(fmatrix))
+ # --- zero the candidates of padded roots (no compaction) ---
+ fmatrix = torch.where(valid_root_mask.view(B, 3, 1, 1), fmatrix, torch.zeros_like(fmatrix))
# --- denormalize for ALL batches ---
# F = T2^T * F * T1
@@ -375,8 +372,7 @@ def find_fundamental(
``method="7POINT"`` returns three candidates in no particular order.
- ``weights`` weight each correspondence's equation in the linear system: only their ratios matter, a
negative weight counts as zero, and ``method="7POINT"`` ignores them.
- - Known defect: when the 7-point cubic has one real root, the two extra candidates are one rank-3
- matrix repeated instead of zeros (`#4862 <https://github.com/kornia/kornia/issues/4862>`_).
+ - When the 7-point cubic has one real root, the two extra ``"7POINT"`` candidates are zero matrices.
Args:
points1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`: :math:`N \ge 8` for
diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.py
index f5a0b28bd..15338f816 100644
--- a/kornia/geometry/solvers/polynomial_solver.py
+++ b/kornia/geometry/solvers/polynomial_solver.py
@@ -144,6 +144,18 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:
undefined; this is a surrogate convention, not a mathematical Jacobian. :func:`solve_quartic`
inherits this convention wherever it falls back to :func:`solve_cubic`.
+ """
+ return _solve_cubic_with_count(coeffs)[0]
+
+
+def _solve_cubic_with_count(coeffs: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ """Solve a cubic as :func:`solve_cubic` does and also count its real roots.
+
+ Returns:
+ The roots of :func:`solve_cubic`, shape `(B, 3)`, and the number of real roots per row counted with
+ multiplicity, shape `(B,)`. The real roots fill the first slots and the rest are the ``0.0`` padding,
+ which the count tells apart from a root at 0.
+
"""
KORNIA_CHECK_SHAPE(coeffs, ["B", "4"])
@@ -152,7 +164,8 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:
# Q > 0: every root comes back NaN. Solve half-precision cubics in float32 and return the roots
# in the input dtype, as solve_quartic does for its Ferrari path.
if coeffs.dtype in (torch.float16, torch.bfloat16):
- return solve_cubic(coeffs.float()).to(coeffs.dtype)
+ roots, num_real = _solve_cubic_with_count(coeffs.float())
+ return roots.to(coeffs.dtype), num_real
_PI = torch.tensor(math.pi, device=coeffs.device, dtype=coeffs.dtype)
@@ -163,6 +176,7 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:
d = coeffs[:, 3] # constant term
solutions = torch.zeros((len(coeffs), 3), device=a.device, dtype=a.dtype)
+ num_real = torch.zeros(len(coeffs), device=a.device, dtype=torch.long)
mask_a_zero = a == 0
mask_b_zero = b == 0
@@ -176,6 +190,9 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:
if torch.any(mask_second_order):
solutions[mask_second_order, 0:2] = solve_quadratic(coeffs[mask_second_order, 1:])
+ # solve_quadratic's own discriminant: two real roots (a double root repeated) or none.
+ quad_b, quad_c, quad_d = b[mask_second_order], c[mask_second_order], d[mask_second_order]
+ num_real[mask_second_order] = torch.where(quad_c * quad_c - 4 * quad_b * quad_d < 0, 0, 2)
if torch.any(mask_first_order):
# cx + d = 0. The (a * x + b) * x^2 / c term is 0 in the forward pass, but it keeps the root's
@@ -184,6 +201,7 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:
x0_first = -d[mask_first_order] / c_first
a_first, b_first = a[mask_first_order], b[mask_first_order]
solutions[mask_first_order, 0] = x0_first - (a_first * x0_first + b_first) * x0_first * x0_first / c_first
+ num_real[mask_first_order] = 1
# Normalized form x^3 + a2 * x^2 + a1 * x + a0 = 0
inv_a = 1.0 / a[~mask_a_zero]
@@ -220,6 +238,7 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:
# but it keeps the root's dependence on Q in the gradient (d root / dQ = -1 / A).
x0_Q_zero = A_Q_zero - Q[mask_Q_zero] / A_Q_zero - b_a_3[mask_Q_zero]
solutions[mask_Q_zero_solutions, 0] = x0_Q_zero
+ num_real[mask_Q_zero_solutions] = 1
mask_QR_zero = (Q == 0) & (R == 0)
mask_QR_zero_solutions = (a_Q_zero == 0) & (a_R_zero == 0)
@@ -228,6 +247,7 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:
solutions[mask_QR_zero_solutions] = torch.stack(
[-b_a_3[mask_QR_zero], -b_a_3[mask_QR_zero], -b_a_3[mask_QR_zero]], dim=1
)
+ num_real[mask_QR_zero_solutions] = 3
# D <= 0
mask_D_zero = (D <= 0) & (Q != 0)
@@ -253,6 +273,7 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:
x1_D_zero = 2 * sqrt_Q_D_zero * torch.cos((theta_D_zero + 2 * _PI) / 3.0) - b_a_3[mask_D_zero]
x2_D_zero = 2 * sqrt_Q_D_zero * torch.cos((theta_D_zero + 4 * _PI) / 3.0) - b_a_3[mask_D_zero]
solutions[mask_D_zero_solutions] = torch.stack([x0_D_zero, x1_D_zero, x2_D_zero], dim=1)
+ num_real[mask_D_zero_solutions] = 3
a_D_positive = torch.zeros_like(a)
a_D_positive[~mask_a_zero] = D
@@ -277,8 +298,9 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:
BD[mask_R_positive] = -Q[mask_R_positive] / AD[mask_R_positive]
x0_D_positive = AD[mask_D_positive] + BD[mask_D_positive] - b_a_3[mask_D_positive]
solutions[mask_D_positive_solution, 0] = x0_D_positive
+ num_real[mask_D_positive_solution] = 1
- return solutions
+ return solutions, num_real
def _quartic_root_residual_tol(dtype: torch.dtype) -> float:
diff --git a/tests/geometry/epipolar/test_fundamental.py b/tests/geometry/epipolar/test_fundamental.py
index 38f1c7be7..55df7f9cc 100644
--- a/tests/geometry/epipolar/test_fundamental.py
+++ b/tests/geometry/epipolar/test_fundamental.py
@@ -793,19 +793,23 @@ class TestConventionFundamental(BaseTester):
swapped = epi.get_closest_point_on_epipolar_line(x2, x1, F)
assert (_hom(swapped) * lines).sum(-1).abs().max() > 1.0
- def test_wart_run_7point_padded_roots_returned_4862(self, device, dtype):
+ def test_run_7point_zeroes_padded_roots_4862(self, device, dtype):
two_view = two_view_scene(device, dtype)
_skip_half(dtype, _NO_HALF_EIGH)
- # #4862: a 7-point sample whose cubic has one real root. The solver pads the two missing roots with 0.0 and the
- # validity mask never fires, so candidates 1 and 2 are the same rank-3 matrix instead of being zeroed.
- # Any fix (zeros, NaN, or fewer candidates) makes these assertions fail.
+ # #4862: a 7-point sample whose cubic has one real root. The solver pads the two missing roots with 0.0; their
+ # candidates used to be one rank-3 matrix repeated, and are now zeroed as the padding they are.
idx = [0, 1, 2, 3, 4, 6, 10]
F = epi.find_fundamental(two_view["x1"][:, idx], two_view["x2"][:, idx], method="7POINT")
assert F.shape == (1, 3, 3, 3)
- assert torch.equal(F[:, 1], F[:, 2])
+ assert (F[:, 1:] == 0).all()
+ sv = torch.linalg.svdvals(F[0, 0].cpu().double())
+ assert sv[2] < 1e-8 * sv[0] # candidate 0 is a genuine rank-2 solution
+ # Control: a sample whose cubic has three real roots keeps three rank-2 candidates.
+ idx = [0, 1, 2, 3, 4, 5, 6]
+ F = epi.find_fundamental(two_view["x1"][:, idx], two_view["x2"][:, idx], method="7POINT")
sv = torch.linalg.svdvals(F[0].cpu().double())
- assert sv[0, 2] < 1e-8 * sv[0, 0] # candidate 0 is a genuine rank-2 solution
- assert (sv[1:, 2] > 1e-7 * sv[1:, 0]).all() # the padded candidates are rank 3
+ assert (sv[:, 0] > 0).all()
+ assert (sv[:, 2] < 1e-8 * sv[:, 0]).all()
def test_convention_normalize_transformation_eps_divisor_4874(self, device, dtype):
# #4874: eps guards the divisor without biasing the normalized matrix.
diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.py
index 2a593f9b7..64bfa2780 100644
--- a/tests/geometry/solvers/test_polynomial_solver.py
+++ b/tests/geometry/solvers/test_polynomial_solver.py
@@ -21,6 +21,7 @@ import torch
import kornia.geometry.solvers as solver
from kornia.core.exceptions import ShapeError
+from kornia.geometry.solvers.polynomial_solver import _solve_cubic_with_count
from testing.base import BaseTester
@@ -243,6 +244,28 @@ class TestCubicSolver(BaseTester):
roots.sum().backward()
assert bool(torch.isfinite(x.grad).all()), x.grad
+ def test_real_root_count_4862(self, device, dtype):
+ # #4862: the 0.0 padding is indistinguishable from a root at 0 in the roots alone; the count tells them apart.
+ coeffs = torch.tensor(
+ [
+ [1.0, -6.0, 11.0, -6.0], # (x - 1)(x - 2)(x - 3): D <= 0
+ [1.0, 0.0, 1.0, 0.0], # x (x^2 + 1): one real root at 0, D > 0
+ [1.0, 0.0, 0.0, -1.0], # x^3 - 1: Q == 0
+ [1.0, 3.0, 3.0, 1.0], # (x + 1)^3: Q == R == 0
+ [1.0, -2.0, 1.0, 0.0], # x (x - 1)^2: D == 0, the double root counts twice
+ [0.0, 1.0, -3.0, 2.0], # (x - 1)(x - 2)
+ [0.0, 1.0, -2.0, 1.0], # (x - 1)^2: zero discriminant, the double root counts twice
+ [0.0, 1.0, 0.0, 1.0], # x^2 + 1
+ [0.0, 0.0, 2.0, -1.0], # 2x - 1
+ [0.0, 0.0, 0.0, 1.0], # a nonzero constant
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ roots, num_real = _solve_cubic_with_count(coeffs)
+ self.assert_close(roots, solver.solve_cubic(coeffs), rtol=0.0, atol=0.0)
+ assert num_real.tolist() == [3, 1, 1, 3, 3, 2, 2, 0, 1, 0]
+
class TestMultiplyDegOnePoly(BaseTester):
def test_smoke(self, device, dtype):