π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(geometry): Convention blocks and pins for homography estimation, RANSAC and the solvers (batch 8c) (#4892)
Dmytro Mishkin536e67539637
diff --git a/changelog.d/4892.added.md b/changelog.d/4892.added.mdnew file mode 100644index 000000000..0a58ba6a0--- /dev/null+++ b/changelog.d/4892.added.md@@ -0,0 +1 @@+Convention blocks for homography estimation (`find_homography_dlt` and its iterated and line-segment variants, the transfer errors), `RANSAC` and the polynomial and homogeneous solvers (`solve_quadratic`, `solve_cubic`, `solve_quartic`, `determinant_to_polynomial`, `null_vector_3x4`), with convention and wart pins; `solve_quartic` is added to the rendered API reference. The documented defects are linked to their issues (#4833, #4866β#4870, #4872β#4874, #4881, #4890, #4905) and not fixed here.diff --git a/docs/source/geometry.solvers.rst b/docs/source/geometry.solvers.rstindex d20b3981b..acd3cdef4 100644--- a/docs/source/geometry.solvers.rst+++ b/docs/source/geometry.solvers.rst@@ -18,6 +18,7 @@ Polynomial Solvers.. autofunction:: solve_quadratic.. autofunction:: solve_cubic+.. autofunction:: solve_quartic.. autofunction:: multiply_deg_one_poly.. autofunction:: multiply_deg_two_one_poly.. autofunction:: determinant_to_polynomialdiff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.pyindex dcf3da34f..dfda5b131 100644--- a/kornia/geometry/homography.py+++ b/kornia/geometry/homography.py@@ -34,6 +34,15 @@ def oneway_transfer_error() -> torch.Tensor:r"""Return transfer error in image 2 for correspondences given the homography matrix.+ Convention:+ - ``oneway_transfer_error(pts1, pts2, H)`` measures in image 2, between ``H`` applied to ``pts1`` and+ ``pts2``.+ - ``squared=True``, the default here and in :func:`symmetric_transfer_error`, returns the squared+ distance; :func:`line_segment_transfer_error_one_way` defaults to ``squared=False``.+ - Known defects: ``eps`` is added to the projective denominator and inside the square root, so the error+ depends on the scale of ``H``, and an exact match scores ``sqrt(eps)``, not 0, with ``squared=False``+ (`#4881 <https://github.com/kornia/kornia/issues/4881>`_).+Args:pts1: correspondences from the left images with shape(B, N, 2 or 3). If they are homogeneous, converted automatically.@@ -41,7 +50,7 @@ def oneway_transfer_error((B, N, 2 or 3). If they are homogeneous, converted automatically.H: Homographies with shape :math:`(B, 3, 3)`.squared: if True (default), the squared distance is returned.- eps: Small constant for safe sqrt.+ eps: added to the projective denominator and, with ``squared=False``, inside the square root.Returns:the computed distance with shape :math:`(B, N)`.@@ -99,6 +108,12 @@ def symmetric_transfer_error() -> torch.Tensor:r"""Return Symmetric transfer error for correspondences given the homography matrix.+ Convention:+ - Argument order as :func:`oneway_transfer_error`. The squared value is the image-2 error of ``H`` plus+ the image-1 error of ``H^-1``, and ``squared=False`` returns the square root of that sum.+ - Known defects: the ``eps`` defect of :func:`oneway_transfer_error` applies here too+ (`#4881 <https://github.com/kornia/kornia/issues/4881>`_).+Args:pts1: correspondences from the left images with shape(B, N, 2 or 3). If they are homogeneous, converted automatically.@@ -106,7 +121,7 @@ def symmetric_transfer_error((B, N, 2 or 3). If they are homogeneous, converted automatically.H: Homographies with shape :math:`(B, 3, 3)`.squared: if True (default), the squared distance is returned.- eps: Small constant for safe sqrt.+ eps: added to the projective denominator and, with ``squared=False``, inside the square root.Returns:the computed distance with shape :math:`(B, N)`. Rows whose homography is not invertible@@ -148,8 +163,14 @@ def line_segment_transfer_error_one_way() -> torch.Tensor:r"""Return transfer error in image 2 for line segment correspondences given the homography matrix.- Line segment end points are reprojected into image 2, and point-to-line error is calculated w.r.t. line,- induced by line segment in image 2. See :cite:`homolines2001` for details.+ Both endpoints of each image-1 segment are mapped into image 2 by ``H`` and scored against the line through+ the matching image-2 segment. See :cite:`homolines2001` for details.++ Convention:+ - Argument order and direction as :func:`oneway_transfer_error`.+ - Known defects: the image-2 line is not normalised, so the error is the mean perpendicular distance of+ the two mapped endpoints multiplied by the length of the image-2 segment, not a pixel distance+ (`#4867 <https://github.com/kornia/kornia/issues/4867>`_).Args:ls1: line segment correspondences from the left images with shape@@ -157,10 +178,10 @@ def line_segment_transfer_error_one_way(ls2: line segment correspondences from the right images with shape(B, N, 2, 2).H: Homographies with shape :math:`(B, 3, 3)`.- squared: if True (default is False), the squared distance is returned.+ squared: if True (default is False), the squared error is returned.Returns:- the computed distance with shape :math:`(B, N)`.+ the computed error with shape :math:`(B, N)`."""KORNIA_CHECK_SHAPE(H, ["B", "3", "3"])@@ -187,7 +208,19 @@ def find_homography_dlt() -> torch.Tensor:r"""Compute the homography matrix using the DLT formulation.- The linear system is solved by using the Weighted Least Squares Solution for the 4 Points algorithm.+ The weighted DLT system of four or more correspondences is solved with ``solver``.++ Convention:+ - ``H`` maps ``points1`` to ``points2``, ``points2 ~ H @ points1``, and is scaled so that+ ``H[2, 2] = 1``; :ref:`two-view-conventions` compares this with OpenCV.+ - ``weights`` multiply each correspondence's squared algebraic residual: a weight of 0 removes the+ correspondence from the equations, and only relative weights matter.+ - ``solver="lu"`` and ``"svd"`` give the same homography on exact data, to roundoff scaled by the+ conditioning of the system; on noisy data they solve different least-squares problems and differ.+ - Known defects: a zero-weight correspondence still enters the point normalisation, so on noisy data it+ moves the result (`#4890 <https://github.com/kornia/kornia/issues/4890>`_); and ``H`` is divided by+ ``H[2, 2] + 1e-8``, so ``H[2, 2]`` is not exactly 1, and it can be far from 1 when the true ``H[2, 2]``+ is small (`#4874 <https://github.com/kornia/kornia/issues/4874>`_).Args:points1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`.@@ -296,15 +329,21 @@ def find_homography_dlt_iterated() -> torch.Tensor:r"""Compute the homography matrix using the iteratively-reweighted least squares (IRWLS).- The linear system is solved by using the Reweighted Least Squares Solution for the 4 Points algorithm.+ Convention:+ - Direction and ``H[2, 2] = 1`` as :func:`find_homography_dlt`. Each solve after the first re-weights+ with ``exp(-e / (2 * soft_inl_th**2))`` of the unsquared symmetric transfer error ``e``.+ - Known defects: the exponent is linear, not quadratic, in ``e``, so ``soft_inl_th`` is not a pixel+ standard deviation (`#4870 <https://github.com/kornia/kornia/issues/4870>`_); those of+ :func:`find_homography_dlt` apply (`#4874 <https://github.com/kornia/kornia/issues/4874>`_,+ `#4890 <https://github.com/kornia/kornia/issues/4890>`_).Args:points1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`.points2: A set of points in the second image with a tensor shape :math:`(B, N, 2)`.weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.Used for the first iteration of the IRWLS.- soft_inl_th: Soft inlier threshold used for weight calculation.- n_iter: number of iterations.+ soft_inl_th: scale in the re-weighting kernel given above.+ n_iter: number of solves, including the initial one.Returns:the computed homography matrix with shape :math:`(B, 3, 3)`.@@ -323,9 +362,17 @@ def sample_is_valid_for_homography(points1: torch.Tensor, points2: torch.Tensor)Analogous to https://github.com/opencv/opencv/blob/4.x/modules/calib3d/src/usac/degeneracy.cpp#L88+ Convention:+ - :class:`~kornia.geometry.ransac.RANSAC` uses it to discard minimal samples for ``"homography"``. It+ checks only that the four triples of the first four points keep their orientation across the two+ views, so a mirror-image sample is rejected. A triple that is collinear in both views, for instance+ through a repeated point, counts as kept, so collinearity alone does not reject a sample.+Args:- points1: A set of points in the first image with a tensor shape :math:`(B, 4, 2)`.- points2: A set of points in the second image with a tensor shape :math:`(B, 4, 2)`.+ points1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`; only the first four+ points are used.+ points2: A set of points in the second image with a tensor shape :math:`(B, N, 2)`; only the first four+ points are used.Returns:Mask with the minimal sample is good for homography estimation :math:`(B)`.@@ -359,16 +406,27 @@ def sample_is_valid_for_homography(points1: torch.Tensor, points2: torch.Tensor)def find_homography_lines_dlt(ls1: torch.Tensor, ls2: torch.Tensor, weights: Optional[torch.Tensor] = None) -> torch.Tensor:- """Compute the homography matrix using the DLT formulation for line correspondences.+ """Compute the homography matrix from line segment correspondences with a DLT formulation.See :cite:`homolines2001` for details.- The linear system is solved by using the Weighted Least Squares Solution for the 4 Line correspondences algorithm.+ Convention:+ - ``H`` maps image-1 points to image-2 points, as in :func:`find_homography_dlt`. Each segment is a+ ``[start, end]`` pair of ``(x, y)`` points, and ``weights`` has one entry per segment.+ - Known defects: each segment's equations are built from endpoints of two different segments, not from+ its own start and end, so the estimate is correct only when the endpoints are themselves point+ correspondences, and a zero weight does not remove its segment+ (`#4866 <https://github.com/kornia/kornia/issues/4866>`_); the endpoints of a zero-weight segment still+ enter the point normalisation (`#4890 <https://github.com/kornia/kornia/issues/4890>`_); and the+ ``H[2, 2]`` scaling of :func:`find_homography_dlt` applies+ (`#4874 <https://github.com/kornia/kornia/issues/4874>`_).Args:- ls1: A set of line segments in the first image with a tensor shape :math:`(B, N, 2, 2)`.- ls2: A set of line segments in the second image with a tensor shape :math:`(B, N, 2, 2)`.- weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.+ ls1: A set of line segments in the first image with a tensor shape :math:`(B, N, 2, 2)`, or+ :math:`(N, 2, 2)`, which is treated as :math:`B = 1`.+ ls2: A set of line segments in the second image with a tensor shape :math:`(B, N, 2, 2)`, or+ :math:`(N, 2, 2)`, which is treated as :math:`B = 1`.+ weights: Tensor containing the weights per segment with a shape of :math:`(B, N)`.Returns:the computed homography matrix with shape :math:`(B, 3, 3)`.@@ -433,15 +491,23 @@ def find_homography_lines_dlt_iterated() -> torch.Tensor:r"""Compute the homography matrix using the iteratively-reweighted least squares (IRWLS) from line segments.- The linear system is solved by using the Reweighted Least Squares Solution for the 4 line segments algorithm.+ Convention:+ - As :func:`find_homography_dlt_iterated`, with :func:`find_homography_lines_dlt` as the solver and the+ unsquared error of :func:`line_segment_transfer_error_one_way` as ``e``.+ - Known defects: those of the three functions apply+ (`#4866 <https://github.com/kornia/kornia/issues/4866>`_,+ `#4867 <https://github.com/kornia/kornia/issues/4867>`_,+ `#4870 <https://github.com/kornia/kornia/issues/4870>`_,+ `#4874 <https://github.com/kornia/kornia/issues/4874>`_,+ `#4890 <https://github.com/kornia/kornia/issues/4890>`_).Args:ls1: A set of line segments in the first image with a tensor shape :math:`(B, N, 2, 2)`.ls2: A set of line segments in the second image with a tensor shape :math:`(B, N, 2, 2)`.- weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.+ weights: Tensor containing the weights per segment with a shape of :math:`(B, N)`.Used for the first iteration of the IRWLS.- soft_inl_th: Soft inlier threshold used for weight calculation.- n_iter: number of iterations.+ soft_inl_th: scale in the re-weighting kernel of :func:`find_homography_dlt_iterated`.+ n_iter: number of solves, including the initial one.Returns:the computed homography matrix with shape :math:`(B, 3, 3)`.diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.pyindex 2ed1f307f..73d0ed684 100644--- a/kornia/geometry/ransac.py+++ b/kornia/geometry/ransac.py@@ -42,14 +42,35 @@ __all__ = ["RANSAC"]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.+ - 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>`_).+Args:- model_type: type of model to estimate: "homography", "fundamental", "fundamental_7pt",+ model_type: type of model to estimate: "homography", "fundamental", "fundamental_7pt", "essential","homography_from_linesegments".- inliers_threshold: threshold for the correspondence to be an inlier.+ inl_th: inlier threshold, in the units given above.batch_size: number of generated samples at once.- max_iterations: maximum batches to generate. Actual number of models to try is ``batch_size * max_iterations``.+ 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_local_iterations: number of local optimization (polishing) iterations.+ max_lo_iters: number of local optimization (polishing) iterations."""@@ -70,13 +91,14 @@ class RANSAC(nn.Module):Args:model_type: type of model to estimate: "homography", "fundamental", "fundamental_7pt", "essential","homography_from_linesegments".- inl_th: threshold for the correspondence to be an inlier. Internally is squared.+ 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. Actual number of models to try is ``batch_size * max_iter``.+ 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.score_type: scoring method to use: "ransac" or "msac".- prosac_sampling: whether to use PROSAC sampling instead of random sampling.+ prosac_sampling: meant to select PROSAC sampling; it has no effect+ (`#4869 <https://github.com/kornia/kornia/issues/4869>`_).seed: optional random seed for reproducible results. If None, uses global random state."""@@ -148,7 +170,7 @@ class RANSAC(nn.Module):sample_size: number of samples to draw from the population.pop_size: size of the population to sample from.batch_size: number of sample sets to generate.- iteration: current iteration number (used for PROSAC sampling).+ iteration: current iteration number, added to ``seed`` when one is set.device: device to place the samples on.Returns:@@ -230,6 +252,7 @@ class RANSAC(nn.Module):- Best model- Inlier mask for the best model- Score of the best model+ - Number of inliers of the best model"""if len(kp1.shape) == 2:@@ -325,7 +348,11 @@ class RANSAC(nn.Module):weights: optional correspondence weights (not used currently).Raises:- ValueError: if input shapes are invalid or insufficient correspondences.+ 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."""if self.model_type in ["homography", "fundamental"]:@@ -352,13 +379,14 @@ class RANSAC(nn.Module):r"""Call main forward method to execute the RANSAC algorithm.Args:- kp1: source image keypoints :math:`(N, 2)`.- kp2: distance image keypoints :math:`(N, 2)`.+ 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``.weights: optional correspondences weights. Not used now.Returns:- - Estimated model, shape of :math:`(3, 3)`.- - The inlier/outlier mask, shape of :math:`(N,)`, where N is number of input correspondences.+ - 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."""self.validate_inputs(kp1, kp2, weights)diff --git a/kornia/geometry/solvers/homogeneous.py b/kornia/geometry/solvers/homogeneous.pyindex c2a38f6ec..602ee9687 100644--- a/kornia/geometry/solvers/homogeneous.py+++ b/kornia/geometry/solvers/homogeneous.py@@ -72,9 +72,11 @@ def null_vector_3x4(A: torch.Tensor) -> torch.Tensor:The computation uses the **4-D cross-product** (cofactor expansion):each component of :math:`\mathbf{v}` is a :math:`3 \times 3` determinant ofthe submatrix obtained by dropping the corresponding column of :math:`A`.- This is equivalent to computing the last right singular vector of :math:`A`- via SVD but replaces the SVD with 48 scalar multiplications and 20- additions β no LAPACK or cuSOLVER call is made.+ For a rank-3 :math:`A` this gives the last right singular vector up to scale+ and sign, but replaces the SVD with 48 scalar multiplications and 20+ additions β no LAPACK or cuSOLVER call is made. The sign follows the+ cofactor formula below (``[I | 0]`` gives ``[0, 0, 0, -1]``), and a lower+ rank gives the zero vector rather than a unit vector... math::@@ -106,7 +108,7 @@ def null_vector_3x4(A: torch.Tensor) -> torch.Tensor:Example:>>> A = torch.tensor([[[1., 0., 0., 0.],... [0., 1., 0., 0.],- ... [0., 0., 1., 0.]]]) # null vector is [0,0,0,1]+ ... [0., 0., 1., 0.]]]) # null vector is [0,0,0,-1]>>> v = null_vector_3x4(A) # shape (1, 4)>>> (A @ v.unsqueeze(-1)).squeeze(-1) # should be near zerotensor([[0., 0., 0.]])diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.pyindex bb8c6f2f4..a3ae2fad9 100644--- a/kornia/geometry/solvers/polynomial_solver.py+++ b/kornia/geometry/solvers/polynomial_solver.py@@ -32,6 +32,17 @@ def solve_quadratic(coeffs: torch.Tensor) -> torch.Tensor:.. math:: coeffs[0]x^2 + coeffs[1]x + coeffs[2] = 0+ Convention:+ - The coefficients of :func:`solve_quadratic`, :func:`solve_cubic` and :func:`solve_quartic` are batched+ ``(B, k + 1)`` for degree ``k``, highest degree first; :ref:`two-view-conventions` compares this with+ ``numpy.roots``.+ - Only real roots are returned, and a repeated root is repeated. A missing real root is reported as+ ``0.0``, which is indistinguishable from a root at 0, so count real roots from the discriminant when+ it matters.+ - For ``coeffs = [a, b, c]`` and ``D = b**2 - 4 * a * c``, ``solve_quadratic`` returns+ ``[(-b + sqrt(D)) / (2 * a), (-b - sqrt(D)) / (2 * a)]``, so the order flips with the sign of ``a``.+ - Known defects: ``a = 0`` returns non-finite values (`#4873 <https://github.com/kornia/kornia/issues/4873>`_).+Args:coeffs : The coefficients of quadratic equation :`(B, 3)`@@ -42,11 +53,6 @@ def solve_quadratic(coeffs: torch.Tensor) -> torch.Tensor:>>> coeffs = torch.tensor([[1., 4., 4.]])>>> roots = solve_quadratic(coeffs)- .. note::- In cases where a quadratic polynomial has only one real root, the output will be in the format- [real_root, 0]. And for the torch.complex roots should be represented as 0. This is done to maintain- a consistent output shape for all cases.-"""KORNIA_CHECK_SHAPE(coeffs, ["B", "3"])@@ -89,6 +95,13 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:.. math:: coeffs[0]x^3 + coeffs[1]x^2 + coeffs[2]x + coeffs[3] = 0+ Convention:+ - Coefficient layout and zero padding as :func:`solve_quadratic`. Three real roots are returned unsorted,+ and a single real root is in slot 0.+ - Known defects: with a zero leading coefficient, a linear equation gets the root ``1.0`` and+ ``bx^2 + d`` returns zeros+ (`#4873 <https://github.com/kornia/kornia/issues/4873>`_).+Args:coeffs : The coefficients cubic equation : `(B, 4)`@@ -100,9 +113,6 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:>>> roots = solve_cubic(coeffs).. note::- In cases where a cubic polynomial has only one or two real roots, the output for the non-real- roots should be represented as 0. Thus, the output for a single real root should be in the- format [real_root, 0, 0], and for two real roots, it should be [real_root_1, real_root_2, 0].``float16`` and ``bfloat16`` cubics are solved in ``float32`` and the roots are cast back tothe input dtype.@@ -286,6 +296,15 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:.. math:: coeffs[0]x^4 + coeffs[1]x^3 + coeffs[2]x^2 + coeffs[3]x + coeffs[4] = 0+ Convention:+ - Coefficient layout and zero padding as :func:`solve_quadratic`; the roots are unordered.+ - Known defects: the solver is not scale-invariant, so a quartic whose roots are all small can lose real+ roots and return values that are not roots (`#4833 <https://github.com/kornia/kornia/issues/4833>`_);+ a leading coefficient below ``1e-6`` in magnitude (``1e-12`` in float64) counts as zero whatever the+ other coefficients are, so a small multiple of a quartic is solved as a cubic and loses its roots+ (`#4905 <https://github.com/kornia/kornia/issues/4905>`_); and a row with a zero leading coefficient is+ passed to :func:`solve_cubic`, with its defects (`#4873 <https://github.com/kornia/kornia/issues/4873>`_).+Args:coeffs : The coefficients quartic equation : `(B, 5)`@@ -297,9 +316,6 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:>>> roots = solve_quartic(coeffs).. note::- In cases where a quartic polynomial has fewer than four real roots, the remaining entries- in the output are set to 0. Similarly, any non-real (complex) roots are represented as 0.- This is done to maintain a consistent output shape for all cases.For ``float16`` and ``bfloat16`` quartics, Ferrari intermediates are evaluated in ``float32``and the returned roots are cast back to the input dtype.@@ -2165,11 +2181,16 @@ def determinant_to_polynomial() -> torch.Tensor:r"""Represent the determinant by the 10th polynomial, used for 5PC solver [@nister2004efficient].+ Convention:+ - Each row of ``A`` holds two cubics (columns 0 to 3 and 4 to 7) and a quartic (columns 8 to 12) in+ ``z``, highest degree first. The returned coefficients are lowest degree first (``cs[i]`` multiplies+ ``z**i``), the reverse of the :func:`solve_quadratic` layout.+Args:- A: torch.Tensor :math:`(*, 3, 13)`.+ A: torch.Tensor :math:`(B, 3, 13)`.Returns:- a degree 10 poly, representing determinant (Eqn. 14 in the paper).+ a degree 10 poly of shape :math:`(B, 11)`, representing determinant (Eqn. 14 in the paper)."""B, device, dtype = A.shape[0], A.device, A.dtypediff --git a/tests/geometry/solvers/test_homogeneous.py b/tests/geometry/solvers/test_homogeneous.pyindex c206d6259..62c56b4f3 100644--- a/tests/geometry/solvers/test_homogeneous.py+++ b/tests/geometry/solvers/test_homogeneous.py@@ -246,3 +246,26 @@ class TestNullVector3x4(BaseTester):A = torch.rand(1, 3, 4, device=device, dtype=dtype)v = s.null_vector_3x4(A)assert v.shape == (1, 4)+++class TestConventionNullVector3x4(BaseTester):+ def test_convention_null_vector_3x4_cofactor_sign(self, device, dtype):+ def null(rows):+ return solvers.null_vector_3x4(torch.tensor(rows, device=device, dtype=dtype))++ def expect(values):+ return torch.tensor(values, device=device, dtype=dtype)++ identity = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]+ # v_j = (-1)^j det(A without column j): [I | 0] gives [0, 0, 0, -1], not the unit vector +e4, and the vector+ # is not normalised (2 [I | 0] gives -8 e4).+ self.assert_close(null(identity), expect([0.0, 0.0, 0.0, -1.0]))+ self.assert_close(null([[2.0 * x for x in row] for row in identity]), expect([0.0, 0.0, 0.0, -8.0]))+ # A generic integer matrix: the cofactors are exact in every dtype. |v| = sqrt(2896), where an SVD's null+ # vector has unit norm and an arbitrary sign.+ A = [[2.0, -1.0, 0.0, 3.0], [1.0, 3.0, -2.0, 0.0], [0.0, 1.0, 4.0, -1.0]]+ self.assert_close(null(A), expect([40.0, -16.0, -4.0, -32.0]))+ # Swapping two rows flips the sign; a rank-2 matrix gives the zero vector.+ self.assert_close(null([A[1], A[0], A[2]]), expect([-40.0, 16.0, 4.0, 32.0]))+ rank2 = [A[0], A[1], [a + 2.0 * b for a, b in zip(A[0], A[1])]]+ self.assert_close(null(rank2), expect([0.0, 0.0, 0.0, 0.0]))diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.pyindex 93734ac73..6a65e7fd3 100644--- a/tests/geometry/solvers/test_polynomial_solver.py+++ b/tests/geometry/solvers/test_polynomial_solver.py@@ -20,6 +20,7 @@ import pytestimport torchimport kornia.geometry.solvers as solver+from kornia.core.exceptions import ShapeErrorfrom testing.base import BaseTester@@ -1036,3 +1037,132 @@ class TestQuarticSolver(BaseTester):roots = solver.solve_quartic(coeffs)assert roots.min().item() < -1e5, roots+++# determinant_to_polynomial input: three rows of 13 coefficients, each two cubics (columns 0-3, 4-7) and a quartic+# (columns 8-12), highest degree first; generated by [[((7 * k + 3 * r) % 11 - 5) / 4 for k in range(13)] for r in+# range(3)], so no row, column or coefficient block is symmetric.+_DET_ROWS = [+ [-1.25, 0.5, -0.5, 1.25, 0.25, -0.75, 1.0, 0.0, -1.0, 0.75, -0.25, -1.25, 0.5],+ [-0.5, 1.25, 0.25, -0.75, 1.0, 0.0, -1.0, 0.75, -0.25, -1.25, 0.5, -0.5, 1.25],+ [0.25, -0.75, 1.0, 0.0, -1.0, 0.75, -0.25, -1.25, 0.5, -0.5, 1.25, 0.25, -0.75],+]+++def _polyval(coeffs: list, z: float) -> float:+ """Evaluate coefficients given highest degree first."""+ out = 0.0+ for c in coeffs:+ out = out * z + c+ return out+++class TestConventionPolynomialSolvers(BaseTester):+ @pytest.mark.parametrize(+ "coeffs, expected",+ [+ ([1.0, -3.0, 2.0], [2.0, 1.0]), # two real roots+ ([1.0, 0.0, 1.0], [0.0, 0.0]), # x^2 + 1: no real root, both slots are 0.0+ ([1.0, -3.0, 0.0], [3.0, 0.0]), # x^2 - 3x: a genuine root at 0 looks the same as a padded slot+ ],+ )+ def test_convention_solve_quadratic_real_roots_zero_padded(self, coeffs, expected, device, dtype):+ # Only real roots are returned; a missing real root is reported as 0.0 (a design choice, not NaN).+ out = solver.solve_quadratic(torch.tensor([coeffs], device=device, dtype=dtype))+ self.assert_close(out, torch.tensor([expected], device=device, dtype=dtype))++ @pytest.mark.parametrize(+ "fn, coeffs, roots",+ [+ # 2x^2 - 5x - 3 = (2x + 1)(x - 3)+ (solver.solve_quadratic, [2.0, -5.0, -3.0], [-0.5, 3.0]),+ # -2 (x - 3)(x + 0.5)(x - 1.25)+ (solver.solve_cubic, [-2.0, 7.5, -3.25, -3.75], [-0.5, 1.25, 3.0]),+ # 3 (x - 4)(x + 2)(x - 1)(x + 0.5)+ (solver.solve_quartic, [3.0, -7.5, -22.5, 15.0, 12.0], [-2.0, -0.5, 1.0, 4.0]),+ ],+ ids=["quadratic", "cubic", "quartic"],+ )+ def test_convention_solver_coefficient_layout_highest_degree_first(self, fn, coeffs, roots, device, dtype):+ # coeffs[0] multiplies the highest power, as in numpy.roots; read lowest degree first, the same rows have+ # the reciprocal roots (for instance 1/3 and -2 for the quadratic). Rows are batched (B, k + 1).+ out = fn(torch.tensor([coeffs], device=device, dtype=dtype))+ self.assert_close(out.sort(dim=-1).values, torch.tensor([roots], device=device, dtype=dtype))+ with pytest.raises(ShapeError):+ fn(torch.tensor(coeffs, device=device, dtype=dtype))++ def test_convention_solver_root_multiplicity_and_order(self, device, dtype):+ def solve(fn, coeffs):+ return fn(torch.tensor([coeffs], device=device, dtype=dtype))++ def expect(values):+ return torch.tensor([values], device=device, dtype=dtype)++ # solve_quadratic returns [(-b + sqrt(D)) / (2a), (-b - sqrt(D)) / (2a)]: the larger root first for a > 0,+ # the smaller first for a < 0 (roots 3 and -0.5 both times).+ self.assert_close(solve(solver.solve_quadratic, [1.0, -2.5, -1.5]), expect([3.0, -0.5]))+ self.assert_close(solve(solver.solve_quadratic, [-1.0, 2.5, 1.5]), expect([-0.5, 3.0]))+ # A repeated root is repeated, not padded.+ self.assert_close(solve(solver.solve_quadratic, [1.0, -6.0, 9.0]), expect([3.0, 3.0]))+ cubic = solve(solver.solve_cubic, [1.0, -3.0, 0.0, 4.0]) # (x - 2)^2 (x + 1)+ self.assert_close(cubic.sort(dim=-1).values, expect([-1.0, 2.0, 2.0]))+ # A single real root is in slot 0 of solve_cubic, followed by the zero padding: (x - 2)(x^2 + 1).+ self.assert_close(solve(solver.solve_cubic, [1.0, -2.0, 1.0, -2.0]), expect([2.0, 0.0, 0.0]))++ def test_convention_determinant_to_polynomial_output_lowest_degree_first(self, device, dtype):+ cs = solver.determinant_to_polynomial(torch.tensor([_DET_ROWS], device=device, dtype=dtype))+ assert cs.shape == (1, 11)+ cs = cs[0].cpu().double()+ for z in (0.6, -1.3):+ # The determinant of the 3 x 3 matrix of the rows' polynomials, each read highest degree first.+ entries = [[_polyval(r[0:4], z), _polyval(r[4:8], z), _polyval(r[8:13], z)] for r in _DET_ROWS]+ det = torch.linalg.det(torch.tensor(entries, dtype=torch.float64))+ # cs[i] multiplies z**i, the reverse of the solve_* layout; read highest degree first it is another+ # polynomial (0.39 instead of 0.94 at z = 0.6).+ ascending = sum(cs[i] * z**i for i in range(11))+ descending = sum(cs[10 - i] * z**i for i in range(11))+ self.assert_close(ascending, det, rtol=1e-6, atol=1e-6)+ assert (descending - det).abs() > 0.1++ @pytest.mark.parametrize(+ "fn, coeffs, expected",+ [+ (solver.solve_cubic, [0.0, 0.0, 2.0, -6.0], [1.0, 0.0, 0.0]), # 2x - 6: the root is 3+ (solver.solve_cubic, [0.0, 1.0, 0.0, -4.0], [0.0, 0.0, 0.0]), # x^2 - 4: the roots +-2 are lost+ (solver.solve_quartic, [0.0, 0.0, 0.0, 2.0, -6.0], [1.0, 0.0, 0.0, 0.0]), # through solve_cubic+ (solver.solve_quadratic, [0.0, 2.0, -6.0], None), # 2x - 6: non-finite+ ],+ ids=["cubic_linear", "cubic_bx2_plus_d", "quartic_linear", "quadratic_linear"],+ )+ def test_wart_solve_cubic_linear_returns_one_4873(self, fn, coeffs, expected, device, dtype):+ # #4873: a zero leading coefficient is not handled. solve_cubic writes the constant 1.0 for any linear+ # equation and drops the roots of bx^2 + d, solve_quartic inherits that, and solve_quadratic divides by+ # zero. Once fixed, 2x - 6 gives the root 3 and x^2 - 4 gives +-2.+ out = fn(torch.tensor([coeffs], device=device, dtype=dtype))+ if expected is None:+ assert not bool(torch.isfinite(out).all())+ else:+ self.assert_close(out, torch.tensor([expected], device=device, dtype=dtype))++ def test_wart_solve_quartic_small_scale_4833(self, device, dtype):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("this row's 2e-11 and -4.2e-08 coefficients underflow float16 and keep 3 digits in bfloat16")+ # #4833: x^4 - 0.009x^3 + 3e-05x^2 - 4.2e-08x + 2e-11 = (x - 0.001)(x - 0.002)(x^2 - 0.006x + 1e-05) has+ # the real roots 1e-3 and 2e-3, but the solver is not scale-invariant and returns neither to 1 %.+ coeffs = torch.tensor([[1.0, -0.009, 3e-05, -4.2e-08, 2e-11]], device=device, dtype=dtype)+ out = solver.solve_quartic(coeffs)+ for root in (1e-3, 2e-3):+ assert (out - root).abs().min() > 1e-2 * root++ def test_wart_solve_quartic_absolute_leading_tolerance_4905(self, device, dtype):+ # (x - 1)(x - 2)(x - 3)(x - 4), and the same row times a power of two (exact in every dtype) that brings the+ # leading coefficient below the fallback tolerance (1e-6, or 1e-12 in float64).+ row = torch.tensor([[1.0, -10.0, 35.0, -50.0, 24.0]], device=device, dtype=dtype)+ scale = 2.0**-41 if dtype == torch.float64 else 2.0**-21+ roots = torch.tensor([[1.0, 2.0, 3.0, 4.0]], device=device, dtype=dtype)+ self.assert_close(solver.solve_quartic(row).sort(dim=-1).values, roots)+ # #4905: the tolerance is absolute, so the scaled row is solved as the cubic that remains without x^4, and+ # the roots 2, 3 and 4 are lost. Once the test is relative, both rows give the same roots.+ out = solver.solve_quartic(row * scale)+ for root in (2.0, 3.0, 4.0):+ assert (out - root).abs().min() > 0.5diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.pyindex e0150fb43..891c15a0a 100644--- a/tests/geometry/test_homography.py+++ b/tests/geometry/test_homography.py@@ -606,3 +606,383 @@ class TestFindHomographyDLTIter(BaseTester):self.assert_close(kornia.geometry.transform_points(dst_homo_src, points_src[:, :-1]), points_dst[:, :-1], rtol=1e-3, atol=1e-3)+++# Planar fixture for the convention pins: twelve generic image-1 points, no two sharing a coordinate, and a fixed+# homography _H_TRUE (a mild projective warp) whose entries are all distinct and non-zero, so swapping the images,+# transposing or inverting H changes every quantity derived from it. The pins compute p2 = _H_TRUE(p1) themselves.+_PLANAR_P1 = [+ [318.8, 279.9], [194.8, 137.7], [316.9, 316.9], [362.2, 154.2], [153.2, 90.1], [325.8, 259.0],+ [204.8, 129.7], [447.6, 170.0], [294.1, 216.2], [158.5, 95.9], [258.3, 329.9], [242.0, 87.6],+] # fmt: skip+_H_TRUE = [+ [1.034685, -0.04160598, -63.61482],+ [0.1039753, 1.135451, -62.87412],+ [2.851519e-04, 1.404178e-04, 1.0],+]+_HALF_DLT = (+ "the homography DLTs form the normalised points, the design and normal matrices and the denormalisation in the "+ "input dtype, so in float16/bfloat16 an exact fit misses by up to several pixels"+)+_F16_LU = (+ "find_homography_dlt's solver='lu' path casts its unnormalised float32 solution back to float16, where the "+ "denormalisation can overflow to inf/NaN depending on rounding (the float16 manifest carries test_clean_points_lu "+ "for the same reason, #4153)"+)+_HALF_POINTS = (+ "kornia evaluates the transfer errors in the input dtype, and the fixture's pixel coordinates carry up to 2 px "+ "of rounding in bfloat16 (0.25 px in float16), the size of the offsets these pins measure"+)+_HALF_LINES = (+ "line_segment_transfer_error_one_way builds the unnormalised image-2 line in the input dtype; its constant term "+ "is of order (pixel coordinate)**2, which overflows float16 and which bfloat16 cannot resolve"+)+++def _skip_half(dtype: torch.dtype, reason: str) -> None:+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip(reason)+++def _planar(device, dtype):+ """Twelve exact planar matches ``p2 = H(p1)``, generated in float64 on the CPU and cast, and ``H``."""+ p1 = torch.tensor([_PLANAR_P1], dtype=torch.float64)+ H = torch.tensor([_H_TRUE], dtype=torch.float64)+ p2 = kornia.geometry.transform_points(H, p1)+ return p1.to(device, dtype), p2.to(device, dtype), H.to(device, dtype)+++def _inverse(H: torch.Tensor) -> torch.Tensor:+ """H^-1 scaled so that its [2, 2] entry is 1, computed in float64 on the CPU."""+ H_inv = torch.linalg.inv(H.cpu().double())+ return (H_inv / H_inv[..., 2:, 2:]).to(H.device, H.dtype)+++def _transfer_max(H: torch.Tensor, src: torch.Tensor, dst: torch.Tensor) -> torch.Tensor:+ return (kornia.geometry.transform_points(H, src) - dst).abs().max()+++def _unit_normal(seg: torch.Tensor) -> torch.Tensor:+ """Unit normal of the segment ``seg = [start, end]``, shape ``(..., 2, 2)`` -> ``(..., 2)``."""+ d = seg[..., 1, :] - seg[..., 0, :]+ return torch.stack([-d[..., 1], d[..., 0]], -1) / d.norm(dim=-1, keepdim=True)+++class TestConventionHomography(BaseTester):+ def test_convention_find_homography_dlt_maps_p1_to_p2(self, device, dtype):+ if dtype == torch.float16:+ pytest.skip(_F16_LU)+ p1, p2, H_true = _planar(device, dtype)+ H = find_homography_dlt(p1, p2)+ # points2 ~ H @ points1 (OpenCV's findHomography(src, dst) order). The control: applying H to points2 misses+ # points1 by about 195 px.+ assert _transfer_max(H, p1, p2) < 0.05 * _transfer_max(H, p2, p1)+ self.assert_close(H[..., 2, 2], torch.ones_like(H[..., 2, 2]))+ if dtype in (torch.float32, torch.float64): # half precision resolves the direction but not the entries+ self.assert_close(H, H_true, rtol=1e-4, atol=1e-4)+ # Relabelling the images returns the inverse.+ self.assert_close(find_homography_dlt(p2, p1), _inverse(H_true), rtol=1e-4, atol=1e-4)+ # Four or more correspondences: three are rejected before any solve.+ with pytest.raises(Exception):+ find_homography_dlt(p1[:, :3], p2[:, :3])++ def test_convention_find_homography_dlt_lu_equals_svd(self, device, dtype):+ _skip_half(dtype, _HALF_DLT)+ p1, p2, _ = _planar(device, dtype)+ tol = 1e-8 if dtype == torch.float64 else 5e-2 # pixels+ # Twelve points take the normal equations; four take solver="lu"'s QR-gauge path.+ for n in (12, 4):+ H_lu = find_homography_dlt(p1[:, :n], p2[:, :n], solver="lu")+ H_svd = find_homography_dlt(p1[:, :n], p2[:, :n], solver="svd")+ assert _transfer_max(H_svd, p1, p2) < tol+ diff = (kornia.geometry.transform_points(H_lu, p1) - kornia.geometry.transform_points(H_svd, p1)).abs()+ assert diff.max() < tol++ @pytest.mark.parametrize("solver", ["lu", "svd"])+ def test_convention_find_homography_dlt_zero_weight_drops_point(self, solver, device, dtype):+ _skip_half(dtype, _HALF_DLT)+ p1, p2, _ = _planar(device, dtype)+ p2_out = p2.clone()+ p2_out[0, 5] += torch.tensor([40.0, -25.0], device=device, dtype=dtype) # one correspondence off by 47 px+ clean = torch.arange(12, device=device) != 5+ tol = 1e-8 if dtype == torch.float64 else 1e-2++ def clean_error(H):+ return _transfer_max(H, p1[:, clean], p2[:, clean])++ # On exact data: unweighted, the outlier pulls H by about 12 px on the clean points, and a weight of 0 removes+ # its equations (on noisy data it still moves H through the point normalisation, #4890).+ assert clean_error(find_homography_dlt(p1, p2_out, None, solver)) > 5.0+ w_zero = torch.ones(1, 12, device=device, dtype=dtype)+ w_zero[0, 5] = 0.0+ assert clean_error(find_homography_dlt(p1, p2_out, w_zero, solver)) < tol+ # Only relative weights matter: w and 5 w give the same H, while changing one weight relative to the+ # others moves it by pixels.+ w = torch.tensor([[1.0, 0.5, 2.0, 1.5, 0.75, 0.3, 1.25, 1.0, 0.5, 2.0, 1.5, 1.0]], device=device, dtype=dtype)+ w_other = w.clone()+ w_other[0, 5] = 0.9+ mapped = kornia.geometry.transform_points(find_homography_dlt(p1, p2_out, w, solver), p1)+ assert _transfer_max(find_homography_dlt(p1, p2_out, 5.0 * w, solver), p1, mapped) < tol+ assert _transfer_max(find_homography_dlt(p1, p2_out, w_other, solver), p1, mapped) > 1.0++ def test_convention_find_homography_lines_dlt_direction_and_layout(self, device, dtype):+ _skip_half(dtype, _HALF_DLT)+ p1, p2, _ = _planar(device, dtype)+ # Six segments (B, N, 2, 2) = [start, end] x (x, y), whose endpoints are point correspondences.+ ls1, ls2 = p1.reshape(1, 6, 2, 2), p2.reshape(1, 6, 2, 2)+ tol = 1e-8 if dtype == torch.float64 else 1e-2+ H = find_homography_lines_dlt(ls1, ls2)+ # Same direction as find_homography_dlt: H maps image-1 points onto image 2.+ assert _transfer_max(H, p1, p2) < tol+ assert _transfer_max(H, p2, p1) > 100.0+ self.assert_close(H[..., 2, 2], torch.ones_like(H[..., 2, 2]))+ mapped = kornia.geometry.transform_points(H, p1)+ # Unbatched (N, 2, 2) input is B = 1.+ H_unbatched = find_homography_lines_dlt(ls1[0], ls2[0])+ assert H_unbatched.shape == (1, 3, 3)+ assert _transfer_max(H_unbatched, p1, mapped) < tol+ # The control for the layout: the same numbers read as (x, y) x [start, end] fit a different map.+ assert _transfer_max(find_homography_lines_dlt(ls1.transpose(-2, -1), ls2.transpose(-2, -1)), p1, p2) > 100.0+ # weights has one entry per segment.+ assert (+ _transfer_max(find_homography_lines_dlt(ls1, ls2, torch.ones(1, 6, device=device, dtype=dtype)), p1, mapped)+ < tol+ )++ @pytest.mark.parametrize("error_fn", ["oneway", "symmetric", "line"])+ def test_convention_transfer_errors_argument_order_and_squared(self, error_fn, device, dtype):+ _skip_half(dtype, _HALF_LINES if error_fn == "line" else _HALF_POINTS)+ p1, p2, H = _planar(device, dtype)+ others = torch.arange(12, device=device) != 5+ if error_fn == "line":+ ls1, ls2 = p1.reshape(1, 6, 2, 2), p2.reshape(1, 6, 2, 2)+ # (ls1, ls2, H) with H mapping image 1 to image 2; the swapped call is far off.+ exact = line_segment_transfer_error_one_way(ls1, ls2, H)+ assert exact.max() < 1e-3 * line_segment_transfer_error_one_way(ls2, ls1, H).min()+ # squared=False is the default here, unlike the two point errors.+ ls2_off = ls2.clone()+ ls2_off[0, 2] += 3.0 * _unit_normal(ls2[0, 2]) # segment 2 moved 3 px off its line in image 2+ default = line_segment_transfer_error_one_way(ls1, ls2_off, H)+ unsquared = line_segment_transfer_error_one_way(ls1, ls2_off, H, squared=False)+ squared = line_segment_transfer_error_one_way(ls1, ls2_off, H, squared=True)+ self.assert_close(default, unsquared)+ self.assert_close(squared, unsquared**2)+ assert (squared - unsquared)[0, 2] > 1.0+ return+ p2_off = p2.clone()+ p2_off[0, 5] += torch.tensor([3.0, -4.0], device=device, dtype=dtype) # match 5 moved 5 px in image 2+ if error_fn == "oneway":+ # (pts1, pts2, H) measures in image 2 between H(pts1) and pts2; squared=True is the default.+ default = oneway_transfer_error(p1, p2_off, H)+ self.assert_close(default[0, 5], torch.tensor(25.0, device=device, dtype=dtype))+ self.assert_close(oneway_transfer_error(p1, p2_off, H, squared=False)[0, 5], default.new_tensor(5.0))+ assert default[0, others].max() < 1e-6+ assert oneway_transfer_error(p2_off, p1, H).min() > 1e3+ return+ # The squared symmetric error is the image-2 error of H plus the image-1 error of H^-1, squared=True by+ # default, and squared=False is the square root of that sum (not the sum of the two distances).+ default = symmetric_transfer_error(p1, p2_off, H)+ there_and_back = oneway_transfer_error(p1, p2_off, H) + oneway_transfer_error(p2_off, p1, _inverse(H))+ self.assert_close(default, there_and_back)+ unsquared = symmetric_transfer_error(p1, p2_off, H, squared=False)+ self.assert_close(unsquared[0, 5], default[0, 5].sqrt())+ assert default[0, 5] > 50.0 and default[0, others].max() < 1e-6+ assert symmetric_transfer_error(p2_off, p1, H).min() > 1e3++ def test_convention_sample_is_valid_for_homography_rejects_reflection(self, device, dtype):+ def valid(pts1, pts2):+ t = torch.tensor([pts1], device=device, dtype=dtype), torch.tensor([pts2], device=device, dtype=dtype)+ return bool(sample_is_valid_for_homography(*t)[0])++ view1 = [[10.0, 20.0], [70.0, 30.0], [60.0, 90.0], [15.0, 75.0]]+ view2 = [[12.0, 18.0], [80.0, 35.0], [66.0, 99.0], [11.0, 70.0]]+ mirrored = [[100.0 - x, y] for x, y in view2]+ # The first four points must keep the orientation of all four triples across the views.+ assert valid(view1, view2)+ assert valid(view2, view1)+ assert not valid(view1, mirrored)+ # Collinearity is not checked: a triple collinear in both views passes (collinear in one view only fails),+ # and so does a sample that repeats a point.+ collinear1 = [[10.0, 20.0], [30.0, 50.0], [50.0, 80.0], [15.0, 75.0]]+ collinear2 = [[12.0, 18.0], [32.0, 28.0], [52.0, 38.0], [11.0, 70.0]]+ assert valid(collinear1, collinear2)+ assert not valid(collinear1, view2)+ assert valid([*view1[:3], view1[0]], [*view2[:3], view2[0]])+ # Points after the fourth are ignored.+ assert valid([*view1, [1000.0, -7.0]], [*view2, [-5.0, 400.0]])+ mask = sample_is_valid_for_homography(+ torch.tensor([view1] * 3, device=device, dtype=dtype), torch.tensor([view2] * 3, device=device, dtype=dtype)+ )+ assert mask.dtype == torch.bool and mask.shape == (3,)++ @pytest.mark.parametrize("model", ["points", "lines"])+ def test_convention_find_homography_dlt_iterated_n_iter_counts_solves(self, model, device, dtype, monkeypatch):+ if model == "points" and dtype == torch.float16:+ pytest.skip(_F16_LU)+ p1, p2, _ = _planar(device, dtype)+ if model == "points":+ name, iterated, args = "find_homography_dlt", find_homography_dlt_iterated, (p1, p2)+ else:+ name = "find_homography_lines_dlt"+ iterated, args = find_homography_lines_dlt_iterated, (p1.reshape(1, 6, 2, 2), p2.reshape(1, 6, 2, 2))+ plain = getattr(kornia.geometry.homography, name)+ weights = torch.ones(1, args[0].shape[1], device=device, dtype=dtype)+ calls = []++ def spy(*a, **k):+ calls.append(1)+ return plain(*a, **k)++ monkeypatch.setattr(kornia.geometry.homography, name, spy)+ # n_iter counts the solves, the initial one included, so n_iter=1 is the plain solver.+ H1 = iterated(*args, weights, n_iter=1)+ assert len(calls) == 1+ assert torch.equal(H1, plain(*args, weights))+ calls.clear()+ H = iterated(*args, weights, n_iter=3)+ assert len(calls) == 3+ if dtype in (torch.float32, torch.float64):+ # Same direction as the plain solver; half precision does not hold it through the re-weighted solves on+ # this fixture.+ assert _transfer_max(H, p1, p2) < 1e-2+ assert _transfer_max(H, p2, p1) > 100.0++ def test_wart_find_homography_lines_dlt_endpoint_pairing_4866(self, device, dtype):+ _skip_half(dtype, _HALF_LINES)+ p1, p2, H_true = _planar(device, dtype)+ ls1, ls2 = p1.reshape(1, 6, 2, 2), p2.reshape(1, 6, 2, 2)+ # Slide every image-2 endpoint along its segment's true line: H_true still maps each image-1 segment onto its+ # image-2 line, but the endpoints are no longer point correspondences.+ d = ls2[:, :, 1] - ls2[:, :, 0]+ slid = torch.stack([ls2[:, :, 0] + 0.3 * d, ls2[:, :, 1] + 0.25 * d], dim=2)+ assert line_segment_transfer_error_one_way(ls1, slid, H_true).max() < 1e-2+ # #4866: the equations of segment i use flattened points i and N + i, so the estimate misses by thousands+ # of pixels here. Once the endpoints are paired per segment it recovers H_true.+ assert _transfer_max(find_homography_lines_dlt(ls1, slid), p1, p2) > 100.0+ # For the same reason a zero weight does not remove its segment: the outlier still moves the estimate.+ ls2_out = ls2.clone()+ ls2_out[0, 3] += torch.tensor([[35.0, -20.0], [-15.0, 30.0]], device=device, dtype=dtype)+ weights = torch.ones(1, 6, device=device, dtype=dtype)+ weights[0, 3] = 0.0+ clean = (torch.arange(12, device=device) != 6) & (torch.arange(12, device=device) != 7)+ assert _transfer_max(find_homography_lines_dlt(ls1, ls2_out, weights), p1[:, clean], p2[:, clean]) > 10.0++ def test_wart_line_segment_error_scales_with_length_4867(self, device, dtype):+ _skip_half(dtype, _HALF_LINES)+ p1, _, H = _planar(device, dtype)+ short = p1[:, [1, 7]].reshape(1, 1, 2, 2)+ mid = short.mean(dim=2, keepdim=True)+ errors, lengths = [], []+ for seg1 in (short, mid + 2.0 * (short - mid)): # the same line, the segment twice as long+ seg2 = kornia.geometry.transform_points(H, seg1.reshape(1, 2, 2)).reshape(1, 1, 2, 2)+ offset = seg2 + 3.0 * _unit_normal(seg2)[..., None, :] # moved 3 px off its line in image 2+ errors.append(line_segment_transfer_error_one_way(seg1, offset, H))+ lengths.append((seg2[..., 1, :] - seg2[..., 0, :]).norm(dim=-1))+ # #4867: the image-2 line is not normalised, so the error is 3 px times the image-2 segment length (223 and+ # 447 px here), not 3 px. Once the line is normalised both errors are 3.+ for error, length in zip(errors, lengths):+ self.assert_close(error / length, torch.full_like(error, 3.0))+ assert errors[1] > 1.9 * errors[0]++ @pytest.mark.parametrize("model", ["points", "lines"])+ def test_wart_find_homography_dlt_iterated_weight_unsquared_4870(self, model, device, dtype, monkeypatch):+ if model == "points" and dtype == torch.float16:+ pytest.skip(_F16_LU)+ if model == "lines":+ _skip_half(dtype, _HALF_LINES)+ p1, p2, _ = _planar(device, dtype)+ if model == "points":+ p2_off = p2.clone()+ p2_off[0, 5] += torch.tensor([6.0, -4.0], device=device, dtype=dtype)+ name, iterated, args, k = "find_homography_dlt", find_homography_dlt_iterated, (p1, p2_off), 5++ def error(H):+ return symmetric_transfer_error(p1, p2_off, H, squared=False)++ else:+ ls1, ls2 = p1.reshape(1, 6, 2, 2), p2.reshape(1, 6, 2, 2).clone()+ ls2[0, 2] += 0.05 * _unit_normal(ls2[0, 2])+ name, iterated, args, k = "find_homography_lines_dlt", find_homography_lines_dlt_iterated, (ls1, ls2), 2++ def error(H):+ return line_segment_transfer_error_one_way(ls1, ls2, H, squared=False)++ plain = getattr(kornia.geometry.homography, name)+ weights = torch.ones(1, args[0].shape[1], device=device, dtype=dtype)+ # soft_inl_th is set from the moved correspondence's first-solve error e_k, so that its weight under the+ # linear kernel is exp(-1/2) whatever the error's scale.+ sigma = float(error(plain(*args, weights))[0, k].sqrt())+ calls = []++ def spy(a, b, w=None, *rest):+ H = plain(a, b, w, *rest)+ calls.append((w, H))+ return H++ monkeypatch.setattr(kornia.geometry.homography, name, spy)+ iterated(*args, weights, soft_inl_th=sigma, n_iter=2)+ assert len(calls) == 2+ e = error(calls[0][1])+ # #4870: the second solve weights each correspondence by exp(-e / (2 sigma^2)) with the unsquared error e,+ # which for the moved correspondence is far from the Gaussian exp(-e^2 / (2 sigma^2)).+ self.assert_close(calls[1][0], torch.exp(-e / (2.0 * sigma**2)))+ assert (calls[1][0] - torch.exp(-(e**2) / (2.0 * sigma**2)))[0, k].abs() > 0.1++ def test_wart_transfer_error_exact_match_is_sqrt_eps_4881(self, device, dtype):+ _skip_half(+ dtype,+ "eps=1e-8 is below float16's subnormal range, and in bfloat16 the fixture's matches are 2 px from exact",+ )+ p1, p2, H = _planar(device, dtype)+ # #4881: eps is added inside the square root, so an exact match scores sqrt(1e-8) = 1e-4, not 0 ...+ assert oneway_transfer_error(p1, p2, H, squared=False).min() > 5e-5+ assert symmetric_transfer_error(p1, p2, H, squared=False).min() > 5e-5+ if dtype == torch.float64:+ assert oneway_transfer_error(p1, p2, H, squared=False, eps=0.0).max() < 1e-9+ # ... and to the projective denominator, so the error depends on the scale of H: 1e-8 H scores tens of+ # pixels on the same exact matches.+ assert oneway_transfer_error(p1, p2, 1e-8 * H, squared=False).min() > 1.0++ @pytest.mark.parametrize("model", ["points", "lines"])+ def test_wart_find_homography_dlt_h22_eps_divisor_4874(self, model, device, dtype):+ _skip_half(dtype, _HALF_DLT)+ p1, p2, _ = _planar(device, dtype)+ # The same fixture with the true H[2, 2] set to 1e-6 (a mild warp whose origin maps far out), exact matches.+ H_small = torch.tensor([_H_TRUE], dtype=torch.float64)+ H_small[0, 2, 2] = 1e-6+ p2_small = kornia.geometry.transform_points(H_small, p1.cpu().double()).to(device, dtype)++ def fit(dst):+ if model == "points":+ return find_homography_dlt(p1, dst, solver="svd")+ return find_homography_lines_dlt(p1.reshape(1, 6, 2, 2), dst.reshape(1, 6, 2, 2))++ # With the true H[2, 2] = 1 the returned entry is 1.+ assert (fit(p2)[0, 2, 2] - 1.0).abs() < 1e-4+ # #4874: H is divided by H[2, 2] + 1e-8, and the unnormalised entry here is a few 1e-6, so the returned+ # H[2, 2] misses 1 by about 2e-3. Once the divisor is H[2, 2] itself, it is 1.+ assert (fit(p2_small)[0, 2, 2] - 1.0).abs() > 1e-3++ @pytest.mark.parametrize("solver", ["lu", "svd"])+ def test_wart_find_homography_dlt_zero_weight_moves_normalisation_4890(self, solver, device, dtype):+ _skip_half(dtype, _HALF_DLT)+ p1, p2, _ = _planar(device, dtype)+ # 3-px noise on the twelve matches, generated by+ # g = torch.Generator().manual_seed(0)+ # torch.round(3 * torch.randn(1, 12, 2, generator=g, dtype=torch.float64), decimals=1)+ noise = [+ [-6.9, -1.1], [-3.2, 3.0], [-2.7, -3.8], [-1.9, -2.6], [0.7, 2.2], [-4.0, 3.9],+ [-4.5, -2.1], [1.6, -2.9], [2.0, 3.1], [0.5, -2.2], [-2.2, 0.3], [-5.2, 3.1],+ ] # fmt: skip+ p2 = p2 + torch.tensor([noise], device=device, dtype=dtype)+ # A far correspondence with weight 0, appended to the twelve.+ far1 = torch.cat([p1, torch.tensor([[[2000.0, 1500.0]]], device=device, dtype=dtype)], 1)+ far2 = torch.cat([p2, torch.tensor([[[-800.0, 2400.0]]], device=device, dtype=dtype)], 1)+ weights = torch.ones(1, 13, device=device, dtype=dtype)+ weights[0, 12] = 0.0+ H_weighted = find_homography_dlt(far1, far2, weights, solver)+ H_dropped = find_homography_dlt(p1, p2, None, solver)+ # #4890: the zero-weight correspondence leaves the equations but still enters the Hartley normalisation, so+ # on noisy data it moves H (by 0.08 px with solver="lu" and 0.25 px with "svd" here). Once the normalisation+ # uses the weights, the two estimates agree to roundoff.+ assert _transfer_max(H_weighted, p1, kornia.geometry.transform_points(H_dropped, p1)) > 1e-2diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.pyindex 72a618226..79af23a53 100644--- a/tests/geometry/test_ransac.py+++ b/tests/geometry/test_ransac.py@@ -19,7 +19,9 @@import pytestimport torch+import korniafrom kornia.geometry import RANSAC, transform_points+from kornia.geometry.conversions import axis_angle_to_rotation_matrix, convert_points_from_homogeneousfrom kornia.geometry.epipolar import find_fundamental, project_to_essential, sampson_epipolar_distancefrom testing.base import BaseTester@@ -523,3 +525,270 @@ class TestRANSACEssential(BaseTester):return model(p1, p2)[0]self.gradcheck(gradfun, (points1, points2), fast_mode=False, requires_grad=(True, False, False))+++# Sixteen exact planar matches for the convention pins. _MATCHES_1 is an asymmetric 4 x 4 lattice with a per-point+# diagonal jitter, generated by+# torch.stack(torch.meshgrid(torch.tensor([160., 230., 330., 440.]), torch.tensor([95., 150., 240., 320.]),+# indexing="xy"), -1).reshape(16, 2) + torch.linspace(0, 3, 16)[:, None]+# and _H_TRUE is a fixed homography (a mild projective warp) whose entries are all distinct and non-zero, so swapping+# the images changes the model.+_MATCHES_1 = [+ [160.0, 95.0], [230.2, 95.2], [330.4, 95.4], [440.6, 95.6], [160.8, 150.8], [231.0, 151.0], [331.2, 151.2],+ [441.4, 151.4], [161.6, 241.6], [231.8, 241.8], [332.0, 242.0], [442.2, 242.2], [162.4, 322.4], [232.6, 322.6],+ [332.8, 322.8], [443.0, 323.0],+] # fmt: skip+_H_TRUE = [+ [1.034685, -0.04160598, -63.61482],+ [0.1039753, 1.135451, -62.87412],+ [2.851519e-04, 1.404178e-04, 1.0],+]+# Sixteen fixed points per image that no homography relates to each other or to the matches above.+_UNRELATED_1 = [+ [75.0, 410.0], [390.0, 30.0], [505.0, 260.0], [120.0, 205.0], [285.0, 380.0], [455.0, 60.0], [30.0, 140.0],+ [350.0, 290.0], [205.0, 25.0], [480.0, 395.0], [95.0, 330.0], [260.0, 175.0], [410.0, 225.0], [180.0, 450.0],+ [55.0, 70.0], [300.0, 120.0],+] # fmt: skip+_UNRELATED_2 = [+ [310.0, 95.0], [60.0, 280.0], [150.0, 30.0], [420.0, 330.0], [25.0, 190.0], [240.0, 400.0], [380.0, 170.0],+ [100.0, 60.0], [470.0, 240.0], [200.0, 130.0], [330.0, 20.0], [45.0, 420.0], [270.0, 300.0], [495.0, 110.0],+ [140.0, 260.0], [215.0, 355.0],+] # fmt: skip+# A non-planar two-view scene for the fundamental-matrix pin: K1 != K2, fx != fy, cx != cy, a rotation about a+# non-axis direction and a translation off every axis. Twelve points at depth 4 to 6 in camera 1, no two sharing a+# coordinate; the matches are their pixel projections through P1 = K1 [I | 0] and P2 = K2 [R | t].+_SCENE_K1 = [[800.0, 0.0, 320.0], [0.0, 760.0, 200.0], [0.0, 0.0, 1.0]]+_SCENE_K2 = [[700.0, 0.0, 300.0], [0.0, 740.0, 240.0], [0.0, 0.0, 1.0]]+_SCENE_AXIS_ANGLE = [0.1, -0.2, 0.05]+_SCENE_T = [0.5, 0.1, 0.02]+_SCENE_X = [+ [-0.0075, 0.5364, 4.4163], [-0.7359, -0.3852, 5.8596], [-0.0198, 0.7929, 5.4462], [0.2646, -0.3022, 5.4847],+ [-0.9553, -0.6623, 5.0526], [0.0370, 0.3953, 4.4873], [-0.6779, -0.4355, 5.1692], [0.8304, -0.2058, 4.0663],+ [-0.1612, 0.1058, 4.2774], [-0.9277, -0.6295, 4.4845], [-0.3898, 0.8640, 5.6309], [-0.4603, -0.6986, 5.5863],+] # fmt: skip+_HALF_LINES = (+ "line_segment_transfer_error_one_way builds the unnormalised image-2 line in the input dtype; its constant term "+ "is of order (pixel coordinate)**2, which overflows float16 and which bfloat16 cannot resolve"+)+++def _cpu_only(device: torch.device) -> None:+ if device.type != "cpu":+ pytest.skip("the RANSAC convention pins are verified on the CPU only")+++def _planar_matches(device, dtype):+ """Sixteen exact matches ``kp2 = H(kp1)``, generated in float64 on the CPU and cast, shape ``(16, 2)`` each."""+ kp1 = torch.tensor([_MATCHES_1], dtype=torch.float64)+ kp2 = transform_points(torch.tensor([_H_TRUE], dtype=torch.float64), kp1)+ return kp1[0].to(device, dtype), kp2[0].to(device, dtype)+++def _scene_matches(device, dtype):+ """Pixel matches of the two-view scene, projected in float64 on the CPU and cast, shape ``(12, 2)`` each."""+ f64 = torch.float64+ R = axis_angle_to_rotation_matrix(torch.tensor([_SCENE_AXIS_ANGLE], dtype=f64))[0]+ X = torch.tensor(_SCENE_X, dtype=f64)+ kp1 = convert_points_from_homogeneous(X @ torch.tensor(_SCENE_K1, dtype=f64).T)+ kp2 = convert_points_from_homogeneous(+ (X @ R.T + torch.tensor(_SCENE_T, dtype=f64)) @ torch.tensor(_SCENE_K2, dtype=f64).T+ )+ return kp1.to(device, dtype), kp2.to(device, dtype)+++def _planar_segments(device, dtype, stretch: float):+ """Eight segments made of consecutive lattice points and their exact images; segment 0 is ``stretch`` x longer."""+ ls1 = torch.tensor(_MATCHES_1, dtype=torch.float64).reshape(8, 2, 2)+ ls1[0, 1] = ls1[0, 0] + stretch * (ls1[0, 1] - ls1[0, 0])+ ls2 = transform_points(torch.tensor([_H_TRUE], dtype=torch.float64), ls1.reshape(1, 16, 2)).reshape(8, 2, 2)+ return ls1.to(device, dtype), ls2.to(device, dtype)+++def _fixed_model(ransac: RANSAC, model: torch.Tensor) -> RANSAC:+ """Make every minimal sample return ``model``, so that forward's thresholding is observed on a known model."""+ ransac.minimal_solver = lambda kp1, kp2, weights: model.expand(kp1.shape[0], 3, 3).clone()+ return ransac+++def _max_transfer(model: torch.Tensor, src: torch.Tensor, dst: torch.Tensor) -> torch.Tensor:+ return (transform_points(model[None], src[None]) - dst[None]).abs().max()+++class TestConventionRANSAC(BaseTester):+ def test_convention_ransac_model_maps_kp1_to_kp2(self, device, dtype, monkeypatch):+ _cpu_only(device)+ kp1, kp2 = _planar_matches(device, dtype)+ # inl_th=5 keeps every exact match an inlier in bfloat16 too, whose pixel coordinates carry up to 2 px of+ # rounding here.+ model, mask = RANSAC("homography", inl_th=5.0, seed=0, max_iter=3, batch_size=64)(kp1, kp2)+ # A (3, 3) model and an (N,) bool mask; the model maps kp1 onto kp2, and the control (applying it to kp2)+ # misses kp1 by about 213 px.+ assert model.shape == (3, 3)+ assert mask.shape == (16,) and mask.dtype == torch.bool and bool(mask.all())+ assert _max_transfer(model, kp1, kp2) < 0.05 * _max_transfer(model, kp2, kp1)+ swapped, _ = RANSAC("homography", inl_th=5.0, seed=0, max_iter=3, batch_size=64)(kp2, kp1)+ assert _max_transfer(swapped, kp2, kp1) < 0.05 * _max_transfer(swapped, kp1, kp2)+ # No sample reaches consensus on unrelated points: an all-zero model and no inliers.+ unrelated_1 = torch.tensor(_UNRELATED_1[:12], device=device, dtype=dtype)+ unrelated_2 = torch.tensor(_UNRELATED_2[:12], device=device, dtype=dtype)+ model, mask = RANSAC("homography", inl_th=0.5, seed=0, max_iter=3, batch_size=64)(unrelated_1, unrelated_2)+ assert bool((model == 0).all())+ assert mask.shape == (12,) and mask.dtype == torch.bool and not bool(mask.any())+ # "homography" screens its minimal samples with sample_is_valid_for_homography: when every sample is+ # rejected, no model is estimated from the exact matches either.+ samples = []++ def reject_all(points1, points2):+ samples.append(tuple(points1.shape))+ return torch.zeros(points1.shape[0], dtype=torch.bool, device=points1.device)++ monkeypatch.setattr(kornia.geometry.ransac, "sample_is_valid_for_homography", reject_all)+ model, mask = RANSAC("homography", inl_th=5.0, seed=0, max_iter=3, batch_size=64)(kp1, kp2)+ # Every sample is rejected, so nothing stops early: max_iter=3 batches of batch_size=64 minimal samples,+ # the documented maximum.+ assert len(samples) == 3 and all(shape == (64, 4, 2) for shape in samples)+ assert bool((model == 0).all()) and not bool(mask.any())++ @pytest.mark.parametrize("model_type", ["homography", "fundamental"])+ def test_convention_ransac_inl_th_is_pixels_for_point_models(self, model_type, device, dtype):+ _cpu_only(device)+ if model_type == "homography":+ # inl_th is compared with the one-way transfer error in pixels (forward passes inl_th**2 to the squared+ # error): a match displaced by 10 px is an outlier at inl_th=4 and an inlier at inl_th=15. RANSAC may+ # absorb part of the displacement into a compromise model, so the flip lies at or below 10 px; both+ # thresholds stay clear of it, and in squared-pixel units both would reject the match.+ kp1, kp2 = _planar_matches(device, dtype)+ kp2_bad = kp2.clone()+ kp2_bad[9, 0] += 10.0 # an interior match, displaced along x+ for inl_th, expected in ((4.0, False), (15.0, True)):+ _, mask = RANSAC("homography", inl_th=inl_th, max_iter=20, seed=0)(kp1, kp2_bad)+ assert mask.dtype == torch.bool and mask.shape == (16,)+ assert bool(mask[9]) is expected+ assert int(mask.sum()) == 15 + int(expected)+ # With the true H fixed, the moved match's one-way error is exactly 10 px (its symmetric error is+ # about 15 px): an inlier at inl_th=11 and an outlier at inl_th=9. The minimal samples still pass+ # sample_is_valid_for_homography, which rejects some lattice samples, so a seeded batch of 64 is drawn.+ H = torch.tensor([_H_TRUE], device=device, dtype=dtype)+ for inl_th, expected in ((9.0, False), (11.0, True)):+ ransac = RANSAC("homography", inl_th=inl_th, batch_size=64, max_iter=1, max_lo_iters=0, seed=0)+ _, mask = _fixed_model(ransac, H)(kp1, kp2_bad)+ assert bool(mask[9]) is expected+ assert int(mask.sum()) == 15 + int(expected)+ return+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("find_fundamental calls torch.linalg.eigh, which has no float16/bfloat16 kernel")+ kp1, kp2 = _scene_matches(device, dtype)+ if dtype == torch.float64:+ # kp1 is the estimator's first image: the returned F explains every match in this order+ # (x2^T F x1 = 0), and its transpose, the other image order, explains none. float64 only: in float32+ # the fit on these exact matches already misses by a pixel or two.+ F_est, mask_est = RANSAC("fundamental", inl_th=1.0, seed=0, max_iter=3, batch_size=64)(kp1, kp2)+ assert bool(mask_est.all())+ assert sampson_epipolar_distance(kp1[None], kp2[None], F_est[None], squared=False).max() < 1e-2+ assert sampson_epipolar_distance(kp1[None], kp2[None], F_est.mT[None], squared=False).min() > 1.0+ # For the fundamental models inl_th is compared with the Sampson distance in pixels. The model is fixed to+ # the F of the twelve exact matches, so the threshold is observed without sampling.+ F = find_fundamental(kp1[None], kp2[None])+ kp2_bad = kp2.clone()+ kp2_bad[6] += torch.tensor([4.0, -3.0], device=device, dtype=dtype)+ distance = sampson_epipolar_distance(kp1[None], kp2_bad[None], F, squared=False)[0, 6]+ # About 2.6 px: an outlier at inl_th=2 and an inlier at inl_th=4. Compared in squared-pixel units, or with+ # the distance itself against inl_th**2, the two verdicts would not both hold.+ assert 2.0 < distance < 4.0+ for inl_th, expected in ((2.0, False), (4.0, True)):+ ransac = RANSAC("fundamental", inl_th=inl_th, batch_size=1, max_iter=1, max_lo_iters=0, seed=0)+ model, mask = _fixed_model(ransac, F)(kp1, kp2_bad)+ assert torch.equal(model, F[0])+ assert bool(mask[6]) is expected+ assert int(mask.sum()) == 11 + int(expected)++ def test_convention_ransac_seed_is_private(self, device, dtype):+ _cpu_only(device)+ kp1, kp2 = _planar_matches(device, dtype)+ kp2[9, 0] += 10.0++ def run(seed):+ return RANSAC("homography", inl_th=2.0, seed=seed, max_iter=3, batch_size=16)(kp1, kp2)++ # A seeded call draws from a private generator: it leaves the global RNG state unchanged, and a second+ # instance with the same seed reproduces it whatever the global generator holds.+ state = torch.get_rng_state()+ model_a, mask_a = run(11)+ assert torch.equal(torch.get_rng_state(), state)+ torch.manual_seed(123)+ model_b, mask_b = run(11)+ assert torch.equal(model_a, model_b) and torch.equal(mask_a, mask_b)+ # seed=None draws from the global generator: it advances it, and reseeding it reproduces the result.+ torch.manual_seed(5)+ state = torch.get_rng_state()+ model_c, mask_c = run(None)+ assert not torch.equal(torch.get_rng_state(), state)+ torch.manual_seed(5)+ 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):+ _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 = []+ 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]++ def test_wart_ransac_msac_no_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)])+ kp2 = torch.cat([kp2, torch.tensor(_UNRELATED_2, device=device, dtype=dtype)])+ # 16 exact matches and 16 outliers. score_type="ransac" finds the homography of the sixteen.+ model, mask = RANSAC("homography", inl_th=5.0, score_type="ransac", seed=0, max_iter=5, batch_size=256)(+ 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.+ 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())++ def test_wart_ransac_prosac_sampling_ignored_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 = 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)++ @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+ ):+ _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):+ RANSAC(model_type, max_iter=1, batch_size=4, seed=0)(kp1[:n], kp2[:n])