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 only when is the nearest neighbor of among the features of the second image and is the nearest neighbor of 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 for and descriptors of length ; 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
MUTUAL-NN-MATCH(A, B)- 1
for each a_i of A: f(i) ← NEAREST(a_i, B) ▷ hole: the distance and the search method - 2
for each b_j of B: g(j) ← NEAREST(b_j, A) - 3
for each i do - 4
if 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 and 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 and .
| feature | nearest in the other set | picked back? |
|---|---|---|
| picks : yes | ||
| is at 0.5 from both and ; the tie goes to : yes | ||
| picks : no | ||
| picks : no |
The result is . Plain nearest neighbor matching from would use twice. The point 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 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 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 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 and be lists of vectors with , and let . Let be the smallest index that minimizes , and the smallest index that minimizes . The output is .
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.
Lemma 2 (a matching). Each and each is in at most one pair of .
Proof. Row is listed only with . If and are in , then .
Lemma 3 (the definition). if and only if is the first smallest value of row and the first smallest value of column , where "first" means the smallest index among equal values.
Proof. This is the definition of and : is the first condition and the second.
Lemma 4 (symmetry). Matching against gives .
Proof. Swapping the lists swaps the roles of and , and the condition of Lemma 3 is symmetric in rows and columns.
Lemma 5 (the closest pair is kept). Let , let be the smallest row that contains the value , and let . Then . In particular is not empty.
Proof. because row contains , which is the global minimum. Column has minimum , and every row with has by the choice of . So .
Lemma 6 (inside the greedy matching). Suppose all values are distinct. The greedy matching takes pairs in increasing order of and keeps a pair when neither end is used. Then is a subset of the greedy matching.
Proof. Take . By Lemma 3 every other pair in row or column has a larger value. So when the greedy method reaches , it has taken only pairs with smaller values, none of which uses or . Both ends are free, and it keeps .
Theorem. mutual_nn_match returns the pairs of Lemma 3 in increasing order of . They form a partial matching that contains the closest pair, does not depend on which list is called , and, for distinct distances, is a subset of the greedy matching.
Proof. Lines L1 and L2 compute and by Lemma 1, and lines L3 and L4 keep exactly the pairs with . Lemmas 2 to 6 give the properties.
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.
# 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
- Richard Szeliski, Computer Vision: Algorithms and Applications, 2nd edition, Springer, 2022, Section 7.1.3, feature matching: matching strategies and error rates
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 5K7F44 Edit this page History Report an error Markdown