π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): measure the XFeat* refinement soft-argmax from bin 3, not the reference's bin 4 (#6419)
Dmytro Mishkin160e0f0f7a1f
diff --git a/changelog.d/6419.fixed.md b/changelog.d/6419.fixed.mdnew file mode 100644index 000000000..f7e77f2ae--- /dev/null+++ b/changelog.d/6419.fixed.md@@ -0,0 +1 @@+`XFeat.match_xfeat_star` measures the refinement soft-argmax from bin 3 of the fine matcher's 8 x 8 heatmap, where the pretrained fine matcher puts a zero displacement, instead of from bin 4 as the reference implementation does. The refined points of the first image used to be shifted by about 1 px up and to the left; matching an image with itself, 94 % of them now stay within 1 px, against 1 %. Away from a zero displacement the refinement still moves a point only about half of the way, as the reference does.diff --git a/kornia/feature/xfeat.py b/kornia/feature/xfeat.pyindex 4f0b55289..af8810337 100644--- a/kornia/feature/xfeat.py+++ b/kornia/feature/xfeat.py@@ -350,6 +350,18 @@ class XFeat(nn.Module):a border position against part of its window. With the pretrained weights on Oxford graf and boat img1,every candidate of the reference that kornia leaves out lies in that border strip.+ XFeat* (:meth:`match_xfeat_star`) moves each matched keypoint of the first image by the soft-argmax of the+ fine matcher's 8 x 8 heatmap times the keypoint's scale, measured from bin 3 of each axis. This also departs+ on purpose from the reference implementation, which measures it from bin 4, the window centre: the pretrained+ fine matcher puts a zero displacement at bin 3. Matching Oxford bikes img1 with itself (pretrained weights,+ ``multiscale=False``), the reference's refinement moves the points by (-1.04, -1.25) px on average and leaves+ 1 % of them within 1 px of their position, against (-0.04, -0.25) px and 94 % from bin 3. On 18 Oxford affine+ pairs the median homography corner error drops from 2.58 to 2.30 px; IMC 2021 PhotoTourism relative pose+ mAA@10 is the same within noise (0.441 and 0.443 over 813 pairs). Away from a zero displacement the soft-argmax+ still moves a point only about half of the way, as in the reference: on Oxford graf 1-2 to 1-5 its response to+ the true sub-cell offset has a slope of about 0.5, so bin 3 removes the constant part of the error, not that+ shrinkage.+Example:>>> model = XFeat.from_pretrained()>>> img = torch.rand(1, 3, 256, 256)@@ -427,14 +439,18 @@ class XFeat(nn.Module):@staticmethoddef _subpix_softmax2d(heatmaps: torch.Tensor, temp: float = 3.0) -> torch.Tensor:- """Compute soft-argmax offsets from an (N, H, W) heatmap."""+ """Compute soft-argmax offsets from an (N, H, W) heatmap, measured from bin ``(W // 2 - 1, H // 2 - 1)``.++ That bin, not the window centre the reference implementation uses, is where the pretrained fine matcher puts+ a zero displacement; see the XFeat* note of :class:`XFeat`.+ """N, H, W = heatmaps.shapeheatmaps = torch.softmax(temp * heatmaps.view(N, H * W), -1).view(N, H, W)x, y = torch.meshgrid(torch.arange(W, device=heatmaps.device), torch.arange(H, device=heatmaps.device), indexing="xy")- x = x - (W // 2)- y = y - (H // 2)+ x = x - (W // 2 - 1)+ y = y - (H // 2 - 1)coords = torch.cat([(x[None] * heatmaps)[..., None], (y[None] * heatmaps)[..., None]], -1)return coords.view(N, H * W, 2).sum(1)diff --git a/tests/feature/test_xfeat.py b/tests/feature/test_xfeat.pyindex ec92e8e70..e6c697aa1 100644--- a/tests/feature/test_xfeat.py+++ b/tests/feature/test_xfeat.py@@ -485,6 +485,20 @@ def test_lighterglue_reference_matches(device, data):assert frac > 0.95, f"Only {frac:.1%} of reference matches reproduced within joint distance 2.0 px"[email protected]("data", ["xfeat_outdoor"], indirect=True)+def test_xfeat_star_refines_an_image_matched_with_itself_in_place_6418(device, data):+ # #6418: each cell of an image matched with itself is its own coarse match, so the mean refinement offset is the+ # bias of the refinement. Measured from bin 4, as the reference does, it is about -1 px on each axis.+ xfeat = XFeat.from_pretrained().to(device)+ out = xfeat.detectAndComputeDense(data["img1"].to(device), multiscale=False)+ refined = xfeat._refine_matches(out, out, xfeat._batch_match(out["descriptors"], out["descriptors"]), 0)+ displacement = refined[:, :2] - refined[:, 2:]+ assert displacement.shape[0] > 100+ assert displacement.mean(0).abs().max() < 0.5+ assert (displacement.norm(dim=-1) < 1).float().mean() > 0.8++class TestConventionsXFeat(BaseTester):@staticmethoddef _net_outputs(peaks, h, w, reliability=0.5):@@ -644,6 +658,14 @@ class TestConventionsXFeat(BaseTester):xfeat.detectAndComputeDense(image, -1, False)assert seen == [None]+ def test_convention_xfeat_star_offsets_are_measured_from_bin_3_6418(self, device, dtype):+ # a heatmap peaked at bin (x, y) of its 8 x 8 window moves the keypoint by (x - 3, y - 3)+ heatmaps = torch.zeros(3, 8, 8, device=device, dtype=dtype)+ for i, (x, y) in enumerate(((3, 3), (5, 2), (0, 7))):+ heatmaps[i, y, x] = 20.0+ expected = torch.tensor([[0.0, 0.0], [2.0, -1.0], [-3.0, 4.0]], device=device, dtype=dtype)+ self.assert_close(XFeat._subpix_softmax2d(heatmaps), expected, atol=1e-3, rtol=0)+def test_smoke_xfeat_star_matching_runs_with_a_scale_of_zero_budget(self, device, dtype):torch.manual_seed(0)xfeat = XFeat().to(device).eval()