Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(geometry): add shared affine solver and affine RANSAC (#5940)

Dmytro Mishkin4863aed8aa75
diff --git a/changelog.d/5940.added.md b/changelog.d/5940.added.md
new file mode 100644
index 000000000..c2c1333cb
--- /dev/null
+++ b/changelog.d/5940.added.md
@@ -0,0 +1 @@
+Add weighted `kornia.geometry.find_affine` estimation and `RANSAC(model_type="affine")` for full 2D affine transforms. AdaLAM shares the linear solver while retaining its seed-constrained neighborhood RANSAC. Affine fitting and scoring retain at least float32 arithmetic under autocast.
diff --git a/docs/source/geometry.ransac.rst b/docs/source/geometry.ransac.rst
index a93a6a86f..8b698b10a 100644
--- a/docs/source/geometry.ransac.rst
+++ b/docs/source/geometry.ransac.rst
@@ -6,7 +6,39 @@ kornia.geometry.ransac
.. currentmodule:: kornia.geometry.ransac
-Robust model fitting with RANSAC (Random Sample Consensus), used to estimate homographies, fundamental and essential matrices from noisy correspondences.
+Robust model fitting with RANSAC (Random Sample Consensus), used to estimate affine transforms, homographies, fundamental and essential matrices from noisy correspondences.
+
+Affine transforms
+-----------------
+
+``model_type="affine"`` estimates a full 2D affine transform, including translation,
+from three non-collinear source points. It returns a source-to-target ``(3, 3)``
+matrix with bottom row ``[0, 0, 1]`` and a boolean ``(N,)`` inlier mask.
+``inl_th`` is a Euclidean distance in the target points' units.
+Affine fitting and residual scoring compute in at least float32, even inside an
+autocast context, and the returned matrix retains the input dtype. At least four
+inliers are required to accept a model; otherwise the result is the all-zero
+failure matrix and an all-false mask.
+
+.. code-block:: python
+
+ from kornia.geometry import RANSAC
+
+ estimator = RANSAC("affine", inl_th=2.0, seed=0)
+ matrix, inliers = estimator(points1, points2)
+ warp_matrix = matrix[:2] # 2x3 form accepted by warp_affine after batching
+
+Affine estimation supports uniform and PROSAC sampling, MSAC and inlier-count
+scoring, and the existing ``local_optimization="dlt"`` loop. Here the refit is
+linear least squares with free translation using
+:func:`~kornia.geometry.solvers.find_affine`; ``"lm"``, ``compile=True`` and
+DEGENSAC are not supported. ``max_lo_iters=0`` disables local optimization.
+Like the other model types, each call estimates one model for one correspondence
+set; ``batch_size`` batches hypotheses, not independent problems.
+
+AdaLAM shares the linear fitting primitive but retains its specialized loop:
+its local 2x2 models are constrained by a matched seed, and its variable-size
+neighborhoods, sampling and confidence-based inlier selection are unchanged.
Batches, scores, and refinement
-------------------------------
@@ -61,8 +93,8 @@ 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 re-weights segments by the same distance.
-A model is accepted only with more inliers than its minimal sample (four
-correspondences for homographies, five for essential and seven or eight for
+A model is accepted only with more inliers than its minimal sample (three
+correspondences for affine transforms, four 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.
diff --git a/docs/source/geometry.solvers.rst b/docs/source/geometry.solvers.rst
index 6ce2ce2d4..21353fdf9 100644
--- a/docs/source/geometry.solvers.rst
+++ b/docs/source/geometry.solvers.rst
@@ -6,7 +6,18 @@ kornia.geometry.solvers
.. currentmodule:: kornia.geometry.solvers
-Polynomial and homogeneous linear solvers used by the geometric estimators.
+Affine, polynomial and homogeneous linear solvers used by the geometric estimators.
+
+Affine estimation
+-----------------
+
+:func:`find_affine` fits a full 2D affine transform from at least three
+non-collinear source points and their corresponding target points. It supports
+weighted least-squares fitting and returns a source-to-target homogeneous
+``(B, 3, 3)`` matrix. Use :class:`~kornia.geometry.ransac.RANSAC` with
+``model_type="affine"`` when the correspondences contain outliers.
+
+.. autofunction:: find_affine
Homogeneous Solvers
-------------------
diff --git a/kornia/feature/adalam/ransac.py b/kornia/feature/adalam/ransac.py
index 8c3bc1164..988c53588 100644
--- a/kornia/feature/adalam/ransac.py
+++ b/kornia/feature/adalam/ransac.py
@@ -19,7 +19,9 @@ from typing import Any, Dict, Tuple, Union
import torch
-from .utils import arange_sequence, batch_2x2_ellipse, batch_2x2_inv, draw_first_k_couples, piecewise_arange
+from kornia.geometry.solvers.affine import _find_affine_linear, _find_affine_linear_pair
+
+from .utils import arange_sequence, batch_2x2_ellipse, draw_first_k_couples, piecewise_arange
def stable_sort_residuals(residuals: torch.Tensor, ransidx: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
@@ -241,6 +243,30 @@ def sample_padded_inliers(
return padded_inlier_x, padded_inlier_y
+def _reset_large_scale_changes(
+ affinities: torch.Tensor, scale_rate_threshold: float
+) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Replace affinities whose scale change exceeds the threshold by the identity, as AdaLAM does.
+
+ Returns the affinities and the mask of those that pass. Rank-deficient (NaN) affinities fail the test but stay
+ NaN, so that :func:`_finite_residuals` gives them no support instead of the identity's.
+ """
+ eigenvals, _eigenvecs = batch_2x2_ellipse(affinities)
+ valid = (eigenvals[..., 1] >= 1 / scale_rate_threshold**2) & (eigenvals[..., 0] <= scale_rate_threshold**2)
+ reset = ~valid & ~eigenvals[..., 0].isnan()
+ identity = torch.eye(2, device=affinities.device, dtype=affinities.dtype)
+ return torch.where(reset[..., None, None], identity, affinities), valid
+
+
+def _finite_residuals(y_pred: torch.Tensor, ysamples: torch.Tensor) -> torch.Tensor:
+ """Residuals for the confidence sorter, which needs finite values.
+
+ A rank-deficient (NaN) fit gets residual 2: outside both normalized unit neighborhoods, it cannot provide
+ support at min_confidence > 1.
+ """
+ return torch.norm(y_pred - ysamples, dim=-1).nan_to_num(nan=2.0)
+
+
def ransac(
xsamples: torch.Tensor,
ysamples: torch.Tensor,
@@ -264,16 +290,14 @@ def ransac(
) # (niters, 2, numransacs, 2) -> (niters, numransacs, 2, 2)
sampled_y = torch.transpose(ysamples[rand_samples_abs], dim0=1, dim1=2)
- # minimal fit for sampled_x @ A^T = sampled_y
- affinities_fit = torch.transpose(batch_2x2_inv(sampled_x, check_dets=True) @ sampled_y, -1, -2)
+ # minimal fit for sampled_x @ A^T = sampled_y; rank-deficient pairs are NaN
+ affinities_fit = _find_affine_linear_pair(sampled_x, sampled_y)
valid_affinities = None
if not refit:
- eigenvals, _eigenvecs = batch_2x2_ellipse(affinities_fit)
- valid_affinities = (eigenvals[..., 1] >= 1 / DET_THR**2) & (eigenvals[..., 0] <= DET_THR**2)
- affinities_fit[~valid_affinities] = torch.eye(2, device=dv, dtype=affinities_fit.dtype)
+ affinities_fit, valid_affinities = _reset_large_scale_changes(affinities_fit, DET_THR)
y_pred = (affinities_fit[:, ransidx] @ xsamples.unsqueeze(-1)).squeeze(-1)
- residuals = torch.norm(y_pred - ysamples, dim=-1) # (niters, numsamples)
+ residuals = _finite_residuals(y_pred, ysamples) # (niters, numsamples)
inl_ransidx, inl_sampleidx, inl_counts, inl_iters, inl_confidence = _select_inliers(
residuals, xsamples, ysamples, ransidx, rdims, idxoffsets, affinities_fit, config, valid_affinities
@@ -297,21 +321,12 @@ def ransac(
xsamples, ysamples, inl_counts, inl_ransidx, inl_sampleidx, numransacs, dv
)
- # A @ pad_x.T = pad_y.T
- # A = pad_y.T @ pad_x @ (pad_x.T @ pad_x)^-1
- refit_affinity = (
- padded_inlier_y.transpose(-2, -1)
- @ padded_inlier_x
- @ batch_2x2_inv(padded_inlier_x.transpose(-2, -1) @ padded_inlier_x, check_dets=True)
- )
-
- # Filter out degenerate affinities with large scale changes
- eigenvals, _eigenvecs = batch_2x2_ellipse(refit_affinity)
- bad_ones = (eigenvals[..., 1] < 1 / DET_THR**2) | (eigenvals[..., 0] > DET_THR**2)
- refit_affinity[bad_ones] = torch.eye(2, device=dv, dtype=refit_affinity.dtype)
+ # Keep translation anchored at the seed; zero padding contributes no evidence.
+ refit_affinity = _find_affine_linear(padded_inlier_x, padded_inlier_y)
+ refit_affinity, valid_refits = _reset_large_scale_changes(refit_affinity, DET_THR)
y_pred = (refit_affinity[ransidx] @ xsamples.unsqueeze(-1)).squeeze(-1)
- residuals = torch.norm(y_pred - ysamples, dim=-1)
+ residuals = _finite_residuals(y_pred, ysamples)
inl_ransidx, inl_sampleidx, inl_counts, inl_iters, inl_confidence = _select_inliers(
residuals.unsqueeze(0),
@@ -322,6 +337,6 @@ def ransac(
idxoffsets,
refit_affinity.unsqueeze(0),
config,
- ~bad_ones.unsqueeze(0),
+ valid_refits.unsqueeze(0),
)
return inl_sampleidx, refit_affinity, inl_confidence, inl_counts
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.py
index 8b7b8d8a9..8cb11326b 100644
--- a/kornia/geometry/ransac.py
+++ b/kornia/geometry/ransac.py
@@ -63,6 +63,7 @@ from kornia.geometry.homography import (
sample_is_valid_for_homography,
sampson_homography_distance,
)
+from kornia.geometry.solvers.affine import _find_affine_triplet, find_affine
__all__ = ["RANSAC"]
@@ -80,6 +81,25 @@ _DEGENSAC_MODELS = ("fundamental", "fundamental_7pt")
_COMPILED_CPU_SCORE_RESIDUALS = 1 << 22
+def _affine_transfer_error(pts1: torch.Tensor, pts2: torch.Tensor, models: torch.Tensor) -> torch.Tensor:
+ """Squared one-way transfer errors ``(B, N)`` of affine models ``(B, 3, 3)`` on one set of correspondences.
+
+ ``pts1`` and ``pts2`` are ``(1, N, 2)``, as RANSAC scores them. This is :func:`oneway_transfer_error` without its
+ projective division and ``w' = 0`` guard, which an affine model's ``[0, 0, 1]`` bottom row makes unnecessary; like
+ that function, it computes in at least float32.
+ """
+ # Scoring needs the same precision as fitting, including inside mixed-precision pipelines.
+ with torch.autocast(device_type=pts1.device.type, enabled=False):
+ num_points = pts1.shape[-2]
+ dtype = torch.promote_types(torch.promote_types(pts1.dtype, pts2.dtype), models.dtype)
+ work = torch.promote_types(dtype, torch.float32)
+ x1 = pts1.reshape(num_points, 2).to(work)
+ x2 = pts2.reshape(num_points, 2).to(work)
+ linear = models[:, :2, :2].to(work).reshape(-1, 2)
+ projected = (linear @ x1.T).view(-1, 2, num_points) + models[:, :2, 2:].to(work)
+ return ((projected[:, 0] - x2[:, 0]).square() + (projected[:, 1] - x2[:, 1]).square()).to(dtype)
+
+
@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)."""
@@ -163,14 +183,16 @@ class RANSAC(nn.Module):
- ``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 candidate has more inliers than
- its minimal sample (four correspondences for homographies, five for ``"essential"``, seven for
- ``"fundamental"`` and ``"fundamental_7pt"``, eight for ``"fundamental_8pt"``).
+ its minimal sample (three correspondences for affine transforms, four for homographies,
+ five for ``"essential"``, seven for ``"fundamental"`` and ``"fundamental_7pt"``,
+ eight for ``"fundamental_8pt"``).
- ``"fundamental"`` draws seven-point samples, like ``"fundamental_7pt"``; ``"fundamental_8pt"`` draws
eight-point ones.
- ``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 the fundamental models 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``.
+ correspondence is an inlier when its one-way transfer error for ``"homography"`` or ``"affine"``,
+ its Sampson distance for the fundamental models 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"`` (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.
@@ -186,10 +208,12 @@ class RANSAC(nn.Module):
fundamental matrices are estimated on Hartley-normalized correspondences; essential matrices in the
caller's calibrated coordinates, which a normalization would take off the essential manifold, refined on
that manifold and returned with unit Frobenius norm.
- - ``local_optimization="dlt"``, the only choice for ``"homography_from_linesegments"``, refits each new best
+ - ``local_optimization="dlt"``, the only choice for ``"affine"`` and line segments, refits each new best
model from its inliers: with the default ``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.
+ iteratively. Affine models use a linear least-squares refit with free translation and return
+ a homogeneous matrix with bottom row ``[0, 0, 1]``; their minimal samples need three
+ non-collinear source points.
- ``degensac=True``, an opt-in for ``"fundamental"`` and ``"fundamental_7pt"`` with
``local_optimization="lm"``, runs DEGENSAC (Chum, Werner and Matas, CVPR 2005). Every seven-point model that
sets a new record among the raw scores is tested for an H-degenerate sample: five or more of its seven
@@ -218,7 +242,7 @@ class RANSAC(nn.Module):
one. PROSAC sampling and DEGENSAC are not supported.
Args:
- model_type: "homography", "fundamental", "fundamental_7pt", "fundamental_8pt", "essential", or
+ model_type: "affine", "homography", "fundamental", "fundamental_7pt", "fundamental_8pt", "essential", or
"homography_from_linesegments".
inl_th: positive inlier threshold, in the units given above.
batch_size: hypotheses generated and verified at once, or ``"auto"`` to pick the batches per call from
@@ -243,7 +267,7 @@ class RANSAC(nn.Module):
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.
local_optimization: ``"lm"`` or ``"dlt"``, as described above; None picks ``"lm"`` for homographies,
- fundamental and essential matrices and ``"dlt"`` for line segments.
+ fundamental and essential matrices and ``"dlt"`` for affine transforms and line segments.
refine_iters: Levenberg-Marquardt iterations of the final refinement with ``local_optimization="lm"``;
zero disables it.
compile: run ``local_optimization="lm"`` as one compiled graph, as described above.
@@ -274,7 +298,7 @@ class RANSAC(nn.Module):
"""Initialize the RANSAC estimator.
Args:
- model_type: type of model to estimate: "homography", "fundamental", "fundamental_7pt",
+ model_type: type of model to estimate: "affine", "homography", "fundamental", "fundamental_7pt",
"fundamental_8pt", "essential", "homography_from_linesegments".
inl_th: inlier threshold; the class docstring gives its unit per ``model_type``.
batch_size: number of generated samples at once, or ``"auto"`` (see :meth:`resolve_batch_size`).
@@ -305,6 +329,7 @@ class RANSAC(nn.Module):
"""
super().__init__()
self.supported_models = [
+ "affine",
"homography",
"fundamental",
"fundamental_7pt",
@@ -364,7 +389,20 @@ class RANSAC(nn.Module):
self.minimal_solver: Callable[..., torch.Tensor]
self.polisher_solver: Callable[..., torch.Tensor]
- if model_type == "homography":
+ self._set_model(model_type, inl_th)
+ 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 _set_model(self, model_type: str, inl_th: float) -> None:
+ """Select the model's residual, fitting methods and sample cardinalities."""
+ if model_type == "affine":
+ self.error_fn = _affine_transfer_error
+ # Three correspondences determine an affine map: minimal samples are solved directly.
+ self.minimal_solver = _find_affine_triplet
+ self.polisher_solver = find_affine
+ self.minimal_sample_size = 3
+ self.polisher_sample_size = 3
+ elif model_type == "homography":
self.error_fn = oneway_transfer_error
self.minimal_solver = find_homography_dlt
# The polisher's Gaussian re-weighting uses the inlier threshold as its standard deviation.
@@ -398,8 +436,6 @@ 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,
@@ -494,15 +530,17 @@ class RANSAC(nn.Module):
def resolve_batch_size(self, num_tc: int, device: torch.device) -> int:
"""Return the batch size of a ``local_optimization="dlt"`` call: the configured one, or the ``"auto"`` choice.
- On CUDA and MPS a homography batch costs about the same from a few hundred up to 8192 hypotheses
- (the four-point solve is launch-bound), so the whole :attr:`sample_budget` is drawn in batches of
- up to 8192; the epipolar solvers are compute-bound past 2048 hypotheses, so their batches stop there
+ On CUDA and MPS a homography or affine batch costs about the same from a few hundred up to 8192 hypotheses
+ (the four- and three-point solves are launch-bound), so the whole :attr:`sample_budget` is drawn in batches
+ of up to 8192; the epipolar solvers are compute-bound past 2048 hypotheses, so their batches stop there
and early stopping is checked in between. The verification holds a ``batch x N`` residual matrix and a
few temporaries of that size, so past ``2**27`` entries (about 1 GiB at peak in float32) the batch
shrinks with ``N``, down to the 2048 of the historical fixed batch. On CPU the cost is linear in
``batch * N`` residuals, and the eight-point solver is about ten times a DLT, so the batch aims at a
- millisecond or so of work, 256 to 2048 hypotheses for homographies and 128 to 512 for the epipolar
- models. Other devices retain the historical 2048-sample batch.
+ millisecond or so of work, 256 to 2048 hypotheses for homographies and 128 to 512 for affine and the
+ epipolar models: a three-point affine sample needs far fewer draws than a four-point one, and the smaller
+ batches let early stopping act sooner (1.1-4.3x faster at equal recall on 500-8000 synthetic matches with
+ 10-50% inliers). Other devices retain the historical 2048-sample batch.
With ``local_optimization="lm"`` an ``"auto"`` batch instead starts at 256 samples on CPU (512 for
homographies) and doubles after every batch, up to 2048 (4096 for homographies), so that inputs with
@@ -524,7 +562,7 @@ class RANSAC(nn.Module):
if device.type == "cpu":
work, lower, upper = (1 << 19, 256, 2048) if planar else (1 << 17, 128, 512)
elif device.type in ("cuda", "mps"):
- work, lower, upper = 1 << 27, 2048, 8192 if planar else 2048
+ work, lower, upper = 1 << 27, 2048, 8192 if planar or self.model_type == "affine" else 2048
else:
return min(_DEFAULT_BATCH, self.sample_budget)
batch = min(max(work // max(num_tc, 1), lower), upper)
diff --git a/kornia/geometry/solvers/__init__.py b/kornia/geometry/solvers/__init__.py
index 641c1fbad..561fd6590 100644
--- a/kornia/geometry/solvers/__init__.py
+++ b/kornia/geometry/solvers/__init__.py
@@ -20,6 +20,7 @@
This subpackage provides polynomial solvers and related utilities for geometry tasks.
"""
+from .affine import find_affine
from .homogeneous import null_vector_3x4
from .polynomial_solver import (
determinant_to_polynomial,
@@ -32,6 +33,7 @@ from .polynomial_solver import (
__all__ = [
"determinant_to_polynomial",
+ "find_affine",
"multiply_deg_one_poly",
"multiply_deg_two_one_poly",
"null_vector_3x4",
diff --git a/kornia/geometry/solvers/affine.py b/kornia/geometry/solvers/affine.py
new file mode 100644
index 000000000..df863ef88
--- /dev/null
+++ b/kornia/geometry/solvers/affine.py
@@ -0,0 +1,217 @@
+# 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.
+#
+
+"""Affine transformations estimated from point correspondences."""
+
+from __future__ import annotations
+
+from typing import Optional
+
+import torch
+
+__all__ = ["find_affine"]
+
+
+def _check_points(points1: torch.Tensor, points2: torch.Tensor, min_points: int, batched: bool) -> None:
+ if points1.shape != points2.shape:
+ raise ValueError(f"points1 and points2 must have the same shape. Got {points1.shape} and {points2.shape}.")
+ if (points1.ndim != 3 if batched else points1.ndim < 2) or points1.shape[-1] != 2:
+ prefix = "(B, N, 2)" if batched else "(..., N, 2)"
+ raise ValueError(f"points must have shape {prefix}. Got {points1.shape}.")
+ if points1.shape[-2] < min_points:
+ raise ValueError(f"At least {min_points} correspondences are required. Got {points1.shape[-2]}.")
+ if points1.device != points2.device:
+ raise ValueError("points1 and points2 must be on the same device.")
+ if not points1.is_floating_point() or not points2.is_floating_point():
+ raise TypeError("points1 and points2 must be floating point tensors.")
+ if points1.dtype != points2.dtype:
+ raise TypeError("points1 and points2 must have the same dtype.")
+
+
+def _prepare_weights(weights: Optional[torch.Tensor], points: torch.Tensor, batch_shape: torch.Size) -> torch.Tensor:
+ if weights is None:
+ return torch.ones((*batch_shape, points.shape[-2]), device=points.device, dtype=points.dtype)
+ if weights.shape != (*batch_shape, points.shape[-2]):
+ raise ValueError(f"weights must have shape {(*batch_shape, points.shape[-2])}. Got {weights.shape}.")
+ if weights.device != points.device:
+ raise ValueError("weights and points must be on the same device.")
+ if not weights.is_floating_point():
+ raise TypeError("weights must be a floating point tensor.")
+ # Weight values are not checked: reading them back would sync the host on accelerators, twice per call in RANSAC's
+ # local optimization, and break fullgraph compilation. The contract is in find_affine's docstring.
+ return weights
+
+
+def _fit_affine_components(
+ points1: torch.Tensor, points2: torch.Tensor, weights: torch.Tensor
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """Fit ``points2 = A @ points1 + t`` using a guarded weighted normal equation."""
+ # Explicit casts alone do not prevent autocast from lowering matrix multiplications again.
+ with torch.autocast(device_type=points1.device.type, enabled=False):
+ work_dtype = torch.float32 if points1.dtype in (torch.float16, torch.bfloat16) else points1.dtype
+ x, y = points1.to(work_dtype), points2.to(work_dtype)
+ # Weight rescaling leaves the least-squares problem unchanged and avoids
+ # underflow/overflow in the normal equation for extreme input weights. Do
+ # this before casting weights to the point arithmetic dtype: float32 weights
+ # may exceed the finite range of float16 inputs.
+ weight_dtype = torch.promote_types(work_dtype, weights.dtype)
+ weights_for_scaling = weights.to(weight_dtype)
+ max_weight = weights_for_scaling.amax(dim=-1, keepdim=True)
+ normalized_weights = weights_for_scaling / torch.where(max_weight > 0, max_weight, torch.ones_like(max_weight))
+ w = normalized_weights.to(work_dtype)
+ support = w.sum(dim=-1, keepdim=True)
+ safe_support = torch.where(support > 0, support, torch.ones_like(support))
+ x_mean = (x * w[..., None]).sum(dim=-2) / safe_support
+ y_mean = (y * w[..., None]).sum(dim=-2) / safe_support
+
+ xc, yc = x - x_mean[..., None, :], y - y_mean[..., None, :]
+ # Scaling makes the rank criterion relative to the data and keeps normal equations conditioned.
+ # Unlike an RMS scale, max-absolute scaling never evaluates sqrt at its singular point.
+ nonzero_weight = (w > 0)[..., None]
+ x_scale = torch.where(nonzero_weight, xc.abs(), torch.zeros_like(xc)).amax(dim=(-2, -1), keepdim=True)
+ y_scale = torch.where(nonzero_weight, yc.abs(), torch.zeros_like(yc)).amax(dim=(-2, -1), keepdim=True)
+ one = torch.ones_like(x_scale)
+ x_scale = torch.where(x_scale > 0, x_scale, one)
+ y_scale = torch.where(y_scale > 0, y_scale, one)
+ xn, yn = xc / x_scale, yc / y_scale
+ # Rotate the source onto the principal axes of its weighted scatter. For a scatter elongated along any
+ # other direction, det = a * d - b * c cancels, and its relative error, about aspect**2 * eps, scales the
+ # whole linear map. The fit is invariant to this rotation, so the detached angle loses no gradient and
+ # atan2(0, 0) of an isotropic scatter is never differentiated.
+ scatter = ((xn * w[..., None]).transpose(-1, -2) @ xn).detach()
+ angle = 0.5 * torch.atan2(2 * scatter[..., 0, 1], scatter[..., 0, 0] - scatter[..., 1, 1])
+ rotation = torch.stack((angle.cos(), angle.sin(), -angle.sin(), angle.cos()), dim=-1).reshape_as(scatter)
+ xn = xn @ rotation.transpose(-1, -2)
+
+ normal = (xn * w[..., None]).transpose(-1, -2) @ xn
+ cross = (yn * w[..., None]).transpose(-1, -2) @ xn
+ a, b, c, d = normal[..., 0, 0], normal[..., 0, 1], normal[..., 1, 0], normal[..., 1, 1]
+ det = a * d - b * c
+ trace = a + d
+ eps = torch.finfo(work_dtype).eps
+ valid = (support[..., 0] > 0) & (det > eps * trace.square())
+ safe_det = torch.where(valid, det, torch.ones_like(det))
+ inverse = torch.stack((d, -b, -c, a), dim=-1).reshape_as(normal) / safe_det[..., None, None]
+ linear_normalized = cross @ inverse @ rotation
+ linear = linear_normalized * (y_scale / x_scale)
+ translation = y_mean - torch.matmul(linear, x_mean[..., None]).squeeze(-1)
+ nan_linear = torch.full_like(linear, float("nan"))
+ nan_translation = torch.full_like(translation, float("nan"))
+ return torch.where(valid[..., None, None], linear, nan_linear), torch.where(
+ valid[..., None], translation, nan_translation
+ )
+
+
+def _find_affine_linear(points1: torch.Tensor, points2: torch.Tensor) -> torch.Tensor:
+ """Estimate origin-fixed 2D linear maps ``points2 = points1 @ A^T`` by least squares.
+
+ Solves the 2x2 normal equation ``A (X^T X) = Y^T X`` directly for points of shape ``(..., N, 2)``. Unlike
+ :func:`find_affine`, it neither centers, scales nor rotates the points, so it suits well-scaled, well-spread
+ points: AdaLAM refits its local affinities with it, on coordinates relative to the seed correspondence and
+ normalized by the neighborhood radius, where zero padding rows contribute nothing. Rank-deficient fits are
+ NaN under the relative criterion ``det(X^T X) <= eps * trace(X^T X)**2``.
+ """
+ _check_points(points1, points2, 1, batched=False)
+ with torch.autocast(device_type=points1.device.type, enabled=False):
+ work_dtype = torch.float32 if points1.dtype in (torch.float16, torch.bfloat16) else points1.dtype
+ x, y = points1.to(work_dtype), points2.to(work_dtype)
+ normal = x.transpose(-1, -2) @ x
+ a, b, c, d = normal[..., 0, 0], normal[..., 0, 1], normal[..., 1, 0], normal[..., 1, 1]
+ det = a * d - b * c
+ valid = det > torch.finfo(work_dtype).eps * (a + d).square()
+ safe_det = torch.where(valid, det, torch.ones_like(det))
+ inverse = torch.stack((d, -b, -c, a), dim=-1).reshape_as(normal) / safe_det[..., None, None]
+ linear = (y.transpose(-1, -2) @ x) @ inverse
+ return torch.where(valid[..., None, None], linear, torch.full_like(linear, float("nan"))).to(points1.dtype)
+
+
+def _find_affine_linear_pair(points1: torch.Tensor, points2: torch.Tensor) -> torch.Tensor:
+ """Solve origin-fixed 2D linear maps exactly from two correspondences.
+
+ The minimal case of :func:`_find_affine_linear` for points of shape ``(..., 2, 2)``: two correspondences
+ determine the map, so the 2x2 system is solved directly rather than through the normal equation, which
+ squares its condition number. Rank-deficient samples are NaN under the same relative criterion,
+ ``det(X^T X) <= eps * trace(X^T X)**2``, written without squaring as ``|det X| <= sqrt(eps) * ||X||_F**2``.
+ """
+ _check_points(points1, points2, 2, batched=False)
+ if points1.shape[-2] != 2:
+ raise ValueError(f"Exactly 2 correspondences are required. Got {points1.shape[-2]}.")
+ with torch.autocast(device_type=points1.device.type, enabled=False):
+ work_dtype = torch.float32 if points1.dtype in (torch.float16, torch.bfloat16) else points1.dtype
+ x, y = points1.to(work_dtype), points2.to(work_dtype)
+ a, b, c, d = x[..., 0, 0], x[..., 0, 1], x[..., 1, 0], x[..., 1, 1]
+ det = a * d - b * c
+ valid = det.abs() > torch.finfo(work_dtype).eps ** 0.5 * x.square().sum(dim=(-2, -1))
+ safe_det = torch.where(valid, det, torch.ones_like(det))
+ # x @ A^T = y, so A^T = adj(x) @ y / det(x).
+ adjugate = torch.stack((d, -b, -c, a), dim=-1).reshape_as(x)
+ linear = (adjugate @ y).transpose(-1, -2) / safe_det[..., None, None]
+ return torch.where(valid[..., None, None], linear, torch.full_like(linear, float("nan"))).to(points1.dtype)
+
+
+def _find_affine_triplet(
+ points1: torch.Tensor, points2: torch.Tensor, weights: Optional[torch.Tensor] = None
+) -> torch.Tensor:
+ """Solve 2D affine transformations exactly from three correspondences, RANSAC's minimal samples.
+
+ Points have shape ``(B, 3, 2)`` and the result is homogeneous ``(B, 3, 3)``, like :func:`find_affine`. The linear
+ part maps the differences to the first correspondence, by :func:`_find_affine_linear_pair`, and the translation
+ follows from the first correspondence; collinear samples are NaN under that function's rank criterion. Positive
+ weights do not change an exact fit, so ``weights``, part of RANSAC's solver interface, are not used.
+ """
+ _check_points(points1, points2, 3, batched=True)
+ if points1.shape[-2] != 3:
+ raise ValueError(f"Exactly 3 correspondences are required. Got {points1.shape[-2]}.")
+ with torch.autocast(device_type=points1.device.type, enabled=False):
+ work_dtype = torch.float32 if points1.dtype in (torch.float16, torch.bfloat16) else points1.dtype
+ x, y = points1.to(work_dtype), points2.to(work_dtype)
+ origin1, origin2 = x[:, :1], y[:, :1]
+ linear = _find_affine_linear_pair(x[:, 1:] - origin1, y[:, 1:] - origin2)
+ translation = origin2.transpose(-1, -2) - linear @ origin1.transpose(-1, -2)
+ bottom = torch.tensor([0.0, 0.0, 1.0], device=x.device, dtype=work_dtype).expand(x.shape[0], 1, 3)
+ return torch.cat((torch.cat((linear, translation), dim=-1), bottom), dim=-2).to(points1.dtype)
+
+
+def find_affine(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[torch.Tensor] = None) -> torch.Tensor:
+ r"""Estimate 2D affine transformations from point correspondences.
+
+ Fits the weighted least-squares model :math:`\mathbf{y}=A\mathbf{x}+\mathbf{t}`
+ independently for each batch. The calculation centers and isotropically normalizes
+ each point set before solving its 2-by-2 normal equation. Inputs must have the
+ same floating-point dtype and device; half inputs are accumulated in float32.
+ Ambient autocast is disabled during fitting to preserve this arithmetic precision.
+
+ Args:
+ points1: Source points with shape :math:`(B, N, 2)`, where :math:`N \geq 3`.
+ points2: Destination points with shape :math:`(B, N, 2)`.
+ weights: Optional correspondence weights with shape :math:`(B, N)`. They must be
+ finite and non-negative; other values are not detected and give undefined
+ results. Only relative weights matter.
+
+ Returns:
+ Homogeneous affine transformations with shape :math:`(B, 3, 3)`. Degenerate
+ batches without three non-collinear, positive-weight source points contain
+ NaNs, allowing robust estimators to reject singular fits as invalid models.
+ """
+ _check_points(points1, points2, 3, batched=True)
+ weights = _prepare_weights(weights, points1, points1.shape[:-2])
+ linear, translation = _fit_affine_components(points1, points2, weights)
+ result = torch.zeros((*points1.shape[:-2], 3, 3), device=points1.device, dtype=linear.dtype)
+ result[..., :2, :2] = linear
+ result[..., :2, 2] = translation
+ result[..., 2, 2] = 1
+ return result.to(points1.dtype)
diff --git a/tests/api_surface.json b/tests/api_surface.json
index 770458106..6223d9ef5 100644
--- a/tests/api_surface.json
+++ b/tests/api_surface.json
@@ -562,6 +562,7 @@
"essential_from_fundamental",
"euclidean_distance",
"euler_from_quaternion",
+ "find_affine",
"find_essential",
"find_fundamental",
"find_homography_dlt",
@@ -927,6 +928,7 @@
],
"kornia.geometry.solvers": [
"determinant_to_polynomial",
+ "find_affine",
"multiply_deg_one_poly",
"multiply_deg_two_one_poly",
"null_vector_3x4",
@@ -934,6 +936,9 @@
"solve_quadratic",
"solve_quartic"
],
+ "kornia.geometry.solvers.affine": [
+ "find_affine"
+ ],
"kornia.geometry.subpix": [
"AdaptiveQuadInterp3d",
"ConvQuadInterp3d",
diff --git a/tests/feature/test_adalam_affine.py b/tests/feature/test_adalam_affine.py
new file mode 100644
index 000000000..be009bca5
--- /dev/null
+++ b/tests/feature/test_adalam_affine.py
@@ -0,0 +1,70 @@
+# 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.
+#
+
+from __future__ import annotations
+
+import pytest
+import torch
+
+from kornia.feature.adalam import get_adalam_default_config
+from kornia.feature.adalam.ransac import ransac
+
+from testing.base import BaseTester
+
+
+class TestAdalamSharedAffine(BaseTester):
+ @pytest.mark.parametrize("refit", [False, True])
+ def test_ragged_neighborhoods(self, device, dtype, refit):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("AdaLAM operates on full-precision coordinates")
+ generator = torch.Generator().manual_seed(19)
+ sizes = [40, 25]
+ source = torch.rand(sum(sizes), 2, generator=generator).to(device=device, dtype=dtype) - 0.5
+ source[0] = 0
+ source[sizes[0]] = 0
+ groups = torch.arange(2, device=device).repeat_interleave(torch.tensor(sizes, device=device))
+ expected = torch.tensor([[[1.1, -0.2], [0.1, 0.9]], [[0.8, 0.1], [-0.1, 1.2]]], device=device, dtype=dtype)
+ target = (expected[groups] @ source[..., None]).squeeze(-1)
+ # Independent nonzero localization noise exercises AdaLAM's original adaptive selection.
+ noise = 0.002 * torch.randn(target.shape, generator=generator).to(device=device, dtype=dtype)
+ noise[0] = 0
+ noise[sizes[0]] = 0
+ target += noise
+ outliers = torch.tensor([35, 36, 37, 38, 39, 60, 61, 62, 63, 64], device=device)
+ target[outliers] += 10
+ config = get_adalam_default_config()
+ config["device"] = device
+ indices, models, confidence, counts = ransac(
+ source, target, torch.tensor(sizes, device=device), config, refit=refit
+ )
+ assert not torch.isin(indices, outliers).any()
+ assert (counts >= torch.tensor([25, 15], device=device)).all()
+ assert (confidence >= config["min_confidence"]).all()
+ self.assert_close(models, expected, atol=0.03, rtol=0.03)
+
+ @pytest.mark.parametrize("refit", [False, True])
+ def test_rank_deficient_neighborhood(self, device, dtype, refit):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("AdaLAM operates on full-precision coordinates")
+ source = torch.zeros(20, 2, device=device, dtype=dtype)
+ source[:, 0] = torch.linspace(-0.5, 0.5, 20, device=device, dtype=dtype)
+ target = source * 1.1
+ config = get_adalam_default_config()
+ config["device"] = device
+ _, _, confidence, counts = ransac(source, target, torch.tensor([20], device=device), config, refit=refit)
+ accepted = (confidence >= config["min_confidence"]) & (counts * (1 - 1 / confidence) >= config["min_inliers"])
+ assert not accepted.any()
diff --git a/tests/geometry/test_affine.py b/tests/geometry/test_affine.py
new file mode 100644
index 000000000..579fb0894
--- /dev/null
+++ b/tests/geometry/test_affine.py
@@ -0,0 +1,346 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import pytest
+import torch
+
+from kornia.geometry.solvers.affine import (
+ _find_affine_linear,
+ _find_affine_linear_pair,
+ _find_affine_triplet,
+ find_affine,
+)
+
+from testing.base import BaseTester, dynamo_is_available
+
+
+class TestFindAffine(BaseTester):
+ @staticmethod
+ def _points(device, dtype):
+ points = torch.tensor([[0.0, 0.0], [2.0, 0.0], [0.0, 3.0], [3.0, 2.0]], device=device, dtype=dtype)[None]
+ matrix = torch.tensor([[1.5, -0.25, 4.0], [0.5, -2.0, -3.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype)[None]
+ target = points @ matrix[:, :2, :2].transpose(-1, -2) + matrix[:, None, :2, 2]
+ return points, target, matrix
+
+ def test_exact(self, device, dtype):
+ points, target, expected = self._points(device, dtype)
+ actual = find_affine(points, target)
+ tol = 2e-3 if dtype in (torch.float16, torch.bfloat16) else 1e-5
+ self.assert_close(actual, expected, rtol=tol, atol=tol)
+
+ def test_minimal_three_points(self, device, dtype):
+ points, target, expected = self._points(device, dtype)
+ actual = find_affine(points[:, :3], target[:, :3])
+ tol = 2e-3 if dtype in (torch.float16, torch.bfloat16) else 1e-5
+ self.assert_close(actual, expected, rtol=tol, atol=tol)
+
+ def test_weighted_ignores_zero_weight_outlier(self, device, dtype):
+ points, target, expected = self._points(device, dtype)
+ target[..., -1, :] += 100
+ weights = torch.tensor([[1.0, 1.0, 1.0, 0.0]], device=device, dtype=dtype)
+ actual = find_affine(points, target, weights)
+ tol = 2e-3 if dtype in (torch.float16, torch.bfloat16) else 1e-5
+ self.assert_close(actual, expected, rtol=tol, atol=tol)
+
+ def test_weighted_noisy_fit_matches_lstsq_reference(self, device, dtype):
+ points, target, _ = self._points(device, dtype)
+ target = target + torch.tensor(
+ [[[0.2, -0.1], [-0.1, 0.15], [0.05, 0.2], [-0.2, -0.05]]], device=device, dtype=dtype
+ )
+ weights = torch.tensor([[0.25, 1.5, 2.0, 0.75]], device=device, dtype=dtype)
+ # Use CPU float64 for an independent, portable reference; MPS lacks lstsq.
+ points_cpu, target_cpu, weights_cpu = points.cpu().double(), target.cpu().double(), weights.cpu().double()
+ design = torch.cat((points_cpu, torch.ones_like(points_cpu[..., :1])), dim=-1)
+ reference = torch.linalg.lstsq(
+ design * weights_cpu.sqrt()[..., None], target_cpu * weights_cpu.sqrt()[..., None]
+ ).solution.to(device=device, dtype=dtype)
+ expected = torch.eye(3, device=device, dtype=dtype)[None]
+ expected[:, :2, :] = reference.transpose(-1, -2)
+ actual = find_affine(points, target, weights)
+ tol = 3e-3 if dtype in (torch.float16, torch.bfloat16) else 1e-5
+ self.assert_close(actual, expected, rtol=tol, atol=tol)
+ weight_scale = 1.0e-2 if dtype in (torch.float16, torch.bfloat16) else 1.0e-10
+ self.assert_close(find_affine(points, target, weights * weight_scale), actual, rtol=tol, atol=tol)
+
+ def test_weights_do_not_narrow_before_normalization(self, device, dtype):
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("Exercises mixed-precision weight normalization.")
+ points, target, expected = self._points(device, dtype)
+ tolerance = 3e-3
+ for scale in (1.0e-8, 1.0e10):
+ weights = torch.full((1, 4), scale, device=device, dtype=torch.float32)
+ actual = find_affine(points, target, weights)
+ self.assert_close(actual, expected, rtol=tolerance, atol=tolerance)
+
+ def test_float64_extreme_weight_scale_invariance(self, device):
+ if device.type != "cpu":
+ pytest.skip("CPU float64 regression for extreme floating-point weights.")
+ points, target, expected = self._points(device, torch.float64)
+ weights = torch.full((1, 4), 1.0e300, device=device, dtype=torch.float64)
+ actual = find_affine(points, target, weights)
+ self.assert_close(actual, expected, rtol=1e-10, atol=1e-10)
+
+ @pytest.mark.parametrize("angle", [0.0, 45.0, 120.0])
+ def test_elongated_source_any_direction(self, device, dtype, angle):
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("Input rounding dominates in half precision.")
+ # A 1000 px by 6 px strip of exact correspondences, centred at (700, 500) and rotated by `angle`.
+ u = torch.linspace(-500.0, 500.0, 64, dtype=torch.float64)
+ v = 3.0 * torch.tensor([1.0, -1.0], dtype=torch.float64).repeat(32)
+ theta = torch.tensor(angle, dtype=torch.float64).deg2rad()
+ points = torch.stack(
+ (700 + u * theta.cos() - v * theta.sin(), 500 + u * theta.sin() + v * theta.cos()), dim=-1
+ )[None]
+ _, _, matrix = self._points("cpu", torch.float64)
+ target = points @ matrix[:, :2, :2].transpose(-1, -2) + matrix[:, None, :2, 2]
+ actual = find_affine(points.to(device, dtype), target.to(device, dtype)).cpu().double()
+ transferred = points @ actual[:, :2, :2].transpose(-1, -2) + actual[:, None, :2, 2]
+ tol = 1e-2 if dtype == torch.float32 else 1e-8
+ self.assert_close(transferred, target, rtol=0, atol=tol)
+
+ def test_scale_and_translation_conditioning(self, device, dtype):
+ points, target, expected = self._points(device, dtype)
+ scale = 10.0 if dtype in (torch.float16, torch.bfloat16) else 1.0e3
+ offset_value = 100.0 if dtype in (torch.float16, torch.bfloat16) else 1.0e5
+ offset = torch.tensor([offset_value, -2.0 * offset_value], device=device, dtype=dtype)
+ points = points * scale + offset
+ target = target * scale - offset
+ expected = expected.clone()
+ expected[:, :2, 2] = scale * expected[:, :2, 2] - offset - (expected[:, :2, :2] @ offset[..., None])[..., 0]
+ actual = find_affine(points, target)
+ tol = 1e-2 if dtype in (torch.float16, torch.bfloat16) else 2e-4
+ self.assert_close(actual, expected, rtol=tol, atol=tol)
+
+ def test_autocast_preserves_float32_solver_precision(self, device):
+ """Float32 inputs must not let ambient AMP narrow the affine matrix products."""
+ if device.type not in ("cpu", "cuda", "mps"):
+ pytest.skip("CPU/CUDA/MPS mixed-precision coverage")
+ autocast_dtype = torch.bfloat16 if device.type == "cpu" else torch.float16
+ u = torch.linspace(-500.0, 500.0, 64, device=device)
+ v = 100.0 * torch.tensor([1.0, -1.0], device=device).repeat(32)
+ theta = torch.tensor(45.0, device=device).deg2rad()
+ points = torch.stack(
+ (700.0 + u * theta.cos() - v * theta.sin(), 500.0 + u * theta.sin() + v * theta.cos()), dim=-1
+ )[None]
+ expected = torch.tensor([[1.5, -0.25, 4.0], [0.5, -2.0, -3.0], [0.0, 0.0, 1.0]], device=device)[None]
+ target = points @ expected[:, :2, :2].transpose(-1, -2) + expected[:, None, :2, 2]
+ weights = torch.linspace(0.1, 2.0, points.shape[1], device=device)[None]
+
+ reference = find_affine(points, target, weights)
+ reference_refit = _find_affine_linear(points - points[:, :1], target - target[:, :1])
+ reference_pair = _find_affine_linear_pair(points[:, 1:3] - points[:, :1], target[:, 1:3] - target[:, :1])
+ reference_triplet = _find_affine_triplet(points[:, :3], target[:, :3])
+
+ with torch.autocast(device.type, dtype=autocast_dtype):
+ actual = find_affine(points, target, weights)
+ refit = _find_affine_linear(points - points[:, :1], target - target[:, :1])
+ pair = _find_affine_linear_pair(points[:, 1:3] - points[:, :1], target[:, 1:3] - target[:, :1])
+ triplet = _find_affine_triplet(points[:, :3], target[:, :3])
+ assert torch.is_autocast_enabled(device.type)
+
+ assert actual.dtype == refit.dtype == pair.dtype == triplet.dtype == points.dtype
+ self.assert_close(actual, reference, rtol=0, atol=0)
+ self.assert_close(refit, reference_refit, rtol=0, atol=0)
+ self.assert_close(pair, reference_pair, rtol=0, atol=0)
+ self.assert_close(triplet, reference_triplet, rtol=0, atol=0)
+ self.assert_close(actual, expected, rtol=0, atol=3e-4)
+ self.assert_close(refit, expected[:, :2, :2], rtol=0, atol=1e-5)
+ self.assert_close(pair, expected[:, :2, :2], rtol=0, atol=1e-5)
+ self.assert_close(triplet, expected, rtol=0, atol=2e-4)
+
+ def test_invalid_batches_are_nan(self, device, dtype):
+ good, target, _ = self._points(device, dtype)
+ bad = torch.tensor([[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [3.0, 0.0]], device=device, dtype=dtype)[None]
+ actual = find_affine(torch.cat((good, bad)), torch.cat((target, bad)))
+ assert torch.isfinite(actual[0]).all()
+ assert torch.isnan(actual[1, :2]).all()
+ zero_weight = find_affine(good, target, torch.zeros(1, 4, device=device, dtype=dtype))
+ assert torch.isnan(zero_weight[:, :2]).all()
+
+ def test_errors(self, device, dtype):
+ points = torch.zeros(1, 2, 2, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="At least 3"):
+ find_affine(points, points)
+ with pytest.raises(ValueError, match="same shape"):
+ find_affine(torch.zeros(1, 3, 2, device=device, dtype=dtype), points)
+ points = torch.zeros(1, 3, 2, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="weights"):
+ find_affine(points, points, torch.ones(1, 2, device=device, dtype=dtype))
+ with pytest.raises(ValueError, match="shape"):
+ find_affine(points[:, None], points[:, None])
+ other_dtype = torch.float16 if dtype == torch.float32 else torch.float32
+ with pytest.raises(TypeError, match="same dtype"):
+ find_affine(points, points.to(other_dtype))
+
+ def test_origin_fixed_linear(self, device, dtype):
+ matrix = torch.tensor([[2.0, -1.0], [0.5, 3.0]], device=device, dtype=dtype)
+ points = torch.tensor([[1.0, 0.0], [0.0, 2.0]], device=device, dtype=dtype)
+ target = points @ matrix.T
+ actual = _find_affine_linear(points, target)
+ tol = 2e-3 if dtype in (torch.float16, torch.bfloat16) else 1e-5
+ self.assert_close(actual, matrix, rtol=tol, atol=tol)
+ padded = _find_affine_linear(points[:1], target[:1])
+ assert torch.isnan(padded).all()
+
+ def test_origin_fixed_least_squares_with_zero_padding(self, device, dtype):
+ generator = torch.Generator().manual_seed(5)
+ points = torch.rand(2, 10, 2, generator=generator, dtype=torch.float64) - 0.5
+ matrix = torch.tensor([[1.1, -0.2], [0.1, 0.9]], dtype=torch.float64)
+ target = points @ matrix.T + 0.01 * torch.randn(2, 10, 2, generator=generator, dtype=torch.float64)
+ # Origin-fixed least squares, as AdaLAM refits relative to its seed: no intercept column.
+ expected = torch.linalg.lstsq(points, target).solution.transpose(-1, -2)
+ # Zero rows, AdaLAM's padding of neighborhoods with fewer inliers, contribute nothing.
+ padded_points = torch.cat((points, torch.zeros(2, 4, 2, dtype=torch.float64)), dim=1)
+ padded_target = torch.cat((target, torch.zeros(2, 4, 2, dtype=torch.float64)), dim=1)
+ actual = _find_affine_linear(padded_points.to(device, dtype), padded_target.to(device, dtype))
+ assert actual.dtype == dtype
+ tol = 1e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-5
+ self.assert_close(actual, expected.to(device, dtype), rtol=tol, atol=tol)
+
+ def test_origin_fixed_pair(self, device, dtype):
+ matrix = torch.tensor([[2.0, -1.0], [0.5, 3.0]], device=device, dtype=dtype)
+ points = torch.tensor(
+ [[[1.0, 0.0], [0.0, 2.0]], [[0.5, -0.25], [0.25, 0.75]], [[-1.0, 1.0], [1.0, 1.0]]],
+ device=device,
+ dtype=dtype,
+ )[None].expand(2, -1, -1, -1)
+ target = points @ matrix.T
+ actual = _find_affine_linear_pair(points, target)
+ assert actual.shape == (2, 3, 2, 2)
+ assert actual.dtype == dtype
+ tol = 2e-3 if dtype in (torch.float16, torch.bfloat16) else 1e-5
+ self.assert_close(actual, matrix.expand_as(actual), rtol=tol, atol=tol)
+
+ def test_origin_fixed_pair_rank_deficient(self, device, dtype):
+ # Collinear with the origin, a repeated point, a point at the origin, and a near-collinear pair whose
+ # |det X| / ||X||_F**2 = 1e-5 lies below sqrt(eps) of float32.
+ points = torch.tensor(
+ [[[1.0, 2.0], [-2.0, -4.0]], [[1.0, 2.0], [1.0, 2.0]], [[0.0, 0.0], [1.0, 2.0]], [[1.0, 0.0], [1.0, 2e-5]]],
+ device=device,
+ dtype=dtype,
+ )
+ actual = _find_affine_linear_pair(points, points + 1)
+ assert torch.isnan(actual[:3]).all()
+ if dtype != torch.float64:
+ assert torch.isnan(actual[3]).all()
+
+ def test_origin_fixed_pair_matches_least_squares(self, device, dtype):
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("Compares two float32 solvers on the same half-rounded inputs.")
+ generator = torch.Generator().manual_seed(3)
+ points = (torch.rand(64, 2, 2, generator=generator) - 0.5).to(device=device, dtype=dtype)
+ target = (torch.rand(64, 2, 2, generator=generator) - 0.5).to(device=device, dtype=dtype)
+ # Two exactly singular pairs: collinear with the origin, and one point at the origin.
+ points[0, 1] = -3 * points[0, 0]
+ points[1, 0] = 0
+ expected = _find_affine_linear(points, target)
+ actual = _find_affine_linear_pair(points, target)
+ self.assert_close(torch.isnan(actual), torch.isnan(expected), atol=0, rtol=0)
+ assert torch.isnan(actual[:2]).all()
+ valid = ~torch.isnan(expected)
+ # The normal equation squares the condition number; the direct solve does not.
+ self.assert_close(actual[valid], expected[valid], rtol=1e-3, atol=1e-3)
+
+ def test_triplet(self, device, dtype):
+ points, target, expected = self._points(device, dtype)
+ # Move the first point off the origin: the translation follows from it. The shifted targets stay
+ # integers or quarters below 256, exact in bfloat16.
+ offset = torch.tensor([30.0, -20.0], device=device, dtype=dtype)
+ points, target = points[:, :3] + offset, target[:, :3] + offset @ expected[0, :2, :2].T
+ actual = _find_affine_triplet(points.expand(4, -1, -1), target.expand(4, -1, -1), torch.ones(4, 3))
+ assert actual.shape == (4, 3, 3)
+ assert actual.dtype == dtype
+ self.assert_close(actual[:, 2], expected[:, 2].expand(4, -1), atol=0, rtol=0)
+ tol = 1e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-4
+ self.assert_close(actual, expected.expand(4, -1, -1), rtol=tol, atol=tol)
+
+ def test_triplet_matches_find_affine(self, device, dtype):
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("Compares two float32 solvers on the same half-rounded inputs.")
+ generator = torch.Generator().manual_seed(7)
+ points = (1000 * torch.rand(64, 3, 2, generator=generator)).to(device=device, dtype=dtype)
+ target = (1000 * torch.rand(64, 3, 2, generator=generator)).to(device=device, dtype=dtype)
+ points[0, 2] = 2 * points[0, 1] - points[0, 0] # collinear
+ points[1, 1] = points[1, 0] # repeated
+ expected = find_affine(points, target)
+ actual = _find_affine_triplet(points, target)
+ self.assert_close(torch.isnan(actual), torch.isnan(expected), atol=0, rtol=0)
+ assert torch.isnan(actual[:2, :2]).all()
+ # Both are exact fits: each maps its own three source points onto their targets.
+ valid = ~torch.isnan(actual).any(dim=(-2, -1))
+ transferred = points[valid] @ actual[valid, :2, :2].transpose(-1, -2) + actual[valid, None, :2, 2]
+ tol = 1e-2 if dtype == torch.float32 else 1e-8
+ self.assert_close(transferred, target[valid], rtol=0, atol=tol)
+
+ def test_origin_fixed_pair_errors(self, device, dtype):
+ points = torch.zeros(4, 3, 2, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="Exactly 2"):
+ _find_affine_linear_pair(points, points)
+ with pytest.raises(ValueError, match="At least 2"):
+ _find_affine_linear_pair(points[:, :1], points[:, :1])
+ with pytest.raises(ValueError, match="same shape"):
+ _find_affine_linear_pair(points[:, :2], points[:2, :2])
+ quadruples = torch.zeros(4, 4, 2, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="Exactly 3"):
+ _find_affine_triplet(quadruples, quadruples)
+
+ def test_gradcheck(self, device):
+ points, target, _ = self._points(device, torch.float64)
+ self.gradcheck(find_affine, (points.requires_grad_(), target.requires_grad_()), rtol=1e-5, atol=1e-6)
+
+ def test_weighted_gradcheck_and_constant_target(self, device):
+ points, _, _ = self._points(device, torch.float64)
+ target = torch.tensor([[[2.0, -3.0]]], device=device, dtype=torch.float64).expand_as(points).clone()
+ weights = torch.tensor([[0.5, 1.0, 1.5, 2.0]], device=device, dtype=torch.float64, requires_grad=True)
+ self.gradcheck(find_affine, (points.requires_grad_(), target.requires_grad_(), weights), rtol=1e-5, atol=1e-6)
+ find_affine(points, target).square().sum().backward()
+ assert torch.isfinite(points.grad).all()
+ assert torch.isfinite(target.grad).all()
+
+ def test_empty_batch(self, device, dtype):
+ points = torch.empty(0, 3, 2, device=device, dtype=dtype)
+ assert find_affine(points, points).shape == (0, 3, 3)
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason="no Dynamo on this torch/python pair")
+ def test_eager_backend_traces_weighted_fit(self, device, dtype):
+ # Weight values are not read back on the host, so a weighted fit traces as one graph. The name keeps
+ # "compile" and "dynamo" out, so the ordinary jobs run it.
+ points, target, _ = self._points(device, dtype)
+ weights = torch.tensor([[0.5, 1.0, 1.5, 2.0]], device=device, dtype=dtype)
+ torch._dynamo.reset()
+ autocast_dtype = torch.bfloat16 if device.type == "cpu" else torch.float16
+ with torch.autocast(device.type, dtype=autocast_dtype):
+ actual = torch.compile(find_affine, backend="eager", fullgraph=True)(points, target, weights)
+ self.assert_close(actual, find_affine(points, target, weights))
+
+ def test_weighted_fit_without_host_sync(self, device, dtype):
+ if device.type != "cuda":
+ pytest.skip("Host synchronization is observable on CUDA only.")
+ points, target, _ = self._points(device, dtype)
+ weights = torch.ones(1, 4, device=device, dtype=dtype)
+ find_affine(points, target, weights) # lazy CUDA and cuBLAS initialization may synchronize
+ previous = torch.cuda.get_sync_debug_mode()
+ torch.cuda.set_sync_debug_mode("error")
+ try:
+ find_affine(points, target, weights)
+ finally:
+ torch.cuda.set_sync_debug_mode(previous)
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ points, target, _ = self._points(device, dtype)
+ actual = torch_optimizer(find_affine)(points, target)
+ self.assert_close(actual, find_affine(points, target))
diff --git a/tests/geometry/test_ransac_affine.py b/tests/geometry/test_ransac_affine.py
new file mode 100644
index 000000000..c929a21c0
--- /dev/null
+++ b/tests/geometry/test_ransac_affine.py
@@ -0,0 +1,157 @@
+# 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.
+#
+
+from __future__ import annotations
+
+import pytest
+import torch
+
+from kornia.geometry import RANSAC, transform_points
+from kornia.geometry.homography import oneway_transfer_error
+from kornia.geometry.ransac import _affine_transfer_error
+
+from testing.base import BaseTester
+
+
+class TestRANSACAffine(BaseTester):
+ @pytest.mark.parametrize("score_type", ["ransac", "msac"])
+ @pytest.mark.parametrize("prosac", [False, True])
+ @pytest.mark.parametrize("lo_sample_size", [None, 8])
+ def test_affine_with_outliers(self, device, dtype, score_type, prosac, lo_sample_size):
+ grid = torch.arange(-3, 5, device=device, dtype=dtype)
+ source = torch.cartesian_prod(grid, grid)
+ expected = torch.tensor([[1.0, 0.25, 2.0], [-0.5, 1.0, -1.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype)
+ target = transform_points(expected[None], source[None])[0]
+ target[-16:] += 20.0
+ estimator = RANSAC(
+ "affine",
+ inl_th=0.125,
+ batch_size=32,
+ max_samples=256,
+ max_lo_iters=3,
+ score_type=score_type,
+ prosac_sampling=prosac,
+ lo_sample_size=lo_sample_size,
+ seed=4,
+ )
+ model, inliers = estimator(source, target)
+ self.assert_close(model, expected)
+ self.assert_close(inliers, torch.arange(len(source), device=device) < 48)
+ self.assert_close(model[2], expected[2], atol=0, rtol=0)
+ classified = oneway_transfer_error(source[None], target[None], model[None])[0] <= estimator.inl_th**2
+ self.assert_close(inliers, classified)
+ assert model.device == device
+ assert model.dtype == dtype
+ assert inliers.dtype == torch.bool
+
+ @pytest.mark.parametrize("case", ["collinear", "duplicate", "minimal_only"])
+ def test_no_supported_model(self, device, dtype, case):
+ source = torch.tensor([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [2.0, 2.0]], device=device, dtype=dtype)
+ if case == "collinear":
+ source[:, 1] = 0
+ elif case == "duplicate":
+ source[:] = 1
+ else:
+ source = source[:3]
+ estimator = RANSAC("affine", batch_size=8, max_samples=16, seed=0)
+ model, inliers = estimator(source, source + 1)
+ self.assert_close(model, torch.zeros(3, 3, device=device, dtype=dtype), atol=0, rtol=0)
+ assert inliers.shape == (len(source),)
+ assert not inliers.any()
+
+ def test_threshold_is_target_distance(self, device, dtype):
+ source = torch.tensor([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [2.0, 2.0], [3.0, 1.0]], device=device, dtype=dtype)
+ target = source.clone()
+ target[-2:, 0] += torch.tensor([0.375, 0.75], device=device, dtype=dtype)
+ estimator = RANSAC("affine", inl_th=0.5)
+ _, inliers, _, count = estimator.verify(source, target, torch.eye(3, device=device, dtype=dtype)[None], 0.5**2)
+ self.assert_close(inliers, torch.tensor([True, True, True, True, False], device=device))
+ assert count == 4
+
+ def test_affine_autocast_preserves_float32_scoring_and_inliers(self, device):
+ if device.type not in ("cpu", "cuda", "mps"):
+ pytest.skip("CPU/CUDA/MPS mixed-precision coverage")
+ autocast_dtype = torch.bfloat16 if device.type == "cpu" else torch.float16
+ u = torch.linspace(-500.0, 500.0, 64, device=device)
+ v = 100.0 * torch.tensor([1.0, -1.0], device=device).repeat(32)
+ theta = torch.tensor(45.0, device=device).deg2rad()
+ source = torch.stack(
+ (700.0 + u * theta.cos() - v * theta.sin(), 500.0 + u * theta.sin() + v * theta.cos()), dim=-1
+ )
+ expected = torch.tensor([[1.5, -0.25, 4.0], [0.5, -2.0, -3.0], [0.0, 0.0, 1.0]], device=device)[None]
+ target = transform_points(expected, source[None])[0]
+ estimator = RANSAC("affine", inl_th=1.0, batch_size=64, max_iter=3, seed=1)
+ reference_residuals = _affine_transfer_error(source[None], target[None], expected)
+ _, reference_inliers = estimator(source, target)
+ _, reference_verified, _, reference_count = estimator.verify(source, target, expected, estimator.inl_th**2)
+
+ with torch.autocast(device.type, dtype=autocast_dtype):
+ residuals = _affine_transfer_error(source[None], target[None], expected)
+ _, inliers = estimator(source, target)
+ _, verified, _, count = estimator.verify(source, target, expected, estimator.inl_th**2)
+ assert torch.is_autocast_enabled(device.type)
+
+ assert residuals.dtype == source.dtype
+ self.assert_close(residuals, reference_residuals, atol=0, rtol=0)
+ self.assert_close(inliers, reference_inliers, atol=0, rtol=0)
+ self.assert_close(verified, reference_verified, atol=0, rtol=0)
+ assert count == reference_count
+ self.assert_close(residuals, torch.zeros_like(residuals), atol=0, rtol=0)
+ assert inliers.all()
+ assert verified.all()
+ assert count == len(source)
+
+ def test_transfer_error_matches_oneway(self, device, dtype):
+ generator = torch.Generator().manual_seed(11)
+ source = (1000 * torch.rand(1, 50, 2, generator=generator)).to(device=device, dtype=dtype)
+ target = (1000 * torch.rand(1, 50, 2, generator=generator)).to(device=device, dtype=dtype)
+ models = torch.eye(3).repeat(6, 1, 1)
+ models[:, :2] += 0.1 * torch.randn(6, 2, 3, generator=generator) + torch.tensor([0.0, 0.0, 20.0])
+ models = models.to(device=device, dtype=dtype)
+ actual = _affine_transfer_error(source, target, models)
+ assert actual.shape == (6, 50)
+ assert actual.dtype == dtype
+ self.assert_close(actual, oneway_transfer_error(source, target, models))
+
+ @pytest.mark.parametrize("kwargs", [{"local_optimization": "lm"}, {"compile": True}, {"degensac": True}])
+ def test_unsupported_refinement(self, kwargs):
+ with pytest.raises(ValueError):
+ RANSAC("affine", **kwargs)
+
+ def test_auto_batch_size(self):
+ # Three-point samples: the epipolar models' CPU batches, the homographies' accelerator batches.
+ estimator = RANSAC("affine")
+ assert estimator.resolve_batch_size(2000, torch.device("cpu")) == 128
+ assert estimator.resolve_batch_size(500, torch.device("cpu")) == 262
+ assert estimator.resolve_batch_size(2000, torch.device("cuda")) == 8192
+ assert estimator.resolve_batch_size(50000, torch.device("cuda")) == 2684
+
+ def test_too_few_correspondences(self, device, dtype):
+ points = torch.zeros(2, 2, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="at least"):
+ RANSAC("affine")(points, points)
+
+ def test_seeded_reproducibility(self, device, dtype):
+ generator = torch.Generator().manual_seed(21)
+ source = torch.rand(40, 2, generator=generator).to(device=device, dtype=dtype)
+ target = source + 2
+ target[-10:] -= 20
+ estimator = RANSAC("affine", inl_th=0.1, max_samples=32, batch_size=16, seed=7, max_lo_iters=0)
+ first = estimator(source, target)
+ second = estimator(source, target)
+ for actual, expected in zip(first, second):
+ self.assert_close(actual, expected, atol=0, rtol=0)