π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): return the homography for exact correspondences in find_homography_dlt's LU solver (#5648)
Niansia15b6edf01590
diff --git a/changelog.d/5648.fixed.md b/changelog.d/5648.fixed.mdnew file mode 100644index 000000000..5ab370ff0--- /dev/null+++ b/changelog.d/5648.fixed.md@@ -0,0 +1,8 @@+`kornia.geometry.homography.find_homography_dlt` with the default `solver="lu"` and five or more points, and+`find_homography_dlt_iterated`, return the homography instead of an all-NaN matrix on exact correspondences+whose normal matrix has an exactly zero last LU pivot, such as identical point sets, integer shifts and exact+90-degree rotations of integer keypoints. How often that happens depends on the BLAS and LAPACK in use: 98 of 500+random sets of 10 integer keypoints with an integer shift on the reporter's Windows machine, 6 of 500 on macOS arm64.+Only the last pivot being zero means the system has rank 8, so the homography is unique; it now matches+`solver="svd"` and `cv2.findHomography`. Systems with an earlier zero pivot, such as coincident points, still+give NaN.diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.pyindex e4c50d55d..2585a9d7c 100644--- a/kornia/geometry/homography.py+++ b/kornia/geometry/homography.py@@ -559,6 +559,35 @@ def _homography_dlt_system(return A, transform1, transform2+def _rank8_null_vector(normal: torch.Tensor) -> torch.Tensor:+ """Null vector of a ``(B, 9, 9)`` DLT normal matrix whose LU has only its last pivot zero, else NaN.++ Only the last pivot being zero means the first eight columns are independent, so the null vector has+ ``h[8] != 0`` and, the matrix being symmetric, its leading 8x8 block is non-singular: fixing ``h[8] = 1``+ leaves that block's system, solved with ``normal`` itself so the result stays differentiable. Roundoff+ can leave a degenerate matrix with tiny non-zero pivots instead, so the first eight must also be above+ ``sqrt(eps)`` relative to the largest. On the integer keypoints of the tests (exact identities, shifts+ and 90-degree rotations) the smallest stayed above ``4e-2``; on coincident or collinear points it was+ below ``1e-6``. Non-finite matrices are factorized as zeros (see #4770) and give NaN.+ """+ work_dtype = torch.float64 if normal.dtype == torch.float64 else torch.float32+ normal = normal.to(work_dtype)+ finite = normal.isfinite().flatten(1).all(-1)+ normal = torch.where(finite[:, None, None], normal, torch.zeros_like(normal))+ lu, _, info = torch.linalg.lu_factor_ex(normal.detach())+ diagonal = lu.diagonal(dim1=-2, dim2=-1).abs()+ tiny = torch.finfo(work_dtype).tiny+ leading = diagonal[:, :8].amin(-1) > diagonal.amax(-1).clamp_min(tiny) * torch.finfo(work_dtype).eps ** 0.5+ rank8 = finite & (info == normal.shape[-1]) & leading+ # Rows that are not rank 8 solve the identity against zero, so their (discarded) values and gradients+ # stay finite and cannot leak NaN into parameters shared with the rest of the batch.+ block = torch.where(rank8[:, None, None], normal[:, :8, :8], torch.eye(8, device=normal.device, dtype=work_dtype))+ rhs = torch.where(rank8[:, None], -normal[:, :8, 8], torch.zeros_like(normal[:, :8, 8]))+ head = torch.linalg.solve_ex(block, rhs)[0]+ null = torch.cat([head, torch.ones_like(head[:, :1])], -1)+ return torch.where(rank8[:, None], null, torch.full_like(null, float("nan")))++def _homography_from_dlt_system(A: torch.Tensor,weights: Optional[torch.Tensor],@@ -601,9 +630,14 @@ def _homography_from_dlt_system(if not minimal_lu:B = torch.ones(A.shape[0], A.shape[1], device=device, dtype=dtype)sol, _, valid = safe_solve_with_mask(B, A)- # A singular normal matrix (degenerate points) has no solution: report it as NaN rather- # than the identity system's solution that ``safe_solve_with_mask`` leaves in its place.- sol = torch.where(valid[:, None, None], sol, torch.full_like(sol, float("nan")))+ # Exact correspondences leave the normal matrix singular, and its null vector is the homography.+ # Roundoff usually keeps the LU pivots non-zero and the solve above lands on that vector, but an+ # exactly zero last pivot (identical point sets after Hartley normalization, an integer shift)+ # makes the solve fail. With only that pivot zero the rank is 8, so the homography is unique and+ # the leading 8x8 block determines it with h[8] = 1. Any other singular system (an earlier zero+ # pivot, as for coincident points) has no unique homography: report it as NaN rather than the+ # identity system's solution that ``safe_solve_with_mask`` leaves in its place.+ sol = torch.where(valid[:, None, None], sol, _rank8_null_vector(A).to(sol.dtype)[..., None])else:# A four-point sample gives eight equations for nine unknowns, so the normal matrix# is singular and LU-factoring it is what produced all-NaN homographies. Work fromdiff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.pyindex 56b4f1e51..c1d39caa6 100644--- a/tests/geometry/test_homography.py+++ b/tests/geometry/test_homography.py@@ -27,7 +27,9 @@ from kornia.geometry.epipolar import normalize_pointsfrom kornia.geometry.homography import (_four_point_homography,_homography_design_rows,+ _homography_from_dlt_system,_oneway_transfer_error_shared_impl_,+ _rank8_null_vector,_transfer_basis,_transfer_errors,_transfer_from_basis,@@ -538,6 +540,78 @@ class TestFindHomographyDLT(BaseTester):H = find_homography_dlt(points, points, solver="lu")assert H.isnan().all().item()+ @pytest.mark.parametrize(+ ("points", "linear", "shift"),+ [+ # identical point sets: the Hartley-normalized systems are bitwise equal+ ([[140, 30], [130, 40], [0, 120], [150, 110], [120, 180], [20, 40]], [[1, 0], [0, 1]], [0, 0]),+ ([[140, 30], [130, 40], [0, 120], [150, 110], [120, 180], [20, 40]], [[1, 0], [0, 1]], [3, -5]),+ ([[122, 119], [0, 180], [173, 155], [105, 57], [180, 19], [14, 118]], [[0, -1], [1, 0]], [0, 0]),+ ],+ )+ def test_exact_correspondences_lu(self, points, linear, shift, device, dtype):+ # On these exact correspondences the last LU pivot of the normal matrix is exactly zero with some BLAS+ # and LAPACK builds (float32 and float64 on Windows x86), not with others (macOS arm64), so they pin the+ # fix only where it shows; test_exact_rank8_system_lu_gives_the_homography_5644 pins it on every backend.+ # The homography is still unique (rank 8), so the LU solver has to return it, as the+ # SVD solver and cv2.findHomography(points1, points2, 0) do, rather than NaN. Six points in general+ # position determine it, so it is checked through the points it maps (MPS float32 gets the pixel-unit+ # translation of the 90-degree rotation to about 2e-4).+ _skip_half(dtype, _HALF_DLT)+ points1 = torch.tensor([points], device=device, dtype=dtype)+ linear_part = torch.tensor(linear, device=device, dtype=dtype)+ points2 = points1 @ linear_part.T + torch.tensor(shift, device=device, dtype=dtype)+ weights = torch.ones(1, 6, device=device, dtype=dtype)+ for H in (+ find_homography_dlt(points1, points2, solver="lu"),+ find_homography_dlt_iterated(points1, points2, weights),+ ):+ assert H.isfinite().all().item()+ self.assert_close(kornia.geometry.transform_points(H, points1), points2, rtol=1e-4, atol=1e-3)++ def test_collinear_points_lu_give_nan(self, device, dtype):+ # Roundoff can leave the normal matrix of collinear points with tiny non-zero leading pivots and a+ # zero last one, which must not be taken for the unique homography of exact correspondences.+ points = torch.tensor(+ [[[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]]], device=device, dtype=dtype+ )+ assert find_homography_dlt(points, points, solver="lu").isnan().all().item()++ @pytest.mark.parametrize("weights", [None, [1.0, 3.0, 2.0, 0.5, 3.0, 1.0, 2.0, 3.5]])+ def test_exact_rank8_system_lu_gives_the_homography_5644(self, weights, device, dtype):+ # Whether the normal matrix of real correspondences gets an exactly zero last LU pivot depends on the+ # rounding of the BLAS and LAPACK in use. This design matrix has entries -1, 0 and 1 (the corners of the+ # normalized square, each twice, turned by 90 degrees), so its normal matrix is integer and its pivoted LU+ # is exact on every backend: pivots 8 (16 with these weights, which give every corner the same total)+ # and a last one of 0. The rank is 8, so the homography is unique, and the LU solver must return it.+ _skip_half(dtype, _HALF_DLT)+ corners = torch.tensor([[1.0, 1.0], [-1.0, 1.0], [-1.0, -1.0], [1.0, -1.0]] * 2, device=device, dtype=dtype)+ rotation = torch.tensor([[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype)+ A = _homography_design_rows(corners[None], (corners @ rotation[:2, :2].T)[None])+ w = None if weights is None else torch.tensor([weights], device=device, dtype=dtype)+ eye = torch.eye(3, device=device, dtype=dtype)[None]+ H = _homography_from_dlt_system(A, w, eye, eye, "lu", torch.device(device), dtype)+ assert torch.equal(H, rotation[None])++ def test_rank8_fallback_needs_leading_pivots_above_sqrt_eps_5644(self, device, dtype):+ # Roundoff can give a degenerate normal matrix an exactly zero last pivot and tiny non-zero leading ones, so+ # the fallback takes a zero last pivot for rank 8 only when the other pivots are above ``sqrt(eps)`` of the+ # largest. ``L diag(1, ..., 1, tau, 0) L^T`` with ``L[8, :8] = 1/2`` has an exact LU with exactly those+ # pivots and the null vector ``(-1/2, ..., -1/2, 1)``: returned for ``tau`` just above the bound, NaN just+ # below it, where ``eps`` itself would still accept it.+ _skip_half(dtype, _HALF_DLT)+ bound = 26 if dtype == torch.float64 else 11 # sqrt(eps) is 2 ** -26 (float64) or 2 ** -11.5 (float32)+ null = torch.tensor([-0.5] * 8 + [1.0], device=device, dtype=dtype)+ normals = []+ for tau in (2.0 ** -(bound - 2), 2.0 ** -(bound + 2)):+ L = torch.eye(9, device=device, dtype=dtype)+ L[8, :8] = 0.5+ d = torch.tensor([1.0] * 7 + [tau, 0.0], device=device, dtype=dtype)+ normals.append(L @ torch.diag(d) @ L.T)+ result = _rank8_null_vector(torch.stack(normals))+ assert torch.equal(result[0], null)+ assert result[1].isnan().all()+@pytest.mark.parametrize("solver", ["svd", "lu"])def test_singular_normalization_gives_nan(self, device, dtype, solver):# A spread whose squared radius overflows gives points2 a zero Hartley scale and a singular