Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(feature): match LoFTR on precomputed per-image features (#5880)

Dmytro Mishkindef0caf0e07d
diff --git a/changelog.d/5880.added.md b/changelog.d/5880.added.md
new file mode 100644
index 000000000..75f8ed4c3
--- /dev/null
+++ b/changelog.d/5880.added.md
@@ -0,0 +1,6 @@
+`LoFTR.extract_features(image)` returns the features of an image that do not depend on the image it is matched with
+(the backbone's coarse and fine maps, the coarse one position-encoded), and `LoFTR.forward` accepts them as
+`features0` / `features1` instead of `image0` / `image1`, on either side or both. Matching one image against many no
+longer runs the backbone for every pair. For images of different sizes the matches are bitwise the same as when
+passing the images; `forward` still runs two images of the same size through the backbone together.
+All image and feature input combinations reject unequal batch sizes with `ValueError`.
diff --git a/docs/source/feature.matching.rst b/docs/source/feature.matching.rst
index 7e37b9f5a..8347a2b71 100644
--- a/docs/source/feature.matching.rst
+++ b/docs/source/feature.matching.rst
@@ -36,4 +36,4 @@ Learned matchers
:members: forward
.. autoclass:: LoFTR
- :members: forward
+ :members: forward, extract_features
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index 12b6ea339..f678f9737 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -110,6 +110,9 @@ class LoFTR(nn.Module):
Returns:
Dictionary with image correspondences and confidence scores.
+ The backbone features of an image do not depend on the image it is matched with. To match one image against
+ many, compute them once with :meth:`extract_features` and pass them as ``features0`` / ``features1``.
+
Example:
>>> img1 = torch.rand(1, 1, 320, 200)
>>> img2 = torch.rand(1, 1, 128, 128)
@@ -146,7 +149,56 @@ class LoFTR(nn.Module):
self.load_state_dict(pretrained_dict["state_dict"])
self.eval()
- def forward(self, data: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
+ def extract_features(self, image: torch.Tensor) -> dict[str, torch.Tensor]:
+ r"""Compute the features of images that do not depend on the image they are matched with.
+
+ These are the backbone's coarse and fine feature maps, the coarse one with its positional encoding. Pass the
+ returned dict to :meth:`forward` as ``features0`` or ``features1`` instead of ``image0`` or ``image1`` to
+ match an image against many others without running the backbone again for every pair.
+
+ Args:
+ image: grayscale images with shape :math:`(N, 1, H, W)`.
+
+ Returns:
+ - ``coarse``, position-encoded 1/8-resolution features
+ :math:`(N, C_c, \lceil H/8 \rceil, \lceil W/8 \rceil)`.
+ - ``fine``, 1/2-resolution features :math:`(N, C_f, \lceil H/2 \rceil, \lceil W/2 \rceil)`. With the
+ default config this is 128 channels, about 96 MB in float32 for a 1024 x 736 image.
+
+ Example:
+ >>> loftr = LoFTR(None)
+ >>> images = [torch.rand(1, 1, 64, 80), torch.rand(1, 1, 72, 64), torch.rand(1, 1, 64, 64)]
+ >>> features = [loftr.extract_features(image) for image in images]
+ >>> out = loftr({"features0": features[0], "features1": features[1]})
+ >>> out = loftr({"features0": features[0], "image1": images[2]})
+
+ """
+ feat_c, feat_f = self.backbone(image)
+ return {"coarse": self.pos_encoding(feat_c), "fine": feat_f}
+
+ def _pair_features(self, data: dict[str, Any]) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
+ """Features of both sides of the pair: given, or extracted from the images."""
+ for side in (0, 1):
+ if (f"image{side}" in data) == (f"features{side}" in data):
+ raise ValueError(f"Pass exactly one of `image{side}` and `features{side}`.")
+ if "image0" in data and "image1" in data and data["image0"].shape[2:] == data["image1"].shape[2:]:
+ # one backbone pass for both images: faster & better BN convergence
+ n = data["image0"].size(0)
+ both = self.extract_features(torch.cat([data["image0"], data["image1"]], dim=0))
+ features = [{k: v[:n] for k, v in both.items()}, {k: v[n:] for k, v in both.items()}]
+ else:
+ features = []
+ for side in (0, 1):
+ given = data.get(f"features{side}")
+ features.append(given if given is not None else self.extract_features(data[f"image{side}"]))
+ if features[0]["coarse"].size(0) != features[1]["coarse"].size(0):
+ raise ValueError(
+ f"Both sides need the same batch size. Got {features[0]['coarse'].size(0)} and "
+ f"{features[1]['coarse'].size(0)}."
+ )
+ return features[0], features[1]
+
+ def forward(self, data: dict[str, Any]) -> dict[str, torch.Tensor]:
"""Run forward.
Args:
@@ -155,6 +207,8 @@ class LoFTR(nn.Module):
Keyword Args:
image0: left image with shape :math:`(N, 1, H1, W1)`.
image1: right image with shape :math:`(N, 1, H2, W2)`.
+ features0 (optional): instead of ``image0``, its :meth:`extract_features` output.
+ features1 (optional): instead of ``image1``, its :meth:`extract_features` output.
mask0 (optional): left image mask. '0' indicates a padded position :math:`(N, H1, W1)`.
mask1 (optional): right image mask. '0' indicates a padded position :math:`(N, H2, W2)`.
@@ -171,21 +225,16 @@ class LoFTR(nn.Module):
# stride.
stride_c, stride_f = self.config["resolution"]
- # 1. Local Feature CNN
+ # 1. Local Feature CNN (and the positional encoding), unless the caller passes them
+ features0, features1 = self._pair_features(data)
+ feat_c0, feat_f0 = features0["coarse"], features0["fine"]
+ feat_c1, feat_f1 = features1["coarse"], features1["fine"]
_data: dict[str, torch.Tensor | int | torch.Size] = {
- "bs": data["image0"].size(0),
- "hw0_i": data["image0"].shape[2:],
- "hw1_i": data["image1"].shape[2:],
+ "bs": feat_c0.size(0),
"stride_c": stride_c,
"stride_f": stride_f,
}
- if _data["hw0_i"] == _data["hw1_i"]: # faster & better BN convergence
- feats_c, feats_f = self.backbone(torch.cat([data["image0"], data["image1"]], dim=0))
- (feat_c0, feat_c1), (feat_f0, feat_f1) = feats_c.split(_data["bs"]), feats_f.split(_data["bs"])
- else: # handle different input shapes
- (feat_c0, feat_f0), (feat_c1, feat_f1) = self.backbone(data["image0"]), self.backbone(data["image1"])
-
_data.update(
{
"hw0_c": feat_c0.shape[2:],
@@ -196,17 +245,17 @@ class LoFTR(nn.Module):
)
# 2. coarse-level loftr module
- # add featmap with positional encoding, then flatten it to sequence [N, HW, C]
+ # flatten the position-encoded featmap to sequence [N, HW, C]
- # feat_c0 = rearrange(self.pos_encoding(feat_c0), 'n c h w -> n (h w) c')
- # feat_c1 = rearrange(self.pos_encoding(feat_c1), 'n c h w -> n (h w) c')
+ # feat_c0 = rearrange(feat_c0, 'n c h w -> n (h w) c')
+ # feat_c1 = rearrange(feat_c1, 'n c h w -> n (h w) c')
# Token-major copies: the reshape of the permuted maps is a channel-strided view, and every transformer GEMM
# on it would run on the transposed layout.
- feat_c0 = self.pos_encoding(feat_c0).permute(0, 2, 3, 1)
+ feat_c0 = feat_c0.permute(0, 2, 3, 1)
n, _h, _w, c = feat_c0.shape
feat_c0 = feat_c0.reshape(n, -1, c).contiguous()
- feat_c1 = self.pos_encoding(feat_c1).permute(0, 2, 3, 1)
+ feat_c1 = feat_c1.permute(0, 2, 3, 1)
n1, _h1, _w1, c1 = feat_c1.shape
feat_c1 = feat_c1.reshape(n1, -1, c1).contiguous()
diff --git a/tests/feature/test_loftr.py b/tests/feature/test_loftr.py
index 5e305df4e..e24e29f58 100644
--- a/tests/feature/test_loftr.py
+++ b/tests/feature/test_loftr.py
@@ -196,6 +196,73 @@ class TestLoFTR(BaseTester):
assert kpts0[:, 1].max() <= 56
assert kpts0[:, 1].max() >= 8 * 4
+ @pytest.mark.parametrize("masked", [False, True])
+ def test_precomputed_features_give_the_same_matches(self, device, dtype, masked):
+ # Images of different sizes run through the backbone one by one either way, so matching precomputed
+ # features gives bitwise the same output, on either side and on both.
+ model = _loftr_matching_every_cell(device, dtype)
+ gen = torch.Generator().manual_seed(3)
+ image0 = torch.rand(1, 1, 100, 67, generator=gen).to(device, dtype)
+ image1 = torch.rand(1, 1, 93, 86, generator=gen).to(device, dtype)
+ masks = {}
+ if masked:
+ masks = {
+ "mask0": torch.ones(1, 100, 67, device=device, dtype=dtype),
+ "mask1": torch.ones(1, 93, 86, device=device, dtype=dtype),
+ }
+ masks["mask0"][:, 72:], masks["mask1"][:, :, 64:] = 0, 0
+ with torch.no_grad():
+ expected = model({"image0": image0, "image1": image1, **masks})
+ features0, features1 = model.extract_features(image0), model.extract_features(image1)
+ outputs = [
+ model({"features0": features0, "features1": features1, **masks}),
+ model({"features0": features0, "image1": image1, **masks}),
+ model({"image0": image0, "features1": features1, **masks}),
+ ]
+ assert expected["keypoints0"].shape[0] >= 5 # the masks leave 10
+ for out in outputs:
+ assert out.keys() == expected.keys()
+ for key, value in expected.items():
+ self.assert_close(out[key], value, rtol=0.0, atol=0.0)
+
+ def test_extract_features_shapes_and_batching(self, device, dtype):
+ model = _loftr_matching_every_cell(device, dtype)
+ images = torch.rand(2, 1, 100, 67).to(device, dtype)
+ # cuDNN's default TF32 convolutions round differently for each batch size (up to ~1e-3), so compare in fp32
+ with torch.no_grad(), torch.backends.cudnn.flags(enabled=torch.backends.cudnn.enabled, allow_tf32=False):
+ batched = model.extract_features(images)
+ single = model.extract_features(images[1:])
+ assert batched["coarse"].shape == (2, 256, 13, 9)
+ assert batched["fine"].shape == (2, 128, 50, 34)
+ # a batch of images gives each image's features (up to the backend's choice of kernel for the batch size)
+ self.assert_close(batched["coarse"][1:], single["coarse"])
+ self.assert_close(batched["fine"][1:], single["fine"])
+
+ def test_inputs_are_validated(self, device, dtype):
+ model = _loftr_matching_every_cell(device, dtype)
+ image = torch.rand(1, 1, 64, 64).to(device, dtype)
+ with torch.no_grad():
+ features = model.extract_features(image)
+ with pytest.raises(ValueError, match="exactly one of `image0` and `features0`"):
+ model({"image0": image, "features0": features, "image1": image})
+ with pytest.raises(ValueError, match="exactly one of `image1` and `features1`"):
+ model({"image0": image})
+
+ @pytest.mark.parametrize("batch_sizes", [(1, 2), (2, 1)])
+ @pytest.mark.parametrize(
+ "input_keys",
+ [("image0", "image1"), ("features0", "features1"), ("image0", "features1"), ("features0", "image1")],
+ )
+ def test_mismatched_batch_sizes(self, device, dtype, batch_sizes, input_keys):
+ model = _loftr_matching_every_cell(device, dtype)
+ with torch.no_grad():
+ data = {}
+ for key, batch_size in zip(input_keys, batch_sizes):
+ image = torch.rand(batch_size, 1, 64, 64, device=device, dtype=dtype)
+ data[key] = model.extract_features(image) if key.startswith("features") else image
+ with pytest.raises(ValueError, match="same batch size"):
+ model(data)
+
@pytest.mark.slow
def test_gradcheck(self, device):
patches = torch.rand(1, 1, 32, 32, device=device, dtype=torch.float64)