π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
RANSAC: DEGENSAC for seven-point fundamental matrices and sampson_homography_distance (#5099)
Dmytro Mishkina81cbdde75d7
diff --git a/changelog.d/5099.added.md b/changelog.d/5099.added.mdnew file mode 100644index 000000000..217aa92ca--- /dev/null+++ b/changelog.d/5099.added.md@@ -0,0 +1 @@+`RANSAC` gains opt-in `degensac=True` (off by default), DEGENSAC's dominant-plane recovery for seven-point fundamental matrices (Chum, Werner and Matas, CVPR 2005), following Chum's implementation in pydegensac: record-setting seven-point models are tested for five or more correspondences related by one homography, and a degenerate one hands that homography to a plane-and-parallax search over the correspondences off the plane. The new `kornia.geometry.homography.sampson_homography_distance` returns the Sampson distance of correspondences to homographies, the first-order geometric error over both images (Hartley and Zisserman, section 4.2.6): unlike `oneway_transfer_error`, it accounts for noise in both images and does not depend on the scale of `H`, and an exact correspondence scores 0.diff --git a/docs/source/geometry.ransac.rst b/docs/source/geometry.ransac.rstindex 47896ac13..8bf71cbd8 100644--- a/docs/source/geometry.ransac.rst+++ b/docs/source/geometry.ransac.rst@@ -173,5 +173,24 @@ non-minimal solver's sample size (eight for fundamental/essential matrices).On PhotoTourism fundamental matrices the subset refits match or beat full-inlierrefitting at a lower cost on both CPU and CUDA.+Dominant planes+---------------++A seven-point sample with five correspondences on one plane yields a fundamental+matrix consistent with the whole plane, whatever its two other correspondences+are (Chum, Werner and Matas, CVPR 2005). When most inliers lie on one plane, such+a wrong model can have the most support and stop the sampling, and no refinement+recovers the off-plane inliers it never counted. ``"fundamental"`` and+``"fundamental_7pt"`` support opt-in DEGENSAC (``degensac=True``): record-setting samples+are tested for this degeneracy, and a degenerate one hands its plane homography+to a plane-and-parallax search over the correspondences off the plane, whose+best model, refined, competes with the minimal ones. Each plane is searched once+per call.+:func:`~kornia.geometry.homography.sampson_homography_distance` measures the+plane. The test's tolerance, taken from Chum's implementation, also flags samples+in scenes without a dominant plane, so the estimate for a given seed can change+there too. ``degensac=False`` (the default) and ``degensac=None`` leave it off,+retaining the plain seven-point behavior.+.. autoclass:: RANSAC:members: forward, resolve_batch_sizediff --git a/kornia/geometry/_degensac.py b/kornia/geometry/_degensac.pynew file mode 100644index 000000000..4eb4fc2cc--- /dev/null+++ b/kornia/geometry/_degensac.py@@ -0,0 +1,315 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++"""DEGENSAC kernels: fundamental matrices unaffected by a dominant plane (Chum, Werner and Matas, CVPR 2005).++:class:`~kornia.geometry.ransac.RANSAC` runs them for seven-point fundamental matrices. They follow Chum's C+implementation in pydegensac (``DegUtils.c``, ``ranH.c``, ``rtools.h``, ``exp_ranF.c``): the H-degeneracy test of a+seven-point sample (``checksample``), the local optimization of the homography (``innerH``), and the plane-and-parallax+search (``rFtH``). Points are Hartley-normalized homogeneous points, and every threshold is a squared distance in that+frame.+"""++from __future__ import annotations++import math+import sys+from typing import List, Optional, Tuple++import torch++from kornia.geometry.epipolar._metrics import _sampson_from_quadratic_basis, _sampson_quadratic_basis+from kornia.geometry.epipolar.numeric import cross_product_matrix+from kornia.geometry.homography import find_homography_dlt, sampson_homography_distance++# Every five-element subset of seven correspondences contains one of these triplets (paper, section 3).+_TRIPLETS = ((0, 1, 2), (3, 4, 5), (0, 1, 6), (3, 4, 6), (2, 5, 6))+# innerH (ranH.c, rtools.h): repetitions, least-squares steps, initial selection multiple, points per fit, subset cap.+_RAN_REP = 10+_ILSQ_ITERS = 4+_TC = 4+_INL_LIMIT = 10+_SUBSET_CAP = 12+# SC_M scoring (rtools.h, the compiled __SCORE__): the MSAC gain truncates at 9/4 of the threshold.+_GAIN_SCALE = 9.0 / 4.0+# rFtH (DegUtils.c): stopping confidence, draw cap, support a kept model must exceed (sam_sizO), models kept.+_PP_CONFIDENCE = 0.999+_PP_MAX_DRAWS = 20000+_PP_MIN_SUPPORT = 4+_PP_KEEP = 8+# Two planes are the same when their inlier sets have a Jaccard index of at least this (VSAC's criterion for models).+_SAME_PLANE = 0.95+++def _left_epipole(F: torch.Tensor) -> torch.Tensor:+ """Unit left null vectors ``(B, 3)`` of rank-2 matrices ``(B, 3, 3)``: ``F^T e' = 0``, the epipoles in image 2."""+ columns = F.mT+ crosses = torch.linalg.cross(columns[:, [0, 0, 1]], columns[:, [1, 2, 2]])+ best = crosses.square().sum(-1).argmax(1)+ e = crosses[torch.arange(F.shape[0], device=F.device), best]+ return e * e.square().sum(-1, keepdim=True).rsqrt()+++def _homographies_from_fundamental(F: torch.Tensor, x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:+ """Plane homographies ``(..., T, 3, 3)`` through triplets ``x1``, ``x2`` for ``F`` ``(..., 3, 3)``.++ ``H = A - e' (M^{-1} b)^T`` with ``A = [e']_x F``, ``M`` the triplet's homogeneous first-image points as rows and+ ``b_i = (x'_i x A x_i)^T (x'_i x e') / |x'_i x e'|^2`` (Hartley and Zisserman, result 13.6; the paper's eq. 4).+ A collinear triplet gives a NaN homography.+ """+ e = _left_epipole(F.reshape(-1, 3, 3)).reshape(*F.shape[:-2], 3)+ A = cross_product_matrix(e) @ F+ c1 = torch.linalg.cross(x2, x1 @ A[..., None, :, :].mT)+ c2 = torch.linalg.cross(x2, e[..., None, None, :].expand_as(x2))+ b = (c1 * c2).sum(-1) / c2.square().sum(-1)+ v, info = torch.linalg.solve_ex(x1, b)+ v = v.masked_fill((info != 0)[..., None], float("nan"))+ return A[..., None, :, :] - e[..., None, :, None] * v[..., None, :]+++def _h_degenerate_sample(+ F: torch.Tensor, x1: torch.Tensor, x2: torch.Tensor, threshold: float+) -> Optional[torch.Tensor]:+ """Chum's ``checksample``: a homography through at least five of the seven correspondences, if there is one.++ ``F`` ``(3, 3)`` is a seven-point model of the sample ``x1``, ``x2`` ``(7, 3)`` (homogeneous, ``w = 1``). Each+ triplet of :data:`_TRIPLETS` gives a homography compatible with ``F``; it is refitted by DLT to the five+ correspondences closest to it, and the sample is H-degenerate when five or more then have a squared Sampson+ distance below ``threshold``. Returns the first such homography ``(3, 3)``, or None.+ """+ index = torch.tensor(_TRIPLETS, device=x1.device)+ H = _homographies_from_fundamental(F, x1[index], x2[index])+ H = H[torch.isfinite(H).flatten(1).all(1)]+ if len(H) == 0:+ return None+ errors = sampson_homography_distance(x1[None, :, :2], x2[None, :, :2], H)+ closest = errors.argsort(1)[:, :5]+ refit = find_homography_dlt(x1[closest][..., :2], x2[closest][..., :2], solver="svd")+ errors = sampson_homography_distance(x1[None, :, :2], x2[None, :, :2], refit)+ degenerate = ((errors < threshold).sum(1) >= 5) & torch.isfinite(refit).flatten(1).all(1)+ if not bool(degenerate.any()):+ return None+ return refit[int(degenerate.nonzero()[0, 0])]+++def _h_degenerate_samples(+ F: torch.Tensor, x1: torch.Tensor, x2: torch.Tensor, threshold: float+) -> List[Optional[torch.Tensor]]:+ """Batch the deterministic degeneracy tests of ``F`` ``(B, 3, 3)`` and samples ``(B, 7, 3)``.++ Return the first qualifying triplet's refitted homography per sample, or None, as+ :func:`_h_degenerate_sample` does. RANSAC still recovers these samples in draw order; batching only their+ independent checks preserves the private generator and the previously searched planes.+ """+ result: List[Optional[torch.Tensor]] = [None] * len(F)+ if len(F) == 0:+ return result+ index = torch.tensor(_TRIPLETS, device=x1.device)+ H = _homographies_from_fundamental(F, x1[:, index], x2[:, index]).flatten(0, 1)+ rows = torch.isfinite(H).flatten(1).all(1).nonzero().flatten()+ if len(rows) == 0:+ return result+ owners = rows // len(_TRIPLETS)+ p1, p2 = x1[owners, :, :2], x2[owners, :, :2]+ errors = sampson_homography_distance(p1, p2, H[rows])+ closest = errors.argsort(1)[:, :5, None].expand(-1, -1, 2)+ refit = find_homography_dlt(p1.gather(1, closest), p2.gather(1, closest), solver="svd")+ errors = sampson_homography_distance(p1, p2, refit)+ degenerate = ((errors < threshold).sum(1) >= 5) & torch.isfinite(refit).flatten(1).all(1)+ for row in degenerate.nonzero().flatten().tolist():+ owner = int(owners[row])+ if result[owner] is None:+ result[owner] = refit[row]+ return result+++def _plane_parallax_fundamentals(+ H: torch.Tensor, x1: torch.Tensor, x2: torch.Tensor, first: torch.Tensor, second: torch.Tensor+) -> torch.Tensor:+ """Fundamental matrices ``(P, 3, 3)`` of unit Frobenius norm from a plane homography and pairs of correspondences.++ Plane and parallax (Hartley and Zisserman, section 13.3): the line through ``H x1`` and ``x2`` of an off-plane+ correspondence passes through the epipole, so two of them give ``e' = l_i x l_j`` and ``F = [e']_x H``. ``x1``,+ ``x2`` are homogeneous ``(n, 3)``; ``first`` and ``second`` ``(P,)`` index them. Parallel lines give NaN.+ """+ lines = torch.linalg.cross(x1 @ H.mT, x2)+ epipoles = torch.linalg.cross(lines[first], lines[second])+ # Parallel lines meet nowhere. Their cross product is exactly 0 only without fused multiply-adds; with them it is+ # rounding noise that would normalize into an arbitrary finite model, so a relative test makes both give NaN.+ scale = lines[first].norm(dim=-1) * lines[second].norm(dim=-1)+ parallel = epipoles.norm(dim=-1) <= 64 * torch.finfo(epipoles.dtype).eps * scale+ epipoles = epipoles.masked_fill(parallel[:, None], float("nan"))+ F = cross_product_matrix(epipoles) @ H+ return F * F.square().sum((-2, -1), keepdim=True).rsqrt()+++def _msac_gain(errors: torch.Tensor, threshold: float) -> torch.Tensor:+ """Chum's ``SC_M`` score ``(C,)`` of squared errors ``(C, N)``: ``sum(max(0, 1 - e / (9/4 threshold)))``."""+ return (1.0 - errors / (_GAIN_SCALE * threshold)).clamp_min(0.0).sum(1)+++def _best_candidate(gains: torch.Tensor, alive: torch.Tensor) -> Optional[int]:+ """Index of the first largest finite gain among live candidates, or None.++ Candidates are in the order Chum's loops visit them; ``scoreLess`` is strict, so a tie keeps the earlier one, which+ is also the index ``argmax`` returns.+ """+ gains = torch.where(alive & torch.isfinite(gains), gains, torch.full_like(gains, -math.inf))+ if not bool(torch.isfinite(gains).any()):+ return None+ return int(gains.argmax())+++def _inner_homography(+ H: torch.Tensor, x1: torch.Tensor, x2: torch.Tensor, threshold: float, generator: Optional[torch.Generator]+) -> Tuple[torch.Tensor, torch.Tensor]:+ """Chum's ``innerH``: the local optimization of ``H`` ``(3, 3)``, scored with the homography Sampson distance.++ ``x1``, ``x2`` are ``(N, 2)`` float64 host points and ``threshold`` is ``16 t``. ``inHrani`` runs+ :data:`_RAN_REP` repetitions, batched here: each fits a DLT to a random subset of ``min(n / 2, 12)`` of the ``n``+ inliers of ``H`` and refines it with ``iterH``: a fit to that model's inliers, then :data:`_ILSQ_ITERS` refits with+ the selection threshold lowered from ``4 * threshold`` by ``3 * threshold / 4`` after each, every fit using at most+ :data:`_INL_LIMIT` selected points, a random subset when there are more. A repetition whose subset model has fewer+ than 4 inliers contributes nothing; one whose selection falls below 4 points stops. Every evaluated model is a+ candidate, ranked by :func:`_msac_gain`. ``innerH`` passes 10 as the argument it calls ``iters``, which+ ``inHrani`` receives as ``inlLimit``; the repetition count is the constant ``RAN_REP``, also 10.++ Returns:+ The best candidate, or ``H`` when no repetition produced one (``inHrani`` leaves it unchanged), and its squared+ Sampson distances ``(N,)``.+ """+ n_points = x1.shape[0]+ pts1, pts2 = x1[None], x2[None]++ def errors_of(models: torch.Tensor) -> torch.Tensor:+ return sampson_homography_distance(pts1, pts2, models)++ def fit(selected: torch.Tensor, cap: int) -> torch.Tensor:+ # A uniform random subset of at most ``cap`` selected points per row; zero weights pad the rest.+ keys = torch.rand(selected.shape, generator=generator, dtype=x1.dtype).masked_fill(~selected, -1.0)+ top = keys.topk(min(cap, n_points), dim=1)+ weights = (top.values >= 0).to(x1.dtype)+ return find_homography_dlt(x1[top.indices], x2[top.indices], weights, solver="svd")++ base = errors_of(H[None])[0]+ inliers = base <= threshold+ count = int(inliers.sum())+ if count < 8:+ return H, base+ models = fit(inliers.expand(_RAN_REP, -1), min(count // 2, _SUBSET_CAP))+ errors = errors_of(models)+ selected = errors <= threshold+ alive = selected.sum(1) >= 4+ candidates: List[torch.Tensor] = [models]+ gains: List[torch.Tensor] = [_msac_gain(errors, threshold)]+ live: List[torch.Tensor] = [alive]+ models = fit(selected, _INL_LIMIT)+ selection = _TC * threshold+ step = (selection - threshold) / _ILSQ_ITERS+ for _ in range(_ILSQ_ITERS):+ errors = errors_of(models)+ candidates.append(models)+ gains.append(_msac_gain(errors, threshold))+ live.append(alive)+ selected = errors <= selection+ alive = alive & (selected.sum(1) >= 4)+ models = fit(selected, _INL_LIMIT)+ selection -= step+ errors = errors_of(models)+ candidates.append(models)+ gains.append(_msac_gain(errors, threshold))+ live.append(alive)+ best = _best_candidate(torch.stack(gains, 1).flatten(), torch.stack(live, 1).flatten())+ if best is None:+ return H, base+ winner = torch.stack(candidates, 1).flatten(0, 1)[best]+ return winner, errors_of(winner[None])[0]+++def _repeats_plane(plane: torch.Tensor, seen: List[torch.Tensor]) -> bool:+ """Whether the inlier mask ``plane`` matches one in ``seen``: a Jaccard index of at least 0.95.++ Every degenerate record setter of a dominant plane finds that plane again; VSAC likewise skips the local+ optimization of a model whose inliers repeat the best one's (Ivashechkin, Barath and Matas, ICCV 2021).+ """+ return any(float((plane & other).sum()) >= _SAME_PLANE * float((plane | other).sum()) for other in seen)+++def _inside_plane(inliers: torch.Tensor, seen: List[torch.Tensor]) -> bool:+ """Whether 95% or more of the inlier mask ``inliers`` lies inside one plane of ``seen``.++ The test for a sample's own, noisier homography before its refinement: its inliers are a subset of a plane already+ refined in the call rather than a match of it. Another plane's correspondences are inliers of the first plane only+ near the line where the two meet.+ """+ return any(float((inliers & plane).sum()) >= _SAME_PLANE * float(inliers.sum()) for plane in seen)+++def _pair_draws(support: int, total: int, confidence: float) -> int:+ """Two-point samples needed for ``confidence`` with ``support`` inliers among ``total`` correspondences.++ :meth:`~kornia.geometry.ransac.RANSAC.max_samples_by_conf` for a sample of two, which this module cannot import.+ """+ if support >= total:+ return 1+ probability = support * (support - 1) / (total * (total - 1))+ if probability <= 0.0:+ return sys.maxsize+ return min(sys.maxsize, math.ceil(math.log1p(-confidence) / math.log1p(-probability)))+++def _plane_parallax_search(+ H: torch.Tensor,+ x1: torch.Tensor,+ x2: torch.Tensor,+ threshold: float,+ batch: int,+ generator: Optional[torch.Generator],+) -> Optional[Tuple[torch.Tensor, torch.Tensor]]:+ """Chum's ``rFtH``: plane-and-parallax RANSAC over pairs of off-plane correspondences.++ ``x1``, ``x2`` ``(n, 3)`` are the off-plane correspondences, normalized, on their device; ``H`` is the plane+ homography there and ``threshold`` is ``2 t``. Pairs are drawn on the host from ``generator`` (a device's generator+ cannot draw on the host) in batches of ``batch`` and moved to the device. A model's support counts the off-plane+ correspondences with a squared Sampson distance below ``threshold``; drawing stops at twice the two-point bound for+ the best support at confidence 0.999, as ``rFtH``'s loop runs to ``2 * max_sam``, or after 20000 draws.++ Returns:+ Up to eight models with more than four off-plane inliers and their support, best first, or None.+ """+ n = x1.shape[0]+ basis = _sampson_quadratic_basis(x1, x2)+ kept = x1.new_zeros(0, 3, 3)+ kept_support = torch.zeros(0, dtype=torch.long, device=x1.device)+ best, drawn, limit = 0, 0, _PP_MAX_DRAWS+ while drawn < limit:+ size = min(batch, limit - drawn)+ first = (torch.rand(size, generator=generator, dtype=torch.float64) * n).long()+ second = (torch.rand(size, generator=generator, dtype=torch.float64) * (n - 1)).long()+ second = second + (second >= first).long()+ models = _plane_parallax_fundamentals(H, x1, x2, first.to(x1.device), second.to(x1.device))+ support = (_sampson_from_quadratic_basis(models, basis) < threshold).sum(1)+ kept_support, order = torch.cat([kept_support, support]).topk(min(_PP_KEEP, len(kept_support) + size))+ kept = torch.cat([kept, models])[order]+ drawn += size+ best = max(best, int(kept_support[0]))+ if best > _PP_MIN_SUPPORT:+ limit = min(limit, 2 * _pair_draws(best, n, _PP_CONFIDENCE))+ qualifying = kept_support > _PP_MIN_SUPPORT+ if not bool(qualifying.any()):+ return None+ return kept[qualifying], kept_support[qualifying]diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.pyindex d626749e0..ab0b7797f 100644--- a/kornia/geometry/homography.py+++ b/kornia/geometry/homography.py@@ -15,12 +15,13 @@# limitations under the License.#+import mathimport warningsfrom typing import Optional, Tupleimport torch-from kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPEfrom kornia.core.utils import _extract_device_dtype, _torch_svd_cast, safe_inverse_with_mask, safe_solve_with_maskfrom kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneousfrom kornia.geometry.epipolar import normalize_points, normalize_transformation@@ -37,6 +38,7 @@ __all__ = ["line_segment_transfer_error_one_way","oneway_transfer_error","sample_is_valid_for_homography",+ "sampson_homography_distance","symmetric_transfer_error",]@@ -177,6 +179,84 @@ def symmetric_transfer_error(return torch.where(good_H_reshape, out, max_tensor)+def sampson_homography_distance(+ pts1: torch.Tensor, pts2: torch.Tensor, H: torch.Tensor, squared: bool = True+) -> torch.Tensor:+ r"""Return the Sampson distance of correspondences to homographies.++ The first-order approximation of the geometric error: the squared distance by which ``pts1`` and ``pts2``+ together must move for :math:`x_2 \sim H x_1` to hold (Hartley and Zisserman, *Multiple View Geometry*, 2nd ed.,+ section 4.2.6). With :math:`x_1 = (x, y, 1)`, :math:`x_2 = (u, v, 1)` and :math:`H x_1 = (p, q, w)`, the+ algebraic residuals :math:`\epsilon = (v w - q, p - u w)` and their Jacobian :math:`J` with respect to+ :math:`(x, y, u, v)` give :math:`d^2 = \epsilon^\top (J J^\top)^{-1} \epsilon`.++ Convention:+ - Argument order and direction as :func:`oneway_transfer_error`: ``H`` maps ``pts1`` to ``pts2``. Unlike the+ one-way transfer error, the distance accounts for noise in both images and does not depend on the scale+ of ``H``.+ - For an affine ``H`` the constraint is linear in the coordinates, and the distance is the exact geometric+ error.+ - An exact correspondence scores 0; a correspondence whose :math:`J J^\top` is singular scores ``inf``; a+ non-finite correspondence or homography gives NaN.+ - Computed in at least float32 and returned in the promoted dtype of the inputs, or in float32 when they are+ all integers.++ Args:+ pts1: points in the first image with shape :math:`(B, N, 2)`, or homogeneous :math:`(B, N, 3)`.+ pts2: points in the second image with shape :math:`(B, N, 2)`, or homogeneous :math:`(B, N, 3)`.+ H: homographies with shape :math:`(B, 3, 3)`. Points with a leading dimension of 1 are scored against every+ homography.+ squared: if True (default), the squared distance is returned, else the distance.++ Returns:+ the computed distance with shape :math:`(B, N)`.++ """+ KORNIA_CHECK_SHAPE(H, ["B", "3", "3"])+ KORNIA_CHECK(pts1.shape[-1] in (2, 3) and pts2.shape[-1] in (2, 3), "points must have 2 or 3 coordinates")+ dtype = torch.promote_types(torch.promote_types(pts1.dtype, pts2.dtype), H.dtype)+ work = torch.promote_types(dtype, torch.float32)+ # Integer coordinates give a floating distance. Everything runs in at least float32, the dehomogenization too:+ # x / w of a small w overflows float16.+ out_dtype = dtype if dtype.is_floating_point else work+ pts1, pts2 = pts1.to(work), pts2.to(work)+ if pts1.shape[-1] == 3:+ finite = torch.isfinite(pts1).all(-1, keepdim=True)+ pts1 = convert_points_from_homogeneous(pts1).masked_fill(~finite, float("nan"))+ if pts2.shape[-1] == 3:+ finite = torch.isfinite(pts2).all(-1, keepdim=True)+ pts2 = convert_points_from_homogeneous(pts2).masked_fill(~finite, float("nan"))+ x, y = pts1[..., 0], pts1[..., 1]+ u, v = pts2[..., 0], pts2[..., 1]+ # The distance does not depend on the scale of H, but its quadratic is of fourth order in H: dividing by the+ # largest entry keeps tiny and huge finite scales in range. A zero H stays zero, and non-finite entries give NaN.+ H = H.to(work)+ scale = H.abs().amax(dim=(-2, -1), keepdim=True)+ h = (H / torch.where(scale > 0, scale, torch.ones_like(scale)))[..., None]+ p = h[..., 0, 0, :] * x + h[..., 0, 1, :] * y + h[..., 0, 2, :]+ q = h[..., 1, 0, :] * x + h[..., 1, 1, :] * y + h[..., 1, 2, :]+ w = h[..., 2, 0, :] * x + h[..., 2, 1, :] * y + h[..., 2, 2, :]+ e1, e2 = v * w - q, p - u * w+ # Jacobian rows over (x, y, u, v): (v h20 - h10, v h21 - h11, 0, w) and (h00 - u h20, h01 - u h21, -w, 0).+ jx1, jy1 = v * h[..., 2, 0, :] - h[..., 1, 0, :], v * h[..., 2, 1, :] - h[..., 1, 1, :]+ jx2, jy2 = h[..., 0, 0, :] - u * h[..., 2, 0, :], h[..., 0, 1, :] - u * h[..., 2, 1, :]+ a = jx1.square() + jy1.square() + w.square()+ c = jx2.square() + jy2.square() + w.square()+ b = jx1 * jx2 + jy1 * jy2+ det = a * c - b.square()+ num = c * e1.square() - 2 * b * e1 * e2 + a * e2.square()+ # A singular J J^T has no finite correction. The division takes a safe denominator inside the where, so the+ # inf branch leaves finite gradients (#4229); rounding can make the quadratic form slightly negative. NaN fails+ # every comparison below and passes through, as in oneway_transfer_error.+ d2 = num / torch.where(det > 0, det, torch.ones_like(det))+ d2 = torch.where(det <= 0, torch.full_like(det, math.inf), d2)+ d2 = torch.where(d2 < 0, torch.zeros_like(d2), d2)+ if not squared:+ positive = d2 > 0+ d2 = torch.where(positive, torch.where(positive, d2, torch.ones_like(d2)).sqrt(), d2)+ return d2.to(out_dtype)++def line_segment_transfer_error_one_way(ls1: torch.Tensor, ls2: torch.Tensor, H: torch.Tensor, squared: bool = False) -> torch.Tensor:diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.pyindex e2041ac69..802df72c6 100644--- a/kornia/geometry/ransac.py+++ b/kornia/geometry/ransac.py@@ -22,12 +22,20 @@ from __future__ import annotationsimport mathimport sysfrom functools import lru_cache, partial-from typing import Callable, Optional, Tuple, Union+from typing import Callable, List, Optional, Tuple, Unionimport torchfrom torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.geometry._degensac import (+ _h_degenerate_sample,+ _h_degenerate_samples,+ _inner_homography,+ _inside_plane,+ _plane_parallax_search,+ _repeats_plane,+)from kornia.geometry.conversions import convert_points_to_homogeneousfrom kornia.geometry.epipolar import find_essential, find_fundamental, project_to_essential, sampson_epipolar_distancefrom kornia.geometry.epipolar._metrics import _sampson_from_quadratic_basis, _sampson_quadratic_basis@@ -52,6 +60,7 @@ from kornia.geometry.homography import (find_homography_lines_dlt_iterated,oneway_transfer_error,sample_is_valid_for_homography,+ sampson_homography_distance,)__all__ = ["RANSAC"]@@ -62,6 +71,8 @@ _DEFAULT_BATCH = 2048# Model types that local_optimization="lm" supports, and how many minimal models it refines._LM_MODELS = ("homography", "fundamental", "fundamental_7pt", "fundamental_8pt", "essential")_LM_CANDIDATES = 8+# Model types that DEGENSAC supports: seven-point fundamental matrices (Chum, Werner and Matas, CVPR 2005).+_DEGENSAC_MODELS = ("fundamental", "fundamental_7pt")@lru_cache(maxsize=32)@@ -78,6 +89,18 @@ def _prosac_growth(sample_size: int, pop_size: int, budget: int) -> Tuple[int, .return tuple(ends)+def _resolve_degensac(degensac: Optional[bool], model_type: str, local_optimization: str) -> bool:+ """The ``degensac`` setting of :class:`RANSAC`: None leaves it off; True requires support."""+ if degensac is not None and not isinstance(degensac, bool):+ raise ValueError(f"degensac must be None, True or False, got {degensac!r}")+ supported = model_type in _DEGENSAC_MODELS and local_optimization == "lm"+ if degensac and not supported:+ raise ValueError(+ 'degensac=True requires model_type "fundamental" or "fundamental_7pt" with local_optimization="lm"'+ )+ return False if degensac is None else degensac++def _normalize_correspondences(kp1: torch.Tensor, kp2: torch.Tensor, shared_scale: bool) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, float, float]:@@ -142,10 +165,25 @@ class RANSAC(nn.Module):model from its inliers: with the default ``lo_sample_size=32``, ``max_lo_iters`` randomized refits on32-inlier subsets followed by one full-inlier refit; ``lo_sample_size=None`` refits all inliersiteratively.+ - ``degensac=True``, an opt-in for ``"fundamental"`` and ``"fundamental_7pt"`` with+ ``local_optimization="lm"``, runs DEGENSAC (Chum, Werner and Matas, CVPR 2005). Every seven-point model that+ sets a new record among the raw scores is tested for an H-degenerate sample: five or more of its seven+ correspondences related by one homography. Such a model fits the dominant plane and whatever happens to+ agree with it off the plane, so the homography is refined, and fundamental matrices are drawn from it and+ pairs of correspondences off the plane (plane and parallax). The best of them, refined, joins the+ eight-model pool and, when it outscores the incumbent, sets the stopping bound. Thresholds and iteration+ counts follow Chum's implementation in pydegensac; the draws come from a private host generator. A plane+ already searched in the call is not searched again: a sample whose homography's inliers lie 95% or more+ inside it is skipped before refinement, and a refined plane whose inliers match it (Jaccard index 0.95 or+ more) before the search. The default, ``degensac=False``, keeps the plain seven-point loop.+ Explicit recovery reproduces that result exactly when no record-setting sample is degenerate.+ Chum's tolerance, three times the squared threshold for five of the seven correspondences, also flags+ samples in many scenes without a dominant plane; there the recovered models only join the competition.- ``prosac_sampling=True`` expects correspondences sorted best-first and stops with PROSAC'stermination-length test; ``confidence=1`` runs the whole ``batch_size * max_iter`` budget.- A seeded call uses a private generator and leaves torch's global RNG state unchanged; ``seed=None``- draws from the global generator.+ draws the minimal samples from the global generator. DEGENSAC's recovery draws always come from a private+ host generator, which an unseeded call seeds from the sample that triggers the recovery.Args:model_type: "homography", "fundamental", "fundamental_7pt", "fundamental_8pt", "essential", or@@ -176,6 +214,9 @@ class RANSAC(nn.Module):fundamental and essential matrices and ``"dlt"`` for line segments.refine_iters: Levenberg-Marquardt iterations of the final refinement with ``local_optimization="lm"``;zero disables it.+ degensac: run DEGENSAC's dominant-plane recovery, as described above. Defaults to False; None also leaves+ it off. True enables it for ``"fundamental"`` and ``"fundamental_7pt"`` with ``local_optimization="lm"``,+ the only supported combinations; True with any other raises ``ValueError``."""@@ -194,6 +235,7 @@ class RANSAC(nn.Module):max_samples: Optional[int] = None,local_optimization: Optional[str] = None,refine_iters: int = 3,+ degensac: Optional[bool] = False,) -> None:"""Initialize the RANSAC estimator.@@ -221,6 +263,9 @@ class RANSAC(nn.Module):final robust refinement) or ``"dlt"`` (refits of each new best model); None picks ``"lm"`` where itis supported, for homographies, fundamental and essential matrices.refine_iters: Levenberg-Marquardt iterations of the final refinement on the inliers with ``"lm"``.+ degensac: opt-in DEGENSAC dominant-plane recovery for seven-point fundamental matrices.+ Defaults to False; None also leaves it off. True requires seven-point matrices with+ local_optimization="lm"."""super().__init__()@@ -258,6 +303,7 @@ class RANSAC(nn.Module):raise ValueError(f'local_optimization must be "lm" or "dlt", got {local_optimization!r}')if local_optimization == "lm" and model_type not in _LM_MODELS:raise ValueError(f'local_optimization="lm" supports {", ".join(_LM_MODELS)}, not {model_type!r}')+ degensac = _resolve_degensac(degensac, model_type, local_optimization)self.score_type = score_typeself.inl_th = inl_thself.max_iter = max_iter@@ -272,6 +318,7 @@ class RANSAC(nn.Module):self.lo_sample_size = lo_sample_sizeself.local_optimization = local_optimizationself.refine_iters = refine_iters+ self.degensac = degensac# The PROSAC growth schedule as a device tensor, reused across the batches of a call.self._prosac_ends: Optional[Tuple[Tuple[int, int, int, torch.device], torch.Tensor]] = None@@ -888,35 +935,64 @@ class RANSAC(nn.Module):inliers_best_total = torch.zeros_like(inliers_best_total)return best_model_total, inliers_best_total- def _lm_minimal_models(self, x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:+ def _lm_minimal_models(+ self, x1: torch.Tensor, x2: torch.Tensor, track_origins: bool = False+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:"""Minimal models ``(M, 3, 3)`` of normalized (for essential matrices, calibrated) samples ``(B, m, 3)``.Samples that :func:`~kornia.geometry.homography.sample_is_valid_for_homography` rejects and absent roots ofthe seven-point cubic are dropped on CPU; on other devices, where dropping would need a synchronization, theyare NaN models, which score no inliers. The orientation test is unaffected by the normalization, atranslation and a positive scale.++ Returns:+ The models and the sample row ``(M,)`` each was solved from, in draw order: sample by sample, and root by+ root within a sample, as DEGENSAC's record setters need them. The sample rows are None unless+ ``track_origins=True``, avoiding this bookkeeping for plain RANSAC."""compact = x1.device.type == "cpu"+ rows = torch.arange(x1.shape[0], device=x1.device) if track_origins else Noneif self.model_type == "homography":oriented = sample_is_valid_for_homography(x1[..., :2], x2[..., :2])if compact:x1, x2 = x1[oriented], x2[oriented]+ if rows is not None:+ rows = rows[oriented]if len(x1) == 0:- return x1.new_zeros(0, 3, 3)- return _four_point_homography(x1, x2)+ return x1.new_zeros(0, 3, 3), rows+ return _four_point_homography(x1, x2), rowsmodels = _four_point_homography(x1, x2)- return models.masked_fill(~oriented[:, None, None], float("nan"))+ return models.masked_fill(~oriented[:, None, None], float("nan")), rowsdesign = _epipolar_design_rows(x1, x2)if self.model_type == "essential":# Samples with a non-finite correspondence, rank-deficient samples and complex roots give NaN slots.candidates, valid = _five_point_candidates(design)- return candidates[valid] if compact else candidates.flatten(0, 1)+ if rows is not None:+ rows = rows.repeat_interleave(candidates.shape[1])+ if compact:+ return candidates[valid], rows[valid.flatten()] if rows is not None else None+ return candidates.flatten(0, 1), rowsif self.minimal_sample_size == 7:candidates, valid = _seven_point_candidates(design)models = candidates.masked_fill(~valid[..., None, None], float("nan")).flatten(0, 1)+ if rows is not None:+ rows = rows.repeat_interleave(candidates.shape[1])else:models = _eight_point_fundamental(design)- return models[torch.isfinite(models).flatten(1).all(1)] if compact else models+ if compact:+ keep = torch.isfinite(models).flatten(1).all(1)+ return models[keep], rows[keep] if rows is not None else None+ return models, rows++ @staticmethod+ def _raw_record_setters(scores: torch.Tensor, prior: float) -> List[int]:+ """Indices of the models, in draw order, whose score beats ``prior`` and every earlier score of the batch.++ The models a sequential loop would find to set a new raw record (Chum's ``maxSs``), found at once with a+ running maximum over the CPU ``scores``.+ """+ earlier = torch.cat([scores.new_full((1,), prior), torch.cummax(scores, 0).values[:-1]])+ return (scores > earlier.clamp_min(prior)).nonzero().flatten().tolist()def _lm_errors(self, models: torch.Tensor, x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:"""Squared residuals ``(M, N)`` of normalized models on normalized correspondences (calibrated: essential)."""@@ -979,6 +1055,177 @@ class RANSAC(nn.Module):return _refine_essential_lm(models, x1, x2, mask, loss, scale2, iters)return _refine_fundamental_lm(models, x1, x2, mask, loss, scale2, iters)+ def _degensac_recover(+ self,+ model: torch.Tensor,+ sample: torch.Tensor,+ x1: torch.Tensor,+ x2: torch.Tensor,+ x1_host: torch.Tensor,+ x2_host: torch.Tensor,+ basis: torch.Tensor,+ threshold: float,+ generator: Optional[torch.Generator],+ seen_planes: Optional[List[torch.Tensor]] = None,+ homography: Optional[torch.Tensor] = None,+ ) -> Optional[Tuple[torch.Tensor, torch.Tensor, torch.Tensor, Optional[torch.Tensor]]]:+ """DEGENSAC's recovery of a raw record setter (Chum, Werner and Matas, CVPR 2005; Chum's ``exp_ranF.c``).++ ``model`` ``(3, 3)`` is a seven-point model of ``sample`` ``(7,)``, both on the device of the normalized+ correspondences ``x1``, ``x2`` ``(N, 3)``; ``x1_host``, ``x2_host`` are the same correspondences on the host in+ float64, NaN where not finite; ``threshold`` is the squared threshold ``t`` of that frame. When the sample is+ H-degenerate and its homography has at least 8 inliers at ``3 t``, the homography is refined (``innerH``), and+ with more than 6 plane inliers at ``16 t`` and at least 4 correspondences beyond ``100 t``, plane-and-parallax+ models are drawn from those (:mod:`kornia.geometry._degensac`), unless ``seen_planes``, the refined planes'+ inlier masks of the call's earlier recoveries, already holds the plane (:func:`_repeats_plane`); a new plane+ is appended to it. The best-scoring model is refined like the pool, with ``max_lo_iters`` truncated+ Levenberg-Marquardt iterations, Chum's ``innerFH`` role, and the better of it and its refinement is returned+ alone, as ``rFtH`` returns one model: near-duplicates from one search would crowd the eight-model pool.++ ``homography``, when supplied, is the result of the batch's degeneracy check in float64 on the host.++ Returns:+ The recovered model ``(1, 3, 3)`` with its score, support and, with PROSAC, inlier mask, as+ :meth:`_lm_score_models` returns them; None when the sample is not H-degenerate or nothing is recovered.+ """+ m = self.minimal_sample_size+ if homography is None:+ sample_host = sample.cpu()+ homography = _h_degenerate_sample(+ model.detach().cpu().double(), x1_host[sample_host], x2_host[sample_host], 3 * threshold+ )+ if homography is None:+ return None+ rows = (torch.isfinite(x1_host).all(1) & torch.isfinite(x2_host).all(1)).nonzero().flatten()+ p1, p2 = x1_host[rows, :2], x2_host[rows, :2]+ errors = sampson_homography_distance(p1[None], p2[None], homography[None])[0]+ planes = [] if seen_planes is None else seen_planes+ # A plane already searched in this call is skipped before its refinement when the sample's own homography+ # falls inside it, and after when the refined plane matches it.+ if int((errors < 3 * threshold).sum()) < 8 or _inside_plane(errors <= 16 * threshold, planes):+ return None+ homography, errors = _inner_homography(homography, p1, p2, 16 * threshold, generator)+ plane, off_plane = errors <= 16 * threshold, errors > 100 * threshold+ if _repeats_plane(plane, planes):+ return None+ planes.append(plane)+ if int(plane.sum()) <= 6 or int(off_plane.sum()) < 4:+ return None+ off_rows = rows[off_plane].to(x1.device)+ found = _plane_parallax_search(+ homography.to(x1.device, x1.dtype),+ x1[off_rows],+ x2[off_rows],+ 2 * threshold,+ 256 if x1.device.type == "cpu" else 2048,+ generator,+ )+ if found is None:+ return None+ models = found[0]+ scores, counts, masks = self._lm_score_models(models, basis, threshold)+ scores = scores.masked_fill(counts <= m, -1.0)+ if float(scores.max()) < 0:+ return None+ best = int(scores.argmax())+ raw = models[best : best + 1], scores[best : best + 1], counts[best : best + 1]+ raw_mask = None if masks is None else masks[best : best + 1]+ if self.max_lo_iters == 0:+ return (*raw, raw_mask)+ refined = self._lm_refine(+ raw[0].cpu().double(), x1_host[rows], x2_host[rows], None, "truncated", threshold, self.max_lo_iters+ ).to(x1.device, x1.dtype)+ scores, counts, masks = self._lm_score_models(refined, basis, threshold)+ scores = scores.masked_fill(counts <= m, -1.0)+ # The truncated loss is not the score: with score_type="ransac" a step can trade inliers (568 -> 566 on one+ # dominant-plane sample). Keep the better model, the refit on ties.+ if float(scores[0]) < float(raw[1][0]):+ return (*raw, raw_mask)+ return refined, scores, counts, masks++ @staticmethod+ def _lm_pool(+ candidates: torch.Tensor, candidate_scores: torch.Tensor, models: torch.Tensor, scores: torch.Tensor+ ) -> Tuple[torch.Tensor, torch.Tensor]:+ """The pool's ``_LM_CANDIDATES`` best models and scores after adding ``models``, placed first for ties."""+ candidate_scores, order = torch.cat([scores, candidate_scores]).topk(+ min(_LM_CANDIDATES, len(scores) + len(candidate_scores))+ )+ return torch.cat([models, candidates])[order], candidate_scores++ def _lm_stopping_bound(+ self, masks: Optional[torch.Tensor], row: Union[int, torch.Tensor], support: int, num_tc: int+ ) -> int:+ """Samples to draw for an incumbent with ``support`` inliers, as in OpenCV's USAC.++ PROSAC's termination test on ``masks[row]`` when PROSAC keeps masks, else the classic bound.+ """+ if masks is not None:+ return self._prosac_max_samples(masks[row], support)+ return min(+ self.sample_budget, self.max_samples_by_conf(support, num_tc, self.minimal_sample_size, self.confidence)+ )++ def _degensac_batch(+ self,+ models: torch.Tensor,+ samples: torch.Tensor,+ scores: torch.Tensor,+ prior: float,+ x1: torch.Tensor,+ x2: torch.Tensor,+ x1_host: torch.Tensor,+ x2_host: torch.Tensor,+ basis: torch.Tensor,+ threshold: float,+ iteration: int,+ seen_planes: Optional[List[torch.Tensor]] = None,+ ) -> List[Tuple[torch.Tensor, torch.Tensor, torch.Tensor, Optional[torch.Tensor]]]:+ """DEGENSAC's recoveries of a batch's raw record setters, in draw order (:meth:`_raw_record_setters`).++ ``models`` ``(M, 3, 3)`` were solved from ``samples`` ``(M, 7)`` and scored ``scores``; ``prior`` is the raw+ record before the batch. Every recovery draw comes from one private host generator per batch: a device+ generator cannot draw on the host, and the global one, which an unseeded call's minimal samples come from,+ must not advance, or every later sample of the call would differ from ``degensac=False``. A seeded call seeds+ it ``seed + 2 * sample_budget + iteration``; an unseeded one from the first record setter's sample, drawn from+ the global generator, so that its draws still differ between calls.+ """+ # Transfer and test all record setters together; only the subsequent recovery depends on earlier planes.+ records = self._raw_record_setters(scores.cpu(), prior)+ if not records:+ return []+ generator = torch.Generator()+ if self.seed is not None:+ generator.manual_seed(self.seed + 2 * self.sample_budget + iteration)+ else:+ # Python hashes a tuple of ints the same in every process.+ generator.manual_seed(hash(tuple(samples[records[0]].tolist())) & 0x7FFFFFFFFFFFFFFF)+ planes = [] if seen_planes is None else seen_planes+ recoveries = []+ samples_host = samples[records].cpu()+ homographies = _h_degenerate_samples(+ models[records].detach().cpu().double(), x1_host[samples_host], x2_host[samples_host], 3 * threshold+ )+ for record, homography in zip(records, homographies):+ if homography is None:+ continue+ recovered = self._degensac_recover(+ models[record],+ samples[record],+ x1,+ x2,+ x1_host,+ x2_host,+ basis,+ threshold,+ generator,+ planes,+ homography,+ )+ if recovered is not None:+ recoveries.append(recovered)+ return recoveries+def _forward_lm(self, kp1: torch.Tensor, kp2: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:"""RANSAC with batched minimal solvers and Levenberg-Marquardt local optimization and refinement.@@ -1023,14 +1270,20 @@ class RANSAC(nn.Module):grow = not isinstance(self.batch_size, int)candidates, candidate_scores = x1.new_zeros(0, 3, 3), x1.new_zeros(0)best_score = -1.0+ # DEGENSAC tests the models that set a new raw record (Chum's maxSs), which recovered models never raise;+ # best_score is the incumbent's, over raw and recovered models (maxS).+ degensac = self.degensac and m == 7+ best_minimal_score = -1.0+ seen_planes: List[torch.Tensor] = []max_samples, drawn, iteration = budget, 0, 0while drawn < max_samples:current = min(batch, max_samples - drawn)indices = self.sample(m, num_tc, current, iteration, device, offset=drawn)+ batch_iteration = iterationdrawn, iteration = drawn + current, iteration + 1if grow:batch = min(2 * batch, largest)- models = self._lm_minimal_models(x1[indices], x2[indices])+ models, origin = self._lm_minimal_models(x1[indices], x2[indices], track_origins=degensac)if len(models) == 0:continue# Reject insufficient support before ranking: high MSAC scores from minimal samples alone must not@@ -1040,20 +1293,40 @@ class RANSAC(nn.Module):top_scores, top = scores_all.topk(min(_LM_CANDIDATES, len(models)))top_counts = counts_all[top]# The run's best minimal models so far, refined after sampling.- candidate_scores, order = torch.cat([top_scores, candidate_scores]).topk(- min(_LM_CANDIDATES, len(top_scores) + len(candidate_scores))- )- candidates = torch.cat([models[top], candidates])[order]+ candidates, candidate_scores = self._lm_pool(candidates, candidate_scores, models[top], top_scores)scores, counts = torch.stack([top_scores, top_counts.to(top_scores.dtype)]).tolist()best = max(range(len(scores)), key=scores.__getitem__)if scores[best] > best_score:# The bound follows the new incumbent's own support, as with local_optimization="dlt".best_score = scores[best]- if masks_all is not None:- max_samples = self._prosac_max_samples(masks_all[top[best]], int(counts[best]))- else:- support = int(counts[best])- max_samples = min(budget, self.max_samples_by_conf(support, num_tc, m, self.confidence))+ max_samples = self._lm_stopping_bound(masks_all, top[best], int(counts[best]), num_tc)+ if origin is None or scores[best] <= best_minimal_score:+ continue+ recoveries = self._degensac_batch(+ models,+ indices[origin],+ scores_all,+ best_minimal_score,+ x1,+ x2,+ x1_host,+ x2_host,+ basis,+ threshold,+ batch_iteration,+ seen_planes,+ )+ best_minimal_score = scores[best]+ for recovered_models, recovered_scores, recovered_counts, recovered_masks in recoveries:+ candidates, candidate_scores = self._lm_pool(+ candidates, candidate_scores, recovered_models, recovered_scores+ )+ winner = int(recovered_scores.argmax())+ if float(recovered_scores[winner]) > best_score:+ best_score = float(recovered_scores[winner])+ max_samples = self._lm_stopping_bound(+ recovered_masks, winner, int(recovered_counts[winner]), num_tc+ )x1_host, x2_host = x1_host[finite], x2_host[finite]candidates = candidates.to(host).double()[candidate_scores.to(host) >= 0]if len(candidates) == 0:diff --git a/testing/geometry/create.py b/testing/geometry/create.pyindex 48a4e9ffc..46d888d32 100644--- a/testing/geometry/create.py+++ b/testing/geometry/create.py@@ -17,7 +17,8 @@from __future__ import annotations-from typing import Optional, Union+import math+from typing import Optional, Tuple, Unionimport torch@@ -109,3 +110,72 @@ def generate_two_view_random_scene("x1": x1,"x2": x2,}+++def create_dominant_plane_scene(+ num_points: int,+ inlier_ratio: float,+ plane_fraction: float,+ seed: int,+ zoom: float = 1.0,+ skew: float = 0.0,+ noise: float = 0.5,+ device: Optional[torch.device] = None,+ dtype: torch.dtype = torch.float32,+) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:+ """Two views of a scene where ``plane_fraction`` of the inliers lie on one plane, DEGENSAC's regime.++ Camera 1 has a focal length of 800 px and principal point (320, 240). Camera 2 is rotated 8 degrees about y and+ 3 about x, translated by (-1, 0.1, 0.15), with focal length ``800 * zoom`` and skew ``800 * zoom * skew``. Plane+ points lie on z = 6 + 0.2 x; off-plane points at depths 2.5 to 10.5. Inliers get Gaussian noise of ``noise`` px in+ both images; outliers are uniform in 640 x 480. Generated in float64 on the CPU from ``seed``, then shuffled.++ Returns:+ ``kp1``, ``kp2`` ``(N, 2)``; ``labels`` ``(N,)``: 0 plane, 1 off-plane inlier, 2 outlier; and the noise-free+ off-plane points of both images ``(M, 2)``, to measure whether an estimate explains the off-plane geometry.+ """+ f64 = torch.float64+ generator = torch.Generator().manual_seed(seed)++ def rotation(axis: str, degrees: float) -> torch.Tensor:+ c, s = math.cos(math.radians(degrees)), math.sin(math.radians(degrees))+ if axis == "y":+ return torch.tensor([[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]], dtype=f64)+ return torch.tensor([[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]], dtype=f64)++ K1 = torch.tensor([[800.0, 0.0, 320.0], [0.0, 800.0, 240.0], [0.0, 0.0, 1.0]], dtype=f64)+ K2 = torch.tensor(+ [[800.0 * zoom, 800.0 * zoom * skew, 320.0], [0.0, 800.0 * zoom, 240.0], [0.0, 0.0, 1.0]], dtype=f64+ )+ R = rotation("y", 8.0) @ rotation("x", 3.0)+ t = torch.tensor([-1.0, 0.1, 0.15], dtype=f64)++ def project(K: torch.Tensor, X: torch.Tensor) -> torch.Tensor:+ x = X @ K.T+ return x[:, :2] / x[:, 2:]++ num_inliers = int(num_points * inlier_ratio)+ num_plane = int(num_inliers * plane_fraction)+ num_off = num_inliers - num_plane+ xy = (torch.rand(num_plane, 2, generator=generator, dtype=f64) - 0.5) * torch.tensor([4.0, 3.0], dtype=f64)+ plane = torch.cat([xy, 6.0 + 0.2 * xy[:, :1]], 1)+ depth = 2.5 + 8.0 * torch.rand(num_off, 1, generator=generator, dtype=f64)+ ray = (torch.rand(num_off, 2, generator=generator, dtype=f64) - 0.5) * torch.tensor([0.6, 0.45], dtype=f64)+ off = torch.cat([ray * depth, depth], 1) + torch.tensor([0.3, 0.0, 0.0], dtype=f64)+ X = torch.cat([plane, off])+ clean1, clean2 = project(K1, X), project(K2, X @ R.T + t)+ kp1 = clean1 + noise * torch.randn(clean1.shape, generator=generator, dtype=f64)+ kp2 = clean2 + noise * torch.randn(clean2.shape, generator=generator, dtype=f64)+ num_outliers = num_points - num_inliers+ size = torch.tensor([640.0, 480.0], dtype=f64)+ kp1 = torch.cat([kp1, torch.rand(num_outliers, 2, generator=generator, dtype=f64) * size])+ kp2 = torch.cat([kp2, torch.rand(num_outliers, 2, generator=generator, dtype=f64) * size])+ labels = torch.cat([torch.zeros(num_plane), torch.ones(num_off), torch.full((num_outliers,), 2.0)]).long()+ order = torch.randperm(num_points, generator=generator)+ return (+ kp1[order].to(device, dtype),+ kp2[order].to(device, dtype),+ labels[order].to(device),+ clean1[num_plane:].to(device, dtype),+ clean2[num_plane:].to(device, dtype),+ )diff --git a/tests/api_surface.json b/tests/api_surface.jsonindex fbbe9f3e0..f87c4ad9a 100644--- a/tests/api_surface.json+++ b/tests/api_surface.json@@ -553,6 +553,7 @@"rotation_matrix_to_quaternion","sample_is_valid_for_homography","sampson_epipolar_distance",+ "sampson_homography_distance","save_pointcloud_ply","save_pointcloud_ply_binary","scale",diff --git a/tests/geometry/test_degensac.py b/tests/geometry/test_degensac.pynew file mode 100644index 000000000..46404771e--- /dev/null+++ b/tests/geometry/test_degensac.py@@ -0,0 +1,299 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++import math++import pytest+import torch++import kornia.geometry._degensac as degensac_module+from kornia.geometry._degensac import (+ _best_candidate,+ _h_degenerate_sample,+ _homographies_from_fundamental,+ _inner_homography,+ _left_epipole,+ _msac_gain,+ _pair_draws,+ _plane_parallax_fundamentals,+ _plane_parallax_search,+)+from kornia.geometry.epipolar.fundamental import _epipolar_design_rows, _seven_point_candidates+from kornia.geometry.epipolar.numeric import cross_product_matrix+from kornia.geometry.homography import oneway_transfer_error, sampson_homography_distance+from kornia.geometry.ransac import RANSAC++# The kernels run on the host in float64 by design (RANSAC moves one sample there), so these tests do not take the+# device and dtype fixtures; RANSAC's own tests cover the device paths.+F64 = torch.float64+++def _two_view_geometry():+ """A calibrated pair, the plane z - 0.2 x = 6 and its homography, and F; all in pixels, float64."""+ K = torch.tensor([[800.0, 0.0, 320.0], [0.0, 800.0, 240.0], [0.0, 0.0, 1.0]], dtype=F64)+ a, b = math.radians(8.0), math.radians(3.0)+ Ry = torch.tensor([[math.cos(a), 0.0, math.sin(a)], [0.0, 1.0, 0.0], [-math.sin(a), 0.0, math.cos(a)]], dtype=F64)+ Rx = torch.tensor([[1.0, 0.0, 0.0], [0.0, math.cos(b), -math.sin(b)], [0.0, math.sin(b), math.cos(b)]], dtype=F64)+ R, t = Ry @ Rx, torch.tensor([-1.0, 0.1, 0.15], dtype=F64)+ normal, distance = torch.tensor([-0.2, 0.0, 1.0], dtype=F64), 6.0+ K_inv = torch.linalg.inv(K)+ H = K @ (R + torch.outer(t, normal) / distance) @ K_inv+ F = K_inv.T @ cross_product_matrix(t) @ R @ K_inv+ return K, R, t, H / H[2, 2], F / F.norm()+++def _points(K, R, t, count, planar, generator):+ if planar:+ xy = (torch.rand(count, 2, generator=generator, dtype=F64) - 0.5) * torch.tensor([4.0, 3.0], dtype=F64)+ X = torch.cat([xy, 6.0 + 0.2 * xy[:, :1]], 1)+ else:+ X = torch.cat(+ [+ (torch.rand(count, 2, generator=generator, dtype=F64) - 0.5) * 2,+ 3 + 5 * torch.rand(count, 1, generator=generator, dtype=F64),+ ],+ 1,+ )+ x1, x2 = X @ K.T, (X @ R.T + t) @ K.T+ return x1 / x1[:, 2:], x2 / x2[:, 2:]+++def _same_up_to_scale(A, B):+ A, B = A / A.norm(), B / B.norm()+ return float(torch.minimum((A - B).abs().max(), (A + B).abs().max()))+++class TestLeftEpipole:+ def test_null_vector_of_transpose(self):+ _, _, _, _, F = _two_view_geometry()+ e = _left_epipole(F[None])[0]+ assert float((F.T @ e).abs().max()) < 1e-12+ assert abs(float(e.norm()) - 1.0) < 1e-12+++class TestHomographiesFromFundamental:+ def test_recovers_plane_homography(self):+ K, R, t, H, F = _two_view_geometry()+ x1, x2 = _points(K, R, t, 3, True, torch.Generator().manual_seed(0))+ estimate = _homographies_from_fundamental(F, x1[None], x2[None])[0]+ assert _same_up_to_scale(estimate, H) < 1e-10+ compatibility = estimate.T @ F # skew-symmetric exactly when H is compatible with F+ assert float((compatibility + compatibility.T).abs().max()) < 1e-10 * float(compatibility.abs().max())++ def test_collinear_triplet_is_nan(self):+ _, _, _, _, F = _two_view_geometry()+ x1 = torch.tensor([[[0.0, 0.0, 1.0], [1.0, 1.0, 1.0], [2.0, 2.0, 1.0]]], dtype=F64)+ assert torch.isnan(_homographies_from_fundamental(F, x1, x1)).any()+++class TestHDegenerateSample:+ THRESHOLD = 3.0 # 3 t with t = 1 px^2; the sample is noise-free++ def test_five_plane_pairs_flag_the_compatible_root(self):+ # Five H-related pairs and two others: only one seven-point root is guaranteed compatible with H (paper,+ # section 2.3), so only that one must flag.+ K, R, t, H, _ = _two_view_geometry()+ generator = torch.Generator().manual_seed(1)+ p1, p2 = _points(K, R, t, 5, True, generator)+ o1, o2 = _points(K, R, t, 2, False, generator)+ x1, x2 = torch.cat([p1, o1]), torch.cat([p2, o2])+ candidates, valid = _seven_point_candidates(_epipolar_design_rows(x1[None], x2[None]))+ compatible = []+ for root in range(3):+ if not bool(valid[0, root]):+ continue+ product = H.T @ candidates[0, root]+ skew = float((product + product.T).abs().max() / product.abs().max())+ compatible.append((skew, root))+ _, root = min(compatible)+ assert _h_degenerate_sample(candidates[0, root], x1, x2, self.THRESHOLD) is not None++ @pytest.mark.parametrize("on_plane", [6, 7])+ def test_six_and_seven_plane_pairs_flag_a_compatible_model(self, on_plane):+ # Exact 6- and 7-of-7 data make the seven-point cubic vanish identically (paper, sections 2.1-2.2), so the+ # model is an explicit member of the compatible family F = [e']_x H rather than a solver root.+ K, R, t, H, _ = _two_view_geometry()+ generator = torch.Generator().manual_seed(2)+ p1, p2 = _points(K, R, t, on_plane, True, generator)+ o1, o2 = _points(K, R, t, 7 - on_plane, False, generator)+ x1, x2 = torch.cat([p1, o1]), torch.cat([p2, o2])+ F = cross_product_matrix(K @ t) @ H+ homography = _h_degenerate_sample(F / F.norm(), x1, x2, self.THRESHOLD)+ assert homography is not None+ assert _same_up_to_scale(homography, H) < 1e-6++ def test_general_position_does_not_flag(self):+ K, R, t, _, _ = _two_view_geometry()+ x1, x2 = _points(K, R, t, 7, False, torch.Generator().manual_seed(3))+ candidates, valid = _seven_point_candidates(_epipolar_design_rows(x1[None], x2[None]))+ for root in range(3):+ if bool(valid[0, root]):+ assert _h_degenerate_sample(candidates[0, root], x1, x2, self.THRESHOLD) is None++ def test_batched_checks_keep_sample_order_and_invalid_entries(self):+ K, R, t, _, F = _two_view_geometry()+ generator = torch.Generator().manual_seed(3)+ plane1, plane2 = _points(K, R, t, 7, True, generator)+ general1, general2 = _points(K, R, t, 7, False, generator)+ models = torch.stack([F, torch.zeros_like(F), F, torch.full_like(F, float("nan")), F])+ x1 = torch.stack([plane1, plane1, general1, plane1, plane1.flip(0)])+ x2 = torch.stack([plane2, plane2, general2, plane2, plane2.flip(0)])+ expected = [_h_degenerate_sample(f, a, b, self.THRESHOLD) for f, a, b in zip(models, x1, x2)]+ assert [h is not None for h in expected] == [True, False, False, False, True]+ actual = degensac_module._h_degenerate_samples(models, x1, x2, self.THRESHOLD)+ assert len(actual) == len(expected)+ for result, reference in zip(actual, expected):+ if reference is None:+ assert result is None+ else:+ assert result is not None and torch.equal(result, reference)++ @pytest.mark.parametrize("count", [0, 3])+ def test_empty_or_invalid_batch(self, count):+ models = torch.zeros(count, 3, 3, dtype=F64)+ samples = torch.ones(count, 7, 3, dtype=F64)+ assert degensac_module._h_degenerate_samples(models, samples, samples, self.THRESHOLD) == [None] * count+++class TestPlaneParallax:+ def test_two_off_plane_pairs_give_the_fundamental_matrix(self):+ K, R, t, H, F = _two_view_geometry()+ o1, o2 = _points(K, R, t, 4, False, torch.Generator().manual_seed(4))+ models = _plane_parallax_fundamentals(H, o1, o2, torch.tensor([0, 2]), torch.tensor([1, 3]))+ for model in models:+ assert _same_up_to_scale(model, F) < 1e-10+ assert abs(float(model.norm()) - 1.0) < 1e-12++ def test_parallel_lines_give_nan(self):+ _, _, _, H, _ = _two_view_geometry()+ x1 = torch.tensor([[100.0, 100.0, 1.0]], dtype=F64)+ x2 = torch.tensor([[150.0, 120.0, 1.0]], dtype=F64)+ models = _plane_parallax_fundamentals(H, x1, x2, torch.tensor([0]), torch.tensor([0]))+ assert torch.isnan(models).all()+++def _plane_with_outliers(H, generator, noise=1.0, count=300, outliers=200):+ clean = torch.rand(count, 2, generator=generator, dtype=F64) * 100+ mapped = torch.cat([clean, torch.ones(count, 1, dtype=F64)], 1) @ H.T+ p1 = clean + noise * torch.randn(count, 2, generator=generator, dtype=F64)+ p2 = mapped[:, :2] / mapped[:, 2:] + noise * torch.randn(count, 2, generator=generator, dtype=F64)+ o1 = torch.rand(outliers, 2, generator=generator, dtype=F64) * 100+ o2 = torch.rand(outliers, 2, generator=generator, dtype=F64) * 400+ return torch.cat([p1, o1]), torch.cat([p2, o2])+++class TestInnerHomography:+ THRESHOLD = 16.0 # 16 t with t = 1 px^2++ def test_zoom_keeps_plane_inliers_a_transfer_cutoff_drops(self):+ # At a 4x zoom the one-way transfer error is about 17 times the Sampson one along the zoom, so the fixed+ # 32 t transfer cutoff the first design used would drop a third of the plane; innerH keeps it.+ H = torch.tensor([[4.0, 0.3, 10.0], [0.1, 4.0, -5.0], [1e-4, 0.0, 1.0]], dtype=F64)+ generator = torch.Generator().manual_seed(0)+ x1, x2 = _plane_with_outliers(H, generator)+ start = H * (1 + 1e-3 * torch.randn(3, 3, generator=generator, dtype=F64))+ _, errors = _inner_homography(start, x1, x2, self.THRESHOLD, torch.Generator().manual_seed(1))+ assert int((errors[:300] <= self.THRESHOLD).sum()) >= 297+ assert int((errors[300:] <= self.THRESHOLD).sum()) <= 5+ transfer = oneway_transfer_error(x1[None], x2[None], H[None])[0]+ assert int((transfer[:300] <= 2 * self.THRESHOLD).sum()) < 250++ def test_shear_keeps_plane_inliers(self):+ H = torch.tensor([[1.0, 1.5, 3.0], [0.0, 1.0, 2.0], [0.0, 0.0, 1.0]], dtype=F64)+ generator = torch.Generator().manual_seed(2)+ x1, x2 = _plane_with_outliers(H, generator)+ start = H * (1 + 1e-3 * torch.randn(3, 3, generator=generator, dtype=F64))+ _, errors = _inner_homography(start, x1, x2, self.THRESHOLD, torch.Generator().manual_seed(3))+ assert int((errors[:300] <= self.THRESHOLD).sum()) >= 297++ def test_seeded_generator_is_reproducible(self):+ H = torch.tensor([[1.1, 0.1, 3.0], [0.0, 0.9, 2.0], [1e-4, 0.0, 1.0]], dtype=F64)+ x1, x2 = _plane_with_outliers(H, torch.Generator().manual_seed(4))+ first = _inner_homography(H, x1, x2, self.THRESHOLD, torch.Generator().manual_seed(5))+ second = _inner_homography(H, x1, x2, self.THRESHOLD, torch.Generator().manual_seed(5))+ assert torch.equal(first[0], second[0]) and torch.equal(first[1], second[1])++ def test_repetitions_without_inliers_contribute_nothing(self, monkeypatch):+ # When every subset model h0 has fewer than 4 inliers, iterH returns an empty score, h0 included, so innerH+ # keeps the homography it was given. Were h0 kept as a candidate, its finite gain of 0 would win instead.+ H = torch.tensor([[1.1, 0.1, 3.0], [0.0, 0.9, 2.0], [1e-4, 0.0, 1.0]], dtype=F64)+ x1, x2 = _plane_with_outliers(H, torch.Generator().manual_seed(11))+ far = torch.tensor([[1.0, 0.0, 1e4], [0.0, 1.0, 1e4], [0.0, 0.0, 1.0]], dtype=F64)+ monkeypatch.setattr(+ degensac_module,+ "find_homography_dlt",+ lambda p1, p2, weights=None, solver="svd": far.expand(p1.shape[0], 3, 3).clone(),+ )+ homography, _ = _inner_homography(H, x1, x2, self.THRESHOLD, torch.Generator().manual_seed(12))+ assert torch.equal(homography, H)++ def test_too_few_inliers_keep_the_homography(self):+ H = torch.eye(3, dtype=F64)+ x1 = torch.rand(20, 2, generator=torch.Generator().manual_seed(6), dtype=F64) * 100+ x2 = x1 + 50.0 # no inliers of H at 16 t+ homography, errors = _inner_homography(H, x1, x2, self.THRESHOLD, None)+ assert torch.equal(homography, H)+ assert torch.equal(errors, sampson_homography_distance(x1[None], x2[None], H[None])[0])+++class TestCandidateRanking:+ def test_gain_not_count_decides(self):+ # Candidate 0 has more inliers at the threshold but larger errors; SC_M's gain prefers candidate 1.+ threshold = 1.0+ errors = torch.tensor([[0.9, 0.9, 0.9, 0.9], [0.0, 0.0, 0.0, 5.0]], dtype=F64)+ assert (errors <= threshold).sum(1).tolist() == [4, 3]+ gains = _msac_gain(errors, threshold)+ assert float(gains[1]) > float(gains[0])+ assert _best_candidate(gains, torch.tensor([True, True])) == 1++ def test_ties_keep_the_first_and_dead_candidates_never_win(self):+ gains = torch.tensor([1.0, 3.0, 3.0, 5.0], dtype=F64)+ assert _best_candidate(gains, torch.tensor([True, True, True, False])) == 1+ assert _best_candidate(gains, torch.zeros(4, dtype=torch.bool)) is None+ assert _best_candidate(torch.tensor([float("nan"), 2.0], dtype=F64), torch.tensor([True, True])) == 1+++class TestPlaneParallaxSearch:+ def test_pair_draws_match_ransac_bound(self):+ for support, total in [(5, 100), (30, 430), (99, 100), (2, 50)]:+ assert _pair_draws(support, total, 0.999) == RANSAC.max_samples_by_conf(support, total, 2, 0.999)++ def test_finds_the_epipolar_geometry_among_outliers(self):+ K, R, t, H, F = _two_view_geometry()+ generator = torch.Generator().manual_seed(7)+ o1, o2 = _points(K, R, t, 40, False, generator)+ r1 = torch.cat([torch.rand(200, 2, generator=generator, dtype=F64) * 640, torch.ones(200, 1, dtype=F64)], 1)+ r2 = torch.cat([torch.rand(200, 2, generator=generator, dtype=F64) * 480, torch.ones(200, 1, dtype=F64)], 1)+ x1, x2 = torch.cat([o1, r1]), torch.cat([o2, r2])+ # Unit-norm models on pixel coordinates lose accuracy in the quadratic Sampson basis; normalize like RANSAC.+ scale = 1.0 / 300.0+ T = torch.tensor([[scale, 0.0, -320 * scale], [0.0, scale, -240 * scale], [0.0, 0.0, 1.0]], dtype=F64)+ y1, y2 = x1 @ T.T, x2 @ T.T+ H_normalized = T @ H @ torch.linalg.inv(T)+ found = _plane_parallax_search(H_normalized, y1, y2, 2.0 * scale**2, 256, torch.Generator().manual_seed(8))+ assert found is not None+ models, support = found+ assert len(models) <= 8 and bool((support > 4).all()) and int(support[0]) >= 38+ best = T.T @ models[0] @ T # y = T x, so y2^T F y1 = x2^T (T^T F T) x1+ assert _same_up_to_scale(best, F) < 1e-6++ def test_no_consensus_returns_none(self):+ generator = torch.Generator().manual_seed(9)+ x1 = torch.cat([torch.rand(6, 2, generator=generator, dtype=F64), torch.ones(6, 1, dtype=F64)], 1)+ x2 = torch.cat([torch.rand(6, 2, generator=generator, dtype=F64), torch.ones(6, 1, dtype=F64)], 1)+ found = _plane_parallax_search(torch.eye(3, dtype=F64), x1, x2, 1e-12, 4096, torch.Generator().manual_seed(10))+ assert found is Nonediff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.pyindex 93c792b53..121ae0262 100644--- a/tests/geometry/test_homography.py+++ b/tests/geometry/test_homography.py@@ -38,8 +38,10 @@ from kornia.geometry.homography import (line_segment_transfer_error_one_way,oneway_transfer_error,sample_is_valid_for_homography,+ sampson_homography_distance,symmetric_transfer_error,)+from kornia.geometry.linalg import transform_pointsfrom testing.base import BaseTesterfrom testing.geometry.create import create_random_homography@@ -213,6 +215,219 @@ class TestSymmetricTransferError(BaseTester):assert torch.isfinite(pts1.grad).all()+def _projective_homography():+ """A homography with non-zero h31 and h32, in float64 on the CPU (MPS has no float64)."""+ return torch.tensor([[1.1, 0.2, 5.0], [-0.1, 0.9, -3.0], [2e-3, -1e-3, 1.0]], dtype=torch.float64)+++def _homography_residuals(point: torch.Tensor, H: torch.Tensor) -> torch.Tensor:+ """The two algebraic rows of ``x2 x H x1`` for one correspondence ``(x, y, u, v)``, as a Jacobian oracle."""+ x1 = torch.stack([point[0], point[1], torch.ones((), dtype=point.dtype)])+ Hx = H @ x1+ return torch.stack([point[3] * Hx[2] - Hx[1], Hx[0] - point[2] * Hx[2]])+++class TestSampsonHomographyDistance(BaseTester):+ # Expected values are formed in float64 on the CPU from the dtype-rounded inputs, then compared on the device.++ def test_smoke(self, device, dtype):+ pts1 = torch.rand(1, 6, 2, device=device, dtype=dtype)+ pts2 = torch.rand(1, 6, 2, device=device, dtype=dtype)+ H = create_random_homography(pts1, 3)+ assert sampson_homography_distance(pts1, pts2, H).shape == (1, 6)++ def test_points_broadcast_against_homographies(self, device, dtype):+ pts1 = torch.rand(1, 6, 2, device=device, dtype=dtype)+ pts2 = torch.rand(1, 6, 2, device=device, dtype=dtype)+ H = create_random_homography(torch.rand(4, 6, 2, device=device, dtype=dtype), 3)+ batched = sampson_homography_distance(pts1, pts2, H)+ assert batched.shape == (4, 6)+ for k in range(4):+ self.assert_close(batched[k : k + 1], sampson_homography_distance(pts1, pts2, H[k : k + 1]))++ def test_homogeneous_points(self, device, dtype):+ pts1 = torch.rand(2, 5, 2, device=device, dtype=dtype)+ pts2 = torch.rand(2, 5, 2, device=device, dtype=dtype)+ H = create_random_homography(pts1, 3)+ ones = torch.ones(2, 5, 1, device=device, dtype=dtype)+ self.assert_close(+ sampson_homography_distance(torch.cat([pts1, ones], -1), torch.cat([pts2, ones], -1), H),+ sampson_homography_distance(pts1, pts2, H),+ )++ def test_exact_correspondences_score_zero(self, device, dtype):+ H = _projective_homography()[None]+ pts1 = torch.rand(1, 10, 2, generator=torch.Generator().manual_seed(0), dtype=torch.float64)+ pts2 = transform_points(H, pts1)+ actual = sampson_homography_distance(pts1.to(device, dtype), pts2.to(device, dtype), H.to(device, dtype))+ # The floor is the rounding of the inputs (coordinates up to ~6), not the formula.+ atol = {torch.float16: 1e-3, torch.bfloat16: 1e-2}.get(dtype, 1e-6)+ self.assert_close(actual, torch.zeros_like(actual), rtol=0.0, atol=atol)++ def test_invariant_to_homography_scale(self, device, dtype):+ H = _projective_homography()[None].to(device, dtype)+ pts1 = torch.rand(1, 10, 2, device=device, dtype=dtype) * 10+ pts2 = torch.rand(1, 10, 2, device=device, dtype=dtype) * 10+ self.assert_close(+ sampson_homography_distance(pts1, pts2, 4.0 * H),+ sampson_homography_distance(pts1, pts2, H),+ low_tolerance=True,+ )++ def test_affine_equals_exact_geometric_error(self, device, dtype):+ # For x2 = A x1 + c the constraint is linear, so the first-order correction is exact: r^T (I + A A^T)^-1 r.+ H = torch.eye(3, dtype=torch.float64)+ H[:2, :2] = torch.tensor([[1.3, 0.4], [-0.2, 0.8]], dtype=torch.float64)+ H[:2, 2] = torch.tensor([2.0, -1.0], dtype=torch.float64)+ H = H.to(dtype)+ generator = torch.Generator().manual_seed(1)+ pts1 = (torch.rand(1, 8, 2, generator=generator, dtype=torch.float64) * 4).to(dtype)+ pts2 = (torch.rand(1, 8, 2, generator=generator, dtype=torch.float64) * 4).to(dtype)+ A, c = H[:2, :2].double(), H[:2, 2].double()+ r = pts2[0].double() - pts1[0].double() @ A.T - c+ expected = (r * torch.linalg.solve(torch.eye(2, dtype=torch.float64) + A @ A.T, r.T).T).sum(-1)+ actual = sampson_homography_distance(pts1.to(device), pts2.to(device), H[None].to(device))[0]+ self.assert_close(actual, expected.to(device, dtype))++ def test_projective_matches_independent_jacobian(self, device, dtype):+ # h31 and h32 are non-zero, so a wrong projective term in the hand-written Jacobian changes the value; the+ # affine case, scale invariance and gradcheck cannot see one.+ H = _projective_homography()+ generator = torch.Generator().manual_seed(2)+ pts1 = torch.rand(12, 2, generator=generator, dtype=torch.float64) * 100+ noise = 0.7 * torch.randn(12, 2, generator=generator, dtype=torch.float64)+ pts2 = transform_points(H[None], pts1[None])[0] + noise+ pts1, pts2 = pts1.to(dtype).double(), pts2.to(dtype).double()+ expected = []+ for point in torch.cat([pts1, pts2], 1):+ e = _homography_residuals(point, H.to(dtype).double())+ J = torch.func.jacrev(_homography_residuals)(point, H.to(dtype).double())+ expected.append(e @ torch.linalg.solve(J @ J.T, e))+ expected = torch.stack(expected)+ actual = sampson_homography_distance(+ pts1[None].to(device, dtype), pts2[None].to(device, dtype), H[None].to(device, dtype)+ )+ self.assert_close(actual[0], expected.to(device, dtype), low_tolerance=True)++ def test_close_to_gold_standard_correction(self, device):+ # First order: within 1% of the exact two-image correction, found by Gauss-Newton, at 0.5 px noise.+ if device.type == "mps":+ pytest.skip("the reference correction needs float64")+ dtype = torch.float64+ H = _projective_homography().to(device)+ generator = torch.Generator().manual_seed(3)+ clean = (torch.rand(30, 2, generator=generator, dtype=dtype) * 100).to(device)+ pts1 = clean + 0.5 * torch.randn(30, 2, generator=generator, dtype=dtype).to(device)+ noise = 0.5 * torch.randn(30, 2, generator=generator, dtype=dtype).to(device)+ pts2 = transform_points(H[None], clean[None])[0] + noise+ estimate = pts1.clone()+ for _ in range(30):+ estimate = estimate.requires_grad_(True)+ residual = torch.cat([pts1 - estimate, pts2 - transform_points(H[None], estimate[None])[0]], 1)+ jacobian = torch.stack(+ [torch.autograd.grad(residual[:, k].sum(), estimate, retain_graph=True)[0] for k in range(4)], 1+ )+ estimate, residual = estimate.detach(), residual.detach()+ estimate = estimate - torch.linalg.solve(jacobian.mT @ jacobian, jacobian.mT @ residual[..., None])[..., 0]+ gold = (pts1 - estimate).square().sum(1) + (pts2 - transform_points(H[None], estimate[None])[0]).square().sum(1)+ self.assert_close(sampson_homography_distance(pts1[None], pts2[None], H[None])[0], gold, rtol=1e-2, atol=1e-6)++ def test_distance_is_root_of_squared(self, device, dtype):+ pts1 = torch.rand(1, 6, 2, device=device, dtype=dtype)+ pts2 = torch.rand(1, 6, 2, device=device, dtype=dtype)+ H = create_random_homography(pts1, 3)+ self.assert_close(+ sampson_homography_distance(pts1, pts2, H, squared=False),+ sampson_homography_distance(pts1, pts2, H).sqrt(),+ )++ def test_non_finite_inputs_give_nan(self, device, dtype):+ # As with oneway_transfer_error, a non-finite correspondence or homography scores NaN; inf is kept for a+ # singular J J^T, a well-defined input without a finite correction.+ pts = torch.rand(1, 3, 2, device=device, dtype=dtype)+ pts[0, 1] = float("nan")+ H = torch.eye(3, device=device, dtype=dtype)[None]+ for squared in (True, False):+ distances = sampson_homography_distance(pts, pts + 0.1, H, squared=squared)+ assert bool(torch.isnan(distances[0, 1])) and bool(torch.isfinite(distances[0, [0, 2]]).all())+ nan_homography = torch.full((1, 3, 3), float("nan"), device=device, dtype=dtype)+ assert bool(torch.isnan(sampson_homography_distance(pts[:, :1], pts[:, :1], nan_homography)).all())++ @pytest.mark.parametrize("squared", [True, False])+ @pytest.mark.parametrize("invalid_input", [0, 1])+ def test_nonfinite_homogeneous_coordinates_give_nan(self, device, dtype, squared, invalid_input):+ points = torch.tensor([[[1.0, 2.0, 1.0]]], device=device, dtype=dtype).expand(1, 4, 3).clone()+ invalid = points.clone()+ invalid[0, 1:, 2] = invalid.new_tensor([float("nan"), float("inf"), -float("inf")])+ inputs = [points[..., :2], points[..., :2]]+ inputs[invalid_input] = invalid+ H = torch.eye(3, device=device, dtype=dtype)[None].expand(2, -1, -1)+ distances = sampson_homography_distance(*inputs, H, squared=squared)+ assert distances.shape == (2, 4)+ assert torch.isnan(distances[:, 1:]).all()+ self.assert_close(distances[:, 0], torch.zeros_like(distances[:, 0]))++ def test_extreme_homography_scales(self, device, dtype):+ # The quadratic has terms of fourth order in H, which underflow or overflow the working precision for tiny or+ # huge finite scales; the distance does not depend on the scale.+ if dtype == torch.float16:+ pytest.skip("scales that overflow the float32 working precision are not representable in float16")+ finfo = torch.finfo(torch.float64 if dtype == torch.float64 else torch.float32)+ pts1 = torch.zeros(1, 1, 2, device=device, dtype=dtype)+ pts2 = torch.tensor([[[1.0, 0.0]]], device=device, dtype=dtype)+ for scale in (finfo.tiny**0.3, finfo.max**0.3):+ H = scale * torch.eye(3, device=device, dtype=torch.float64 if device.type != "mps" else torch.float32)+ actual = sampson_homography_distance(pts1, pts2, H.to(dtype)[None])+ self.assert_close(actual, torch.full_like(actual, 0.5))++ def test_homogeneous_points_convert_in_working_precision(self, device, dtype):+ # x / w of a small w overflows float16 when it is formed in the input dtype; an exact correspondence is 0.+ pts = torch.tensor([[[1.0, 0.0, 1e-5]]], device=device, dtype=dtype)+ distance = sampson_homography_distance(pts, pts, torch.eye(3, device=device, dtype=dtype)[None])+ assert distance.tolist() == [[0.0]]++ def test_integer_inputs_give_a_floating_distance(self, device):+ # Pixel coordinates may be integers; the distance is computed in float32 and must not be cast back.+ pts1 = torch.tensor([[[0, 0]]], device=device)+ pts2 = torch.tensor([[[1, 0]]], device=device)+ distance = sampson_homography_distance(pts1, pts2, torch.eye(3, dtype=torch.long, device=device)[None])+ assert distance.dtype == torch.float32 and distance.tolist() == [[0.5]]++ def test_singular_jacobian_is_inf(self, device, dtype):+ # The zero matrix makes both residual rows and the Jacobian vanish: no finite correction exists.+ pts = torch.rand(1, 3, 2, device=device, dtype=dtype)+ H = torch.zeros(1, 3, 3, device=device, dtype=dtype)+ assert torch.isinf(sampson_homography_distance(pts, pts, H)).all()++ def test_exception(self, device, dtype):+ pts = torch.rand(1, 3, 2, device=device, dtype=dtype)+ with pytest.raises(Exception):+ sampson_homography_distance(pts, pts, torch.eye(3, device=device, dtype=dtype))+ with pytest.raises(Exception):+ sampson_homography_distance(pts[..., :1], pts[..., :1], torch.eye(3, device=device, dtype=dtype)[None])++ def test_gradcheck(self, device):+ pts1 = torch.rand(2, 4, 2, device=device, dtype=torch.float64)+ pts2 = pts1 + 0.1 * torch.rand(2, 4, 2, device=device, dtype=torch.float64)+ H = create_random_homography(pts1, 3)+ self.gradcheck(sampson_homography_distance, (pts1, pts2, H))+ self.gradcheck(lambda a, b, h: sampson_homography_distance(a, b, h, squared=False), (pts1, pts2, H))++ @pytest.mark.parametrize("homogeneous", [False, True])+ def test_dynamo(self, device, dtype, torch_optimizer, homogeneous):+ pts1 = torch.rand(2, 5, 2, device=device, dtype=dtype)+ pts2 = torch.rand(2, 5, 2, device=device, dtype=dtype)+ H = create_random_homography(pts1, 3)+ if homogeneous:+ pts1 = torch.cat([pts1, torch.ones_like(pts1[..., :1])], -1)+ pts2 = torch.cat([pts2, torch.ones_like(pts2[..., :1])], -1)+ pts1[0, 0, 2] = float("nan")+ op = sampson_homography_distance+ actual, expected = torch_optimizer(op)(pts1, pts2, H), op(pts1, pts2, H)+ assert torch.equal(actual.isnan(), expected.isnan())+ self.assert_close(actual.nan_to_num(), expected.nan_to_num())++class TestFindHomographyDLT(BaseTester):@pytest.mark.parametrize("solver", ["lu", "svd"])def test_zero_weight_outlier_does_not_change_estimate(self, solver, device, dtype):diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.pyindex 1a47671c9..40c304f9d 100644--- a/tests/geometry/test_ransac.py+++ b/tests/geometry/test_ransac.py@@ -23,16 +23,19 @@ import pytestimport torchimport kornia+import kornia.geometry.ransac as ransac_modulefrom kornia.geometry import RANSAC, transform_points+from kornia.geometry._degensac import _h_degenerate_samplefrom kornia.geometry.conversions import axis_angle_to_rotation_matrix, convert_points_from_homogeneousfrom kornia.geometry.epipolar import find_fundamental, project_to_essential, sampson_epipolar_distance-from kornia.geometry.epipolar._metrics import _sampson_errors+from kornia.geometry.epipolar._metrics import _sampson_errors, _sampson_quadratic_basisfrom kornia.geometry.epipolar.fundamental import _rank2_projection, _refine_fundamental_lmfrom kornia.geometry.homography import _refine_homography_lm, _transfer_errors, oneway_transfer_errorfrom kornia.geometry.ransac import _normalize_correspondencesfrom testing.base import BaseTesterfrom testing.casts import dict_to+from testing.geometry.create import create_dominant_plane_scene# RANSAC's batched minimal solvers take the Metal shader compiler down on the paravirtualized GPU# of the hosted macOS runners, and the next MPS allocation aborts the pytest process (SIGABRT).@@ -2104,3 +2107,537 @@ class TestRANSACScoring(BaseTester):self.assert_close(score, errors.new_tensor([1.75]))assert torch.equal(errors.isnan(), original.isnan())self.assert_close(errors.nan_to_num(), original.nan_to_num(), rtol=0, atol=0)+++class TestRANSACDegensacOptions(BaseTester):+ @pytest.mark.parametrize(+ "model_type", ["fundamental", "fundamental_7pt", "fundamental_8pt", "homography", "essential"]+ )+ def test_default_is_off(self, model_type):+ assert RANSAC(model_type).degensac is False++ @pytest.mark.parametrize("model_type", ["fundamental", "fundamental_7pt"])+ def test_explicit_opt_in(self, model_type):+ assert RANSAC(model_type, degensac=True).degensac is True++ def test_default_is_off_with_dlt(self):+ assert RANSAC("fundamental", local_optimization="dlt").degensac is False++ @pytest.mark.parametrize(+ ("model_type", "local_optimization"),+ [+ ("homography", None),+ ("essential", None),+ ("fundamental_8pt", None),+ ("fundamental", "dlt"),+ ("homography_from_linesegments", None),+ ],+ )+ def test_true_rejects_unsupported(self, model_type, local_optimization):+ with pytest.raises(ValueError, match="degensac"):+ RANSAC(model_type, local_optimization=local_optimization, degensac=True)++ def test_rejects_non_bool(self):+ with pytest.raises(ValueError, match="degensac"):+ RANSAC("fundamental", degensac=1)++ @pytest.mark.parametrize("model_type", ["fundamental", "fundamental_8pt", "homography", "essential"])+ def test_minimal_models_omit_unused_origins(self, model_type, device, dtype):+ ransac = RANSAC(model_type)+ work = torch.float64 if dtype == torch.float64 else torch.float32+ x1 = torch.cat([torch.rand(8, ransac.minimal_sample_size, 2), torch.ones(8, ransac.minimal_sample_size, 1)], -1)+ x2 = torch.cat([torch.rand_like(x1[..., :2]), torch.ones_like(x1[..., :1])], -1)+ x1, x2 = x1.to(device, work), x2.to(device, work)+ models, origin = ransac._lm_minimal_models(x1, x2)+ assert origin is None+ tracked_models, tracked_origin = ransac._lm_minimal_models(x1, x2, track_origins=True)+ assert tracked_origin is not None and len(tracked_origin) == len(models)+ assert torch.equal(models.isnan(), tracked_models.isnan())+ self.assert_close(models.nan_to_num(), tracked_models.nan_to_num(), atol=0, rtol=0)++ def test_raw_record_setters_are_draw_order_prefix_maxima(self):+ scores = torch.tensor([0.5, 2.0, 1.0, 3.0, 3.0, -1.0, 4.0])+ assert RANSAC._raw_record_setters(scores, 1.0) == [1, 3, 6]+ assert RANSAC._raw_record_setters(scores, 5.0) == []+ assert RANSAC._raw_record_setters(scores, -1.0) == [0, 1, 3, 6]++ @pytest.mark.parametrize("model_type", ["fundamental", "fundamental_8pt", "homography", "essential"])+ def test_lm_minimal_models_report_their_sample(self, model_type, device, dtype):+ # Every model fits its own sample far better than the other fifteen, so the reported row identifies it; the+ # eight-point model is not exact on its sample after the rank-2 projection, hence argmin rather than zero.+ work = torch.float64 if dtype == torch.float64 else torch.float32+ ransac = RANSAC(model_type)+ generator = torch.Generator().manual_seed(0)+ m = ransac.minimal_sample_size+ x1 = torch.cat([torch.rand(16, m, 2, generator=generator), torch.ones(16, m, 1)], -1)+ x2 = torch.cat([torch.rand(16, m, 2, generator=generator), torch.ones(16, m, 1)], -1)+ models, rows = ransac._lm_minimal_models(x1.to(device, work), x2.to(device, work), track_origins=True)+ assert rows is not None+ assert rows.shape == (len(models),) and rows.dtype == torch.long+ assert bool((rows[1:] >= rows[:-1]).all()) # draw order+ finite = torch.isfinite(models).flatten(1).all(1)+ models, rows = models[finite].cpu().double(), rows[finite].cpu()+ s1, s2 = x1.double(), x2.double()+ if model_type == "homography":+ mapped = torch.einsum("mij,snj->msni", models, s1)+ residual = (mapped[..., :2] / mapped[..., 2:] - s2[None, ..., :2]).norm(dim=-1).amax(-1)+ else:+ residual = torch.einsum("sni,mij,snj->msn", s2, models, s1).abs().amax(-1)+ assert float((residual.argmin(1) == rows).double().mean()) >= 0.9+++def _degensac_inputs(kp1, kp2, inl_th, device, work):+ """The normalized inputs ``_forward_lm`` builds for a seven-point fundamental matrix."""+ x1_host, x2_host, t1, t2, s1, _ = _normalize_correspondences(kp1.cpu().double(), kp2.cpu().double(), True)+ x1, x2 = x1_host.to(device, work), x2_host.to(device, work)+ return x1, x2, x1_host, x2_host, t1, t2, _sampson_quadratic_basis(x1, x2), (inl_th / s1) ** 2+++def _degenerate_sample(labels, generator):+ """Five plane correspondences and two outliers, an H-degenerate seven-point sample."""+ plane = (labels == 0).nonzero().flatten().cpu()+ outliers = (labels == 2).nonzero().flatten().cpu()+ return torch.cat(+ [+ plane[torch.randperm(len(plane), generator=generator)[:5]],+ outliers[torch.randperm(len(outliers), generator=generator)[:2]],+ ]+ )+++def _skip_half(dtype):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("the scene's pixel coordinates quantize at the noise scale in half precision")+++def _off_plane_error(F, clean1, clean2):+ """Median Sampson distance, in pixels, of the noise-free off-plane correspondences to F, on the host."""+ points1, points2 = clean1[None].cpu().double(), clean2[None].cpu().double()+ return float(sampson_epipolar_distance(points1, points2, F[None].cpu().double(), squared=False)[0].median())+++def _explains_off_plane(F, clean1, clean2):+ """Whether F puts the noise-free off-plane correspondences within 2 px of their epipolar lines (median)."""+ return bool(F.abs().sum() > 0) and _off_plane_error(F, clean1, clean2) < 2.0+++class TestRANSACDegensacRecovery(BaseTester):+ @pytest.mark.parametrize("max_lo_iters", [0, 5])+ def test_degenerate_samples_are_recovered(self, device, dtype, max_lo_iters):+ # Every sample the degeneracy test flags must come back as a model that explains the off-plane geometry;+ # a sample it does not flag must come back as None.+ _skip_half(dtype)+ work = torch.float64 if dtype == torch.float64 else torch.float32+ kp1, kp2, labels, clean1, clean2 = create_dominant_plane_scene(1000, 0.6, 0.95, 0, device=device, dtype=dtype)+ ransac = RANSAC("fundamental", inl_th=1.0, max_lo_iters=max_lo_iters, seed=0, degensac=True)+ x1, x2, x1_host, x2_host, t1, t2, basis, threshold = _degensac_inputs(kp1, kp2, 1.0, device, work)+ generator = torch.Generator().manual_seed(1)+ flagged = 0+ for _ in range(10):+ sample = _degenerate_sample(labels, generator)+ models, _ = ransac._lm_minimal_models(x1[sample.to(device)][None], x2[sample.to(device)][None])+ models = models[torch.isfinite(models).flatten(1).all(1)]+ scores, counts, _ = ransac._lm_score_models(models, basis, threshold)+ model = models[int(scores.masked_fill(counts <= 7, -1.0).argmax())]+ result = ransac._degensac_recover(+ model, sample.to(device), x1, x2, x1_host, x2_host, basis, threshold, torch.Generator().manual_seed(2)+ )+ degenerate = _h_degenerate_sample(model.cpu().double(), x1_host[sample], x2_host[sample], 3 * threshold)+ if degenerate is None:+ assert result is None+ continue+ flagged += 1+ assert result is not None+ out_models, scores, counts, masks = result+ assert masks is None+ # One model per recovery, as Chum's rFtH returns one: near-duplicates from one search would crowd the+ # eight-model pool (on the loftr_fund pair they cost test_real_dirty_7pt its margin in 2 of 20 seeds).+ assert out_models.shape == (1, 3, 3) and scores.shape == counts.shape == (1,)+ best = out_models[int(scores.argmax())].cpu().double()+ assert _explains_off_plane(t2.mT @ best @ t1, clean1.cpu(), clean2.cpu())+ assert flagged >= 5++ def test_record_checks_are_batched(self, device, dtype, monkeypatch):+ _skip_half(dtype)+ sizes = []+ original = ransac_module._h_degenerate_samples++ def check(models, *args):+ sizes.append(len(models))+ return original(models, *args)++ def scalar_check(*args):+ raise AssertionError("a record's already batched degeneracy test must not run again")++ monkeypatch.setattr(ransac_module, "_h_degenerate_samples", check)+ monkeypatch.setattr(ransac_module, "_h_degenerate_sample", scalar_check)+ kp1, kp2, _, clean1, clean2 = create_dominant_plane_scene(1000, 0.6, 0.95, 0, device=device, dtype=dtype)+ F, _ = RANSAC("fundamental", inl_th=1.0, seed=0, degensac=True)(kp1, kp2)+ assert sizes and max(sizes) > 1+ assert _explains_off_plane(F.cpu(), clean1.cpu(), clean2.cpu())++ @pytest.mark.parametrize("score_type", ["msac", "ransac"])+ def test_batched_recovery_matches_scalar_checks(self, device, dtype, score_type, monkeypatch):+ _skip_half(dtype)+ kp1, kp2, _, _, _ = create_dominant_plane_scene(1000, 0.6, 0.95, 5, device=device, dtype=dtype)+ estimator = RANSAC("fundamental", inl_th=1.0, seed=5, degensac=True, score_type=score_type)+ batched = estimator(kp1, kp2)++ def scalar_checks(models, x1, x2, threshold):+ return [_h_degenerate_sample(f, a, b, threshold) for f, a, b in zip(models, x1, x2)]++ monkeypatch.setattr(ransac_module, "_h_degenerate_samples", scalar_checks)+ scalar = estimator(kp1, kp2)+ assert torch.equal(batched[0], scalar[0]) and torch.equal(batched[1], scalar[1])++ def test_unseeded_recoveries_leave_the_global_generator(self, device, dtype):+ # The minimal samples of an unseeded call come from the global generator. Recoveries drawing from it too+ # would shift every later sample, so an unseeded call with a recovery would sample a different sequence than+ # degensac=False (on the loftr_fund pair: 9 of 20 global seeds with 2+ gross errors instead of 5).+ _skip_half(dtype)+ work = torch.float64 if dtype == torch.float64 else torch.float32+ kp1, kp2, labels, _, _ = create_dominant_plane_scene(1000, 0.6, 0.95, 0, device=device, dtype=dtype)+ ransac = RANSAC("fundamental", inl_th=1.0, degensac=True)+ x1, x2, x1_host, x2_host, _, _, basis, threshold = _degensac_inputs(kp1, kp2, 1.0, device, work)+ generator = torch.Generator().manual_seed(4)+ samples = torch.stack([_degenerate_sample(labels, generator) for _ in range(8)]).to(device)+ models, rows = ransac._lm_minimal_models(x1[samples], x2[samples], track_origins=True)+ assert rows is not None+ scores, counts, _ = ransac._lm_score_models(models, basis, threshold)+ scores = scores.masked_fill(counts <= 7, -1.0)+ state = torch.get_rng_state()+ recoveries = ransac._degensac_batch(+ models, samples[rows], scores, -1.0, x1, x2, x1_host, x2_host, basis, threshold, 0+ )+ assert recoveries # the recovery drew+ assert torch.equal(torch.get_rng_state(), state)++ def test_unseeded_recovery_draws_follow_the_samples(self, device, dtype, monkeypatch):+ # An unseeded call seeds its private recovery generator from the sample that triggered the recovery, which+ # comes from the global generator: the draws differ between calls without advancing it. A constant seed+ # would repeat the same draws, and so the same luck, on every unseeded call.+ _skip_half(dtype)+ seeds = []+ original = RANSAC._degensac_recover++ def spy(+ self,+ model,+ sample,+ x1,+ x2,+ x1_host,+ x2_host,+ basis,+ threshold,+ generator,+ seen_planes=None,+ homography=None,+ ):+ seeds.append(generator.initial_seed())+ return original(+ self, model, sample, x1, x2, x1_host, x2_host, basis, threshold, generator, seen_planes, homography+ )++ monkeypatch.setattr(RANSAC, "_degensac_recover", spy)+ kp1, kp2, _, _, _ = create_dominant_plane_scene(1000, 0.6, 0.95, 0, device=device, dtype=dtype)+ per_call = []+ for global_seed in (0, 1):+ seeds.clear()+ torch.manual_seed(global_seed)+ RANSAC("fundamental", inl_th=1.0, degensac=True)(kp1, kp2)+ per_call.append(set(seeds))+ assert per_call[0] and per_call[1] and per_call[0] != per_call[1]++ def test_repeated_plane_is_searched_once(self, device, dtype, monkeypatch):+ # Every degenerate record setter of a dominant plane finds the same plane (the refined planes of repeated+ # recoveries have Jaccard index 0.997-1.0 on these scenes), and nine searches of it per call made DEGENSAC+ # eleven times slower than plain RANSAC; VSAC skips a model whose inliers repeat (Jaccard index 0.95).+ _skip_half(dtype)+ work = torch.float64 if dtype == torch.float64 else torch.float32+ kp1, kp2, labels, _, _ = create_dominant_plane_scene(1000, 0.6, 0.95, 0, device=device, dtype=dtype)+ ransac = RANSAC("fundamental", inl_th=1.0, seed=0, degensac=True)+ x1, x2, x1_host, x2_host, _, _, basis, threshold = _degensac_inputs(kp1, kp2, 1.0, device, work)+ generator = torch.Generator().manual_seed(4)+ samples = torch.stack([_degenerate_sample(labels, generator) for _ in range(8)]).to(device)+ models, rows = ransac._lm_minimal_models(x1[samples], x2[samples], track_origins=True)+ assert rows is not None+ scores, counts, _ = ransac._lm_score_models(models, basis, threshold)+ scores = scores.masked_fill(counts <= 7, -1.0)+ records = [+ record+ for record in RANSAC._raw_record_setters(scores.cpu(), -1.0)+ if _h_degenerate_sample(+ models[record].cpu().double(),+ x1_host[samples[rows][record].cpu()],+ x2_host[samples[rows][record].cpu()],+ 3 * threshold,+ )+ is not None+ ]+ assert len(records) >= 2 # several degenerate record setters of the same plane+ calls = []+ original = ransac_module._plane_parallax_search+ monkeypatch.setattr(ransac_module, "_plane_parallax_search", lambda *a: calls.append(1) or original(*a))+ recoveries = ransac._degensac_batch(+ models, samples[rows], scores, -1.0, x1, x2, x1_host, x2_host, basis, threshold, 0+ )+ assert len(calls) == 1 and len(recoveries) == 1++ def test_dominant_plane_is_refined_once_per_call(self, device, dtype, monkeypatch):+ # A later record setter's homography is noisier than the refined plane (Jaccard index 0.03-1.0 against it at+ # N=4000), so a Jaccard test before innerH let one to five repeated refinements through per call; its inliers+ # lie inside the refined plane (98.3-100% of them in every repeat measured), which a containment test sees.+ _skip_half(dtype)+ refinements = []+ original = ransac_module._inner_homography+ monkeypatch.setattr(ransac_module, "_inner_homography", lambda *a: refinements.append(1) or original(*a))+ for seed in range(3):+ refinements.clear()+ kp1, kp2, _, _, _ = create_dominant_plane_scene(4000, 0.6, 0.95, seed, device=device, dtype=dtype)+ RANSAC("fundamental", inl_th=1.0, seed=seed, degensac=True)(kp1, kp2)+ assert len(refinements) == 1, f"seed {seed}"++ def test_dominant_plane_is_searched_at_most_twice_per_call(self, device, dtype, monkeypatch):+ _skip_half(dtype)+ calls = []+ original = ransac_module._plane_parallax_search+ monkeypatch.setattr(ransac_module, "_plane_parallax_search", lambda *a: calls.append(1) or original(*a))+ kp1, kp2, _, clean1, clean2 = create_dominant_plane_scene(1000, 0.6, 0.95, 0, device=device, dtype=dtype)+ F, _ = RANSAC("fundamental", inl_th=1.0, confidence=0.999, seed=0, degensac=True)(kp1, kp2)+ assert _explains_off_plane(F.cpu(), clean1.cpu(), clean2.cpu())+ assert 1 <= len(calls) <= 2 # one plane; nine searches before deduplication++ def _recover_once(self, max_lo_iters, score_type, scene_seed, device, dtype):+ """Recover the scene's first degenerate sample (5 plane + 2 outliers) with a fixed recovery generator."""+ work = torch.float64 if dtype == torch.float64 else torch.float32+ kp1, kp2, labels, _, _ = create_dominant_plane_scene(1000, 0.6, 0.95, scene_seed, device=device, dtype=dtype)+ x1, x2, x1_host, x2_host, _, _, basis, threshold = _degensac_inputs(kp1, kp2, 1.0, device, work)+ sample = _degenerate_sample(labels, torch.Generator().manual_seed(scene_seed)).to(device)+ ransac = RANSAC("fundamental", inl_th=1.0, score_type=score_type, max_lo_iters=max_lo_iters, degensac=True)+ models, _ = ransac._lm_minimal_models(x1[sample][None], x2[sample][None])+ models = models[torch.isfinite(models).flatten(1).all(1)]+ scores, counts, _ = ransac._lm_score_models(models, basis, threshold)+ model = models[int(scores.masked_fill(counts <= 7, -1.0).argmax())]+ generator = torch.Generator().manual_seed(999)+ return ransac._degensac_recover(model, sample, x1, x2, x1_host, x2_host, basis, threshold, generator)++ def test_refinement_never_lowers_the_recovered_score(self, device, dtype):+ # With score_type="ransac" the truncated LM can trade inliers: on this sample it took the recovered model from+ # 568 to 566. The recovery keeps the better of its raw and refined models.+ _skip_half(dtype)+ raw = self._recover_once(0, "ransac", 5, device, dtype)+ refined = self._recover_once(5, "ransac", 5, device, dtype)+ assert raw is not None and refined is not None+ assert float(refined[1][0]) >= float(raw[1][0])++ def test_worse_refinement_keeps_the_raw_model(self, device, dtype, monkeypatch):+ _skip_half(dtype)+ raw = self._recover_once(0, "msac", 0, device, dtype)+ # A "refinement" that returns a scrambled model scores far below the raw one.+ monkeypatch.setattr(RANSAC, "_lm_refine", lambda self, models, *args: models.roll(1, dims=-1))+ kept = self._recover_once(5, "msac", 0, device, dtype)+ assert raw is not None and kept is not None+ assert torch.equal(kept[0], raw[0]) and torch.equal(kept[1], raw[1])++ def test_non_degenerate_sample_returns_none(self, device, dtype):+ # Seven off-plane correspondences are not always in general position at the test's tolerance: a five-point+ # homography fit leaves two redundant constraints, and five of the first seven here fit one within 2.2 px^2+ # < 3 t. The contract is the implication: a sample the test does not flag is not recovered.+ _skip_half(dtype)+ work = torch.float64 if dtype == torch.float64 else torch.float32+ kp1, kp2, labels, _, _ = create_dominant_plane_scene(1000, 0.6, 0.5, 0, device=device, dtype=dtype)+ ransac = RANSAC("fundamental", inl_th=1.0, seed=0, degensac=True)+ x1, x2, x1_host, x2_host, _, _, basis, threshold = _degensac_inputs(kp1, kp2, 1.0, device, work)+ off_plane = (labels == 1).nonzero().flatten().cpu()+ unflagged = 0+ for group in range(6):+ sample = off_plane[7 * group : 7 * group + 7]+ models, _ = ransac._lm_minimal_models(x1[sample.to(device)][None], x2[sample.to(device)][None])+ for model in models[torch.isfinite(models).flatten(1).all(1)]:+ if _h_degenerate_sample(model.cpu().double(), x1_host[sample], x2_host[sample], 3 * threshold) is None:+ unflagged += 1+ recovered = ransac._degensac_recover(+ model, sample.to(device), x1, x2, x1_host, x2_host, basis, threshold, None+ )+ assert recovered is None+ assert unflagged >= 3+++_SCENES = {"frontal": {}, "zoom": {"zoom": 3.0}, "skew": {"skew": 0.5}}+++class TestRANSACDegensac(BaseTester):+ @pytest.mark.parametrize("scene", sorted(_SCENES))+ def test_recovers_dominant_plane(self, device, dtype, scene):+ # On main (a7d177cbf) plain seven-point RANSAC fails every one of these seeds on every scene on CPU, so the+ # explicit recovery's assertions fail there. Accelerators sample differently (MPS: plain succeeds on one+ # frontal and zoomed seed), so the plain count only asserts that the scenes stay hard for it.+ _skip_half(dtype)+ plain_failures = 0+ for seed in range(5):+ kp1, kp2, labels, clean1, clean2 = create_dominant_plane_scene(+ 1000, 0.6, 0.95, seed, device=device, dtype=dtype, **_SCENES[scene]+ )+ F, mask = RANSAC("fundamental", inl_th=1.0, confidence=0.999, seed=seed, degensac=True)(kp1, kp2)+ assert _explains_off_plane(F.cpu(), clean1.cpu(), clean2.cpu()), f"seed {seed}"+ off_plane = labels == 1+ assert float((mask & off_plane).sum()) >= 0.8 * float(off_plane.sum()), f"seed {seed}"+ F_plain, _ = RANSAC("fundamental", inl_th=1.0, confidence=0.999, seed=seed, degensac=False)(kp1, kp2)+ plain_failures += int(not _explains_off_plane(F_plain.cpu(), clean1.cpu(), clean2.cpu()))+ assert plain_failures >= 3++ @pytest.mark.parametrize("score_type", ["msac", "ransac"])+ def test_both_score_types(self, device, dtype, score_type):+ _skip_half(dtype)+ kp1, kp2, _, clean1, clean2 = create_dominant_plane_scene(1000, 0.6, 0.95, 0, device=device, dtype=dtype)+ F, _ = RANSAC("fundamental", inl_th=1.0, confidence=0.999, seed=0, score_type=score_type, degensac=True)(+ kp1, kp2+ )+ assert _explains_off_plane(F.cpu(), clean1.cpu(), clean2.cpu())++ def test_never_degenerate_is_bitwise_plain(self, device, dtype, monkeypatch):+ # With the test stubbed to find no degenerate sample, the record tracking, sample rows and host transfers+ # must leave the result bit for bit the same, even where recoveries would fire.+ _skip_half(dtype)+ monkeypatch.setattr(ransac_module, "_h_degenerate_samples", lambda models, *args: [None] * len(models))+ kp1, kp2, _, _, _ = create_dominant_plane_scene(1000, 0.6, 0.95, 0, device=device, dtype=dtype)+ F, mask = RANSAC("fundamental", inl_th=1.0, seed=0, degensac=True)(kp1, kp2)+ F_plain, mask_plain = RANSAC("fundamental", inl_th=1.0, seed=0, degensac=False)(kp1, kp2)+ assert torch.equal(F, F_plain) and torch.equal(mask, mask_plain)++ def test_scene_without_plane_keeps_its_accuracy(self, device, dtype, monkeypatch):+ # Without a dominant plane, record setters are still often H-degenerate at Chum's 3 t: five of seven+ # correspondences fit one homography within 0.6-2.1 t in 5 of these 6 seeds. The recoveries then join the+ # pool, so the estimate is not bitwise the plain one, but it must explain the geometry as well.+ _skip_half(dtype)+ calls = []+ original = ransac_module._plane_parallax_search+ monkeypatch.setattr(ransac_module, "_plane_parallax_search", lambda *a: calls.append(1) or original(*a))+ # plane_fraction=0 puts every inlier at a random depth: no dominant plane.+ for seed in range(6):+ kp1, kp2, _, clean1, clean2 = create_dominant_plane_scene(1000, 0.6, 0.0, seed, device=device, dtype=dtype)+ F, mask = RANSAC("fundamental", inl_th=1.0, seed=seed, degensac=True)(kp1, kp2)+ F_plain, mask_plain = RANSAC("fundamental", inl_th=1.0, seed=seed, degensac=False)(kp1, kp2)++ error, error_plain = _off_plane_error(F, clean1, clean2), _off_plane_error(F_plain, clean1, clean2)+ assert error <= error_plain + 0.01, f"seed {seed}"+ assert abs(int(mask.sum()) - int(mask_plain.sum())) <= 0.01 * len(mask), f"seed {seed}"+ assert calls # the recovered path ran++ def test_recovered_incumbent_does_not_hide_later_records(self, device, dtype, monkeypatch):+ # The stub's first model outscores every raw model. A trigger tied to the incumbent's score would stop+ # testing after the first batch; the raw record keeps finding record setters in later batches.+ _skip_half(dtype)+ batches = []++ def stub(+ self,+ model,+ sample,+ x1,+ x2,+ x1_host,+ x2_host,+ basis,+ threshold,+ generator,+ seen_planes=None,+ homography=None,+ ):+ batches.append(generator.initial_seed())+ models = model[None].clone()+ huge = torch.full((1,), 1e9, dtype=x1.dtype, device=x1.device)+ return models, huge, torch.full((1,), float(len(x1)), dtype=x1.dtype, device=x1.device), None++ monkeypatch.setattr(RANSAC, "_degensac_recover", stub)+ kp1, kp2, _, _, _ = create_dominant_plane_scene(1000, 0.6, 0.95, 0, device=device, dtype=dtype)+ RANSAC("fundamental", inl_th=1.0, batch_size=64, max_iter=20, confidence=1.0, seed=0, degensac=True)(kp1, kp2)+ assert len(set(batches)) >= 2++ def test_seeded_calls_are_reproducible_and_private(self, device, dtype, monkeypatch):+ _skip_half(dtype)+ kp1, kp2, _, _, _ = create_dominant_plane_scene(1000, 0.6, 0.95, 0, device=device, dtype=dtype)++ def device_state():+ if device.type == "cuda":+ return torch.cuda.get_rng_state(device)+ if device.type == "mps":+ return torch.mps.get_rng_state()+ return None++ calls = []+ original = ransac_module._plane_parallax_search+ monkeypatch.setattr(ransac_module, "_plane_parallax_search", lambda *a: calls.append(1) or original(*a))+ cpu_state, accelerator_state = torch.get_rng_state(), device_state()+ first = RANSAC("fundamental", inl_th=1.0, seed=3, degensac=True)(kp1, kp2)+ second = RANSAC("fundamental", inl_th=1.0, seed=3, degensac=True)(kp1, kp2)+ assert calls # the recovery drew+ assert torch.equal(first[0], second[0]) and torch.equal(first[1], second[1])+ assert torch.equal(torch.get_rng_state(), cpu_state)+ if accelerator_state is not None:+ assert torch.equal(device_state(), accelerator_state)++ # Review focus 1: non-finite correspondences.+ def test_non_finite_rows_are_skipped(self, device, dtype):+ _skip_half(dtype)+ kp1, kp2, _, clean1, clean2 = create_dominant_plane_scene(1000, 0.6, 0.95, 0, device=device, dtype=dtype)+ kp1[:5] = float("nan")+ kp2[5:10] = float("inf")+ F, mask = RANSAC("fundamental", inl_th=1.0, seed=0, degensac=True)(kp1, kp2)+ assert not bool(mask[:10].any())+ assert _explains_off_plane(F.cpu(), clean1.cpu(), clean2.cpu())++ # Review focus 2: a fully planar scene. Its off-plane set is the outliers, so the pair search runs on them and may+ # return a model consistent with the plane plus a few outliers (as Chum's code does; VSAC's DEGENSAC+ adds a+ # randomness check against that). Every model consistent with the plane is valid here: the plane must stay in.+ def test_fully_planar_scene(self, device, dtype):+ _skip_half(dtype)+ kp1, kp2, labels, _, _ = create_dominant_plane_scene(1000, 0.6, 1.0, 0, device=device, dtype=dtype)+ F, mask = RANSAC("fundamental", inl_th=1.0, seed=0, degensac=True)(kp1, kp2)+ assert F.shape == (3, 3) and bool(F.abs().sum() > 0)+ plane = labels == 0+ assert float((mask & plane).sum()) >= 0.9 * float(plane.sum())++ # Review focus 3: tiny inputs.+ @pytest.mark.parametrize("num_points", [7, 10, 20])+ def test_tiny_inputs(self, device, dtype, num_points):+ kp1, kp2, _, _, _ = create_dominant_plane_scene(num_points, 0.8, 0.9, 0, device=device, dtype=dtype)+ F, mask = RANSAC("fundamental", inl_th=1.0, seed=0, degensac=True)(kp1, kp2)+ assert F.shape == (3, 3) and mask.shape == (num_points,) and mask.dtype == torch.bool++ # Review focus 4: PROSAC's stopping rule takes the recovered incumbent's mask.+ def test_prosac(self, device, dtype, monkeypatch):+ # The raw degenerate incumbent already certifies itself after the first batch here, so the final model alone+ # cannot show which mask set the recovered incumbent's bound: spy on PROSAC's termination test instead.+ _skip_half(dtype)+ recovered, tested = [], []+ original_recover, original_prosac = RANSAC._degensac_recover, RANSAC._prosac_max_samples++ def spy_recover(self, *args):+ result = original_recover(self, *args)+ if result is not None:+ recovered.append(result[3][0].clone())+ return result++ def spy_prosac(self, inliers, num_inliers):+ tested.append(inliers.clone())+ return original_prosac(self, inliers, num_inliers)++ monkeypatch.setattr(RANSAC, "_degensac_recover", spy_recover)+ monkeypatch.setattr(RANSAC, "_prosac_max_samples", spy_prosac)+ kp1, kp2, labels, clean1, clean2 = create_dominant_plane_scene(1000, 0.6, 0.95, 0, device=device, dtype=dtype)+ order = torch.argsort(labels.cpu(), stable=True).to(device) # inliers first, a best-first ranking+ F, _ = RANSAC("fundamental", inl_th=1.0, seed=0, prosac_sampling=True, degensac=True)(kp1[order], kp2[order])+ assert _explains_off_plane(F.cpu(), clean1.cpu(), clean2.cpu())+ # The recovered incumbent's stopping bound is PROSAC's test on its own inlier mask.+ assert recovered and any(torch.equal(mask, inliers) for mask in recovered for inliers in tested)++ # Review focus 5: half-precision correspondences run the float64 host recovery and float32 device scoring.+ def test_half_precision_smoke(self, device):+ if device.type != "cpu":+ pytest.skip("the half-precision RANSAC legs run on CPU; accelerator half kernels are covered elsewhere")+ for dtype in (torch.float16, torch.bfloat16):+ kp1, kp2, _, _, _ = create_dominant_plane_scene(500, 0.6, 0.95, 0, device=device, dtype=dtype)+ F, mask = RANSAC("fundamental", inl_th=2.0, seed=0, degensac=True)(kp1, kp2)+ assert F.shape == (3, 3) and F.dtype == dtype and mask.shape == (500,)