🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
clean version of fast ransac (#3458)
Dmytro Mishkine9e93584c7e5
diff --git a/kornia/geometry/epipolar/__init__.py b/kornia/geometry/epipolar/__init__.pyindex 48b2a10c3..f065d0db7 100644--- a/kornia/geometry/epipolar/__init__.py+++ b/kornia/geometry/epipolar/__init__.py@@ -15,11 +15,6 @@# limitations under the License.#-"""Kornia Geometry Epipolar — Epipolar geometry operations for Kornia.--This subpackage provides functions for epipolar distance, fundamental matrices, and stereo vision.-"""-from ._metrics import (left_to_right_epipolar_distance,right_to_left_epipolar_distance,diff --git a/kornia/geometry/epipolar/_metrics.py b/kornia/geometry/epipolar/_metrics.pyindex 5c1a8a31c..8b7c8d0b0 100644--- a/kornia/geometry/epipolar/_metrics.py+++ b/kornia/geometry/epipolar/_metrics.py@@ -17,14 +17,15 @@"""Module including useful metrics for Structure from Motion."""-from torch import Tensor+import torch+from torch import Tensor, ones_likefrom kornia.core.check import KORNIA_CHECK_IS_TENSORfrom kornia.geometry.conversions import convert_points_to_homogeneousfrom kornia.geometry.linalg import point_line_distance-def sampson_epipolar_distance(+def _sampson_epipolar_distance_manual_impl_(pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool = True, eps: float = 1e-8) -> Tensor:"""Return Sampson distance for correspondences given the fundamental matrix.@@ -48,6 +49,64 @@ def sampson_epipolar_distance(if (len(Fm.shape) < 3) or not Fm.shape[-2:] == (3, 3):raise ValueError(f"Fm must be a (*, 3, 3) tensor. Got {Fm.shape}")+ # Extract coords; support 2D (w=1) and 3D homogeneous+ x = pts1[..., :, 0]+ y = pts1[..., :, 1]+ u = pts2[..., :, 0]+ v = pts2[..., :, 1]+ # homogeneous weights with correct dtype/shape+ w1 = pts1[..., :, 2] if pts1.shape[-1] == 3 else ones_like(x)+ w2 = pts2[..., :, 2] if pts2.shape[-1] == 3 else ones_like(u)++ # Grab F entries and add a length-1 axis to broadcast across N+ f00 = Fm[..., 0, 0][..., None]+ f01 = Fm[..., 0, 1][..., None]+ f02 = Fm[..., 0, 2][..., None]+ f10 = Fm[..., 1, 0][..., None]+ f11 = Fm[..., 1, 1][..., None]+ f12 = Fm[..., 1, 2][..., None]+ f20 = Fm[..., 2, 0][..., None]+ f21 = Fm[..., 2, 1][..., None]+ f22 = Fm[..., 2, 2][..., None]++ # Fx = F @ [x,y,w1]+ Fx0 = f00 * x + f01 * y + f02 * w1+ Fx1 = f10 * x + f11 * y + f12 * w1+ Fx2 = f20 * x + f21 * y + f22 * w1++ # (F^T x')_{1:2} for x' = [u,v,w2]+ # (first two coordinates only)+ Ft0 = f00 * u + f10 * v + f20 * w2 # (F^T x')_0+ Ft1 = f01 * u + f11 * v + f21 * w2 # (F^T x')_1++ # Numerator: (x'^T F x)^2 = (u*Fx0 + v*Fx1 + w2*Fx2)^2+ num = (u * Fx0 + v * Fx1 + w2 * Fx2) ** 2+ # Denominator: ||(F x)_{1:2}||^2 + ||(F^T x')_{1:2}||^2+ den = Fx0 * Fx0 + Fx1 * Fx1 + Ft0 * Ft0 + Ft1 * Ft1 + eps+ out: Tensor = num / den+ if squared:+ return out+ return (out + eps).sqrt()+++def _sampson_epipolar_distance_matmul_impl_(+ pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool = True, eps: float = 1e-8+) -> Tensor:+ """Return Sampson distance for correspondences given the fundamental matrix.++ Args:+ pts1: correspondences from the left images with shape :math:`(*, N, (2|3))`. If they are not homogeneous,+ converted automatically.+ pts2: correspondences from the right images with shape :math:`(*, N, (2|3))`. If they are not homogeneous,+ converted automatically.+ Fm: Fundamental matrices with shape :math:`(*, 3, 3)`. Called Fm to avoid ambiguity with torch.nn.functional.+ squared: if True (default), the squared distance is returned.+ eps: Small constant for safe sqrt.++ Returns:+ the computed Sampson distance with shape :math:`(*, N)`.++ """if pts1.shape[-1] == 2:pts1 = convert_points_to_homogeneous(pts1)@@ -76,53 +135,108 @@ def sampson_epipolar_distance(return (out + eps).sqrt()-def symmetrical_epipolar_distance(- pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool = True, eps: float = 1e-8+def sampson_epipolar_distance(+ pts1: Tensor,+ pts2: Tensor,+ Fm: Tensor,+ squared: bool = True,+ eps: float = 1e-8,+ use_matmul_at_less_than_points: int = 10000,) -> Tensor:- """Return symmetrical epipolar distance for correspondences given the fundamental matrix.+ """Return Sampson distance for correspondences given the fundamental matrix.Args:- pts1: correspondences from the left images with shape :math:`(*, N, (2|3))`. If they are not homogeneous,- converted automatically.- pts2: correspondences from the right images with shape :math:`(*, N, (2|3))`. If they are not homogeneous,- converted automatically.- Fm: Fundamental matrices with shape :math:`(*, 3, 3)`. Called Fm to avoid ambiguity with torch.nn.functional.- squared: if True (default), the squared distance is returned.- eps: Small constant for safe sqrt.+ pts1: correspondences from the left images with shape :math:`(*, N, (2|3))`. If they are not homogeneous,+ converted automatically.+ pts2: correspondences from the right images with shape :math:`(*, N, (2|3))`. If they are not homogeneous,+ converted automatically.+ Fm: Fundamental matrices with shape :math:`(*, 3, 3)`. Called Fm to avoid ambiguity with torch.nn.functional.+ squared: if True (default), the squared distance is returned.+ eps: Small constant for safe sqrt.+ use_matmul_at_less_than_points: If the number of points is less than this value, use the matmul implementation.Returns:- the computed Symmetrical distance with shape :math:`(*, N)`.+ the computed Sampson distance with shape :math:`(*, N)`."""+ if Fm.device.type == "cuda":+ num_points = pts1.shape[-2]+ if num_points < use_matmul_at_less_than_points:+ return _sampson_epipolar_distance_matmul_impl_(pts1, pts2, Fm, squared, eps)+ return _sampson_epipolar_distance_manual_impl_(pts1, pts2, Fm, squared, eps)+++def _symmetrical_epipolar_distance_manual_impl_(+ pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool = True, eps: float = 1e-8+) -> Tensor:+ """Return symmetric epipolar distance for correspondences given the fundamental matrix (CPU-optimized)."""if not isinstance(Fm, Tensor):raise TypeError(f"Fm type is not a torch.Tensor. Got {type(Fm)}")- if (len(Fm.shape) < 3) or not Fm.shape[-2:] == (3, 3):+ if (len(Fm.shape) < 3) or Fm.shape[-2:] != (3, 3):raise ValueError(f"Fm must be a (*, 3, 3) tensor. Got {Fm.shape}")+ # Extract coords; support 2D (w=1) and 3D homogeneous+ x = pts1[..., :, 0]+ y = pts1[..., :, 1]+ u = pts2[..., :, 0]+ v = pts2[..., :, 1]++ # homogeneous weights with correct dtype/shape+ w1 = pts1[..., :, 2] if pts1.shape[-1] == 3 else ones_like(x)+ w2 = pts2[..., :, 2] if pts2.shape[-1] == 3 else ones_like(u)++ # Grab F entries and add a length-1 axis to broadcast across N+ f00 = Fm[..., 0, 0][..., None]+ f01 = Fm[..., 0, 1][..., None]+ f02 = Fm[..., 0, 2][..., None]+ f10 = Fm[..., 1, 0][..., None]+ f11 = Fm[..., 1, 1][..., None]+ f12 = Fm[..., 1, 2][..., None]+ f20 = Fm[..., 2, 0][..., None]+ f21 = Fm[..., 2, 1][..., None]+ f22 = Fm[..., 2, 2][..., None]++ # Fx = F @ [x, y, w1]^T (compute components explicitly)+ Fx0 = f00 * x + f01 * y + f02 * w1+ Fx1 = f10 * x + f11 * y + f12 * w1+ Fx2 = f20 * x + f21 * y + f22 * w1++ # (F^T x')_{0:1} for x' = [u, v, w2]+ Ft0 = f00 * u + f10 * v + f20 * w2 # (F^T x')_0+ Ft1 = f01 * u + f11 * v + f21 * w2 # (F^T x')_1++ # Numerator: (x'^T F x)^2 = (u*Fx0 + v*Fx1 + w2*Fx2)^2+ num = (u * Fx0 + v * Fx1 + w2 * Fx2).pow(2)++ # denominator_inv = 1/|| (F x)_{1:2} ||^2 + 1/|| (F^T x')_{1:2} ||^2+ inv1 = 1.0 / (Fx0.pow(2) + Fx1.pow(2) + eps)+ inv2 = 1.0 / (Ft0.pow(2) + Ft1.pow(2) + eps)+ den_inv = inv1 + inv2++ out: Tensor = num * den_inv+ if squared:+ return out+ return (out + eps).sqrt()+++def _symmetrical_epipolar_distance_matmul_impl_(+ pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool = True, eps: float = 1e-8+) -> Tensor:if pts1.shape[-1] == 2:pts1 = convert_points_to_homogeneous(pts1)-if pts2.shape[-1] == 2:pts2 = convert_points_to_homogeneous(pts2)- # From Hartley and Zisserman, symmetric epipolar distance (11.10)- # sed = (x'^T F x) ** 2 / (((Fx)_1**2) + (Fx)_2**2)) + 1/ (((F^Tx')_1**2) + (F^Tx')_2**2))-- # line1_in_2 = (F @ pts1.transpose(dim0=-2, dim1=-1)).transpose(dim0=-2, dim1=-1)- # line2_in_1 = (F.transpose(dim0=-2, dim1=-1) @ pts2.transpose(dim0=-2, dim1=-1)).transpose(dim0=-2, dim1=-1)-- # Instead we can just transpose F once and switch the order of multiplicationF_t: Tensor = Fm.transpose(dim0=-2, dim1=-1)line1_in_2: Tensor = pts1 @ F_tline2_in_1: Tensor = pts2 @ Fm- # numerator = (x'^T F x) ** 2numerator: Tensor = (pts2 * line1_in_2).sum(dim=-1).pow(2)- # denominator_inv = 1/ (((Fx)_1**2) + (Fx)_2**2)) + 1/ (((F^Tx')_1**2) + (F^Tx')_2**2))- denominator_inv: Tensor = 1.0 / (line1_in_2[..., :2].norm(2, dim=-1).pow(2)) + 1.0 / (- line2_in_1[..., :2].norm(2, dim=-1).pow(2)+ denominator_inv: Tensor = 1.0 / (line1_in_2[..., :2].norm(2, dim=-1).pow(2) + eps) + 1.0 / (+ line2_in_1[..., :2].norm(2, dim=-1).pow(2) + eps)out: Tensor = numerator * denominator_invif squared:@@ -130,6 +244,31 @@ def symmetrical_epipolar_distance(return (out + eps).sqrt()+def symmetrical_epipolar_distance(+ pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool = True, eps: float = 1e-8+) -> Tensor:+ """Return symmetrical epipolar distance for correspondences given the fundamental matrix.++ Args:+ pts1: correspondences from the left images with shape :math:`(*, N, (2|3))`. If they are not homogeneous,+ converted automatically.+ pts2: correspondences from the right images with shape :math:`(*, N, (2|3))`. If they are not homogeneous,+ converted automatically.+ Fm: Fundamental matrices with shape :math:`(*, 3, 3)`. Called Fm to avoid ambiguity with torch.nn.functional.+ squared: if True (default), the squared distance is returned.+ eps: Small constant for safe sqrt.++ Returns:+ the computed Symmetrical distance with shape :math:`(*, N)`.++ """+ if Fm.device.type == "cuda":+ num_points = pts1.shape[-2]+ if num_points < 10000:+ return _symmetrical_epipolar_distance_matmul_impl_(pts1, pts2, Fm, squared, eps)+ return _symmetrical_epipolar_distance_manual_impl_(pts1, pts2, Fm, squared, eps)++def left_to_right_epipolar_distance(pts1: Tensor, pts2: Tensor, Fm: Tensor) -> Tensor:r"""Return one-sided epipolar distance for correspondences given the fundamental matrix.diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.pyindex c5579eeb9..9e97ef657 100644--- a/kornia/geometry/epipolar/essential.py+++ b/kornia/geometry/epipolar/essential.py@@ -15,7 +15,7 @@# limitations under the License.#-"""nn.Module containing functionalities for the Essential matrix."""+"""Module containing functionalities for the Essential matrix."""from typing import Optional, Tuple@@ -23,8 +23,8 @@ import torchfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPEfrom kornia.core.ops import eye_like, vec_like-from kornia.core.utils import _torch_solve_cast, _torch_svd_cast-from kornia.geometry import solvers+from kornia.core.utils import _torch_svd_cast+from kornia.geometry.solvers.polynomial_solver import T_deg1, T_deg2, coefficient_map, multiplication_indices, signsfrom .numeric import cross_product_matrix, matrix_cofactor_tensorfrom .projection import depth_from_point, projection_from_KRt@@ -49,232 +49,379 @@ def run_5point(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[tand the solver implemented referred to [@barath2020magsac++][@wei2023generalized][@wang2023vggsfm].Args:- points1: A set of carlibrated points in the first image with a torch.tensor shape :math:`(B, N, 2), N>=8`.- points2: A set of points in the second image with a torch.tensor shape :math:`(B, N, 2), N>=8`.- weights: torch.Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.+ points1: A set of carlibrated points in the first image with a tensor shape :math:`(B, N, 2), N>=8`.+ points2: A set of points in the second image with a tensor shape :math:`(B, N, 2), N>=8`.+ weights: Not used, kept for compatibility.Returns:- the computed essential matrix with shape :math:`(B, 3, 3)`.+ the computed essential matrix with shape :math:`(B, 10, 3, 3)`."""KORNIA_CHECK_SHAPE(points1, ["B", "N", "2"])KORNIA_CHECK_SAME_SHAPE(points1, points2)KORNIA_CHECK(points1.shape[1] >= 5, "Number of points should be >=5")- if weights is not None:- KORNIA_CHECK_SAME_SHAPE(points1[:, :, 0], weights)batch_size, _, _ = points1.shape- x1, y1 = torch.chunk(points1, dim=-1, chunks=2) # Bx1xN- x2, y2 = torch.chunk(points2, dim=-1, chunks=2) # Bx1xN- ones_tensor = torch.ones_like(x1)-+ x1, y1 = points1[..., 0:1], points1[..., 1:2]+ x2, y2 = points2[..., 0:1], points2[..., 1:2]+ ones = torch.ones_like(x1)# build the equation system and find the null space.# https://www.cc.gatech.edu/~afb/classes/CS4495-Fall2013/slides/CS4495-09-TwoViews-2.pdf# [x * x', x * y', x, y * x', y * y', y, x', y', 1]# BxNx9- X = torch.cat([x1 * x2, x1 * y2, x1, y1 * x2, y1 * y2, y1, x2, y2, ones_tensor], dim=-1)-- # apply the weights to the linear system- if weights is None:- X = X.transpose(-2, -1) @ X- else:- w_diag = torch.diag_embed(weights)- X = X.transpose(-2, -1) @ w_diag @ X-+ X = torch.cat([x1 * x2, x1 * y2, x1, y1 * x2, y1 * y2, y1, x2, y2, ones], dim=-1)# use Nister's 5PC to solve essential matrix- E_Nister = null_to_Nister_solution(X, batch_size)+ E = null_to_Nister_solution(X, batch_size)+ bad = torch.isnan(E).all(dim=(-1, -2)).all(dim=-1) # (B,)+ if bad.any():+ eye3 = torch.eye(3, device=E.device, dtype=E.dtype).view(1, 1, 3, 3).expand(batch_size, 10, 3, 3)+ E = torch.where(bad.view(batch_size, 1, 1, 1), eye3, E)+ return E- return E_Nister+def _multiply_deg_one_poly(a: torch.Tensor, b: torch.Tensor, T_deg1: torch.Tensor) -> torch.Tensor:+ # a, b: (..., 4)+ product_basis = a.unsqueeze(2) * b.unsqueeze(1) # (..., 4, 4)+ product_vector = product_basis.flatten(start_dim=-2) # (..., 16)+ return product_vector @ T_deg1 # (..., 10)-def fun_select(null_mat: torch.Tensor, i: int, j: int, ratio: int = 3) -> torch.Tensor:- return null_mat[:, ratio * j + i]+def _multiply_deg_two_one_poly(a: torch.Tensor, b: torch.Tensor, T_deg2: torch.Tensor) -> torch.Tensor:+ # a: (..., 10), b: (..., 4)+ product_basis = a.unsqueeze(2) * b.unsqueeze(1) # (..., 10, 4)+ product_vector = product_basis.flatten(start_dim=-2) # (..., 40)+ return product_vector @ T_deg2 # (..., 20)-def null_to_Nister_solution(X: torch.Tensor, batch_size: int) -> torch.Tensor:- r"""Use Nister's 5PC to solve essential matrix.- The linear system is solved by Nister's 5-point algorithm [@nister2004efficient],- and the solver implemented referred to [@barath2020magsac++][@wei2023generalized][@wang2023vggsfm].+def _determinant_to_polynomial_jit(+ A: torch.Tensor,+ multiplication_indices: torch.Tensor,+ signs: torch.Tensor,+ coefficient_map: torch.Tensor,+) -> torch.Tensor:+ # A: (B, 3, 13) -> (B, 11)+ B = A.shape[0]+ A_flat = A.view(B, -1) # (B, 39)- Args:- X: Coefficients for the null space :math:`(B, N, 2), N>=8`.- batch_size: batcs size of the input, the number of image pairs :math:`B`.+ gathered_values = A_flat[:, multiplication_indices] # (B, 486, 3)+ products = torch.prod(gathered_values, dim=-1) # (B, 486)+ signed_products = products * signs # (B, 486)- Returns:- the computed essential matrix with shape :math:`(B, 3, 3)`.- Note that the returned E matrices should be the same batch size with the input.+ cs = torch.zeros(B, 11, device=A.device, dtype=A.dtype)+ batch_coefficient_map = coefficient_map.unsqueeze(0).expand(B, -1) # (B, 486)+ cs.scatter_add_(1, batch_coefficient_map, signed_products)+ return cs- """- # compute eigenvectors and retrieve the one with the smallest eigenvalue, using SVD- # turn off the grad check due to the unstable gradients from SVD.- # several close to zero values of eigenvalues.- _, _, V = _torch_svd_cast(X) # torch.svd- null_ = V[:, :, -4:] # the last four rows- nullSpace = V.transpose(-1, -2)[:, -4:, :]+def _solve_2x2_tikhonov_safe(A: torch.Tensor, b: torch.Tensor, eps: float = 1e-12) -> Tuple[torch.Tensor, torch.Tensor]:+ r"""Solve (A)x=b for A (...,2,2), b (...,2,1) using Tikhonov regularization.- coeffs = torch.zeros(batch_size, 10, 20, device=null_.device, dtype=null_.dtype)- d = torch.zeros(batch_size, 60, device=null_.device, dtype=null_.dtype)+ Uses the following methods:+ - direct inverse when det is OK+ - otherwise solve normal equations (A^T A + λI)x = A^T b (λ from trace scale)+ Never throws. Returns (x, bad) where bad marks ill-conditioned A.+ """+ a = A[..., 0, 0]+ bb = A[..., 0, 1]+ c = A[..., 1, 0]+ d = A[..., 1, 1]++ det = a * d - bb * c+ det_abs = det.abs()+ bad = (det_abs <= eps) | torch.isnan(det_abs) | torch.isinf(det_abs)++ # ---- direct inverse branch (but branchless via where) ----+ det_safe = torch.where(det_abs > eps, det, torch.ones_like(det) * eps)+ inv_det = 1.0 / det_safe++ inv00 = d * inv_det+ inv01 = (-bb) * inv_det+ inv10 = (-c) * inv_det+ inv11 = a * inv_det++ x0_dir = inv00 * b[..., 0, 0] + inv01 * b[..., 1, 0]+ x1_dir = inv10 * b[..., 0, 0] + inv11 * b[..., 1, 0]+ x_dir = torch.stack((x0_dir, x1_dir), dim=-1).unsqueeze(-1) # (...,2,1)++ # ---- fallback: normal equations with λI (always SPD if λ>0) ----+ # ATA = A^T A, ATb = A^T b+ # ATA = [[a^2 + c^2, a*bb + c*d],+ # [a*bb + c*d, bb^2 + d^2]]+ ata00 = a * a + c * c+ ata01 = a * bb + c * d+ ata11 = bb * bb + d * d++ atb0 = a * b[..., 0, 0] + c * b[..., 1, 0]+ atb1 = bb * b[..., 0, 0] + d * b[..., 1, 0]++ # λ from trace scale; ensure strictly positive even if A is zero+ tr = ata00 + ata11+ lam = (tr * 1e-8).clamp_min(eps)++ m00 = ata00 + lam+ m01 = ata01+ m10 = ata01+ m11 = ata11 + lam++ det_m = m00 * m11 - m01 * m10+ det_m_safe = det_m.abs().clamp_min(eps)+ inv_det_m = 1.0 / det_m_safe++ invm00 = m11 * inv_det_m+ invm01 = (-m01) * inv_det_m+ invm10 = (-m10) * inv_det_m+ invm11 = m00 * inv_det_m++ x0_fb = invm00 * atb0 + invm01 * atb1+ x1_fb = invm10 * atb0 + invm11 * atb1+ x_fb = torch.stack((x0_fb, x1_fb), dim=-1).unsqueeze(-1) # (...,2,1)++ # choose fallback only when bad; else direct+ x = torch.where(bad.unsqueeze(-1).unsqueeze(-1), x_fb, x_dir)++ # if still non-finite, mark bad and zero it+ nonfinite = torch.isnan(x).any(dim=(-2, -1)) | torch.isinf(x).any(dim=(-2, -1))+ bad = bad | nonfinite+ x = torch.where(bad.unsqueeze(-1).unsqueeze(-1), torch.zeros_like(x), x)++ return x, bad+++# --- fun_select inline, to keep it JIT-simple ---+def _fun_select(mat: torch.Tensor, i: int, j: int, ratio: int = 3) -> torch.Tensor:+ return mat[:, ratio * j + i]+++def _null_to_Nister_solution_script(+ X: torch.Tensor,+ batch_size: int,+ T_deg1: torch.Tensor,+ T_deg2: torch.Tensor,+ multiplication_indices: torch.Tensor,+ signs: torch.Tensor,+ coefficient_map: torch.Tensor,+ idx_ij: torch.Tensor, # kept for signature compatibility (unused)+ i_idx: torch.Tensor,+ j_idx: torch.Tensor,+ idx3: torch.Tensor,+ top_idx: torch.Tensor,+ bot_idx: torch.Tensor,+) -> torch.Tensor:+ original_dtype = X.dtype++ _, _, V = _torch_svd_cast(X) # V: (B, 9, 9)+ null_ = V[:, :, -4:].contiguous() # (B, 9, 4)+ nullSpace = V.transpose(-1, -2)[:, -4:, :] # (B, 4, 9)++ B = batch_size+ device = X.device+ dtype = X.dtype++ coeffs = torch.zeros(B, 10, 20, device=device, dtype=dtype)++ # (B,9,4) -> (B,3,3,4) with column-major fix+ null_ij = null_.view(B, 3, 3, 4).transpose(1, 2).contiguous() # (B, 3, 3, 4)++ # ---- determinant constraint ----+ n00 = null_ij[:, 0, 0, :]+ n01 = null_ij[:, 0, 1, :]+ n02 = null_ij[:, 0, 2, :]+ n10 = null_ij[:, 1, 0, :]+ n11 = null_ij[:, 1, 1, :]+ n12 = null_ij[:, 1, 2, :]+ n20 = null_ij[:, 2, 0, :]+ n21 = null_ij[:, 2, 1, :]+ n22 = null_ij[:, 2, 2, :]++ # small reuse to reduce launches+ p01_12 = _multiply_deg_one_poly(n01, n12, T_deg1)+ p02_11 = _multiply_deg_one_poly(n02, n11, T_deg1)+ p02_10 = _multiply_deg_one_poly(n02, n10, T_deg1)+ p00_12 = _multiply_deg_one_poly(n00, n12, T_deg1)+ p00_11 = _multiply_deg_one_poly(n00, n11, T_deg1)+ p01_10 = _multiply_deg_one_poly(n01, n10, T_deg1)- # Determinant constraintcoeffs[:, 9] = (- solvers.multiply_deg_two_one_poly(- solvers.multiply_deg_one_poly(fun_select(null_, 0, 1), fun_select(null_, 1, 2))- - solvers.multiply_deg_one_poly(fun_select(null_, 0, 2), fun_select(null_, 1, 1)),- fun_select(null_, 2, 0),- )- + solvers.multiply_deg_two_one_poly(- solvers.multiply_deg_one_poly(fun_select(null_, 0, 2), fun_select(null_, 1, 0))- - solvers.multiply_deg_one_poly(fun_select(null_, 0, 0), fun_select(null_, 1, 2)),- fun_select(null_, 2, 1),- )- + solvers.multiply_deg_two_one_poly(- solvers.multiply_deg_one_poly(fun_select(null_, 0, 0), fun_select(null_, 1, 1))- - solvers.multiply_deg_one_poly(fun_select(null_, 0, 1), fun_select(null_, 1, 0)),- fun_select(null_, 2, 2),- )+ _multiply_deg_two_one_poly(p01_12 - p02_11, n20, T_deg2)+ + _multiply_deg_two_one_poly(p02_10 - p00_12, n21, T_deg2)+ + _multiply_deg_two_one_poly(p00_11 - p01_10, n22, T_deg2))- indices = torch.tensor([[0, 10, 20], [10, 40, 30], [20, 30, 50]])-- # Compute EE^T (Eqn. 20 in the paper)- for i in range(3):- for j in range(3):- d[:, indices[i, j] : indices[i, j] + 10] = (- solvers.multiply_deg_one_poly(fun_select(null_, i, 0), fun_select(null_, j, 0))- + solvers.multiply_deg_one_poly(fun_select(null_, i, 1), fun_select(null_, j, 1))- + solvers.multiply_deg_one_poly(fun_select(null_, i, 2), fun_select(null_, j, 2))- )-- for i in range(10):- t = 0.5 * (d[:, indices[0, 0] + i] + d[:, indices[1, 1] + i] + d[:, indices[2, 2] + i])- d[:, indices[0, 0] + i] -= t- d[:, indices[1, 1] + i] -= t- d[:, indices[2, 2] + i] -= t-- cnt = 0- for i in range(3):- for j in range(3):- row = (- solvers.multiply_deg_two_one_poly(d[:, indices[i, 0] : indices[i, 0] + 10], fun_select(null_, 0, j))- + solvers.multiply_deg_two_one_poly(d[:, indices[i, 1] : indices[i, 1] + 10], fun_select(null_, 1, j))- + solvers.multiply_deg_two_one_poly(d[:, indices[i, 2] : indices[i, 2] + 10], fun_select(null_, 2, j))- )- coeffs[:, cnt] = row- cnt += 1-- b = coeffs[:, :, 10:]- singular_filter = torch.linalg.matrix_rank(coeffs[:, :, :10]) >= torch.max(- torch.linalg.matrix_rank(coeffs), torch.ones_like(torch.linalg.matrix_rank(coeffs[:, :, :10])) * 10- )+ # ---- EE^T constraints ----+ a_data = null_ij[:, i_idx, :, :] # (B,9,3,4)+ b_data = null_ij[:, j_idx, :, :] # (B,9,3,4)+ prods = _multiply_deg_one_poly(a_data.reshape(-1, 4), b_data.reshape(-1, 4), T_deg1).view(B, 9, 3, 10)+ D_blocks = prods.sum(dim=2).view(B, 3, 3, 10).contiguous()++ # trace removal+ diag = D_blocks[:, idx3, idx3, :] # (B,3,10)+ t = 0.5 * diag.sum(dim=1, keepdim=True) # (B,1,10)+ D_blocks[:, idx3, idx3, :] = D_blocks[:, idx3, idx3, :] - t++ # first 9 rows of coeffs+ D_for_i = D_blocks[:, i_idx, :, :] # (B,9,3,10)+ Null_for_j = null_ij[:, :, j_idx, :].permute(0, 2, 1, 3).contiguous() # (B,9,3,4)+ prods2 = _multiply_deg_two_one_poly(D_for_i.reshape(-1, 10), Null_for_j.reshape(-1, 4), T_deg2).view(B, 9, 3, 20)+ coeffs[:, :9, :] = prods2.sum(dim=2) # (B,9,20)++ # ---- elimination: solve A10 * X = b_poly ----+ A10 = coeffs[:, :, :10] # (B, 10, 10)+ b_poly = coeffs[:, :, 10:] # (B, 10, 10)++ # Prefer direct solve; if singular, add tiny damping (no batch compaction).+ eye10 = torch.eye(10, device=device, dtype=dtype).unsqueeze(0).expand(B, 10, 10)- # check if there is no solution- if singular_filter.sum() == 0:- return torch.eye(3, dtype=coeffs.dtype, device=coeffs.device)[None].expand(batch_size, 10, -1, -1).clone()+ # Try direct solve first+ eliminated = torch.linalg.solve(A10, b_poly) # (B,10,10)- eliminated_mat = _torch_solve_cast(coeffs[singular_filter, :, :10], b[singular_filter])+ # Detect NaN/Inf from singular solve and fix with damping solve+ bad = torch.isnan(eliminated).any(dim=(-2, -1)) | torch.isinf(eliminated).any(dim=(-2, -1)) # (B,)+ if bad.any():+ # Damped solve only for bad rows but WITHOUT compaction:+ # build damped A = A10 + λI, where λ depends on scale+ # (use per-batch scalar to avoid huge allocations)+ diagA = torch.diagonal(A10, dim1=-2, dim2=-1).abs().mean(dim=-1) # (B,)+ lam = (diagA * 1e-8 + 1e-8).to(dtype) # (B,)+ A_damped = A10 + eye10 * lam.view(B, 1, 1)+ eliminated_d = torch.linalg.solve(A_damped, b_poly)+ eliminated = torch.where(bad.view(B, 1, 1), eliminated_d, eliminated)- coeffs_ = torch.cat((coeffs[singular_filter, :, :10], eliminated_mat), dim=-1)+ coeffs_ = torch.cat((A10, eliminated), dim=-1) # (B,10,20)- # check the batch size after singular filter, for batch operation afterwards- batch_size_filtered = coeffs_.shape[0]+ # ---- build A (B,3,13) ----+ A = torch.zeros(B, 3, 13, device=device, dtype=dtype)- A = torch.zeros(coeffs_.shape[0], 3, 13, device=coeffs_.device, dtype=coeffs_.dtype)+ A[:, :, 1:4] = coeffs_[:, top_idx, 10:13]+ A[:, :, 0:3] = A[:, :, 0:3] - coeffs_[:, bot_idx, 10:13]- for i in range(3):- A[:, i, 0] = 0.0- A[:, i : i + 1, 1:4] = coeffs_[:, 4 + 2 * i : 5 + 2 * i, 10:13]- A[:, i : i + 1, 0:3] -= coeffs_[:, 5 + 2 * i : 6 + 2 * i, 10:13]- A[:, i, 4] = 0.0- A[:, i : i + 1, 5:8] = coeffs_[:, 4 + 2 * i : 5 + 2 * i, 13:16]- A[:, i : i + 1, 4:7] -= coeffs_[:, 5 + 2 * i : 6 + 2 * i, 13:16]- A[:, i, 8] = 0.0- A[:, i : i + 1, 9:13] = coeffs_[:, 4 + 2 * i : 5 + 2 * i, 16:20]- A[:, i : i + 1, 8:12] -= coeffs_[:, 5 + 2 * i : 6 + 2 * i, 16:20]+ A[:, :, 5:8] = coeffs_[:, top_idx, 13:16]+ A[:, :, 4:7] = A[:, :, 4:7] - coeffs_[:, bot_idx, 13:16]- # Bx11- cs = solvers.determinant_to_polynomial(A)+ A[:, :, 9:13] = coeffs_[:, top_idx, 16:20]+ A[:, :, 8:12] = A[:, :, 8:12] - coeffs_[:, bot_idx, 16:20]- # A: Bx3x13- # nullSpace: Bx4x9- # companion matrices to solve the polynomial, in batch- C = torch.zeros((batch_size_filtered, 10, 10), device=cs.device, dtype=cs.dtype)- eye_mat = torch.eye(C[0, 0:-1, 0:-1].shape[0], device=cs.device, dtype=cs.dtype)- C[:, 0:-1, 1:] = eye_mat+ # ---- determinant polynomial -> companion ----+ cs = _determinant_to_polynomial_jit(A, multiplication_indices, signs, coefficient_map) # (B,11)- cs_de = cs[:, -1].unsqueeze(-1)- cs_de = torch.where(cs_de == 0, torch.tensor(1e-8, dtype=cs_de.dtype), cs_de)- C[:, -1, :] = -cs[:, :-1] / cs_de+ C = torch.zeros(B, 10, 10, device=device, dtype=dtype)+ C[:, 0:9, 1:10] = torch.eye(9, device=device, dtype=dtype)- roots = torch.real(torch.linalg.eigvals(C))+ cs_de = cs[:, -1].clamp_min(1e-8)+ C[:, -1, :] = -cs[:, :-1] / cs_de.unsqueeze(-1)- roots_unsqu = roots.unsqueeze(1)+ roots_eig = torch.linalg.eigvals(C) # (B,10), complex+ roots = torch.real(roots_eig)+ is_real = torch.abs(torch.imag(roots_eig)) < 1e-10++ roots_unsqu = roots.unsqueeze(1) # (B,1,10)Bs = torch.stack((A[:, :3, :1] * (roots_unsqu**3)+ A[:, :3, 1:2] * roots_unsqu.square()- + A[:, 0:3, 2:3] * roots_unsqu- + A[:, 0:3, 3:4],- A[:, 0:3, 4:5] * (roots_unsqu**3)- + A[:, 0:3, 5:6] * roots_unsqu.square()- + A[:, 0:3, 6:7] * roots_unsqu- + A[:, 0:3, 7:8],+ + A[:, :3, 2:3] * roots_unsqu+ + A[:, :3, 3:4],+ A[:, :3, 4:5] * (roots_unsqu**3)+ + A[:, :3, 5:6] * roots_unsqu.square()+ + A[:, :3, 6:7] * roots_unsqu+ + A[:, :3, 7:8],),dim=1,- )+ ).transpose(1, -1) # (B,10,3,2)- Bs = Bs.transpose(1, -1)-- bs = (+ bs_vec = ((- A[:, 0:3, 8:9] * (roots_unsqu**4)- + A[:, 0:3, 9:10] * (roots_unsqu**3)- + A[:, 0:3, 10:11] * roots_unsqu.square()- + A[:, 0:3, 11:12] * roots_unsqu- + A[:, 0:3, 12:13]+ A[:, :3, 8:9] * (roots_unsqu**4)+ + A[:, :3, 9:10] * (roots_unsqu**3)+ + A[:, :3, 10:11] * roots_unsqu.square()+ + A[:, :3, 11:12] * roots_unsqu+ + A[:, :3, 12:13]).transpose(1, 2).unsqueeze(-1)- )+ ) # (B,10,3,1)- xzs = torch.matmul(torch.linalg.inv(Bs[:, :, 0:2, 0:2]), bs[:, :, 0:2])+ A2 = Bs[:, :, 0:2, 0:2] # (B,10,2,2)+ b2 = bs_vec[:, :, 0:2, :] # (B,10,2,1)- mask = (abs(Bs[:, 2].unsqueeze(1) @ xzs - bs[:, 2].unsqueeze(1)) > 1e-3).flatten()+ xzs, bad2 = _solve_2x2_tikhonov_safe(A2, b2, 1e-12) # never throws- # mask: bx10x1x1- mask = (- abs(torch.matmul(Bs[:, :, 2, :].unsqueeze(2), xzs) - bs[:, :, 2, :].unsqueeze(2)) > 1e-3- ) # .flatten(start_dim=1)+ # ---- build Es ----+ xzs_sq = xzs.squeeze(-1) # (B,10,2)+ x = -xzs_sq[:, :, 0]+ y = -xzs_sq[:, :, 1]+ z = roots- # bx10- mask = mask.squeeze(3).squeeze(2)+ N0 = nullSpace[:, 0, :].unsqueeze(1) # (B,1,9)+ N1 = nullSpace[:, 1, :].unsqueeze(1)+ N2 = nullSpace[:, 2, :].unsqueeze(1)+ N3 = nullSpace[:, 3, :].unsqueeze(1)- if torch.any(mask):- q_batch, r_batch = torch.linalg.qr(Bs[mask])- xyz_to_feed = torch.linalg.solve(r_batch, torch.matmul(q_batch.transpose(-1, -2), bs[mask]))- xzs[mask] = xyz_to_feed+ Es_vec = x.unsqueeze(-1) * N0 + y.unsqueeze(-1) * N1 + z.unsqueeze(-1) * N2 + N3 # (B,10,9)+ inv_norm = torch.rsqrt(x * x + y * y + z * z + 1.0)+ Es_vec = Es_vec * inv_norm.unsqueeze(-1)- nullSpace_filtered = nullSpace[singular_filter]+ Es = Es_vec.view(B, 10, 3, 3).transpose(-1, -2)+ # after Es is created (B,10,3,3)+ if bad2.any():+ Es[bad2] = torch.nan+ # mark complex roots as NaN (keeps shape, no compaction)+ if is_real.logical_not().any():+ Es[~is_real] = torch.nan- Es = (- nullSpace_filtered[:, 0:1] * (-xzs[:, :, 0])- + nullSpace_filtered[:, 1:2] * (-xzs[:, :, 1])- + nullSpace_filtered[:, 2:3] * roots.unsqueeze(-1)- + nullSpace_filtered[:, 3:4]- )+ return Es.to(dtype=original_dtype)+++# Indices for null_ij reshaping+IDX_IJ = torch.tensor([[0, 3, 6], [1, 4, 7], [2, 5, 8]], dtype=torch.long)+I_IDX = torch.tensor([0, 0, 0, 1, 1, 1, 2, 2, 2], dtype=torch.long)+J_IDX = torch.tensor([0, 1, 2, 0, 1, 2, 0, 1, 2], dtype=torch.long)+IDX3 = torch.tensor([0, 1, 2], dtype=torch.long)++TOP_IDX = torch.tensor([4, 6, 8], dtype=torch.long)+BOT_IDX = torch.tensor([5, 7, 9], dtype=torch.long)- inv = 1.0 / torch.sqrt((-xzs[:, :, 0]) ** 2 + (-xzs[:, :, 1]) ** 2 + roots.unsqueeze(-1) ** 2 + 1.0)- Es *= inv- Es = Es.view(batch_size_filtered, -1, 3, 3).transpose(-1, -2)+def fun_select(null_mat: torch.Tensor, i: int, j: int, ratio: int = 3) -> torch.Tensor:+ return null_mat[:, ratio * j + i]- # make sure the returned batch size equals to that of inputs- E_return = torch.eye(3, dtype=Es.dtype, device=Es.device)[None].expand(batch_size, 10, -1, -1).clone()- E_return[singular_filter] = Es- return E_return+def null_to_Nister_solution(X: torch.Tensor, batch_size: int) -> torch.Tensor:+ device = X.device+ dtype_internal = X.dtype++ T1 = T_deg1.to(device=device, dtype=dtype_internal)+ T2 = T_deg2.to(device=device, dtype=dtype_internal)+ mult_idx = multiplication_indices.to(device=device)+ sgns = signs.to(device=device, dtype=dtype_internal)+ coeff_map = coefficient_map.to(device=device)+ i_idx_dev = I_IDX.to(device=device)+ j_idx_dev = J_IDX.to(device=device)+ idx3_dev = IDX3.to(device=device)+ top_idx_dev = TOP_IDX.to(device=device)+ bot_idx_dev = BOT_IDX.to(device=device)+ idx_ij_dev = IDX_IJ.to(device=device)++ return _null_to_Nister_solution_script(+ X,+ batch_size,+ T1,+ T2,+ mult_idx,+ sgns,+ coeff_map,+ idx_ij_dev,+ i_idx_dev,+ j_idx_dev,+ idx3_dev,+ top_idx_dev,+ bot_idx_dev,+ )def essential_from_fundamental(F_mat: torch.Tensor, K1: torch.Tensor, K2: torch.Tensor) -> torch.Tensor:@@ -609,9 +756,9 @@ def find_essential(r"""Find essential matrices.Args:- points1: A set of points in the first image with a torch.tensor shape :math:`(B, N, 2), N>=5`.- points2: A set of points in the second image with a torch.tensor shape :math:`(B, N, 2), N>=5`.- weights: torch.Tensor containing the weights per point correspondence with a shape of :math:`(5, N)`.+ points1: A set of points in the first image with a tensor shape :math:`(B, N, 2), N>=5`.+ points2: A set of points in the second image with a tensor shape :math:`(B, N, 2), N>=5`.+ weights: Tensor containing the weights per point correspondence with a shape of :math:`(5, N)`.Returns:the computed essential matrices with shape :math:`(B, 10, 3, 3)`.diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.pyindex 2238d3099..d9c052c25 100644--- a/kornia/geometry/epipolar/fundamental.py+++ b/kornia/geometry/epipolar/fundamental.py@@ -15,8 +15,9 @@# limitations under the License.#-"""nn.Module containing the functionalities for computing the Fundamental Matrix."""+"""Module containing the functionalities for computing the Fundamental Matrix."""+import mathfrom typing import Literal, Optional, Tupleimport torch@@ -24,7 +25,6 @@ import torchfrom kornia.core.check import KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPEfrom kornia.core.utils import _torch_svd_cast, safe_inverse_with_maskfrom kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous-from kornia.geometry.linalg import transform_pointsfrom kornia.geometry.solvers import solve_cubic@@ -39,7 +39,7 @@ def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tenthe result as optimal.Args:- points: torch.Tensor containing the points to be normalized with shape :math:`(B, N, 2)`.+ points: Tensor containing the points to be normalized with shape :math:`(B, N, 2)`.eps: epsilon value to avoid numerical instabilities.Returns:@@ -47,35 +47,37 @@ def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tenin the shape :math:`(B, 3, 3)`."""- if len(points.shape) != 3:+ if points.ndim != 3:raise AssertionError(points.shape)if points.shape[-1] != 2:raise AssertionError(points.shape)- x_mean = torch.mean(points, dim=1, keepdim=True) # Bx1x2+ B, _N, _ = points.shape+ device, dtype = points.device, points.dtype- scale = (points - x_mean).norm(dim=-1, p=2).mean(dim=-1) # B- scale = torch.sqrt(torch.tensor(2.0)) / (scale + eps) # B+ # Center at mean+ x_mean = points.mean(dim=1, keepdim=True) # (B,1,2)+ centered = points - x_mean # (B,N,2)- ones_tensor, zeros_tensor = torch.ones_like(scale), torch.zeros_like(scale)+ # Mean Euclidean distance to origin (radius)+ mean_radius = centered.norm(dim=-1, p=2).mean(dim=-1) # (B,)- transform = torch.stack(- [- scale,- zeros_tensor,- -scale * x_mean[..., 0, 0],- zeros_tensor,- scale,- -scale * x_mean[..., 0, 1],- zeros_tensor,- zeros_tensor,- ones_tensor,- ],- dim=-1,- ) # Bx9+ # Scale so that mean radius becomes sqrt(2)+ scale = (math.sqrt(2.0)) / (mean_radius + eps) # (B,)++ # Apply similarity transform in-place-ish (broadcast scale)+ points_norm = centered * scale.view(B, 1, 1) # (B,N,2)- transform = transform.view(-1, 3, 3) # Bx3x3- points_norm = transform_points(transform, points) # BxNx2+ # Build transform matrix:+ # T = [[s, 0, -s*mx],+ # [0, s, -s*my],+ # [0, 0, 1 ]]+ transform = torch.zeros((B, 3, 3), device=device, dtype=dtype)+ transform[..., 0, 0] = scale+ transform[..., 1, 1] = scale+ transform[..., 0, 2] = -scale * x_mean[..., 0, 0]+ transform[..., 1, 2] = -scale * x_mean[..., 0, 1]+ transform[..., 2, 2] = 1.0return points_norm, transform@@ -83,7 +85,7 @@ def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tendef normalize_transformation(M: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:r"""Normalize a given transformation matrix.- The function trakes the transformation matrix and F.normalize so that the value in+ The function trakes the transformation matrix and normalize so that the value inthe last row and column is one.Args:@@ -100,115 +102,177 @@ def normalize_transformation(M: torch.Tensor, eps: float = 1e-8) -> torch.Tensorreturn torch.where(norm_val.abs() > eps, M / (norm_val + eps), M)+def _nullspace_via_eigh(A: torch.Tensor) -> torch.Tensor:+ """Compute the nullspace of a matrix A using the eigh method.++ Args:+ A: (..., 7, 9)++ Returns:+ N: (..., 9, 2) where columns span the right nullspace of A+ """+ AT = A.transpose(-2, -1) # (..., 9, 7)+ G = AT @ A # (..., 9, 9) SPD+ _evals, evecs = torch.linalg.eigh(G) # ascending eigenvalues+ N = evecs[..., :, :2] # eigenvectors for 2 smallest evals+ return N # orthonormal columns+++def _F1F2_from_nullspace(N: torch.Tensor):+ """Compute the F1 and F2 matrices from the nullspace of a matrix A.++ Args:+ N: (..., 9, 2) where columns span the right nullspace of A+ Returns:+ F1: (..., 3, 3)+ F2: (..., 3, 3)+ """+ F1 = N[..., 0].view(-1, 3, 3)+ F2 = N[..., 1].view(-1, 3, 3)+ return F1, F2+++def _normalize_F(F: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:+ """Frobenius-normalize each 3x3 (keeps cubic coefficients well-scaled).++ Args:+ F: (..., 3, 3)+ eps: small value to avoid unstabilities.++ Returns:+ F: (..., 3, 3)+ """+ nrm = F.norm(dim=(-2, -1), p=1, keepdim=True).clamp_min(eps)+ return F / nrm++# Reference: Adapted from the 'run_7point' function in opencv# https://github.com/opencv/opencv/blob/4.x/modules/calib3d/src/fundam.cpp+def _isclose0(x: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:+ # torch.isclose(x, 0) but TorchScript/GPU-friendly (no scalar tensor creation)+ return x.abs() <= eps++def run_7point(points1: torch.Tensor, points2: torch.Tensor) -> torch.Tensor:r"""Compute the fundamental matrix using the 7-point algorithm.+ The 7-point algorithm computes the fundamental matrix from exactly 7 point correspondences.+ Unlike the 8-point algorithm, this method can return up to 3 possible fundamental matrices+ as solutions to the rank-2 constraint, which is formulated as a cubic equation.++ Reference: Hartley/Zisserman 11.1.2 pag.281+Args:- points1: A set of points in the first image with a torch.tensor shape :math:`(B, N, 2)`.- points2: A set of points in the second image with a torch.tensor shape :math:`(B, N, 2)`.+ points1: A set of 7 points in the first image with shape :math:`(B, 7, 2)`.+ points2: A set of 7 points in the second image with shape :math:`(B, 7, 2)`.Returns:- the computed fundamental matrix with shape :math:`(B, 3*m, 3), Valid values of m are 1, 2 or 3`+ The computed fundamental matrices with shape :math:`(B, 3, 3, 3)`, containing up to 3+ candidate solutions per batch. Invalid solutions are zeroed out."""KORNIA_CHECK_SHAPE(points1, ["B", "7", "2"])KORNIA_CHECK_SHAPE(points2, ["B", "7", "2"])- batch_size = points1.shape[0]+ B = points1.shape[0]+ device = points1.device+ dtype = points1.dtypepoints1_norm, transform1 = normalize_points(points1)points2_norm, transform2 = normalize_points(points2)- x1, y1 = torch.chunk(points1_norm, dim=-1, chunks=2) # Bx1xN- x2, y2 = torch.chunk(points2_norm, dim=-1, chunks=2) # Bx1xN-- ones_tensor = torch.ones_like(x1)- # form a linear system: which represents- # the equation (x2[i], 1)*F*(x1[i], 1) = 0- X = torch.cat([x2 * x1, x2 * y1, x2, y2 * x1, y2 * y1, y2, x1, y1, ones_tensor], -1) # BxNx9-- # X * Fmat = 0 is singular (7 equations for 9 variables)- # solving for nullspace of X to get two F- ####### unstable failing gradcheck- # _, _, v = torch.linalg.svd(X)- _, _, v = _torch_svd_cast(X)-- # last two singular vector as a basic of the space- f1 = v[..., 7].view(-1, 3, 3)- f2 = v[..., 8].view(-1, 3, 3)+ x1, y1 = torch.chunk(points1_norm, dim=-1, chunks=2) # (B,7,1)+ x2, y2 = torch.chunk(points2_norm, dim=-1, chunks=2) # (B,7,1)+ ones = torch.ones_like(x1)- # lambda*f1 + mu*f2 is an arbitrary fundamental matrix- # f ~ lambda*f1 + (1 - lambda)*f2- # det(f) = det(lambda*f1 + (1-lambda)*f2), find lambda- # form a cubic equation- # finding the coefficients of cubic polynomial (coeffs)+ # (B,7,9)+ X = torch.cat([x2 * x1, x2 * y1, x2, y2 * x1, y2 * y1, y2, x1, y1, ones], dim=-1)- coeffs = torch.zeros((batch_size, 4), device=v.device, dtype=v.dtype)+ # nullspace basis -> (B,3,3)+ f1, f2 = _F1F2_from_nullspace(_nullspace_via_eigh(X))+ f1 = _normalize_F(f1)+ f2 = _normalize_F(f2)+ # --- cubic coeffs (keep your known-good inverse-based formula) ---+ coeffs = torch.zeros((B, 4), device=device, dtype=dtype)f1_det = torch.linalg.det(f1)f2_det = torch.linalg.det(f2)++ inv_f1, _ = safe_inverse_with_mask(f1)+ inv_f2, _ = safe_inverse_with_mask(f2)+coeffs[:, 0] = f1_det- coeffs[:, 1] = torch.einsum("bii->b", f2 @ safe_inverse_with_mask(f1)[0]) * f1_det- coeffs[:, 2] = torch.einsum("bii->b", f1 @ safe_inverse_with_mask(f2)[0]) * f2_det+ coeffs[:, 1] = torch.einsum("bii->b", f2 @ inv_f1) * f1_det+ coeffs[:, 2] = torch.einsum("bii->b", f1 @ inv_f2) * f2_detcoeffs[:, 3] = f2_det- # solve the cubic equation, there can be 1 to 3 roots- # roots = torch.tensor(np.roots(coeffs.numpy()))- roots = solve_cubic(coeffs)+ roots = solve_cubic(coeffs) # (B,3)- fmatrix = torch.zeros((batch_size, 3, 3, 3), device=v.device, dtype=v.dtype)- valid_root_mask = (torch.count_nonzero(roots, dim=1) < 3) | (torch.count_nonzero(roots, dim=1) > 1)+ # 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- _lambda = roots+ # --- compute lambda/mu for ALL batches (no compaction) ---+ _lambda = roots.clone()_mu = torch.ones_like(_lambda)- _s = f1[valid_root_mask, 2, 2].unsqueeze(dim=1) * roots[valid_root_mask] + f2[valid_root_mask, 2, 2].unsqueeze(- dim=1- )- # _s_non_zero_mask = torch.abs(_s ) > 1e-16- _s_non_zero_mask = ~torch.isclose(_s, torch.tensor(0.0, device=v.device, dtype=v.dtype))+ # _s = f1[2,2] * root + f2[2,2] for each of 3 roots+ f1_22 = f1[:, 2, 2].unsqueeze(1) # (B,1)+ f2_22 = f2[:, 2, 2].unsqueeze(1) # (B,1)+ _s = f1_22 * roots + f2_22 # (B,3)- _mu[_s_non_zero_mask] = 1.0 / _s[_s_non_zero_mask]- _lambda[_s_non_zero_mask] = _lambda[_s_non_zero_mask] * _mu[_s_non_zero_mask]+ # avoid torch.isclose with scalar tensor creation+ _s_non_zero_mask = ~_isclose0(_s, 1e-12) # (B,3) bool- f1_expanded = f1.unsqueeze(1).expand(batch_size, 3, 3, 3)- f2_expanded = f2.unsqueeze(1).expand(batch_size, 3, 3, 3)+ # mu = 1/s where s != 0, else mu stays 1+ mu_new = torch.where(_s_non_zero_mask, 1.0 / _s, _mu)+ lam_new = torch.where(_s_non_zero_mask, _lambda * mu_new, _lambda)- fmatrix[valid_root_mask] = (- f1_expanded[valid_root_mask] * _lambda[valid_root_mask, :, None, None]- + f2_expanded[valid_root_mask] * _mu[valid_root_mask, :, None, None]- )+ _mu = mu_new+ _lambda = lam_new- mat_ind = torch.zeros(3, 3, dtype=torch.bool)- mat_ind[2, 2] = True- fmatrix[_s_non_zero_mask, mat_ind] = 1.0- fmatrix[~_s_non_zero_mask, mat_ind] = 0.0+ # --- form candidates for ALL batches: F = f1*lambda + f2*mu ---+ f1_expanded = f1.unsqueeze(1).expand(B, 3, 3, 3)+ f2_expanded = f2.unsqueeze(1).expand(B, 3, 3, 3)- trans1_exp = transform1[valid_root_mask].unsqueeze(1).expand(-1, fmatrix.shape[2], -1, -1)- trans2_exp = transform2[valid_root_mask].unsqueeze(1).expand(-1, fmatrix.shape[2], -1, -1)+ fmatrix = f1_expanded * _lambda[:, :, None, None] + f2_expanded * _mu[:, :, None, None] # (B,3,3,3)- fmatrix[valid_root_mask] = torch.matmul(- trans2_exp.transpose(-2, -1), torch.matmul(fmatrix[valid_root_mask], trans1_exp)- )+ # --- enforce last element handling like your original ---+ # If s != 0 set F[2,2]=1 else set to 0 (per-candidate)+ # This is exactly what your boolean-indexing version did, but without advanced indexing.+ 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)- return normalize_transformation(fmatrix)+ # --- 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))+ # --- denormalize for ALL batches ---+ # F = T2^T * F * T1+ fmatrix = (transform2.unsqueeze(1).transpose(-2, -1) @ fmatrix) @ transform1.unsqueeze(1)++ return normalize_transformation(fmatrix)-def run_8point(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[torch.Tensor] = None) -> torch.Tensor:- r"""Compute the fundamental matrix using the DLT formulation.- The linear system is solved by using the Weighted Least Squares Solution for the 8 Points algorithm.+def run_8point(+ points1: torch.Tensor,+ points2: torch.Tensor,+ weights: Optional[torch.Tensor] = None,+ use_einsum_at_more_than_points: int = 512,+) -> torch.Tensor:+ r"""Compute the fundamental matrix using (weighted) 8-point DLT, optimized.Args:- points1: A set of points in the first image with a torch.tensor shape :math:`(B, N, 2), N>=8`.- points2: A set of points in the second image with a torch.tensor shape :math:`(B, N, 2), N>=8`.- weights: torch.Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.+ points1: (B, N, 2), N >= 8+ points2: (B, N, 2), N >= 8+ weights: optional (B, N) nonnegative weights+ use_einsum_at_more_than_points: threshold for using einsum vs GEMM for large NReturns:- the computed fundamental matrix with shape :math:`(B, 3, 3)`.-+ (B, 3, 3) fundamental matrices"""KORNIA_CHECK_SHAPE(points1, ["B", "N", "2"])KORNIA_CHECK_SHAPE(points2, ["B", "N", "2"])@@ -217,42 +281,53 @@ def run_8point(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[traise AssertionError(points1.shape)if weights is not None:KORNIA_CHECK_SHAPE(weights, ["B", "N"])- if not (weights.shape[1] == points1.shape[1]):+ if weights.shape[1] != points1.shape[1]:raise AssertionError(weights.shape)- points1_norm, transform1 = normalize_points(points1)- points2_norm, transform2 = normalize_points(points2)-- x1, y1 = torch.chunk(points1_norm, dim=-1, chunks=2) # Bx1xN- x2, y2 = torch.chunk(points2_norm, dim=-1, chunks=2) # Bx1xN+ # Hartley normalization (same as before)+ pts1n, T1 = normalize_points(points1)+ pts2n, T2 = normalize_points(points2)- ones_tensor = torch.ones_like(x1)+ x1, y1 = torch.chunk(pts1n, dim=-1, chunks=2) # (B,N,1)+ x2, y2 = torch.chunk(pts2n, dim=-1, chunks=2) # (B,N,1)+ ones = torch.ones_like(x1)- # build equations system and solve DLT- # https://www.cc.gatech.edu/~afb/classes/CS4495-Fall2013/slides/CS4495-09-TwoViews-2.pdf- # [x * x', x * y', x, y * x', y * y', y, x', y', 1]+ # Design matrix rows A_i = [x2*x1, x2*y1, x2, y2*x1, y2*y1, y2, x1, y1, 1]+ # Shape: A ∈ (B, N, 9)+ A = torch.cat([x2 * x1, x2 * y1, x2, y2 * x1, y2 * y1, y2, x1, y1, ones], dim=-1).squeeze(-2)- X = torch.cat([x2 * x1, x2 * y1, x2, y2 * x1, y2 * y1, y2, x1, y1, ones_tensor], dim=-1) # BxNx9+ B, N, _ = A.shape- # apply the weights to the linear system+ # Build normal matrix M = A^T W A (B,9,9) without forming NxN diagonals.if weights is None:- X = X.transpose(-2, -1) @ X+ if N < use_einsum_at_more_than_points:+ # Use GEMM on tall A: (B,9,N) @ (B,N,9)+ M = A.transpose(-2, -1).contiguous() @ A+ else:+ # Accumulate via einsum (saves bandwidth for huge N)+ M = torch.einsum("bni,bnj->bij", A, A)else:- w_diag = torch.diag_embed(weights)- X = X.transpose(-2, -1) @ w_diag @ X- # compute eigevectors and retrieve the one with the smallest eigenvalue-- _, _, V = _torch_svd_cast(X)- F_mat = V[..., -1].view(-1, 3, 3)+ w = weights.clamp_min(0)+ if N < use_einsum_at_more_than_points:+ # Row-scale by sqrt(w) then GEMM+ Aw = A * w.unsqueeze(-1).sqrt()+ M = Aw.transpose(-2, -1).contiguous() @ Aw+ else:+ # Weighted einsum+ M = torch.einsum("bni,bnj,bn->bij", A, A, w)- # reconstruct and force the matrix to have rank2- U, S, V = _torch_svd_cast(F_mat)- rank_mask = torch.tensor([1.0, 1.0, 0.0], device=F_mat.device, dtype=F_mat.dtype)+ _evals, evecs = torch.linalg.eigh(M) # ascending order+ h = evecs[..., 0] # (B,9), eigenvector for smallest λ+ F_hat = h.view(B, 3, 3)- F_projected = U @ (torch.diag_embed(S * rank_mask) @ V.transpose(-2, -1))- F_est = transform2.transpose(-2, -1) @ (F_projected @ transform1)+ # Enforce rank-2 with a 3x3 SVD+ U, S, V = _torch_svd_cast(F_hat)+ S_new = torch.zeros_like(S)+ S_new[..., :-1] = S[..., :-1]+ F_rank2 = U @ torch.diag_embed(S_new) @ V.mH+ F = T2.transpose(-2, -1) @ (F_rank2 @ T1)- return normalize_transformation(F_est)+ return normalize_transformation(F)def find_fundamental(@@ -264,13 +339,13 @@ def find_fundamental(r"""Find the fundamental matrix.Args:- points1: A set of points in the first image with a torch.tensor shape :math:`(B, N, 2), N>=8`.- points2: A set of points in the second image with a torch.tensor shape :math:`(B, N, 2), N>=8`.- weights: torch.Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.+ points1: A set of points in the first image with a tensor shape :math:`(B, N, 2), N>=8`.+ points2: A set of points in the second image with a tensor shape :math:`(B, N, 2), N>=8`.+ weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.method: The method to use for computing the fundamental matrix. Supported methods are "7POINT" and "8POINT".Returns:- the computed fundamental matrix with shape :math:`(B, 3*m, 3)`, torch.where `m` number of fundamental matrix.+ the computed fundamental matrix with shape :math:`(B, 3*m, 3)`, where `m` number of fundamental matrix.Raises:ValueError: If an invalid method is provided.@@ -289,12 +364,11 @@ def compute_correspond_epilines(points: torch.Tensor, F_mat: torch.Tensor) -> tor"""Compute the corresponding epipolar line for a given set of points.Args:- points: torch.tensor containing the set of points to project in the shape of :math:`(*, N, 2)`- or :math:`(*, N, 3)`.+ points: tensor containing the set of points to project in the shape of :math:`(*, N, 2)` or :math:`(*, N, 3)`.F_mat: the fundamental to use for projection the points in the shape of :math:`(*, 3, 3)`.Returns:- a torch.tensor with shape :math:`(*, N, 3)` containing a vector of the epipolar+ a tensor with shape :math:`(*, N, 3)` containing a vector of the epipolarlines corresponding to the points to the other image. Each line is described as:math:`ax + by + c = 0` and encoding the vectors as :math:`(a, b, c)`.@@ -323,11 +397,11 @@ def get_perpendicular(lines: torch.Tensor, points: torch.Tensor) -> torch.Tensorr"""Compute the perpendicular to a line, through the point.Args:- lines: torch.tensor containing the set of lines :math:`(*, N, 3)`.- points: torch.tensor containing the set of points :math:`(*, N, 2)`.+ lines: tensor containing the set of lines :math:`(*, N, 3)`.+ points: tensor containing the set of points :math:`(*, N, 2)`.Returns:- a torch.tensor with shape :math:`(*, N, 3)` containing a vector of the epipolar+ a tensor with shape :math:`(*, N, 3)` containing a vector of the epipolarperpendicular lines. Each line is described as:math:`ax + by + c = 0` and encoding the vectors as :math:`(a, b, c)`.@@ -362,7 +436,7 @@ def get_closest_point_on_epipolar_line(pts1: torch.Tensor, pts2: torch.Tensor, Fif not isinstance(Fm, torch.Tensor):raise TypeError(f"Fm type is not a torch.Tensor. Got {type(Fm)}")if (len(Fm.shape) < 3) or not Fm.shape[-2:] == (3, 3):- raise ValueError(f"Fm must be a (*, 3, 3) torch.tensor. Got {Fm.shape}")+ raise ValueError(f"Fm must be a (*, 3, 3) tensor. Got {Fm.shape}")if pts1.shape[-1] == 2:pts1 = convert_points_to_homogeneous(pts1)if pts2.shape[-1] == 2:@@ -399,8 +473,7 @@ def fundamental_from_essential(E_mat: torch.Tensor, K1: torch.Tensor, K2: torch.# adapted from:# https://github.com/opencv/opencv_contrib/blob/master/modules/sfm/src/fundamental.cpp#L109-# https://github.com/openMVG/openMVG/blob/160643be515007580086650f2ae7f1a42d32e9fb/-# src/openMVG/multiview/projection.cpp#L134+# https://github.com/openMVG/openMVG/blob/160643be515007580086650f2ae7f1a42d32e9fb/src/openMVG/multiview/projection.cpp#L134def fundamental_from_projections(P1: torch.Tensor, P2: torch.Tensor) -> torch.Tensor:@@ -412,7 +485,6 @@ def fundamental_from_projections(P1: torch.Tensor, P2: torch.Tensor) -> torch.TeReturns:The fundamental matrix with shape :math:`(*, 3, 3)`.-"""KORNIA_CHECK_SHAPE(P1, ["*", "3", "4"])KORNIA_CHECK_SHAPE(P2, ["*", "3", "4"])diff --git a/kornia/geometry/epipolar/numeric.py b/kornia/geometry/epipolar/numeric.pyindex b208854a8..ddda3cadd 100644--- a/kornia/geometry/epipolar/numeric.py+++ b/kornia/geometry/epipolar/numeric.py@@ -15,9 +15,9 @@# limitations under the License.#-import torch+"""Module containing numerical functionalities for SfM."""-"""nn.Module containing numerical functionalities for SfM."""+import torchdef cross_product_matrix(x: torch.Tensor) -> torch.Tensor:diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.pyindex a9202ae4f..241596f17 100644--- a/kornia/geometry/epipolar/projection.py+++ b/kornia/geometry/epipolar/projection.py@@ -15,12 +15,11 @@# limitations under the License.#-"""nn.Module for image projections."""+"""Module for image projections."""from typing import Tuple, Unionimport torch-import torch.nn.functional as Ffrom torch.linalg import qr as linalg_qrfrom kornia.core.check import KORNIA_CHECK_SHAPE@@ -37,8 +36,8 @@ def intrinsics_like(focal: float, input: torch.Tensor) -> torch.Tensor:Args:focal: the focal length for the camera matrix.- input: image torch.tensor that will determine the batch size and image height- and width. It is assumed to be a torch.tensor in the shape of :math:`(B, C, H, W)`.+ input: image tensor that will determine the batch size and image height+ and width. It is assumed to be a tensor in the shape of :math:`(B, C, H, W)`.Returns:The camera matrix with the shape of :math:`(B, 3, 3)`.@@ -84,7 +83,7 @@ def scale_intrinsics(camera_matrix: torch.Tensor, scale_factor: Union[float, torArgs:camera_matrix: the camera calibration matrix containing the intrinsic- parameters. The expected shape for the torch.tensor is :math:`(B, 3, 3)`.+ parameters. The expected shape for the tensor is :math:`(B, 3, 3)`.scale_factor: the scaling factor to be applied.Returns:@@ -120,10 +119,10 @@ def projection_from_KRt(K: torch.Tensor, R: torch.Tensor, t: torch.Tensor) -> toraise AssertionErrorRt = torch.cat([R, t], dim=-1) # 3x4- Rt_h = F.pad(Rt, [0, 0, 0, 1], "constant", 0.0) # 4x4+ Rt_h = torch.nn.functional.pad(Rt, [0, 0, 0, 1], "constant", 0.0) # 4x4Rt_h[..., -1, -1] += 1.0- K_h = F.pad(K, [0, 1, 0, 1], "constant", 0.0) # 4x4+ K_h = torch.nn.functional.pad(K, [0, 1, 0, 1], "constant", 0.0) # 4x4K_h[..., -1, -1] += 1.0return K @ Rtdiff --git a/kornia/geometry/epipolar/triangulation.py b/kornia/geometry/epipolar/triangulation.pyindex 61cf9b624..ac5bfce58 100644--- a/kornia/geometry/epipolar/triangulation.py+++ b/kornia/geometry/epipolar/triangulation.py@@ -15,7 +15,7 @@# limitations under the License.#-"""nn.Module with the functionalities for triangulation."""+"""Module with the functionalities for triangulation."""import torchdiff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.pyindex 069f69c0c..f89c2d5ae 100644--- a/kornia/geometry/homography.py+++ b/kornia/geometry/homography.py@@ -22,10 +22,9 @@ import torchfrom kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.core.utils import _extract_device_dtype, _torch_svd_cast, safe_inverse_with_mask, safe_solve_with_mask--from .conversions import convert_points_from_homogeneous, convert_points_to_homogeneous-from .epipolar import normalize_points-from .linalg import transform_points+from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous+from kornia.geometry.epipolar import normalize_points+from kornia.geometry.linalg import transform_pointsTupleTensor = Tuple[torch.Tensor, torch.Tensor]@@ -50,19 +49,49 @@ def oneway_transfer_error("""KORNIA_CHECK_SHAPE(H, ["B", "3", "3"])- if pts1.size(-1) == 3:- pts1 = convert_points_from_homogeneous(pts1)+ if pts1.shape[-1] == 3:+ x1y1 = convert_points_from_homogeneous(pts1)+ x1 = x1y1[..., 0]+ y1 = x1y1[..., 1]+ else:+ x1 = pts1[..., :, 0]+ y1 = pts1[..., :, 1]- if pts2.size(-1) == 3:- pts2 = convert_points_from_homogeneous(pts2)+ if pts2.shape[-1] == 3:+ u2v2 = convert_points_from_homogeneous(pts2)+ u2 = u2v2[..., 0]+ v2 = u2v2[..., 1]+ else:+ u2 = pts2[..., :, 0]+ v2 = pts2[..., :, 1]++ # ---- Grab H entries and broadcast across N ----+ h00 = H[..., 0, 0][..., None]+ h01 = H[..., 0, 1][..., None]+ h02 = H[..., 0, 2][..., None]+ h10 = H[..., 1, 0][..., None]+ h11 = H[..., 1, 1][..., None]+ h12 = H[..., 1, 2][..., None]+ h20 = H[..., 2, 0][..., None]+ h21 = H[..., 2, 1][..., None]+ h22 = H[..., 2, 2][..., None]# From Hartley and Zisserman, Error in one image (4.6)# dist = \sum_{i} ( d(x', Hx)**2)- pts1_in_2: torch.Tensor = transform_points(H, pts1)- error_squared: torch.Tensor = (pts1_in_2 - pts2).pow(2).sum(dim=-1)+ # ---- Apply homography to pts1 (Euclidean) and dehomogenize ----+ # [x'; y'; w']^T = H @ [x1, y1, 1]^T+ x_num = h00 * x1 + h01 * y1 + h02+ y_num = h10 * x1 + h11 * y1 + h12+ w_den = h20 * x1 + h21 * y1 + h22++ u1in2 = x_num / (w_den + eps)+ v1in2 = y_num / (w_den + eps)++ # ---- Squared transfer error in image 2 ----+ err2 = (u1in2 - u2).pow(2) + (v1in2 - v2).pow(2)if squared:- return error_squared- return (error_squared + eps).sqrt()+ return err2+ return (err2 + eps).sqrt()def symmetric_transfer_error(@@ -184,16 +213,16 @@ def find_homography_dlt(A = torch.cat((ax, ay), dim=-1).reshape(ax.shape[0], -1, ax.shape[-1])if weights is None:- Aw = A+ # All points are equally important+ A = A.transpose(-2, -1) @ Aelse:# We should use provided weightsif not (len(weights.shape) == 2 and weights.shape == points1.shape[:2]):raise AssertionError(weights.shape)- w_full = weights.repeat_interleave(2, dim=1)- Aw = torch.einsum("...ij,...i->...ij", A, w_full)+ w_full = weights.repeat_interleave(2, dim=1).unsqueeze(1)+ A = (A.transpose(-2, -1) * w_full) @ Aif solver == "svd":- A = A.transpose(-2, -1) @ Awtry:_, _, V = _torch_svd_cast(A)except RuntimeError:@@ -201,14 +230,8 @@ def find_homography_dlt(return torch.empty((points1_norm.size(0), 3, 3), device=device, dtype=dtype)H = V[..., -1].view(-1, 3, 3)elif solver == "lu":- if points1.shape[1] > 4:- A = A.transpose(-2, -1) @ Aw- B = torch.ones(A.shape[0], A.shape[1], device=device, dtype=dtype)- else:- B = -Aw[..., -1]- A = Aw[..., :-1]+ B = torch.ones(A.shape[0], A.shape[1], device=device, dtype=dtype)sol, _, _ = safe_solve_with_mask(B, A)- sol = torch.nn.functional.pad(sol, (0, 0, 0, 1), value=1) if sol.shape[1] == 8 else solH = sol.reshape(-1, 3, 3)else:raise NotImplementedError@@ -254,30 +277,32 @@ def sample_is_valid_for_homography(points1: torch.Tensor, points2: torch.Tensor)points2: A set of points in the second image with a tensor shape :math:`(B, 4, 2)`.Returns:- Mask with the minimal sample is good for homography estimation:math:`(B, 3, 3)`.+ Mask with the minimal sample is good for homography estimation :math:`(B)`."""if points1.shape != points2.shape:raise AssertionError(points1.shape)- KORNIA_CHECK_SHAPE(points1, ["B", "4", "2"])- KORNIA_CHECK_SHAPE(points2, ["B", "4", "2"])- device = points1.device- idx_perm = torch.tensor([[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]], dtype=torch.long, device=device)- points_src_h = convert_points_to_homogeneous(points1)- points_dst_h = convert_points_to_homogeneous(points2)-- src_perm = points_src_h[:, idx_perm]- dst_perm = points_dst_h[:, idx_perm]- left_sign = (- torch.linalg.cross(src_perm[..., 1:2, :], src_perm[..., 2:3, :], dim=-1)- @ src_perm[..., 0:1, :].permute(0, 1, 3, 2)- ).sign()-- right_sign = (- torch.linalg.cross(dst_perm[..., 1:2, :], dst_perm[..., 2:3, :], dim=-1)- @ dst_perm[..., 0:1, :].permute(0, 1, 3, 2)- ).sign()- sample_is_valid = (left_sign == right_sign).view(-1, 4).min(dim=1)[0]+ # Triples to test: (0,1,2), (0,1,3), (0,2,3), (1,2,3)+ idx_i = torch.tensor([0, 0, 0, 1], device=points1.device)+ J = torch.tensor([1, 1, 2, 2], device=points1.device)+ K = torch.tensor([2, 3, 3, 3], device=points1.device)++ # Gather the triples for both sets: shape (B, 4, 2)+ p1_i, p1_j, p1_k = points1[:, idx_i], points1[:, J], points1[:, K]+ p2_i, p2_j, p2_k = points2[:, idx_i], points2[:, J], points2[:, K]++ # 2D orientation (signed area) for each triple:+ # orient(a,b,c) = cross2d(b-a, c-a) = (bx-ax)*(cy-ay) - (by-ay)*(cx-ax)+ def _orient(a: torch.Tensor, b: torch.Tensor, c: torch.Tensor) -> torch.Tensor:+ ab = b - a+ ac = c - a+ return ab[..., 0] * ac[..., 1] - ab[..., 1] * ac[..., 0] # shape (B, 4)++ left_sign = torch.sign(_orient(p1_i, p1_j, p1_k))+ right_sign = torch.sign(_orient(p2_i, p2_j, p2_k))++ # Valid if all four orientation signs match across views+ sample_is_valid = (left_sign == right_sign).all(dim=1)return sample_is_validdiff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.pyindex 1462c7761..e5e1e2b20 100644--- a/kornia/geometry/ransac.py+++ b/kornia/geometry/ransac.py@@ -15,25 +15,22 @@# limitations under the License.#-"""nn.Module containing RANSAC modules."""+"""Module containing RANSAC modules."""import mathfrom functools import partial-from typing import Callable, Optional, Tuple, Union+from typing import Callable, Optional, Tupleimport torchfrom torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPE-from kornia.geometry import (- find_fundamental,+from kornia.geometry.epipolar import find_essential, find_fundamental, sampson_epipolar_distance+from kornia.geometry.homography import (find_homography_dlt,find_homography_dlt_iterated,find_homography_lines_dlt,find_homography_lines_dlt_iterated,- symmetrical_epipolar_distance,-)-from kornia.geometry.homography import (line_segment_transfer_error_one_way,oneway_transfer_error,sample_is_valid_for_homography,@@ -43,7 +40,7 @@ __all__ = ["RANSAC"]class RANSAC(nn.Module):- """nn.Module for robust geometry estimation with RANSAC. https://en.wikipedia.org/wiki/Random_sample_consensus.+ """Module for robust geometry estimation with RANSAC. https://en.wikipedia.org/wiki/Random_sample_consensus.Args:model_type: type of model to estimate: "homography", "fundamental", "fundamental_7pt",@@ -64,21 +61,33 @@ class RANSAC(nn.Module):max_iter: int = 10,confidence: float = 0.99,max_lo_iters: int = 5,+ score_type: str = "ransac",+ prosac_sampling: bool = False,) -> None:"""Initialize the RANSAC estimator.Args:- model_type: type of model to estimate: "homography", "fundamental", "fundamental_7pt",+ model_type: type of model to estimate: "homography", "fundamental", "fundamental_7pt", "essential","homography_from_linesegments".- inl_th: threshold for the correspondence to be an inlier.+ inl_th: threshold for the correspondence to be an inlier. Internally is squared.batch_size: number of generated samples at once.max_iter: maximum batches to generate. Actual number of models to try is ``batch_size * max_iter``.confidence: desired confidence of the result, used for the early stopping.max_lo_iters: number of local optimization (polishing) iterations.+ score_type: scoring method to use: "ransac" or "msac".+ prosac_sampling: whether to use PROSAC sampling instead of random sampling."""super().__init__()- self.supported_models = ["homography", "fundamental", "fundamental_7pt", "homography_from_linesegments"]+ self.supported_models = [+ "homography",+ "fundamental",+ "fundamental_7pt",+ "homography_from_linesegments",+ "essential",+ ]+ self.supported_scores = ["msac", "ransac"]+ self.score_type = score_typeself.inl_th = inl_thself.max_iter = max_iterself.batch_size = batch_size@@ -86,6 +95,7 @@ class RANSAC(nn.Module):self.confidence = confidenceself.max_lo_iters = max_lo_itersself.model_type = model_type+ self.prosac_sampling = prosac_samplingself.error_fn: Callable[..., torch.Tensor]self.minimal_solver: Callable[..., torch.Tensor]@@ -96,26 +106,36 @@ class RANSAC(nn.Module):self.minimal_solver = find_homography_dltself.polisher_solver = find_homography_dlt_iteratedself.minimal_sample_size = 4+ self.polisher_sample_size = 4elif model_type == "homography_from_linesegments":self.error_fn = line_segment_transfer_error_one_wayself.minimal_solver = find_homography_lines_dltself.polisher_solver = find_homography_lines_dlt_iteratedself.minimal_sample_size = 4+ self.polisher_sample_size = 4elif model_type == "fundamental":- self.error_fn = symmetrical_epipolar_distance+ self.error_fn = sampson_epipolar_distanceself.minimal_solver = find_fundamentalself.minimal_sample_size = 8self.polisher_solver = find_fundamental+ self.polisher_sample_size = 8elif model_type == "fundamental_7pt":- self.error_fn = symmetrical_epipolar_distance+ self.error_fn = sampson_epipolar_distanceself.minimal_solver = partial(find_fundamental, method="7POINT")self.minimal_sample_size = 7self.polisher_solver = find_fundamental+ self.polisher_sample_size = 8+ elif model_type == "essential":+ self.error_fn = sampson_epipolar_distance+ self.minimal_solver = find_essential+ self.minimal_sample_size = 5+ self.polisher_solver = find_fundamental+ self.polisher_sample_size = 8else:raise NotImplementedError(f"{model_type} is unknown. Try one of {self.supported_models}")def sample(- self, sample_size: int, pop_size: int, batch_size: int, device: Optional[Union[str, torch.device, None]] = None+ self, sample_size: int, pop_size: int, batch_size: int, iteration: int, device: Optional[torch.device] = None) -> torch.Tensor:"""Minimal sampler, but unlike traditional RANSAC we sample in batches.@@ -125,20 +145,21 @@ class RANSAC(nn.Module):sample_size: number of samples to draw from the population.pop_size: size of the population to sample from.batch_size: number of sample sets to generate.+ iteration: current iteration number (used for PROSAC sampling).device: device to place the samples on.Returns:- torch.Tensor of sampled indices with shape :math:`(batch_size, sample_size)`.+ Tensor of sampled indices with shape :math:`(batch_size, sample_size)`."""if device is None:device = torch.device("cpu")- rand_tensor = torch.rand(batch_size, pop_size, device=device)- _, out = rand_tensor.topk(k=sample_size, dim=1)+ rand = torch.rand(batch_size, pop_size, device=device)+ _, out = rand.topk(k=sample_size, dim=1)return out@staticmethod- def max_samples_by_conf(n_inl: int, num_tc: int, sample_size: int, conf: float) -> float:+ def max_samples_by_conf(n_inl: int, num_tc: int, sample_size: int, conf: float) -> int:"""Update max_iter to stop iterations earlier https://en.wikipedia.org/wiki/Random_sample_consensus.Args:@@ -153,10 +174,23 @@ class RANSAC(nn.Module):"""eps = 1e-9if num_tc <= sample_size:- return 1.0+ return 1if n_inl == num_tc:- return 1.0- return math.log(1.0 - conf) / min(-eps, math.log(max(eps, 1.0 - math.pow(n_inl / num_tc, sample_size))))+ return 1+ if n_inl <= sample_size:+ return 1+ if conf >= 1.0:+ return 1+ if conf <= 0.0:+ return 1+ # Proper RANSAC formula for sampling without replacement+ # P(all samples are inliers) = (n_inl/num_tc) * ((n_inl-1)/(num_tc-1)) * ...+ # ... * ((n_inl-sample_size+1)/(num_tc-sample_size+1))+ prob_inlier = 1.0+ for i in range(sample_size):+ prob_inlier *= (n_inl - i) / (num_tc - i)++ return int(math.log(1.0 - conf) / min(-eps, math.log(max(eps, 1.0 - prob_inlier))))def estimate_model_from_minsample(self, kp1: torch.Tensor, kp2: torch.Tensor) -> torch.Tensor:"""Estimate models from minimal samples.@@ -166,7 +200,7 @@ class RANSAC(nn.Module):kp2: target keypoints with shape :math:`(batch_size, sample_size, 2)`.Returns:- Estimated models torch.tensor.+ Estimated models tensor."""batch_size, sample_size = kp1.shape[:2]@@ -175,7 +209,7 @@ class RANSAC(nn.Module):def verify(self, kp1: torch.Tensor, kp2: torch.Tensor, models: torch.Tensor, inl_th: float- ) -> Tuple[torch.Tensor, torch.Tensor, float]:+ ) -> Tuple[torch.Tensor, torch.Tensor, float, float]:"""Verify models by computing inliers and selecting the best model.Args:@@ -200,13 +234,20 @@ class RANSAC(nn.Module):errors = self.error_fn(kp1.expand(batch_size, -1, 2, 2), kp2.expand(batch_size, -1, 2, 2), models)else:errors = self.error_fn(kp1.expand(batch_size, -1, 2), kp2.expand(batch_size, -1, 2), models)- inl = errors <= inl_th- models_score = inl.to(kp1).sum(dim=1)- best_model_idx = models_score.argmax()- best_model_score = models_score[best_model_idx].item()+ inl_mask = errors <= inl_th+ score_ransac = inl_mask.sum(dim=1)+ if self.score_type == "msac":+ score = errors.shape[1] - errors.clamp(min=0.0, max=inl_th).sum(dim=1)+ elif self.score_type == "ransac":+ score = score_ransac+ else:+ raise ValueError(f"Unsupported score type: {self.score_type}")+ best_model_idx = score.argmax()+ best_model_score = score[best_model_idx].item()+ num_inliers = score_ransac[best_model_idx].item()model_best = models[best_model_idx].clone()- inliers_best = inl[best_model_idx]- return model_best, inliers_best, best_model_score+ inliers_best = inl_mask[best_model_idx]+ return model_best, inliers_best, best_model_score, num_inliersdef remove_bad_samples(self, kp1: torch.Tensor, kp2: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:"""Remove degenerate samples based on model-specific constraints.@@ -233,13 +274,11 @@ class RANSAC(nn.Module):models: candidate models to filter.Returns:- Filtered models torch.tensor.+ Filtered models tensor."""- # ToDo: add more and better degenerate model rejection- # For now it is simple and hardcoded- main_diagonal = torch.diagonal(models, dim1=1, dim2=2)- mask = main_diagonal.abs().min(dim=1)[0] > 1e-4+ # Filter out NaN or Inf models+ mask = torch.isfinite(models).all(dim=-1).all(dim=-1)return models[mask]def polish_model(self, kp1: torch.Tensor, kp2: torch.Tensor, inliers: torch.Tensor) -> torch.Tensor:@@ -251,7 +290,7 @@ class RANSAC(nn.Module):inliers: boolean mask indicating inlier correspondences.Returns:- Polished model torch.tensor.+ Polished model tensor."""# TODO: Replace this with MAGSAC++ polisher@@ -305,7 +344,7 @@ class RANSAC(nn.Module):Returns:- Estimated model, shape of :math:`(1, 3, 3)`.- - The inlier/outlier mask, shape of :math:`(1, N)`, torch.where N is number of input correspondences.+ - The inlier/outlier mask, shape of :math:`(1, N)`, where N is number of input correspondences."""self.validate_inputs(kp1, kp2, weights)@@ -315,30 +354,30 @@ class RANSAC(nn.Module):inliers_best_total: torch.Tensor = torch.zeros(num_tc, 1, device=kp1.device, dtype=torch.bool)for i in range(self.max_iter):# Sample minimal samples in batch to estimate models- idxs = self.sample(self.minimal_sample_size, num_tc, self.batch_size, kp1.device)+ idxs = self.sample(self.minimal_sample_size, num_tc, self.batch_size, i, kp1.device)kp1_sampled = kp1[idxs]kp2_sampled = kp2[idxs]-kp1_sampled, kp2_sampled = self.remove_bad_samples(kp1_sampled, kp2_sampled)if len(kp1_sampled) == 0:continue# Estimate modelsmodels = self.estimate_model_from_minsample(kp1_sampled, kp2_sampled)+ if self.model_type in ["essential", "fundamental_7pt"]:+ models = models.reshape(-1, 3, 3)models = self.remove_bad_models(models)if (models is None) or (len(models) == 0):continue# Score the models and select the best one- model, inliers, model_score = self.verify(kp1, kp2, models, self.inl_th)+ model, inliers, model_score, num_inliers = self.verify(kp1, kp2, models, self.inl_th**2)# Store far-the-best model and (optionally) do a local optimization- if model_score > best_score_total:+ if (model_score > best_score_total) and num_inliers >= self.polisher_sample_size:# Local optimizationfor _ in range(self.max_lo_iters):model_lo = self.polish_model(kp1, kp2, inliers)if (model_lo is None) or (len(model_lo) == 0):continue- _, inliers_lo, score_lo = self.verify(kp1, kp2, model_lo, self.inl_th)- # print (f"Orig score = {best_model_score}, LO score = {score_lo} TC={num_tc}")- if score_lo > model_score:+ _, inliers_lo, score_lo, num_inliers_lo = self.verify(kp1, kp2, model_lo, self.inl_th**2)+ if (score_lo > model_score) and (num_inliers_lo >= self.polisher_sample_size):model = model_lo.clone()[0]inliers = inliers_lo.clone()model_score = score_lo@@ -350,10 +389,10 @@ class RANSAC(nn.Module):best_score_total = model_score# Should we already stop?- new_max_iter = int(- self.max_samples_by_conf(int(best_score_total), num_tc, self.minimal_sample_size, self.confidence)+ new_max_iter = self.max_samples_by_conf(+ int(best_score_total), num_tc, self.minimal_sample_size, self.confidence)- # print (f"New max_iter = {new_max_iter}")+# Stop estimation, if the model is very goodif (i + 1) * self.batch_size >= new_max_iter:breakdiff --git a/tests/geometry/epipolar/test_essential.py b/tests/geometry/epipolar/test_essential.pyindex 6716a018c..de448c3bf 100644--- a/tests/geometry/epipolar/test_essential.py+++ b/tests/geometry/epipolar/test_essential.py@@ -66,6 +66,7 @@ class TestFindEssential(BaseTester):E = epi.essential.find_essential(calibrated_x1, calibrated_x2)if torch.all(E != 0):distance = epi.symmetrical_epipolar_distance(calibrated_x1, calibrated_x2, E)+ distance = torch.nan_to_num(distance, nan=1e8)# Note : here we check only the best model, although all solutions are returnedmean_error = distance.mean(-1).min()self.assert_close(mean_error, torch.tensor(0.0, device=device, dtype=dtype), atol=1e-4, rtol=1e-4)@@ -85,8 +86,9 @@ class TestFindEssential(BaseTester):weights = torch.ones_like(calibrated_x2)[..., 0]E_est = epi.essential.find_essential(calibrated_x1, calibrated_x2, weights)error = epi.sampson_epipolar_distance(calibrated_x1, calibrated_x2, E_est)+ error = torch.nan_to_num(error, nan=1e8)self.assert_close(- error[:, torch.argmin(error.mean(-1).min())],+ error[:, torch.argmin(error.mean(-1))],torch.zeros((calibrated_x1.shape[:2]), device=device, dtype=dtype),atol=1e-4,rtol=1e-4,diff --git a/tests/geometry/epipolar/test_fundamental.py b/tests/geometry/epipolar/test_fundamental.pyindex 65e48697a..b870d8b53 100644--- a/tests/geometry/epipolar/test_fundamental.py+++ b/tests/geometry/epipolar/test_fundamental.py@@ -250,7 +250,18 @@ class TestFindFundamental(BaseTester):device=device,dtype=dtype,)+ # We need this voodoo, because the order of the solutions is not guaranteed by the algorithm.F_mat = epi.find_fundamental(points1, points2, method="7POINT")+ ordering = []+ for expected in Fm_expected[0]:+ min_diff = float("inf")+ for i, estimated in enumerate(F_mat[0]):+ diff = (expected - estimated).abs().sum()+ if diff < min_diff:+ min_diff = diff+ min_index = i+ ordering.append(min_index)+ F_mat[0] = F_mat[0][ordering]self.assert_close(F_mat, Fm_expected, rtol=1e-3, atol=1e-3)def test_synthetic_sampson_7point(self, device, dtype):diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.pyindex 11afa95a6..c09113bac 100644--- a/tests/geometry/solvers/test_polynomial_solver.py+++ b/tests/geometry/solvers/test_polynomial_solver.py@@ -73,11 +73,11 @@ class TestCubicSolver:(torch.tensor([[2.0, 3.0, -11.0, -6.0]]), torch.tensor([[2.0, -3.0, -0.5]])),(torch.tensor([[1.0, 0.0, 4.0, 4.0]]), torch.tensor([[-0.847, 0.0, 0.0]])),(torch.tensor([[2.0, -6.0, 6.0, -2.0]]), torch.tensor([[1.0, 1.0, 1.0]])),- (torch.tensor([[0.0, 0.0, 3.0, -1.0]]), torch.tensor([[1.0, 0.0, 0.0]])), # handle first order+ (torch.tensor([[0.0, 0.0, 1.0, -1.0]]), torch.tensor([[1.0, 0.0, 0.0]])), # handle first order(torch.tensor([[0.0, 1.0, -5.0, 6.0]]), torch.tensor([[3.0, 2.0, 0.0]])), # handle second order],)- def test_solve_quadratic(self, coeffs, expected_solutions, device, dtype):+ def test_solve_quadratic_in_cubic(self, coeffs, expected_solutions, device, dtype):roots = solver.solve_cubic(coeffs)assert_close(roots[0], expected_solutions[0], rtol=1e-3, atol=1e-3)diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.pyindex 635cfd08e..d549a19bd 100644--- a/tests/geometry/test_ransac.py+++ b/tests/geometry/test_ransac.py@@ -15,7 +15,6 @@# limitations under the License.#-import mathimport pytestimport torch@@ -264,13 +263,59 @@ class TestRANSACFundamental(BaseTester):class TestRansacMethods:def test_max_samples_by_conf(self):+ """Test max_samples_by_conf with realistic scenarios."""conf = 0.99- eps = 1e-9+ # Test 1: Very few inliers (1 out of 1000) with sample_size=7+ # Returns 1 because n_inl <= sample_size (early exit condition)x = RANSAC.max_samples_by_conf(n_inl=1, num_tc=1000, sample_size=7, conf=conf)- assert x > 0.0- assert x == math.log(1.0 - conf) / -eps-- x = RANSAC.max_samples_by_conf(n_inl=999999999, num_tc=1000000000, sample_size=1, conf=conf)- assert x > 0.0- assert x == math.log(1.0 - conf) / math.log(eps)+ assert x == 1 # Early exit when n_inl <= sample_size++ # Test 2: Low inlier ratio (10 out of 1000, 1%) with sample_size=7+ # Should require many iterations+ x = RANSAC.max_samples_by_conf(n_inl=10, num_tc=1000, sample_size=7, conf=conf)+ assert x > 0+ # With 1% inliers, probability of all 7 samples being inliers is very low+ # So we need a huge number of samples+ assert x > 1_000_000 # Should be a very large number++ # Test 3: Medium inlier ratio (500 out of 1000, 50%) with sample_size=4+ # Should require moderate number of iterations+ x = RANSAC.max_samples_by_conf(n_inl=500, num_tc=1000, sample_size=4, conf=conf)+ assert x > 0+ # With 50% inliers, probability of all 4 samples being inliers is ~0.0625+ # So we need log(1-0.99)/log(1-0.0625) ≈ 70 samples+ assert 50 < x < 100++ # Test 4: High inlier ratio (900 out of 1000, 90%) with sample_size=4+ # Should require very few iterations+ x = RANSAC.max_samples_by_conf(n_inl=900, num_tc=1000, sample_size=4, conf=conf)+ assert x > 0+ # With 90% inliers, probability of all 4 samples being inliers is ~0.66+ # So we need log(1-0.99)/log(1-0.66) ≈ 4 samples+ assert x < 10++ # Test 5: Edge case - all points are inliers+ x = RANSAC.max_samples_by_conf(n_inl=100, num_tc=100, sample_size=4, conf=conf)+ assert x == 1 # Only need 1 sample if all are inliers++ # Test 6: Edge case - not enough points for sample+ x = RANSAC.max_samples_by_conf(n_inl=10, num_tc=10, sample_size=15, conf=conf)+ assert x == 1 # Returns 1 when num_tc <= sample_size++ # Test 7: Edge case - too few inliers (n_inl <= sample_size)+ x = RANSAC.max_samples_by_conf(n_inl=2, num_tc=1000, sample_size=4, conf=conf)+ assert x == 1 # Returns 1 when n_inl <= sample_size++ # Test 8: Edge case - confidence at boundaries+ x = RANSAC.max_samples_by_conf(n_inl=50, num_tc=100, sample_size=4, conf=1.0)+ assert x == 1 # Returns 1 when conf >= 1.0++ x = RANSAC.max_samples_by_conf(n_inl=50, num_tc=100, sample_size=4, conf=0.0)+ assert x == 1 # Returns 1 when conf <= 0.0++ # Test 9: Verify monotonicity - more inliers should require fewer samples+ x1 = RANSAC.max_samples_by_conf(n_inl=200, num_tc=1000, sample_size=4, conf=conf)+ x2 = RANSAC.max_samples_by_conf(n_inl=500, num_tc=1000, sample_size=4, conf=conf)+ x3 = RANSAC.max_samples_by_conf(n_inl=800, num_tc=1000, sample_size=4, conf=conf)+ assert x1 > x2 > x3 # More inliers = fewer samples needed