π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(epipolar): Convention blocks and pins for the two-view F/E contract (batch 8a) (#4887)
Dmytro Mishkin5783577baa77
diff --git a/changelog.d/4887.added.md b/changelog.d/4887.added.mdnew file mode 100644index 000000000..35d584e22--- /dev/null+++ b/changelog.d/4887.added.md@@ -0,0 +1 @@+Convention blocks for the two-view F/E contract (`find_fundamental`, `find_essential`, the epipolar metrics, `decompose_essential_matrix` and their siblings), a "Two-view geometry" section on the Conventions & Pitfalls page with the OpenCV mapping, and 28 convention and wart pins; the warts are documented and linked (#2198, #4831, #4855, #4862, #4874β#4881, #4883, #4884), not fixed.diff --git a/docs/source/geometry.epipolar.rst b/docs/source/geometry.epipolar.rstindex 69a9a9166..9b2400a2e 100644--- a/docs/source/geometry.epipolar.rst+++ b/docs/source/geometry.epipolar.rst@@ -19,6 +19,7 @@ Essential.. autofunction:: essential_from_fundamental.. autofunction:: essential_from_Rt.. autofunction:: decompose_essential_matrix+.. autofunction:: decompose_essential_matrix_no_svd.. autofunction:: motion_from_essential.. autofunction:: motion_from_essential_choose_solution.. autofunction:: relative_camera_motiondiff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex 2a9c44ce5..4cd7b96e8 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -467,6 +467,73 @@ The equivalences hold on every window that holds an in-image kernel cell while :``max_val``: an empty ``geodesic`` window returns an infinity in scipy and scikit-image and a finite value builtfrom ``max_val`` in kornia (`#4734 <https://github.com/kornia/kornia/issues/4734>`_).+.. _two-view-conventions:++Two-view geometry+-----------------++The two-view estimators take the first image's points first and follow OpenCV's order:+:func:`~kornia.geometry.epipolar.find_fundamental` returns an ``F`` with :math:`x_2^\top F x_1 = 0` in image+coordinates and :func:`~kornia.geometry.epipolar.find_essential` an ``E`` with :math:`x_2^\top E x_1 = 0` in+normalised camera coordinates, and :func:`~kornia.geometry.homography.find_homography_dlt` and+:class:`~kornia.geometry.ransac.RANSAC` with ``model_type="homography"`` return an ``H`` that maps ``points1`` to+``points2``. Extrinsics are world-to-camera, as in :doc:`/get-started/camera-conventions`. Side by side:++.. list-table::+ :header-rows: 1++ * - Topic+ - kornia+ - OpenCV+ * - fundamental matrix+ - ``find_fundamental(points1, points2)``, scaled to ``F[2, 2] = 1`` unless that entry is numerically zero;+ ``method="7POINT"`` returns three candidates ``(B, 3, 3, 3)`` in no particular order, padded when the cubic+ has one real root (`#4862 <https://github.com/kornia/kornia/issues/4862>`_)+ - ``findFundamentalMat(points1, points2)``, the same ``F``; ``FM_7POINT`` stacks only the real solutions as+ ``(3k, 3)``+ * - essential matrix+ - ``find_essential`` takes normalised camera coordinates :math:`K^{-1} [u, v, 1]^\top` and returns ten+ slots, ``NaN`` for complex roots; a sample with no real solution returns ten identity matrices+ (`#4883 <https://github.com/kornia/kornia/issues/4883>`_)+ - ``findEssentialMat`` takes pixels and ``cameraMatrix`` (or one matrix per camera); with exactly 5 points it+ stacks the real solutions as ``(3k, 3)``, with more it returns the single ``E`` its RANSAC or LMedS selects+ * - homography+ - ``find_homography_dlt(points1, points2)`` maps ``points1`` to ``points2``+ - ``findHomography(src, dst)``, the same direction+ * - pose from ``E``+ - ``decompose_essential_matrix`` returns ``R1``, ``R2`` and a unit ``t``; which candidate is the true pose is+ not fixed.+ ``motion_from_essential_choose_solution`` selects it by cheirality from pixel coordinates, and returns+ candidate 0 when no point passes (`#4879 <https://github.com/kornia/kornia/issues/4879>`_)+ - ``decomposeEssentialMat`` returns the same candidate set, whose labels are not fixed either and differ from+ kornia's, so a candidate index does not port; ``recoverPose`` selects the same pose and also returns the+ inlier count+ * - projection matrix+ - ``KRt_from_projection`` returns the translation ``t`` of ``P = K [R | t]``; for ``det P[:, :3] < 0`` it+ returns a reflection (`#4864 <https://github.com/kornia/kornia/issues/4864>`_)+ - ``decomposeProjectionMatrix`` returns the homogeneous camera centre :math:`C = -R^\top t`; for+ ``det P[:, :3] < 0`` it keeps ``det R = 1`` and returns ``K[2, 2] < 0``+ * - triangulation+ - ``triangulate_points`` returns Euclidean points ``(*, N, 3)``+ - ``triangulatePoints`` returns homogeneous points ``(4, N)``+ * - epipolar lines+ - ``compute_correspond_epilines(x1, F)`` for first-image points; pass ``F.transpose(-2, -1)`` for+ second-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``+ * - RANSAC threshold+ - ``inl_th`` is a point distance in the keypoints' units, calibrated units for ``model_type="essential"``;+ for line segments it depends on the segment length (`#4867 <https://github.com/kornia/kornia/issues/4867>`_)+ - ``ransacReprojThreshold`` of ``findHomography``, the same unit for points+ * - polynomial roots+ - ``solve_quadratic``, ``solve_cubic`` and ``solve_quartic`` take coefficients highest degree first and+ return only the real roots, a missing root padded with ``0.0``; ``solve_quartic``'s order is unspecified;+ a zero leading coefficient gives wrong roots (`#4873 <https://github.com/kornia/kornia/issues/4873>`_)+ - ``numpy.roots`` takes the same coefficient order, returns the complex roots too and drops leading zeros+Pitfall checklist-----------------diff --git a/kornia/geometry/epipolar/_metrics.py b/kornia/geometry/epipolar/_metrics.pyindex 235bd209c..fca26f9ae 100644--- a/kornia/geometry/epipolar/_metrics.py+++ b/kornia/geometry/epipolar/_metrics.py@@ -142,17 +142,27 @@ def sampson_epipolar_distance(eps: float = 1e-8,use_matmul_at_less_than_points: int = 10000,) -> Tensor:- """Return Sampson distance for correspondences given the fundamental matrix.+ r"""Return Sampson distance for correspondences given the fundamental matrix.++ Convention:+ - ``pts1`` are first-image points, ``pts2`` second-image points, and ``Fm`` follows+ :math:`x_2^\top F x_1 = 0`, as returned by :func:`find_fundamental`+ (see :ref:`two-view geometry <two-view-conventions>`).+ - Returns squared pixel distances by default; a 3-vector point is used as given, so it must have+ :math:`w = 1`.+ - 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>`_).Args:- pts1: correspondences from the left images with shape :math:`(*, N, (2|3))`. If they are not homogeneous,- converted automatically.- pts2: correspondences from the right images with shape :math:`(*, N, (2|3))`. If they are not homogeneous,- converted automatically.+ 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.- eps: Small constant for safe sqrt.- use_matmul_at_less_than_points: If the number of points is less than this value, use the matmul implementation.+ 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.+ 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.Returns:the computed Sampson distance with shape :math:`(*, N)`.@@ -245,16 +255,21 @@ def _symmetrical_epipolar_distance_matmul_impl_(def symmetrical_epipolar_distance(pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool = True, eps: float = 1e-8) -> Tensor:- """Return symmetrical epipolar distance for correspondences given the fundamental matrix.+ r"""Return symmetrical epipolar distance for correspondences given the fundamental matrix.++ Convention:+ - Argument order and units as :func:`sampson_epipolar_distance`; the value is the sum of the two+ squared 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>`_).Args:- pts1: correspondences from the left images with shape :math:`(*, N, (2|3))`. If they are not homogeneous,- converted automatically.- pts2: correspondences from the right images with shape :math:`(*, N, (2|3))`. If they are not homogeneous,- converted automatically.+ 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.- eps: Small constant for safe sqrt.+ 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.Returns:the computed Symmetrical distance with shape :math:`(*, N)`.@@ -270,19 +285,20 @@ def symmetrical_epipolar_distance(def left_to_right_epipolar_distance(pts1: Tensor, pts2: Tensor, Fm: Tensor) -> Tensor:r"""Return one-sided epipolar distance for correspondences given the fundamental matrix.- This method measures the distance from points in the right images to the epilines- of the corresponding points in the left images as they reflect in the right images.+ Convention:+ - 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>`_).Args:- pts1: correspondences from the left images with shape- :math:`(*, N, 2 or 3)`. If they are not homogeneous, converted automatically.- pts2: correspondences from the right images with shape- :math:`(*, N, 2 or 3)`. If they are not homogeneous, converted automatically.+ 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 toavoid ambiguity with torch.nn.functional.Returns:- the computed Symmetrical distance with shape :math:`(*, N)`.+ the one-sided distance with shape :math:`(*, N)`."""KORNIA_CHECK_IS_TENSOR(pts1)@@ -304,19 +320,20 @@ def left_to_right_epipolar_distance(pts1: Tensor, pts2: Tensor, Fm: Tensor) -> Tdef right_to_left_epipolar_distance(pts1: Tensor, pts2: Tensor, Fm: Tensor) -> Tensor:r"""Return one-sided epipolar distance for correspondences given the fundamental matrix.- This method measures the distance from points in the left images to the epilines- of the corresponding points in the right images as they reflect in the left images.+ Convention:+ - 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>`_).Args:- pts1: correspondences from the left images with shape- :math:`(*, N, 2 or 3)`. If they are not homogeneous, converted automatically.- pts2: correspondences from the right images with shape- :math:`(*, N, 2 or 3)`. If they are not homogeneous, converted automatically.+ 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 toavoid ambiguity with torch.nn.functional.Returns:- the computed Symmetrical distance with shape :math:`(*, N)`.+ the one-sided distance with shape :math:`(*, N)`."""KORNIA_CHECK_IS_TENSOR(pts1)diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.pyindex 8fc6c8ede..8ab949628 100644--- a/kornia/geometry/epipolar/essential.py+++ b/kornia/geometry/epipolar/essential.py@@ -50,8 +50,8 @@ def run_5point(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[tand the solver implemented referred to [@barath2020magsac++][@wei2023generalized][@wang2023vggsfm].Args:- points1: A set of carlibrated points in the first image with a tensor shape :math:`(B, N, 2), N>=8`.- points2: A set of points in the second image with a tensor shape :math:`(B, N, 2), N>=8`.+ points1: A set of calibrated points in the first image with a tensor shape :math:`(B, N, 2), N>=5`.+ points2: A set of points in the second image with a tensor shape :math:`(B, N, 2), N>=5`.weights: Not used, kept for compatibility.Returns:@@ -455,6 +455,10 @@ def essential_from_fundamental(F_mat: torch.Tensor, K1: torch.Tensor, K2: torch.Uses the method from Hartley/Zisserman 9.6 pag 257 (formula 9.12).+ Convention:+ - :math:`E = K_2^\top F K_1` with ``K1`` the camera of the first image, so ``E`` follows the+ :math:`x_2^\top E x_1 = 0` order of :func:`find_essential`; it keeps the scale of ``F_mat``.+Args:F_mat: The fundamental matrix with shape of :math:`(*, 3, 3)`.K1: The camera matrix from first camera with shape :math:`(*, 3, 3)`.@@ -479,6 +483,9 @@ def project_to_essential(E_mat: torch.Tensor) -> torch.Tensor::func:`decompose_essential_matrix` and :func:`motion_from_essential`. The projection averagesthe two largest singular values and zeroes the smallest one.+ Convention:+ - The result is not normalised to unit Frobenius norm, unlike the candidates of :func:`find_essential`.+Args:E_mat: The matrices to project with shape :math:`(*, 3, 3)`.@@ -502,12 +509,22 @@ def decompose_essential_matrix(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torchThis function decomposes the essential matrix E using svd decomposition [96]and give the possible solutions: :math:`R1, R2, t`.+ Convention:+ - Returns two rotations and a unit translation; the true pose is one of :math:`(R_1, \pm t)`,+ :math:`(R_2, \pm t)`. :math:`(R_1, -t)` and :math:`(R_2, t)` give :math:`[t]_\times R` with the sign+ of ``E_mat``, :math:`(R_1, t)` and :math:`(R_2, -t)` the opposite sign. Which of the four is the true+ pose is not fixed: it can change when ``E_mat`` is negated or rescaled. Select by cheirality with+ :func:`motion_from_essential_choose_solution`; :ref:`two-view geometry <two-view-conventions>`+ compares OpenCV's labels.+ - Known defects: a ``(3, 3)`` input returns rotations of shape ``(1, 3, 3)`` but ``t`` of shape+ ``(3, 1)`` (`#4878 <https://github.com/kornia/kornia/issues/4878>`_).+Args:E_mat: The essential matrix in the form of :math:`(*, 3, 3)`.Returns:- A tuple containing the first and second possible rotation matrices and the translation vector.- The shape of the tensors with be same input :math:`[(*, 3, 3), (*, 3, 3), (*, 3, 1)]`.+ A tuple containing the first and second possible rotation matrices and the translation vector,+ with shapes :math:`[(*, 3, 3), (*, 3, 3), (*, 3, 1)]` for an input with a batch dimension."""KORNIA_CHECK_SHAPE(E_mat, ["*", "3", "3"])@@ -542,16 +559,21 @@ def decompose_essential_matrix(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torchdef decompose_essential_matrix_no_svd(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:r"""Decompose the essential matrix to rotation and translation.- Recover rotation and translation from essential matrices without SVD- reference: Horn, Berthold KP. Recovering baseline and orientation from essential matrix[J].- J. Opt. Soc. Am, 1990, 110.+ Recovers the rotations and translation from an essential matrix without SVD.+ Reference: Horn, Berthold KP. Recovering baseline and orientation from essential matrix[J].+ J. Opt. Soc. Am, 1990, 110.++ Convention:+ - Same candidate set as :func:`decompose_essential_matrix`, with ``t`` of unit norm.+ - Known defects: the rotations are wrong for a batch of more than one matrix+ (`#4880 <https://github.com/kornia/kornia/issues/4880>`_).Args:E_mat: The essential matrix in the form of :math:`(*, 3, 3)`.Returns:- A tuple containing the first and second possible rotation matrices and the translation vector.- The shape of the tensors with be same input :math:`[(*, 3, 3), (*, 3, 3), (*, 3, 1)]`.+ A tuple containing the first and second possible rotation matrices and the translation vector, with+ shapes :math:`[(B, 3, 3), (B, 3, 3), (B, 3, 1)]`: all leading dims are flattened into one batch dim."""KORNIA_CHECK_SHAPE(E_mat, ["*", "3", "3"])@@ -613,6 +635,11 @@ def essential_from_Rt(R1: torch.Tensor, t1: torch.Tensor, R2: torch.Tensor, t2:Reference: Hartley/Zisserman 9.6 pag 257 (formula 9.12)+ Convention:+ - Returns :math:`[t]_\times R` for the relative motion ``(R, t)`` of :func:`relative_camera_motion`, so+ :math:`x_2^\top E x_1 = 0` in normalised camera coordinates. It is not normalised:+ :math:`\|E\|_F = \sqrt{2} \|t\|`.+Args:R1: The first camera rotation matrix with shape :math:`(*, 3, 3)`.t1: The first camera translation vector with shape :math:`(*, 3, 1)`.@@ -643,6 +670,12 @@ def motion_from_essential(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch.TensComputes and return four possible poses exist for the decomposition of the Essentialmatrix. The possible solutions are :math:`[R1,t], [R1,-t], [R2,t], [R2,-t]`.+ Convention:+ - The candidates of :func:`decompose_essential_matrix` are stacked on dim ``-3`` in that order; which+ index is the true pose is not fixed.+ - Known defects: a ``(3, 3)`` input returns rotations of shape ``(1, 4, 3, 3)`` but translations of+ shape ``(4, 3, 1)`` (`#4878 <https://github.com/kornia/kornia/issues/4878>`_).+Args:E_mat: The essential matrix in the form of :math:`(*, 3, 3)`.@@ -674,26 +707,32 @@ def motion_from_essential_choose_solution(r"""Recover the relative camera rotation and the translation from an estimated essential matrix.The method checks the corresponding points in two images and also returns the triangulated- 3d points. Internally uses :py:meth:`~kornia.geometry.epipolar.decompose_essential_matrix` and then chooses- the best solution based on the combination that gives more 3d points in front of the camera plane from+ 3d points. Internally uses :py:meth:`~kornia.geometry.epipolar.decompose_essential_matrix` and:py:meth:`~kornia.geometry.epipolar.triangulate_points`.+ Convention:+ - ``K1`` and ``K2`` are applied inside, so ``x1`` and ``x2`` are pixel coordinates.+ - Returns the candidate with the most points at positive depth in both cameras, with+ :math:`\|t\| = 1`, and the points triangulated in the first camera's frame at that scale.+ - Known defects: in a batch every element uses the first element's candidate+ (`#2198 <https://github.com/kornia/kornia/issues/2198>`_); with no valid point it returns candidate 0+ without a signal (`#4879 <https://github.com/kornia/kornia/issues/4879>`_).+Args:- E_mat: The essential matrix in the form of :math:`(*, 3, 3)`.- K1: The camera matrix from first camera with shape :math:`(*, 3, 3)`.- K2: The camera matrix from second camera with shape :math:`(*, 3, 3)`.- x1: The set of points seen from the first camera frame in the camera plane- coordinates with shape :math:`(*, N, 2)`.- x2: The set of points seen from the first camera frame in the camera plane- coordinates with shape :math:`(*, N, 2)`.+ E_mat: The essential matrix in the form of :math:`(B, 3, 3)`, or :math:`(3, 3)` with every other input+ unbatched too.+ K1: The camera matrix from first camera with shape :math:`(B, 3, 3)`.+ K2: The camera matrix from second camera with shape :math:`(B, 3, 3)`.+ x1: The set of points in the first image with shape :math:`(B, N, 2)`.+ x2: The set of points in the second image with shape :math:`(B, N, 2)`.mask: A boolean mask which can be used to exclude some points from choosingthe best solution. This is useful for using this function with sets of points ofdifferent cardinality (for instance after filtering with RANSAC) while keeping batch- semantics. Mask is of shape :math:`(*, N)`.+ semantics. Mask is of shape :math:`(B, N)`.Returns:The rotation and translation plus the 3d triangulated points.- The tuple is as following :math:`[(*, 3, 3), (*, 3, 1), (*, N, 3)]`.+ The tuple is as following :math:`[(B, 3, 3), (B, 3, 1), (B, N, 3)]`, without ``B`` for unbatched inputs."""KORNIA_CHECK_SHAPE(E_mat, ["*", "3", "3"])@@ -777,6 +816,11 @@ def relative_camera_motion(one assuming the first one to be at the origin. If :math:`T1` and :math:`T2` are the camera motions,the computed relative motion is :math:`T = T_{2}T^{-1}_{1}`.+ Convention:+ - Inputs are world-to-camera extrinsics, :math:`x_{cam} = R X + t` (see :doc:`camera and world+ conventions </get-started/camera-conventions>`); the result is :math:`R = R_2 R_1^\top` and+ :math:`t = t_2 - R_2 R_1^\top t_1`, the motion from camera 1 to camera 2.+Args:R1: The first camera rotation matrix with shape :math:`(*, 3, 3)`.t1: The first camera translation vector with shape :math:`(*, 3, 1)`.@@ -807,15 +851,30 @@ def find_essential() -> torch.Tensor:r"""Find essential matrices.+ Convention:+ - ``points1`` (first image) and ``points2`` (second image) are normalised camera coordinates+ :math:`K^{-1} [u, v, 1]^\top`, not pixels; each real candidate satisfies :math:`x_2^\top E x_1 = 0`+ in them. :ref:`Two-view geometry <two-view-conventions>` maps this onto OpenCV.+ - All ten slots are always returned: each real root gives a candidate of unit Frobenius norm, and each+ complex root a ``NaN`` slot.+ - Known defects: ``weights`` is ignored (`#4876 <https://github.com/kornia/kornia/issues/4876>`_); a sample+ with no real solution returns ten identity matrices instead of ``NaN``+ (`#4883 <https://github.com/kornia/kornia/issues/4883>`_); in ``float32`` an exact five-point sample can+ miss the true solution, which six or more correspondences recover+ (`#4884 <https://github.com/kornia/kornia/issues/4884>`_); input gradients are wrong for fewer than 9+ correspondences (`#4855 <https://github.com/kornia/kornia/issues/4855>`_); backward raises on some+ degenerate samples, such as identical point sets (`#4831 <https://github.com/kornia/kornia/issues/4831>`_);+ on MPS the 5-point solve needs the CPU fallback (`#4528 <https://github.com/kornia/kornia/issues/4528>`_).+Args:points1: A set of points in the first image with a tensor shape :math:`(B, N, 2), N>=5`.points2: A set of points in the second image with a tensor shape :math:`(B, N, 2), N>=5`.- weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.+ weights: Accepted with a shape of :math:`(B, N)` and ignored (see Known defects).Returns:the computed essential matrices with shape :math:`(B, 10, 3, 3)`.- Note that all possible solutions are returned, i.e., 10 essential matrices for each image pair.- To choose the best one out of 10, try to check the one with the lowest Sampson distance.+ To choose the best one out of 10, try to check the one with the lowest Sampson distance, ignoring the+ ``NaN`` slots."""return run_5point(points1, points2, weights).to(points1.dtype)diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.pyindex 13f841c5e..6715887d3 100644--- a/kornia/geometry/epipolar/fundamental.py+++ b/kornia/geometry/epipolar/fundamental.py@@ -31,9 +31,8 @@ from kornia.geometry.solvers import solve_cubicdef normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]:r"""Normalize points (isotropic).- Computes the transformation matrix such that the two principal moments of the set of points- are equal to unity, forming an approximately symmetric circular cloud of points of radius 1- about the origin. Reference: Hartley/Zisserman 4.4.4 pag.107+ Computes the Hartley normalisation: the points are translated to zero mean and scaled isotropically so+ that their mean distance to the origin is :math:`\sqrt{2}`. Reference: Hartley/Zisserman 4.4.4 pag.107This operation is an essential step before applying the DLT algorithm in order to considerthe result as optimal.@@ -44,7 +43,7 @@ def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.TenReturns:tuple containing the normalized points in the shape :math:`(B, N, 2)` and the transformation matrix- in the shape :math:`(B, 3, 3)`.+ in the shape :math:`(B, 3, 3)` that maps the input points to them."""if points.ndim != 3:@@ -85,12 +84,17 @@ def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tendef normalize_transformation(M: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:r"""Normalize a given transformation matrix.- The function trakes the transformation matrix and normalize so that the value in- the last row and column is one.+ Convention:+ - Divides ``M`` by its last entry ``M[..., -1, -1]``, which gives :func:`find_fundamental` its+ ``F[2, 2] = 1`` scaling. A matrix whose last entry is within ``eps`` of zero is returned unchanged.+ - Known defects: the divisor is ``M[..., -1, -1] + eps``, so the last entry is not exactly one, and it is+ far from one when ``|M[..., -1, -1]|`` is close to ``eps``+ (`#4874 <https://github.com/kornia/kornia/issues/4874>`_).Args:M: The transformation to be normalized of any shape with a minimum size of 2x2.- eps: small value to avoid unstabilities during the backpropagation.+ eps: added to the divisor, and the magnitude of the last entry at or below which ``M`` is returned+ unchanged.Returns:the normalized transformation matrix with same shape as the input.@@ -156,8 +160,8 @@ def run_7point(points1: torch.Tensor, points2: torch.Tensor) -> torch.Tensor:r"""Compute the fundamental matrix using the 7-point algorithm.The 7-point algorithm computes the fundamental matrix from exactly 7 point correspondences.- Unlike the 8-point algorithm, this method can return up to 3 possible fundamental matrices- as solutions to the rank-2 constraint, which is formulated as a cubic equation.+ Unlike the 8-point algorithm, this method returns 3 candidate fundamental matrices, one per root of the+ cubic that formulates the rank-2 constraint, padded to three.Reference: Hartley/Zisserman 11.1.2 pag.281@@ -166,8 +170,9 @@ def run_7point(points1: torch.Tensor, points2: torch.Tensor) -> torch.Tensor:points2: A set of 7 points in the second image with shape :math:`(B, 7, 2)`.Returns:- The computed fundamental matrices with shape :math:`(B, 3, 3, 3)`, containing up to 3- candidate solutions per batch. Invalid solutions are zeroed out.+ The computed fundamental matrices with shape :math:`(B, 3, 3, 3)`, always 3 candidates per batch+ element. A cubic with a single real root still gives 3: the two extra candidates are one rank-3 matrix+ repeated, not zeros (`#4862 <https://github.com/kornia/kornia/issues/4862>`_)."""KORNIA_CHECK_SHAPE(points1, ["B", "7", "2"])@@ -334,14 +339,30 @@ def find_fundamental() -> torch.Tensor:r"""Find the fundamental matrix.+ Convention:+ - ``points1`` are in the first image and ``points2`` in the second; the result satisfies+ :math:`x_2^\top F x_1 = 0`, the second image's point on the left.+ :ref:`Two-view geometry <two-view-conventions>` maps this onto OpenCV.+ - The result is scaled so that ``F[2, 2] = 1`` by :func:`normalize_transformation`, which leaves it at its+ unnormalised scale when ``F[2, 2]`` is numerically zero, as for exactly rectified stereo.+ ``method="7POINT"`` returns three candidates in no particular order.+ - ``weights`` weight each correspondence's equation in the linear system: only their ratios matter, a+ negative weight counts as zero, and ``method="7POINT"`` ignores them.+ - Known defects: when the 7-point cubic has one real root, the two extra candidates are one rank-3+ matrix repeated instead of zeros (`#4862 <https://github.com/kornia/kornia/issues/4862>`_); a zero weight+ does not drop a correspondence, which still enters the point normalisation and changes the result+ (`#4875 <https://github.com/kornia/kornia/issues/4875>`_).+Args:- points1: A set of points in the first image with a tensor shape :math:`(B, N, 2), N>=8`.- points2: A set of points in the second image with a tensor shape :math:`(B, N, 2), N>=8`.+ points1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`: :math:`N \ge 8` for+ ``"8POINT"``, exactly 7 for ``"7POINT"``.+ points2: A set of points in the second image with the shape of ``points1``.weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.method: The method to use for computing the fundamental matrix. Supported methods are "7POINT" and "8POINT".Returns:- the computed fundamental matrix with shape :math:`(B, 3*m, 3)`, where `m` number of fundamental matrix.+ the computed fundamental matrix with shape :math:`(B, 3, 3)` for ``"8POINT"`` and+ :math:`(B, 3, 3, 3)` for ``"7POINT"``.Raises:ValueError: If an invalid method is provided.@@ -359,13 +380,17 @@ def find_fundamental(def compute_correspond_epilines(points: torch.Tensor, F_mat: torch.Tensor) -> torch.Tensor:r"""Compute the corresponding epipolar line for a given set of points.+ Convention:+ - For first-image points and ``F`` from :func:`find_fundamental` the lines lie in the second image;+ for second-image points pass ``F.transpose(-2, -1)``. Lines are scaled to :math:`a^2 + b^2 = 1`.+Args:points: tensor containing the set of points to project in the shape of :math:`(*, N, 2)` or :math:`(*, N, 3)`.F_mat: the fundamental to use for projection the points in the shape of :math:`(*, 3, 3)`.Returns:- a tensor with shape :math:`(*, N, 3)` containing a vector of the epipolar- lines corresponding to the points to the other image. Each line is described as+ a tensor with shape :math:`(*, N, 3)` containing the epipolar lines :math:`F x` of the points.+ Each line is described as:math:`ax + by + c = 0` and encoding the vectors as :math:`(a, b, c)`."""@@ -393,13 +418,14 @@ def get_perpendicular(lines: torch.Tensor, points: torch.Tensor) -> torch.Tensorr"""Compute the perpendicular to a line, through the point.Args:- lines: tensor containing the set of lines :math:`(*, N, 3)`.- points: tensor containing the set of points :math:`(*, N, 2)`.+ lines: tensor containing the set of lines :math:`(B, N, 3)`.+ points: tensor containing the set of points :math:`(B, N, 2)`.Returns:- a tensor with shape :math:`(*, N, 3)` containing a vector of the epipolar+ a tensor with shape :math:`(B, N, 3)` containing a vector of the epipolarperpendicular lines. Each line is described as- :math:`ax + by + c = 0` and encoding the vectors as :math:`(a, b, c)`.+ :math:`ax + by + c = 0` and encoding the vectors as :math:`(a, b, c)`; the normal :math:`(a, b)` has the+ norm of the input line's and is not rescaled."""KORNIA_CHECK_SHAPE(lines, ["*", "N", "3"])@@ -416,17 +442,21 @@ def get_perpendicular(lines: torch.Tensor, points: torch.Tensor) -> torch.Tensordef get_closest_point_on_epipolar_line(pts1: torch.Tensor, pts2: torch.Tensor, Fm: torch.Tensor) -> torch.Tensor:- """Return closest point on the epipolar line to the correspondence, given the fundamental matrix.+ r"""Return closest point on the epipolar line to the correspondence, given the fundamental matrix.++ Convention:+ - Returns, in the second image, the point of the epipolar line of ``pts1`` closest to ``pts2``, for+ ``Fm`` in the :math:`x_2^\top F x_1 = 0` order of :func:`find_fundamental`.Args:- pts1: correspondences from the left images with shape :math:`(*, N, (2|3))`. If they are not homogeneous,- converted automatically.- pts2: correspondences from the right images with shape :math:`(*, N, (2|3))`. If they are not homogeneous,- converted automatically.- Fm: Fundamental matrices with shape :math:`(*, 3, 3)`. Called Fm to avoid ambiguity with torch.nn.functional.+ pts1: points in the first image with shape :math:`(B, N, 2)` or :math:`(B, N, 3)`. If they are not+ homogeneous, converted automatically.+ pts2: points in the second image with shape :math:`(B, N, 2)` or :math:`(B, N, 3)`. If they are not+ homogeneous, converted automatically.+ Fm: Fundamental matrices with shape :math:`(B, 3, 3)`. Called Fm to avoid ambiguity with torch.nn.functional.Returns:- point on epipolar line :math:`(*, N, 2)`.+ point on epipolar line :math:`(B, N, 2)`."""if not isinstance(Fm, torch.Tensor):@@ -447,6 +477,11 @@ def fundamental_from_essential(E_mat: torch.Tensor, K1: torch.Tensor, K2: torch.Uses the method from Hartley/Zisserman 9.6 pag 257 (formula 9.12).+ Convention:+ - :math:`F = K_2^{-\top} E K_1^{-1}` with ``K1`` the camera of the first image, so ``F`` follows the+ :math:`x_2^\top F x_1 = 0` order of :func:`find_fundamental`; it keeps the scale of ``E_mat``, with no+ ``F[2, 2] = 1`` normalisation.+Args:E_mat: The essential matrix with shape of :math:`(*, 3, 3)`.K1: The camera matrix from first camera with shape :math:`(*, 3, 3)`.@@ -473,6 +508,13 @@ def fundamental_from_essential(E_mat: torch.Tensor, K1: torch.Tensor, K2: torch.def fundamental_from_projections(P1: torch.Tensor, P2: torch.Tensor) -> torch.Tensor:r"""Get the Fundamental matrix from Projection matrices.+ Convention:+ - The result satisfies :math:`x_2^\top F x_1 = 0` for ``(P1, P2)``, the order of :func:`find_fundamental`.+ It is not normalised, and for ``P1 = [I | 0]``, ``P2 = [R | t]`` it is the negative of+ :func:`~kornia.geometry.epipolar.essential_from_Rt` for the same motion.+ - Known defects: float16 overflows to ``inf`` for pixel-unit projection matrices+ (`#4877 <https://github.com/kornia/kornia/issues/4877>`_).+Args:P1: The projection matrix from first camera with shape :math:`(*, 3, 4)`.P2: The projection matrix from second camera with shape :math:`(*, 3, 4)`.diff --git a/kornia/geometry/epipolar/numeric.py b/kornia/geometry/epipolar/numeric.pyindex 2cb078a54..788ad435c 100644--- a/kornia/geometry/epipolar/numeric.py+++ b/kornia/geometry/epipolar/numeric.py@@ -21,13 +21,17 @@ import torchdef cross_product_matrix(x: torch.Tensor) -> torch.Tensor:- r"""Return the cross_product_matrix symmetric matrix of a vector.+ r"""Return the skew-symmetric cross-product matrix of a vector.++ Convention:+ - Same matrix as :func:`~kornia.geometry.conversions.vector_to_skew_symmetric_matrix`,+ :math:`[x]_\times w = x \times w`, for any number of leading dims.Args:x: The input vector to construct the matrix in the shape :math:`(*, 3)`.Returns:- The constructed cross_product_matrix symmetric matrix with shape :math:`(*, 3, 3)`.+ The skew-symmetric matrix with shape :math:`(*, 3, 3)`."""if not x.shape[-1] == 3:diff --git a/testing/two_view.py b/testing/two_view.pynew file mode 100644index 000000000..ff1c9a5cb--- /dev/null+++ b/testing/two_view.py@@ -0,0 +1,69 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++from __future__ import annotations++from typing import Dict++import torch++from kornia.geometry.conversions import axis_angle_to_rotation_matrix+from kornia.geometry.epipolar import projection_from_KRt+++def two_view_scene(device: torch.device, dtype: torch.dtype) -> Dict[str, torch.Tensor]:+ """Asymmetric two-view scene built in ``dtype`` from literals.++ ``K1 != K2``, ``fx != fy``, ``cx != cy``, a rotation about a non-axis direction and a translation off every+ axis, so swapping the images, transposing a matrix or negating ``t`` changes every quantity derived from it.+ Twelve points at depth 4 to 6 in the first camera, no two sharing a coordinate. ``x1``/``x2`` are exact pixel+ projections through ``P1 = K1 [I | 0]`` and ``P2 = K2 [R | t]``; ``(R, t)`` is world-to-camera for camera 2.+ """+ K1 = torch.tensor([[[800.0, 0.0, 320.0], [0.0, 760.0, 200.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ K2 = torch.tensor([[[700.0, 0.0, 300.0], [0.0, 740.0, 240.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ R = axis_angle_to_rotation_matrix(torch.tensor([[0.1, -0.2, 0.05]], device=device, dtype=dtype))+ t = torch.tensor([[[0.5], [0.1], [0.02]]], device=device, dtype=dtype)+ X = torch.tensor(+ [+ [+ [-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],+ ]+ ],+ device=device,+ dtype=dtype,+ )+ eye = torch.eye(3, device=device, dtype=dtype)[None]+ P1 = projection_from_KRt(K1, eye, torch.zeros(1, 3, 1, device=device, dtype=dtype))+ P2 = projection_from_KRt(K2, R, t)++ def proj(P: torch.Tensor, X: torch.Tensor) -> torch.Tensor:+ Xh = torch.cat([X, torch.ones_like(X[..., :1])], -1)+ x = (P @ Xh.transpose(1, 2)).transpose(1, 2)+ return x[..., :2] / x[..., 2:]++ return {"K1": K1, "K2": K2, "R": R, "t": t, "X": X, "P1": P1, "P2": P2, "x1": proj(P1, X), "x2": proj(P2, X)}diff --git a/tests/geometry/epipolar/test_epipolar_metrics.py b/tests/geometry/epipolar/test_epipolar_metrics.pyindex ffeb3d9cb..ff44a0106 100644--- a/tests/geometry/epipolar/test_epipolar_metrics.py+++ b/tests/geometry/epipolar/test_epipolar_metrics.py@@ -15,12 +15,16 @@# limitations under the License.#+from functools import partial++import pytestimport torchimport kornia.geometry.epipolar as epifrom testing.base import BaseTesterfrom testing.geometry.create import create_random_fundamental_matrix+from testing.two_view import two_view_sceneclass TestSymmetricalEpipolarDistance(BaseTester):@@ -213,3 +217,99 @@ class TestRightToLeftEpipolarDistance(BaseTester):Fm = create_random_fundamental_matrix(batch_size, dtype=torch.float64, device=device)self.gradcheck(epi.right_to_left_epipolar_distance, (points1, points2, Fm), requires_grad=(True, False, False))+++_HALF_PIXEL_F = (+ "a pixel-unit F spans eight decades (entries down to ~1e-8): float16 flushes the small entries to zero and "+ "bfloat16's 8-bit mantissa cannot resolve the epipolar residual, which kornia evaluates in the input dtype"+)+# Fixed pixel offsets added to x2 so that the distances are non-zero.+_NOISE = [+ [1.5, -2.0], [-2.5, 1.0], [0.5, 3.0], [-1.0, -1.5], [2.0, 0.5], [-3.0, 2.5],+ [1.0, -0.5], [-0.5, -3.0], [2.5, 1.5], [-2.0, -2.5], [3.0, -1.0], [-1.5, 2.0],+] # fmt: skip+++def _hom(p: torch.Tensor) -> torch.Tensor:+ return torch.cat([p, torch.ones_like(p[..., :1])], -1)+++def _pixel_F_unit_norm(scene) -> torch.Tensor:+ """Ground-truth F of the two-view fixture in closed form, scaled to unit Frobenius norm."""+ eye = torch.eye(3, device=scene["R"].device, dtype=scene["R"].dtype)[None]+ E = epi.essential_from_Rt(eye, torch.zeros_like(scene["t"]), scene["R"], scene["t"])+ F = epi.fundamental_from_essential(E, scene["K1"], scene["K2"])+ return F / F.norm(dim=(-2, -1), keepdim=True)+++def _cpu64(x: torch.Tensor) -> torch.Tensor:+ """Reference arithmetic in float64 on the CPU (MPS has no float64)."""+ return x.detach().cpu().double()+++class TestConventionEpipolarMetrics(BaseTester):+ @pytest.mark.parametrize("metric", ["sampson", "symmetrical", "left_to_right", "right_to_left"])+ def test_convention_metrics_argument_order_and_squared(self, metric, 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)+ # Reference in float64 from the point-to-epiline geometry, in pixels: pts1 are first-image points, pts2+ # second-image points, and Fm follows x2^T F x1 = 0.+ F64, p1, p2 = _cpu64(F), _cpu64(x1), _cpu64(x2)+ lines_in_2 = _hom(p1) @ F64.transpose(-2, -1) # epilines of pts1, in the second image+ lines_in_1 = _hom(p2) @ F64 # epilines of pts2, in the first image+ algebraic = (_hom(p2) * lines_in_2).sum(-1)+ d2 = algebraic.abs() / lines_in_2[..., :2].norm(dim=-1) # pts2 to the epiline of pts1+ d1 = algebraic.abs() / lines_in_1[..., :2].norm(dim=-1) # pts1 to the epiline of pts2+ expected = {+ "sampson": algebraic**2 / (lines_in_2[..., :2].pow(2).sum(-1) + lines_in_1[..., :2].pow(2).sum(-1)),+ "symmetrical": d1**2 + d2**2, # the sum of the two squared distances, not their mean+ "left_to_right": d2,+ "right_to_left": d1,+ }[metric]+ fn = getattr(epi, f"{metric}_epipolar_distance")+ self.assert_close(_cpu64(fn(x1, x2, F)), expected, rtol=1e-3, atol=0.0)+ # Control: the points swapped against the same F give a different value on every correspondence.+ assert ((_cpu64(fn(x2, x1, F)) - expected).abs() / expected).min() > 0.5+ # Relabelling the images (swap the points, transpose F) keeps Sampson and the symmetric distance and swaps+ # the two one-way distances.+ relabelled = {"left_to_right": "right_to_left", "right_to_left": "left_to_right"}.get(metric, metric)+ relabelled_fn = getattr(epi, f"{relabelled}_epipolar_distance")+ self.assert_close(_cpu64(relabelled_fn(x2, x1, F.transpose(-2, -1))), expected, rtol=1e-3, atol=0.0)+ if metric in ("sampson", "symmetrical"):+ # squared=True is the default; squared=False returns the root, in pixels. The one-way distances are+ # unsquared and have no squared argument.+ self.assert_close(_cpu64(fn(x1, x2, F, squared=False)), expected.sqrt(), rtol=1e-3, atol=0.0)+ if metric == "sampson":+ # A 3-vector point is used as given: w = 1 matches the 2-vector input, w = 2 is not dehomogenised and+ # changes every value.+ 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):+ 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 (+ partial(epi.sampson_epipolar_distance, use_matmul_at_less_than_points=0),+ epi.symmetrical_epipolar_distance,+ ):+ 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-2diff --git a/tests/geometry/epipolar/test_essential.py b/tests/geometry/epipolar/test_essential.pyindex cc6174ba2..d3ab6e830 100644--- a/tests/geometry/epipolar/test_essential.py+++ b/tests/geometry/epipolar/test_essential.py@@ -23,6 +23,7 @@ import kornia.geometry.epipolar as epifrom testing.base import BaseTesterfrom testing.geometry.create import generate_two_view_random_scene+from testing.two_view import two_view_sceneclass TestFindEssential(BaseTester):@@ -634,3 +635,313 @@ class TestMotionFromEssentialChooseSolution(BaseTester):(E_mat, K1, K2, x1, x2),requires_grad=(True, False, False, False, False),)+++_NO_HALF_LU = "{} calls torch.det (LU), which has no float16/bfloat16 kernel"+_NO_HALF_FIND_ESSENTIAL = "find_essential calls torch.linalg.lu_factor_ex, which has no float16/bfloat16 kernel"+_HALF_PIXEL_F = (+ "a pixel-unit F spans eight decades (entries down to ~1e-8): float16 flushes the small entries to zero and "+ "bfloat16's 8-bit mantissa cannot resolve the epipolar residual, which kornia evaluates in the input dtype"+)++# A five-point sample of normalised coordinates with no real root (recipe in the #4883 pin).+_NO_REAL_ROOT_P1 = [+ [-0.094936139146062, 0.3761027702259922],+ [-0.13508466816570844, -0.15520684765969847],+ [0.4518000060718804, 0.7491498583169849],+ [-0.021505790125727963, 0.25308016814257595],+ [-0.021008959788924204, -0.29327032505050715],+]+_NO_REAL_ROOT_P2 = [+ [0.5908350760196772, -0.024407062108416273],+ [0.4805667988287366, -0.025019944402247606],+ [-0.5701912982679379, 0.4911702947428827],+ [-0.8380815108891836, 0.2981499818513886],+ [-0.8246696433582323, 0.08361235498654443],+]+++def _skip_half(dtype: torch.dtype, reason: str) -> None:+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip(reason)+++def _skip_find_essential(device: torch.device, dtype: torch.dtype) -> None:+ _skip_half(dtype, _NO_HALF_FIND_ESSENTIAL)+ if device.type == "mps":+ pytest.skip("find_essential calls torch.linalg.eigvals, which has no MPS kernel (#4528)")+++def _hom(p: torch.Tensor) -> torch.Tensor:+ return torch.cat([p, torch.ones_like(p[..., :1])], -1)+++def _epipolar_residual(F: torch.Tensor, pts1: torch.Tensor, pts2: torch.Tensor) -> torch.Tensor:+ """|pts2^T F pts1| per correspondence."""+ return (_hom(pts2) * (_hom(pts1) @ F.transpose(-2, -1))).sum(-1).abs()+++def _normalized(K: torch.Tensor, pts: torch.Tensor) -> torch.Tensor:+ """Normalised camera coordinates K^-1 [u, v, 1]^T, dehomogenised."""+ return (_hom(pts) @ torch.linalg.inv(K).transpose(-2, -1))[..., :2]+++def _gt_essential(scene):+ eye = torch.eye(3, device=scene["R"].device, dtype=scene["R"].dtype)[None]+ return epi.essential_from_Rt(eye, torch.zeros_like(scene["t"]), scene["R"], scene["t"])+++def _first_camera(device, dtype):+ """A non-identity first camera, as world-to-camera extrinsics (R, t)."""+ Ra = kornia.geometry.conversions.axis_angle_to_rotation_matrix(+ torch.tensor([[-0.3, 0.15, 0.2]], device=device, dtype=dtype)+ )+ ta = torch.tensor([[[0.2], [-0.4], [1.1]]], device=device, dtype=dtype)+ return Ra, ta+++class TestConventionEssential(BaseTester):+ def test_convention_find_essential_returns_ten_candidates(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ _skip_find_essential(device, dtype)+ n1, n2 = _normalized(two_view["K1"], two_view["x1"]), _normalized(two_view["K2"], two_view["x2"])+ real = {}+ for num_points in (5, 12):+ E = epi.find_essential(n1[:, :num_points], n2[:, :num_points])+ # Always ten slots; each is either a real solution of unit Frobenius norm or all-NaN (complex root).+ assert E.shape == (1, 10, 3, 3)+ finite = torch.isfinite(E).all(dim=-1).all(dim=-1)[0]+ assert (finite | torch.isnan(E).all(dim=-1).all(dim=-1)[0]).all()+ real[num_points] = E[0, finite]+ assert real[num_points].shape[0] >= 1+ self.assert_close(real[num_points].norm(dim=(-2, -1)), torch.ones_like(real[num_points][:, 0, 0]))+ # True-E recovery is checked on all twelve points because the minimal sample can miss it (#4884).+ # Minimal sample: every real candidate satisfies x2^T E x1 = 0 on the normalised coordinates of points1+ # (first image) and points2 (second image); the swapped product is the control.+ p1, p2 = n1[:, :5], n2[:, :5]+ for cand in real[5]:+ assert _epipolar_residual(cand[None], p1, p2).max() < 1e-3 * _epipolar_residual(cand[None], p2, p1).max()+ # All twelve points: one candidate is the true E up to sign, on the same side.+ E_gt = _gt_essential(two_view)+ E_gt = E_gt / E_gt.norm()+ dist = torch.minimum((real[12] - E_gt).abs().amax(dim=(-2, -1)), (real[12] + E_gt).abs().amax(dim=(-2, -1)))+ assert dist.min() < 1e-4+ best = real[12][dist.argmin()][None]+ assert _epipolar_residual(best, n1, n2).max() < 1e-3 * _epipolar_residual(best, n2, n1).max()++ def test_convention_essential_from_Rt_is_tx_R_of_relative_motion(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ R, t = two_view["R"], two_view["t"]+ Ra, ta = _first_camera(device, dtype)+ # E = [t]x R of relative_camera_motion(R1, t1, R2, t2), here with a non-identity first camera.+ E = epi.essential_from_Rt(Ra, ta, R @ Ra, R @ ta + t)+ self.assert_close(E, epi.cross_product_matrix(t[..., 0]) @ R, low_tolerance=True)+ # Not normalised: ||E||_F = sqrt(2) ||t||.+ self.assert_close(E.norm(dim=(-2, -1)), (2.0**0.5) * t.norm(dim=(-2, -1)), low_tolerance=True)+ # Swapping the cameras gives E^T, which is far from E on this fixture.+ E_swapped = epi.essential_from_Rt(R @ Ra, R @ ta + t, Ra, ta)+ self.assert_close(E_swapped, E.transpose(-2, -1), low_tolerance=True)+ assert (E - E.transpose(-2, -1)).abs().max() > 0.5++ def test_convention_essential_from_fundamental_K_sides(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ _skip_half(dtype, _HALF_PIXEL_F)+ K1, K2 = two_view["K1"], two_view["K2"]+ E_gt = _gt_essential(two_view)+ F = epi.fundamental_from_essential(E_gt, K1, K2)+ F = F / F[..., 2:, 2:] # the scale an estimator returns+ # E = K2^T F K1: K1 is the camera of points1.+ E = epi.essential_from_fundamental(F, K1, K2)+ self.assert_close(E, K2.transpose(-2, -1) @ F @ K1)+ n1, n2 = _normalized(K1, two_view["x1"]), _normalized(K2, two_view["x2"])+ E_swapped = epi.essential_from_fundamental(F, K2, K1)+ resid = _epipolar_residual(E / E.norm(), n1, n2).max()+ assert resid < 1e-3 * _epipolar_residual(E_swapped / E_swapped.norm(), n1, n2).max()++ def test_convention_motion_from_essential_candidate_order(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ _skip_half(dtype, _NO_HALF_LU.format("motion_from_essential"))+ R, t = two_view["R"], two_view["t"]+ t_unit = t / t.norm(dim=-2, keepdim=True)+ E = _gt_essential(two_view)+ # project_to_essential keeps the input's scale: it is not normalised to unit Frobenius norm.+ E_unit = E / E.norm(dim=(-2, -1), keepdim=True)+ projected_norm = epi.project_to_essential(5.0 * E_unit).norm(dim=(-2, -1))+ self.assert_close(projected_norm, torch.full_like(projected_norm, 5.0))+ candidate_sets = []+ for E_in in (E, -E, 3.0 * E):+ Rs, ts = epi.motion_from_essential(E_in)+ R1, R2, t_dec = epi.decompose_essential_matrix(E_in)+ assert Rs.shape == (1, 4, 3, 3) and ts.shape == (1, 4, 3, 1)+ # Order [(R1, t), (R1, -t), (R2, t), (R2, -t)] of decompose_essential_matrix, with a unit t.+ self.assert_close(Rs[:, 0], R1)+ self.assert_close(Rs[:, 1], R1)+ self.assert_close(Rs[:, 2], R2)+ self.assert_close(Rs[:, 3], R2)+ self.assert_close(ts[:, 0], t_dec)+ self.assert_close(ts[:, 1], -t_dec)+ self.assert_close(ts[:, 2], t_dec)+ self.assert_close(ts[:, 3], -t_dec)+ self.assert_close(ts.norm(dim=(-2, -1)), torch.ones(1, 4, device=device, dtype=dtype))+ # Candidates 1 and 2 rebuild E_in itself as [t]x R (up to a positive scale), candidates 0 and 3 its+ # negative. Which of them is the true pose follows the sign and scale of E_in, so no index is fixed.+ # With det U = +1, [u3]x U W V^T = -U diag(1, 1, 0) V^T, so this pairing does not depend on the SVD's+ # sign choices.+ unit = E_in * (2.0**0.5) / E_in.norm()+ for i, sign in enumerate((-1.0, 1.0, 1.0, -1.0)):+ self.assert_close(epi.cross_product_matrix(ts[:, i, :, 0]) @ Rs[:, i], sign * unit)+ hits = [+ bool((Rs[:, i] - R).abs().max() < 1e-4 and (ts[:, i] - t_unit).abs().max() < 1e-4) for i in range(4)+ ]+ assert sum(hits) == 1+ candidate_sets.append((Rs[0], ts[0]))+ # E, -E and 3E give the same candidate set.+ Rs0, ts0 = candidate_sets[0]+ for Rs_k, ts_k in candidate_sets[1:]:+ for i in range(4):+ match = (Rs_k - Rs0[i]).abs().amax(dim=(-2, -1)) + (ts_k - ts0[i]).abs().amax(dim=(-2, -1))+ assert match.min() < 1e-4++ def test_convention_choose_solution_recovers_relative_motion(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ _skip_half(dtype, _NO_HALF_LU.format("motion_from_essential_choose_solution"))+ R, t, X = two_view["R"], two_view["t"], two_view["X"]+ K1, K2, x1, x2 = two_view["K1"], two_view["K2"], two_view["x1"], two_view["x2"]+ t_norm = t.norm(dim=-2, keepdim=True)+ E = _gt_essential(two_view)+ # Pixel coordinates in, K1 and K2 applied inside: the pose of camera 2 relative to camera 1 with a unit t,+ # and the points triangulated in the first camera's frame at that scale, all at positive depth.+ for E_in in (E, -E):+ R_out, t_out, X_out = epi.motion_from_essential_choose_solution(E_in, K1, K2, x1, x2)+ self.assert_close(R_out, R, rtol=1e-4, atol=1e-4)+ self.assert_close(t_out, t / t_norm, rtol=1e-4, atol=1e-4)+ self.assert_close(X_out, X / t_norm, rtol=1e-4, atol=1e-3)+ assert (X_out[..., 2] > 0).all()+ # Swapping the images (E^T, K2, K1, x2, x1) returns the inverse motion.+ R_sw, t_sw, _ = epi.motion_from_essential_choose_solution(E.transpose(-2, -1), K2, K1, x2, x1)+ self.assert_close(R_sw, R.transpose(-2, -1), rtol=1e-4, atol=1e-4)+ self.assert_close(t_sw, -R.transpose(-2, -1) @ t / t_norm, rtol=1e-4, atol=1e-4)+ # Control: with K1 and K2 swapped the triangulated points are wrong.+ _, _, X_swapped_k = epi.motion_from_essential_choose_solution(E, K2, K1, x1, x2)+ assert (X_swapped_k - X / t_norm).abs().max() > 1.0++ def test_convention_relative_camera_motion_world_to_camera(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ R, t = two_view["R"], two_view["t"]+ Ra, ta = _first_camera(device, dtype)+ # World-to-camera extrinsics: camera 2 = (R Ra, R ta + t) sits at (R, t) from camera 1 = (Ra, ta), and the+ # result is (R2 R1^T, t2 - R2 R1^T t1).+ R_rel, t_rel = epi.relative_camera_motion(Ra, ta, R @ Ra, R @ ta + t)+ self.assert_close(R_rel, R, low_tolerance=True)+ self.assert_close(t_rel, t, low_tolerance=True)+ # Swapping the cameras gives the inverse motion, far from (R, t) on this fixture.+ R_sw, t_sw = epi.relative_camera_motion(R @ Ra, R @ ta + t, Ra, ta)+ self.assert_close(R_sw, R.transpose(-2, -1), low_tolerance=True)+ self.assert_close(t_sw, -R.transpose(-2, -1) @ t, low_tolerance=True)+ assert (R_sw - R).abs().max() > 0.1 and (t_sw - t).abs().max() > 0.5++ def test_wart_find_essential_ignores_weights_4876(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ _skip_find_essential(device, dtype)+ # #4876: weights is documented per correspondence but ignored: an outlier with weight 0, all-zero weights and+ # all-one weights give the same output (NaN slots compared as 0). Once weights are used these differ.+ n1, n2 = _normalized(two_view["K1"], two_view["x1"]), _normalized(two_view["K2"], two_view["x2"])+ p1 = torch.cat([n1, torch.tensor([[[0.4, -0.3]]], device=device, dtype=dtype)], 1)+ p2 = torch.cat([n2, torch.tensor([[[-0.35, 0.25]]], device=device, dtype=dtype)], 1)+ ones = torch.ones(1, 13, device=device, dtype=dtype)+ outlier_off = ones.clone()+ outlier_off[0, 12] = 0.0+ E_ones = epi.find_essential(p1, p2, ones)+ assert torch.equal(epi.find_essential(p1, p2, outlier_off).nan_to_num(0.0), E_ones.nan_to_num(0.0))+ assert torch.equal(epi.find_essential(p1, p2, torch.zeros_like(ones)).nan_to_num(0.0), E_ones.nan_to_num(0.0))+ # Control: the outlier does move the estimate, so a working weight would change the result.+ E_clean = epi.find_essential(n1, n2)++ def best(E):+ real = E[0, torch.isfinite(E[0]).all(dim=-1).all(dim=-1)]+ return min(_epipolar_residual(e[None], n1, n2).max() for e in real)++ assert best(E_ones) > 1e3 * best(E_clean)++ def test_wart_decompose_unbatched_t_shape_4878(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ _skip_half(dtype, _NO_HALF_LU.format("decompose_essential_matrix"))+ # #4878: an unbatched (3, 3) input gains a batch dim on the rotations but not on t.+ E = _gt_essential(two_view)[0]+ R1, R2, t = epi.decompose_essential_matrix(E)+ assert R1.shape == (1, 3, 3) and R2.shape == (1, 3, 3)+ assert t.shape == (3, 1)+ Rs, ts = epi.motion_from_essential(E)+ assert Rs.shape == (1, 4, 3, 3)+ assert ts.shape == (4, 3, 1)++ def test_wart_choose_solution_all_masked_returns_candidate0_4879(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ _skip_half(dtype, _NO_HALF_LU.format("motion_from_essential_choose_solution"))+ K1, K2, x1, x2 = two_view["K1"], two_view["K2"], two_view["x1"], two_view["x2"]+ R, t = two_view["R"], two_view["t"]+ E = _gt_essential(two_view)+ Rs, ts = epi.motion_from_essential(E)+ t_unit = t / t.norm(dim=-2, keepdim=True)+ # On this E candidate 0 is not the true pose, so returning it is visibly wrong.+ assert (Rs[:, 0] - R).abs().max() > 0.1 or (ts[:, 0] - t_unit).abs().max() > 0.1+ # #4879: with every point masked out no candidate passes the depth test, and candidate 0 comes back unflagged.+ mask = torch.zeros(1, 12, dtype=torch.bool, device=device)+ R_out, t_out, _ = epi.motion_from_essential_choose_solution(E, K1, K2, x1, x2, mask=mask)+ assert torch.equal(R_out, Rs[:, 0]) and torch.equal(t_out, ts[:, 0])+ # Control: one unmasked point is enough to select the true pose.+ mask[0, 5] = True+ R_one, t_one, _ = epi.motion_from_essential_choose_solution(E, K1, K2, x1, x2, mask=mask)+ self.assert_close(R_one, R, rtol=1e-4, atol=1e-4)+ self.assert_close(t_one, t_unit, rtol=1e-4, atol=1e-4)++ def test_wart_decompose_no_svd_batch_non_rotations_4880(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ # #4880: the rotation normaliser sums over the whole batch, so a batch of two copies of E returns non-rotations,+ # while the same E alone returns rotations.+ E = _gt_essential(two_view)+ eye = torch.eye(3, device=device, dtype=torch.float32)++ def orthogonality_error(Rm):+ Rm = Rm.float()+ return (Rm @ Rm.transpose(-2, -1) - eye).norm(dim=(-2, -1))++ R1, R2, _ = epi.decompose_essential_matrix_no_svd(E)+ assert orthogonality_error(R1).max() < 0.25 and orthogonality_error(R2).max() < 0.25+ R1b, R2b, _ = epi.decompose_essential_matrix_no_svd(torch.cat([E, E]))+ assert (orthogonality_error(R1b) > 1.0).all() and (orthogonality_error(R2b) > 1.0).all()++ def test_wart_choose_solution_batched_uses_element0_index_2198(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ _skip_half(dtype, _NO_HALF_LU.format("motion_from_essential_choose_solution"))+ K1, K2, x1, x2 = two_view["K1"], two_view["K2"], two_view["x1"], two_view["x2"]+ R, t = two_view["R"], two_view["t"]+ t_unit = t / t.norm(dim=-2, keepdim=True)+ E = _gt_essential(two_view)++ def is_truth(R_out, t_out):+ return bool((R_out - R[0]).abs().max() < 1e-4 and (t_out - t_unit[0]).abs().max() < 1e-4)++ # E and -E have their true pose at different candidate indices; each alone is recovered.+ for E_in in (E, -E):+ R_out, t_out, _ = epi.motion_from_essential_choose_solution(E_in, K1, K2, x1, x2)+ assert is_truth(R_out[0], t_out[0])+ # #2198: in the batch [E, -E] with the same correspondences, element 1 gets element 0's index: a wrong pose+ # with points behind a camera.+ R_b, t_b, X_b = epi.motion_from_essential_choose_solution(+ torch.cat([E, -E]), K1.expand(2, 3, 3), K2.expand(2, 3, 3), x1.expand(2, 12, 2), x2.expand(2, 12, 2)+ )+ assert is_truth(R_b[0], t_b[0])+ assert not is_truth(R_b[1], t_b[1])+ assert (X_b[1, :, 2] < 0).any()++ def test_wart_find_essential_no_real_root_identity_4883(self, device, dtype):+ _skip_find_essential(device, dtype)+ # #4883: a five-point sample with no real root returns ten identity matrices instead of NaN slots. Sample:+ # g = torch.Generator().manual_seed(0)+ # p1 = torch.randn(4000, 5, 2, generator=g, dtype=torch.float64) * 0.5 # then p2 from the same g+ # p1[1371], p2[1371]+ p1 = torch.tensor(_NO_REAL_ROOT_P1, device=device, dtype=dtype)[None]+ p2 = torch.tensor(_NO_REAL_ROOT_P2, device=device, dtype=dtype)[None]+ E = epi.find_essential(p1, p2)+ assert torch.equal(E, torch.eye(3, device=device, dtype=dtype).expand(1, 10, 3, 3))diff --git a/tests/geometry/epipolar/test_fundamental.py b/tests/geometry/epipolar/test_fundamental.pyindex b870d8b53..6a155f592 100644--- a/tests/geometry/epipolar/test_fundamental.py+++ b/tests/geometry/epipolar/test_fundamental.py@@ -24,6 +24,7 @@ import kornia.geometry.epipolar as epifrom testing.base import BaseTesterfrom testing.geometry.create import create_random_fundamental_matrix, generate_two_view_random_scene+from testing.two_view import two_view_sceneclass TestNormalizePoints(BaseTester):@@ -555,3 +556,240 @@ class TestGetClosestPointOnEpipolarLine(BaseTester):pts2 = torch.rand(2, 4, 2, device=device, dtype=torch.float64)Fm = create_random_fundamental_matrix(1, dtype=torch.float64, device=device)self.gradcheck(epi.get_closest_point_on_epipolar_line, (pts1, pts2, Fm), requires_grad=(True, False, False))+++_NO_HALF_EIGH = "find_fundamental calls torch.linalg.eigh, which has no float16/bfloat16 kernel"+_HALF_PIXEL_F = (+ "a pixel-unit F spans eight decades (entries down to ~1e-8): float16 flushes the small entries to zero and "+ "bfloat16's 8-bit mantissa cannot resolve the epipolar residual, which kornia evaluates in the input dtype"+)+# Fixed pixel offsets added to x2 where a pin needs inexact matches.+_NOISE = [+ [1.5, -2.0], [-2.5, 1.0], [0.5, 3.0], [-1.0, -1.5], [2.0, 0.5], [-3.0, 2.5],+ [1.0, -0.5], [-0.5, -3.0], [2.5, 1.5], [-2.0, -2.5], [3.0, -1.0], [-1.5, 2.0],+] # fmt: skip+++def _skip_half(dtype: torch.dtype, reason: str) -> None:+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip(reason)+++def _hom(p: torch.Tensor) -> torch.Tensor:+ return torch.cat([p, torch.ones_like(p[..., :1])], -1)+++def _epipolar_residual(F: torch.Tensor, pts1: torch.Tensor, pts2: torch.Tensor) -> torch.Tensor:+ """|pts2^T F pts1| per correspondence."""+ return (_hom(pts2) * (_hom(pts1) @ F.transpose(-2, -1))).sum(-1).abs()+++def _pixel_F(scene: Dict[str, torch.Tensor]) -> torch.Tensor:+ """Ground-truth F of the two-view fixture in closed form, scaled so that F[2, 2] = 1."""+ eye = torch.eye(3, device=scene["R"].device, dtype=scene["R"].dtype)[None]+ E = epi.essential_from_Rt(eye, torch.zeros_like(scene["t"]), scene["R"], scene["t"])+ F = epi.fundamental_from_essential(E, scene["K1"], scene["K2"])+ return F / F[..., 2:, 2:]+++class TestConventionFundamental(BaseTester):+ def test_convention_find_fundamental_acts_x2_F_x1(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ _skip_half(dtype, _NO_HALF_EIGH)+ x1, x2 = two_view["x1"], two_view["x2"]+ F = epi.find_fundamental(x1, x2, torch.ones_like(x1[..., 0]))+ # x2^T F x1 = 0 for points1 from the first image and points2 from the second (OpenCV's findFundamentalMat+ # order). The swapped product is the control: on this fixture it is of order 1.+ assert _epipolar_residual(F, x1, x2).max() < 1e-3 * _epipolar_residual(F, x2, x1).max()+ # Relabelling the images returns the transpose.+ self.assert_close(epi.find_fundamental(x2, x1), F.transpose(-2, -1), rtol=1e-4, atol=1e-4)+ # The result is scaled so that F[2, 2] = 1.+ self.assert_close(F[..., 2, 2], torch.ones_like(F[..., 2, 2]))++ def test_convention_find_fundamental_7point_candidates(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ _skip_half(dtype, _NO_HALF_EIGH)+ # A 7-point sample whose cubic has three real roots, so all three candidates are genuine solutions.+ idx = [0, 1, 2, 3, 4, 5, 6]+ x1, x2 = two_view["x1"][:, idx], two_view["x2"][:, idx]+ F = epi.find_fundamental(x1, x2, method="7POINT")+ assert F.shape == (1, 3, 3, 3)+ for k in range(3):+ Fk = F[:, k]+ assert _epipolar_residual(Fk, x1, x2).max() < 1e-3 * _epipolar_residual(Fk, x2, x1).max()+ sv = torch.linalg.svdvals(Fk.cpu().double())+ assert sv[..., 2] < 1e-8 * sv[..., 0] # rank 2+ self.assert_close(F[..., 2, 2], torch.ones_like(F[..., 2, 2]))+ # The candidate order carries no meaning: exactly one candidate fits all twelve points, so it is selected by+ # residual, never by position.+ fits = [bool(_epipolar_residual(F[:, k], two_view["x1"], two_view["x2"]).max() < 1e-2) for k in range(3)]+ assert sum(fits) == 1+ # Relabelling the images returns the transposed candidates, as a set.+ Fs = epi.find_fundamental(x2, x1, method="7POINT").transpose(-2, -1)+ dist = (F[0, :, None] - Fs[0, None]).abs().amax(dim=(-2, -1))+ assert dist.amin(dim=1).max() < 1e-3++ def test_convention_find_fundamental_weights_semantics(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ _skip_half(dtype, _NO_HALF_EIGH)+ x1 = two_view["x1"]+ x2 = two_view["x2"] + torch.tensor([_NOISE], device=device, dtype=dtype)+ w = torch.tensor([[0.5, 1.0, 2.0, 1.5, 0.75, 1.25, 3.0, 0.25, 1.0, 2.5, 0.6, 1.8]], device=device, dtype=dtype)+ F_w = epi.find_fundamental(x1, x2, w)+ # Only the ratios of the weights matter: scaling them all by 7 gives the same F.+ self.assert_close(epi.find_fundamental(x1, x2, 7.0 * w), F_w, rtol=1e-4, atol=1e-4)+ # Control: other ratios (all ones) give a different F on these inexact matches.+ assert (epi.find_fundamental(x1, x2, torch.ones_like(w)) - F_w).abs().max() > 1e-3+ # A negative weight counts as zero, to the bit; both differ from the original weight.+ w_zero, w_neg = w.clone(), w.clone()+ w_zero[0, 3], w_neg[0, 3] = 0.0, -5.0+ F_zero = epi.find_fundamental(x1, x2, w_zero)+ assert torch.equal(epi.find_fundamental(x1, x2, w_neg), F_zero)+ assert (F_zero - F_w).abs().max() > 1e-3+ # method="7POINT" ignores the weights: a zero and a negative weight, which would drop a constraint from a+ # weighted minimal system, leave the three candidates unchanged to the bit.+ x1_7, x2_7 = x1[:, :7], two_view["x2"][:, :7]+ w7 = torch.tensor([[1.0, 0.0, -2.0, 5.0, 0.1, 3.0, 1.0]], device=device, dtype=dtype)+ F7 = epi.find_fundamental(x1_7, x2_7, method="7POINT")+ assert torch.equal(epi.find_fundamental(x1_7, x2_7, w7, method="7POINT"), F7)++ def test_convention_fundamental_from_projections_direction_and_scale(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ if dtype == torch.float16:+ pytest.skip("float16 overflows to inf on pixel-unit projection matrices (#4877)")+ _skip_half(dtype, _HALF_PIXEL_F)+ x1, x2 = two_view["x1"], two_view["x2"]+ F = epi.fundamental_from_projections(two_view["P1"], two_view["P2"])+ # x2^T F x1 = 0 for (P1, P2): points1 from the first camera, the order of find_fundamental.+ F_unit = F / F.norm()+ assert _epipolar_residual(F_unit, x1, x2).max() < 1e-3 * _epipolar_residual(F_unit, x2, x1).max()+ # Control: swapping the cameras gives the transposed relation, which fails on (x1, x2).+ F_sw = epi.fundamental_from_projections(two_view["P2"], two_view["P1"])+ F_sw_unit = F_sw / F_sw.norm()+ assert _epipolar_residual(F_sw_unit, x1, x2).max() > 1e3 * _epipolar_residual(F_unit, x1, x2).max()+ # Not normalised: neither F[2, 2] = 1 nor unit Frobenius norm.+ assert (F[..., 2, 2] - 1.0).abs().max() > 1.0 and (F.norm() - 1.0).abs() > 1.0+ # For P1 = [I | 0], P2 = [R | t] it is the negative of essential_from_Rt for the same motion, at its scale.+ R, t = two_view["R"], two_view["t"]+ eye = torch.eye(3, device=device, dtype=dtype)[None]+ zero = torch.zeros_like(t)+ F_n = epi.fundamental_from_projections(torch.cat([eye, zero], -1), torch.cat([R, t], -1))+ E = epi.essential_from_Rt(eye, zero, R, t)+ self.assert_close(F_n, -E)+ assert (F_n - E).abs().max() > 0.5++ def test_convention_fundamental_from_essential_K_sides(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ _skip_half(dtype, _HALF_PIXEL_F)+ K1, K2, x1, x2 = two_view["K1"], two_view["K2"], two_view["x1"], two_view["x2"]+ eye = torch.eye(3, device=device, dtype=dtype)[None]+ E = epi.essential_from_Rt(eye, torch.zeros_like(two_view["t"]), two_view["R"], two_view["t"])+ F = epi.fundamental_from_essential(E, K1, K2)+ # F = K2^-T E K1^-1: K1 is the camera of points1, so x2^T F x1 = 0 in pixels.+ self.assert_close(K2.transpose(-2, -1) @ F @ K1, E)+ F_swapped = epi.fundamental_from_essential(E, K2, K1)+ resid = _epipolar_residual(F / F.norm(), x1, x2)+ assert resid.max() < 1e-3 * _epipolar_residual(F_swapped / F_swapped.norm(), x1, x2).max()++ def test_convention_epilines_of_image1_points_lie_in_image2(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ _skip_half(dtype, _HALF_PIXEL_F)+ x1, x2 = two_view["x1"], two_view["x2"]+ F = _pixel_F(two_view)+ # Lines F x1 of first-image points live in the second image, scaled to a^2 + b^2 = 1.+ lines = epi.compute_correspond_epilines(x1, F)+ self.assert_close(lines[..., :2].norm(dim=-1), torch.ones_like(lines[..., 0]))+ on, off = (_hom(x2) * lines).sum(-1).abs(), (_hom(x1) * lines).sum(-1).abs()+ assert on.max() < 1e-3 * off.max()+ # For second-image points pass F transposed: the lines live in the first image.+ lines1 = epi.compute_correspond_epilines(x2, F.transpose(-2, -1))+ self.assert_close(lines1[..., :2].norm(dim=-1), torch.ones_like(lines1[..., 0]))+ on1, off1 = (_hom(x1) * lines1).sum(-1).abs(), (_hom(x2) * lines1).sum(-1).abs()+ assert on1.max() < 1e-3 * off1.max()++ def test_convention_normalize_points_hartley(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ # Hartley normalisation: translate to zero mean and scale isotropically to mean distance sqrt(2); the+ # returned T maps the input onto the output. The fixture's spread differs in x and y.+ points = two_view["x1"]+ points_norm, T = epi.normalize_points(points)+ mean_atol = {torch.bfloat16: 3e-2, torch.float16: 3e-3}.get(dtype, 1e-5)+ self.assert_close(points_norm.mean(dim=1), torch.zeros_like(points_norm[:, 0]), rtol=0.0, atol=mean_atol)+ mean_dist = points_norm.norm(dim=-1).mean(dim=-1)+ self.assert_close(mean_dist, torch.full_like(mean_dist, 2.0**0.5))+ self.assert_close((_hom(points) @ T.transpose(-2, -1))[..., :2], points_norm, low_tolerance=True)+ assert T[0, 0, 0] == T[0, 1, 1]+ assert T[0, 0, 1] == 0 and T[0, 1, 0] == 0++ def test_convention_normalize_transformation_keeps_zero_last_entry(self, device, dtype):+ # The F[2, 2] = 1 scaling skips a last entry within eps of zero, such as the F of an exactly rectified pair+ # (x2^T F x1 = v1 - v2): the matrix comes back unchanged instead of divided by eps.+ M = torch.tensor([[[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]]], device=device, dtype=dtype)+ assert torch.equal(epi.normalize_transformation(M), M)+ # Control: a last entry above eps is divided out.+ M[0, 2, 2] = 0.5+ self.assert_close(epi.normalize_transformation(M), M / 0.5)++ def test_convention_get_closest_point_on_epipolar_line_in_image2(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ _skip_half(dtype, _HALF_PIXEL_F)+ x1 = two_view["x1"]+ x2 = two_view["x2"] + torch.tensor([_NOISE], device=device, dtype=dtype)+ F = _pixel_F(two_view)+ # The result lies in the second image, on the epiline F x1, at the foot of the perpendicular from x2.+ closest = epi.get_closest_point_on_epipolar_line(x1, x2, F)+ lines = epi.compute_correspond_epilines(x1, F)+ assert (_hom(closest) * lines).sum(-1).abs().max() < 1e-3+ self.assert_close((closest - x2).norm(dim=-1), epi.left_to_right_epipolar_distance(x1, x2, F))+ # Control: with the arguments swapped the point is off that line by pixels.+ swapped = epi.get_closest_point_on_epipolar_line(x2, x1, F)+ assert (_hom(swapped) * lines).sum(-1).abs().max() > 1.0++ def test_wart_run_7point_padded_roots_returned_4862(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ _skip_half(dtype, _NO_HALF_EIGH)+ # #4862: a 7-point sample whose cubic has one real root. The solver pads the two missing roots with 0.0 and the+ # validity mask never fires, so candidates 1 and 2 are the same rank-3 matrix instead of being zeroed.+ # Any fix (zeros, NaN, or fewer candidates) makes these assertions fail.+ idx = [0, 1, 2, 3, 4, 6, 10]+ F = epi.find_fundamental(two_view["x1"][:, idx], two_view["x2"][:, idx], method="7POINT")+ assert F.shape == (1, 3, 3, 3)+ assert torch.equal(F[:, 1], F[:, 2])+ sv = torch.linalg.svdvals(F[0].cpu().double())+ assert sv[0, 2] < 1e-8 * sv[0, 0] # candidate 0 is a genuine rank-2 solution+ assert (sv[1:, 2] > 1e-7 * sv[1:, 0]).all() # the padded candidates are rank 3++ def test_wart_normalize_transformation_eps_divisor_4874(self, device, dtype):+ # #4874: the divisor is M[2, 2] + eps, so the last entry is 1 only to eps / |M[2, 2]|.+ M = torch.tensor([[[2.0, 0.5, 3.0], [-1.0, 4.0, 0.25], [0.75, -2.0, 0.1]]], device=device, dtype=dtype)+ out = epi.normalize_transformation(M, eps=1e-3)+ assert (out[0, 2, 2] - 1.0).abs() > 5e-3+ if dtype != torch.float16: # float16 rounds 1e-6 + 1e-8 back to 1e-6+ M[0, 2, 2] = 1e-6+ assert (epi.normalize_transformation(M)[0, 2, 2] - 1.0).abs() > 5e-3++ def test_wart_find_fundamental_zero_weight_changes_result_4875(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ _skip_half(dtype, _NO_HALF_EIGH)+ # #4875: a correspondence with weight 0 leaves the linear system but still enters the Hartley+ # normalisation, so a far outlier with weight 0 moves the estimate. Once fixed, the two estimates agree.+ x1 = two_view["x1"]+ x2 = two_view["x2"] + torch.tensor([_NOISE], device=device, dtype=dtype)+ outlier1 = torch.tensor([[[2000.0, -1500.0]]], device=device, dtype=dtype)+ outlier2 = torch.tensor([[[-1800.0, 2500.0]]], device=device, dtype=dtype)+ weights = torch.ones(1, 13, device=device, dtype=dtype)+ weights[0, 12] = 0.0+ F_weighted = epi.find_fundamental(torch.cat([x1, outlier1], 1), torch.cat([x2, outlier2], 1), weights)+ F_dropped = epi.find_fundamental(x1, x2)+ err_weighted = epi.sampson_epipolar_distance(x1, x2, F_weighted).mean()+ err_dropped = epi.sampson_epipolar_distance(x1, x2, F_dropped).mean()+ assert err_weighted > 2.0 * err_dropped++ def test_wart_fundamental_from_projections_float16_overflow_4877(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ if dtype != torch.float16:+ pytest.skip("the overflow is float16's: bfloat16, float32 and float64 hold pixel-unit 4x4 determinants")+ # #4877: the 4x4 determinants of pixel-unit projection matrices exceed float16's range, so F holds inf.+ F = epi.fundamental_from_projections(two_view["P1"], two_view["P2"])+ assert F.dtype == torch.float16+ assert torch.isinf(F).any()diff --git a/tests/geometry/epipolar/test_numeric.py b/tests/geometry/epipolar/test_numeric.pyindex 6df214069..95ead8115 100644--- a/tests/geometry/epipolar/test_numeric.py+++ b/tests/geometry/epipolar/test_numeric.py@@ -22,6 +22,7 @@ import korniaimport kornia.geometry.epipolar as epifrom testing.base import BaseTester+from testing.two_view import two_view_sceneclass TestSkewSymmetric(BaseTester):@@ -107,3 +108,18 @@ class TestVecLike:assert vec.shape == (B, N, 1)assert vec.device == image.deviceassert vec.dtype == image.dtype+++class TestConventionCrossProductMatrix(BaseTester):+ def test_convention_cross_product_matrix_equals_vector_to_skew_symmetric_matrix(self, device, dtype):+ two_view = two_view_scene(device, dtype)+ v = two_view["X"][0] # (12, 3), no two entries equal+ M = epi.cross_product_matrix(v)+ # The same matrix as kornia.geometry.conversions.vector_to_skew_symmetric_matrix, to the bit.+ assert torch.equal(M, kornia.geometry.conversions.vector_to_skew_symmetric_matrix(v))+ # Skew-symmetric, with [v]x w = v x w (the transposed matrix would give w x v).+ assert torch.equal(M.transpose(-2, -1), -M)+ w = two_view["t"][0, :, 0].expand_as(v)+ self.assert_close((M @ w[..., None])[..., 0], torch.linalg.cross(v, w, dim=-1), low_tolerance=True)+ # Any number of leading dims.+ assert epi.cross_product_matrix(two_view["X"].reshape(2, 2, 3, 3)).shape == (2, 2, 3, 3, 3)