Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

RANSAC: MSAC and 32-inlier subset LO by default; benchmark the defaults against PoseLib (#5002)

Dmytro Mishkin0fbed00b059d
diff --git a/benchmarks/common.py b/benchmarks/common.py
index e92897c06..559efeb38 100644
--- a/benchmarks/common.py
+++ b/benchmarks/common.py
@@ -151,6 +151,7 @@ def run_metadata(device: torch.device) -> dict[str, Any]:
"torch_num_threads": torch.get_num_threads(),
"opencv_num_threads": opencv_num_threads,
"opencv": _optional_version("cv2"),
+ "poselib": _optional_version("poselib"),
"torchvision": _optional_version("torchvision"),
"numpy": _optional_version("numpy"),
"albumentations": _optional_version("albumentations"),
diff --git a/benchmarks/geometry/ransac.py b/benchmarks/geometry/ransac.py
index 67f2c1664..611b654a7 100644
--- a/benchmarks/geometry/ransac.py
+++ b/benchmarks/geometry/ransac.py
@@ -20,6 +20,8 @@
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.
+``sweep`` runs kornia at its class defaults with and without PROSAC, and the optional
+OpenCV (``cv2``) and PoseLib (``poselib``) reference estimators when installed.
python benchmarks/geometry/ransac.py prepare --data-root ../imc2021-simple/data/phototourism \
--scenes sacre_coeur,reichstag --cache sift=raw_matches.h5 \
@@ -406,16 +408,91 @@ def load_ransac_module(path: Path) -> Any:
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"},
-}
+# Kornia runs at the class defaults, with and without PROSAC: the defaults are the benchmark's subject.
+SWEEP_KORNIA: dict[str, dict[str, Any]] = {"default": {}, "prosac": {"prosac_sampling": True}}
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")
+SWEEP_POSELIB = {"poselib": False, "poselib-prosac": True} # progressive_sampling
+# PoseLib's default success probability, kept as in imc2021-simple; kornia and OpenCV use --confidence.
+POSELIB_SUCCESS_PROB = 0.9999
+
+
+def base_methods(module: Any, methods: list[str]) -> list[str]:
+ """The requested kornia configurations another revision implements, at its own defaults.
+
+ Revisions before #4902 accept ``prosac_sampling`` but ignore it; the PROSAC growth schedule
+ (``_prosac_growth``) arrived with the sampler, so its presence tells real support apart.
+ """
+ prosac = hasattr(module, "_prosac_growth")
+ return [m for m in methods if prosac or not SWEEP_KORNIA[m].get("prosac_sampling")]
+
+
+def reference_calls(
+ args: argparse.Namespace,
+ backends: dict[str, Any],
+ thresholds: list[float],
+ points1: Any,
+ points2: Any,
+ ranked: bool,
+) -> list[tuple[dict[str, Any], Any]]:
+ """One timed call per OpenCV/PoseLib method, iteration budget and threshold for a pair."""
+ cv2, poselib = backends.get("cv2"), backends.get("poselib")
+ opencv_methods = [m for m in args.opencv.split(",") if m] if cv2 is not None else []
+ poselib_methods = [m for m in args.poselib.split(",") if m] if poselib is not None else []
+ calls: list[tuple[dict[str, Any], Any]] = []
+ 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))
+ for name, iters, threshold in itertools.product(
+ poselib_methods, [int(x) for x in args.poselib_iters.split(",")], thresholds
+ ):
+ if SWEEP_POSELIB[name] and not ranked:
+ continue
+
+ def estimate_poselib(
+ prosac: bool = SWEEP_POSELIB[name],
+ iters: int = iters,
+ th: float = threshold,
+ p1: Any = points1,
+ p2: Any = points2,
+ ) -> Any:
+ # PoseLib's own stopping rule: ``max_iterations`` is the budget, the default
+ # ``min_iterations`` (1000) and ``success_prob`` 0.9999 as in imc2021-simple.
+ options = {"max_epipolar_error": th, "progressive_sampling": prosac, "max_iterations": iters}
+ options.update(success_prob=POSELIB_SUCCESS_PROB, seed=args.seed)
+ matrix, info = poselib.estimate_fundamental(p1, p2, options, {})
+ return matrix, info["inliers"] # a Python list; converted after the timer stops
+
+ config = {"method": f"poselib {name}", "device": "cpu", "batch": None}
+ config.update(sample_budget=iters, threshold_px=threshold)
+ calls.append((config, estimate_poselib))
+ return calls
+
+
+def optional_backends(args: argparse.Namespace) -> dict[str, Any]:
+ """Import the reference libraries whose methods were requested; a missing one is reported and skipped."""
+ backends: dict[str, Any] = {}
+ for module, requested, label in (("cv2", args.opencv, "OpenCV"), ("poselib", args.poselib, "PoseLib")):
+ if any(requested.split(",")):
+ backend, reason = optional_import(module)
+ if backend is None:
+ print(f"# NOTE: skipping {label} methods ({reason})")
+ else:
+ backends[module] = backend
+ return backends
def sweep(args: argparse.Namespace) -> None:
@@ -430,21 +507,16 @@ def sweep(args: argparse.Namespace) -> None:
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))
+ device, _, _ = setup_run(args, opencv=any(args.opencv.split(",")))
+ backends = optional_backends(args)
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]:
+ base = load_ransac_module(args.base_source)
+ supported = base_methods(base, kornia_methods)
+ if skipped := [m for m in kornia_methods if m not in supported]:
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 = []
+ estimators.append(("kornia-base", base.RANSAC, supported))
sync = torch.cuda.synchronize if device.type == "cuda" else (lambda: None)
thresholds = [float(x) for x in args.thresholds.split(",")]
meta = start_run(
@@ -460,15 +532,21 @@ def sweep(args: argparse.Namespace) -> None:
base_ransac_source_sha256=digest(args.base_source) if args.base_source is not None else None,
thresholds_px=thresholds,
confidence=args.confidence,
+ stopping_probability={"kornia": args.confidence, "opencv": args.confidence, "poselib": POSELIB_SUCCESS_PROB},
+ poselib=getattr(backends.get("poselib"), "__version__", None),
seed=args.seed,
)
rows = []
+ warmed: set[tuple[Any, ...]] = set()
with np.load(args.npz, allow_pickle=False) as data, torch.inference_mode():
- for pair_index, key in enumerate(pair_keys(data, args)):
+ 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))
+ ranked = field in data
+ if not ranked: # PROSAC needs a best-first order; the export order is not one
+ print(f"# NOTE: {key} has no match score or ratio: PROSAC configurations are skipped")
+ order = np.argsort(data[field].reshape(-1), kind="stable") if ranked 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)
@@ -476,6 +554,8 @@ def sweep(args: argparse.Namespace) -> None:
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):
+ if SWEEP_KORNIA[name].get("prosac_sampling") and not ranked:
+ continue
batch = min(args.batch, budget)
estimator = ransac_class(
model_type="fundamental",
@@ -490,28 +570,13 @@ def sweep(args: argparse.Namespace) -> None:
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()
+ calls.extend(reference_calls(args, backends, thresholds, points1, points2, ranked))
for config, call in calls:
+ signature = (config["method"], config["sample_budget"], config["threshold_px"])
+ if signature not in warmed: # first call per configuration: lazy initialization and
+ with contextlib.suppress(Exception): # solver handles stay out of the timings
+ call()
+ warmed.add(signature)
error = None
sync()
start = time.perf_counter()
@@ -552,17 +617,22 @@ def sweep(args: argparse.Namespace) -> None:
# 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),
+ "kornia default": ("defaults", "kornia", "#2a78d6", "-", "o", True),
+ "kornia prosac": ("defaults + PROSAC", "kornia", "#4a3aa7", "-", "^", True),
+ "kornia-base default": ("defaults", "kornia-base", "#2a78d6", "--", "o", False),
+ "kornia-base prosac": ("defaults + PROSAC", "kornia-base", "#4a3aa7", "--", "^", False),
+ "poselib poselib": ("PoseLib", "poselib", "#1f1f1e", ":", "s", True),
+ "poselib poselib-prosac": ("PoseLib + PROSAC", "poselib", "#5f5e5a", "-.", "D", True),
"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)"}
+PLOT_GROUPS = {
+ "kornia": "kornia, this PR",
+ "kornia-base": "kornia, main before this PR",
+ "poselib": "PoseLib (CPU)",
+ "opencv": "OpenCV (CPU)",
+}
PAGE, INK, MUTED, GRID = "#fcfcfb", "#0b0b0b", "#52514e", "#e4e3df"
@@ -684,9 +754,7 @@ def plot(args: argparse.Namespace) -> None:
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()
- )
+ if any(device == d and any(m.startswith("kornia") for m in methods) for (_, device), methods in curves.items())
]
figure, axes = plt.subplots(
len(devices),
@@ -700,8 +768,8 @@ def plot(args: argparse.Namespace) -> None:
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")})
+ if device != "cpu": # the reference libraries run on the CPU; repeat them in every row
+ lines.update({m: p for m, p in curves.get((feature, "cpu"), {}).items() if not m.startswith("kornia")})
for method in PLOT_SERIES:
if method in lines:
points = sorted(lines[method], key=lambda p: p["mean_time_ms"])
@@ -718,8 +786,8 @@ def plot(args: argparse.Namespace) -> None:
"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."
+ if "opencv" in handles or "poselib" in handles:
+ note += " OpenCV and PoseLib (iteration budgets) run on the CPU and are 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)
@@ -862,10 +930,12 @@ def main() -> None:
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("--poselib", default=",".join(SWEEP_POSELIB), help=f"subset of {','.join(SWEEP_POSELIB)}")
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("--poselib-iters", default="10,25,100,400,1600,6400,25600", help="PoseLib max_iterations")
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)
@@ -934,8 +1004,9 @@ def main() -> None:
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)
+ unknown |= set(args.poselib.split(",")) - set(SWEEP_POSELIB)
if unknown - {""}:
- parser.error(f"unknown --kornia or --opencv method: {sorted(unknown - {''})}")
+ parser.error(f"unknown --kornia, --opencv or --poselib 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}
diff --git a/changelog.d/5002.breaking.md b/changelog.d/5002.breaking.md
new file mode 100644
index 000000000..0dccf96a7
--- /dev/null
+++ b/changelog.d/5002.breaking.md
@@ -0,0 +1 @@
+`RANSAC` defaults changed: `score_type` is now `"msac"` (was `"ransac"`) and `lo_sample_size` is now `32` (was `None`, iterative full-inlier refits). Candidates are now ranked by truncated squared residuals instead of inlier count, and local optimization fits `max_lo_iters` random 32-inlier subsets before one full-inlier refit whenever the consensus set has more than 32 inliers. Estimates for a given seed change accordingly; pass `score_type="ransac"` and `lo_sample_size=None` to keep the previous behavior. The RANSAC time-mAA benchmark now compares the class defaults, with and without PROSAC, against PoseLib and OpenCV, and skips PROSAC configurations on pairs without a match ranking.
diff --git a/docs/source/geometry.ransac.rst b/docs/source/geometry.ransac.rst
index 74002da60..641703861 100644
--- a/docs/source/geometry.ransac.rst
+++ b/docs/source/geometry.ransac.rst
@@ -34,9 +34,10 @@ hypotheses for homographies and 128 to 512 for the epipolar models, fewer for
more correspondences, which lets early stopping pay off. An integer
``batch_size`` fixes the batch on every device.
-``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.
+The default ``score_type="msac"`` minimizes the sum of squared residuals
+truncated at ``inl_th ** 2``; ``"ransac"`` counts inliers instead. 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
@@ -83,7 +84,7 @@ model PROSAC certifies first may fit them well and the pose poorly. Prefer
uniform sampling there, or run PROSAC with ``confidence=1`` when the extra
draws are affordable.
-By default, local optimization repeatedly refits all current inliers. For the
+Local optimization refits the incumbent on its inliers. For the
homography models the refit is the iteratively re-weighted least squares of
:func:`~kornia.geometry.homography.find_homography_dlt_iterated`, whose Gaussian
weights use ``inl_th`` as their standard deviation, so a correspondence at the
@@ -92,15 +93,17 @@ 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
+Set ``max_lo_iters=0`` to disable it. By default, ``lo_sample_size=32`` caps each
+randomized non-minimal refit: ``max_lo_iters`` independent 32-inlier 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, which ``lo_sample_size=None`` selects for every consensus set. 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.
+On PhotoTourism fundamental matrices the subset refits match or beat full-inlier
+refitting at a lower cost on both CPU and CUDA.
.. autoclass:: RANSAC
:members: forward, resolve_batch_size
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.py
index 90b390271..9d9683996 100644
--- a/kornia/geometry/ransac.py
+++ b/kornia/geometry/ransac.py
@@ -73,8 +73,10 @@ class RANSAC(nn.Module):
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.
+ - ``score_type="msac"`` (the default) 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.
+ - Local optimization defaults to ``lo_sample_size=32``: ``max_lo_iters`` randomized refits on 32-inlier
+ subsets followed by one full-inlier refit; ``lo_sample_size=None`` refits all inliers iteratively.
- ``prosac_sampling=True`` expects correspondences sorted best-first and stops with PROSAC's
termination-length test; ``confidence=1`` runs the whole ``batch_size * max_iter`` budget.
- A seeded call uses a private generator and leaves torch's global RNG state unchanged; ``seed=None``
@@ -94,13 +96,16 @@ class RANSAC(nn.Module):
seven- and five-point solvers can return multiple models per sample.
confidence: 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.
+ score_type: "msac" (default) for truncated squared residuals, or "ransac" for support count.
prosac_sampling: use PROSAC sampling on best-first ordered correspondences. The growth schedule
advances per sampled set within each batch; stopping tests the incumbent's support within ranked
- prefixes (Chum and Matas, 2005, section 2.2) as well as within the whole set.
+ prefixes (Chum and Matas, 2005, section 2.2) as well as within the whole set. It pays off when the
+ ranking tracks inlier-ness and the inlier ratio is low (ratio-tested SIFT). On learned matches with
+ 85% or more inliers it can certify a model fitted to a spatially clustered top-ranked prefix after
+ one batch and score below uniform sampling; use uniform sampling or ``confidence=1`` there.
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.
+ lo_sample_size: inlier-subset size for a batch of ``max_lo_iters`` randomized local refits followed
+ by a full-inlier refit (default 32). None uses iterative full-inlier refitting.
max_samples: optional budget of minimal samples that overrides the one implied by ``batch_size`` and
``max_iter``; the last batch is truncated to it.
@@ -114,10 +119,10 @@ class RANSAC(nn.Module):
max_iter: int = 10,
confidence: float = 0.99,
max_lo_iters: int = 5,
- score_type: str = "ransac",
+ score_type: str = "msac",
prosac_sampling: bool = False,
seed: Optional[int] = None,
- lo_sample_size: Optional[int] = None,
+ lo_sample_size: Optional[int] = 32,
max_samples: Optional[int] = None,
) -> None:
"""Initialize the RANSAC estimator.
@@ -134,12 +139,12 @@ class RANSAC(nn.Module):
(``2048 * max_iter`` with ``batch_size="auto"``) unless ``max_samples`` is given.
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".
+ score_type: scoring method to use: "msac" (default) or "ransac".
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.
Stops when a ranked prefix, or the whole set, certifies the incumbent with ``confidence``.
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.
+ lo_sample_size: cap on the number of inliers used by each randomized local refit (default 32).
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.
diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.py
index 354d4ea22..a93ae670b 100644
--- a/tests/geometry/test_ransac.py
+++ b/tests/geometry/test_ransac.py
@@ -463,8 +463,11 @@ class TestRANSACSeed:
# 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)
+ # Under RANSAC scoring every all-inlier sample ties and the first one drawn wins, so the
+ # result follows the seed; the MSAC optimum over an exhaustive draw is the same for any seed.
+ common = {"inl_th": 2.0, "max_iter": 5, "max_lo_iters": 0, "score_type": "ransac"}
+ ransac_a = RANSAC("homography", seed=1, **common).to(device=device, dtype=dtype)
+ ransac_b = RANSAC("homography", seed=2, **common).to(device=device, dtype=dtype)
H_a, _ = ransac_a(points1, points2)
H_b, _ = ransac_b(points1, points2)
@@ -1190,6 +1193,20 @@ class TestRANSACSampling(BaseTester):
assert calls[1] > 1
+class TestRANSACDefaults(BaseTester):
+ def test_defaults_are_msac_and_bounded_lo(self):
+ ransac = RANSAC("fundamental")
+ assert ransac.score_type == "msac"
+ assert ransac.lo_sample_size == 32
+ assert ransac.max_lo_iters == 5
+ assert not ransac.prosac_sampling
+
+ def test_legacy_configuration_is_still_available(self):
+ ransac = RANSAC("fundamental", score_type="ransac", lo_sample_size=None)
+ assert ransac.score_type == "ransac"
+ assert ransac.lo_sample_size is None
+
+
class TestRANSACAutoBatch(BaseTester):
def test_default_is_auto_with_the_historical_budget(self):
ransac = RANSAC("homography")