Algorithm Search⌘K

Techniquecore

Mutual nearest neighbor matching

Also called cross-check matching, symmetric matching.

Keep a pair only when each feature is the nearest neighbor of the other in descriptor space.

Mutual nearest neighbor matching keeps a pair of features (ai,bj)(a_i, b_j) only when bjb_j is the nearest neighbor of aia_i among the features of the second image and aia_i is the nearest neighbor of bjb_j among the features of the first. One nearest neighbor search in each direction and a comparison give the result. Unlike plain nearest neighbor matching, the result is a partial matching: each feature is used at most once. The check has no parameter, so it needs no tuning, and it is often combined with the ratio test or a distance threshold.

In plain words

Two people at a party each have to pick the one person they like most. If Ann picks Bob and Bob picks Ann, they are a pair. If Ann picks Bob but Bob picks Carol, nobody is paired with Ann. Feature matching works the same way. A point in the first image picks the most similar point in the second image, and that point picks back. Only the pairs that pick each other are kept. A point that is not in the other image at all still picks someone, but the one it picks usually prefers another point, so the false pick is dropped.

When it applies

  • You have two sets of features, descriptors or embeddings, with a distance or a similarity between any two, and you want a one-to-one correspondence.
  • Many features have no true partner, and you want to drop most of them without a tuned threshold.
  • You can afford a nearest neighbor search in both directions. With exact search the cost is O(mnD)O(m n D) for mm and nn descriptors of length DD; the two directions can share the distance matrix.
  • The score can be a distance to minimize or a similarity to maximize, such as the confidence matrix of a learned matcher.

The template

  1. MUTUAL-NN-MATCH(A, B)
  2. 1for each a_i of A: f(i) ← NEAREST(a_i, B) ▷ hole: the distance and the search method
  3. 2for each b_j of B: g(j) ← NEAREST(b_j, A)
  4. 3for each i do
  5. 4if g(f(i)) = i then output (i, f(i))

The holes are the distance and the nearest neighbor search of lines L1 and L2. Ties must go to a fixed choice, such as the smaller index, so that ff and gg are functions. The code in impl/python/mutual_nearest_neighbor_matching.py uses exact search and Euclidean distance. The proof in proofs/correctness.md shows that the output is exactly the set of pairs whose distance is the first smallest of its row and of its column, that it is a partial matching, that swapping the two sets gives the same pairs, that the closest pair overall is always kept, so the output is never empty for non-empty sets, and that with distinct distances every mutual pair is also chosen by the greedy matching, which takes the pairs in increasing order of distance.

Example. On a line, let A={0,4,5}A = \{0, 4, 5\} and B={1,4.5,9}B = \{1, 4.5, 9\}.

feature nearest in the other set picked back?
a0=0a_0 = 0 b0=1b_0 = 1 b0b_0 picks a0a_0: yes
a1=4a_1 = 4 b1=4.5b_1 = 4.5 b1b_1 is at 0.5 from both a1a_1 and a2a_2; the tie goes to a1a_1: yes
a2=5a_2 = 5 b1=4.5b_1 = 4.5 b1b_1 picks a1a_1: no
b2=9b_2 = 9 a2=5a_2 = 5 a2a_2 picks b1b_1: no

The result is {(a0,b0),(a1,b1)}\{(a_0, b_0), (a_1, b_1)\}. Plain nearest neighbor matching from AA would use b1b_1 twice. The point b2b_2 is far from everything and stays unmatched.

Classic examples

  • Brute-force descriptor matching. Many matching libraries offer a "cross-check" flag on brute-force matching that keeps only the mutual pairs; it is the parameter-free alternative to the ratio test.
  • Stereo. The left-right consistency check keeps a disparity only when matching from the right image back to the left returns the same pixel, the same idea on a dense grid.
  • Tracking. The forward-backward error tracks a point forward and then back and keeps it when it returns near its start.
  • Learned matchers. LoFTR keeps the mutual best pairs of its confidence matrix above a threshold, and SuperGlue keeps mutual best pairs of its assignment matrix.

Variations

  • With the ratio test. Apply the ratio test in one or both directions and then the mutual check, which removes both ambiguous and one-sided matches.
  • Mutual k nearest neighbors. Keep a pair when each is among the kk nearest of the other. The result is no longer a matching.
  • Global assignment. The Hungarian algorithm finds the one-to-one matching of minimum total distance. It always matches min⁡(m,n)\min(m, n) pairs, so it needs a cost for leaving a feature unmatched to reject outliers.
  • Greedy and stable matching. Taking the closest free pair again and again gives a full matching that contains every mutual pair when the distances are distinct, and that is stable for the preferences "closer is better".

Pitfalls

  • Ties. Descriptors with equal distances, for example quantized or binary ones with Hamming distance, give ties. Without a fixed tie rule the result depends on the scan order, and a pair can be kept in one direction and not in the other.
  • Repeated structure. If two features of BB are near copies, the one that is not chosen loses its true partner. The check keeps one of them, which may be the wrong one; it does not test for ambiguity as the ratio test does.
  • Approximate search. With approximate nearest neighbors in either direction, a true mutual pair can be missed, and the result can differ when the sets are swapped.
  • Not a quality test. A mutual pair can still be far apart, for example two outliers that are each the other's best. Add a distance threshold or a geometric check such as RANSAC.
Proof: Properties of mutual nearest neighbor matchingfull

Let A=(a0,…,am−1)A = (a_0, \dots, a_{m-1}) and B=(b0,…,bn−1)B = (b_0, \dots, b_{n-1}) be lists of vectors with m,n≥1m, n \ge 1, and let d(i,j)=∥ai−bj∥d(i, j) = \lVert a_i - b_j \rVert. Let f(i)f(i) be the smallest index jj that minimizes d(i,j)d(i, j), and g(j)g(j) the smallest index ii that minimizes d(i,j)d(i, j). The output is M={(i,f(i)):g(f(i))=i}M = \{ (i, f(i)) : g(f(i)) = i \}.

Lemma 1 (the scan). nearest(a, B) returns the smallest index of a nearest vector.

Proof. The scan keeps the smallest value seen so far and replaces it only on a strictly smaller value, so the first index that reaches the minimum is kept. □\square

Lemma 2 (a matching). Each ii and each jj is in at most one pair of MM.

Proof. Row ii is listed only with f(i)f(i). If (i,j)(i, j) and (i′,j)(i', j) are in MM, then i=g(j)=i′i = g(j) = i'. □\square

Lemma 3 (the definition). (i,j)∈M(i, j) \in M if and only if d(i,j)d(i, j) is the first smallest value of row ii and the first smallest value of column jj, where "first" means the smallest index among equal values.

Proof. This is the definition of ff and gg: j=f(i)j = f(i) is the first condition and i=g(j)i = g(j) the second. □\square

Lemma 4 (symmetry). Matching BB against AA gives {(j,i):(i,j)∈M}\{(j, i) : (i, j) \in M\}.

Proof. Swapping the lists swaps the roles of ff and gg, and the condition of Lemma 3 is symmetric in rows and columns. □\square

Lemma 5 (the closest pair is kept). Let δ=min⁡i,jd(i,j)\delta = \min_{i, j} d(i, j), let i∗i^* be the smallest row that contains the value δ\delta, and let j∗=f(i∗)j^* = f(i^*). Then (i∗,j∗)∈M(i^*, j^*) \in M. In particular MM is not empty.

Proof. d(i∗,j∗)=δd(i^*, j^*) = \delta because row i∗i^* contains δ\delta, which is the global minimum. Column j∗j^* has minimum δ\delta, and every row ii with d(i,j∗)=δd(i, j^*) = \delta has i≥i∗i \ge i^* by the choice of i∗i^*. So g(j∗)=i∗g(j^*) = i^*. □\square

Lemma 6 (inside the greedy matching). Suppose all values d(i,j)d(i, j) are distinct. The greedy matching takes pairs in increasing order of dd and keeps a pair when neither end is used. Then MM is a subset of the greedy matching.

Proof. Take (i,j)∈M(i, j) \in M. By Lemma 3 every other pair in row ii or column jj has a larger value. So when the greedy method reaches (i,j)(i, j), it has taken only pairs with smaller values, none of which uses ii or jj. Both ends are free, and it keeps (i,j)(i, j). □\square

Theorem. mutual_nn_match returns the pairs of Lemma 3 in increasing order of ii. They form a partial matching that contains the closest pair, does not depend on which list is called AA, and, for distinct distances, is a subset of the greedy matching.

Proof. Lines L1 and L2 compute ff and gg by Lemma 1, and lines L3 and L4 keep exactly the pairs with g(f(i))=ig(f(i)) = i. Lemmas 2 to 6 give the properties. ■\blacksquare

Code

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.

mutual_nearest_neighbor_matching.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mutual-nearest-neighbor-matching/. The authors are listed in prov/5K7F44.jsonl.

"""Mutual nearest neighbor matching, also called cross-check matching.

For each descriptor a_i of A find its nearest descriptor f(i) in B, and for
each descriptor b_j of B its nearest descriptor g(j) in A. Keep (i, f(i))
when g(f(i)) = i. Ties for the nearest go to the smaller index, so f and g
are functions and the result does not depend on the order of the scan.

Precondition: all vectors have the same length. Cost: O(|A| |B| D) time with
exact search over descriptors of length D, and O(|A| + |B|) extra space.
"""

from typing import List, Sequence, Tuple

Vec = Sequence[float]


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


def nearest(a: Vec, B: Sequence[Vec]) -> int:
    """Index of the nearest vector of B to a, the smallest index on ties; -1 if B is empty."""
    best, arg = float("inf"), -1
    for j, b in enumerate(B):
        d = sqdist(a, b)
        if d < best:
            best, arg = d, j
    return arg


def mutual_nn_match(A: Sequence[Vec], B: Sequence[Vec]) -> List[Tuple[int, int]]:
    """Return the mutual nearest neighbor pairs (i, j) in increasing order of i."""
    if not A or not B:
        return []
    f = [nearest(a, B) for a in A]  # @line L1
    g = [nearest(b, A) for b in B]  # @line L2
    out = []
    for i in range(len(A)):  # @line L3
        if g[f[i]] == i:  # @line L4
            out.append((i, f[i]))
    return out
test_mutual_nearest_neighbor_matching.py 77 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mutual-nearest-neighbor-matching/. The authors are listed in prov/5K7F44.jsonl.

import random

from mutual_nearest_neighbor_matching import mutual_nn_match, nearest, sqdist


def brute(A, B):
    """Keep (i, j) when d(i, j) is the first smallest of row i and of column j."""
    out = []
    for i, a in enumerate(A):
        for j, b in enumerate(B):
            d = sqdist(a, b)
            row = all(d < sqdist(a, B[k]) or (d == sqdist(a, B[k]) and j <= k) for k in range(len(B)))
            col = all(d < sqdist(A[k], b) or (d == sqdist(A[k], b) and i <= k) for k in range(len(A)))
            if row and col:
                out.append((i, j))
    return out


def greedy(A, B):
    pairs = sorted((sqdist(a, b), i, j) for i, a in enumerate(A) for j, b in enumerate(B))
    used_a, used_b, out = set(), set(), set()
    for _, i, j in pairs:
        if i not in used_a and j not in used_b:
            used_a.add(i)
            used_b.add(j)
            out.add((i, j))
    return out


def test_worked_example():
    A = [(0.0, 0.0), (4.0, 0.0), (5.0, 0.0)]
    B = [(1.0, 0.0), (4.5, 0.0), (9.0, 0.0)]
    # f = (0, 1, 1), g = (0, 1, 2): row 2 and row 1 both pick b_1, b_1 picks a_1 on a tie
    assert [nearest(a, B) for a in A] == [0, 1, 1]
    assert [nearest(b, A) for b in B] == [0, 1, 2]
    assert mutual_nn_match(A, B) == [(0, 0), (1, 1)]


def test_many_small_inputs_against_the_definition():
    rng = random.Random(1)
    for _ in range(600):
        d = rng.randint(1, 3)
        A = [tuple(rng.randint(0, 4) for _ in range(d)) for _ in range(rng.randint(0, 6))]
        B = [tuple(rng.randint(0, 4) for _ in range(d)) for _ in range(rng.randint(0, 6))]
        got = mutual_nn_match(A, B)
        assert got == brute(A, B)
        assert len({i for i, _ in got}) == len(got) == len({j for _, j in got})
        if A and B:
            assert got  # the first smallest pair is always kept
            m = min(sqdist(a, b) for a in A for b in B)
            i0 = min(i for i, a in enumerate(A) if any(sqdist(a, b) == m for b in B))
            assert (i0, nearest(A[i0], B)) in got


def test_swapping_the_sets_transposes_the_result():
    rng = random.Random(2)
    for _ in range(200):
        A = [tuple(rng.randint(0, 3) for _ in range(2)) for _ in range(rng.randint(1, 6))]
        B = [tuple(rng.randint(0, 3) for _ in range(2)) for _ in range(rng.randint(1, 6))]
        assert sorted((j, i) for i, j in mutual_nn_match(A, B)) == mutual_nn_match(B, A)


def test_subset_of_the_greedy_matching_for_distinct_distances():
    rng = random.Random(3)
    for _ in range(200):
        A = [tuple(rng.random() for _ in range(3)) for _ in range(rng.randint(1, 8))]
        B = [tuple(rng.random() for _ in range(3)) for _ in range(rng.randint(1, 8))]
        assert set(mutual_nn_match(A, B)) <= greedy(A, B)


def test_empty_and_single():
    assert mutual_nn_match([], [(1.0,)]) == []
    assert mutual_nn_match([(1.0,)], []) == []
    assert mutual_nn_match([(1.0,)], [(7.0,)]) == [(0, 0)]

References

  1. Richard Szeliski, Computer Vision: Algorithms and Applications, 2nd edition, Springer, 2022, Section 7.1.3, feature matching: matching strategies and error rates
  2. 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, Section 3.3, the match selection by a confidence threshold and the mutual nearest neighbor criterion
  3. 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, the mutual nearest neighbor baselines of the experiments

Where this leads

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 proofH2 full proof
  • correctness: no review record reviews/5K7F44/proof-correctness.yaml
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)
WritingW3 standard
  • five exercises