Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(epipolar): normalize transformations without epsilon bias (#4911)

Puttala Jeevan Kumar6e51ef7670b8
diff --git a/changelog.d/4911.breaking.md b/changelog.d/4911.breaking.md
new file mode 100644
index 000000000..d4733ebcb
--- /dev/null
+++ b/changelog.d/4911.breaking.md
@@ -0,0 +1,7 @@
+`normalize_transformation`, and with it `find_fundamental`, now divides by the last entry itself instead of
+`M[2, 2] + 1e-8`, so the returned last entry is exactly 1 (#4874). Before, it was `M[2, 2] / (M[2, 2] + 1e-8)`: 0.990
+for `M[2, 2] = 1e-6` and 101 for `-1.01e-8`, and the backward returned NaN for a matrix whose last entry was exactly
+`-1e-8`. `find_homography_dlt` and `find_homography_lines_dlt` now end with `normalize_transformation` as well. They
+used to divide by `H[2, 2] + 1e-8` without a guard, so a homography whose last entry was at most `1e-8` in magnitude
+came back multiplied by at least `5e7`, with a last entry anywhere below `0.5`; it is now returned at its
+unnormalised scale. At the usual scale, `|H[2, 2]|` of order 1, the result changes by about `1e-8`, relative.
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index 6715887d3..dcbf5187c 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -87,14 +87,10 @@ def normalize_transformation(M: torch.Tensor, eps: float = 1e-8) -> torch.Tensor
Convention:
- Divides ``M`` by its last entry ``M[..., -1, -1]``, which gives :func:`find_fundamental` its
``F[2, 2] = 1`` scaling. A matrix whose last entry is within ``eps`` of zero is returned unchanged.
- - Known defects: the divisor is ``M[..., -1, -1] + eps``, so the last entry is not exactly one, and it is
- far from one when ``|M[..., -1, -1]|`` is close to ``eps``
- (`#4874 <https://github.com/kornia/kornia/issues/4874>`_).
Args:
M: The transformation to be normalized of any shape with a minimum size of 2x2.
- eps: added to the divisor, and the magnitude of the last entry at or below which ``M`` is returned
- unchanged.
+ eps: magnitude of the last entry at or below which ``M`` is returned unchanged.
Returns:
the normalized transformation matrix with same shape as the input.
@@ -103,7 +99,9 @@ def normalize_transformation(M: torch.Tensor, eps: float = 1e-8) -> torch.Tensor
if len(M.shape) < 2:
raise AssertionError(M.shape)
norm_val: torch.Tensor = M[..., -1:, -1:]
- return torch.where(norm_val.abs() > eps, M / (norm_val + eps), M)
+ mask = norm_val.abs() > eps
+ divisor = torch.where(mask, norm_val, torch.ones_like(norm_val))
+ return torch.where(mask, M / divisor, M)
def _nullspace_via_eigh(A: torch.Tensor) -> torch.Tensor:
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index dfda5b131..e7510780a 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -23,7 +23,7 @@ import torch
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.core.utils import _extract_device_dtype, _torch_svd_cast, safe_inverse_with_mask, safe_solve_with_mask
from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
-from kornia.geometry.epipolar import normalize_points
+from kornia.geometry.epipolar import normalize_points, normalize_transformation
from kornia.geometry.linalg import transform_points
TupleTensor = Tuple[torch.Tensor, torch.Tensor]
@@ -212,15 +212,15 @@ def find_homography_dlt(
Convention:
- ``H`` maps ``points1`` to ``points2``, ``points2 ~ H @ points1``, and is scaled so that
- ``H[2, 2] = 1``; :ref:`two-view-conventions` compares this with OpenCV.
+ ``H[2, 2] = 1`` by :func:`~kornia.geometry.epipolar.normalize_transformation`, which leaves it at its
+ unnormalised scale when ``|H[2, 2]|`` is at most ``1e-8``; :ref:`two-view-conventions` compares this
+ with OpenCV.
- ``weights`` multiply each correspondence's squared algebraic residual: a weight of 0 removes the
correspondence from the equations, and only relative weights matter.
- ``solver="lu"`` and ``"svd"`` give the same homography on exact data, to roundoff scaled by the
conditioning of the system; on noisy data they solve different least-squares problems and differ.
- - Known defects: a zero-weight correspondence still enters the point normalisation, so on noisy data it
- moves the result (`#4890 <https://github.com/kornia/kornia/issues/4890>`_); and ``H`` is divided by
- ``H[2, 2] + 1e-8``, so ``H[2, 2]`` is not exactly 1, and it can be far from 1 when the true ``H[2, 2]``
- is small (`#4874 <https://github.com/kornia/kornia/issues/4874>`_).
+ - Known defect: a zero-weight correspondence still enters the point normalisation, so on noisy data it
+ moves the result (`#4890 <https://github.com/kornia/kornia/issues/4890>`_).
Args:
points1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`.
@@ -321,7 +321,7 @@ def find_homography_dlt(
else:
raise NotImplementedError
H = safe_inverse_with_mask(transform2)[0] @ (H @ transform1)
- return H / (H[..., -1:, -1:] + eps)
+ return normalize_transformation(H, eps)
def find_homography_dlt_iterated(
@@ -333,9 +333,8 @@ def find_homography_dlt_iterated(
- Direction and ``H[2, 2] = 1`` as :func:`find_homography_dlt`. Each solve after the first re-weights
with ``exp(-e / (2 * soft_inl_th**2))`` of the unsquared symmetric transfer error ``e``.
- Known defects: the exponent is linear, not quadratic, in ``e``, so ``soft_inl_th`` is not a pixel
- standard deviation (`#4870 <https://github.com/kornia/kornia/issues/4870>`_); those of
- :func:`find_homography_dlt` apply (`#4874 <https://github.com/kornia/kornia/issues/4874>`_,
- `#4890 <https://github.com/kornia/kornia/issues/4890>`_).
+ standard deviation (`#4870 <https://github.com/kornia/kornia/issues/4870>`_); that of
+ :func:`find_homography_dlt` applies (`#4890 <https://github.com/kornia/kornia/issues/4890>`_).
Args:
points1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`.
@@ -416,10 +415,8 @@ def find_homography_lines_dlt(
- Known defects: each segment's equations are built from endpoints of two different segments, not from
its own start and end, so the estimate is correct only when the endpoints are themselves point
correspondences, and a zero weight does not remove its segment
- (`#4866 <https://github.com/kornia/kornia/issues/4866>`_); the endpoints of a zero-weight segment still
- enter the point normalisation (`#4890 <https://github.com/kornia/kornia/issues/4890>`_); and the
- ``H[2, 2]`` scaling of :func:`find_homography_dlt` applies
- (`#4874 <https://github.com/kornia/kornia/issues/4874>`_).
+ (`#4866 <https://github.com/kornia/kornia/issues/4866>`_); and the endpoints of a zero-weight segment
+ still enter the point normalisation (`#4890 <https://github.com/kornia/kornia/issues/4890>`_).
Args:
ls1: A set of line segments in the first image with a tensor shape :math:`(B, N, 2, 2)`, or
@@ -483,7 +480,7 @@ def find_homography_lines_dlt(
H = V[..., -1].view(-1, 3, 3)
H = safe_inverse_with_mask(transform2)[0] @ (H @ transform1)
- return H / (H[..., -1:, -1:] + eps)
+ return normalize_transformation(H, eps)
def find_homography_lines_dlt_iterated(
@@ -498,7 +495,6 @@ def find_homography_lines_dlt_iterated(
(`#4866 <https://github.com/kornia/kornia/issues/4866>`_,
`#4867 <https://github.com/kornia/kornia/issues/4867>`_,
`#4870 <https://github.com/kornia/kornia/issues/4870>`_,
- `#4874 <https://github.com/kornia/kornia/issues/4874>`_,
`#4890 <https://github.com/kornia/kornia/issues/4890>`_).
Args:
diff --git a/tests/geometry/epipolar/test_fundamental.py b/tests/geometry/epipolar/test_fundamental.py
index 8fa17dec2..fd727f949 100644
--- a/tests/geometry/epipolar/test_fundamental.py
+++ b/tests/geometry/epipolar/test_fundamental.py
@@ -759,14 +759,30 @@ class TestConventionFundamental(BaseTester):
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
- def test_wart_normalize_transformation_eps_divisor_4874(self, device, dtype):
- # #4874: the divisor is M[2, 2] + eps, so the last entry is 1 only to eps / |M[2, 2]|.
+ def test_convention_normalize_transformation_eps_divisor_4874(self, device, dtype):
+ # #4874: eps guards the divisor without biasing the normalized matrix.
M = torch.tensor([[[2.0, 0.5, 3.0], [-1.0, 4.0, 0.25], [0.75, -2.0, 0.1]]], device=device, dtype=dtype)
out = epi.normalize_transformation(M, eps=1e-3)
- assert (out[0, 2, 2] - 1.0).abs() > 5e-3
- if dtype != torch.float16: # float16 rounds 1e-6 + 1e-8 back to 1e-6
- M[0, 2, 2] = 1e-6
- assert (epi.normalize_transformation(M)[0, 2, 2] - 1.0).abs() > 5e-3
+ self.assert_close(out, M / M[..., -1:, -1:], rtol=0, atol=0)
+
+ @pytest.mark.parametrize("value", [1.0, 1e-3, 1e-6, -1e-7, 1.01e-8, -1.01e-8])
+ def test_normalize_transformation_exact_last_entry(self, device, dtype, value):
+ if dtype == torch.float16:
+ pytest.skip("the near-threshold values are not representable in float16")
+ M = torch.tensor([[2.0, 0.5, 1.0], [0.3, 1.5, -2.0], [0.1, 0.2, value]], device=device, dtype=dtype)
+ out = epi.normalize_transformation(M)
+ assert out[2, 2] == 1
+ self.assert_close(out, M / M[2, 2], rtol=0, atol=0)
+
+ def test_normalize_transformation_singular_guard(self, device, dtype):
+ values = torch.tensor([0.0, 0.99e-8, -0.99e-8, 1e-8, -1e-8], device=device, dtype=dtype)
+ M = torch.ones(5, 3, 3, device=device, dtype=dtype)
+ M[..., 2, 2] = values
+ M.requires_grad_()
+ out = epi.normalize_transformation(M)
+ self.assert_close(out, M, rtol=0, atol=0)
+ out.sum().backward()
+ self.assert_close(M.grad, torch.ones_like(M), rtol=0, atol=0)
def test_wart_find_fundamental_zero_weight_changes_result_4875(self, device, dtype):
two_view = two_view_scene(device, dtype)
diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.py
index 891c15a0a..2fdd21c25 100644
--- a/tests/geometry/test_homography.py
+++ b/tests/geometry/test_homography.py
@@ -540,6 +540,53 @@ class TestFindHomographyFromLinesDLT(BaseTester):
self.gradcheck(find_homography_lines_dlt, (ls1, ls2, weights), rtol=1e-6, atol=1e-6)
+class TestHomographyNormalization(BaseTester):
+ @pytest.mark.parametrize("solver", ["lu", "svd", "lines"])
+ @pytest.mark.parametrize("last_entry", [1e-6, -1e-6, 0.0, 1e-10, -1e-10])
+ def test_small_last_entry(self, device, solver, last_entry):
+ # Float64 resolves the small homogeneous scale without solver rounding masking #4874.
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
+ points = torch.tensor(
+ [
+ [
+ [1.0, 1.0],
+ [2.0, 1.0],
+ [2.0, 3.0],
+ [1.0, 3.0],
+ [3.0, 2.0],
+ [4.0, 1.0],
+ [4.0, 4.0],
+ [1.0, 4.0],
+ [2.0, 5.0],
+ [5.0, 2.0],
+ [3.0, 4.0],
+ [5.0, 5.0],
+ ]
+ ],
+ device=device,
+ dtype=torch.float64,
+ )
+ H = torch.tensor(
+ [[[1.0, 0.2, 0.3], [0.1, 1.0, 0.2], [0.1, 0.2, last_entry]]], device=device, dtype=points.dtype
+ )
+ projected = torch.cat([points, torch.ones_like(points[..., :1])], dim=-1) @ H.transpose(-1, -2)
+ target = (projected[..., :2] / projected[..., 2:]).detach().requires_grad_()
+ if solver == "lines":
+ out = find_homography_lines_dlt(points.reshape(1, 6, 2, 2), target.reshape(1, 6, 2, 2))
+ else:
+ out = find_homography_dlt(points[:, :4], target[:, :4], solver=solver)
+ if abs(last_entry) > 1e-8:
+ assert out[0, 2, 2] == 1
+ else:
+ # Keep the finite, unscaled estimate when its last entry is too small to normalize.
+ assert out[..., 2, 2].abs().max() <= 1e-8
+ assert out.abs().max() < 10
+ self.assert_close(out / out[..., :1, :1], H, rtol=1e-6, atol=1e-8)
+ out.sum().backward()
+ assert torch.isfinite(target.grad).all()
+
+
class TestFindHomographyDLTIter(BaseTester):
def test_smoke(self, device, dtype):
points1 = torch.rand(1, 4, 2, device=device, dtype=dtype)
@@ -944,7 +991,7 @@ class TestConventionHomography(BaseTester):
assert oneway_transfer_error(p1, p2, 1e-8 * H, squared=False).min() > 1.0
@pytest.mark.parametrize("model", ["points", "lines"])
- def test_wart_find_homography_dlt_h22_eps_divisor_4874(self, model, device, dtype):
+ def test_convention_find_homography_dlt_h22_eps_divisor_4874(self, model, device, dtype):
_skip_half(dtype, _HALF_DLT)
p1, p2, _ = _planar(device, dtype)
# The same fixture with the true H[2, 2] set to 1e-6 (a mild warp whose origin maps far out), exact matches.
@@ -959,9 +1006,9 @@ class TestConventionHomography(BaseTester):
# With the true H[2, 2] = 1 the returned entry is 1.
assert (fit(p2)[0, 2, 2] - 1.0).abs() < 1e-4
- # #4874: H is divided by H[2, 2] + 1e-8, and the unnormalised entry here is a few 1e-6, so the returned
- # H[2, 2] misses 1 by about 2e-3. Once the divisor is H[2, 2] itself, it is 1.
- assert (fit(p2_small)[0, 2, 2] - 1.0).abs() > 1e-3
+ # #4874: divide by H[2, 2] itself even when the unnormalised entry is only a few 1e-6.
+ h22 = fit(p2_small)[0, 2, 2]
+ self.assert_close(h22, torch.ones_like(h22), rtol=0.0, atol=1e-6)
@pytest.mark.parametrize("solver", ["lu", "svd"])
def test_wart_find_homography_dlt_zero_weight_moves_normalisation_4890(self, solver, device, dtype):