Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(ransac): repair MSAC, implement PROSAC, add bounded LO and an IMC accuracy-vs-time benchmark (#4902)

Dmytro Mishkindfac11ab8aac
diff --git a/benchmarks/README.md b/benchmarks/README.md
index 330dddf73..d89387128 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -35,7 +35,7 @@ Deeper, single-topic scripts:
| Directory | Contents |
| --- | --- |
| [`augmentation/`](augmentation/) | Cross-library augmentation benchmarks β€” [`flagship.py`](augmentation/flagship.py) (class-API, parameter sampling included, vs torchvision v2/albumentations/OpenCV/PIL) plus pipeline/per-op scripts; see its [README](augmentation/README.md). |
-| [`geometry/`](geometry/) | [`flagship.py`](geometry/flagship.py): core geometry ops vs OpenCV/torchvision v2. |
+| [`geometry/`](geometry/) | [`flagship.py`](geometry/flagship.py): core geometry ops vs OpenCV/torchvision v2. [`ransac.py`](geometry/ransac.py): batched RANSAC runtime and IMC pose accuracy on cached correspondences. |
| [`morphology/`](morphology/) | [`flagship.py`](morphology/flagship.py): representative morphology ops vs torchmorph, albumentations, scikit-image and OpenCV. [`engines.py`](morphology/engines.py): dilation engine comparison across explicit public engines. |
| [`filters/`](filters/) | [`flagship.py`](filters/flagship.py): core filters vs OpenCV/albumentations/torchvision v2/kornia-rs/PIL/scikit-image. [`gaussian_cpu.py`](filters/gaussian_cpu.py): Gaussian blur and scale-pyramid base/branch timing and numerical comparisons; [report](filters/gaussian_cpu.md). |
| [`color/`](color/) | pytest-benchmark microbenchmarks for color conversions (`*_test.py`). |
diff --git a/benchmarks/geometry/ransac.py b/benchmarks/geometry/ransac.py
new file mode 100644
index 000000000..5f22605c5
--- /dev/null
+++ b/benchmarks/geometry/ransac.py
@@ -0,0 +1,931 @@
+# 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.
+#
+
+"""RANSAC speed and two-view pose quality on cached IMC correspondences.
+
+Run from the checkout being measured (copy this harness to older checkouts).
+Preparation/evaluation require optional h5py and the imc2021-simple package;
+measurement needs only the normal Kornia environment and NumPy. No downloads.
+
+ python benchmarks/geometry/ransac.py prepare --data-root ../imc2021-simple/data/phototourism \
+ --scenes sacre_coeur,reichstag --cache sift=raw_matches.h5 \
+ --cache xfeat=raw_matches_xfeat_n2048_lighterglue.h5 --pairs 20 --npz /tmp/pairs.npz
+ python benchmarks/geometry/ransac.py run --npz /tmp/pairs.npz --device cuda \
+ --batches 256,2048 --sample-budget 8192 --scores ransac,msac --prosac off,on \
+ --lo-iters 0,5 --seeds 0,1,2 --json /tmp/predictions.json
+ python benchmarks/geometry/ransac.py evaluate --npz /tmp/pairs.npz \
+ --predictions /tmp/predictions.json --json /tmp/evaluated.json
+ python benchmarks/geometry/ransac.py sweep --npz /tmp/pairs.npz --device cpu --json /tmp/sweep.json
+ python benchmarks/geometry/ransac.py evaluate --npz /tmp/pairs.npz \
+ --predictions /tmp/sweep.json --json /tmp/sweep-evaluated.json
+ python benchmarks/geometry/ransac.py plot --evaluated /tmp/sweep-evaluated.json --out /tmp/time_maa.png
+ git show main:kornia/geometry/ransac.py > /tmp/base_ransac.py
+ python benchmarks/geometry/ransac.py compare --npz /tmp/pairs.npz --device cpu \
+ --base-source /tmp/base_ransac.py --json /tmp/compare.json
+
+Timing covers public RANSAC.forward on preloaded device tensors, including sampling,
+scoring and local optimization, excluding construction, sorting, transfers and pose
+recovery. A fixed estimator seed is reset by each forward; repeated timing calls
+therefore measure the same work. Sample budgets count minimal samples, not solutions
+(the seven-point solver can emit multiple solutions). Confidence stopping can reduce
+actual work. Batch sizes must divide the budget. Quality is evaluated separately for
+every seed, using imc2021.metrics.pose_error and maa_imc (strict thresholds 1..10 deg).
+Failure means nonfinite pose error; finite errors >=10 deg also miss every mAA threshold.
+Scene mAA is averaged equally, then seeds equally, separately for each feature/config.
+Prepared pairs come from the intersection of requested raw feature caches per scene,
+selected without replacement by a pinned NumPy RNG. Cached score (preferred)
+and ratio both rank lower values first, following imc2021-simple. --timing-pairs
+limits repeated timing per scene/feature while preserving all quality evaluations. This is a diagnostic subset, not
+an official full IMC leaderboard result. Missing caches are reported and skipped.
+
+``sweep`` deliberately departs from the benchmark contract's "never time a single call": like the IMC
+time-mAA protocol, it times one synchronized call per pair and configuration and averages over pairs, so a
+curve point reflects the per-pair latency a caller sees. Use ``run`` or ``compare`` (``time_us``) for A/B timing.
+"""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import contextlib
+import hashlib
+import importlib.util
+import itertools
+import json
+import sys
+import time
+from collections import defaultdict
+from functools import partial
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+import torch
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT))
+sys.path.insert(1, str(ROOT / "benchmarks"))
+
+from common import finish_run, optional_import, save_json, setup_run, start_run, time_us # noqa: E402
+
+from kornia.geometry import RANSAC # noqa: E402
+
+
+def digest(path: Path) -> str:
+ """Identify exact input bytes without publishing a machine-local path."""
+ with path.open("rb") as stream:
+ return hashlib.file_digest(stream, "sha256").hexdigest()
+
+
+def measured_ransac_source() -> Path:
+ """The ``ransac.py`` actually imported, which an editable install may resolve outside this checkout."""
+ return Path(sys.modules[RANSAC.__module__].__file__ or "")
+
+
+def prepare(args: argparse.Namespace) -> None:
+ """Export raw matches and ground truth, never an upstream estimator's inliers."""
+ try:
+ import h5py
+ from imc2021.io import load_calibration
+ except ImportError as exc:
+ raise SystemExit(f"Preparation requires h5py and imc2021-simple: {exc}") from exc
+ payload: dict[str, Any] = {}
+ sources = []
+ rng = np.random.default_rng(args.selection_seed)
+ for scene in args.scenes.split(","):
+ scene_dir = args.data_root / scene / args.scene_set
+ calib = load_calibration(scene_dir)
+ caches = {}
+ for spec in args.cache:
+ label, filename = spec.split("=", 1)
+ path = scene_dir / filename
+ if not path.is_file():
+ print(f"# NOTE: skipping missing cache {scene}/{filename}")
+ continue
+ with h5py.File(path, "r") as handle:
+ pairs = {(a, b) for a in handle for b in handle[a] if a in calib and b in calib}
+ caches[label] = (path, pairs)
+ if not caches:
+ continue
+ common_pairs = sorted(set.intersection(*(pairs for _, pairs in caches.values())))
+ indices = sorted(rng.choice(len(common_pairs), min(args.pairs, len(common_pairs)), replace=False))
+ for label, (path, _) in caches.items():
+ sources.append({"scene": scene, "feature": label, "file": path.name, "sha256": digest(path)})
+ with h5py.File(path, "r") as handle:
+ for index in indices:
+ a, b = common_pairs[index]
+ group = handle[a][b]
+ prefix = f"{scene}__{label}__{index}__"
+ if "mkp_a" not in group or "mkp_b" not in group:
+ raise ValueError(f"{path.name} is not a raw correspondence cache")
+ for field in ("mkp_a", "mkp_b", "ratio", "score"):
+ if field in group:
+ payload[prefix + field] = group[field][:]
+ payload[prefix + "names"] = np.array([a, b])
+ for side, name in (("a", a), ("b", b)):
+ for field in ("K", "R", "T"):
+ payload[prefix + side + "_" + field] = calib[name][field]
+ if not payload:
+ raise SystemExit("No pairs found in the requested caches")
+ payload["provenance"] = np.array(json.dumps({"sources": sources, "selection_seed": args.selection_seed}))
+ np.savez_compressed(args.npz, **payload)
+ print(f"# exported {sum(key.endswith('__mkp_a') for key in payload)} feature/pair records to {args.npz}")
+
+
+def pair_keys(data: Any, args: argparse.Namespace) -> list[str]:
+ """Select exported pairs without changing their deterministic preparation order."""
+ keys = sorted(key.removesuffix("__mkp_a") for key in data.files if key.endswith("__mkp_a"))
+ if args.scenes:
+ keys = [key for key in keys if key.split("__")[0] in args.scenes.split(",")]
+ if args.features:
+ keys = [key for key in keys if key.split("__")[1] in args.features.split(",")]
+ counts: dict[tuple[str, str], int] = defaultdict(int)
+ selected = []
+ for key in keys:
+ group = tuple(key.split("__")[:2])
+ if args.pairs is None or counts[group] < args.pairs:
+ selected.append(key)
+ counts[group] += 1
+ return selected
+
+
+def run(args: argparse.Namespace) -> None:
+ """Measure full public estimator calls and preserve their outputs for evaluation."""
+ device, dtype, sync = setup_run(args, opencv=False)
+ meta = start_run(
+ "RANSAC",
+ args,
+ device,
+ units="pairs/s",
+ regimes=["Preloaded device tensors; full RANSAC.forward including sampling, scoring and LO"],
+ )
+ meta.update(
+ dataset_sha256=digest(args.npz),
+ sample_budget=args.sample_budget,
+ confidence=args.confidence,
+ threshold_px=args.threshold,
+ min_run_time=args.min_run_time,
+ timing_pairs_per_scene_feature=args.timing_pairs,
+ actual_work="sampled_sets counts minimal sets in untimed prediction, excluding solver roots",
+ ransac_source_sha256=digest(measured_ransac_source()),
+ timing_includes="RANSAC.forward only; fixed estimator seed per repeated call",
+ )
+ configs = list(
+ itertools.product(
+ [int(x) for x in args.batches.split(",")],
+ args.scores.split(","),
+ args.prosac.split(","),
+ [int(x) for x in args.lo_iters.split(",")],
+ [int(x) for x in args.seeds.split(",")],
+ )
+ )
+ if any(batch <= 0 or args.sample_budget % batch for batch, *_ in configs):
+ raise SystemExit("Every positive batch size must divide --sample-budget exactly")
+ rows = []
+ with np.load(args.npz, allow_pickle=False) as data, torch.inference_mode():
+ keys = pair_keys(data, args)
+ if not keys:
+ raise SystemExit("No pairs selected")
+ timing_counts: dict[tuple[str, str], int] = defaultdict(int)
+ for key in keys:
+ scene, feature, _ = key.split("__")
+ timed = args.timing_pairs is None or timing_counts[scene, feature] < args.timing_pairs
+ timing_counts[scene, feature] += 1
+ a, b = data[key + "__mkp_a"], data[key + "__mkp_b"]
+ if key + "__score" in data:
+ order = np.argsort(data[key + "__score"].reshape(-1), kind="stable")
+ ranking = "ascending score"
+ elif key + "__ratio" in data:
+ order = np.argsort(data[key + "__ratio"].reshape(-1), kind="stable")
+ ranking = "ascending ratio"
+ else:
+ order, ranking = np.arange(len(a)), "unranked"
+ # Both samplers see identical order; PROSAC assumes best matches come first.
+ kp1 = torch.as_tensor(a[order], device=device, dtype=dtype)
+ kp2 = torch.as_tensor(b[order], device=device, dtype=dtype)
+ for batch, score, prosac, lo, seed in configs:
+ row: dict[str, Any] = {
+ "op": "RANSAC",
+ "backend": "kornia (eager)",
+ "batch": batch,
+ "dtype": args.dtype,
+ "pair": key,
+ "scene": scene,
+ "feature": feature,
+ "model_type": args.model,
+ "score_type": score,
+ "prosac": prosac == "on",
+ "max_lo_iters": lo,
+ "lo_sample_size": args.lo_sample_size,
+ "seed": seed,
+ "correspondences": len(a),
+ "ranking": ranking,
+ "timed": timed,
+ "median_us": None,
+ "iqr_us": None,
+ "throughput_per_s": None,
+ }
+ if prosac == "on" and ranking == "unranked":
+ row["error"] = "unavailable: PROSAC requires cached ratios or scores"
+ else:
+ estimator = RANSAC(
+ model_type=args.model,
+ inl_th=args.threshold,
+ batch_size=batch,
+ max_iter=args.sample_budget // batch,
+ confidence=args.confidence,
+ max_lo_iters=lo,
+ score_type=score,
+ prosac_sampling=prosac == "on",
+ seed=seed,
+ **({"lo_sample_size": args.lo_sample_size} if args.lo_sample_size is not None else {}),
+ )
+ try:
+ original_sample = estimator.sample
+ sampled_sets = 0
+
+ def counted_sample(
+ *sample_args: Any, _sample: Any = original_sample, **sample_kwargs: Any
+ ) -> Any:
+ nonlocal sampled_sets
+ sampled_sets += int(sample_args[2] if len(sample_args) > 2 else sample_kwargs["batch_size"])
+ return _sample(*sample_args, **sample_kwargs)
+
+ estimator.sample = counted_sample
+ try:
+ matrix, mask = estimator(kp1, kp2)
+ finally:
+ estimator.sample = original_sample
+ row["sampled_sets"] = sampled_sets
+ if timed:
+ median, iqr = time_us(partial(estimator, kp1, kp2), args.min_run_time, sync=sync)
+ if not np.isfinite(median):
+ raise RuntimeError("Timing call failed")
+ row.update(median_us=median, iqr_us=iqr, throughput_per_s=1e6 / median)
+ original_mask = np.zeros(len(a), dtype=bool)
+ original_mask[order] = mask.detach().cpu().numpy().reshape(-1)
+ row.update(
+ matrix=matrix.detach().cpu().tolist(),
+ inlier_indices=np.flatnonzero(original_mask).tolist(),
+ )
+ except (RuntimeError, ValueError) as exc:
+ row["error"] = type(exc).__name__
+ rows.append(row)
+ print(
+ f"{key} batch={batch} {score} prosac={prosac} lo={lo} seed={seed}: {row['median_us']} us",
+ flush=True,
+ )
+ finish_run(args, "geometry-ransac", meta, rows)
+
+
+def compare(args: argparse.Namespace) -> None:
+ """Time another revision's RANSAC and this checkout's variants alternately in one process.
+
+ Separate processes on a hybrid CPU can differ by up to 2x on identical code, so an A/B timing
+ must share one warmed process. ``--base-source`` is that revision's ``kornia/geometry/ransac.py``
+ (``git show <rev>:kornia/geometry/ransac.py``). It is loaded next to the current module and
+ imports this checkout's kornia internals, so it is only valid when that file is the sole
+ library difference between the revisions. Each call is timed ``--rounds`` times, alternating
+ the variant order, and the minimum median is kept.
+ """
+ device, _, sync = setup_run(args, opencv=False)
+ variants: dict[str, tuple[Any, dict[str, Any]]] = {"new": (RANSAC, {})}
+ if args.base_source is not None:
+ variants = {"base": (load_ransac_module(args.base_source).RANSAC, {}), **variants}
+ variants["new-lo0"] = (RANSAC, {"max_lo_iters": 0})
+ for cap in [int(x) for x in args.lo_sample_sizes.split(",") if x]:
+ variants[f"new-lo{cap}-subsets"] = (RANSAC, {"lo_sample_size": cap})
+ variants["new-prosac"] = (RANSAC, {"prosac_sampling": True})
+ meta = start_run(
+ "RANSAC A/B",
+ args,
+ device,
+ units="ms",
+ regimes=["One warmed process; variants alternate per round; minimum median per variant"],
+ )
+ meta.update(
+ dataset_sha256=digest(args.npz),
+ ransac_source_sha256=digest(measured_ransac_source()),
+ base_ransac_source_sha256=digest(args.base_source) if args.base_source is not None else None,
+ sample_budget=args.sample_budget,
+ confidence=args.confidence,
+ threshold_px=args.threshold,
+ rounds=args.rounds,
+ min_run_time=args.min_run_time,
+ )
+ rows = []
+ with np.load(args.npz, allow_pickle=False) as data, torch.inference_mode():
+ for key in pair_keys(data, args):
+ scene, feature, _ = key.split("__")
+ a, b = data[key + "__mkp_a"], data[key + "__mkp_b"]
+ field = key + "__score" if key + "__score" in data else key + "__ratio"
+ order = np.argsort(data[field].reshape(-1), kind="stable") if field in data else np.arange(len(a))
+ kp1 = torch.as_tensor(a[order], device=device, dtype=torch.float32)
+ kp2 = torch.as_tensor(b[order], device=device, dtype=torch.float32)
+ batches = [int(x) for x in args.batches.split(",")]
+ seeds = [int(x) for x in args.seeds.split(",")]
+ for score, batch, seed in itertools.product(args.scores.split(","), batches, seeds):
+ names = list(variants)
+ estimators = {
+ name: cls(
+ model_type="fundamental",
+ inl_th=args.threshold,
+ batch_size=batch,
+ max_iter=args.sample_budget // batch,
+ confidence=args.confidence,
+ score_type=score,
+ seed=seed,
+ **{"max_lo_iters": args.lo_iters, **options},
+ )
+ for name, (cls, options) in variants.items()
+ }
+ best = dict.fromkeys(names, float("inf"))
+ for round_index in range(args.rounds):
+ for name in names if round_index % 2 == 0 else names[::-1]:
+ median, _ = time_us(partial(estimators[name], kp1, kp2), args.min_run_time, sync=sync)
+ best[name] = min(best[name], median)
+ for name in names:
+ rows.append(
+ {
+ "op": "RANSAC",
+ "backend": name,
+ "pair": key,
+ "scene": scene,
+ "feature": feature,
+ "score_type": score,
+ "batch": batch,
+ "seed": seed,
+ "median_us": best[name],
+ }
+ )
+ print(f"{key}: timed {len(variants)} variants", flush=True)
+ finish_run(args, "geometry-ransac-compare", meta, rows)
+
+
+def load_ransac_module(path: Path) -> Any:
+ """Load another revision's ``kornia/geometry/ransac.py`` next to this checkout's module.
+
+ It imports this checkout's kornia internals, so it is only valid when that file is the sole
+ library difference between the revisions (``git show <rev>:kornia/geometry/ransac.py``).
+ """
+ spec = importlib.util.spec_from_file_location("kornia.geometry._ransac_other_revision", path)
+ if spec is None or spec.loader is None:
+ raise SystemExit(f"Cannot load {path}")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+SWEEP_KORNIA = {
+ "msac": {"score_type": "msac"},
+ "msac-lo32": {"score_type": "msac", "lo_sample_size": 32},
+ "msac-prosac": {"score_type": "msac", "prosac_sampling": True},
+ "ransac": {"score_type": "ransac"},
+}
+SWEEP_OPENCV = {"usac_magsac": "USAC_MAGSAC", "usac_accurate": "USAC_ACCURATE", "ransac": "FM_RANSAC"}
+# The revision before PROSAC and bounded LO has no lo_sample_size and ignores prosac_sampling, so
+# --base-source runs only the configurations it implements.
+SWEEP_BASE_KORNIA = ("msac", "ransac")
+
+
+def sweep(args: argparse.Namespace) -> None:
+ """Time single calls over a budget x inlier-threshold grid for the time-mAA curve.
+
+ Every configuration runs once per pair, all configurations of one pair back to back, so slow
+ drift affects every method alike. Each call is timed on its own with device synchronization,
+ as in the IMC time-mAA protocol; the curve averages the times over pairs (see the module
+ docstring for why this is not ``time_us``). Kornia's budget is
+ ``batch_size * max_iter`` minimal sets (a budget below ``--batch`` runs as one batch of that
+ size); OpenCV's is ``maxIters``. Predictions are stored with bit-packed inlier masks and scored
+ by ``evaluate``.
+ """
+ kornia_methods = [m for m in args.kornia.split(",") if m]
+ opencv_methods = [m for m in args.opencv.split(",") if m]
+ device, _, _ = setup_run(args, opencv=bool(opencv_methods))
+ estimators: list[tuple[str, Any, list[str]]] = [("kornia", RANSAC, kornia_methods)]
+ if args.base_source is not None:
+ # Another revision's RANSAC next to this one, interleaved per pair in the same process.
+ base_methods = [m for m in kornia_methods if m in SWEEP_BASE_KORNIA]
+ if skipped := [m for m in kornia_methods if m not in base_methods]:
+ print(f"# NOTE: kornia-base skips {','.join(skipped)}: not implemented by the base revision")
+ estimators.append(("kornia-base", load_ransac_module(args.base_source).RANSAC, base_methods))
+ cv2 = None
+ if opencv_methods:
+ cv2, reason = optional_import("cv2")
+ if cv2 is None:
+ print(f"# NOTE: skipping OpenCV methods ({reason})")
+ opencv_methods = []
+ sync = torch.cuda.synchronize if device.type == "cuda" else (lambda: None)
+ thresholds = [float(x) for x in args.thresholds.split(",")]
+ meta = start_run(
+ "RANSAC time-mAA sweep",
+ args,
+ device,
+ units="ms",
+ regimes=["Single synchronized call per pair and configuration; inputs preloaded on the device"],
+ )
+ meta.update(
+ dataset_sha256=digest(args.npz),
+ ransac_source_sha256=digest(measured_ransac_source()),
+ base_ransac_source_sha256=digest(args.base_source) if args.base_source is not None else None,
+ thresholds_px=thresholds,
+ confidence=args.confidence,
+ seed=args.seed,
+ )
+ rows = []
+ with np.load(args.npz, allow_pickle=False) as data, torch.inference_mode():
+ for pair_index, key in enumerate(pair_keys(data, args)):
+ scene, feature, _ = key.split("__")
+ a, b = data[key + "__mkp_a"], data[key + "__mkp_b"]
+ field = key + "__score" if key + "__score" in data else key + "__ratio"
+ order = np.argsort(data[field].reshape(-1), kind="stable") if field in data else np.arange(len(a))
+ kp1 = torch.as_tensor(a[order], device=device, dtype=torch.float32)
+ kp2 = torch.as_tensor(b[order], device=device, dtype=torch.float32)
+ points1, points2 = a[order].astype(np.float64), b[order].astype(np.float64)
+ calls: list[tuple[dict[str, Any], Any]] = []
+ budgets = [int(x) for x in args.budgets.split(",")]
+ for prefix, ransac_class, methods in estimators:
+ for name, budget, threshold in itertools.product(methods, budgets, thresholds):
+ batch = min(args.batch, budget)
+ estimator = ransac_class(
+ model_type="fundamental",
+ inl_th=threshold,
+ batch_size=batch,
+ max_iter=budget // batch,
+ confidence=args.confidence,
+ max_lo_iters=args.lo_iters,
+ seed=args.seed,
+ **SWEEP_KORNIA[name],
+ )
+ config = {"method": f"{prefix} {name}", "device": device.type, "batch": batch}
+ config.update(sample_budget=budget, threshold_px=threshold)
+ calls.append((config, partial(estimator, kp1, kp2)))
+ for name, iters, threshold in itertools.product(
+ opencv_methods, [int(x) for x in args.opencv_iters.split(",")], thresholds
+ ):
+
+ def estimate(
+ flag: int = getattr(cv2, SWEEP_OPENCV[name]),
+ iters: int = iters,
+ th: float = threshold,
+ p1: Any = points1,
+ p2: Any = points2,
+ ) -> Any:
+ cv2.setRNGSeed(args.seed)
+ return cv2.findFundamentalMat(p1, p2, flag, th, args.confidence, iters)
+
+ config = {"method": f"opencv {name}", "device": "cpu", "batch": None}
+ config.update(sample_budget=iters, threshold_px=threshold)
+ calls.append((config, estimate))
+ if pair_index == 0:
+ for _, call in calls: # lazy initialization and solver handles stay out of the timings
+ with contextlib.suppress(Exception):
+ call()
+ for config, call in calls:
+ error = None
+ sync()
+ start = time.perf_counter()
+ try:
+ matrix, mask = call()
+ except Exception as exc: # e.g. an OpenCV USAC assertion: scored as a failed estimate
+ matrix, mask, error = None, None, type(exc).__name__
+ sync()
+ elapsed_ms = (time.perf_counter() - start) * 1000
+ row: dict[str, Any] = {
+ "op": "RANSAC",
+ "backend": config["method"],
+ "pair": key,
+ "scene": scene,
+ "feature": feature,
+ "model_type": "fundamental",
+ "seed": args.seed,
+ "correspondences": len(a),
+ "time_ms": elapsed_ms,
+ **config,
+ }
+ if error is not None:
+ row["error"] = error
+ if torch.is_tensor(matrix):
+ matrix, mask = matrix.cpu().numpy(), mask.cpu().numpy()
+ if matrix is not None and np.shape(matrix) == (3, 3) and np.abs(matrix).max() > 0:
+ original = np.zeros(len(a), dtype=bool)
+ original[order] = np.asarray(mask).reshape(-1).astype(bool)
+ packed = base64.b64encode(np.packbits(original).tobytes()).decode()
+ row.update(matrix=np.asarray(matrix).tolist(), inliers_packed=packed)
+ rows.append(row)
+ print(f"{key}: {len(calls)} configurations", flush=True)
+ finish_run(args, "geometry-ransac-sweep", meta, rows)
+
+
+# Line style separates the families: kornia solid in color (one validated categorical hue per
+# configuration, checked all-pairs), another kornia revision dashed with hollow markers in the same
+# hue, OpenCV in neutral greys with its own dash patterns. Markers differ within each family too,
+# so identity never rests on color alone.
+PLOT_SERIES = { # method: (label, group, color, linestyle, marker, filled)
+ "kornia msac": ("MSAC", "kornia", "#2a78d6", "-", "o", True),
+ "kornia ransac": ("RANSAC score", "kornia", "#eb6834", "-", "s", True),
+ "kornia msac-lo32": ("MSAC + subset LO (32)", "kornia", "#1baf7a", "-", "D", True),
+ "kornia msac-prosac": ("MSAC + PROSAC", "kornia", "#4a3aa7", "-", "^", True),
+ "kornia-base msac": ("MSAC", "kornia-base", "#2a78d6", "--", "o", False),
+ "kornia-base ransac": ("RANSAC score", "kornia-base", "#eb6834", "--", "s", False),
+ "opencv usac_magsac": ("USAC_MAGSAC (MAGSAC++)", "opencv", "#1f1f1e", ":", "s", True),
+ "opencv usac_accurate": ("USAC_ACCURATE", "opencv", "#5f5e5a", "-.", "D", True),
+ "opencv ransac": ("FM_RANSAC", "opencv", "#8f8e89", "--", "v", True),
+}
+PLOT_GROUPS = {"kornia": "kornia, this PR", "kornia-base": "kornia, main before this PR", "opencv": "OpenCV (CPU)"}
+PAGE, INK, MUTED, GRID = "#fcfcfb", "#0b0b0b", "#52514e", "#e4e3df"
+
+
+def style_axis(axis: Any) -> None:
+ """Log-scale x axis with a recessive grid and no top/right spines."""
+ axis.set_facecolor(PAGE)
+ axis.set_xscale("log")
+ axis.grid(True, which="major", color=GRID, linewidth=0.8)
+ axis.set_axisbelow(True)
+ for spine in ("top", "right"):
+ axis.spines[spine].set_visible(False)
+ for spine in ("left", "bottom"):
+ axis.spines[spine].set_color(GRID)
+ axis.tick_params(colors=MUTED, labelsize=8)
+
+
+def draw_series(axis: Any, method: str, xs: list[float], ys: list[float], handles: dict[str, dict[str, Any]]) -> None:
+ """Draw one method's line in its family style and remember the handle for the grouped legend."""
+ label, group, color, linestyle, marker, filled = PLOT_SERIES[method]
+ (line,) = axis.plot(
+ xs,
+ ys,
+ color=color,
+ linestyle=linestyle,
+ linewidth=2 if group != "opencv" else 1.6,
+ marker=marker,
+ markersize=5.5,
+ markerfacecolor=color if filled else PAGE,
+ markeredgecolor=color if not filled else PAGE,
+ markeredgewidth=1.4 if not filled else 0.8,
+ label=label,
+ )
+ handles.setdefault(group, {}).setdefault(label, line)
+
+
+def grouped_legend(figure: Any, handles: dict[str, dict[str, Any]], y: float) -> None:
+ """One titled legend per family, side by side below the panels."""
+ groups = [g for g in PLOT_GROUPS if g in handles]
+ for index, group in enumerate(groups):
+ legend = figure.legend(
+ list(handles[group].values()),
+ list(handles[group]),
+ title=PLOT_GROUPS[group],
+ loc="upper center",
+ bbox_to_anchor=((index + 0.5) / len(groups), y),
+ fontsize=8.5,
+ title_fontsize=9,
+ frameon=False,
+ labelcolor=INK,
+ handlelength=3.2,
+ )
+ legend.get_title().set_color(INK)
+
+
+def plot_thresholds(plt: Any, configs: dict[tuple[Any, ...], dict[str, Any]], features: list[str], args: Any) -> None:
+ """Pose mAA against the inlier threshold on the CPU sweep, every method at its largest budget."""
+ figure, axes = plt.subplots(1, len(features), figsize=(6.4 * len(features), 5.4), squeeze=False, facecolor=PAGE)
+ thresholds = sorted({key[4] for key in configs})
+ handles: dict[str, dict[str, Any]] = {}
+ for axis, feature in zip(axes[0], features):
+ for method in PLOT_SERIES:
+ budgets = [key[3] for key in configs if key[:3] == (feature, method, "cpu")]
+ if not budgets:
+ continue
+ largest = (feature, method, "cpu", max(budgets))
+ points = sorted((key[4], value["maa"]) for key, value in configs.items() if key[:4] == largest)
+ draw_series(axis, method, [t for t, _ in points], [m for _, m in points], handles)
+ style_axis(axis)
+ axis.set_xticks(thresholds, [f"{t:g}" for t in thresholds])
+ axis.minorticks_off()
+ axis.set_title({"sift": "SIFT", "xfeat": "XFeat"}.get(feature, feature), color=INK)
+ axis.set_xlabel("inlier threshold (px, log scale)", color=MUTED, fontsize=9)
+ axis.set_ylabel("pose mAA (1-10Β°)", color=MUTED, fontsize=9)
+ figure.suptitle(args.title or "Pose accuracy vs. inlier threshold (CPU, largest budget)", color=INK)
+ grouped_legend(figure, handles, 0.2)
+ figure.text(
+ 0.5,
+ 0.005,
+ "Each method at its largest budget: kornia 16384 minimal sample sets, OpenCV maxIters 25600.",
+ ha="center",
+ fontsize=8,
+ color=MUTED,
+ )
+ figure.tight_layout(rect=(0, 0.2, 1, 1))
+ figure.savefig(args.threshold_out, dpi=args.dpi, facecolor=PAGE)
+ print(f"# figure written to {args.threshold_out}")
+
+
+def plot(args: argparse.Namespace) -> None:
+ """Draw the IMC-style time-mAA curve from evaluated sweeps: best threshold per budget point."""
+ import matplotlib as mpl
+
+ mpl.use("Agg")
+ import matplotlib.pyplot as plt
+
+ configs: dict[tuple[Any, ...], dict[str, Any]] = {}
+ for path in args.evaluated:
+ for summary in json.loads(path.read_text())["metadata"]["quality_summary"]:
+ key = tuple(summary.get(f) for f in ("feature", "method", "device", "sample_budget", "threshold_px"))
+ if key in configs:
+ raise SystemExit(f"{key} appears in more than one evaluated file")
+ configs[key] = summary
+ best: dict[tuple[Any, ...], dict[str, Any]] = {}
+ for (feature, method, device, budget, _threshold), summary in configs.items():
+ point = best.setdefault((feature, method, device, budget), summary)
+ if summary["maa"] > point["maa"]:
+ best[feature, method, device, budget] = summary
+ curves: dict[tuple[str, str], dict[str, list[dict[str, Any]]]] = defaultdict(lambda: defaultdict(list))
+ for (feature, method, device, budget), summary in sorted(best.items(), key=lambda item: item[0][3]):
+ curves[feature, device][method].append(
+ {
+ "budget": budget,
+ "threshold_px": summary["threshold_px"],
+ "maa": summary["maa"],
+ "mean_time_ms": summary["mean_time_ms"],
+ }
+ )
+ features = sorted({feature for feature, _ in curves})
+ devices = [
+ d
+ for d in ("cpu", "cuda")
+ if any(
+ device == d and any(not m.startswith("opencv") for m in methods) for (_, device), methods in curves.items()
+ )
+ ]
+ figure, axes = plt.subplots(
+ len(devices),
+ len(features),
+ figsize=(6.4 * len(features), 4.6 * len(devices) + 1.4),
+ squeeze=False,
+ facecolor=PAGE,
+ )
+ handles: dict[str, dict[str, Any]] = {}
+ for row, device in enumerate(devices):
+ for column, feature in enumerate(features):
+ axis = axes[row][column]
+ lines = dict(curves[feature, device])
+ if device != "cpu": # OpenCV runs on the CPU; repeat it as the reference in every row
+ lines.update({m: p for m, p in curves.get((feature, "cpu"), {}).items() if m.startswith("opencv")})
+ for method in PLOT_SERIES:
+ if method in lines:
+ points = sorted(lines[method], key=lambda p: p["mean_time_ms"])
+ draw_series(axis, method, [p["mean_time_ms"] for p in points], [p["maa"] for p in points], handles)
+ style_axis(axis)
+ name = {"sift": "SIFT", "xfeat": "XFeat"}.get(feature, feature)
+ axis.set_title(f"{name}, kornia on {device.upper()}", color=INK)
+ axis.set_xlabel("mean time per pair (ms, log scale)", color=MUTED, fontsize=9)
+ axis.set_ylabel("pose mAA (1-10Β°)", color=MUTED, fontsize=9)
+ figure.suptitle(args.title or "Fundamental matrix: pose accuracy vs. time", color=INK, fontsize=12.5)
+ legend_space = 1.4 / (4.6 * len(devices) + 1.4)
+ grouped_legend(figure, handles, legend_space)
+ note = (
+ "Each point is one budget at its best inlier threshold from the sweep; "
+ "mean over pairs of single synchronized calls."
+ )
+ if "opencv" in handles:
+ note += " OpenCV (maxIters budget) runs on the CPU and is repeated in the CUDA row."
+ figure.text(0.5, 0.004, note, ha="center", fontsize=8, color=MUTED)
+ figure.tight_layout(rect=(0, legend_space, 1, 1))
+ figure.savefig(args.out, dpi=args.dpi, facecolor=PAGE)
+ print(f"# figure written to {args.out}")
+ if args.points_json is not None:
+ points_out = {f"{f}|{d}": dict(methods) for (f, d), methods in curves.items()}
+ args.points_json.write_text(json.dumps(points_out, indent=2, sort_keys=True) + "\n")
+ if args.threshold_out is not None:
+ plot_thresholds(plt, configs, features, args)
+
+
+CONFIG_FIELDS = (
+ "feature",
+ "model_type",
+ "batch",
+ "score_type",
+ "prosac",
+ "max_lo_iters",
+ "lo_sample_size",
+ "method",
+ "device",
+ "sample_budget",
+ "threshold_px",
+)
+
+
+def evaluate(args: argparse.Namespace) -> None:
+ """Use the companion evaluator's exact pose-error and mAA implementations."""
+ try:
+ from imc2021 import metrics
+ except ImportError as exc:
+ raise SystemExit(f"Evaluation requires imc2021-simple and its optional dependencies: {exc}") from exc
+ # Several prediction files (e.g. one sweep per seed) pool into one evaluation: each seed is its
+ # own scene/seed cell, so the mAA averages over seeds as well as scenes.
+ documents = [json.loads(path.read_text()) for path in args.predictions]
+ dataset = digest(args.npz)
+ if any(doc["metadata"]["dataset_sha256"] != dataset for doc in documents):
+ raise SystemExit("NPZ content differs from the measured dataset")
+ document = documents[0]
+ document["results"] = [row for doc in documents for row in doc["results"]]
+ if args.thresholds is not None:
+ keep = {float(x) for x in args.thresholds.split(",")}
+ document["results"] = [r for r in document["results"] if r.get("threshold_px") in (None, *keep)]
+ if len(documents) > 1:
+ document["metadata"]["pooled_predictions"] = [doc["metadata"] for doc in documents[1:]]
+ groups: dict[tuple[Any, ...], dict[tuple[str, int], list[float]]] = defaultdict(lambda: defaultdict(list))
+ times: dict[tuple[Any, ...], list[float]] = defaultdict(list)
+ with np.load(args.npz, allow_pickle=False) as data:
+ for row in document["results"]:
+ key = row["pair"]
+ errors = dict.fromkeys(("R_err", "t_err", "max_err"), float("inf"))
+ # An all-zero matrix is RANSAC's failure result, whichever command wrote it.
+ if "matrix" in row and np.isfinite(row["matrix"]).all() and np.abs(row["matrix"]).max() > 0:
+ if "inliers_packed" in row:
+ packed = np.frombuffer(base64.b64decode(row["inliers_packed"]), dtype=np.uint8)
+ inliers = np.flatnonzero(np.unpackbits(packed)[: row["correspondences"]])
+ else:
+ inliers = np.array(row["inlier_indices"], dtype=int)
+ calib = [{field: data[f"{key}__{side}_{field}"] for field in ("K", "R", "T")} for side in ("a", "b")]
+ errors = metrics.pose_error(
+ np.asarray(row["matrix"]),
+ data[key + "__mkp_a"][inliers],
+ data[key + "__mkp_b"][inliers],
+ *calib,
+ )
+ row.update(errors)
+ row["failed"] = not np.isfinite(errors["max_err"])
+ config = tuple(row.get(field) for field in CONFIG_FIELDS)
+ groups[config][row["scene"], row["seed"]].append(errors["max_err"])
+ if row.get("time_ms") is not None:
+ times[config].append(row["time_ms"])
+ summaries = []
+ for config, cells in groups.items():
+ cell_results = [
+ {
+ "scene": scene,
+ "seed": seed,
+ "pairs": len(errors),
+ "maa": metrics.maa_imc(errors, list(range(1, 11))),
+ "failure_rate": float(np.mean(~np.isfinite(errors))),
+ }
+ for (scene, seed), errors in sorted(cells.items())
+ ]
+ summary = {field: value for field, value in zip(CONFIG_FIELDS, config) if value is not None}
+ summary.update(
+ maa=float(np.mean([cell["maa"] for cell in cell_results])),
+ failure_rate=float(np.mean([cell["failure_rate"] for cell in cell_results])),
+ mean_time_ms=float(np.mean(times[config])) if times[config] else None,
+ cells=cell_results,
+ )
+ summaries.append(summary)
+ print(json.dumps(summary))
+ meta = document["metadata"]
+ meta.update(
+ quality_summary=summaries,
+ pose_evaluator="imc2021.metrics.pose_error",
+ evaluator_sha256=digest(Path(metrics.__file__)),
+ maa_thresholds_deg=list(range(1, 11)),
+ aggregation="equal-weight scene/seed cells per feature/config; failures retained",
+ )
+ save_json(args.json, meta, document["results"])
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ commands = parser.add_subparsers(dest="command", required=True)
+ prep = commands.add_parser("prepare")
+ prep.add_argument("--data-root", type=Path, required=True)
+ prep.add_argument("--scenes", required=True)
+ prep.add_argument("--scene-set", default="set_100")
+ prep.add_argument("--cache", action="append", required=True, help="label=raw_cache_filename.h5 (repeatable)")
+ prep.add_argument("--pairs", type=int, default=20, help="pairs per scene, shared across features")
+ prep.add_argument("--selection-seed", type=int, default=0)
+ measure = commands.add_parser("run")
+ measure.add_argument("--device", default="cpu")
+ measure.add_argument("--dtype", choices=("float32", "float64"), default="float32")
+ measure.add_argument("--threads", type=int, default=4)
+ measure.add_argument("--batches", default="256,2048")
+ measure.add_argument("--sample-budget", type=int, default=8192)
+ measure.add_argument("--scores", default="ransac,msac")
+ measure.add_argument("--prosac", default="off,on")
+ measure.add_argument("--lo-iters", default="0,5")
+ measure.add_argument(
+ "--lo-sample-size", type=int, help="optional bounded LO subset; omitted for base compatibility"
+ )
+ measure.add_argument("--seeds", default="0,1,2")
+ measure.add_argument("--model", choices=("fundamental", "fundamental_7pt"), default="fundamental")
+ measure.add_argument("--threshold", type=float, default=1.0)
+ measure.add_argument("--confidence", type=float, default=0.999)
+ measure.add_argument("--min-run-time", type=float, default=0.2)
+ measure.add_argument("--scenes")
+ measure.add_argument("--features")
+ measure.add_argument("--pairs", type=int, help="limit pairs per scene/feature")
+ measure.add_argument("--timing-pairs", type=int, help="time only this many pairs per scene/feature; score all")
+ measure.add_argument("--json", type=Path, required=True)
+ measure.set_defaults(contribute=None)
+ sw = commands.add_parser("sweep")
+ sw.add_argument("--device", default="cpu")
+ sw.add_argument("--dtype", choices=("float32",), default="float32")
+ sw.add_argument("--threads", type=int, default=4)
+ sw.add_argument("--kornia", default=",".join(SWEEP_KORNIA), help=f"subset of {','.join(SWEEP_KORNIA)}")
+ sw.add_argument("--opencv", default=",".join(SWEEP_OPENCV), help=f"subset of {','.join(SWEEP_OPENCV)}")
+ sw.add_argument("--base-source", type=Path, help="also sweep another revision's ransac.py as 'kornia-base'")
+ sw.add_argument("--budgets", default="256,512,1024,2048,4096,8192,16384", help="kornia minimal-sample budgets")
+ sw.add_argument("--batch", type=int, default=256, help="kornia batch size (smaller budgets use one batch)")
+ sw.add_argument("--opencv-iters", default="10,25,100,400,1600,6400,25600")
+ sw.add_argument("--thresholds", default="0.25,0.5,0.75,1,1.5,2")
+ sw.add_argument("--confidence", type=float, default=0.999)
+ sw.add_argument("--lo-iters", type=int, default=5)
+ sw.add_argument("--seed", type=int, default=0)
+ sw.add_argument("--scenes")
+ sw.add_argument("--features")
+ sw.add_argument("--pairs", type=int, help="limit pairs per scene/feature")
+ sw.add_argument("--json", type=Path, required=True)
+ sw.set_defaults(contribute=None)
+ pl = commands.add_parser("plot")
+ pl.add_argument("--evaluated", type=Path, nargs="+", required=True)
+ pl.add_argument("--out", type=Path, required=True)
+ pl.add_argument("--dpi", type=int, default=150)
+ pl.add_argument("--points-json", type=Path)
+ pl.add_argument("--threshold-out", type=Path, help="also draw mAA against the inlier threshold")
+ pl.add_argument("--title", help="figure title")
+ ab = commands.add_parser("compare")
+ ab.add_argument("--device", default="cpu")
+ ab.add_argument("--dtype", choices=("float32",), default="float32")
+ ab.add_argument("--threads", type=int, default=4)
+ ab.add_argument("--base-source", type=Path, help="another revision's kornia/geometry/ransac.py")
+ ab.add_argument("--batches", default="256,2048")
+ ab.add_argument("--sample-budget", type=int, default=4096)
+ ab.add_argument("--scores", default="msac,ransac")
+ ab.add_argument("--lo-iters", type=int, default=5)
+ ab.add_argument("--lo-sample-sizes", default="32,128", help="bounded-LO variants of this checkout")
+ ab.add_argument("--seeds", default="0,1,2")
+ ab.add_argument("--threshold", type=float, default=2.0)
+ ab.add_argument("--confidence", type=float, default=0.999)
+ ab.add_argument("--min-run-time", type=float, default=0.1)
+ ab.add_argument("--rounds", type=int, default=3)
+ ab.add_argument("--scenes")
+ ab.add_argument("--features")
+ ab.add_argument("--pairs", type=int, default=2, help="pairs per scene/feature")
+ ab.add_argument("--json", type=Path, required=True)
+ ab.set_defaults(contribute=None)
+ score = commands.add_parser("evaluate")
+ score.add_argument("--predictions", type=Path, nargs="+", required=True, help="pooled, e.g. one file per seed")
+ score.add_argument("--thresholds", help="keep only sweep rows at these inlier thresholds")
+ score.add_argument("--json", type=Path, required=True)
+ for command in (prep, measure, sw, ab, score):
+ command.add_argument("--npz", type=Path, required=True)
+ args = parser.parse_args()
+ if args.command == "run":
+ if args.lo_sample_size is not None and args.lo_sample_size <= 0:
+ parser.error("--lo-sample-size must be positive")
+ if args.timing_pairs is not None and args.timing_pairs < 0:
+ parser.error("--timing-pairs must be nonnegative")
+ if set(args.scores.split(",")) - {"ransac", "msac"}:
+ parser.error("--scores accepts ransac,msac")
+ if set(args.prosac.split(",")) - {"off", "on"}:
+ parser.error("--prosac accepts off,on")
+ if args.sample_budget <= 0 or args.min_run_time <= 0 or args.threads <= 0:
+ parser.error("sample budget, minimum run time and thread count must be positive")
+ if any(int(value) < 0 for value in args.lo_iters.split(",")):
+ parser.error("--lo-iters must be nonnegative")
+ if args.command == "compare":
+ if set(args.scores.split(",")) - {"ransac", "msac"}:
+ parser.error("--scores accepts ransac,msac")
+ batches = [int(x) for x in args.batches.split(",")]
+ if any(batch <= 0 or args.sample_budget % batch for batch in batches):
+ parser.error("Every positive batch size must divide --sample-budget exactly")
+ if args.rounds <= 0 or args.min_run_time <= 0 or args.threads <= 0 or args.lo_iters < 0:
+ parser.error("rounds, minimum run time and thread count must be positive; --lo-iters nonnegative")
+ if getattr(args, "pairs", None) is not None and args.pairs <= 0:
+ parser.error("--pairs must be positive")
+ if args.command == "sweep":
+ unknown = set(args.kornia.split(",")) - set(SWEEP_KORNIA) | set(args.opencv.split(",")) - set(SWEEP_OPENCV)
+ if unknown - {""}:
+ parser.error(f"unknown --kornia or --opencv method: {sorted(unknown - {''})}")
+ if args.batch <= 0 or any(b % min(b, args.batch) for b in (int(x) for x in args.budgets.split(","))):
+ parser.error("every --budgets entry must be a multiple of --batch or smaller than it")
+ commands_by_name = {"prepare": prepare, "run": run, "sweep": sweep, "plot": plot}
+ commands_by_name.update(compare=compare, evaluate=evaluate)
+ commands_by_name[args.command](args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/changelog.d/4902.added.md b/changelog.d/4902.added.md
new file mode 100644
index 000000000..5bc6ea3ef
--- /dev/null
+++ b/changelog.d/4902.added.md
@@ -0,0 +1,4 @@
+`RANSAC(prosac_sampling=True)` now draws progressive samples from correspondences sorted best-first, following Chum
+and Matas (CVPR 2005); the flag used to be accepted and ignored. The schedule advances per sampled set inside each
+batch, and the sampler runs the full `batch_size * max_iter` budget. `RANSAC` also accepts `lo_sample_size`, which
+fits `max_lo_iters` random inlier subsets of that size in one solver batch before a final full-inlier refit.
diff --git a/changelog.d/4902.breaking.md b/changelog.d/4902.breaking.md
new file mode 100644
index 000000000..ec3ab8daa
--- /dev/null
+++ b/changelog.d/4902.breaking.md
@@ -0,0 +1,13 @@
+`RANSAC("homography_from_linesegments")` now compares the squared mean endpoint-to-line distance with `inl_th**2`, so
+`inl_th` is in coordinate units, as for the point models. It used to compare the unsquared algebraic residual, which
+is that distance multiplied by the target segment's length, so each segment had a different effective threshold;
+re-tune `inl_th` for this model. A zero-length target segment is an outlier. `RANSAC.max_samples_by_conf` returns
+`sys.maxsize` instead of `1` when no finite bound exists (fewer inliers than the sample size, or `conf >= 1`), and
+rounds up instead of truncating; `1` used to stop estimation after the first batch. `RANSAC` now raises `ValueError`
+for a nonpositive or nonfinite `inl_th`, a nonpositive `batch_size` or `max_iter`, a negative `max_lo_iters`, or a
+`confidence` outside `(0, 1]`. These used to be accepted: a negative `inl_th` acted as its absolute value, since it is
+squared, zero counted only exact matches and NaN found no model; a zero `batch_size` or `max_iter` returned the failure
+result without sampling; a negative `max_lo_iters` disabled local optimization; and a `confidence` of 0 or above 1
+stopped after the first batch. An unsupported `score_type` now raises at construction rather than on the first call.
+`confidence=1` now runs the full budget; it used to stop after the first batch. The CPU sampler changed, so a fixed
+`seed` draws different, still reproducible, samples than earlier releases.
diff --git a/changelog.d/4902.fixed.md b/changelog.d/4902.fixed.md
new file mode 100644
index 000000000..899dd855b
--- /dev/null
+++ b/changelog.d/4902.fixed.md
@@ -0,0 +1,14 @@
+`RANSAC(score_type="msac")` accepts models again. Acceptance and confidence stopping treated the MSAC score as an inlier
+count, and a hypothesis was kept only when that score exceeded the minimal sample size. The old score subtracted the
+truncated squared residuals from `N`, so with a 2-pixel threshold it usually fell below that cutoff and the estimator
+returned the all-zero failure matrix: eight-point fundamental estimation on 60 IMC phototourism pairs failed for 87% of
+SIFT and all XFeat pairs. With thresholds below 1 the score could instead exceed the inlier count and stop sampling too
+early. The score is now `sum(1 - min(e / inl_th**2, 1))`, accumulated in at least float32, and the inlier count is
+tracked separately for acceptance and stopping, so those pairs no longer fail. Early stopping is checked after every
+batch, using the current best model's support after local optimization. Zero and nonfinite candidate matrices are
+rejected, since a zero fundamental matrix has zero Sampson error for every match. A model needs more inliers than its
+minimal sample for every score, so five-point essential estimates with six or seven inliers, fewer than the eight-point
+polisher needs, are kept. Local optimization keeps a full-inlier refit
+that ties the score instead of discarding it, so RANSAC scoring no longer returns the less precise minimal-sample model
+when support does not grow. The essential-matrix mask is recomputed after projection onto the essential manifold, and
+a projected model left with five inliers or fewer is reported as the failure result.
diff --git a/docs/source/geometry.ransac.rst b/docs/source/geometry.ransac.rst
index f89e8e50a..985749ccb 100644
--- a/docs/source/geometry.ransac.rst
+++ b/docs/source/geometry.ransac.rst
@@ -8,5 +8,66 @@ kornia.geometry.ransac
Robust model fitting with RANSAC (Random Sample Consensus), used to estimate homographies, fundamental and essential matrices from noisy correspondences.
+Batches, scores, and refinement
+-------------------------------
+
+``batch_size`` counts minimal sample sets. The total budget is
+``batch_size * max_iter``; seven-point fundamental and five-point essential
+solvers may produce several candidate matrices from each set. Smaller batches
+permit earlier stopping, while larger batches amortize accelerator overhead.
+``confidence=1`` disables early stopping and runs the whole budget.
+Measure end-to-end latency and pose accuracy when choosing a batch size.
+
+``score_type="msac"`` minimizes the sum of squared residuals truncated at
+``inl_th ** 2``. The returned internal score is normalized to increase with
+quality. Confidence stopping always uses the number of inliers, not this score.
+Fundamental and essential models use Sampson residuals. Essential estimation
+expects camera-normalized coordinates, so its threshold is not in pixels.
+Line-segment homographies use the squared mean distance from the transferred
+endpoints to the target segment's line; zero-length target segments are outliers.
+Their local optimization still weights segments by the length-scaled residual of
+:func:`~kornia.geometry.homography.line_segment_transfer_error_one_way`, which
+down-weights long segments (`#4867 <https://github.com/kornia/kornia/issues/4867>`_).
+
+A model is accepted only with more inliers than its minimal sample (four
+correspondences for homographies, five for essential and seven or eight for
+fundamental matrices): a model fitted to a sample always fits that sample, so
+only further inliers show a consensus. Without one, the estimator returns the
+all-zero matrix and an empty mask.
+
+``prosac_sampling=True`` enables the per-sample growth schedule of
+`Chum and Matas (CVPR 2005) <https://cmp.felk.cvut.cz/~matas/papers/chum-prosac-cvpr05.pdf>`_.
+Order the correspondences from best to worst before calling the estimator.
+For example, when smaller descriptor ratios indicate better matches:
+
+.. code-block:: python
+
+ order = ratios.argsort()
+ estimator = RANSAC("fundamental", score_type="msac", prosac_sampling=True, seed=0)
+ F, sorted_inliers = estimator(points1[order], points2[order])
+ inliers = sorted_inliers.new_empty(sorted_inliers.shape)
+ inliers[order] = sorted_inliers
+
+The prefix grows within a batch, and each growth sample includes the newest
+correspondence. This implements PROSAC sampling, not its original prefix-based
+termination test: it runs the full budget and does not apply the uniform-sampling
+confidence formula to biased draws. Uninformative or reversed rankings can hurt
+accuracy. The ``weights`` argument is not used to rank correspondences.
+
+By default, local optimization repeatedly refits all current inliers. A refit
+replaces the model when it raises the score, or when it ties it: a least-squares
+fit on the same support is more precise than the minimal-sample model. A refit
+that does not raise the score ends the refinement. This is iterative refitting,
+not the full LO-RANSAC algorithm with inner resampling and a threshold schedule.
+Set ``max_lo_iters=0`` to disable it. Optionally, ``lo_sample_size`` caps each
+randomized non-minimal refit: ``max_lo_iters`` independent subsets are fit in one
+solver batch, then the best accepted consensus gets a full-inlier refit.
+Consensus sets no larger than the cap use ordinary iterative full-inlier
+refitting. This bounded variant is inspired by
+`Lebeda et al. (BMVC 2012) <https://cmp.felk.cvut.cz/software/LO-RANSAC/Lebeda-2012-Fixing_LORANSAC-BMVC_abstract.pdf>`_;
+it does not implement the complete LO+ algorithm. The cap must be at least the
+non-minimal solver's sample size (eight for fundamental/essential matrices).
+Evaluate the accuracy/runtime trade-off on your data before enabling it.
+
.. autoclass:: RANSAC
:members: forward
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index 4cd7b96e8..8b45c41d2 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -526,7 +526,8 @@ normalised camera coordinates, and :func:`~kornia.geometry.homography.find_homog
- ``sampsonDistance(pt1, pt2, F)``, the same argument order, independent of the scale of ``F``
* - RANSAC threshold
- ``inl_th`` is a point distance in the keypoints' units, calibrated units for ``model_type="essential"``;
- for line segments it depends on the segment length (`#4867 <https://github.com/kornia/kornia/issues/4867>`_)
+ for line segments, the mean distance of the transferred endpoints from the target segment's line, though
+ local optimization still weights segments by length (`#4867 <https://github.com/kornia/kornia/issues/4867>`_)
- ``ransacReprojThreshold`` of ``findHomography``, the same unit for points
* - polynomial roots
- ``solve_quadratic``, ``solve_cubic`` and ``solve_quartic`` take coefficients highest degree first and
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.py
index 73d0ed684..1bbc4cbff 100644
--- a/kornia/geometry/ransac.py
+++ b/kornia/geometry/ransac.py
@@ -17,9 +17,12 @@
"""Module containing RANSAC modules."""
+from __future__ import annotations
+
import math
-from functools import partial
-from typing import Callable, Optional, Tuple
+import sys
+from functools import lru_cache, partial
+from typing import Callable, Optional, Tuple, Union
import torch
from torch import nn
@@ -39,38 +42,69 @@ from kornia.geometry.homography import (
__all__ = ["RANSAC"]
+@lru_cache(maxsize=32)
+def _prosac_growth(sample_size: int, pop_size: int, budget: int) -> Tuple[int, ...]:
+ """Cumulative draw counts T'_n (Chum & Matas, CVPR 2005, eqs. 3--4)."""
+ expected = float(budget)
+ for i in range(sample_size):
+ expected *= (sample_size - i) / (pop_size - i)
+ ends = [1]
+ for n in range(sample_size + 1, pop_size + 1):
+ next_expected = expected * n / (n - sample_size)
+ ends.append(ends[-1] + max(1, math.ceil(next_expected - expected)))
+ expected = next_expected
+ return tuple(ends)
+
+
+def _squared_line_distance(ls1: torch.Tensor, ls2: torch.Tensor, models: torch.Tensor) -> torch.Tensor:
+ """Convert the line helper's algebraic residual into squared coordinate distance."""
+ residual = line_segment_transfer_error_one_way(ls1, ls2, models)
+ length = (ls2[..., 1, :] - ls2[..., 0, :]).norm(dim=-1)
+ distance = residual / torch.where(length > 0, length, torch.ones_like(length))
+ return torch.where(length > 0, distance.square(), torch.full_like(distance, float("inf")))
+
+
class RANSAC(nn.Module):
"""Module for robust geometry estimation with RANSAC. https://en.wikipedia.org/wiki/Random_sample_consensus.
Convention:
- ``kp1`` and ``kp2`` are passed as the first- and second-image arguments of the estimator selected by
``model_type``, so a homography maps ``kp1`` to ``kp2``. ``forward`` returns a ``(3, 3)`` model and an
- ``(N,)`` bool inlier mask, or an all-zero model and no inliers when no sample reaches consensus.
- - For the four point models, ``inl_th`` is in the keypoints' own units (pixels, or calibrated units for
- ``"essential"``): a correspondence is an inlier when its one-way transfer error for ``"homography"``,
- or its Sampson distance for ``"fundamental"``, ``"fundamental_7pt"`` and ``"essential"``, is at most
- ``inl_th``. :ref:`two-view-conventions` compares this with OpenCV.
+ ``(N,)`` bool inlier mask, or an all-zero model and no inliers when no candidate has more inliers than
+ its minimal sample (four correspondences for homographies, five for ``"essential"``, seven or eight
+ for the fundamental models).
+ - ``inl_th`` is in the keypoints' own units (pixels, or calibrated units for ``"essential"``): a
+ correspondence is an inlier when its one-way transfer error for ``"homography"``, its Sampson distance
+ for ``"fundamental"``, ``"fundamental_7pt"`` and ``"essential"``, or the mean distance of its transferred
+ endpoints from the image-2 segment's line for ``"homography_from_linesegments"`` is at most ``inl_th``.
+ :ref:`two-view-conventions` compares this with OpenCV.
+ - ``score_type="msac"`` ranks candidates by ``sum(1 - min(e / inl_th**2, 1))`` over the squared errors
+ ``e``; acceptance and early stopping count inliers for either score.
+ - ``prosac_sampling=True`` expects correspondences sorted best-first and always 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.
- - Known defects: for ``"homography_from_linesegments"`` the error is the perpendicular distance times the
- image-2 segment length and is compared with ``inl_th**2``, so a segment offset by ``d`` pixels is an inlier
- when ``d * length <= inl_th**2`` (`#4867 <https://github.com/kornia/kornia/issues/4867>`_), and the
- endpoint pairing of :func:`~kornia.geometry.homography.find_homography_lines_dlt` applies
- (`#4866 <https://github.com/kornia/kornia/issues/4866>`_); ``score_type="msac"`` uses its score as an
- inlier count, so with outliers present it can return no model where ``"ransac"`` finds one
- (`#4868 <https://github.com/kornia/kornia/issues/4868>`_); ``prosac_sampling`` has no effect
- (`#4869 <https://github.com/kornia/kornia/issues/4869>`_); and too few correspondences for
- ``"fundamental_7pt"`` and ``"essential"`` are not rejected by the input check and fail inside sampling
- (`#4872 <https://github.com/kornia/kornia/issues/4872>`_).
+ - Known defects: for ``"homography_from_linesegments"``, local optimization weights segments by the
+ length-scaled residual of :func:`~kornia.geometry.homography.line_segment_transfer_error_one_way`, which
+ down-weights long segments (`#4867 <https://github.com/kornia/kornia/issues/4867>`_), and the endpoint
+ pairing of :func:`~kornia.geometry.homography.find_homography_lines_dlt` applies
+ (`#4866 <https://github.com/kornia/kornia/issues/4866>`_).
Args:
- model_type: type of model to estimate: "homography", "fundamental", "fundamental_7pt", "essential",
+ model_type: "homography", "fundamental", "fundamental_7pt", "essential", or
"homography_from_linesegments".
- inl_th: inlier threshold, in the units given above.
+ inl_th: positive inlier threshold, in the units given above.
batch_size: number of generated samples at once.
- max_iter: maximum batches to generate. At most ``batch_size * max_iter`` minimal samples are drawn.
- confidence: desired confidence of the result, used for the early stopping.
- max_lo_iters: number of local optimization (polishing) iterations.
+ max_iter: maximum batches to generate, giving a budget of ``batch_size * max_iter`` minimal samples.
+ The seven- and five-point solvers can return multiple models per sample.
+ confidence: uniform-sampling stopping confidence in ``(0, 1]``; 1 disables early stopping.
+ max_lo_iters: maximum local refitting iterations; zero disables polishing.
+ score_type: "ransac" for support count, or "msac" for truncated squared residuals.
+ prosac_sampling: use PROSAC sampling on best-first ordered correspondences. The growth schedule
+ advances per sampled set within each batch; this mode uses the full sampling budget.
+ seed: optional seed, reset on each call for reproducible estimation on the same device.
+ lo_sample_size: optional inlier-subset size for a batch of ``max_lo_iters`` randomized local
+ refits followed by a full-inlier refit. None uses iterative full-inlier refitting.
"""
@@ -85,6 +119,7 @@ class RANSAC(nn.Module):
score_type: str = "ransac",
prosac_sampling: bool = False,
seed: Optional[int] = None,
+ lo_sample_size: Optional[int] = None,
) -> None:
"""Initialize the RANSAC estimator.
@@ -94,12 +129,17 @@ class RANSAC(nn.Module):
inl_th: inlier threshold; the class docstring gives its unit per ``model_type``.
batch_size: number of generated samples at once.
max_iter: maximum batches to generate. At most ``batch_size * max_iter`` minimal samples are drawn.
- confidence: desired confidence of the result, used for the early stopping.
+ confidence: desired confidence of the result, used for the early stopping. 1 runs the full budget.
max_lo_iters: number of local optimization (polishing) iterations.
score_type: scoring method to use: "ransac" or "msac".
- prosac_sampling: meant to select PROSAC sampling; it has no effect
- (`#4869 <https://github.com/kornia/kornia/issues/4869>`_).
+ prosac_sampling: use PROSAC's progressive sampling schedule. Inputs must be sorted best-first
+ by match quality. The schedule advances for every sampled set, including within batches.
+ Uses the full sampling budget rather than the uniform sampler's confidence stopping rule.
seed: optional random seed for reproducible results. If None, uses global random state.
+ lo_sample_size: optional cap on the number of inliers used by each randomized local refit.
+ Fits ``max_lo_iters`` independent subsets in one batch, followed by one full-inlier refit.
+ None uses iterative full-inlier refitting. Subset refits must raise the score; a full-inlier
+ refit may also tie it, since it is more precise than the minimal-sample model.
"""
super().__init__()
@@ -111,6 +151,14 @@ class RANSAC(nn.Module):
"essential",
]
self.supported_scores = ["msac", "ransac"]
+ if score_type not in self.supported_scores:
+ raise ValueError(f"Unsupported score type: {score_type}")
+ if not math.isfinite(inl_th * inl_th) or inl_th <= 0 or inl_th * inl_th == 0:
+ raise ValueError("inl_th and its square must be positive and finite")
+ if batch_size <= 0 or max_iter <= 0 or max_lo_iters < 0:
+ raise ValueError("batch_size and max_iter must be positive; max_lo_iters must be nonnegative")
+ if not 0 < confidence <= 1:
+ raise ValueError("confidence must lie in (0, 1]")
self.score_type = score_type
self.inl_th = inl_th
self.max_iter = max_iter
@@ -121,6 +169,9 @@ class RANSAC(nn.Module):
self.model_type = model_type
self.prosac_sampling = prosac_sampling
self.seed = seed
+ self.lo_sample_size = lo_sample_size
+ # 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
self.error_fn: Callable[..., torch.Tensor]
self.minimal_solver: Callable[..., torch.Tensor]
@@ -133,8 +184,11 @@ class RANSAC(nn.Module):
self.minimal_sample_size = 4
self.polisher_sample_size = 4
elif model_type == "homography_from_linesegments":
- self.error_fn = line_segment_transfer_error_one_way
+ self.error_fn = _squared_line_distance
self.minimal_solver = find_homography_lines_dlt
+ # Known defect: this IRLS polisher weights segments by the length-scaled residual of
+ # line_segment_transfer_error_one_way, not by the distance used for scoring, so local
+ # optimization down-weights long segments (https://github.com/kornia/kornia/issues/4867).
self.polisher_solver = find_homography_lines_dlt_iterated
self.minimal_sample_size = 4
self.polisher_sample_size = 4
@@ -158,9 +212,16 @@ class RANSAC(nn.Module):
self.polisher_sample_size = 8
else:
raise NotImplementedError(f"{model_type} is unknown. Try one of {self.supported_models}")
+ if lo_sample_size is not None and lo_sample_size < self.polisher_sample_size:
+ raise ValueError(f"lo_sample_size must be at least {self.polisher_sample_size}")
def sample(
- self, sample_size: int, pop_size: int, batch_size: int, iteration: int, device: Optional[torch.device] = None
+ self,
+ sample_size: int,
+ pop_size: int,
+ batch_size: int,
+ iteration: int,
+ device: Optional[Union[torch.device, str]] = None,
) -> torch.Tensor:
"""Minimal sampler, but unlike traditional RANSAC we sample in batches.
@@ -170,23 +231,76 @@ class RANSAC(nn.Module):
sample_size: number of samples to draw from the population.
pop_size: size of the population to sample from.
batch_size: number of sample sets to generate.
- iteration: current iteration number, added to ``seed`` when one is set.
+ iteration: zero-based batch index (used for PROSAC scheduling and the random seed).
device: device to place the samples on.
Returns:
Tensor of sampled indices with shape :math:`(batch_size, sample_size)`.
"""
- if device is None:
- device = torch.device("cpu")
+ device = torch.device("cpu") if device is None else torch.device(device)
+ if not 0 < sample_size <= pop_size:
+ raise ValueError("sample_size must be positive and no larger than pop_size")
+ generator = None
if self.seed is not None:
generator = torch.Generator(device=device)
generator.manual_seed(self.seed + iteration)
- rand = torch.rand(batch_size, pop_size, device=device, generator=generator)
- else:
- rand = torch.rand(batch_size, pop_size, device=device)
- _, out = rand.topk(k=sample_size, dim=1)
- return out
+ if device.type != "cpu" and not self.prosac_sampling:
+ return (
+ torch.rand(batch_size, pop_size, device=device, generator=generator)
+ .topk(k=sample_size, dim=1, sorted=False)
+ .indices
+ )
+ # The PROSAC schedule is indexed by sampled SETS, not outer batches or solver roots.
+ # See https://cmp.felk.cvut.cz/~matas/papers/chum-prosac-cvpr05.pdf, eqs. 3--6.
+ population = torch.full((batch_size,), pop_size, device=device, dtype=torch.long)
+ force_newest = torch.zeros(batch_size, device=device, dtype=torch.bool)
+ if self.prosac_sampling:
+ ends = self._prosac_schedule(sample_size, pop_size, device)
+ draws = torch.arange(batch_size, device=device) + iteration * batch_size + 1
+ population = (torch.searchsorted(ends, draws) + sample_size).clamp(max=pop_size)
+ force_newest = draws <= ends[-1]
+
+ if device.type == "cpu":
+ # Floyd's sampling without replacement: O(B*m^2) comparisons and O(B*m)
+ # storage, independent of N. Vectorize over the entire hypothesis batch.
+ # Random-key topk is faster on CUDA, where these m small steps are launch-bound.
+ rand = torch.rand(batch_size, sample_size, device=device, dtype=torch.float64, generator=generator)
+ out = torch.empty(batch_size, sample_size, device=device, dtype=torch.long)
+ for i in range(sample_size):
+ last = population - sample_size + i
+ candidate = (rand[:, i] * (last + 1)).long()
+ if i > 0:
+ duplicate = (out[:, :i] == candidate[:, None]).any(dim=1)
+ candidate = torch.where(duplicate, last, candidate)
+ if i == sample_size - 1:
+ candidate = torch.where(force_newest, last, candidate)
+ out[:, i] = candidate
+ return out
+
+ rand = torch.rand(batch_size, pop_size, device=device, generator=generator)
+ if self.prosac_sampling:
+ rand.masked_fill_(torch.arange(pop_size, device=device)[None] >= population[:, None], -1.0)
+ # Making the newest point largest forces its inclusion, leaving a uniform
+ # (m-1)-subset of the preceding prefix. After growth, sample uniformly.
+ newest = population[:, None] - 1
+ rand.scatter_(1, newest, torch.where(force_newest[:, None], 2.0, rand.gather(1, newest)))
+ return rand.topk(k=sample_size, dim=1, sorted=False).indices
+
+ def _is_supported(self, num_inliers: float) -> bool:
+ """Whether a model has support beyond the minimal sample it may have been fitted to.
+
+ A minimal-sample model always fits its own sample, so only further inliers are evidence of a
+ consensus; without them, input with no consensus returns the all-zero failure matrix.
+ """
+ return num_inliers > self.minimal_sample_size
+
+ def _prosac_schedule(self, sample_size: int, pop_size: int, device: torch.device) -> torch.Tensor:
+ """Return the cumulative PROSAC draw counts on ``device``, converting them once per configuration."""
+ key = (sample_size, pop_size, self.batch_size * self.max_iter, device)
+ if self._prosac_ends is None or self._prosac_ends[0] != key:
+ self._prosac_ends = (key, torch.tensor(_prosac_growth(*key[:3]), device=device))
+ return self._prosac_ends[1]
@staticmethod
def max_samples_by_conf(n_inl: int, num_tc: int, sample_size: int, conf: float) -> int:
@@ -199,20 +313,17 @@ class RANSAC(nn.Module):
conf: desired confidence level.
Returns:
- Maximum number of samples needed to achieve the desired confidence.
+ Number of samples needed to achieve the desired confidence, rounded up.
+ Returns ``sys.maxsize`` when no finite stopping bound is available.
"""
- eps = 1e-9
- if num_tc <= sample_size:
- return 1
- if n_inl == num_tc:
- return 1
- if n_inl <= sample_size:
- return 1
- if conf >= 1.0:
- return 1
if conf <= 0.0:
return 1
+ # conf >= 1 disables early stopping, even when every correspondence is an inlier.
+ if conf >= 1.0 or num_tc < sample_size or n_inl < sample_size:
+ return sys.maxsize
+ if n_inl >= num_tc:
+ return 1
# Proper RANSAC formula for sampling without replacement
# P(all samples are inliers) = (n_inl/num_tc) * ((n_inl-1)/(num_tc-1)) * ...
# ... * ((n_inl-sample_size+1)/(num_tc-sample_size+1))
@@ -220,7 +331,9 @@ class RANSAC(nn.Module):
for i in range(sample_size):
prob_inlier *= (n_inl - i) / (num_tc - i)
- return int(math.log(1.0 - conf) / min(-eps, math.log(max(eps, 1.0 - prob_inlier))))
+ if prob_inlier == 0.0:
+ return sys.maxsize
+ return min(sys.maxsize, math.ceil(math.log1p(-conf) / math.log1p(-prob_inlier)))
def estimate_model_from_minsample(self, kp1: torch.Tensor, kp2: torch.Tensor) -> torch.Tensor:
"""Estimate models from minimal samples.
@@ -245,16 +358,18 @@ class RANSAC(nn.Module):
kp1: source keypoints.
kp2: target keypoints.
models: candidate models to verify.
- inl_th: inlier threshold.
+ inl_th: positive squared inlier threshold.
Returns:
Tuple containing:
- Best model
- Inlier mask for the best model
- Score of the best model
- - Number of inliers of the best model
+ - Number of inliers (distinct from the MSAC score)
"""
+ if not math.isfinite(inl_th) or inl_th <= 0:
+ raise ValueError("The squared inlier threshold must be positive and finite")
if len(kp1.shape) == 2:
kp1 = kp1[None]
if len(kp2.shape) == 2:
@@ -263,12 +378,29 @@ class RANSAC(nn.Module):
if self.model_type == "homography_from_linesegments":
errors = self.error_fn(kp1.expand(batch_size, -1, 2, 2), kp2.expand(batch_size, -1, 2, 2), models)
else:
- errors = self.error_fn(kp1.expand(batch_size, -1, 2), kp2.expand(batch_size, -1, 2), models)
+ # The point metrics broadcast over models. Expanding points first makes
+ # homogeneous conversion allocate B copies of identical coordinates.
+ errors = self.error_fn(kp1, kp2, models)
+ # Non-finite residuals must not poison the reduction or win argmax. One kernel: this runs for
+ # every batch and every LO step, where accelerator launches dominate the cost.
+ inf = float("inf")
+ errors = errors.nan_to_num(nan=inf, posinf=inf, neginf=inf)
inl_mask = errors <= inl_th
score_ransac = inl_mask.sum(dim=1)
if self.score_type == "msac":
- score = errors.shape[1] - errors.clamp(min=0.0, max=inl_th).sum(dim=1)
+ # Equivalent to minimizing the truncated squared loss (MSAC), normalized
+ # to [0, N]. This is a quality score, NOT an inlier count. Accumulate in at
+ # least float32: a half-precision total rounds to steps of 2-4 in the hundreds.
+ score = (1.0 - errors.clamp(min=0.0, max=inl_th) / inl_th).sum(
+ dim=1, dtype=torch.promote_types(errors.dtype, torch.float32)
+ )
+ # A high-quality but under-supported model must not hide a viable candidate
+ # elsewhere in the same batch. An all-invalid batch is rejected by forward.
+ # The same support rule as _is_supported.
+ score = score.masked_fill(score_ransac <= self.minimal_sample_size, -1)
elif self.score_type == "ransac":
+ # The score is the support, so argmax already prefers any sufficiently supported
+ # candidate; forward rejects an insufficient best support.
score = score_ransac
else:
raise ValueError(f"Unsupported score type: {self.score_type}")
@@ -308,7 +440,7 @@ class RANSAC(nn.Module):
"""
# Filter out NaN or Inf models
- mask = torch.isfinite(models).all(dim=-1).all(dim=-1)
+ mask = torch.isfinite(models).all(dim=-1).all(dim=-1) & (models.abs().amax(dim=(-2, -1)) > 0)
return models[mask]
def polish_model(self, kp1: torch.Tensor, kp2: torch.Tensor, inliers: torch.Tensor) -> torch.Tensor:
@@ -335,9 +467,85 @@ class RANSAC(nn.Module):
# Project it back onto the essential manifold so that downstream decompose_essential_matrix /
# motion_from_essential do not silently fail.
# See https://github.com/kornia/kornia/issues/3874
- if self.model_type == "essential":
- model = project_to_essential(model)
- return model
+ return self._project_refits(model)
+
+ def _project_refits(self, models: torch.Tensor) -> torch.Tensor:
+ """Project essential refits onto the manifold, dropping invalid ones before the projection's SVD."""
+ if self.model_type != "essential":
+ return models
+ models = self.remove_bad_models(models)
+ return project_to_essential(models) if len(models) > 0 else models
+
+ def _subset_refits(
+ self, kp1: torch.Tensor, kp2: torch.Tensor, inliers: torch.Tensor, lo_sample_size: int, iteration: int
+ ) -> torch.Tensor:
+ """Fit ``max_lo_iters`` random ``lo_sample_size``-subsets of the inliers in one solver batch.
+
+ Randomized non-minimal refits let LO escape a bad consensus. Bounded subsets follow Lebeda et al.,
+ BMVC 2012 (LO+), but this is not the full LO+ algorithm with threshold scheduling.
+ """
+ generator = None
+ if self.seed is not None:
+ generator = torch.Generator(device=kp1.device)
+ generator.manual_seed(self.seed + self.max_iter + iteration)
+ indices = inliers.nonzero().flatten()
+ # Independent refits share the current consensus and run in one
+ # solver batch, rather than max_lo_iters tiny accelerator calls.
+ subset = torch.rand(self.max_lo_iters, len(indices), device=kp1.device, generator=generator)
+ selected = indices[subset.topk(lo_sample_size, dim=1).indices]
+ models = self.polisher_solver(kp1[selected], kp2[selected], torch.ones_like(selected, dtype=kp1.dtype))
+ return self._project_refits(models)
+
+ def _local_optimization(
+ self,
+ kp1: torch.Tensor,
+ kp2: torch.Tensor,
+ model: torch.Tensor,
+ inliers: torch.Tensor,
+ model_score: float,
+ num_inliers: float,
+ iteration: int,
+ ) -> Tuple[torch.Tensor, torch.Tensor, float, float, bool]:
+ """Refit a newly accepted model from its inliers.
+
+ Returns:
+ The refined model, its inlier mask, score and support, and whether the model is still the
+ minimal solver's (no refit replaced it).
+
+ """
+ from_minimal_solver = True
+ lo_sample_size = self.lo_sample_size
+ bounded_lo = lo_sample_size is not None and num_inliers > lo_sample_size and self.max_lo_iters > 0
+ for lo_iteration in range(2 if bounded_lo else self.max_lo_iters):
+ if num_inliers < self.polisher_sample_size:
+ break
+ use_subset = bounded_lo and lo_iteration == 0
+ if use_subset and lo_sample_size is not None:
+ model_lo = self._subset_refits(kp1, kp2, inliers, lo_sample_size, iteration)
+ else:
+ model_lo = self.polish_model(kp1, kp2, inliers)
+ if model_lo is not None and len(model_lo) > 0:
+ model_lo = self.remove_bad_models(model_lo)
+ if model_lo is None or len(model_lo) == 0:
+ # A failed subset batch still leaves the full refit. A failed full refit would
+ # only repeat itself, since the inliers it was fitted to have not changed.
+ if use_subset:
+ continue
+ break
+ model_lo_best, inliers_lo, score_lo, num_inliers_lo = self.verify(kp1, kp2, model_lo, self.inl_th**2)
+ improved = score_lo > model_score
+ # A full-inlier least-squares refit that keeps the score is still more precise than
+ # the minimal-sample model; RANSAC scoring ties whenever support does not grow.
+ tied_refit = score_lo == model_score and not use_subset
+ if (improved or tied_refit) and self._is_supported(num_inliers_lo):
+ model = model_lo_best
+ inliers = inliers_lo.clone()
+ model_score = score_lo
+ num_inliers = num_inliers_lo
+ from_minimal_solver = False
+ if not improved and not use_subset:
+ break
+ return model, inliers, model_score, num_inliers, from_minimal_solver
def validate_inputs(self, kp1: torch.Tensor, kp2: torch.Tensor, weights: Optional[torch.Tensor] = None) -> None:
"""Validate input tensors for shape and size requirements.
@@ -348,14 +556,12 @@ class RANSAC(nn.Module):
weights: optional correspondence weights (not used currently).
Raises:
- ValueError: for ``"homography"``, ``"fundamental"`` and ``"homography_from_linesegments"``, if ``kp1``
- and ``kp2`` differ in length or hold fewer correspondences than the minimal sample.
- ``"fundamental_7pt"`` and ``"essential"`` inputs are not checked
- (`#4872 <https://github.com/kornia/kornia/issues/4872>`_).
- ShapeError: for the same model types, if the keypoint shape is wrong.
+ ValueError: if ``kp1`` and ``kp2`` differ in length or hold fewer correspondences than the minimal
+ sample.
+ ShapeError: if the keypoint shape is wrong.
"""
- if self.model_type in ["homography", "fundamental"]:
+ if self.model_type != "homography_from_linesegments":
KORNIA_CHECK_SHAPE(kp1, ["N", "2"])
KORNIA_CHECK_SHAPE(kp2, ["N", "2"])
if not (kp1.shape[0] == kp2.shape[0]) or (kp1.shape[0] < self.minimal_sample_size):
@@ -379,22 +585,29 @@ class RANSAC(nn.Module):
r"""Call main forward method to execute the RANSAC algorithm.
Args:
- kp1: source image keypoints :math:`(N, 2)`, or segments :math:`(N, 2, 2)` for
- ``"homography_from_linesegments"``.
- kp2: destination image keypoints, with the shape of ``kp1``.
+ kp1: source image keypoints :math:`(N, 2)` (or line segments :math:`(N, 2, 2)`).
+ kp2: target image keypoints with the same shape. For PROSAC, both inputs must be sorted
+ best-first using the same correspondence-quality ordering. Essential estimation uses
+ camera-normalized coordinates and a threshold in those units.
weights: optional correspondences weights. Not used now.
Returns:
- - Estimated model, shape of :math:`(3, 3)`; all zeros when no model is found.
- - The inlier mask, shape of :math:`(N,)`, where N is number of input correspondences.
+ - Estimated model, shape of :math:`(3, 3)`, or zeros if no valid model is found. A model needs
+ more inliers than its minimal sample, since a model fitted to a sample fits that sample.
+ - Boolean inlier mask, shape of :math:`(N,)`, in the supplied correspondence order.
"""
self.validate_inputs(kp1, kp2, weights)
- best_score_total: float = float(self.minimal_sample_size)
+ best_score_total = -float("inf")
+ max_samples = self.max_iter * self.batch_size
num_tc: int = len(kp1)
best_model_total = torch.zeros(3, 3, dtype=kp1.dtype, device=kp1.device)
inliers_best_total: torch.Tensor = torch.zeros(num_tc, device=kp1.device, dtype=torch.bool)
+ # Only a minimal-solver model needs projecting onto the essential manifold; LO refits already are.
+ best_needs_projection = False
for i in range(self.max_iter):
+ if i * self.batch_size >= max_samples:
+ break
# Sample minimal samples in batch to estimate models
idxs = self.sample(self.minimal_sample_size, num_tc, self.batch_size, i, kp1.device)
kp1_sampled = kp1[idxs]
@@ -412,39 +625,35 @@ class RANSAC(nn.Module):
# Score the models and select the best one
model, inliers, model_score, num_inliers = self.verify(kp1, kp2, models, self.inl_th**2)
# Store far-the-best model and (optionally) do a local optimization
- if (model_score > best_score_total) and num_inliers >= self.polisher_sample_size:
- # Local optimization
- for _ in range(self.max_lo_iters):
- model_lo = self.polish_model(kp1, kp2, inliers)
- if (model_lo is None) or (len(model_lo) == 0):
- continue
- model_lo_best, inliers_lo, score_lo, num_inliers_lo = self.verify(
- kp1, kp2, model_lo, self.inl_th**2
- )
- if (score_lo > model_score) and (num_inliers_lo >= self.polisher_sample_size):
- model = model_lo_best
- inliers = inliers_lo.clone()
- model_score = score_lo
- else:
- break
+ if (model_score > best_score_total) and self._is_supported(num_inliers):
+ model, inliers, model_score, num_inliers, from_minimal_solver = self._local_optimization(
+ kp1, kp2, model, inliers, model_score, num_inliers, i
+ )
# Now storing the best model
best_model_total = model.clone()
inliers_best_total = inliers.clone()
best_score_total = model_score
+ best_needs_projection = from_minimal_solver
# Should we already stop?
- new_max_iter = self.max_samples_by_conf(
- int(best_score_total), num_tc, self.minimal_sample_size, self.confidence
- )
-
- # Stop estimation, if the model is very good
- if (i + 1) * self.batch_size >= new_max_iter:
- break
- # local optimization with all inliers for better precision
+ # The score may be MSAC; confidence depends on support, and counts
+ # sampled sets, not the number of roots returned by a minimal solver.
+ # The bound follows the incumbent's own support, as in OpenCV's USAC: under
+ # MSAC a better-scoring model can have less support than the one it replaced.
+ if not self.prosac_sampling:
+ max_samples = min(
+ self.max_iter * self.batch_size,
+ self.max_samples_by_conf(int(num_inliers), num_tc, self.minimal_sample_size, self.confidence),
+ )
# The best model may come from the 5-point minimal solver (find_essential), which is not
# guaranteed to return a matrix on the essential manifold. Project the returned model once
# instead of projecting every candidate inside the loop, so that model selection is unaffected.
# See https://github.com/kornia/kornia/issues/3874
- if self.model_type == "essential":
+ if self.model_type == "essential" and best_needs_projection:
best_model_total = project_to_essential(best_model_total[None])[0]
+ _, inliers_best_total, _, support = self.verify(kp1, kp2, best_model_total[None], self.inl_th**2)
+ # Projection moves the residuals; a model that loses its support is no model.
+ if not self._is_supported(support):
+ best_model_total = torch.zeros_like(best_model_total)
+ inliers_best_total = torch.zeros_like(inliers_best_total)
return best_model_total, inliers_best_total
diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.py
index 79af23a53..8406f60e8 100644
--- a/tests/geometry/test_ransac.py
+++ b/tests/geometry/test_ransac.py
@@ -16,6 +16,9 @@
#
+import math
+import sys
+
import pytest
import torch
@@ -194,19 +197,25 @@ class TestRANSACFundamental(BaseTester):
assert Fm.shape == (3, 3)
@pytest.mark.slow
- @pytest.mark.xfail(reason="might slightly and randomly imprecise due to RANSAC randomness")
@pytest.mark.parametrize("data", ["loftr_fund"], indirect=True)
def test_real_clean_8pt(self, device, dtype, data):
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("find_fundamental calls torch.linalg.eigh, which has no float16/bfloat16 kernel")
torch.random.manual_seed(0)
# generate input data
data_dev = dict_to(data, device, dtype)
pts_src = data_dev["pts0"]
pts_dst = data_dev["pts1"]
- # compute transform from source to target
- ransac = RANSAC("fundamental", inl_th=0.5, max_iter=20, max_lo_iters=10).to(device=device, dtype=dtype)
- fundamental_matrix, _ = ransac(pts_src, pts_dst)
+ # The ground-truth F leaves up to 0.58px on these 10 points. At 0.5px the best eight-point fit has
+ # only its own sample as inliers, which is no consensus, so RANSAC returns the zero failure matrix;
+ # at 1px all ten are inliers, and over 100 seeds the refit's largest error is at most 1px.
+ ransac = RANSAC("fundamental", inl_th=1.0, max_iter=20, max_lo_iters=10).to(device=device, dtype=dtype)
+ fundamental_matrix, mask = ransac(pts_src, pts_dst)
+ # A zero matrix is the failure result and has zero Sampson error for every point.
+ assert fundamental_matrix.abs().amax() > 0
+ assert mask.all()
gross_errors = (
- sampson_epipolar_distance(pts_src[None], pts_dst[None], fundamental_matrix[None], squared=False) > 1.0
+ sampson_epipolar_distance(pts_src[None], pts_dst[None], fundamental_matrix[None], squared=False) > 2.0
)
assert gross_errors.sum().item() == 0
@@ -222,6 +231,7 @@ class TestRANSACFundamental(BaseTester):
# compute transform from source to target
ransac = RANSAC("fundamental_7pt", inl_th=1.0, max_iter=100, max_lo_iters=10).to(device=device, dtype=dtype)
fundamental_matrix, _ = ransac(pts_src, pts_dst)
+ assert fundamental_matrix.abs().amax() > 0
gross_errors = (
sampson_epipolar_distance(pts_src[None], pts_dst[None], fundamental_matrix[None], squared=False) > 1.0
)
@@ -243,6 +253,7 @@ class TestRANSACFundamental(BaseTester):
ransac = RANSAC("fundamental", inl_th=1.0, max_iter=20, max_lo_iters=10).to(device=device, dtype=dtype)
# compute transform from source to target
fundamental_matrix, _ = ransac(kp1, kp2)
+ assert fundamental_matrix.abs().amax() > 0
gross_errors = (
sampson_epipolar_distance(pts_src[None], pts_dst[None], fundamental_matrix[None], squared=False) > 10.0
)
@@ -264,6 +275,7 @@ class TestRANSACFundamental(BaseTester):
ransac = RANSAC("fundamental_7pt", inl_th=1.0, max_iter=20, max_lo_iters=10).to(device=device, dtype=dtype)
# compute transform from source to target
fundamental_matrix, _ = ransac(kp1, kp2)
+ assert fundamental_matrix.abs().amax() > 0
gross_errors = (
sampson_epipolar_distance(pts_src[None], pts_dst[None], fundamental_matrix[None], squared=False) > 10.0
)
@@ -340,9 +352,9 @@ class TestRansacMethods:
conf = 0.99
# Test 1: Very few inliers (1 out of 1000) with sample_size=7
- # Returns 1 because n_inl <= sample_size (early exit condition)
+ # An all-inlier minimal sample is impossible.
x = RANSAC.max_samples_by_conf(n_inl=1, num_tc=1000, sample_size=7, conf=conf)
- assert x == 1 # Early exit when n_inl <= sample_size
+ assert x == sys.maxsize
# Test 2: Low inlier ratio (10 out of 1000, 1%) with sample_size=7
# Should require many iterations
@@ -374,15 +386,15 @@ class TestRansacMethods:
# Test 6: Edge case - not enough points for sample
x = RANSAC.max_samples_by_conf(n_inl=10, num_tc=10, sample_size=15, conf=conf)
- assert x == 1 # Returns 1 when num_tc <= sample_size
+ assert x == sys.maxsize
# Test 7: Edge case - too few inliers (n_inl <= sample_size)
x = RANSAC.max_samples_by_conf(n_inl=2, num_tc=1000, sample_size=4, conf=conf)
- assert x == 1 # Returns 1 when n_inl <= sample_size
+ assert x == sys.maxsize
# Test 8: Edge case - confidence at boundaries
x = RANSAC.max_samples_by_conf(n_inl=50, num_tc=100, sample_size=4, conf=1.0)
- assert x == 1 # Returns 1 when conf >= 1.0
+ assert x == sys.maxsize
x = RANSAC.max_samples_by_conf(n_inl=50, num_tc=100, sample_size=4, conf=0.0)
assert x == 1 # Returns 1 when conf <= 0.0
@@ -414,8 +426,10 @@ class TestRANSACSeed:
points1 = torch.rand(20, 2, device=device, dtype=dtype)
points2 = torch.rand(20, 2, device=device, dtype=dtype)
- ransac_a = RANSAC("homography", inl_th=2.0, max_iter=5, seed=1).to(device=device, dtype=dtype)
- ransac_b = RANSAC("homography", inl_th=2.0, max_iter=5, seed=2).to(device=device, dtype=dtype)
+ # Every point is an inlier at this threshold, so local optimization would return the same
+ # least-squares fit for any seed; compare the seed-dependent minimal-sample models instead.
+ ransac_a = RANSAC("homography", inl_th=2.0, max_iter=5, max_lo_iters=0, seed=1).to(device=device, dtype=dtype)
+ ransac_b = RANSAC("homography", inl_th=2.0, max_iter=5, max_lo_iters=0, seed=2).to(device=device, dtype=dtype)
H_a, _ = ransac_a(points1, points2)
H_b, _ = ransac_b(points1, points2)
@@ -727,27 +741,26 @@ class TestConventionRANSAC(BaseTester):
model_d, mask_d = run(None)
assert torch.equal(model_c, model_d) and torch.equal(mask_c, mask_d)
- def test_wart_ransac_linesegment_threshold_units_4867(self, device, dtype):
+ def test_convention_ransac_linesegment_threshold_units_4867(self, device, dtype):
_cpu_only(device)
if dtype in (torch.float16, torch.bfloat16):
pytest.skip(_HALF_LINES)
H = torch.tensor([_H_TRUE], device=device, dtype=dtype)
- # One segment moved 3 px off its line in image 2, scored by the true H. #4867: the line error is the
- # distance times the image-2 segment length and forward compares it with inl_th**2, so at inl_th=17 the
- # 3-px offset is an inlier on a 66-px segment and an outlier on a 129-px one. Once the error is a pixel
- # distance, both are inliers.
- inlier = []
+ # One segment moved 3 px off its line in image 2, scored by the true H. The inlier test uses the mean
+ # endpoint-to-line distance in pixels, whatever the segment's length: the 3-px offset is an inlier at
+ # inl_th=4 and an outlier at inl_th=2 on a 66-px and on a 129-px segment alike. #4867 compared the distance
+ # times the segment length with inl_th**2, which rejected both at inl_th=4.
for stretch in (1.0, 2.0):
ls1, ls2 = _planar_segments(device, dtype, stretch)
d = ls2[0, 1] - ls2[0, 0]
ls2[0] += 3.0 * torch.stack([-d[1], d[0]]) / d.norm()
- ransac = RANSAC("homography_from_linesegments", inl_th=17.0, batch_size=1, max_iter=1, max_lo_iters=0)
- _, mask = _fixed_model(ransac, H)(ls1, ls2)
- assert bool(mask[1:].all())
- inlier.append(bool(mask[0]))
- assert inlier == [True, False]
+ for inl_th, expected in ((4.0, True), (2.0, False)):
+ ransac = RANSAC("homography_from_linesegments", inl_th=inl_th, batch_size=1, max_iter=1, max_lo_iters=0)
+ _, mask = _fixed_model(ransac, H)(ls1, ls2)
+ assert bool(mask[1:].all())
+ assert bool(mask[0]) is expected
- def test_wart_ransac_msac_no_model_with_outliers_4868(self, device, dtype):
+ def test_convention_ransac_msac_finds_model_with_outliers_4868(self, device, dtype):
_cpu_only(device)
kp1, kp2 = _planar_matches(device, dtype)
kp1 = torch.cat([kp1, torch.tensor(_UNRELATED_1, device=device, dtype=dtype)])
@@ -757,38 +770,431 @@ class TestConventionRANSAC(BaseTester):
kp1, kp2
)
assert bool(mask[:16].all()) and not bool(mask[16:].any())
- # #4868: the MSAC score N - sum(min(err, inl_th**2)) is compared with the minimal sample size, a count, so
- # with sixteen outliers at inl_th=5 no model beats it and nothing is returned. Once fixed, msac finds it too.
+ # MSAC ranks candidates by their truncated residuals and accepts them by inlier count, so it finds the same
+ # sixteen. #4868 compared the MSAC score N - sum(min(err, inl_th**2)) with the minimal sample size, a count,
+ # and returned no model here.
model, mask = RANSAC("homography", inl_th=5.0, score_type="msac", seed=0, max_iter=5, batch_size=256)(kp1, kp2)
- assert bool((model == 0).all()) and not bool(mask.any())
+ assert bool(model.abs().amax() > 0)
+ assert bool(mask[:16].all()) and not bool(mask[16:].any())
- def test_wart_ransac_prosac_sampling_ignored_4869(self, device, dtype):
+ def test_convention_ransac_prosac_sampling_4869(self, device, dtype):
_cpu_only(device)
- kp1, kp2 = _planar_matches(device, dtype)
- kp1 = torch.cat([kp1, torch.tensor(_UNRELATED_1, device=device, dtype=dtype)])
- kp2 = torch.cat([kp2, torch.tensor(_UNRELATED_2, device=device, dtype=dtype)])
- # #4869: prosac_sampling is stored and never read, so the sampler and the result are identical either way.
- # A PROSAC sampler draws its first samples from the top-ranked correspondences and changes both.
+ # PROSAC draws its first sample from the four top-ranked correspondences and then grows the prefix it samples
+ # from, one newest correspondence per sample, so its first samples differ from uniform ones. #4869 stored
+ # prosac_sampling and never read it.
prosac = RANSAC("homography", inl_th=2.0, seed=3, prosac_sampling=True, max_iter=3, batch_size=16)
uniform = RANSAC("homography", inl_th=2.0, seed=3, prosac_sampling=False, max_iter=3, batch_size=16)
- assert torch.equal(prosac.sample(4, 32, 6, 0), uniform.sample(4, 32, 6, 0))
- model_p, mask_p = prosac(kp1, kp2)
- model_u, mask_u = uniform(kp1, kp2)
- assert torch.equal(model_p, model_u) and torch.equal(mask_p, mask_u)
+ samples = prosac.sample(4, 32, 6, 0)
+ assert samples[0].sort().values.tolist() == [0, 1, 2, 3]
+ assert samples.amax(dim=1).tolist() == [3, 4, 5, 6, 7, 8]
+ assert not torch.equal(samples, uniform.sample(4, 32, 6, 0))
@pytest.mark.parametrize(
"model_type, n, validated_type, validated_n",
[("fundamental_7pt", 6, "fundamental", 7), ("essential", 4, "homography", 3)],
)
- def test_wart_ransac_no_size_validation_7pt_essential_4872(
- self, model_type, n, validated_type, validated_n, device, dtype
- ):
+ def test_convention_ransac_size_validation_4872(self, model_type, n, validated_type, validated_n, device, dtype):
_cpu_only(device)
kp1, kp2 = _planar_matches(device, dtype)
# Too few correspondences for the validated model types raise kornia's ValueError before sampling.
with pytest.raises(ValueError):
RANSAC(validated_type, max_iter=1, batch_size=4, seed=0)(kp1[:validated_n], kp2[:validated_n])
- # #4872: fundamental_7pt and essential are not validated, and fail inside the sampler with a RuntimeError.
- # Once they are validated this raises ValueError instead.
- with pytest.raises(RuntimeError):
+ # fundamental_7pt and essential are validated the same way. #4872 skipped them, and they failed inside the
+ # sampler with a RuntimeError.
+ with pytest.raises(ValueError):
RANSAC(model_type, max_iter=1, batch_size=4, seed=0)(kp1[:n], kp2[:n])
+
+
+class TestRANSACScoringAndStopping(BaseTester):
+ @pytest.mark.parametrize("threshold", [0.5, 1.0, 2.0])
+ def test_msac_accepts_partial_consensus(self, device, dtype, threshold):
+ # A perfect 40% consensus must be accepted regardless of threshold units.
+ points = torch.arange(200, device=device, dtype=dtype).reshape(100, 2)
+ target = points.clone()
+ target[40:] += 100
+ identity = torch.eye(3, device=device, dtype=dtype)[None]
+ ransac = RANSAC("homography", inl_th=threshold, batch_size=1, max_iter=1, max_lo_iters=0, score_type="msac")
+ ransac.remove_bad_samples = lambda a, b: (a, b)
+ ransac.minimal_solver = lambda a, b, w: identity
+ model, mask = ransac(points, target)
+ self.assert_close(model, identity[0])
+ assert mask.shape == (100,)
+ assert mask.sum() == 40
+
+ @pytest.mark.parametrize("model_type,n", [("homography", 5), ("essential", 6), ("essential", 7)])
+ def test_keep_minimal_consensus_without_polishing(self, device, dtype, model_type, n):
+ # Acceptance needs one inlier beyond the minimal sample, not the eight-point polisher's point count.
+ points = torch.rand(n, 2, device=device, dtype=dtype)
+ matrix = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype)
+ if model_type == "homography":
+ matrix = torch.eye(3, device=device, dtype=dtype)
+ ransac = RANSAC(model_type, batch_size=1, max_iter=1)
+ ransac.remove_bad_samples = lambda a, b: (a, b)
+ ransac.minimal_solver = lambda a, b, w: matrix[None]
+ ransac.polisher_solver = lambda a, b, w: matrix[None]
+ model, mask = ransac(points, points)
+ assert model.abs().sum() > 0
+ assert mask.shape == (n,)
+ assert mask.all()
+
+ def test_invalid_models(self, device, dtype):
+ models = torch.eye(3, device=device, dtype=dtype).repeat(4, 1, 1)
+ models[0] = 0
+ models[1, 0, 0] = float("nan")
+ models[2, 0, 0] = float("inf")
+ valid = RANSAC("fundamental_7pt").remove_bad_models(models)
+ self.assert_close(valid, models[3:])
+
+ def test_msac_nonfinite_residual_is_outlier(self, device, dtype):
+ points = torch.zeros(10, 2, device=device, dtype=dtype)
+ candidates = torch.eye(3, device=device, dtype=dtype).repeat(2, 1, 1)
+ candidates[1, 0, 2] = 1
+ ransac = RANSAC(score_type="msac")
+ errors = torch.zeros(2, 10, device=device, dtype=dtype)
+ errors[0, 0] = float("nan")
+ ransac.error_fn = lambda a, b, m: errors
+ best, _, score, count = ransac.verify(points, points, candidates, 4.0)
+ self.assert_close(best, candidates[1])
+ assert math.isfinite(score)
+ assert count == 10
+
+ def test_stopping_uses_support_after_lo_and_checks_unchanged_best(self, device, dtype):
+ # LO increases support to 70/100. The MSAC score is intentionally different.
+ points = torch.rand(100, 2, device=device, dtype=dtype)
+ matrix = torch.eye(3, device=device, dtype=dtype)[None]
+ ransac = RANSAC("fundamental", batch_size=16, max_iter=10, max_lo_iters=1, score_type="msac")
+ sampled = []
+ ransac.minimal_solver = lambda a, b, w: sampled.append(1) or matrix
+ ransac.polisher_solver = lambda a, b, w: matrix
+ calls = []
+
+ def verify(a, b, models, threshold):
+ calls.append(1)
+ count = 70 if len(calls) == 2 else 50
+ mask = torch.arange(100, device=device) < count
+ return matrix[0], mask, float(count - 20), float(count)
+
+ ransac.verify = verify
+ ransac(points, points)
+ expected = math.ceil(RANSAC.max_samples_by_conf(70, 100, 8, 0.99) / 16)
+ assert len(sampled) == expected
+
+ def test_exact_minimal_support_confidence(self):
+ # Exactly four inliers among ten: success probability is 1 / C(10, 4).
+ expected = math.ceil(math.log1p(-0.99) / math.log1p(-1 / math.comb(10, 4)))
+ assert RANSAC.max_samples_by_conf(4, 10, 4, 0.99) == expected
+
+ @pytest.mark.parametrize("confidence,outliers,batches", [(0.99, 1, 1), (1.0, 1, 3), (0.99, 0, 1), (1.0, 0, 3)])
+ def test_unit_confidence_runs_full_budget(self, device, dtype, confidence, outliers, batches):
+ # 19 of 20 inliers: 0.99 confidence needs three minimal samples, i.e. one batch. With every
+ # point an inlier the bound is one sample, but confidence=1 must still run the whole budget.
+ points = torch.rand(20, 2, device=device, dtype=dtype)
+ target = points.clone()
+ target[:outliers] += 100
+ matrix = torch.eye(3, device=device, dtype=dtype)[None]
+ ransac = RANSAC("homography", batch_size=8, max_iter=3, max_lo_iters=0, confidence=confidence)
+ calls = []
+ ransac.remove_bad_samples = lambda a, b: (a, b)
+ ransac.minimal_solver = lambda a, b, w: calls.append(1) or matrix
+ ransac(points, target)
+ assert len(calls) == batches
+
+ def test_failure_mask_shape(self, device, dtype):
+ points = torch.zeros(10, 2, device=device, dtype=dtype)
+ ransac = RANSAC("fundamental", batch_size=2, max_iter=1)
+ ransac.minimal_solver = lambda a, b, w: torch.zeros(1, 3, 3, device=device, dtype=dtype)
+ _, mask = ransac(points, points)
+ assert mask.shape == (10,)
+ assert not mask.any()
+
+ @pytest.mark.parametrize("score_type", ["ransac", "msac"])
+ def test_under_supported_best_is_rejected(self, device, dtype, score_type):
+ # Four agreeing points are no more than a homography's minimal sample, which any sample fits.
+ points = torch.rand(10, 2, device=device, dtype=dtype)
+ target = points + 100
+ target[:4] = points[:4]
+ identity = torch.eye(3, device=device, dtype=dtype)[None]
+ ransac = RANSAC("homography", batch_size=1, max_iter=2, max_lo_iters=0, score_type=score_type)
+ ransac.remove_bad_samples = lambda a, b: (a, b)
+ ransac.minimal_solver = lambda a, b, w: identity
+ model, mask = ransac(points, target)
+ assert not model.any()
+ assert not mask.any()
+
+ def test_stopping_bound_follows_incumbent_support(self, device, dtype):
+ # Under MSAC a better-scoring model can have less support than the one it replaces. The
+ # stopping bound must then follow the new incumbent, not the larger support it displaced.
+ points = torch.rand(100, 2, device=device, dtype=dtype)
+ matrix = torch.eye(3, device=device, dtype=dtype)[None]
+ ransac = RANSAC("fundamental", batch_size=1, max_iter=50, max_lo_iters=0, score_type="msac")
+ sampled = []
+ ransac.minimal_solver = lambda a, b, w: sampled.append(1) or matrix
+ results = {1: (1.0, 95), 2: (2.0, 60)}
+
+ def verify(a, b, models, threshold):
+ score, count = results.get(len(sampled), (0.0, 50))
+ return matrix[0], torch.arange(100, device=device) < count, score, float(count)
+
+ ransac.verify = verify
+ ransac(points, points)
+ assert RANSAC.max_samples_by_conf(95, 100, 8, 0.99) < 50 < RANSAC.max_samples_by_conf(60, 100, 8, 0.99)
+ assert len(sampled) == 50
+
+ @pytest.mark.parametrize("lo_sample_size,expected_calls", [(None, 1), (8, 2)])
+ def test_invalid_refit_is_not_repeated(self, device, dtype, lo_sample_size, expected_calls):
+ # A failed full-inlier refit would fail identically on the unchanged inliers. A failed subset
+ # batch still leaves the full refit to try.
+ points = torch.rand(20, 2, device=device, dtype=dtype)
+ identity = torch.eye(3, device=device, dtype=dtype)[None]
+ ransac = RANSAC("homography", batch_size=1, max_iter=1, max_lo_iters=5, lo_sample_size=lo_sample_size, seed=0)
+ ransac.remove_bad_samples = lambda a, b: (a, b)
+ ransac.minimal_solver = lambda a, b, w: identity
+ calls = []
+ ransac.polisher_solver = lambda a, b, w: (
+ calls.append(1) or torch.full_like(identity, float("nan")).expand(len(a), 3, 3)
+ )
+ model, mask = ransac(points, points)
+ self.assert_close(model, identity[0])
+ assert mask.all()
+ assert len(calls) == expected_calls
+
+ @pytest.mark.parametrize("lo_sample_size", [None, 8])
+ def test_full_inlier_refit_wins_ties(self, device, dtype, lo_sample_size):
+ # RANSAC scoring ties whenever the refit keeps the same support; the least-squares refit
+ # must still replace the minimal-sample model, which is only as precise as its sample.
+ points = torch.rand(20, 2, device=device, dtype=dtype)
+ minimal = torch.eye(3, device=device, dtype=dtype)[None]
+ refit = 2 * minimal
+ ransac = RANSAC("homography", batch_size=1, max_iter=1, max_lo_iters=3, lo_sample_size=lo_sample_size, seed=0)
+ ransac.remove_bad_samples = lambda a, b: (a, b)
+ ransac.minimal_solver = lambda a, b, w: minimal
+ polished = []
+ ransac.polisher_solver = lambda a, b, w: polished.append(1) or refit.expand(len(a), 3, 3)
+ mask = torch.ones(20, device=device, dtype=torch.bool)
+ ransac.verify = lambda a, b, m, t: (m[0].clone(), mask, 20.0, 20.0)
+ model, _ = ransac(points, points)
+ self.assert_close(model, refit[0])
+ # A tie ends local optimization: it cannot increase support any further.
+ assert len(polished) == (2 if lo_sample_size else 1)
+
+
+class TestRANSACSampling(BaseTester):
+ def test_prosac_growth_per_draw(self, device):
+ # Chum & Matas (CVPR 2005), eqs. 3--6; m=4, N=10, T_N=64.
+ ransac = RANSAC(batch_size=16, max_iter=4, prosac_sampling=True, seed=7)
+ samples = torch.cat([ransac.sample(4, 10, 16, i, device) for i in range(4)])
+ ends = [1, 3, 7, 14, 25, 43, 69]
+ expected = torch.tensor(
+ [next(n + 3 for n, end in enumerate(ends) if t <= end) for t in range(1, 65)], device=device
+ )
+ assert torch.equal(samples.amax(1), expected)
+ assert torch.all(samples.sort(1).values.diff(dim=1) > 0)
+ # A different batch partition must have the same prefix schedule at equal budget.
+ other = RANSAC(batch_size=32, max_iter=2, prosac_sampling=True, seed=7)
+ larger = torch.cat([other.sample(4, 10, 32, i, device) for i in range(2)])
+ assert torch.equal(larger.amax(1), expected)
+
+ def test_sample_accepts_device_string(self, device):
+ ransac = RANSAC(seed=0)
+ by_name = ransac.sample(4, 10, 3, 0, str(device))
+ assert by_name.device.type == device.type
+ assert torch.equal(by_name, ransac.sample(4, 10, 3, 0, device))
+
+ def test_prosac_eventually_uniform(self, device):
+ ransac = RANSAC(batch_size=128, max_iter=1, prosac_sampling=True, seed=3)
+ samples = ransac.sample(4, 10, 128, 10, device)
+ assert torch.any(samples.amax(1) < 9)
+ assert torch.all(samples.sort(1).values.diff(dim=1) > 0)
+
+ @pytest.mark.parametrize("population", [4, 10, 1000])
+ def test_uniform_without_replacement(self, device, population):
+ ransac = RANSAC(seed=0)
+ samples = ransac.sample(4, population, 10000, 0, device)
+ assert samples.min() >= 0
+ assert samples.max() < population
+ assert torch.all(samples.sort(1).values.diff(dim=1) > 0)
+ # Check marginal inclusion, independent of ordering within each sampled set.
+ counts = torch.bincount(samples.flatten(), minlength=population).float()
+ expected = 40000 / population
+ assert (counts - expected).abs().max() < 7 * math.sqrt(expected)
+
+ def test_prosac_does_not_use_uniform_confidence(self, device, dtype):
+ points = torch.rand(20, 2, device=device, dtype=dtype)
+ matrix = torch.eye(3, device=device, dtype=dtype)[None]
+ ransac = RANSAC("homography", batch_size=8, max_iter=3, max_lo_iters=0, prosac_sampling=True)
+ calls = []
+ ransac.remove_bad_samples = lambda a, b: (a, b)
+ ransac.minimal_solver = lambda a, b, w: calls.append(1) or matrix
+ ransac(points, points)
+ assert len(calls) == 3
+
+
+class TestRANSACBoundedLO(BaseTester):
+ def test_subset_refits_and_final_full_refit(self, device, dtype):
+ points = torch.rand(100, 2, device=device, dtype=dtype)
+ matrix = torch.eye(3, device=device, dtype=dtype)[None]
+ ransac = RANSAC("fundamental", batch_size=1, max_iter=1, max_lo_iters=3, lo_sample_size=16, seed=0)
+ ransac.minimal_solver = lambda a, b, w: matrix
+ sizes = []
+ ransac.polisher_solver = lambda a, b, w: sizes.append(a.shape[:2]) or matrix
+ mask = torch.ones(100, device=device, dtype=torch.bool)
+ ransac.verify = lambda a, b, m, t: (matrix[0], mask, 100.0, 100.0)
+ ransac(points, points)
+ assert sizes == [(3, 16), (1, 100)]
+
+ def test_bad_subset_does_not_replace_best(self, device, dtype):
+ points = torch.rand(40, 2, device=device, dtype=dtype)
+ identity = torch.eye(3, device=device, dtype=dtype)[None]
+ wrong = identity.clone()
+ wrong[:, 0, 2] = 100
+ ransac = RANSAC(
+ "homography", batch_size=1, max_iter=1, max_lo_iters=2, lo_sample_size=8, score_type="msac", seed=3
+ )
+ ransac.minimal_solver = lambda a, b, w: identity
+ ransac.remove_bad_samples = lambda a, b: (a, b)
+ ransac.polisher_solver = lambda a, b, w: wrong
+ model, mask = ransac(points, points)
+ self.assert_close(model, identity[0])
+ assert mask.all()
+
+ def test_seeded_subsets_reproducible(self, device, dtype):
+ points = torch.rand(50, 2, device=device, dtype=dtype)
+ identity = torch.eye(3, device=device, dtype=dtype)[None]
+ ransac = RANSAC("homography", batch_size=1, max_iter=1, max_lo_iters=2, lo_sample_size=8, seed=13)
+ ransac.minimal_solver = lambda a, b, w: identity
+ ransac.remove_bad_samples = lambda a, b: (a, b)
+ subsets = []
+ ransac.polisher_solver = lambda a, b, w: subsets.append(a.clone()) or identity
+ ransac(points, points)
+ ransac(points, points)
+ self.assert_close(subsets[0], subsets[2])
+ self.assert_close(subsets[1], subsets[3])
+ assert not torch.equal(subsets[0][0], subsets[0][1])
+
+
+class TestRANSACValidation(BaseTester):
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"inl_th": 0.0},
+ {"inl_th": float("nan")},
+ {"batch_size": 0},
+ {"max_iter": 0},
+ {"max_lo_iters": -1},
+ {"score_type": "magsac"},
+ {"confidence": 1.5},
+ {"confidence": 0.0},
+ {"lo_sample_size": 3},
+ ],
+ )
+ def test_invalid_configuration(self, kwargs):
+ with pytest.raises(ValueError):
+ RANSAC(**kwargs)
+
+ @pytest.mark.parametrize("model", ["fundamental_7pt", "essential"])
+ def test_mismatched_correspondences(self, device, dtype, model):
+ points = torch.zeros(9, 2, device=device, dtype=dtype)
+ with pytest.raises(ValueError):
+ RANSAC(model).validate_inputs(points, points[:8])
+
+ @staticmethod
+ def _projection_case(device, dtype, extra_exact_points):
+ # Every correspondence fits this rank-two F exactly. Its projection onto the essential manifold
+ # fits only the points with y = 0 and moves the others to a squared Sampson error of 0.5.
+ points1 = torch.tensor(
+ [[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0], [2.0, 1.0], [2.0, 0.0], [3.0, 1.0], [3.0, 0.0]]
+ + [[4.0 + i, 0.0] for i in range(extra_exact_points)],
+ device=device,
+ dtype=dtype,
+ )
+ points2 = points1.clone()
+ points2[:, 1] *= 2
+ candidate = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 2.0, 0.0]], device=device, dtype=dtype)[None]
+ ransac = RANSAC("essential", inl_th=0.01, batch_size=1, max_iter=1, max_lo_iters=0)
+ ransac.minimal_solver = lambda a, b, w: candidate
+ return ransac, points1, points2
+
+ def test_essential_mask_matches_projected_output(self, device, dtype):
+ ransac, points1, points2 = self._projection_case(device, dtype, extra_exact_points=2)
+ model, mask = ransac(points1, points2)
+ expected = sampson_epipolar_distance(points1[None], points2[None], model[None])[0] <= 0.01**2
+ assert model.abs().amax() > 0
+ assert torch.equal(mask, expected)
+ assert torch.equal(mask, points1[:, 1] == 0)
+
+ def test_essential_projection_below_minimal_support_fails(self, device, dtype):
+ # Four of the eight points survive the projection, fewer than the five-point minimal sample.
+ ransac, points1, points2 = self._projection_case(device, dtype, extra_exact_points=0)
+ model, mask = ransac(points1, points2)
+ assert not model.any()
+ assert mask.shape == (8,)
+ assert not mask.any()
+
+
+class TestRANSACMSACSelection(BaseTester):
+ def test_skip_candidates_with_insufficient_support(self, device, dtype):
+ points = torch.zeros(10, 2, device=device, dtype=dtype)
+ candidates = torch.eye(3, device=device, dtype=dtype).repeat(2, 1, 1)
+ candidates[1, 0, 2] = 1
+ errors = torch.full((2, 10), 100.0, device=device, dtype=dtype)
+ # Candidate 0 fits only a minimal sample's worth of points, exactly; candidate 1 has one more inlier.
+ errors[0, :4] = 0.0
+ errors[1, :5] = 2.0
+ ransac = RANSAC("homography", score_type="msac")
+ ransac.error_fn = lambda a, b, m: errors
+ model, _, _, count = ransac.verify(points, points, candidates, 4.0)
+ self.assert_close(model, candidates[1])
+ assert count == 5
+
+ def test_msac_score_accumulates_in_float32(self, device):
+ # 999 is not a bfloat16 value: summing the per-point scores in bfloat16 rounds it to 1000.
+ points = torch.zeros(999, 2, device=device, dtype=torch.bfloat16)
+ model = torch.eye(3, device=device, dtype=torch.bfloat16)[None]
+ ransac = RANSAC("homography", score_type="msac")
+ ransac.error_fn = lambda a, b, m: torch.zeros(1, 999, device=device, dtype=torch.bfloat16)
+ _, _, score, count = ransac.verify(points, points, model, 4.0)
+ assert score == 999.0
+ assert count == 999
+
+ @pytest.mark.parametrize("threshold", [0.0, -1.0, float("nan"), float("inf")])
+ def test_invalid_verify_threshold(self, device, dtype, threshold):
+ points = torch.zeros(4, 2, device=device, dtype=dtype)
+ with pytest.raises(ValueError):
+ RANSAC(score_type="msac").verify(points, points, torch.eye(3, device=device, dtype=dtype)[None], threshold)
+
+
+class TestRANSACLineScoring(BaseTester):
+ def test_squared_distance_independent_of_segment_length(self, device, dtype):
+ # Horizontal segments all displaced vertically by 3px: squared distance = 9,
+ # regardless of whether the segment is 1px or 10px long.
+ source = torch.tensor(
+ [[[[0.0, 0.0], [1.0, 0.0]], [[0.0, 0.0], [3.0, 0.0]], [[0.0, 0.0], [5.0, 0.0]], [[0.0, 0.0], [10.0, 0.0]]]],
+ device=device,
+ dtype=dtype,
+ )
+ target = source.clone()
+ target[..., 1] += 3
+ estimator = RANSAC("homography_from_linesegments", score_type="msac")
+ errors = estimator.error_fn(source, target, torch.eye(3, device=device, dtype=dtype)[None])
+ self.assert_close(errors, torch.full((1, 4), 9.0, device=device, dtype=dtype))
+
+ def test_zero_length_target_is_outlier(self, device, dtype):
+ source = torch.tensor([[[[0.0, 0.0], [1.0, 0.0]]]], device=device, dtype=dtype)
+ target = torch.zeros_like(source)
+ estimator = RANSAC("homography_from_linesegments")
+ errors = estimator.error_fn(source, target, torch.eye(3, device=device, dtype=dtype)[None])
+ assert torch.isinf(errors).all()
+
+
+class TestRANSACEssentialInvalidPolisher(BaseTester):
+ @pytest.mark.parametrize("lo_sample_size", [None, 8])
+ def test_discard_nonfinite_polisher_before_projection(self, device, dtype, lo_sample_size):
+ points = torch.rand(20, 2, device=device, dtype=dtype)
+ valid = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype)[None]
+ candidates = torch.cat([torch.full_like(valid, float("nan")), valid])
+ estimator = RANSAC("essential", batch_size=1, max_iter=1, max_lo_iters=2, lo_sample_size=lo_sample_size, seed=0)
+ estimator.minimal_solver = lambda a, b, w: valid
+ estimator.polisher_solver = lambda a, b, w: candidates
+ model, mask = estimator(points, points)
+ assert torch.isfinite(model).all()
+ assert mask.all()