🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): guard the singular cases of the two-view metrics instead of adding eps to the value (#5116)
区梓灏3defedbcda79
diff --git a/changelog.d/5116.breaking.md b/changelog.d/5116.breaking.mdnew file mode 100644index 000000000..a5984cfec--- /dev/null+++ b/changelog.d/5116.breaking.md@@ -0,0 +1,11 @@+`sampson_epipolar_distance`, `symmetrical_epipolar_distance`, `left_to_right_epipolar_distance`,+`right_to_left_epipolar_distance`, `point_line_distance`, `oneway_transfer_error` and `symmetric_transfer_error` no+longer add `eps` to their denominators or inside the square root, and return `inf` in the singular cases instead+(#4881): both epilines with `a = b = 0` for the Sampson distance, either one for the symmetrical distance, the line+for `point_line_distance` and the one-way epipolar distances, and a point that `H` maps to `w' = 0` for the transfer+errors. The values are now independent of the scale of `F`, `H` or the line, `squared=False` returns exactly 0 for an+exact match, with a zero gradient, and the CUDA matmul and the CPU manual Sampson paths agree. Before, the same `F` at+`‖F‖ = 1e-3` scored 90% lower than at `‖F‖ = 1` (9.3e-6 relative there), an exact match scored `sqrt(eps) = 1e-4`,+the two Sampson paths differed by that scale-dependent amount, a degenerate `F` scored `residual² / eps` (`1e8` for+`F = diag(0, 0, 1)`) on CPU and `inf` on CUDA, and on CPU an all-zero `F` or line put every point at distance 0. The+`eps` parameters are still accepted and have no effect.diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex d49af513c..ab41cbea4 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -596,9 +596,8 @@ normalised camera coordinates, and :func:`~kornia.geometry.homography.find_homogsecond-image points- ``computeCorrespondEpilines(x1, 1, F)``; ``whichImage=2`` for second-image points* - Sampson distance- - ``sampson_epipolar_distance(pts1, pts2, F)``, squared by default; the value depends on the scale of ``F``- (`#4881 <https://github.com/kornia/kornia/issues/4881>`_)- - ``sampsonDistance(pt1, pt2, F)``, the same argument order, independent of the scale of ``F``+ - ``sampson_epipolar_distance(pts1, pts2, F)``, squared by default+ - ``sampsonDistance(pt1, pt2, F)``, the same argument order* - RANSAC threshold- ``inl_th`` is a point distance in the keypoints' units, calibrated units for ``model_type="essential"``;for line segments, the mean distance of the transferred endpoints from the target segment's line, whichdiff --git a/kornia/geometry/epipolar/_metrics.py b/kornia/geometry/epipolar/_metrics.pyindex ba0017e3b..39cb8e915 100644--- a/kornia/geometry/epipolar/_metrics.py+++ b/kornia/geometry/epipolar/_metrics.py@@ -25,12 +25,10 @@ from torch import Tensor, ones_likefrom kornia.core.check import KORNIA_CHECK_IS_TENSORfrom kornia.geometry.conversions import convert_points_to_homogeneousfrom kornia.geometry.epipolar.fundamental import _epipolar_design_rows-from kornia.geometry.linalg import point_line_distance+from kornia.geometry.linalg import _inf_where, _nonzero, _sqrt_or_zero, point_line_distance-def _sampson_epipolar_distance_manual_impl_(- pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool = True, eps: float = 1e-8-) -> Tensor:+def _sampson_epipolar_distance_manual_impl_(pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool = True) -> Tensor:"""Return Sampson distance for correspondences given the fundamental matrix.Args:@@ -40,7 +38,6 @@ def _sampson_epipolar_distance_manual_impl_(converted automatically.Fm: Fundamental matrices with shape :math:`(*, 3, 3)`. Called Fm to avoid ambiguity with torch.nn.functional.squared: if True (default), the squared distance is returned.- eps: Small constant for safe sqrt.Returns:the computed Sampson distance with shape :math:`(*, N)`.@@ -85,16 +82,13 @@ def _sampson_epipolar_distance_manual_impl_(# Numerator: (x'^T F x)^2 = (u*Fx0 + v*Fx1 + w2*Fx2)^2num = (u * Fx0 + v * Fx1 + w2 * Fx2) ** 2# Denominator: ||(F x)_{1:2}||^2 + ||(F^T x')_{1:2}||^2- den = Fx0 * Fx0 + Fx1 * Fx1 + Ft0 * Ft0 + Ft1 * Ft1 + eps- out: Tensor = num / den- if squared:- return out- return (out + eps).sqrt()+ den = Fx0 * Fx0 + Fx1 * Fx1 + Ft0 * Ft0 + Ft1 * Ft1+ # Singular when both epilines have a = b = 0 (#4881).+ out: Tensor = _inf_where(num / _nonzero(den), den == 0)+ return out if squared else _sqrt_or_zero(out)-def _sampson_epipolar_distance_matmul_impl_(- pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool = True, eps: float = 1e-8-) -> Tensor:+def _sampson_epipolar_distance_matmul_impl_(pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool = True) -> Tensor:"""Return Sampson distance for correspondences given the fundamental matrix.Args:@@ -104,7 +98,6 @@ def _sampson_epipolar_distance_matmul_impl_(converted automatically.Fm: Fundamental matrices with shape :math:`(*, 3, 3)`. Called Fm to avoid ambiguity with torch.nn.functional.squared: if True (default), the squared distance is returned.- eps: Small constant for safe sqrt.Returns:the computed Sampson distance with shape :math:`(*, N)`.@@ -132,10 +125,8 @@ def _sampson_epipolar_distance_matmul_impl_(# denominator = (((Fx)_1**2) + (Fx)_2**2)) + (((F^Tx')_1**2) + (F^Tx')_2**2))denominator: Tensor = line1_in_2[..., :2].norm(2, dim=-1).pow(2) + line2_in_1[..., :2].norm(2, dim=-1).pow(2)- out: Tensor = numerator / denominator- if squared:- return out- return (out + eps).sqrt()+ out: Tensor = _inf_where(numerator / _nonzero(denominator), denominator == 0)+ return out if squared else _sqrt_or_zero(out)# Shared-point Sampson distances take the GEMM path on CPU from two models on. On CUDA both paths are launch-bound@@ -149,14 +140,14 @@ def _shares_points(pts1: Tensor, pts2: Tensor) -> bool:return math.prod(pts1.shape[:-2]) == 1 and math.prod(pts2.shape[:-2]) == 1 and pts1.shape[-2] == pts2.shape[-2]-def _sampson_errors(F: Tensor, x1: Tensor, x2: Tensor, eps: float) -> Tensor:+def _sampson_errors(F: Tensor, x1: Tensor, x2: Tensor) -> Tensor:"""Squared Sampson distances ``(M, N)`` of fundamental matrices ``(M, 3, 3)`` on homogeneous points ``(N, 3)``.The line ``F x1`` and the first two components of ``F^T x2`` of every model come from ``(3M, 3) @ (3, N)`` and``(2M, 3) @ (3, N)`` products; the residual ``x2 . (F x1)`` and the squared gradient norm are then formed in the- order of the manual implementation, and ``eps`` is added to the denominator. Expanding either into monomials of- the coordinates, as :func:`_sampson_quadratic_basis` does, cancels near the epipoles: on pixel-scale float32 points- 0.01-1000 px from both epipoles an expanded denominator returned negative and infinite distances, and for+ order of the manual implementation, with its guard of the singular denominator. Expanding either into monomials+ of the coordinates, as :func:`_sampson_quadratic_basis` does, cancels near the epipoles: on pixel-scale float32+ points 0.01-1000 px from both epipoles an expanded denominator returned negative and infinite distances, and for``F = [[1, 0, -1000], [0, 1, -1000], [-1000, -1000, 2e6]]``, ``x1 = (1000.1, 1000.2)``, ``x2 = (1000.3, 1000.4)``an expanded residual gives 0.0521 where this gives the manual path's 0.0319 (float64: 0.0403)."""@@ -164,18 +155,15 @@ def _sampson_errors(F: Tensor, x1: Tensor, x2: Tensor, eps: float) -> Tensor:lines = (F.reshape(3 * m, 3) @ x1.T).view(m, 3, n)lines_t = (F.mT[:, :2].reshape(2 * m, 3) @ x2.T).view(m, 2, n)residual = x2[:, 0] * lines[:, 0] + x2[:, 1] * lines[:, 1] + x2[:, 2] * lines[:, 2]- denominator = lines[:, 0].square() + lines[:, 1].square() + lines_t[:, 0].square() + lines_t[:, 1].square() + eps- return residual.square() / denominator+ denominator = lines[:, 0].square() + lines[:, 1].square() + lines_t[:, 0].square() + lines_t[:, 1].square()+ return _inf_where(residual.square() / _nonzero(denominator), denominator == 0)-def _sampson_epipolar_distance_shared_impl_(- pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool, eps: float, denominator_eps: float-) -> Tensor:+def _sampson_epipolar_distance_shared_impl_(pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool) -> Tensor:"""Sampson distances of many fundamental matrices on one set of correspondences, by :func:`_sampson_errors`.``pts1`` and ``pts2`` have leading dimensions of size 1; the result has the broadcast shape ``(*, N)``. Half- precision is computed in float32 and returned in the input dtype. ``denominator_eps`` is ``eps``, or 0 where the- CUDA matmul implementation would have run (#4881).+ precision is computed in float32 and returned in the input dtype."""num_points = pts1.shape[-2]dtype = torch.promote_types(torch.promote_types(pts1.dtype, pts2.dtype), Fm.dtype)@@ -186,9 +174,9 @@ def _sampson_epipolar_distance_shared_impl_(x1 = convert_points_to_homogeneous(x1)if x2.shape[-1] == 2:x2 = convert_points_to_homogeneous(x2)- out = _sampson_errors(Fm.reshape(-1, 3, 3).to(work), x1, x2, denominator_eps)+ out = _sampson_errors(Fm.reshape(-1, 3, 3).to(work), x1, x2)if not squared:- out = (out + eps).sqrt()+ out = _sqrt_or_zero(out)shape = torch.broadcast_shapes(pts1.shape[:-2], pts2.shape[:-2], Fm.shape[:-2])return out.reshape(*shape, num_points).to(dtype)@@ -248,17 +236,18 @@ def sampson_epipolar_distance(- One set of correspondences scored against several matrices (points with leading dimensions of size 1)is computed from two matrix products for all of them, in at least float32; the result matches theper-matrix computation to roundoff.- - Known defects: ``eps`` is added to the denominator, so the value depends on the scale of ``Fm``;- ``squared=False`` returns :math:`\sqrt{d^2 + \epsilon}`, which is not zero for an exact match; and on- CUDA the matmul path omits ``eps`` from the denominator, so CUDA and CPU results differ- (`#4881 <https://github.com/kornia/kornia/issues/4881>`_).+ - The value does not depend on the scale of ``Fm``, and ``squared=False`` returns exactly 0, with a zero+ gradient, for an exact match. A correspondence whose two epilines both have :math:`a = b = 0`, as under a+ degenerate ``Fm``, is at distance ``inf``.Args:pts1: points in the first image with shape :math:`(*, N, 2)` or :math:`(*, N, 3)`.pts2: points in the second image with shape :math:`(*, N, 2)` or :math:`(*, N, 3)`.Fm: Fundamental matrices with shape :math:`(*, 3, 3)`. Called Fm to avoid ambiguity with torch.nn.functional.squared: if True (default), the squared distance is returned, else its square root.- eps: Small constant added to the denominator and, for ``squared=False``, inside the square root.+ eps: unused; it was added to the denominator and inside the square root, which made the value depend on the+ scale of ``Fm`` and an exact match score :math:`\sqrt{\epsilon}` (#4881). The singular case is guarded+ exactly instead. Accepted so that existing calls keep working.use_matmul_at_less_than_points: If ``Fm`` is on CUDA and the number of points is less than this value,use the matmul implementation.@@ -275,16 +264,13 @@ def sampson_epipolar_distance(and _shares_points(pts1, pts2)and (Fm.device.type == "cpu" or num_models * num_points >= _SAMPSON_SHARED_MIN_PAIRS_ACCELERATOR)):- # The CUDA matmul implementation leaves eps out of the denominator (#4881); the shared path follows it there.- return _sampson_epipolar_distance_shared_impl_(pts1, pts2, Fm, squared, eps, 0.0 if matmul else eps)+ return _sampson_epipolar_distance_shared_impl_(pts1, pts2, Fm, squared)if matmul:- return _sampson_epipolar_distance_matmul_impl_(pts1, pts2, Fm, squared, eps)- return _sampson_epipolar_distance_manual_impl_(pts1, pts2, Fm, squared, eps)+ return _sampson_epipolar_distance_matmul_impl_(pts1, pts2, Fm, squared)+ return _sampson_epipolar_distance_manual_impl_(pts1, pts2, Fm, squared)-def _symmetrical_epipolar_distance_manual_impl_(- pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool = True, eps: float = 1e-8-) -> Tensor:+def _symmetrical_epipolar_distance_manual_impl_(pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool = True) -> Tensor:"""Return symmetric epipolar distance for correspondences given the fundamental matrix (CPU-optimized)."""if not isinstance(Fm, Tensor):raise TypeError(f"Fm type is not a torch.Tensor. Got {type(Fm)}")@@ -325,20 +311,15 @@ def _symmetrical_epipolar_distance_manual_impl_(# Numerator: (x'^T F x)^2 = (u*Fx0 + v*Fx1 + w2*Fx2)^2num = (u * Fx0 + v * Fx1 + w2 * Fx2).pow(2)- # denominator_inv = 1/|| (F x)_{1:2} ||^2 + 1/|| (F^T x')_{1:2} ||^2- inv1 = 1.0 / (Fx0.pow(2) + Fx1.pow(2) + eps)- inv2 = 1.0 / (Ft0.pow(2) + Ft1.pow(2) + eps)- den_inv = inv1 + inv2-- out: Tensor = num * den_inv- if squared:- return out- return (out + eps).sqrt()+ # denominator_inv = 1/|| (F x)_{1:2} ||^2 + 1/|| (F^T x')_{1:2} ||^2; singular when either epiline has a = b = 0.+ norm1 = Fx0.pow(2) + Fx1.pow(2)+ norm2 = Ft0.pow(2) + Ft1.pow(2)+ den_inv = 1.0 / _nonzero(norm1) + 1.0 / _nonzero(norm2)+ out: Tensor = _inf_where(num * den_inv, (norm1 == 0) | (norm2 == 0))+ return out if squared else _sqrt_or_zero(out)-def _symmetrical_epipolar_distance_matmul_impl_(- pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool = True, eps: float = 1e-8-) -> Tensor:+def _symmetrical_epipolar_distance_matmul_impl_(pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool = True) -> Tensor:if pts1.shape[-1] == 2:pts1 = convert_points_to_homogeneous(pts1)if pts2.shape[-1] == 2:@@ -350,13 +331,11 @@ def _symmetrical_epipolar_distance_matmul_impl_(numerator: Tensor = (pts2 * line1_in_2).sum(dim=-1).pow(2)- denominator_inv: Tensor = 1.0 / (line1_in_2[..., :2].norm(2, dim=-1).pow(2) + eps) + 1.0 / (- line2_in_1[..., :2].norm(2, dim=-1).pow(2) + eps- )- out: Tensor = numerator * denominator_inv- if squared:- return out- return (out + eps).sqrt()+ norm1: Tensor = line1_in_2[..., :2].norm(2, dim=-1).pow(2)+ norm2: Tensor = line2_in_1[..., :2].norm(2, dim=-1).pow(2)+ denominator_inv: Tensor = 1.0 / _nonzero(norm1) + 1.0 / _nonzero(norm2)+ out: Tensor = _inf_where(numerator * denominator_inv, (norm1 == 0) | (norm2 == 0))+ return out if squared else _sqrt_or_zero(out)def symmetrical_epipolar_distance(@@ -367,16 +346,16 @@ def symmetrical_epipolar_distance(Convention:- Argument order and units as :func:`sampson_epipolar_distance`; the value is the sum of the twosquared point-to-epiline distances.- - Known defects: ``eps`` makes the value depend on the scale of ``Fm``, and ``squared=False`` returns- :math:`\sqrt{d^2 + \epsilon}`, as in :func:`sampson_epipolar_distance`- (`#4881 <https://github.com/kornia/kornia/issues/4881>`_).+ - The value does not depend on the scale of ``Fm``, and ``squared=False`` returns exactly 0 for an exact+ match, as in :func:`sampson_epipolar_distance`. A correspondence with an epiline of :math:`a = b = 0` in+ either image is at distance ``inf``.Args:pts1: points in the first image with shape :math:`(*, N, 2)` or :math:`(*, N, 3)`.pts2: points in the second image with shape :math:`(*, N, 2)` or :math:`(*, N, 3)`.Fm: Fundamental matrices with shape :math:`(*, 3, 3)`. Called Fm to avoid ambiguity with torch.nn.functional.squared: if True (default), the squared distance is returned, else its square root.- eps: Small constant added to the denominators and, for ``squared=False``, inside the square root.+ eps: unused, as in :func:`sampson_epipolar_distance` (#4881).Returns:the computed Symmetrical distance with shape :math:`(*, N)`.@@ -385,8 +364,8 @@ def symmetrical_epipolar_distance(if Fm.device.type == "cuda":num_points = pts1.shape[-2]if num_points < 10000:- return _symmetrical_epipolar_distance_matmul_impl_(pts1, pts2, Fm, squared, eps)- return _symmetrical_epipolar_distance_manual_impl_(pts1, pts2, Fm, squared, eps)+ return _symmetrical_epipolar_distance_matmul_impl_(pts1, pts2, Fm, squared)+ return _symmetrical_epipolar_distance_manual_impl_(pts1, pts2, Fm, squared)def left_to_right_epipolar_distance(pts1: Tensor, pts2: Tensor, Fm: Tensor) -> Tensor:@@ -395,8 +374,8 @@ def left_to_right_epipolar_distance(pts1: Tensor, pts2: Tensor, Fm: Tensor) -> TConvention:- Argument order as :func:`sampson_epipolar_distance`; returns the unsquared pixel distance of each``pts2`` to the epipolar line of its ``pts1`` in the second image.- - Known defects: ``point_line_distance`` adds ``eps`` to the line norm, so the value depends slightly on- the scale of ``Fm`` (`#4881 <https://github.com/kornia/kornia/issues/4881>`_).+ - The value does not depend on the scale of ``Fm``; a point whose epiline has :math:`a = b = 0` is at+ distance ``inf``, as in :func:`~kornia.geometry.linalg.point_line_distance`.Args:pts1: points in the first image with shape :math:`(*, N, 2)` or :math:`(*, N, 3)`.@@ -430,8 +409,8 @@ def right_to_left_epipolar_distance(pts1: Tensor, pts2: Tensor, Fm: Tensor) -> TConvention:- Argument order as :func:`sampson_epipolar_distance`; returns the unsquared pixel distance of each``pts1`` to the epipolar line of its ``pts2`` in the first image.- - Known defects: ``point_line_distance`` adds ``eps`` to the line norm, so the value depends slightly on- the scale of ``Fm`` (`#4881 <https://github.com/kornia/kornia/issues/4881>`_).+ - The value does not depend on the scale of ``Fm``; a point whose epiline has :math:`a = b = 0` is at+ distance ``inf``, as in :func:`~kornia.geometry.linalg.point_line_distance`.Args:pts1: points in the first image with shape :math:`(*, N, 2)` or :math:`(*, N, 3)`.diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.pyindex ab0b7797f..7b15e25d3 100644--- a/kornia/geometry/homography.py+++ b/kornia/geometry/homography.py@@ -27,7 +27,7 @@ from kornia.geometry.conversions import convert_points_from_homogeneous, convertfrom kornia.geometry.epipolar import normalize_points, normalize_transformationfrom kornia.geometry.epipolar._metrics import _shares_pointsfrom kornia.geometry.epipolar.fundamental import _robust_loss-from kornia.geometry.linalg import transform_points+from kornia.geometry.linalg import _inf_where, _nonzero, _sqrt_or_zero, transform_pointsfrom kornia.geometry.solvers.homogeneous import _null_space_lu__all__ = [@@ -58,9 +58,8 @@ def oneway_transfer_error(per-homography computation to roundoff.- ``squared=True``, the default here and in :func:`symmetric_transfer_error`, returns the squareddistance; :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>`_).+ - The error does not depend on the scale of ``H``, and an exact match scores exactly 0, with a zero+ gradient, with ``squared=False``. A point that ``H`` maps to infinity (:math:`w' = 0`) has error ``inf``.Args:pts1: correspondences from the left images with shape@@ -69,7 +68,9 @@ 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: added to the projective denominator and, with ``squared=False``, inside the square root.+ eps: unused; it was added to the projective denominator and inside the square root, which made the error+ depend on the scale of ``H`` and an exact match score ``sqrt(eps)`` (#4881). The singular case is+ guarded exactly instead. Accepted so that existing calls keep working.Returns:the computed distance with shape :math:`(B, N)`.@@ -77,7 +78,7 @@ def oneway_transfer_error("""KORNIA_CHECK_SHAPE(H, ["B", "3", "3"])if H.shape[0] >= 2 and _shares_points(pts1, pts2):- return _oneway_transfer_error_shared_impl_(pts1, pts2, H, squared, eps)+ return _oneway_transfer_error_shared_impl_(pts1, pts2, H, squared)if pts1.shape[-1] == 3:x1y1 = convert_points_from_homogeneous(pts1)@@ -114,14 +115,14 @@ def oneway_transfer_error(y_num = h10 * x1 + h11 * y1 + h12w_den = h20 * x1 + h21 * y1 + h22- u1in2 = x_num / (w_den + eps)- v1in2 = y_num / (w_den + eps)+ # A point mapped to infinity (w' = 0) is singular (#4881).+ w_safe = _nonzero(w_den)+ u1in2 = x_num / w_safe+ v1in2 = y_num / w_safe# ---- Squared transfer error in image 2 ----- err2 = (u1in2 - u2).pow(2) + (v1in2 - v2).pow(2)- if squared:- return err2- return (err2 + eps).sqrt()+ err2 = _inf_where((u1in2 - u2).pow(2) + (v1in2 - v2).pow(2), w_den == 0)+ return err2 if squared else _sqrt_or_zero(err2)def symmetric_transfer_error(@@ -132,8 +133,8 @@ def symmetric_transfer_error(Convention:- Argument order as :func:`oneway_transfer_error`. The squared value is the image-2 error of ``H`` plusthe 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>`_).+ - As :func:`oneway_transfer_error`, the error does not depend on the scale of ``H`` and an exact match+ scores exactly 0 with ``squared=False``.Args:pts1: correspondences from the left images with shape@@ -142,7 +143,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: added to the projective denominator and, with ``squared=False``, inside the square root.+ eps: unused, as in :func:`oneway_transfer_error` (#4881).Returns:the computed distance with shape :math:`(B, N)`. Rows whose homography is not invertible@@ -168,13 +169,13 @@ def symmetric_transfer_error(H_safe = torch.where(good_H.view(-1, 1, 1), H, eye)H_inv_safe, _ = safe_inverse_with_mask(H_safe)- there: torch.Tensor = oneway_transfer_error(pts1, pts2, H_safe, True, eps)- back: torch.Tensor = oneway_transfer_error(pts2, pts1, H_inv_safe, True, eps)+ there: torch.Tensor = oneway_transfer_error(pts1, pts2, H_safe, True)+ back: torch.Tensor = oneway_transfer_error(pts2, pts1, H_inv_safe, True)good_H_reshape: torch.Tensor = good_H.view(-1, 1).expand_as(there)out = there + backif not squared:- out = (out + eps).sqrt()+ out = _sqrt_or_zero(out)max_tensor = torch.full_like(out, max_num)return torch.where(good_H_reshape, out, max_tensor)@@ -348,21 +349,22 @@ def _four_point_homography(x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:return (h * h.square().sum(-1, keepdim=True).rsqrt()).reshape(-1, 3, 3).to(x1.dtype)-def _transfer_errors(H: torch.Tensor, x1: torch.Tensor, x2: torch.Tensor, eps: float) -> torch.Tensor:+def _transfer_errors(H: torch.Tensor, x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:"""Squared one-way transfer errors ``(M, N)`` of homographies ``(M, 3, 3)`` on one set of correspondences.``x1`` is homogeneous ``(N, 3)`` with unit last coordinate and ``x2`` ``(N, 2)``. ``H x1`` of every model is one- ``(3M, 3) @ (3, N)`` product; the rest is :func:`oneway_transfer_error`'s formula, ``eps`` in the projective- denominator included.+ ``(3M, 3) @ (3, N)`` product; the rest is :func:`oneway_transfer_error`'s formula, with its guard of ``w' = 0``."""m, n = H.shape[0], x1.shape[0]projected = (H.reshape(3 * m, 3) @ x1.T).view(m, 3, n)- w = projected[:, 2] + eps- return (projected[:, 0] / w - x2[:, 0]).square() + (projected[:, 1] / w - x2[:, 1]).square()+ w = projected[:, 2]+ w_safe = _nonzero(w)+ err2 = (projected[:, 0] / w_safe - x2[:, 0]).square() + (projected[:, 1] / w_safe - x2[:, 1]).square()+ return _inf_where(err2, w == 0)def _oneway_transfer_error_shared_impl_(- pts1: torch.Tensor, pts2: torch.Tensor, H: torch.Tensor, squared: bool, eps: float+ pts1: torch.Tensor, pts2: torch.Tensor, H: torch.Tensor, squared: bool) -> torch.Tensor:"""One-way transfer errors of many homographies on one set of correspondences, by :func:`_transfer_errors`.@@ -378,8 +380,8 @@ def _oneway_transfer_error_shared_impl_(x1 = convert_points_from_homogeneous(x1)if x2.shape[-1] == 3:x2 = convert_points_from_homogeneous(x2)- err2 = _transfer_errors(H.to(work), convert_points_to_homogeneous(x1), x2, eps)- out = err2 if squared else (err2 + eps).sqrt()+ err2 = _transfer_errors(H.to(work), convert_points_to_homogeneous(x1), x2)+ out = err2 if squared else _sqrt_or_zero(err2)shape = torch.broadcast_shapes(pts1.shape[:-2], pts2.shape[:-2], H.shape[:-2])return out.reshape(*shape, num_points).to(dtype)diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.pyindex 2328fa786..fea78e339 100644--- a/kornia/geometry/linalg.py+++ b/kornia/geometry/linalg.py@@ -284,22 +284,41 @@ def transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Tereturn points_0.to(points_dtype)+def _nonzero(x: torch.Tensor) -> torch.Tensor:+ """``x`` with 1 in place of its zeros: a divisor for entries the caller then sets to inf with :func:`_inf_where`."""+ return torch.where(x == 0, torch.ones_like(x), x)+++def _inf_where(value: torch.Tensor, singular: torch.Tensor) -> torch.Tensor:+ """``value`` with inf at the ``singular`` entries.++ This is the guard that replaces ``eps`` in the two-view metrics (#4881): ``torch.where`` also differentiates the+ branch it does not select, so ``value`` must be formed with divisors from :func:`_nonzero`; the gradient at a+ singular entry is then 0 instead of NaN.+ """+ return torch.where(singular, torch.full_like(value, torch.inf), value)+++def _sqrt_or_zero(squared: torch.Tensor) -> torch.Tensor:+ """``squared.sqrt()`` with a zero gradient at ``squared == 0``, an exact match, where the root's own is infinite."""+ zero = squared <= 0+ return torch.where(zero, torch.zeros_like(squared), torch.where(zero, torch.ones_like(squared), squared).sqrt())++def point_line_distance(point: torch.Tensor, line: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:r"""Return the distance from points to lines.Convention:- - ``line`` need not be normalised. The geometric distance is :math:`|ax + by + c| / \|(a, b)\|` for- :math:`(a, b) \ne (0, 0)`; kornia instead divides by :math:`\|(a, b)\| + \epsilon`.- - Known defect: this ``eps`` biases the distance when the line coefficients are small and returns- :math:`|c| / \epsilon` for a line with :math:`a = b = 0`; in ``float16`` the default ``eps`` rounds to- zero, so that line gives ``inf``, or ``nan`` when :math:`c = 0` as well- (`#4881 <https://github.com/kornia/kornia/issues/4881>`_).+ - ``line`` need not be normalised: the distance is :math:`|ax + by + c| / \|(a, b)\|` at every scale of the+ coefficients. A line with :math:`a = b = 0`, the line at infinity or no line at all, is at distance ``inf``+ from every point, as a point at infinity is from every line.Args:point: points :math:`(*, N, 2)`, or homogeneous points :math:`(*, N, 3)` whose last coordinate is theweight :math:`w`; a point at infinity (:math:`w = 0`) is at distance ``inf`` from every line.line: lines coefficients :math:`(a, b, c)` with shape :math:`(*, N, 3)`, where :math:`ax + by + c = 0`.- eps: small constant added to :math:`\|(a, b)\|` in the denominator.+ eps: unused; it was added to :math:`\|(a, b)\|` and made the distance depend on the scale of the line+ (#4881). The singular line is guarded exactly instead. Accepted so that existing calls keep working.Returns:the computed distance with shape :math:`(*, N)`.@@ -323,20 +342,18 @@ def point_line_distance(point: torch.Tensor, line: torch.Tensor, eps: float = 1enumerator += line[..., 2]numerator.abs_()- # Avoid computing norm multiple times by saving its value- denom_norm = (line[..., 0].square() + line[..., 1].square()).sqrt()-- distance = numerator / (denom_norm + eps)+ # The root and the divisions are taken on safe arguments (see _inf_where); a line with a = b = 0 is singular.+ squared_norm = line[..., 0].square() + line[..., 1].square()+ singular = squared_norm == 0+ distance = numerator / _nonzero(squared_norm).sqrt()if point.shape[-1] == 3:# (x, y, w) is the Euclidean point (x / w, y / w), so its distance is |ax + by + cw| / (|w| |(a, b)|); the- # weight used to be ignored, which is right only for w = 1 (#4935). A point at infinity (w = 0) is at- # distance inf; torch.where also differentiates the branch it does not select, so that division is kept- # finite.+ # weight used to be ignored, which is right only for w = 1 (#4935). A point at infinity (w = 0) is singular+ # as well.w = point[..., 2].abs()- at_infinity = w == 0- safe_w = torch.where(at_infinity, torch.ones_like(w), w)- distance = torch.where(at_infinity, torch.full_like(distance, torch.inf), distance / safe_w)- return distance+ distance = distance / _nonzero(w)+ singular = singular | (w == 0)+ return _inf_where(distance, singular)def batched_dot_product(x: torch.Tensor, y: torch.Tensor, keepdim: bool = False) -> torch.Tensor:diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.pyindex 802df72c6..83a6e55f9 100644--- a/kornia/geometry/ransac.py+++ b/kornia/geometry/ransac.py@@ -1363,7 +1363,7 @@ class RANSAC(nn.Module):# Casting (especially to half precision) changes the model. Classify that exact returned matrix in pixel# coordinates, in float64 so metric arithmetic does not add another round of low-precision error. The public# line/transfer forms also avoid cancellation in the normalized quadratic sampling basis near epipoles.- errors = self.error_fn(kp1_host[None], kp2_host[None], model[None].to(torch.float64), eps=0.0)[0]+ errors = self.error_fn(kp1_host[None], kp2_host[None], model[None].to(torch.float64))[0]mask = finite & (errors <= self.inl_th**2)if not self._is_supported(int(mask.sum())):return failurediff --git a/tests/geometry/epipolar/test_epipolar_metrics.py b/tests/geometry/epipolar/test_epipolar_metrics.pyindex 771f09f9f..b73817fc7 100644--- a/tests/geometry/epipolar/test_epipolar_metrics.py+++ b/tests/geometry/epipolar/test_epipolar_metrics.py@@ -28,6 +28,8 @@ from kornia.geometry.epipolar._metrics import (_sampson_errors,_sampson_from_quadratic_basis,_sampson_quadratic_basis,+ _symmetrical_epipolar_distance_manual_impl_,+ _symmetrical_epipolar_distance_matmul_impl_,)from kornia.geometry.epipolar.fundamental import _rank2_projection@@ -319,30 +321,110 @@ class TestConventionEpipolarMetrics(BaseTester):self.assert_close(fn(_hom(x1), _hom(x2), F), fn(x1, x2, F))assert ((fn(2.0 * _hom(x1), _hom(x2), F) - fn(x1, x2, F)).abs() / fn(x1, x2, F)).min() > 0.25- def test_wart_metrics_eps_scale_dependence_4881(self, device, dtype):+ def test_metrics_do_not_depend_on_the_scale_of_F_4881(self, device, dtype):two_view = two_view_scene(device, dtype)if dtype in (torch.float16, torch.bfloat16):pytest.skip(_HALF_PIXEL_F)x1 = two_view["x1"]x2 = two_view["x2"] + torch.tensor([_NOISE], device=device, dtype=dtype)F = _pixel_F_unit_norm(two_view)- # #4881: eps is added inside the denominators, so the distance depends on the scale of F: the same F at- # ||F|| = 1e-3 scores much lower than at ||F|| = 1. Once fixed the two agree.- # Select Sampson's manual path on every device; its CUDA matmul path omits denominator eps.- for fn in (+ # #4881: eps was added inside the denominators, so the same F at ||F|| = 1e-3 scored 90% lower than at+ # ||F|| = 1, and 1e-6 F moved the one-way distances by a few percent. Every path on every device: the manual,+ # matmul and shared-point (two models) Sampson implementations, both symmetrical ones and the one-way+ # distances. The tolerance is float32 roundoff of the cancelling residual, as in the convention test above.+ paths = (partial(epi.sampson_epipolar_distance, use_matmul_at_less_than_points=0),- epi.symmetrical_epipolar_distance,+ _sampson_epipolar_distance_matmul_impl_,+ lambda a, b, F: _sampson_epipolar_distance_shared_impl_(a, b, F.expand(2, 3, 3), True)[:1],+ _symmetrical_epipolar_distance_manual_impl_,+ _symmetrical_epipolar_distance_matmul_impl_,+ epi.left_to_right_epipolar_distance,+ epi.right_to_left_epipolar_distance,+ )+ for fn in paths:+ unit = fn(x1, x2, F)+ for scale in (1e-6, 1e-3, 1e3):+ self.assert_close(fn(x1, x2, scale * F), unit, rtol=1e-3, atol=0.0)++ def test_exact_match_is_zero_with_a_zero_gradient_4881(self, device, dtype):+ # #4881: squared=False returned sqrt(d^2 + eps), 1e-4 for an exact match, and eps=0 returned 0 with a NaN+ # gradient. The first pts2 lies on the epiline of its pts1 (the fixture of test_shift), exact in every dtype.+ Fm = torch.tensor([[[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]]], device=device, dtype=dtype)+ pts1 = torch.zeros(1, 3, 2, device=device, dtype=dtype)+ pts2 = torch.tensor([[[2.0, 0.0], [2.0, 1.0], [2.0, 2.0]]], device=device, dtype=dtype, requires_grad=True)+ sampson, symmetrical = [0.0, 0.5, 2.0], [0.0, 2.0, 8.0]+ for fn, expected in (+ (partial(epi.sampson_epipolar_distance, use_matmul_at_less_than_points=0), sampson),+ (_sampson_epipolar_distance_matmul_impl_, sampson),+ (+ lambda a, b, F, squared: _sampson_epipolar_distance_shared_impl_(a, b, F.expand(2, 3, 3), squared)[:1],+ sampson,+ ),+ (_symmetrical_epipolar_distance_manual_impl_, symmetrical),+ (_symmetrical_epipolar_distance_matmul_impl_, symmetrical),+ ):+ out = fn(pts1, pts2, Fm, squared=False)+ self.assert_close(out, torch.tensor([expected], device=device, dtype=dtype).sqrt())+ assert out[0, 0] == 0+ (grad,) = torch.autograd.grad(out.sum(), pts2)+ assert torch.isfinite(grad).all()+ assert torch.equal(grad[0, 0], torch.zeros_like(grad[0, 0]))++ def test_degenerate_epilines_are_inf_4881(self, device, dtype):+ # F = diag(0, 0, 1): every epiline has a = b = 0. The manual Sampson path returned residual^2 / eps = 1e8 there+ # and the matmul path inf (#4881). Every path returns inf, with a finite gradient.+ pts1 = torch.rand(1, 5, 2, device=device, dtype=dtype, requires_grad=True)+ pts2 = torch.rand(1, 5, 2, device=device, dtype=dtype)+ Fm = torch.zeros(1, 3, 3, device=device, dtype=dtype)+ Fm[:, 2, 2] = 1.0+ paths = (+ partial(epi.sampson_epipolar_distance, use_matmul_at_less_than_points=0),+ _sampson_epipolar_distance_matmul_impl_,+ lambda a, b, F, squared: _sampson_epipolar_distance_shared_impl_(a, b, F.expand(2, 3, 3), squared)[:1],+ _symmetrical_epipolar_distance_manual_impl_,+ _symmetrical_epipolar_distance_matmul_impl_,+ )+ outputs = [fn(pts1, pts2, Fm, squared=squared) for fn in paths for squared in (True, False)]+ outputs += [+ epi.left_to_right_epipolar_distance(pts1, pts2, Fm),+ epi.right_to_left_epipolar_distance(pts1, pts2, Fm),+ ]+ for out in outputs:+ assert out.isposinf().all(), out+ (grad,) = torch.autograd.grad(out.sum(), pts1)+ assert torch.isfinite(grad).all(), grad++ def test_one_singular_epiline_4881(self, device, dtype):+ # F = [[1, 0, 0], [0, 0, 0], [0, 0, 1]] (rank 2) maps (0, 5) to the line at infinity (0, 0, 1): row 0's+ # epiline F x in image 2 and row 1's F^T x' in image 1; the other epiline of both is (2, 0, 1) and the residual+ # 1. Row 2 is regular: F x = (2, 0, 1), F^T x' = (1, 0, 1), residual 3. The symmetrical distance is inf when+ # either epiline is singular, the Sampson distance only when both are (#4881), so it stays 1 / (0 + 4) there.+ Fm = torch.tensor([[[1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ pts1 = torch.tensor([[[0.0, 5.0], [2.0, 3.0], [2.0, 3.0]]], device=device, dtype=dtype, requires_grad=True)+ pts2 = torch.tensor([[[2.0, 3.0], [0.0, 5.0], [1.0, 1.0]]], device=device, dtype=dtype)+ inf = float("inf")+ sampson, symmetrical = [0.25, 0.25, 1.8], [inf, inf, 11.25]+ for fn, expected in (+ (partial(epi.sampson_epipolar_distance, use_matmul_at_less_than_points=0), sampson),+ (_sampson_epipolar_distance_matmul_impl_, sampson),+ (+ lambda a, b, F, squared: _sampson_epipolar_distance_shared_impl_(a, b, F.expand(2, 3, 3), squared)[:1],+ sampson,+ ),+ (_symmetrical_epipolar_distance_manual_impl_, symmetrical),+ (_symmetrical_epipolar_distance_matmul_impl_, symmetrical),):- unit, small = fn(x1, x2, F), fn(x1, x2, 1e-3 * F)- assert ((unit - small).abs() / unit).min() > 0.5- # squared=False returns sqrt(d^2 + eps), so an exact match scores about sqrt(eps) = 1e-4, not 0.- exact = fn(x1, two_view["x2"], F, squared=False)- assert (exact > 0.9e-4).all()- # The one-way distances go through point_line_distance, which adds eps to the line norm: at ||F|| = 1e-6 the- # value moves by a few percent.- for fn in (epi.left_to_right_epipolar_distance, epi.right_to_left_epipolar_distance):- unit, tiny = fn(x1, x2, F), fn(x1, x2, 1e-6 * F)- assert ((unit - tiny).abs() / unit).min() > 1e-2+ for squared in (True, False):+ out = fn(pts1, pts2, Fm, squared=squared)+ target = torch.tensor([expected], device=device, dtype=dtype)+ self.assert_close(out, target if squared else target.sqrt())+ (grad,) = torch.autograd.grad(out.sum(), pts1)+ assert torch.isfinite(grad).all(), grad+ # The one-way distances: |ax + by + c| / ||(a, b)|| to the epiline of the other point.+ expected = torch.tensor([[inf, 0.5, 1.5]], device=device, dtype=dtype)+ self.assert_close(epi.left_to_right_epipolar_distance(pts1, pts2, Fm), expected)+ expected = torch.tensor([[0.5, inf, 3.0]], device=device, dtype=dtype)+ self.assert_close(epi.right_to_left_epipolar_distance(pts1, pts2, Fm), expected)def _near_epipole_scene(n: int, seed: int):@@ -365,24 +447,22 @@ class TestSampsonSharedPoints(BaseTester):"""One point set scored against many fundamental matrices: two matrix products instead of per-model broadcasting."""@pytest.mark.parametrize("squared", [True, False])- def test_public_dispatch_and_eps_4881(self, device, dtype, squared):+ def test_public_dispatch_and_paths_agree_4881(self, device, dtype, squared):if dtype in (torch.float16, torch.bfloat16):- pytest.skip("eps = 1e-8 is below half precision's resolution")- # 256 matrices x 300 points reach the shared path on every device. At 1e-4 of unit scale, eps moves the- # distances by tens of percent, so the comparison tells the CPU rule (eps in the denominator) from the CUDA- # matmul one (no eps in the denominator, #4881).+ pytest.skip("compared at float32 and float64 accuracy")+ # 256 matrices x 300 points reach the shared path on every device. At 1e-4 of unit scale the eps that the+ # manual path added to the denominator moved the distances by tens of percent against the CUDA matmul path+ # (#4881); the three implementations agree to roundoff.generator = torch.Generator().manual_seed(5)pts1 = torch.rand(1, 300, 2, generator=generator).to(device, dtype)pts2 = torch.rand(1, 300, 2, generator=generator).to(device, dtype)Fm = 1e-4 * create_random_fundamental_matrix(256, dtype=dtype, device=device)out = epi.sampson_epipolar_distance(pts1, pts2, Fm, squared=squared)- matmul = device.type == "cuda"- shared = _sampson_epipolar_distance_shared_impl_(pts1, pts2, Fm, squared, 1e-8, 0.0 if matmul else 1e-8)- assert torch.equal(out, shared)- reference = _sampson_epipolar_distance_matmul_impl_ if matmul else _sampson_epipolar_distance_manual_impl_- expected = reference(pts1, pts2, Fm, squared, 1e-8)- # Roundoff on the near-zero distances aside, eps in or out of the denominator is a 20-60% difference.- self.assert_close(out, expected, rtol=1e-3, atol=1e-3 * float(expected.abs().median()))+ assert torch.equal(out, _sampson_epipolar_distance_shared_impl_(pts1, pts2, Fm, squared))+ for reference in (_sampson_epipolar_distance_manual_impl_, _sampson_epipolar_distance_matmul_impl_):+ expected = reference(pts1, pts2, Fm, squared)+ # Roundoff on the near-zero distances aside.+ self.assert_close(out, expected, rtol=1e-3, atol=1e-3 * float(expected.abs().median()))def test_single_matrix_without_batch_dimension(self, device, dtype):if device.type != "cuda":@@ -409,7 +489,7 @@ class TestSampsonSharedPoints(BaseTester):else _sampson_epipolar_distance_manual_impl_)work = torch.promote_types(dtype, torch.float32)- expected = other(pts1.to(work), pts2.to(work), Fm.to(work), squared, 1e-8).to(dtype)+ expected = other(pts1.to(work), pts2.to(work), Fm.to(work), squared).to(dtype)assert out.dtype == dtypeself.assert_close(out, expected)@@ -419,19 +499,19 @@ class TestSampsonSharedPoints(BaseTester):[torch.rand(1, 7, 2, device=device, dtype=dtype), torch.ones(1, 7, 1, device=device, dtype=dtype)], -1)Fm = create_random_fundamental_matrix(6, dtype=dtype, device=device).reshape(2, 3, 3, 3)- assert _sampson_epipolar_distance_shared_impl_(pts1, pts2, Fm, True, 1e-8, 1e-8).shape == (2, 3, 7)- assert _sampson_epipolar_distance_shared_impl_(pts1[0, 0], pts2[0], Fm[0], True, 1e-8, 1e-8).shape == (3, 7)+ assert _sampson_epipolar_distance_shared_impl_(pts1, pts2, Fm, True).shape == (2, 3, 7)+ assert _sampson_epipolar_distance_shared_impl_(pts1[0, 0], pts2[0], Fm[0], True).shape == (3, 7)empty = torch.zeros(1, 0, 2, device=device, dtype=dtype)- assert _sampson_epipolar_distance_shared_impl_(empty, empty, Fm[0], True, 1e-8, 1e-8).shape == (3, 0)+ assert _sampson_epipolar_distance_shared_impl_(empty, empty, Fm[0], True).shape == (3, 0)def test_homogeneous_points_are_used_as_given(self, device, dtype):pts1 = torch.rand(1, 9, 2, device=device, dtype=dtype)pts2 = torch.rand(1, 9, 2, device=device, dtype=dtype)Fm = create_random_fundamental_matrix(3, dtype=dtype, device=device)scaled = 2.0 * _hom(pts1)- out = _sampson_epipolar_distance_shared_impl_(scaled, pts2, Fm, True, 1e-8, 1e-8)+ out = _sampson_epipolar_distance_shared_impl_(scaled, pts2, Fm, True)work = torch.promote_types(dtype, torch.float32)- expected = _sampson_epipolar_distance_manual_impl_(scaled.to(work), pts2.to(work), Fm.to(work), True, 1e-8)+ expected = _sampson_epipolar_distance_manual_impl_(scaled.to(work), pts2.to(work), Fm.to(work), True)self.assert_close(out, expected.to(dtype))def test_non_contiguous_and_mixed_dtype_models(self, device, dtype):@@ -440,13 +520,11 @@ class TestSampsonSharedPoints(BaseTester):pts1 = torch.rand(1, 11, 2, device=device, dtype=torch.float64)pts2 = torch.rand(1, 11, 2, device=device, dtype=torch.float64)Fm = create_random_fundamental_matrix(4, dtype=dtype, device=device)- out = _sampson_epipolar_distance_shared_impl_(pts1, pts2, Fm.mT, True, 1e-8, 1e-8)+ out = _sampson_epipolar_distance_shared_impl_(pts1, pts2, Fm.mT, True)assert out.dtype == torch.promote_types(torch.float64, dtype)- self.assert_close(- out, _sampson_epipolar_distance_shared_impl_(pts1, pts2, Fm.mT.contiguous(), True, 1e-8, 1e-8)- )+ self.assert_close(out, _sampson_epipolar_distance_shared_impl_(pts1, pts2, Fm.mT.contiguous(), True))one = Fm[:1].expand(5, 3, 3)- expanded = _sampson_epipolar_distance_shared_impl_(pts1, pts2, one, True, 1e-8, 1e-8)+ expanded = _sampson_epipolar_distance_shared_impl_(pts1, pts2, one, True)self.assert_close(expanded, expanded[:1].expand_as(expanded))def test_residual_order_regression(self, device, dtype):@@ -460,10 +538,10 @@ class TestSampsonSharedPoints(BaseTester):x1 = torch.tensor([[[1000.1, 1000.2]]], device=device, dtype=dtype)x2 = torch.tensor([[[1000.3, 1000.4]]], device=device, dtype=dtype)models = F.expand(64, 3, 3)- shared = _sampson_epipolar_distance_shared_impl_(x1, x2, models, True, 0.0, 0.0)[:, 0].cpu().double()- manual = _sampson_epipolar_distance_manual_impl_(x1, x2, F[None], True, 0.0)[0, 0].cpu().double()+ shared = _sampson_epipolar_distance_shared_impl_(x1, x2, models, True)[:, 0].cpu().double()+ manual = _sampson_epipolar_distance_manual_impl_(x1, x2, F[None], True)[0, 0].cpu().double()reference = _sampson_epipolar_distance_manual_impl_(- x1.cpu().double(), x2.cpu().double(), F[None].cpu().double(), True, 0.0+ x1.cpu().double(), x2.cpu().double(), F[None].cpu().double(), True)reference = reference[0, 0].cpu()self.assert_close(shared, manual.expand_as(shared), rtol=1e-4, atol=0.0)@@ -476,10 +554,10 @@ class TestSampsonSharedPoints(BaseTester):x1, x2, F = _near_epipole_scene(2000, seed=seed)perturb = 1 + 1e-4 * torch.randn(7, 3, 3, generator=torch.Generator().manual_seed(1), dtype=torch.float64)models = torch.cat([F[None], F[None] * perturb])- reference = _sampson_epipolar_distance_manual_impl_(x1[None], x2[None], models, True, 0.0)+ reference = _sampson_epipolar_distance_manual_impl_(x1[None], x2[None], models, True)cast = lambda t: t.to(device, dtype) # noqa: E731- shared = _sampson_epipolar_distance_shared_impl_(cast(x1[None]), cast(x2[None]), cast(models), True, 0.0, 0.0)- manual = _sampson_epipolar_distance_manual_impl_(cast(x1[None]), cast(x2[None]), cast(models), True, 0.0)+ shared = _sampson_epipolar_distance_shared_impl_(cast(x1[None]), cast(x2[None]), cast(models), True)+ manual = _sampson_epipolar_distance_manual_impl_(cast(x1[None]), cast(x2[None]), cast(models), True)shared, manual = shared.cpu().double(), manual.cpu().double()assert torch.isfinite(shared).all()assert (shared >= 0).all()@@ -505,7 +583,7 @@ class TestSampsonSharedPoints(BaseTester):perturbed = Fn + 1e-3 * torch.randn(7, 3, 3, generator=generator, dtype=torch.float64)models = torch.cat([Fn[None], _rank2_projection(perturbed)])models = models / models.flatten(1).norm(dim=1)[:, None, None]- reference = _sampson_errors(models, h1, h2, 0.0)+ reference = _sampson_errors(models, h1, h2)cast = lambda t: t.to(device, torch.float32) # noqa: E731errors = _sampson_from_quadratic_basis(cast(models), _sampson_quadratic_basis(cast(h1), cast(h2)))errors = errors.cpu().double()@@ -525,6 +603,4 @@ class TestSampsonSharedPoints(BaseTester):pts1 = torch.rand(1, 5, 2, device=device, dtype=torch.float64)pts2 = torch.rand(1, 5, 2, device=device, dtype=torch.float64)Fm = create_random_fundamental_matrix(3, dtype=torch.float64, device=device)- self.gradcheck(- lambda a, b, F: _sampson_epipolar_distance_shared_impl_(a, b, F, True, 1e-8, 1e-8), (pts1, pts2, Fm)- )+ self.gradcheck(lambda a, b, F: _sampson_epipolar_distance_shared_impl_(a, b, F, True), (pts1, pts2, Fm))diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.pyindex 121ae0262..36858edc2 100644--- a/tests/geometry/test_homography.py+++ b/tests/geometry/test_homography.py@@ -1330,20 +1330,53 @@ class TestConventionHomography(BaseTester):self.assert_close(calls[1][0][0, k], torch.full((), 0.5, device=device, dtype=dtype).neg().exp())assert (calls[1][0] - torch.exp(-e / (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",- )+ def test_transfer_error_does_not_depend_on_the_scale_of_H_4881(self, device, dtype):+ _skip_half(dtype, "1e-8 H flushes to zero in float16; compared at float32 and float64 accuracy")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+ p2 = p2 + torch.tensor([1.5, -2.0], device=device, dtype=dtype)+ # #4881: eps was added to the projective denominator, so 1e-8 H scored tens of pixels on exact matches. The+ # per-homography and the shared-point (several homographies) paths, and the symmetric error.+ for fn in (+ oneway_transfer_error,+ lambda a, b, H, **kw: oneway_transfer_error(a, b, H.expand(2, 3, 3), **kw)[:1],+ symmetric_transfer_error,+ ):+ unit = fn(p1, p2, H, squared=False)+ for scale in (1e-8, 1e-3, 1e6):+ self.assert_close(fn(p1, p2, scale * H, squared=False), unit)++ def test_transfer_error_exact_match_is_zero_with_a_zero_gradient_4881(self, device, dtype):+ # #4881: eps was added inside the square root, so an exact match scored sqrt(1e-8) = 1e-4, not 0, with+ # squared=False, and eps=0 gave a NaN gradient. A translation of integer points is exact in every dtype.+ H = torch.tensor([[[1.0, 0.0, 3.0], [0.0, 1.0, -2.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ p1 = torch.tensor([[[0.0, 0.0], [4.0, 1.0], [-2.0, 5.0]]], device=device, dtype=dtype)+ p2 = (p1 + torch.tensor([3.0, -2.0], device=device, dtype=dtype)).requires_grad_(True)+ for fn in (+ oneway_transfer_error,+ lambda a, b, H, **kw: oneway_transfer_error(a, b, H.expand(2, 3, 3), **kw)[:1],+ symmetric_transfer_error,+ ):+ out = fn(p1, p2, H, squared=False)+ assert torch.equal(out, torch.zeros_like(out)), out+ (grad,) = torch.autograd.grad(out.sum(), p2)+ assert torch.equal(grad, torch.zeros_like(grad)), grad++ def test_transfer_error_of_a_point_mapped_to_infinity_is_inf_4881(self, device, dtype):+ # H maps x = -1 to w' = 0. The error there used to be x' / eps squared (#4881); it is inf, with a finite+ # gradient, and the other point is untouched.+ H = torch.tensor([[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 0.0, 1.0]]], device=device, dtype=dtype)+ p1 = torch.tensor([[[-1.0, 0.0], [0.0, 0.0]]], device=device, dtype=dtype, requires_grad=True)+ p2 = torch.tensor([[[5.0, 5.0], [0.0, 0.0]]], device=device, dtype=dtype)+ for fn in (+ oneway_transfer_error,+ lambda a, b, H, **kw: oneway_transfer_error(a, b, H.expand(2, 3, 3), **kw)[:1],+ symmetric_transfer_error,+ ):+ for squared in (True, False):+ out = fn(p1, p2, H, squared=squared)+ assert bool(out[0, 0].isposinf()) and out[0, 1] == 0, out+ (grad,) = torch.autograd.grad(out.sum(), p1)+ assert torch.isfinite(grad).all(), grad@pytest.mark.parametrize("model", ["points", "lines"])def test_convention_find_homography_dlt_h22_eps_divisor_4874(self, model, device, dtype):@@ -1434,7 +1467,7 @@ class TestHomographySharedKernels(BaseTester):H = torch.eye(3) + 0.1 * (2 * torch.rand(3, 3, 3, generator=generator) - 1)H = H.to(device, dtype)out = oneway_transfer_error(pts1, pts2, H)- assert torch.equal(out, _oneway_transfer_error_shared_impl_(pts1, pts2, H, True, 1e-8))+ assert torch.equal(out, _oneway_transfer_error_shared_impl_(pts1, pts2, H, True))per_model = torch.cat([oneway_transfer_error(pts1, pts2, H[i : i + 1]) for i in range(3)])self.assert_close(out, per_model)@@ -1443,11 +1476,11 @@ class TestHomographySharedKernels(BaseTester):pts1 = torch.rand(1, 7, 2, device=device, dtype=dtype)pts2 = torch.rand(1, 7, 2, device=device, dtype=dtype)# Homogeneous points are dehomogenized, whatever their w.- out = _oneway_transfer_error_shared_impl_(2.0 * _hom(pts1), 3.0 * _hom(pts2), H, True, 1e-8)- self.assert_close(out, _oneway_transfer_error_shared_impl_(pts1, pts2, H, True, 1e-8))- self.assert_close(out, _oneway_transfer_error_shared_impl_(pts1, pts2, H.mT.contiguous().mT, True, 1e-8))+ out = _oneway_transfer_error_shared_impl_(2.0 * _hom(pts1), 3.0 * _hom(pts2), H, True)+ self.assert_close(out, _oneway_transfer_error_shared_impl_(pts1, pts2, H, True))+ self.assert_close(out, _oneway_transfer_error_shared_impl_(pts1, pts2, H.mT.contiguous().mT, True))empty = torch.zeros(1, 0, 2, device=device, dtype=dtype)- assert _oneway_transfer_error_shared_impl_(empty, empty, H, True, 1e-8).shape == (4, 0)+ assert _oneway_transfer_error_shared_impl_(empty, empty, H, True).shape == (4, 0)def test_pixel_scale_accuracy(self, device, dtype):if dtype != torch.float32:@@ -1479,7 +1512,7 @@ class TestHomographySharedKernels(BaseTester):models = torch.randn(6, 3, 3, device=device, dtype=dtype)self.assert_close(_transfer_from_basis(models, _transfer_basis(x1, x2)),- _transfer_errors(models, x1, x2, 0.0),+ _transfer_errors(models, x1, x2),rtol=1e-3,atol=1e-5,)@@ -1488,4 +1521,4 @@ class TestHomographySharedKernels(BaseTester):pts1 = torch.rand(1, 5, 2, device=device, dtype=torch.float64)pts2 = torch.rand(1, 5, 2, device=device, dtype=torch.float64)H = create_random_homography(torch.zeros(3, 1, device=device, dtype=torch.float64), 3, std_val=0.1)- self.gradcheck(lambda a, b, h: _oneway_transfer_error_shared_impl_(a, b, h, True, 1e-8), (pts1, pts2, H))+ self.gradcheck(lambda a, b, h: _oneway_transfer_error_shared_impl_(a, b, h, True), (pts1, pts2, H))diff --git a/tests/geometry/test_linalg.py b/tests/geometry/test_linalg.pyindex 76cec3b04..e4ac5bdbc 100644--- a/tests/geometry/test_linalg.py+++ b/tests/geometry/test_linalg.py@@ -657,25 +657,19 @@ class TestLinalgConventions(BaseTester):# control: the same-order call is off by more than 1 on this pairassert (kgl.relative_transformation(e1, e2)[:3] - expected).abs().max() > 0.5- def test_wart_point_line_distance_eps_bias_4881(self, device, dtype):- # https://github.com/kornia/kornia/issues/4881: eps is added to the line norm,- # |ax + by + c| / (||(a, b)|| + eps), so the distance depends on the scale of the line. The point (1.5, -0.7)- # is 2.34 from 3x + 4y + 10 = 0 at every scale (11.7 / 5); at scale 1e-9 the norm is 5e-9 and the result is- # 2.34 * 5 / 6 = 1.95 (-16.7 %).+ def test_point_line_distance_does_not_depend_on_the_scale_of_the_line_4881(self, device, dtype):+ # #4881: eps = 1e-9 was added to the line norm, |ax + by + c| / (||(a, b)|| + eps), so the point (1.5, -0.7)+ # was 1.95 from 1e-9 * (3x + 4y + 10 = 0) instead of 2.34 (11.7 / 5), and a line with a = b = 0 scored+ # |c| / eps. The distance is the same at every scale, and such a line is at distance inf.point = torch.tensor([[1.5, -0.7]], device=device, dtype=dtype)line = torch.tensor([[3.0, 4.0, 10.0]], device=device, dtype=dtype)exact = torch.tensor([2.34], device=device, dtype=dtype)- self.assert_close(kgl.point_line_distance(point, line), exact)- degenerate = kgl.point_line_distance(point, torch.tensor([[0.0, 0.0, 1.0]], device=device, dtype=dtype))- zero_line = kgl.point_line_distance(point, torch.zeros(1, 3, device=device, dtype=dtype))- if dtype == torch.float16:- # The default eps=1e-9 rounds to zero in float16 (and a 1e-9-scaled line underflows), so the degenerate- # line gives inf and the all-zero line 0 / 0 = nan.- assert torch.isinf(degenerate).all() and torch.isnan(zero_line).all()- return- scaled = kgl.point_line_distance(point, 1e-9 * line)- assert ((scaled - exact) / exact).max() < -0.1- # A degenerate line (0, 0, 1) returns |c| / eps = 1e9 instead of flagging the singular case, and the all-zero- # line returns 0 / eps = 0.- assert torch.isfinite(degenerate).all() and (degenerate > 1e8).all()- assert torch.equal(zero_line, torch.zeros_like(zero_line))+ # A 1e-9-scaled line flushes to zero in float16, and the squared norm of a 1e3-scaled one overflows it.+ scales = (1.0, 1e-3, 10.0) if dtype == torch.float16 else (1.0, 1e-9, 1e3)+ for scale in scales:+ self.assert_close(kgl.point_line_distance(point, scale * line), exact)+ singular = torch.tensor([[0.0, 0.0, 1.0], [0.0, 0.0, 0.0]], device=device, dtype=dtype, requires_grad=True)+ distance = kgl.point_line_distance(point, singular)+ assert distance.isposinf().all(), distance+ distance.sum().backward()+ assert torch.isfinite(singular.grad).all(), singular.graddiff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.pyindex 40c304f9d..8141c1637 100644--- a/tests/geometry/test_ransac.py+++ b/tests/geometry/test_ransac.py@@ -2037,14 +2037,14 @@ class TestRANSACLevenbergMarquardtKernels(BaseTester):refine, scale2, x2_arg = _refine_homography_lm, (2.0 / s2) ** 2, x2[:, :2]def errors(models):- return _transfer_errors(models, x1, x2[:, :2], 0.0)+ return _transfer_errors(models, x1, x2[:, :2])else:start = torch.linalg.inv(t2).mT @ truth @ torch.linalg.inv(t1)refine, scale2, x2_arg = _refine_fundamental_lm, (2.0 / s1) ** 2, x2def errors(models):- return _sampson_errors(models, x1, x2, 0.0)+ return _sampson_errors(models, x1, x2)start = start / start.norm()start = start + 1e-2 * torch.randn(3, 3, generator=torch.Generator().manual_seed(0), dtype=torch.float64)