π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): make match_fginn's geometric check use each query's own 1st NN (#4075)
Dmytro Mishkin179be72a6836
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a546052d7..dc35a55a8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -97,6 +97,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0and the device guard in `BaseTester.gradcheck` for the six callers named something else. No runtimebehavior changed.+* Fix `match_fginn`'s geometric consistency check comparing every query's candidates against **query 0**'s+ candidates instead of against the query's own 1st nearest neighbor, which changes every `match_fginn` and+ `GeometryAwareDescriptorMatcher("fginn")` result -- the latter being that class's *default* mode (#4062). The distance+ `kdist[i, k] = || xy2[idx[i, k]] - xy2[idx[0, k]] ||` was measured from a slice of dim 0 that broadcast query 0's+ whole candidate list over the batch; it is now `candidates_xy[:, 0:1]`, i.e.+ `kdist[i, k] = || xy2[idx[i, k]] - xy2[idx[i, 0]] ||`. Three consequences disappear with it. The geometric term+ was inert -- an unrelated query's candidates are almost always farther apart than `spatial_th`, so nothing was+ penalized and the raw 2nd nearest neighbor was used, making `match_fginn` behave as `match_snn`: on a 300x300+ descriptor set with planted near-duplicates, 15 of the 15 matches shared with `match_snn` had an identical ratio+ before and 14 of 15 after. Query 0 always matched, since `candidates_xy[0] - candidates_xy[0]` is identically zero,+ so all of its candidates were penalized and its ratio collapsed to ~0. And a query's ratio depended on the other+ queries in the batch: with only query 0 changed, one query's ratio moved between `0.9005` and `2.8e-08`. The seven+ existing FGINN tests pass unchanged on both sides, which is how this survived; two tests that discriminate it were+ added. `match_fginn`'s docstring now also records the saturation corner, where every candidate falls within+ `spatial_th` of the 1st nearest neighbor, the ratio collapses towards zero and the match is accepted.+## :rocket: [0.6.11] - 2022-03-28### :new: New Featuresdiff --git a/kornia/feature/matching.py b/kornia/feature/matching.pyindex 755e2a8c2..f8a329eba 100644--- a/kornia/feature/matching.py+++ b/kornia/feature/matching.py@@ -269,6 +269,13 @@ def match_fginn(If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.+ .. note::+ The geometric check looks at the ``min(10, B2)`` nearest candidates and penalizes every one of them+ that lies within ``spatial_th`` pixels of the query's own 1st nearest neighbor. When *all* of them do --+ a dense cluster of detections on one structure -- the effective 2nd nearest neighbor distance saturates,+ the ratio collapses towards zero and the match is **accepted**. That is the intended reading: no distinct+ competing structure among the candidates means the 1st nearest neighbor is unambiguous.+Args:desc1: Batch of descriptors of a shape :math:`(B1, D)`.desc2: Batch of descriptors of a shape :math:`(B2, D)`.@@ -300,15 +307,12 @@ def match_fginn(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)+ candidates_xy = xy2[idxs_in_2] # (B1, num_candidates, 2)+ # Distance from every candidate to the 1st nearest neighbour *of the same query*.+ # Indexing dim 0 here would take query 0's candidate list and broadcast it over all queries.+ 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+ vals_2nd, _ = fginn_vals.min(dim=1)idxs_in_2 = idxs_in_2[:, 0]ratio = vals / vals_2nddiff --git a/tests/feature/test_matching.py b/tests/feature/test_matching.pyindex 4b67686e0..ff351f63f 100644--- a/tests/feature/test_matching.py+++ b/tests/feature/test_matching.py@@ -332,6 +332,65 @@ class TestMatchFGINN(BaseTester):self.assert_close(dists1, expected_dists, rtol=0.001, atol=1e-3)self.assert_close(idxs1, expected_idx)+ @staticmethod+ def _suppression_case(device, dtype):+ """A textbook FGINN case.++ The 2nd nearest neighbour in descriptor space sits 1 px from the 1st, so it is a repeated+ detection of the same structure and must not be used for the ratio test. The effective 2nd+ neighbour is then ``desc2[2]``, giving ``0.1 / 0.5 = 0.2`` rather than ``0.1 / 0.2 = 0.5``.+ """+ desc2 = torch.tensor([[0.1, 0.0], [0.2, 0.0], [0.5, 0.0], [0.9, 0.0]], device=device, dtype=dtype)+ xy2 = torch.tensor(+ [+ [10.0, 10.0], # 1st NN+ [11.0, 10.0], # 1 px away -> suppressed by the spatial check+ [50.0, 50.0], # far -> the effective 2nd NN+ [90.0, 90.0],+ ],+ device=device,+ dtype=dtype,+ )+ lafs2 = laf_from_center_scale_ori(xy2[None], torch.ones(1, 4, 1, 1, device=device, dtype=dtype))+ return desc2, lafs2++ def test_second_neighbour_near_the_first_is_suppressed(self, device, dtype):+ desc2, lafs2 = self._suppression_case(device, dtype)+ query = torch.tensor([0.0, 0.0], device=device, dtype=dtype)+ desc1 = torch.stack([query, query])+ lafs1 = laf_from_center_scale_ori(+ torch.zeros(1, 2, 2, device=device, dtype=dtype), torch.ones(1, 2, 1, 1, device=device, dtype=dtype)+ )++ dists, idxs = match_fginn(desc1, desc2, lafs1, lafs2, th=0.3, spatial_th=5.0)++ expected_dists = torch.tensor([0.2, 0.2], device=device, dtype=dtype).view(-1, 1)+ expected_idx = torch.tensor([[0, 0], [1, 0]], device=device)+ self.assert_close(dists, expected_dists, rtol=1e-3, atol=1e-3)+ self.assert_close(idxs, expected_idx)++ def test_result_is_independent_of_the_other_queries(self, device, dtype):+ """A query's ratio must not depend on unrelated queries in the same batch (see #4062)."""+ desc2, lafs2 = self._suppression_case(device, dtype)+ query = torch.tensor([0.0, 0.0], device=device, dtype=dtype)+ # a decoy whose own nearest neighbour is desc2[3], i.e. a different candidate ordering+ decoy = torch.tensor([1.0, 0.0], device=device, dtype=dtype)++ ratios = []+ for first in (query, decoy):+ desc1 = torch.stack([first, query])+ lafs1 = laf_from_center_scale_ori(+ torch.zeros(1, 2, 2, device=device, dtype=dtype),+ torch.ones(1, 2, 1, 1, device=device, dtype=dtype),+ )+ dists, idxs = match_fginn(desc1, desc2, lafs1, lafs2, th=0.3, spatial_th=5.0)+ hit = dists[idxs[:, 0] == 1]+ assert len(hit) == 1, "the second query must match regardless of the first"+ ratios.append(hit[0, 0])++ self.assert_close(ratios[0], ratios[1], rtol=1e-4, atol=1e-4)+ self.assert_close(ratios[1], torch.tensor(0.2, device=device, dtype=dtype), rtol=1e-3, atol=1e-3)+def test_gradcheck(self, device):desc1 = torch.rand(5, 8, device=device, dtype=torch.float64)desc2 = torch.rand(7, 8, device=device, dtype=torch.float64)