π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Added FGINN matching (#1813)
Dmytro Mishkin6b47c0442324
diff --git a/docs/source/feature.rst b/docs/source/feature.rstindex f4e964a29..d67d73b7d 100644--- a/docs/source/feature.rst+++ b/docs/source/feature.rst@@ -35,10 +35,14 @@ Matching.. autofunction:: match_mnn.. autofunction:: match_snn.. autofunction:: match_smnn+.. autofunction:: match_fginn.. autoclass:: DescriptorMatcher:members: forward+.. autoclass:: GeometryAwareDescriptorMatcher+ :members: forward+.. autoclass:: LocalFeature:members: forwarddiff --git a/docs/source/references.bib b/docs/source/references.bibindex a1ed0f1d5..11fbed519 100644--- a/docs/source/references.bib+++ b/docs/source/references.bib@@ -209,3 +209,12 @@year = {2022},copyright = {Creative Commons Attribution 4.0 International}}++@article{MODS2015,+ aitle = {MODS: Fast and robust method for two-view matching },+ author = {Dmytro Mishkin and Jiri Matas and Michal Perdoch},+ journal = {Computer Vision and Image Understanding },+ year = {2015},+ pages = {81 - 93},+ volume = {141}+}diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.pyindex 855803ee4..877df306b 100644--- a/kornia/feature/__init__.py+++ b/kornia/feature/__init__.py@@ -34,7 +34,15 @@ from .laf import (set_laf_orientation,)from .loftr import LoFTR-from .matching import DescriptorMatcher, match_mnn, match_nn, match_smnn, match_snn+from .matching import (+ DescriptorMatcher,+ GeometryAwareDescriptorMatcher,+ match_fginn,+ match_mnn,+ match_nn,+ match_smnn,+ match_snn,+)from .mkd import MKDDescriptorfrom .orientation import LAFOrienter, OriNet, PatchDominantGradientOrientationfrom .responses import (@@ -57,7 +65,9 @@ __all__ = ["match_mnn","match_snn","match_smnn",+ "match_fginn","DescriptorMatcher",+ "GeometryAwareDescriptorMatcher","get_laf_descriptors","LAFDescriptor","LocalFeature",diff --git a/kornia/feature/matching.py b/kornia/feature/matching.pyindex 20f44a804..f3940d386 100644--- a/kornia/feature/matching.py+++ b/kornia/feature/matching.py@@ -1,11 +1,17 @@-from typing import Optional, Tuple+from typing import Dict, Optional, Tupleimport torchimport torch.nn as nn+from kornia.feature.laf import get_laf_centerfrom kornia.testing import KORNIA_CHECK_DM_DESC, KORNIA_CHECK_SHAPE, Tensor+def _get_default_fginn_params():+ config = {"th": 0.85, "mutual": False, "spatial_th": 10.0}+ return config++def _get_lazy_distance_matrix(desc1: Tensor, desc2: Tensor, dm_: Optional[Tensor] = None):"""Helper function, which checks validity of provided distance matrix, or calculates L2-distance matrix dm isnot provided.@@ -187,6 +193,83 @@ def match_smnn(desc1: Tensor, desc2: Tensor, th: float = 0.95, dm: Optional[Tensreturn match_dists, matches_idxs+def match_fginn(+ desc1: Tensor,+ desc2: Tensor,+ lafs1: Tensor,+ lafs2: Tensor,+ th: float = 0.8,+ spatial_th: float = 10.0,+ mutual: bool = False,+ dm: Optional[Tensor] = None,+) -> Tuple[Tensor, Tensor]:+ """Function, which finds nearest neighbors in desc2 for each vector in desc1.++ The method satisfies first to second nearest neighbor distance <= th,+ and assures 2nd nearest neighbor is geometrically inconsistent with the 1st one+ (see :cite:`MODS2015` for more details)++ If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.++ Args:+ desc1: Batch of descriptors of a shape :math:`(B1, D)`.+ desc2: Batch of descriptors of a shape :math:`(B2, D)`.+ lafs1: LAFs of a shape :math:`(1, B1, 2, 3)`.+ lafs2: LAFs of a shape :math:`(1, B1, 2, 3)`.++ th: distance ratio threshold.+ spatial_th: minimal distance in pixels to 2nd nearest neighbor.+ mutual: also perform mutual nearest neighbor check+ dm: Tensor containing the distances from each descriptor in desc1+ to each descriptor in desc2, shape of :math:`(B1, B2)`.++ Return:+ - Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.+ - Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,+ where 0 <= B3 <= B1.+ """+ KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])+ KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])+ BIG_NUMBER = 1000000.0++ distance_matrix = _get_lazy_distance_matrix(desc1, desc2, dm)+ dtype = distance_matrix.dtype++ if desc2.shape[0] < 2: # We cannot perform snn check, so output empty matches+ return _no_match(distance_matrix)++ num_candidates = max(2, min(10, desc2.shape[0]))+ vals_cand, idxs_in_2 = torch.topk(distance_matrix, num_candidates, dim=1, largest=False)+ vals = vals_cand[:, 0]+ xy2 = get_laf_center(lafs2).view(-1, 2)+ candidates_xy = xy2[idxs_in_2]+ kdist = torch.norm(candidates_xy - candidates_xy[0:1], p=2, dim=2)+ fginn_vals = vals_cand[:, 1:] + (kdist[:, 1:] < spatial_th).to(dtype) * BIG_NUMBER+ fginn_vals_best, fginn_idxs_best = fginn_vals.min(dim=1)++ # orig_idxs = idxs_in_2.gather(1, fginn_idxs_best.unsqueeze(1))[0]+ # if you need to know fginn indexes - uncomment++ vals_2nd = fginn_vals_best+ idxs_in_2 = idxs_in_2[:, 0]++ ratio = vals / vals_2nd+ mask = ratio <= th+ match_dists = ratio[mask]+ if len(match_dists) == 0:+ return _no_match(distance_matrix)+ idxs_in1 = torch.arange(0, idxs_in_2.size(0), device=distance_matrix.device)[mask]+ idxs_in_2 = idxs_in_2[mask]+ matches_idxs = torch.cat([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], dim=1)+ match_dists, matches_idxs = match_dists.view(-1, 1), matches_idxs.view(-1, 2)++ if not mutual: # returning 1-way matches+ return match_dists, matches_idxs+ _, idxs_in_1_mut = torch.min(distance_matrix, dim=0)+ good_mask = matches_idxs[:, 0] == idxs_in_1_mut[matches_idxs[:, 1]]+ return match_dists[good_mask], matches_idxs[good_mask]++class DescriptorMatcher(nn.Module):"""Module version of matching functions.@@ -213,6 +296,8 @@ class DescriptorMatcher(nn.Module):Args:desc1: Batch of descriptors of a shape :math:`(B1, D)`.desc2: Batch of descriptors of a shape :math:`(B2, D)`.+ lafs1: LAFs of a shape :math:`(1, B1, 2, 3)`.+ lafs2: LAFs of a shape :math:`(1, B1, 2, 3)`.Return:- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.@@ -230,3 +315,46 @@ class DescriptorMatcher(nn.Module):else:raise NotImplementedErrorreturn out+++class GeometryAwareDescriptorMatcher(nn.Module):+ """Module version of matching functions.++ See :func:`~kornia.feature.match_nn`, :func:`~kornia.feature.match_snn`,+ :func:`~kornia.feature.match_mnn` or :func:`~kornia.feature.match_smnn` for more details.++ Args:+ match_mode: type of matching, can be `fginn`.+ th: threshold on distance ratio, or other quality measure.+ """++ known_modes = ['fginn']++ def __init__(self, match_mode: str = 'fginn', params: Dict = {}) -> None:+ super().__init__()+ _match_mode: str = match_mode.lower()+ if _match_mode not in self.known_modes:+ raise NotImplementedError(f"{match_mode} is not supported. Try one of {self.known_modes}")+ self.match_mode = _match_mode+ self.params = params++ def forward(self, desc1: Tensor, desc2: Tensor, lafs1: Tensor, lafs2: Tensor) -> Tuple[Tensor, Tensor]:+ """+ Args:+ desc1: Batch of descriptors of a shape :math:`(B1, D)`.+ desc2: Batch of descriptors of a shape :math:`(B2, D)`.+ lafs1: LAFs of a shape :math:`(1, B1, 2, 3)`.+ lafs2: LAFs of a shape :math:`(1, B1, 2, 3)`.++ Return:+ - Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.+ - Long tensor indexes of matching descriptors in desc1 and desc2,+ shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`.+ """+ if self.match_mode == 'fginn':+ params = _get_default_fginn_params()+ params.update(self.params)+ out = match_fginn(desc1, desc2, lafs1, lafs2, params['th'], params['spatial_th'], params['mutual'])+ else:+ raise NotImplementedError+ return outdiff --git a/test/feature/test_matching.py b/test/feature/test_matching.pyindex 724e3ac9c..ed4929fbb 100644--- a/test/feature/test_matching.py+++ b/test/feature/test_matching.py@@ -3,7 +3,16 @@ import torchfrom torch.autograd import gradcheckimport kornia.testing as utils # test utils-from kornia.feature.matching import DescriptorMatcher, match_mnn, match_nn, match_smnn, match_snn+from kornia.feature.laf import laf_from_center_scale_ori+from kornia.feature.matching import (+ DescriptorMatcher,+ GeometryAwareDescriptorMatcher,+ match_fginn,+ match_mnn,+ match_nn,+ match_smnn,+ match_snn,+)from kornia.testing import assert_close@@ -196,3 +205,117 @@ class TestMatchSMNN:matcher_jit = torch.jit.script(DescriptorMatcher(match_type, 0.8).to(device))assert_close(matcher(desc1, desc2)[0], matcher_jit(desc1, desc2)[0])assert_close(matcher(desc1, desc2)[1], matcher_jit(desc1, desc2)[1])+++class TestMatchFGINN:+ @pytest.mark.parametrize("num_desc1, num_desc2, dim", [(2, 4, 4), (2, 5, 128), (6, 2, 32)])+ def test_shape_one_way(self, num_desc1, num_desc2, dim, device):+ desc1 = torch.rand(num_desc1, dim, device=device)+ desc2 = torch.rand(num_desc2, dim, device=device)+ lafs1 = torch.rand(1, num_desc1, 2, 3, device=device)+ lafs2 = torch.rand(1, num_desc2, 2, 3, device=device)++ dists, idxs = match_fginn(desc1, desc2, lafs1, lafs2, 0.9, 1000)+ assert idxs.shape[1] == 2+ assert dists.shape[1] == 1+ assert idxs.shape[0] == dists.shape[0]+ assert dists.shape[0] <= num_desc1++ @pytest.mark.parametrize("num_desc1, num_desc2, dim", [(2, 4, 4), (2, 5, 128), (6, 2, 32)])+ def test_shape_two_way(self, num_desc1, num_desc2, dim, device):+ desc1 = torch.rand(num_desc1, dim, device=device)+ desc2 = torch.rand(num_desc2, dim, device=device)+ lafs1 = torch.rand(1, num_desc1, 2, 3, device=device)+ lafs2 = torch.rand(1, num_desc2, 2, 3, device=device)++ dists, idxs = match_fginn(desc1, desc2, lafs1, lafs2, 0.9, 1000, mutual=True)+ 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.0], [1, 1], [2, 2], [3, 3.0], [5, 5.0]], device=device)+ desc2 = torch.tensor([[5, 5.0], [3, 3.0], [2.3, 2.4], [1, 1], [0, 0.0]], device=device)+ lafs1 = laf_from_center_scale_ori(desc1[None])+ lafs2 = laf_from_center_scale_ori(desc2[None])++ dists, idxs = match_fginn(desc1, desc2, lafs1, lafs2, 0.8, 2.0)+ expected_dists = torch.tensor([0, 0, 0.3536, 0, 0], device=device).view(-1, 1)+ expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)+ assert_close(dists, expected_dists, rtol=0.001, atol=1e-3)+ assert_close(idxs, expected_idx)+ matcher = GeometryAwareDescriptorMatcher('fginn', {"spatial_th": 2.0}).to(device)+ dists1, idxs1 = matcher(desc1, desc2, lafs1, lafs2)+ assert_close(dists1, expected_dists, rtol=0.001, atol=1e-3)+ assert_close(idxs1, expected_idx)++ def test_matching_mutual(self, device):+ desc1 = torch.tensor([[0, 0.1], [1, 1], [2, 2], [3, 3.0], [5, 5.0], [0.0, 0]], device=device)+ desc2 = torch.tensor([[5, 5.0], [3, 3.0], [2.3, 2.4], [1, 1], [0, 0.0]], device=device)+ lafs1 = laf_from_center_scale_ori(desc1[None])+ lafs2 = laf_from_center_scale_ori(desc2[None])++ dists, idxs = match_fginn(desc1, desc2, lafs1, lafs2, 0.8, 2.0, mutual=True)+ expected_dists = torch.tensor([0, 0.3535, 0, 0, 0], device=device).view(-1, 1)+ expected_idx = torch.tensor([[1, 3], [2, 2], [3, 1], [4, 0], [5, 4]], device=device)+ assert_close(dists, expected_dists, rtol=0.001, atol=1e-3)+ assert_close(idxs, expected_idx)+ matcher = GeometryAwareDescriptorMatcher('fginn', {"spatial_th": 2.0, "mutual": True}).to(device)+ dists1, idxs1 = matcher(desc1, desc2, lafs1, lafs2)+ assert_close(dists1, expected_dists, rtol=0.001, atol=1e-3)+ assert_close(idxs1, expected_idx)++ def test_nomatch(self, device):+ desc1 = torch.tensor([[0, 0.0]], device=device)+ desc2 = torch.tensor([[5, 5.0]], device=device)+ lafs1 = laf_from_center_scale_ori(desc1[None])+ lafs2 = laf_from_center_scale_ori(desc2[None])++ dists, idxs = match_fginn(desc1, desc2, lafs1, lafs2, 0.8)+ assert len(dists) == 0+ assert len(idxs) == 0++ def test_matching2(self, device):+ desc1 = torch.tensor([[0, 0.0], [1, 1], [2, 2], [3, 3.0], [5, 5.0]], device=device)+ desc2 = torch.tensor([[5, 5.0], [3, 3.0], [2.3, 2.4], [1, 1], [0, 0.0]], device=device)+ lafs1 = laf_from_center_scale_ori(desc1[None])+ lafs2 = laf_from_center_scale_ori(desc2[None])++ dists, idxs = match_fginn(desc1, desc2, lafs1, lafs2, 0.8, 0.0001)+ expected_dists = torch.tensor([0, 0, 0.3536, 0, 0], device=device).view(-1, 1)+ expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)+ assert_close(dists, expected_dists, rtol=0.001, atol=1e-3)+ assert_close(idxs, expected_idx)+ matcher = GeometryAwareDescriptorMatcher('fginn', {"spatial_th": 2.0}).to(device)+ dists1, idxs1 = matcher(desc1, desc2, lafs1, lafs2)+ assert_close(dists1, expected_dists, rtol=0.001, atol=1e-3)+ assert_close(idxs1, expected_idx)++ def test_gradcheck(self, device):+ desc1 = torch.rand(5, 8, device=device)+ desc2 = torch.rand(7, 8, device=device)+ center1 = torch.rand(1, 5, 2, device=device)+ center2 = torch.rand(1, 7, 2, device=device)+ lafs1 = laf_from_center_scale_ori(center1)+ lafs2 = laf_from_center_scale_ori(center2)+ desc1 = utils.tensor_to_gradcheck_var(desc1) # to var+ desc2 = utils.tensor_to_gradcheck_var(desc2) # to var+ lafs1 = utils.tensor_to_gradcheck_var(lafs1) # to var+ lafs2 = utils.tensor_to_gradcheck_var(lafs2) # to var+ assert gradcheck(match_fginn, (desc1, desc2, lafs1, lafs2, 0.8, 0.05), raise_exception=True, nondet_tol=1e-4)++ @pytest.mark.jit+ @pytest.mark.skip("keyword-arg expansion is not supported")+ def test_jit(self, device, dtype):+ desc1 = torch.rand(5, 8, device=device, dtype=dtype)+ desc2 = torch.rand(7, 8, device=device, dtype=dtype)+ center1 = torch.rand(1, 5, 2, device=device)+ center2 = torch.rand(1, 7, 2, device=device)+ lafs1 = laf_from_center_scale_ori(center1)+ lafs2 = laf_from_center_scale_ori(center2)+ matcher = DescriptorMatcher('fginn', 0.8).to(device)+ matcher_jit = torch.jit.script(DescriptorMatcher('fginn', 0.8).to(device))+ assert_close(matcher(desc1, desc2)[0], matcher_jit(desc1, desc2, lafs1, lafs2)[0])+ assert_close(matcher(desc1, desc2)[1], matcher_jit(desc1, desc2, lafs1, lafs2)[1])