Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(feature): XFeat.match_xfeat matches a batch of image pairs (M1 MPS 1.26x for two pairs) (#6496)

Dmytro Mishkinc295da1ff0a6
diff --git a/changelog.d/6496.breaking.md b/changelog.d/6496.breaking.md
new file mode 100644
index 000000000..82b5b197d
--- /dev/null
+++ b/changelog.d/6496.breaking.md
@@ -0,0 +1,9 @@
+`XFeat.match_xfeat` matches a batch of image pairs: image `b` of `img1` with image `b` of `img2`. For a batch of more
+than one pair it now returns a list with one `(N, 4)` tensor of `(x1, y1, x2, y2)` matches per pair, as
+`match_xfeat_star` does, and an empty batch gives an empty list. Before, a batch was extracted whole, but only its first
+pair was matched, and the method returned the tuple `(mkpts0, mkpts1)` of that pair alone. Code that unpacked the result
+of a batched call must change: with two pairs, `mkpts0, mkpts1 = model.match_xfeat(a, b)` still unpacks, but now into
+the `(N, 4)` matches of pair 0 and of pair 1. A single pair still returns `(mkpts0, mkpts1)`, and batches of different
+sizes raise. Each batch runs through `detectAndCompute` once: matching 2, 4 and 8 pairs of 640 x 480 images in one call
+instead of one call per pair is 1.6x, 2.7x and 3.8x faster on CUDA (RTX 4090). For two pairs it is 1.26x faster on MPS
+(Apple M1) and 1.1-1.2x on an x86 CPU, but 0.93x on an Apple M1 CPU, where one call per pair stays faster.
diff --git a/kornia/feature/xfeat.py b/kornia/feature/xfeat.py
index af8810337..4ad9a9512 100644
--- a/kornia/feature/xfeat.py
+++ b/kornia/feature/xfeat.py
@@ -679,24 +679,41 @@ class XFeat(nn.Module):
img2: torch.Tensor,
top_k: Optional[int] = None,
min_cossim: float = -1,
- ) -> Tuple[torch.Tensor, torch.Tensor]:
- """Detect, describe and mutually match keypoints from two images.
+ ) -> List[torch.Tensor] | Tuple[torch.Tensor, torch.Tensor]:
+ """Detect, describe and mutually match keypoints from two batches of images.
+
+ Pair ``b`` is image ``b`` of ``img1`` with image ``b`` of ``img2``. Each batch goes through
+ :meth:`detectAndCompute` in one call, and then the descriptors of each pair are matched on their own by
+ mutual nearest neighbour. A backend may round a batched convolution differently from a single-image one (MPS,
+ and CUDA with cuDNN's default TF32 convolutions), so a pair matched in a batch can gain or lose a few
+ near-tied matches compared with matching it alone.
Args:
- img1: first image tensor of shape ``(1, C, H, W)``.
- img2: second image tensor of shape ``(1, C, H, W)``.
+ img1: first images ``(B, C, H, W)``.
+ img2: second images ``(B, C, H, W)``, with the same ``B`` as ``img1``.
top_k: number of top keypoints to use.
min_cossim: minimum cosine similarity threshold. Use ``-1`` to disable.
Returns:
- Tuple ``(mkpts0, mkpts1)`` of matched keypoints, each ``(N, 2)``.
+ If ``B != 1``: list of ``(N, 4)`` tensors with ``(x1, y1, x2, y2)`` matches, one per pair; an empty
+ batch gives an empty list.
+ If ``B == 1``: tuple ``(mkpts0, mkpts1)`` of matched keypoints, each ``(N, 2)``.
+
+ See Also:
+ :meth:`match_xfeat_star`: the dense, refined variant, with the same return convention.
"""
+ KORNIA_CHECK(img1.shape[0] == img2.shape[0], "img1 and img2 must hold the same number of images")
if top_k is None:
top_k = self.top_k
- out1 = self.detectAndCompute(img1, top_k=top_k)[0]
- out2 = self.detectAndCompute(img2, top_k=top_k)[0]
- idx0, idx1 = self._match_mnn(out1["descriptors"], out2["descriptors"], min_cossim=min_cossim)
- return out1["keypoints"][idx0], out2["keypoints"][idx1]
+ out1 = self.detectAndCompute(img1, top_k=top_k)
+ out2 = self.detectAndCompute(img2, top_k=top_k)
+ pairs = []
+ for f1, f2 in zip(out1, out2):
+ idx0, idx1 = self._match_mnn(f1["descriptors"], f2["descriptors"], min_cossim=min_cossim)
+ pairs.append((f1["keypoints"][idx0], f2["keypoints"][idx1]))
+ if len(pairs) != 1:
+ return [torch.cat(pair, dim=-1) for pair in pairs]
+ return pairs[0]
@torch.inference_mode()
def match_xfeat_star(
diff --git a/tests/feature/test_xfeat.py b/tests/feature/test_xfeat.py
index 2421f196e..bae54a54b 100644
--- a/tests/feature/test_xfeat.py
+++ b/tests/feature/test_xfeat.py
@@ -21,6 +21,7 @@ import pytest
import torch
from torch.overrides import TorchFunctionMode
+from kornia.core.exceptions import BaseError
from kornia.feature.lightglue import LightGlue
from kornia.feature.xfeat import InterpolateSparse2d, XFeat, XFeatModel
@@ -259,6 +260,35 @@ class TestXFeat(BaseTester):
assert mkpts0.shape == mkpts1.shape
assert mkpts0.shape[-1] == 2
+ def test_match_xfeat_batch_matches_each_pair(self, device, dtype):
+ torch.manual_seed(0)
+ model = XFeat(top_k=256, detection_threshold=0.0).to(device).eval() # random weights score below 0.05
+ img1 = torch.rand(3, 3, 64, 96, device=device)
+ img2 = torch.rand(3, 3, 64, 96, device=device)
+ batched = model.match_xfeat(img1, img2)
+ assert isinstance(batched, list)
+ assert len(batched) == 3
+ # Pair b matches image b of each batch, and no other: the features of one batched extraction, matched per
+ # pair. A batch need not equal single-image calls bit for bit: a backend may round a batched convolution
+ # differently, which can reorder near-tied keypoints (MPS does with these random weights).
+ out1, out2 = model.detectAndCompute(img1), model.detectAndCompute(img2)
+ for b in range(3):
+ # match_xfeat's default min_cossim, not _match_mnn's
+ idx0, idx1 = model._match_mnn(out1[b]["descriptors"], out2[b]["descriptors"], min_cossim=-1)
+ assert idx0.shape[0] > 0
+ expected = torch.cat([out1[b]["keypoints"][idx0], out2[b]["keypoints"][idx1]], dim=-1)
+ self.assert_close(batched[b], expected, rtol=0, atol=0)
+
+ def test_match_xfeat_empty_batch(self, device, dtype):
+ model = XFeat().to(device).eval()
+ img = torch.rand(0, 3, 64, 64, device=device)
+ assert model.match_xfeat(img, img) == []
+
+ def test_match_xfeat_batch_size_mismatch(self, device, dtype):
+ model = XFeat().to(device).eval()
+ with pytest.raises(BaseError, match="same number of images"):
+ model.match_xfeat(torch.rand(2, 3, 64, 64, device=device), torch.rand(1, 3, 64, 64, device=device))
+
@pytest.mark.slow
def test_pretrained_smoke(self, device):
model = XFeat.from_pretrained().to(device)