Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): enforce essential-matrix constraint in RANSAC polishing (#3987)

Atriob976a21d3c02
diff --git a/README.md b/README.md
index d214e4d3b..f76f4842c 100644
--- a/README.md
+++ b/README.md
@@ -55,7 +55,7 @@ Leverage pre-trained AI models optimized for a variety of vision tasks, all with
| **Category** | **Methods/Models** |
|----------------------------|---------------------------------------------------------------------------------------------------------------------|
| **Image Processing** | - Color conversions (RGB, Grayscale, HSV, etc.)<br>- Geometric transformations (Affine, Homography, Resizing, etc.)<br>- Filtering (Gaussian blur, Median blur, etc.)<br>- Edge detection (Sobel, Canny, etc.)<br>- Morphological operations (Erosion, Dilation, etc.) |
-| **Augmentation** | - Random cropping, Erasing<br> - Random geometric transformations (Affine, flipping, Fish Eye, Perspecive, Thin plate spline, Elastic)<br>- Random noises (Gaussian, Median, Motion, Box, Rain, Snow, Salt and Pepper)<br>- Random color jittering (Contrast, Brightness, CLAHE, Equalize, Gamma, Hue, Invert, JPEG, Plasma, Posterize, Saturation, Sharpness, Solarize)<br> - Random MixUp, CutMix, Mosaic, Transplantation, etc. |
+| **Augmentation** | - Random cropping, Erasing<br> - Random geometric transformations (Affine, flipping, Fish Eye, Perspective, Thin plate spline, Elastic)<br>- Random noises (Gaussian, Median, Motion, Box, Rain, Snow, Salt and Pepper)<br>- Random color jittering (Contrast, Brightness, CLAHE, Equalize, Gamma, Hue, Invert, JPEG, Plasma, Posterize, Saturation, Sharpness, Solarize)<br> - Random MixUp, CutMix, Mosaic, Transplantation, etc. |
| **Feature Detection** | - Detector (Harris, GFTT, Hessian, DoG, KeyNet, DISK and DeDoDe)<br> - Descriptor (SIFT, HardNet, TFeat, HyNet, SOSNet, and LAFDescriptor)<br>- Matching (nearest neighbor, mutual nearest neighbor, geometrically aware matching, AdaLAM LightGlue, and LoFTR) |
| **Geometry** | - Camera models and calibration<br>- Stereo vision (epipolar geometry, disparity, etc.)<br>- Homography estimation<br>- Depth estimation from disparity<br>- 3D transformations |
| **Deep Learning Layers** | - Custom convolution layers<br>- Recurrent layers for vision tasks<br>- Loss functions (e.g., SSIM, PSNR, etc.)<br>- Vision-specific optimizers |
diff --git a/docs/source/geometry.epipolar.rst b/docs/source/geometry.epipolar.rst
index 90e0205d2..ff876bf7f 100644
--- a/docs/source/geometry.epipolar.rst
+++ b/docs/source/geometry.epipolar.rst
@@ -15,6 +15,7 @@ Module with useful functionalities for epipolar geometry used by Structure from
Essential
---------
.. autofunction:: find_essential
+.. autofunction:: project_to_essential
.. autofunction:: essential_from_fundamental
.. autofunction:: essential_from_Rt
.. autofunction:: decompose_essential_matrix
diff --git a/kornia/geometry/epipolar/__init__.py b/kornia/geometry/epipolar/__init__.py
index f065d0db7..ca80ba24f 100644
--- a/kornia/geometry/epipolar/__init__.py
+++ b/kornia/geometry/epipolar/__init__.py
@@ -29,6 +29,7 @@ from .essential import (
find_essential,
motion_from_essential,
motion_from_essential_choose_solution,
+ project_to_essential,
relative_camera_motion,
)
from .fundamental import (
@@ -76,6 +77,7 @@ __all__ = [
"motion_from_essential_choose_solution",
"normalize_points",
"normalize_transformation",
+ "project_to_essential",
"projection_from_KRt",
"projections_from_fundamental",
"random_intrinsics",
diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.py
index 92ba2ddbf..5c1aff85f 100644
--- a/kornia/geometry/epipolar/essential.py
+++ b/kornia/geometry/epipolar/essential.py
@@ -38,6 +38,7 @@ __all__ = [
"find_essential",
"motion_from_essential",
"motion_from_essential_choose_solution",
+ "project_to_essential",
"relative_camera_motion",
]
@@ -439,6 +440,32 @@ def essential_from_fundamental(F_mat: torch.Tensor, K1: torch.Tensor, K2: torch.
return K2.transpose(-2, -1) @ F_mat @ K1
+def project_to_essential(E_mat: torch.Tensor) -> torch.Tensor:
+ r"""Project a matrix onto the essential-matrix manifold.
+
+ An essential matrix must be of the form :math:`U \text{diag}(s, s, 0) V^T`. Matrices estimated
+ by other means (e.g. a fundamental matrix fitted with the 8-point DLT) generally violate this
+ constraint, which silently breaks tools that rely on it, such as
+ :func:`decompose_essential_matrix` and :func:`motion_from_essential`. The projection averages
+ the two largest singular values and zeroes the smallest one.
+
+ Args:
+ E_mat: The matrices to project with shape :math:`(*, 3, 3)`.
+
+ Returns:
+ The closest matrices (in Frobenius norm) satisfying the essential-matrix constraint,
+ with shape :math:`(*, 3, 3)`.
+
+ """
+ KORNIA_CHECK_SHAPE(E_mat, ["*", "3", "3"])
+ U, S, V = _torch_svd_cast(E_mat)
+ S_new = torch.zeros_like(S)
+ mean_sv = 0.5 * (S[..., 0] + S[..., 1])
+ S_new[..., 0] = mean_sv
+ S_new[..., 1] = mean_sv
+ return U @ torch.diag_embed(S_new) @ V.mH
+
+
def decompose_essential_matrix(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
r"""Decompose an essential matrix to possible rotations and translation.
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.py
index 437f20f78..6b4644627 100644
--- a/kornia/geometry/ransac.py
+++ b/kornia/geometry/ransac.py
@@ -25,7 +25,7 @@ import torch
from torch import nn
from kornia.core.check import KORNIA_CHECK_SHAPE
-from kornia.geometry.epipolar import find_essential, find_fundamental, sampson_epipolar_distance
+from kornia.geometry.epipolar import find_essential, find_fundamental, project_to_essential, sampson_epipolar_distance
from kornia.geometry.homography import (
find_homography_dlt,
find_homography_dlt_iterated,
@@ -308,6 +308,13 @@ class RANSAC(nn.Module):
model = self.polisher_solver(
kp1_inl, kp2_inl, torch.ones(1, num_inl, dtype=kp1_inl.dtype, device=kp1_inl.device)
)
+ # The polisher fits a fundamental matrix via the 8-point DLT, which does not enforce the
+ # essential-matrix constraint (two equal non-zero singular values and a zero singular value).
+ # Project it back onto the essential manifold so that downstream decompose_essential_matrix /
+ # motion_from_essential do not silently fail.
+ # See https://github.com/kornia/kornia/issues/3874
+ if self.model_type == "essential":
+ model = project_to_essential(model)
return model
def validate_inputs(self, kp1: torch.Tensor, kp2: torch.Tensor, weights: Optional[torch.Tensor] = None) -> None:
@@ -405,4 +412,10 @@ class RANSAC(nn.Module):
if (i + 1) * self.batch_size >= new_max_iter:
break
# local optimization with all inliers for better precision
+ # The best model may come from the 5-point minimal solver (find_essential), which is not
+ # guaranteed to return a matrix on the essential manifold. Project the returned model once
+ # instead of projecting every candidate inside the loop, so that model selection is unaffected.
+ # See https://github.com/kornia/kornia/issues/3874
+ if self.model_type == "essential":
+ best_model_total = project_to_essential(best_model_total[None])[0]
return best_model_total, inliers_best_total
diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.py
index 5451b2e22..3f89850ba 100644
--- a/tests/geometry/test_ransac.py
+++ b/tests/geometry/test_ransac.py
@@ -20,7 +20,7 @@ import pytest
import torch
from kornia.geometry import RANSAC, transform_points
-from kornia.geometry.epipolar import sampson_epipolar_distance
+from kornia.geometry.epipolar import project_to_essential, sampson_epipolar_distance
from testing.base import BaseTester
from testing.casts import dict_to
@@ -368,3 +368,82 @@ class TestRANSACSeed:
def test_none_seed_stored(self, device, dtype):
ransac = RANSAC("homography")
assert ransac.seed is None
+
+
+class TestRANSACEssential(BaseTester):
+ def test_smoke(self, device, dtype):
+ torch.random.manual_seed(0)
+ points1 = torch.rand(8, 2, device=device, dtype=dtype)
+ points2 = torch.rand(8, 2, device=device, dtype=dtype)
+ ransac = RANSAC("essential").to(device=device, dtype=dtype)
+ E, _ = ransac(points1, points2)
+ assert E.shape == (3, 3)
+
+ def test_polish_enforces_essential_constraint(self, device, dtype):
+ """Regression test for https://github.com/kornia/kornia/issues/3874.
+
+ The polishing (local-optimization) step must return an essential matrix, i.e. its two
+ non-zero singular values must be (approximately) equal and the third must be
+ (approximately) zero. The buggy version fit a fundamental matrix and returned it as-is,
+ violating the constraint and silently breaking decompose_essential_matrix.
+ """
+ torch.random.manual_seed(0)
+ ransac = RANSAC("essential").to(device=device, dtype=dtype)
+ kp1 = torch.rand(20, 2, device=device, dtype=dtype)
+ kp2 = torch.rand(20, 2, device=device, dtype=dtype)
+ inliers = torch.ones(20, dtype=torch.bool, device=device)
+ E = ransac.polish_model(kp1, kp2, inliers) # (1, 3, 3)
+ sv = torch.linalg.svdvals(E[0])
+ # two non-zero singular values must be equal (essential-matrix constraint)
+ assert (sv[0] / sv[1] - 1.0).abs() < 1e-2
+ # third singular value must be ~0 (relative to the largest singular value)
+ assert (sv[2] / sv[0]).abs() < 1e-4
+
+ def test_forward_enforces_essential_constraint(self, device, dtype):
+ """Regression test for https://github.com/kornia/kornia/issues/3874 (forward path).
+
+ forward() must return an essential matrix even when local optimization does not win and
+ the best model is the minimal-solver estimate (find_essential), which is not guaranteed
+ to be on the essential manifold. The returned model is projected onto the manifold
+ before being returned, so the constraint holds regardless of which path selects the
+ best model.
+ """
+ torch.random.manual_seed(0)
+ ransac = RANSAC("essential").to(device=device, dtype=dtype)
+ for _ in range(5):
+ kp1 = torch.rand(20, 2, device=device, dtype=dtype)
+ kp2 = torch.rand(20, 2, device=device, dtype=dtype)
+ E, _ = ransac(kp1, kp2)
+ sv = torch.linalg.svdvals(E)
+ assert (sv[0] / sv[1] - 1.0).abs() < 1e-2
+ assert (sv[2] / sv[0]).abs() < 1e-4
+
+ def test_project_to_essential(self, device, dtype):
+ """project_to_essential must enforce the essential-matrix constraint."""
+ torch.random.manual_seed(0)
+ M = torch.rand(4, 3, 3, device=device, dtype=dtype)
+ E = project_to_essential(M)
+ sv = torch.linalg.svdvals(E)
+ assert torch.all((sv[..., 0] / sv[..., 1] - 1.0).abs() < 1e-2)
+ assert torch.all((sv[..., 2] / sv[..., 0]).abs() < 1e-4)
+
+ @pytest.mark.skip(reason="try except block in python version")
+ def test_jit(self, device, dtype):
+ torch.random.manual_seed(0)
+ points1 = torch.rand(8, 2, device=device, dtype=dtype)
+ points2 = torch.rand(8, 2, device=device, dtype=dtype)
+ model = RANSAC("essential").to(device=device, dtype=dtype)
+ model_jit = torch.jit.script(model)
+ self.assert_close(model(points1, points2)[0], model_jit(points1, points2)[0], rtol=1e-3, atol=1e-3)
+
+ @pytest.mark.skip(reason="RANSAC is random algorithm, so Jacobian is not defined")
+ def test_gradcheck(self, device):
+ torch.random.manual_seed(0)
+ points1 = torch.rand(8, 2, device=device, dtype=torch.float64, requires_grad=True)
+ points2 = torch.rand(8, 2, device=device, dtype=torch.float64)
+ model = RANSAC("essential").to(device=device, dtype=torch.float64)
+
+ def gradfun(p1, p2):
+ return model(p1, p2)[0]
+
+ self.gradcheck(gradfun, (points1, points2), fast_mode=False, requires_grad=(True, False, False))