Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[WIP] Feature matching and H/F/E estimation for SFM (#552)

Dmytro Mishkine7356ccfce4d
diff --git a/docs/source/feature.rst b/docs/source/feature.rst
index 31cab0846..3861e5814 100644
--- a/docs/source/feature.rst
+++ b/docs/source/feature.rst
@@ -27,6 +27,16 @@ Descriptors
.. autoclass:: HardNet
.. autoclass:: SOSNet
+
+Matching
+-----------
+
+.. autofunction:: match_nn
+.. autofunction:: match_mnn
+.. autofunction:: match_snn
+.. autofunction:: match_smnn
+
+
Local Affine Frames (LAF)
-------------------------
diff --git a/docs/source/geometry.rst b/docs/source/geometry.rst
index 5a03c7c9d..864740d9d 100644
--- a/docs/source/geometry.rst
+++ b/docs/source/geometry.rst
@@ -25,6 +25,14 @@ Coordinates Subpixel
.. autofunction:: spatial_expectation2d
.. autofunction:: render_gaussian2d
+
+Homography
+--------------------
+
+.. autofunction:: find_homography
+.. autofunction:: find_homography_dlt
+
+
Module
------
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index 797a7c7a1..9270992ba 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -37,6 +37,8 @@ from .sosnet import SOSNet
from .scale_space_detector import ScaleSpaceDetector, PassLAF
from .affine_shape import LAFAffineShapeEstimator, PatchAffineShapeEstimator
from .orientation import LAFOrienter, PatchDominantGradientOrientation
+from .matching import match_nn, match_mnn, match_snn, match_smnn
+
__all__ = [
"nms2d",
@@ -77,4 +79,8 @@ __all__ = [
"laf_from_center_scale_ori",
"laf_to_three_points",
"laf_from_three_points",
+ "match_nn",
+ "match_mnn",
+ "match_snn",
+ "match_smnn",
]
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
new file mode 100644
index 000000000..3b3ea5d41
--- /dev/null
+++ b/kornia/feature/matching.py
@@ -0,0 +1,146 @@
+import torch
+from typing import Tuple, Optional
+
+
+def match_nn(desc1: torch.Tensor, desc2: torch.Tensor,
+ dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Function, which finds nearest neightbors in desc2 for each vector in desc1.
+ If the distance matrix dm is not provided, torch.cdist(desc1, desc2) is used.
+ Args:
+ desc1 (torch.Tensor): Batch of descriptors of a shape :math:`(B1, D)`.
+ desc2 (torch.Tensor): Batch of descriptors of a shape :math:`(B2, D)`.
+ dm (torch.Tensor): optional. Tensor containing the distances from each descriptor in desc1 to each descriptor in
+ desc2, shape of :math:`(B1, B2)`.
+
+ Return:
+ torch.Tensor: Descriptor distance of matching descriptors, shape of. :math:`(B1, 1)
+ torch.Tensor: Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B1, 2)
+ """
+ assert len(desc1.shape) == 2
+ assert len(desc2.shape) == 2
+ if dm is None:
+ dm = torch.cdist(desc1, desc2)
+ else:
+ assert (dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))
+ match_dists, idxs_in_2 = torch.min(dm, dim=1)
+ idxs_in1: torch.Tensor = torch.arange(0, idxs_in_2.size(0), device=idxs_in_2.device)
+ matches_idxs: torch.Tensor = torch.cat([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], dim=1)
+ return match_dists.view(-1, 1), matches_idxs.view(-1, 2)
+
+
+def match_mnn(desc1: torch.Tensor, desc2: torch.Tensor,
+ dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Function, which finds mutual nearest neightbors in desc2 for each vector in desc1.
+ If the distance matrix dm is not provided, torch.cdist(desc1, desc2) is used.
+ Args:
+ desc1 (torch.Tensor): Batch of descriptors of a shape :math:`(B1, D)`.
+ desc2 (torch.Tensor): Batch of descriptors of a shape :math:`(B2, D)`.
+ dm (torch.Tensor): optional. Tensor containing the distances from each descriptor in desc1 to each descriptor in
+ desc2, shape of :math:`(B1, B2)`.
+
+ Return:
+ torch.Tensor: Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)
+ torch.Tensor: Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)
+ where 0 <= B3 <= min(B1, B2)
+ """
+ assert len(desc1.shape) == 2
+ assert len(desc2.shape) == 2
+ if dm is None:
+ dm = torch.cdist(desc1, desc2)
+ else:
+ assert (dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))
+ ms = min(dm.size(0), dm.size(1))
+ match_dists, idxs_in_2 = torch.min(dm, dim=1)
+ match_dists2, idxs_in_1 = torch.min(dm, dim=0)
+ minsize_idxs = torch.arange(ms, device=dm.device)
+ if dm.size(0) <= dm.size(1):
+ mutual_nns = minsize_idxs == idxs_in_1[idxs_in_2][:ms]
+ matches_idxs = torch.cat([minsize_idxs.view(-1, 1), idxs_in_2.view(-1, 1)], dim=1)[mutual_nns]
+ match_dists = match_dists[mutual_nns]
+ else:
+ mutual_nns = minsize_idxs == idxs_in_2[idxs_in_1][:ms]
+ matches_idxs = torch.cat([idxs_in_1.view(-1, 1), minsize_idxs.view(-1, 1)], dim=1)[mutual_nns]
+ match_dists = match_dists2[mutual_nns]
+ return match_dists.view(-1, 1), matches_idxs.view(-1, 2)
+
+
+def match_snn(desc1: torch.Tensor, desc2: torch.Tensor,
+ th: float = 0.8, dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Function, which finds nearest neightbors in desc2 for each vector in desc1.
+ which satisfy first to second nearest neighbor distance <= th.
+ If the distance matrix dm is not provided, torch.cdist(desc1, desc2) is used.
+ Args:
+ desc1 (torch.Tensor): Batch of descriptors of a shape :math:`(B1, D)`.
+ desc2 (torch.Tensor): Batch of descriptors of a shape :math:`(B2, D)`.
+ th (float): distance ratio threshold.
+ dm (torch.Tensor): optional. Tensor containing the distances from each descriptor in desc1 to each descriptor in
+ desc2, shape of :math:`(B1, B2)`.
+
+ Return:
+ torch.Tensor: Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)
+ torch.Tensor: Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)
+ where 0 <= B3 <= B1
+ """
+ assert len(desc1.shape) == 2
+ assert len(desc2.shape) == 2
+ assert desc2.shape[0] >= 2 # to performs second nearest check, we need at least two descriptors
+
+ if dm is None:
+ dm = torch.cdist(desc1, desc2)
+ else:
+ assert (dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))
+ vals, idxs_in_2 = torch.topk(dm, 2, dim=1, largest=False)
+ ratio = vals[:, 0] / vals[:, 1]
+ mask = ratio <= th
+ match_dists = ratio[mask]
+ idxs_in1 = torch.arange(0, idxs_in_2.size(0), device=dm.device)[mask]
+ idxs_in_2 = idxs_in_2[:, 0][mask]
+ matches_idxs = torch.cat([idxs_in1.view(-1, 1), idxs_in_2.cpu().view(-1, 1)], dim=1)
+ return match_dists.view(-1, 1), matches_idxs.view(-1, 2)
+
+
+def match_smnn(desc1: torch.Tensor, desc2: torch.Tensor,
+ th: float = 0.8, dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Function, which finds mutual nearest neightbors in desc2 for each vector in desc1.
+ which satisfy first to second nearest neighbor distance <= th.
+ If the distance matrix dm is not provided, torch.cdist(desc1, desc2) is used.
+ Args:
+ desc1 (torch.Tensor): Batch of descriptors of a shape :math:`(B1, D)`.
+ desc2 (torch.Tensor): Batch of descriptors of a shape :math:`(B2, D)`.
+ th (float): distance ratio threshold.
+ dm (torch.Tensor): optional. Tensor containing the distances from each descriptor in desc1 to each descriptor in
+ desc2, shape of :math:`(B1, B2)`.
+
+ Return:
+ torch.Tensor: Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)
+ torch.Tensor: Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)
+ where 0 <= B3 <= B1
+ """
+ assert len(desc1.shape) == 2
+ assert len(desc2.shape) == 2
+ assert desc1.shape[0] >= 2 # to performs second nearest check, we need at least two descriptors
+ assert desc2.shape[0] >= 2 # to performs second nearest check, we need at least two descriptors
+
+ if dm is None:
+ dm = torch.cdist(desc1, desc2)
+ else:
+ assert (dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))
+ dists1, idx1 = match_snn(desc1, desc2, th, dm)
+ dists2, idx2 = match_snn(desc2, desc1, th, dm.t())
+ if len(dists2) > 0 and len(dists1) > 0:
+ idx2 = idx2.flip(1)
+ idxs_dm = torch.cdist(idx1.float(), idx2.float(), p=1)
+ mutual_idxs1 = idxs_dm.min(dim=1)[0] < 1e-8
+ mutual_idxs2 = idxs_dm.min(dim=0)[0] < 1e-8
+ good_idxs1 = idx1[mutual_idxs1.view(-1)]
+ good_idxs2 = idx2[mutual_idxs2.view(-1)]
+ dists1_good = dists1[mutual_idxs1.view(-1)]
+ dists2_good = dists2[mutual_idxs2.view(-1)]
+ _, idx_upl1 = torch.sort(good_idxs1[:, 0])
+ _, idx_upl2 = torch.sort(good_idxs2[:, 0])
+ good_idxs1 = good_idxs1[idx_upl1]
+ match_dists = torch.max(dists1_good[idx_upl1], dists2_good[idx_upl2])
+ matches_idxs = good_idxs1
+ else:
+ matches_idxs, match_dists = torch.empty(0, 2, device=dm.device), torch.empty(0, 1, device=dm.device)
+ return match_dists.view(-1, 1), matches_idxs.view(-1, 2)
diff --git a/kornia/geometry/__init__.py b/kornia/geometry/__init__.py
index e19690eb7..ab3384430 100644
--- a/kornia/geometry/__init__.py
+++ b/kornia/geometry/__init__.py
@@ -7,3 +7,4 @@ from kornia.geometry.depth import *
from kornia.geometry.dsnt import *
from kornia.geometry.spatial_soft_argmax import *
from kornia.geometry.epipolar import *
+from kornia.geometry.homography import *
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
new file mode 100644
index 000000000..6bf007ee2
--- /dev/null
+++ b/kornia/geometry/homography.py
@@ -0,0 +1,91 @@
+import torch
+from typing import Tuple
+
+import kornia
+from kornia.geometry.epipolar import normalize_points
+
+TupleTensor = Tuple[torch.Tensor, torch.Tensor]
+
+
+def find_homography_dlt(points1: torch.Tensor, points2: torch.Tensor, weights: torch.Tensor) -> torch.Tensor:
+ r"""Computes the homography matrix using the DLT formulation.
+
+ The linear system is solved by using the Weighted Least Squares Solution for the 4 Points algorithm.
+
+ Args:
+ points1 (torch.Tensor): A set of points in the first image with a tensor shape :math:`(B, N, 2)`.
+ points2 (torch.Tensor): A set of points in the second image with a tensor shape :math:`(B, N, 2)`.
+ weights (torch.Tensor): Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.
+
+ Returns:
+ torch.Tensor: the computed homography matrix with shape :math:`(B, 3, 3)`.
+ """
+ assert points1.shape == points2.shape, points1.shape
+ assert len(points1.shape) >= 1 and points1.shape[-1] == 2, points1.shape
+ assert points1.shape[1] >= 4, points1.shape
+
+ eps: float = 1e-8
+ points1_norm, transform1 = normalize_points(points1)
+ points2_norm, transform2 = normalize_points(points2)
+
+ x1, y1 = torch.chunk(points1_norm, dim=-1, chunks=2) # BxNx1
+ x2, y2 = torch.chunk(points2_norm, dim=-1, chunks=2) # BxNx1
+ ones, zeros = torch.ones_like(x1), torch.zeros_like(x1)
+
+ # DIAPO 11: https://www.uio.no/studier/emner/matnat/its/nedlagte-emner/UNIK4690/v16/forelesninger/lecture_4_3-estimating-homographies-from-feature-correspondences.pdf # noqa: E501
+ ax = torch.cat([zeros, zeros, zeros, -x1, -y1, -ones, y2 * x1, y2 * y1, y2], dim=-1)
+ ay = torch.cat([x1, y1, ones, zeros, zeros, zeros, -x2 * x1, -x2 * y1, -x2], dim=-1)
+
+ w_list = []
+ axy_list = []
+ for i in range(points1.shape[1]):
+ axy_list.append(ax[:, i])
+ axy_list.append(ay[:, i])
+ w_list.append(weights[:, i])
+ w_list.append(weights[:, i])
+ A = torch.stack(axy_list, dim=1)
+ w = torch.stack(w_list, dim=1)
+
+ # apply weights
+ w_diag = torch.diag_embed(w)
+ A = A.transpose(-2, -1) @ w_diag @ A
+ try:
+ U, S, V = torch.svd(A)
+ except:
+ return torch.empty(points1_norm.size(0), 3, 3)
+ H = V[..., -1].view(-1, 3, 3)
+ H = transform2.inverse() @ (H @ transform1)
+ H_norm = H / (H[..., -1:, -1:] + eps)
+ return H_norm
+
+
+def find_homography_dlt_iterated(points1: torch.Tensor,
+ points2: torch.Tensor,
+ weights: torch.Tensor,
+ soft_inl_th: float = 3.0,
+ n_iter: int = 5) -> torch.Tensor:
+ r"""Computes the homography matrix using the iteratively-reweighted least squares (IRWLS)
+
+ The linear system is solved by using the Reweighted Least Squares Solution for the 4 Points algorithm.
+
+ Args:
+ points1 (torch.Tensor): A set of points in the first image with a tensor shape :math:`(B, N, 2)`.
+ points2 (torch.Tensor): A set of points in the second image with a tensor shape :math:`(B, N, 2)`.
+ weights (torch.Tensor): Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.
+ Used for the first iteration of the IRWLS.
+ soft_inl_th (float): Soft inlier threshold used for weight calculation
+ n_iter (int): number of iterations. Default is 5.
+
+ Returns:
+ torch.Tensor: the computed homography matrix with shape :math:`(B, 3, 3)`.
+ """
+
+ '''Function, which finds homography via iteratively-reweighted
+ least squares ToDo: add citation'''
+ H: torch.Tensor = find_homography_dlt(points1, points2, weights)
+ for i in range(n_iter - 1):
+ pts1_in_2: torch.Tensor = kornia.transform_points(H, points1)
+ error_squared: torch.Tensor = (pts1_in_2 - points2).pow(2).sum(dim=-1)
+ weights_new: torch.Tensor = torch.exp(-error_squared / (2.0 * (soft_inl_th ** 2)))
+ H = find_homography_dlt(points1, points2, weights_new)
+ return H
diff --git a/test/feature/test_matching.py b/test/feature/test_matching.py
new file mode 100644
index 000000000..33e1ad81f
--- /dev/null
+++ b/test/feature/test_matching.py
@@ -0,0 +1,161 @@
+import pytest
+import kornia.testing as utils # test utils
+
+from torch.testing import assert_allclose
+from torch.autograd import gradcheck
+from kornia.feature.matching import *
+
+
+class TestMatchNN:
+
+ @pytest.mark.parametrize(
+ "num_desc1, num_desc2, dim", [(1, 4, 4), (2, 5, 128), (6, 2, 32)],
+ )
+ def test_shape(self, num_desc1, num_desc2, dim, device):
+ desc1 = torch.rand(num_desc1, dim, device=device)
+ desc2 = torch.rand(num_desc2, dim, device=device)
+
+ dists, idxs = match_nn(desc1, desc2)
+ assert idxs.shape == (num_desc1, 2)
+ assert dists.shape == (num_desc1, 1)
+
+ def test_matching(self, device):
+ desc1 = torch.tensor([[0, 0.], [1, 1], [2, 2], [3, 3.], [5, 5.]], device=device)
+ desc2 = torch.tensor([[5, 5.], [3, 3.], [2.3, 2.4], [1, 1], [0, 0.]], device=device)
+
+ dists, idxs = match_nn(desc1, desc2)
+ expected_dists = torch.tensor([0, 0, 0.5, 0, 0], device=device).view(-1, 1)
+ expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)
+ assert_allclose(dists, expected_dists)
+ assert_allclose(idxs, expected_idx)
+
+ def test_gradcheck(self, device):
+ desc1 = torch.rand(5, 8, device=device)
+ desc2 = torch.rand(7, 8, device=device)
+ desc1 = utils.tensor_to_gradcheck_var(desc1) # to var
+ desc2 = utils.tensor_to_gradcheck_var(desc2) # to var
+ assert gradcheck(match_mnn, (desc1, desc2),
+ raise_exception=True, nondet_tol=1e-4)
+
+
+class TestMatchMNN:
+
+ @pytest.mark.parametrize(
+ "num_desc1, num_desc2, dim", [(1, 4, 4), (2, 5, 128), (6, 2, 32)],
+ )
+ def test_shape(self, num_desc1, num_desc2, dim, device):
+ desc1 = torch.rand(num_desc1, dim, device=device)
+ desc2 = torch.rand(num_desc2, dim, device=device)
+
+ dists, idxs = match_mnn(desc1, desc2)
+ assert idxs.shape[1] == 2
+ assert dists.shape[1] == 1
+ assert idxs.shape[0] == dists.shape[0]
+ assert dists.shape[0] <= num_desc1
+
+ def test_matching(self, device):
+ desc1 = torch.tensor([[0, 0.], [1, 1], [2, 2], [3, 3.], [5, 5.]], device=device)
+ desc2 = torch.tensor([[5, 5.], [3, 3.], [2.3, 2.4], [1, 1], [0, 0.]], device=device)
+
+ dists, idxs = match_mnn(desc1, desc2)
+ expected_dists = torch.tensor([0, 0, 0.5, 0, 0], device=device).view(-1, 1)
+ expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)
+ assert_allclose(dists, expected_dists)
+ assert_allclose(idxs, expected_idx)
+
+ def test_gradcheck(self, device):
+ desc1 = torch.rand(5, 8, device=device)
+ desc2 = torch.rand(7, 8, device=device)
+ desc1 = utils.tensor_to_gradcheck_var(desc1) # to var
+ desc2 = utils.tensor_to_gradcheck_var(desc2) # to var
+ assert gradcheck(match_mnn, (desc1, desc2),
+ raise_exception=True, nondet_tol=1e-4)
+
+
+class TestMatchSNN:
+
+ @pytest.mark.parametrize(
+ "num_desc1, num_desc2, dim", [(2, 4, 4), (2, 5, 128), (6, 2, 32)],
+ )
+ def test_shape(self, num_desc1, num_desc2, dim, device):
+ desc1 = torch.rand(num_desc1, dim, device=device)
+ desc2 = torch.rand(num_desc2, dim, device=device)
+
+ dists, idxs = match_snn(desc1, desc2)
+ assert idxs.shape[1] == 2
+ assert dists.shape[1] == 1
+ assert idxs.shape[0] == dists.shape[0]
+ assert dists.shape[0] <= num_desc1
+
+ def test_matching1(self, device):
+ desc1 = torch.tensor([[0, 0.], [1, 1], [2, 2], [3, 3.], [5, 5.]], device=device)
+ desc2 = torch.tensor([[5, 5.], [3, 3.], [2.3, 2.4], [1, 1], [0, 0.]], device=device)
+
+ dists, idxs = match_snn(desc1, desc2, 0.8)
+ expected_dists = torch.tensor([0, 0, 0.35355339059327373, 0, 0], device=device).view(-1, 1)
+ expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)
+ assert_allclose(dists, expected_dists)
+ assert_allclose(idxs, expected_idx)
+
+ def test_matching2(self, device):
+ desc1 = torch.tensor([[0, 0.], [1, 1], [2, 2], [3, 3.], [5, 5.]], device=device)
+ desc2 = torch.tensor([[5, 5.], [3, 3.], [2.3, 2.4], [1, 1], [0, 0.]], device=device)
+
+ dists, idxs = match_snn(desc1, desc2, 0.1)
+ expected_dists = torch.tensor([0., 0, 0, 0], device=device).view(-1, 1)
+ expected_idx = torch.tensor([[0, 4], [1, 3], [3, 1], [4, 0]], device=device)
+ assert_allclose(dists, expected_dists)
+ assert_allclose(idxs, expected_idx)
+
+ def test_gradcheck(self, device):
+ desc1 = torch.rand(5, 8, device=device)
+ desc2 = torch.rand(7, 8, device=device)
+ desc1 = utils.tensor_to_gradcheck_var(desc1) # to var
+ desc2 = utils.tensor_to_gradcheck_var(desc2) # to var
+ assert gradcheck(match_snn, (desc1, desc2, 0.8),
+ raise_exception=True, nondet_tol=1e-4)
+
+
+class TestMatchSMNN:
+
+ @pytest.mark.parametrize(
+ "num_desc1, num_desc2, dim", [(2, 4, 4), (2, 5, 128), (6, 2, 32)],
+ )
+ def test_shape(self, num_desc1, num_desc2, dim, device):
+ desc1 = torch.rand(num_desc1, dim, device=device)
+ desc2 = torch.rand(num_desc2, dim, device=device)
+
+ dists, idxs = match_smnn(desc1, desc2, 0.8)
+ assert idxs.shape[1] == 2
+ assert dists.shape[1] == 1
+ assert idxs.shape[0] == dists.shape[0]
+ assert dists.shape[0] <= num_desc1
+ assert dists.shape[0] <= num_desc2
+
+ def test_matching1(self, device):
+ desc1 = torch.tensor([[0, 0.], [1, 1], [2, 2], [3, 3.], [5, 5.]], device=device)
+ desc2 = torch.tensor([[5, 5.], [3, 3.], [2.3, 2.4], [1, 1], [0, 0.]], device=device)
+
+ dists, idxs = match_smnn(desc1, desc2, 0.8)
+ expected_dists = torch.tensor([0, 0, 0.5423, 0, 0], device=device).view(-1, 1)
+ expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)
+ assert_allclose(dists, expected_dists)
+ assert_allclose(idxs, expected_idx)
+
+ def test_matching2(self, device):
+ desc1 = torch.tensor([[0, 0.], [1, 1], [2, 2], [3, 3.], [5, 5.]], device=device)
+ desc2 = torch.tensor([[5, 5.], [3, 3.], [2.3, 2.4], [1, 1], [0, 0.]], device=device)
+
+ dists, idxs = match_smnn(desc1, desc2, 0.1)
+ expected_dists = torch.tensor([0., 0, 0, 0], device=device).view(-1, 1)
+ expected_idx = torch.tensor([[0, 4], [1, 3], [3, 1], [4, 0]], device=device)
+ assert_allclose(dists, expected_dists)
+ assert_allclose(idxs, expected_idx)
+
+ def test_gradcheck(self, device):
+ desc1 = torch.rand(5, 8, device=device)
+ desc2 = torch.rand(7, 8, device=device)
+ desc1 = utils.tensor_to_gradcheck_var(desc1) # to var
+ desc2 = utils.tensor_to_gradcheck_var(desc2) # to var
+ assert gradcheck(match_smnn, (desc1, desc2, 0.8),
+ raise_exception=True, nondet_tol=1e-4)
diff --git a/test/geometry/test_homography.py b/test/geometry/test_homography.py
new file mode 100644
index 000000000..ffe8ed6a7
--- /dev/null
+++ b/test/geometry/test_homography.py
@@ -0,0 +1,144 @@
+import pytest
+
+import torch
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+import kornia
+import kornia.testing as utils # test utils
+from kornia.geometry.homography import find_homography_dlt, find_homography_dlt_iterated
+
+
+class TestFindHomographyDLT:
+ def test_smoke(self, device, dtype):
+ points1 = torch.rand(1, 4, 2, device=device, dtype=dtype)
+ points2 = torch.rand(1, 4, 2, device=device, dtype=dtype)
+ weights = torch.ones(1, 4, device=device, dtype=dtype)
+ H = find_homography_dlt(points1, points2, weights)
+ assert H.shape == (1, 3, 3)
+
+ @pytest.mark.parametrize(
+ "batch_size, num_points", [(1, 4), (2, 5), (3, 6)],
+ )
+ def test_shape(self, batch_size, num_points, device, dtype):
+ B, N = batch_size, num_points
+ points1 = torch.rand(B, N, 2, device=device, dtype=dtype)
+ points2 = torch.rand(B, N, 2, device=device, dtype=dtype)
+ weights = torch.ones(B, N, device=device, dtype=dtype)
+ H = find_homography_dlt(points1, points2, weights)
+ assert H.shape == (B, 3, 3)
+
+ @pytest.mark.parametrize("batch_size", [1, 2, 5])
+ def test_clean_points_and_gradcheck(self, batch_size, device):
+ # generate input data
+ H = (torch.eye(3, device=device)[None].repeat(batch_size, 1, 1) +
+ 0.3 * torch.rand(batch_size, 3, 3, device=device))
+ H = H / H[:, 2:3, 2:3]
+
+ points_src = torch.rand(batch_size, 10, 2).to(device)
+ points_dst = kornia.transform_points(H, points_src)
+ weights = torch.ones(batch_size, 10, device=device)
+
+ # compute transform from source to target
+ dst_homo_src = find_homography_dlt(points_src, points_dst, weights)
+
+ assert_allclose(
+ kornia.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)
+
+ # compute gradient check
+ points_src = utils.tensor_to_gradcheck_var(points_src) # to var
+ points_dst = utils.tensor_to_gradcheck_var(points_dst) # to var
+ weights = utils.tensor_to_gradcheck_var(weights) # to var
+
+ assert gradcheck(
+ find_homography_dlt, (
+ points_src,
+ points_dst,
+ weights
+ ), rtol=1e-1, atol=1e-5,
+ raise_exception=True)
+
+
+class TestFindHomographyDLTIter:
+ def test_smoke(self, device, dtype):
+ points1 = torch.rand(1, 4, 2, device=device, dtype=dtype)
+ points2 = torch.rand(1, 4, 2, device=device, dtype=dtype)
+ weights = torch.ones(1, 4, device=device, dtype=dtype)
+ H = find_homography_dlt_iterated(points1, points2, weights, 5)
+ assert H.shape == (1, 3, 3)
+
+ @pytest.mark.parametrize(
+ "batch_size, num_points", [(1, 4), (2, 5), (3, 6)],
+ )
+ def test_shape(self, batch_size, num_points, device, dtype):
+ B, N = batch_size, num_points
+ points1 = torch.rand(B, N, 2, device=device, dtype=dtype)
+ points2 = torch.rand(B, N, 2, device=device, dtype=dtype)
+ weights = torch.ones(B, N, device=device, dtype=dtype)
+ H = find_homography_dlt_iterated(points1, points2, weights, 5)
+ assert H.shape == (B, 3, 3)
+
+ @pytest.mark.parametrize("batch_size", [1, 2, 3])
+ def test_clean_points_and_gradcheck(self, batch_size, device):
+ # generate input data
+ dtype = torch.float64
+ H = (torch.eye(3, device=device)[None].repeat(batch_size, 1, 1) +
+ 0.3 * torch.rand(batch_size, 3, 3, device=device))
+ H = H / H[:, 2:3, 2:3]
+
+ points_src = torch.rand(batch_size, 10, 2).to(device)
+ points_dst = kornia.transform_points(H, points_src)
+ weights = torch.ones(batch_size, 10, device=device)
+
+ # compute transform from source to target
+ dst_homo_src = find_homography_dlt_iterated(points_src, points_dst, weights, 10)
+
+ assert_allclose(
+ kornia.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)
+
+ # compute gradient check
+ points_src = utils.tensor_to_gradcheck_var(points_src) # to var
+ points_dst = utils.tensor_to_gradcheck_var(points_dst) # to var
+ weights = utils.tensor_to_gradcheck_var(weights) # to var
+ assert gradcheck(
+ kornia.find_homography_dlt_iterated, (
+ points_src,
+ points_dst,
+ weights,
+ ),
+ rtol=1e-3, atol=1e-4,
+ raise_exception=True)
+
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ def test_dirty_points_and_gradcheck(self, batch_size, device):
+ # generate input data
+ dtype = torch.float64
+ H = (torch.eye(3, device=device)[None].repeat(batch_size, 1, 1) +
+ 0.3 * torch.rand(batch_size, 3, 3, device=device))
+ H = H / H[:, 2:3, 2:3]
+
+ points_src = 100. * torch.rand(batch_size, 20, 2).to(device)
+ points_dst = kornia.transform_points(H, points_src)
+
+ # making last point an outlier
+ points_dst[:, -1, :] += 20
+
+ weights = torch.ones(batch_size, 20, device=device)
+
+ # compute transform from source to target
+ dst_homo_src = find_homography_dlt_iterated(points_src, points_dst, weights, 0.5, 10)
+
+ assert_allclose(
+ kornia.transform_points(dst_homo_src, points_src[:, :-1]), points_dst[:, :-1], rtol=1e-3, atol=1e-3)
+
+ # compute gradient check
+ points_src = utils.tensor_to_gradcheck_var(points_src) # to var
+ points_dst = utils.tensor_to_gradcheck_var(points_dst) # to var
+ weights = utils.tensor_to_gradcheck_var(weights) # to var
+ assert gradcheck(
+ kornia.find_homography_dlt_iterated, (
+ points_src,
+ points_dst,
+ weights,
+ ),
+ rtol=1e-3, atol=1e-4, raise_exception=True)