Algorithm Search⌘K

Algorithmresearch

LoFTR

Also called detector-free local feature matching.

Match two images without a detector, by transformer attention over coarse feature maps followed by a refinement of each match at a fine level.

Time
O(M N d + K w^2 d) worst · average · best
Space
O(M N + w^2) extra
Where
K = the number of coarse matches; M = the number of coarse cells of image A; N = the number of coarse cells of image B; d = the feature length; w = the window size
Properties
detector freedeterministiclearnednetwork cost excludedsubpixelsymmetric coarse matches
Origin
Jiaming Sun, Zehong Shen, Yuang Wang, Hujun Bao, Xiaowei Zhou, 2021

LoFTR matches two images without a keypoint detector. A convolutional network computes a coarse feature map at 1/8 of the image size and a fine map at 1/2. Transformer layers with self-attention and cross-attention then mix the coarse features of both images. Each coarse cell of one image is compared with each cell of the other, a softmax over rows and a softmax over columns turn the scores into a confidence matrix, and the mutual best pairs above a threshold are the coarse matches. Each coarse match is then refined to a subpixel position inside a small window of the fine map. This page covers the matching steps, the dual-softmax with the mutual check and the window refinement, with their proof and code; the networks and their training are outside the page, and the quality of the features is a measured result.

In plain words

Instead of first picking special points, LoFTR cuts each image into small squares of 8 by 8 pixels and gives each square a vector. Before the vectors are compared, a network lets every square look at the other squares of its own image and of the other image, so a square on a plain wall can still learn where it is. Then every square of one image is scored against every square of the other. A square pair is a match when each is the other's favorite and the confidence is high. Last, each match is made more exact: we look at a small patch of a finer map around the matched square and take the weighted center of where the point fits best.

The problem

The input is the output of the networks:

  • the coarse features f1A,…,fMAf^A_1, \dots, f^A_M and f1B,…,fNBf^B_1, \dots, f^B_N in Rd\mathbb{R}^d, one per cell of the 1/81/8 grids of images A and B, after the transformer layers;
  • the fine feature maps of the two images at 1/21/2 resolution, after the fine transformer layers;
  • a temperature τ\tau, a threshold θ\theta, a window size ww and a scale ss for the fine correlation.

The output is a list of matches (xA,xB)(x^A, x^B), where xAx^A is the image position of a coarse cell of A and xBx^B is a subpixel position in B, each with a confidence. Each coarse cell is in at most one match.

The algorithm

  1. LOFTR-MATCH(f^A, f^B, τ, θ, fine maps, w, s)
  2. 1S_ij ← ⟨f^A_i, f^B_j⟩ / τ for all cells i of A and j of B
  3. 2R ← softmax of each row of S; C ← softmax of each column of S
  4. 3P_ij ← R_ij · C_ij
  5. 4M_c ← the pairs (i, j) where j is the best column of row i, i is the best row of column j, and P_ij ≥ θ
  6. 5for each (i, j) in M_c do
  7. 6c ← the fine vector of A at cell i; W ← the w × w fine window of B centered at cell j
  8. 7q_k ← softmax over the window positions k of s · ⟨c, W_k⟩
  9. 8output (position of i, Σ_k q_k · position of k, P_ij)

Lines L1 to L3 are the dual-softmax of Section 3.3 of the paper. PijP_{ij} is large only when jj is a likely partner of ii among all cells of B and ii is a likely partner of jj among all cells of A, so it is a soft form of mutual nearest neighbor matching. Line L4 is the match selection of the paper: a threshold θ\theta and the mutual nearest neighbor criterion on PP. Ties go to the smaller index. Lines L6 to L8 are the coarse-to-fine module of Section 3.4: the center vector of the window of A is correlated with all vectors of the window of B, a softmax gives a heat map, and the expectation over it is the subpixel position.

The networks before these steps, from Section 3 of the paper: a ResNet-18 backbone with a feature pyramid gives the coarse and the fine maps. The coarse maps are flattened, a 2D positional encoding is added, and NcN_c layers alternate self-attention and cross-attention. The attention is linear attention, with the kernel φ(x)=elu(x)+1\varphi(x) = \mathrm{elu}(x) + 1, so its cost is linear in the number of cells instead of quadratic. A smaller module with NfN_f layers transforms the cropped fine windows. Training uses the negative log-likelihood of PP at the ground-truth coarse matches and an ℓ2\ell_2 loss on the refined positions weighted by the inverse variance of the heat map. Instead of the dual-softmax, the paper also allows the optimal transport layer of SuperGlue with −S-S as the cost.

Example

Coarse matching. Let A have two cells with f0A=(1,0)f^A_0 = (1, 0) and f1A=(0,1)f^A_1 = (0, 1), and B three cells with f0B=(1,0)f^B_0 = (1, 0), f1B=(0.6,0.8)f^B_1 = (0.6, 0.8) and f2B=(0,1)f^B_2 = (0, 1). With τ=0.5\tau = 0.5, line L1 gives

S=(21.2001.62).S = \begin{pmatrix} 2 & 1.2 & 0 \\ 0 & 1.6 & 2 \end{pmatrix}.

The row softmax is R=(0.6310.28350.08540.0750.37120.5538)R = \begin{pmatrix} 0.631 & 0.2835 & 0.0854 \\ 0.075 & 0.3712 & 0.5538 \end{pmatrix}, and the column softmax gives (0.8808,0.1192)(0.8808, 0.1192), (0.4013,0.5987)(0.4013, 0.5987) and (0.1192,0.8808)(0.1192, 0.8808) for the three columns. Their product is

P=(0.55580.11380.01020.00890.22230.4878).P = \begin{pmatrix} 0.5558 & 0.1138 & 0.0102 \\ 0.0089 & 0.2223 & 0.4878 \end{pmatrix}.

With θ=0.2\theta = 0.2, line L4 keeps (0,0)(0, 0) with 0.5558 and (1,2)(1, 2) with 0.4878. The pair (1,1)(1, 1) has P11=0.2223P_{11} = 0.2223, above the threshold, but row 1 prefers column 2, so the mutual check removes it. Cell 1 of B, which lies between the two directions, gets no match.

Refinement. Take a 3×33 \times 3 window with scale s=1s = 1, where the score s⟨c,Wk⟩s \langle c, W_k \rangle is 1 at the center, 2 one fine pixel to the right, and 0 at the other seven positions. The softmax gives 0.4319 to the right position, 0.1589 to the center and 0.0585 to each of the others. The expected horizontal offset is 0.4319+2×0.0585−3×0.0585=0.37350.4319 + 2 \times 0.0585 - 3 \times 0.0585 = 0.3735 fine pixels, and the vertical offset is 0 by symmetry. At stride 2 this moves the match 0.747 image pixels to the right of the cell of B.

Correctness

The matching steps have a proof; the networks do not. The proof in proofs/correctness.md shows:

  • Bounds. Each PijP_{ij} is in (0,1](0, 1], at most both of its softmax factors, and each row and column of PP sums to at most 1.
  • One half. If Pij>1/2P_{ij} > 1/2, it is the unique largest value of its row and of its column. So with θ>1/2\theta > 1/2 the mutual check removes nothing.
  • Invariance and symmetry. A constant added to all scores does not change PP, and swapping the images transposes PP and gives the same coarse matches.
  • A matching. Each coarse cell is in at most one coarse match.
  • Refinement. The refined position is a convex combination of the window positions. If one position leads the others by Δ\Delta in score, the result is within (w2−1)e−Δ(w−1)2(w^2 - 1) e^{-\Delta} (w - 1)\sqrt{2} fine pixels of it.

What this does not show is that the features are good. The paper measures it (2021): the AUC of the corner error for homography estimation on HPatches, the AUC of the pose error on ScanNet for indoor pairs and on MegaDepth for outdoor pairs, and visual localization on InLoc and Aachen Day-Night. In these tests it did better than detector-based methods such as SuperPoint with SuperGlue, and it found matches in regions with little texture, where a detector finds few points. These are benchmark results with the protocol of the paper.

Proof: Correctness of the LoFTR matching stepsfull

This proof covers the matching steps only: lines L1 to L8 of the main page, on given coarse features f1A,…,fmAf^A_1, \dots, f^A_m and f1B,…,fnBf^B_1, \dots, f^B_n in Rd\mathbb{R}^d, with m,n≥1m, n \ge 1, given fine feature maps, a temperature τ>0\tau > 0, a threshold θ\theta, a window size ww and a scale s>0s > 0. Nothing here says that the networks give good features; that is a measured property.

Line L1 sets Sij=⟨fiA,fjB⟩/τS_{ij} = \langle f^A_i, f^B_j \rangle / \tau. Line L2 sets Rij=eSij/∑keSikR_{ij} = e^{S_{ij}} / \sum_k e^{S_{ik}} and Cij=eSij/∑keSkjC_{ij} = e^{S_{ij}} / \sum_k e^{S_{kj}}, and line L3 sets Pij=RijCijP_{ij} = R_{ij} C_{ij}.

Lemma 1 (bounds). Each PijP_{ij} is in (0,1](0, 1], with Pij≤RijP_{ij} \le R_{ij} and Pij≤CijP_{ij} \le C_{ij}. Each row sum and each column sum of PP is at most 1.

Proof. RijR_{ij} and CijC_{ij} are in (0,1](0, 1], so their product is positive and at most each factor. A row of RR sums to 1, so a row of PP sums to ∑jRijCij≤∑jRij=1\sum_j R_{ij} C_{ij} \le \sum_j R_{ij} = 1. Columns are the same with CC. □\square

Lemma 2 (a value above one half is a mutual best). If Pij>1/2P_{ij} > 1/2, then PijP_{ij} is the unique largest value in row ii and in column jj. So with θ>1/2\theta > 1/2 the mutual check of line L4 removes nothing: the matches are exactly the pairs with Pij≥θP_{ij} \ge \theta.

Proof. By Lemma 1, the other entries of row ii sum to at most 1−Pij<1/2<Pij1 - P_{ij} < 1/2 < P_{ij}, so each is smaller than PijP_{ij}. Column jj is the same. □\square

Lemma 3 (invariance and symmetry). Adding a constant tt to every SijS_{ij} does not change PP. Swapping the two images transposes PP, and the set of pairs of line L4 is the same up to the swap.

Proof. The factor ete^t cancels in each softmax. Swapping the images replaces SS by STS^T, which swaps the row and the column softmax, so PP becomes PTP^T. Line L4 keeps (i,j)(i, j) when jj is the first largest entry of row ii and ii is the first largest entry of column jj; for PTP^T the two conditions swap roles, so the same pairs are kept. □\square

Lemma 4 (the output of line L4 is a matching). Each ii and each jj is in at most one pair, and each pair has Pij≥θP_{ij} \ge \theta.

Proof. Each row has one first best column and each column one first best row. A pair (i,j)(i, j) needs both, so two pairs with the same ii would have the same jj, and two pairs with the same jj would have the same ii. □\square

Now the refinement. Let cc be the fine vector of A, let KK be the set of window positions inside the fine map of B, with positions xk∈R2x_k \in \mathbb{R}^2 and vectors gkg_k, and let qk=es⟨c,gk⟩/∑l∈Kes⟨c,gl⟩q_k = e^{s \langle c, g_k \rangle} / \sum_{l \in K} e^{s \langle c, g_l \rangle} be the weights of line L7. Line L8 returns x^=∑kqkxk\hat x = \sum_k q_k x_k.

Lemma 5 (the refined position). x^\hat x is in the convex hull of the positions of KK, so it is inside the window and inside the fine map. If one position k∗k^* has a score larger than every other by at least Δ\Delta, that is s⟨c,gk∗⟩≥s⟨c,gk⟩+Δs \langle c, g_{k^*} \rangle \ge s \langle c, g_k \rangle + \Delta for all k≠k∗k \ne k^*, then

∥x^−xk∗∥≤(∣K∣−1) e−Δmax⁡k∥xk−xk∗∥.\lVert \hat x - x_{k^*} \rVert \le (|K| - 1) \, e^{-\Delta} \max_k \lVert x_k - x_{k^*} \rVert.

Proof. The weights are positive and sum to 1, so x^\hat x is a convex combination of the xkx_k. For the bound, x^−xk∗=∑k≠k∗qk(xk−xk∗)\hat x - x_{k^*} = \sum_{k \ne k^*} q_k (x_k - x_{k^*}), and qk≤e−Δqk∗≤e−Δq_k \le e^{-\Delta} q_{k^*} \le e^{-\Delta} for k≠k∗k \ne k^*. The triangle inequality gives the bound. □\square

For a w×ww \times w window, ∣K∣≤w2|K| \le w^2 and max⁡k∥xk−xk∗∥≤(w−1)2\max_k \lVert x_k - x_{k^*} \rVert \le (w - 1)\sqrt{2}, so the refined position tends to the best window position as the gap Δ\Delta grows.

Theorem. The coarse matches are a partial matching of the coarse cells with confidence at least θ\theta, they do not depend on a constant shift of the scores, and they are symmetric in the two images. For θ>1/2\theta > 1/2 they are exactly the pairs with Pij≥θP_{ij} \ge \theta. Each refined position is a convex combination of the window positions, and it is within (w2−1)e−Δ(w−1)2(w^2 - 1) e^{-\Delta} (w - 1) \sqrt{2} fine pixels of the best window position when that position leads the others by Δ\Delta in score.

Proof. Lemmas 1 to 5. ■\blacksquare

Complexity

The model is the real RAM, and the cost of the networks is outside the page. Line L1 computes MNM N dot products of length dd, O(MNd)O(M N d). Lines L2 to L4 take O(MN)O(M N). For each of the KK coarse matches, lines L6 to L8 compute w2w^2 dot products, O(w2d)O(w^2 d). The total is O(MNd+Kw2d)O(M N d + K w^2 d) time and O(MN+w2)O(M N + w^2) space for the score matrix and one window.

The score matrix is the main cost of the matching steps: for two 640×480640 \times 480 images the coarse grids have 80×60=480080 \times 60 = 4800 cells each, so SS has about 23 million entries. The paper reports 116 ms for the full model with dual-softmax on a 640×480640 \times 480 pair on an RTX 2080Ti GPU, and 130 ms with the optimal transport layer and three Sinkhorn iterations; these are measurements of 2021 and include the networks.

Properties

  • No detector. Every coarse cell is a candidate, so matches can appear on low-texture surfaces where a detector finds no repeatable points.
  • One match per coarse cell. The mutual check makes the coarse matches a partial matching of cells. The density of matches is at most one per 8×88 \times 8 block.
  • Subpixel in B, cell-centered in A. The position in A is the center of the coarse cell at fine resolution; only the position in B is refined.
  • Symmetric at the coarse level. The coarse matches do not depend on which image is called A. The refinement is not symmetric.
  • Learned. The features depend on the training data. The paper trains separate models for indoor and outdoor scenes.

Variants and improvements

  • Optimal transport instead of dual-softmax. The paper allows the Sinkhorn layer of SuperGlue with a dustbin, at a small extra cost.
  • Later dense matchers. Methods such as QuadTree attention, ASpanFormer and the efficient LoFTR variants keep the coarse-to-fine design and change the attention or the refinement.
  • Detector-based matching. SuperPoint with SuperGlue, or SIFT with the ratio test, matches only detected points.
  • Dense flow. Optical flow methods give a vector for every pixel, but they usually assume small motion between the frames; LoFTR targets wide-baseline pairs.

When to use it

Use LoFTR for wide-baseline image pairs with little texture, such as indoor walls and floors, when a GPU is available and you need a relative pose or a homography after RANSAC. Use a detector and descriptor, such as SIFT or SuperPoint, when you need matches across many images, because a detector gives the same points in every image, while LoFTR finds new cells for each pair, which makes tracks across many views harder to build.

Pitfalls

  • Memory. The score matrix has MNM N entries. Large images need downsampling or a cap on the number of cells.
  • Threshold and temperature. θ=0.2\theta = 0.2 in the paper and the temperature τ\tau are tuned values. The text of the paper does not give a number for τ\tau; take it from the trained model you use.
  • Grid alignment. The image position of a coarse cell and the window position in the fine map depend on the strides and on a convention for the cell center. The coarse and the fine maps must use the same one.
  • Border windows. A window near the image border is partly outside the map. Leave those positions out of the softmax, or pad, but do it the same way as in training.
  • Not a keypoint set. Matches of one image pair do not chain into tracks over many images as detected points do.
  • Low resolution. A coarse match is at most one per 8×88 \times 8 cell, so two nearby true matches inside one cell give one result.

Implementations

The networks are outside this page. The Python code in impl/python/loftr.py implements only the matching steps of lines L1 to L8 on given coarse features and fine maps: the score matrix, the dual-softmax, the mutual check with a threshold, and the window refinement by a softmax and an expectation. The coarse cell ii of a grid of width WcW_c is placed at pixel (8(i mod Wc),8⌊i/Wc⌋)(8 (i \bmod W_c), 8 \lfloor i / W_c \rfloor), and window positions outside the fine map are left out; both are conventions of this code. The tests check the dual-softmax against its formula, the mutual check against a brute-force definition with ties, the one-half lemma, shift invariance and symmetry, that the refined position stays in the window and near a clear peak, and that a shuffled grid of features is matched back to the right cells.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

loftr.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/loftr/. The authors are listed in prov/JB95QG.jsonl.

"""The matching steps of LoFTR (Sun, Shen, Wang, Bao and Zhou 2021).

The networks are not part of this file: the convolutional backbone and the
transformer layers. Their outputs are given:

- FA and FB, the coarse features of the two images after the transformer,
  as flat lists of vectors in row-major order over grids of width WcA and WcB.
  The coarse grid has stride 8, and coarse cell i of a grid of width Wc is at
  pixel (8 (i % Wc), 8 (i // Wc)). This placement is a convention of this file.
- GA and GB, the fine feature maps at stride 2, as grids of rows of vectors.
  Coarse cell (x, y) is at fine position (4 x, 4 y).

Coarse matching: S = <FA_i, FB_j> / tau, P = (row softmax of S) times
(column softmax of S), elementwise, and the coarse matches are the mutual
best pairs of P with P at least theta.

Fine refinement: for a coarse match (i, j), take the fine vector of A at the
position of i and a w x w window of B around the position of j. A softmax
of the scaled dot products over the window gives weights, and the expected
offset moves the position of j. Window positions outside the map are left out.
"""

import math
from typing import List, Sequence, Tuple

Vec = Sequence[float]
COARSE = 8
FINE = 2


def dot(a: Vec, b: Vec) -> float:
    return sum(x * y for x, y in zip(a, b))


def softmax(z: Sequence[float]) -> List[float]:
    m = max(z)
    e = [math.exp(x - m) for x in z]
    s = sum(e)
    return [x / s for x in e]


def dual_softmax(FA: Sequence[Vec], FB: Sequence[Vec], tau: float) -> List[List[float]]:
    """Return P with P_ij = softmax_j(S_i.)_j * softmax_i(S_.j)_i and S = <FA_i, FB_j> / tau."""
    S = [[dot(a, b) / tau for b in FB] for a in FA]  # @line L1
    R = [softmax(row) for row in S]  # @line L2
    cols = [softmax([S[i][j] for i in range(len(FA))]) for j in range(len(FB))]
    return [[R[i][j] * cols[j][i] for j in range(len(FB))] for i in range(len(FA))]  # @line L3


def coarse_matches(P: Sequence[Sequence[float]], theta: float) -> List[Tuple[int, int, float]]:
    """Mutual best pairs of P with P_ij >= theta. Ties go to the smaller index."""
    m, n = len(P), len(P[0])
    row_best = [max(range(n), key=lambda j: (P[i][j], -j)) for i in range(m)]  # @line L4
    col_best = [max(range(m), key=lambda i: (P[i][j], -i)) for j in range(n)]
    return [(i, j, P[i][j]) for i, j in enumerate(row_best)
            if col_best[j] == i and P[i][j] >= theta]


def refine(center: Vec, G: Sequence[Sequence[Vec]], fx: int, fy: int, w: int,
           scale: float) -> Tuple[float, float]:
    """Expected position, in fine pixels, of center inside the w x w window of G at (fx, fy)."""
    h, wd = len(G), len(G[0])
    half = w // 2
    pos, score = [], []
    for dy in range(-half, half + 1):  # @line L6
        for dx in range(-half, half + 1):
            x, y = fx + dx, fy + dy
            if 0 <= x < wd and 0 <= y < h:
                pos.append((x, y))
                score.append(dot(center, G[y][x]) * scale)
    q = softmax(score)  # @line L7
    return (sum(p * x for p, (x, _) in zip(q, pos)),  # @line L8
            sum(p * y for p, (_, y) in zip(q, pos)))


def loftr_match(FA: Sequence[Vec], FB: Sequence[Vec], wca: int, wcb: int,
                GA: Sequence[Sequence[Vec]], GB: Sequence[Sequence[Vec]],
                tau: float = 0.1, theta: float = 0.2, w: int = 5,
                scale: float = 1.0) -> List[Tuple[Tuple[float, float], Tuple[float, float], float]]:
    """Return matches as (pixel in A, refined pixel in B, coarse confidence)."""
    P = dual_softmax(FA, FB, tau)
    out = []
    for i, j, p in coarse_matches(P, theta):  # @line L5
        ax, ay = i % wca, i // wca
        bx, by = j % wcb, j // wcb
        center = GA[4 * ay][4 * ax]
        x, y = refine(center, GB, 4 * bx, 4 * by, w, scale)
        out.append(((COARSE * ax, COARSE * ay), (FINE * x, FINE * y), p))
    return out
test_loftr.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/loftr/. The authors are listed in prov/JB95QG.jsonl.

import math
import random

from loftr import coarse_matches, dual_softmax, loftr_match, refine


def rand_vecs(rng, n, d):
    return [[rng.gauss(0.0, 1.0) for _ in range(d)] for _ in range(n)]


def brute_dual_softmax(FA, FB, tau):
    S = [[sum(x * y for x, y in zip(a, b)) / tau for b in FB] for a in FA]
    m, n = len(FA), len(FB)
    P = []
    for i in range(m):
        row = []
        for j in range(n):
            r = math.exp(S[i][j]) / sum(math.exp(S[i][k]) for k in range(n))
            c = math.exp(S[i][j]) / sum(math.exp(S[k][j]) for k in range(m))
            row.append(r * c)
        P.append(row)
    return P


def brute_mutual(P, theta):
    m, n = len(P), len(P[0])
    out = []
    for i in range(m):
        for j in range(n):
            row_ok = all(P[i][j] > P[i][k] or (P[i][j] == P[i][k] and j <= k) for k in range(n))
            col_ok = all(P[i][j] > P[k][j] or (P[i][j] == P[k][j] and i <= k) for k in range(m))
            if row_ok and col_ok and P[i][j] >= theta:
                out.append((i, j, P[i][j]))
    return out


def test_dual_softmax_matches_definition_and_bounds():
    rng = random.Random(1)
    for _ in range(10):
        m, n, d = rng.randint(1, 6), rng.randint(1, 6), rng.randint(1, 4)
        FA, FB = rand_vecs(rng, m, d), rand_vecs(rng, n, d)
        tau = rng.choice((0.5, 1.0, 2.0))
        P, Q = dual_softmax(FA, FB, tau), brute_dual_softmax(FA, FB, tau)
        assert all(abs(p - q) < 1e-12 for rp, rq in zip(P, Q) for p, q in zip(rp, rq))
        assert all(0.0 < p <= 1.0 for r in P for p in r)
        assert all(sum(r) <= 1.0 + 1e-12 for r in P)
        assert all(sum(c) <= 1.0 + 1e-12 for c in zip(*P))


def test_coarse_matches_equal_brute_force_with_ties():
    rng = random.Random(2)
    for trial in range(30):
        m, n = rng.randint(1, 6), rng.randint(1, 6)
        P = dual_softmax(rand_vecs(rng, m, 3), rand_vecs(rng, n, 3), 0.5)
        if trial % 3 == 0:
            P = [[round(p, 1) for p in r] for r in P]
        theta = rng.choice((0.0, 0.1, 0.3))
        got = coarse_matches(P, theta)
        assert got == brute_mutual(P, theta)
        assert len({i for i, _, _ in got}) == len(got) == len({j for _, j, _ in got})


def test_many_small_inputs_against_brute_force():
    rng = random.Random(7)
    for _ in range(600):
        m, n, d = rng.randint(1, 4), rng.randint(1, 4), rng.randint(1, 3)
        FA = [[float(rng.randint(-2, 2)) for _ in range(d)] for _ in range(m)]
        FB = [[float(rng.randint(-2, 2)) for _ in range(d)] for _ in range(n)]
        tau = rng.choice((0.5, 1.0))
        P, Q = dual_softmax(FA, FB, tau), brute_dual_softmax(FA, FB, tau)
        assert all(abs(p - q) < 1e-12 for rp, rq in zip(P, Q) for p, q in zip(rp, rq))
        theta = rng.choice((0.0, 0.2, 0.5))
        assert coarse_matches(Q, theta) == brute_mutual(Q, theta)


def test_above_one_half_is_always_mutual():
    rng = random.Random(3)
    for _ in range(40):
        m, n = rng.randint(1, 5), rng.randint(1, 5)
        P = dual_softmax(rand_vecs(rng, m, 3), rand_vecs(rng, n, 3), 0.2)
        high = [(i, j) for i in range(m) for j in range(n) if P[i][j] > 0.5]
        assert sorted(high) == sorted((i, j) for i, j, _ in coarse_matches(P, 0.5000001))


def test_shift_and_transpose():
    rng = random.Random(4)
    m, n, d = 4, 5, 3
    FA, FB = rand_vecs(rng, m, d), rand_vecs(rng, n, d)
    P = dual_softmax(FA, FB, 0.5)
    # a constant added to every score: append a coordinate 1 to A and c to B
    Ps = dual_softmax([a + [1.0] for a in FA], [b + [3.7] for b in FB], 0.5)
    assert all(abs(p - q) < 1e-12 for rp, rq in zip(P, Ps) for p, q in zip(rp, rq))
    Pt = dual_softmax(FB, FA, 0.5)
    assert all(abs(P[i][j] - Pt[j][i]) < 1e-12 for i in range(m) for j in range(n))
    a = sorted((i, j) for i, j, _ in coarse_matches(P, 0.0))
    b = sorted((i, j) for j, i, _ in coarse_matches(Pt, 0.0))
    assert a == b


def test_refined_position_is_in_the_window():
    rng = random.Random(5)
    G = [[[rng.gauss(0, 1) for _ in range(4)] for _ in range(12)] for _ in range(10)]
    for _ in range(30):
        fx, fy = rng.randrange(12), rng.randrange(10)
        c = [rng.gauss(0, 1) for _ in range(4)]
        x, y = refine(c, G, fx, fy, 5, rng.choice((0.5, 1.0, 4.0)))
        assert max(0, fx - 2) - 1e-12 <= x <= min(11, fx + 2) + 1e-12
        assert max(0, fy - 2) - 1e-12 <= y <= min(9, fy + 2) + 1e-12


def test_peaked_window_gives_the_peak_within_the_bound():
    d, w = 3, 5
    G = [[[0.0] * d for _ in range(9)] for _ in range(9)]
    c = [1.0, 0.0, 0.0]
    G[3][5] = [1.0, 0.0, 0.0]  # offset (+1, -1) from the center (4, 4)
    for gap in (2.0, 5.0, 10.0):
        x, y = refine(c, G, 4, 4, w, gap)
        err = math.hypot(x - 5, y - 3)
        bound = (w * w - 1) * math.exp(-gap) * (w - 1) * math.sqrt(2)
        assert err <= bound + 1e-12
    x, y = refine(c, G, 4, 4, w, 30.0)
    assert abs(x - 5) < 1e-9 and abs(y - 3) < 1e-9


def test_full_pipeline_recovers_a_shuffled_grid():
    rng = random.Random(6)
    hc, wc, d = 3, 4, 16
    FA = [[x / math.sqrt(sum(t * t for t in v)) for x in v] for v in rand_vecs(rng, hc * wc, d)]
    perm = list(range(hc * wc))
    rng.shuffle(perm)
    FB = [None] * (hc * wc)
    for i, j in enumerate(perm):
        FB[j] = [x + rng.gauss(0, 0.05) for x in FA[i]]
    GA = [[[rng.gauss(0, 1) for _ in range(d)] for _ in range(4 * wc)] for _ in range(4 * hc)]
    GB = [[[0.0] * d for _ in range(4 * wc)] for _ in range(4 * hc)]
    for i, j in enumerate(perm):  # put the fine vector of A one fine pixel right of the cell of j
        bx, by = j % wc, j // wc
        GB[4 * by][min(4 * bx + 1, 4 * wc - 1)] = GA[4 * (i // wc)][4 * (i % wc)]
    out = loftr_match(FA, FB, wc, wc, GA, GB, tau=0.1, theta=0.2, w=5, scale=20.0)
    assert len(out) == hc * wc
    for (pa, pb, conf) in out:
        i = pa[1] // 8 * wc + pa[0] // 8
        j = perm[i]
        bx, by = j % wc, j // wc
        want = (2 * min(4 * bx + 1, 4 * wc - 1), 8 * by)
        assert abs(pb[0] - want[0]) < 1e-3 and abs(pb[1] - want[1]) < 1e-3 and conf >= 0.2

History

Dense matching of learned features goes back to neighborhood consensus networks (Rocco and others, 2018), which scored all pairs of cells with 4D convolutions. SuperGlue (2020) brought attention between and within two sets of detected points. Sun, Shen, Wang, Bao and Zhou (2021) applied the same attention to all coarse cells, made it affordable with linear attention, and added a coarse-to-fine step, so the matcher no longer depends on a detector. Several later dense and semi-dense matchers follow the same coarse-to-fine design.

References

  1. Jiaming Sun, Zehong Shen, Yuang Wang, Hujun Bao and Xiaowei Zhou, LoFTR, detector-free local feature matching with transformers, IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), 2021 (arXiv 2104.00680), Section 3.2 (the LoFTR module, positional encoding and linear attention), Section 3.3 (the score matrix, the dual-softmax and the match selection with a threshold and mutual nearest neighbors), Section 3.4 (the coarse-to-fine module), Section 3.5 (the losses), Section 3.6 (the implementation details), Section 4 (the experiments)
  2. Paul-Edouard Sarlin, Daniel DeTone, Tomasz Malisiewicz and Andrew Rabinovich, SuperGlue, learning feature matching with graph neural networks, IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), 2020 (arXiv 1911.11763), Section 3.2, the optimal transport layer that LoFTR offers as an alternative to the dual-softmax

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example