Algorithm Search⌘K

Techniquecore

Lowe's ratio test

Also called nearest neighbor distance ratio test, NNDR test.

Keep a match only when the distance to the nearest descriptor is much smaller than the distance to the second nearest, which rejects ambiguous matches.

Lowe's ratio test is a filter for descriptor matches. For a descriptor of one image, find its nearest and its second nearest descriptor in the other image. If the nearest is much closer than the second, the match is distinctive and is kept; if the two are almost at the same distance, the match is ambiguous and is dropped. Lowe (2004) keeps a match when d1<0.8 d2d_1 < 0.8 \, d_2. The value 0.8 is a tuned design choice, and his statement that it removes about 90 percent of the false matches and loses less than 5 percent of the correct ones is a measurement on his test data, not a theorem.

In plain words

A descriptor is a list of numbers that describes a small patch of an image. To find the same patch in a second image, we look for the closest descriptor there. But the closest one is not always right. A brick wall or a row of windows has many patches that look alike, and a patch that is not in the second image at all still has some closest descriptor. The ratio test asks one more question: how close is the runner-up? If the best is clearly better than the runner-up, we trust it. If the two are nearly as good, we cannot tell them apart, so we throw the match away. A plain distance limit cannot do this, because some good matches are far and some bad matches are near.

When it applies

  • You match descriptors of two images, or of an image against a database, by nearest neighbor search in a metric space.
  • Many query descriptors have no true partner, because of occlusion, a small overlap or clutter, so a match must be judged by how distinct it is, not only by its distance.
  • The distances of correct matches differ a lot from one feature to another, so one global distance threshold works poorly.
  • A second neighbor is available at little extra cost: exact search, best bin first search and the randomized kd-forest all return the kk nearest.

The template

  1. RATIO-TEST-MATCH(A, B, r) ▷ |B| ≥ 2 and 0 < r ≤ 1
  2. 1for each descriptor a_i of A do
  3. 2(j, d_1, d_2) ← NEAREST-TWO(a_i, B) ▷ hole: exact search, BBF or a kd-forest
  4. 3if d_1 < r · d_2 then
  5. 4output (i, j)

The holes are the search method in line L2, the distance and the ratio rr. With exact search and Euclidean distance the code in impl/python/lowe_ratio.py follows these lines; lowe_ratio_test.py only re-exports it, because the tools read a file name that ends in _test as a test file. Line L3 compares squared distances with r2r^2, which gives the same answer without a square root. The proof in proofs/correctness.md shows that the scan of line L2 returns the true nearest two, that the kept set is the same after a common scaling, translation or rotation of all descriptors, that it grows with rr, that a query with two nearest descriptors at the same distance is always rejected, and that two queries can keep the same partner.

Example. In the plane, let B={(1,0),(3,0),(5,4),(5,6.2)}B = \{(1, 0), (3, 0), (5, 4), (5, 6.2)\} and r=0.8r = 0.8.

query aia_i nearest, d1d_1 second, d2d_2 d1/d2d_1 / d_2 kept with r=0.8r = 0.8
(0,0)(0, 0) (1,0)(1, 0), 1 (3,0)(3, 0), 3 0.333 yes
(5,5)(5, 5) (5,4)(5, 4), 1 (5,6.2)(5, 6.2), 1.2 0.833 no
(2.1,0)(2.1, 0) (3,0)(3, 0), 0.9 (1,0)(1, 0), 1.1 0.818 no

The second and third queries sit between two similar candidates, and the test drops them, even though their nearest distances, 1 and 0.9, are not larger than that of the first query. With r=0.85r = 0.85 all three are kept.

Lowe's argument for the test is statistical. A correct match must be much closer than the nearest wrong descriptor, while for a wrong match many other wrong descriptors lie at a similar distance in the high-dimensional space. In Section 7.1 he plots the probability density of the ratio for correct and for false matches on his test images and picks 0.8 from these curves.

Classic examples

  • SIFT matching. SIFT descriptors of 128 values are matched by the nearest neighbor with the ratio test, and the survivors go to a Hough transform and a pose check (Lowe 2004).
  • Approximate search. Best bin first search and the randomized kd-forest return the two nearest neighbors approximately. Lowe used BBF with a cutoff of 200 candidates for this step.
  • RootSIFT. RootSIFT changes the descriptor and keeps the ratio test as it is.
  • Panorama and reconstruction. Image stitching and structure from motion pipelines filter putative matches with the ratio test before RANSAC, which then needs fewer samples because the outlier rate is lower.
  • Binary descriptors. ORB and BRIEF descriptors use the same test with Hamming distance, with a ratio tuned for that distance.

Variations

  • Symmetric ratio test. Run the test in both directions and keep the pairs that pass both ways, which also makes the result a matching; compare mutual nearest neighbor matching.
  • Ratio as a score. Instead of a hard cut, sort the matches by d1/d2d_1 / d_2 and use the order, for example for the sampling order of PROSAC.
  • A distance threshold. Mikolajczyk and Schmid (2005) compare a plain threshold on d1d_1, the nearest neighbor and the ratio of nearest distances as matching strategies for many descriptors.
  • Learned matchers. SuperGlue replaces the hand-made test with attention over both sets of points and a dustbin for points without a partner.

Pitfalls

  • Repeated structure. On facades, tiles or text, the true match has near copies, so d1≈d2d_1 \approx d_2 and the test drops correct matches. Use geometry or a learned matcher there.
  • Duplicate descriptors. If BB holds the same descriptor twice, for example because the detector reports one point twice, every query that matches it is rejected. Remove duplicates, or take the second neighbor among descriptors at a different image position.
  • Matching an image against itself. The nearest neighbor is the query itself at distance 0. Use the second and third neighbors instead of the first and second.
  • Squared distances. A library that returns squared distances needs r2r^2, not rr. With r=0.8r = 0.8 on squared distances the test is the much looser d1<0.894 d2d_1 < 0.894 \, d_2.
  • Approximate search. An approximate second neighbor can be farther than the true one, which makes the ratio smaller and lets ambiguous matches pass.
  • Not a matching. Several queries can keep the same partner. Add a mutual check if each feature may be used once.
  • The threshold. 0.8 is tuned for SIFT on Lowe's data. Other descriptors and distances need their own value.
Proof: Properties of the ratio testfull

Let AA and BB be finite lists of vectors in RD\mathbb{R}^D with ∣B∣≥2|B| \ge 2, let ∥⋅∥\lVert \cdot \rVert be the Euclidean norm, and let 0<r≤10 < r \le 1. For a∈Aa \in A let d1(a)≤d2(a)d_1(a) \le d_2(a) be the two smallest values of ∥a−b∥\lVert a - b \rVert over the entries bb of BB, counted with repetition, and let j(a)j(a) be the smallest index of BB at distance d1(a)d_1(a). The template keeps (i,j(ai))(i, j(a_i)) exactly when d1(ai)<r d2(ai)d_1(a_i) < r \, d_2(a_i). The code tests d12<r2d22d_1^2 < r^2 d_2^2.

Lemma 1 (the nearest two). The scan of nearest_two returns j(a)j(a), d1(a)2d_1(a)^2 and d2(a)2d_2(a)^2.

Proof. Invariant: after the entries 0,…,t0, \dots, t of BB, best and second are the two smallest squared distances among them, counted with repetition, and j1 is the smallest index with distance best. Initially both are ∞\infty. For the next entry with value dd: if d<d < best, the old best becomes the second smallest and dd the smallest, with the new index; if best ≤d<\le d < second, only second changes; else nothing changes. A value equal to best goes to second and does not change j1, so the smallest index is kept. After all entries the invariant gives the claim. □\square

Lemma 2 (squares). For d1,d2≥0d_1, d_2 \ge 0 and r>0r > 0, d1<rd2d_1 < r d_2 if and only if d12<r2d22d_1^2 < r^2 d_2^2.

Proof. Both sides are non-negative, and t↦t2t \mapsto t^2 is strictly increasing on [0,∞)[0, \infty). □\square

Lemma 3 (scale). Multiplying all vectors of AA and BB by the same c>0c > 0, or translating all of them by the same vector, or applying the same orthogonal map to all of them, does not change the kept pairs.

Proof. Each map multiplies every distance ∥a−b∥\lVert a - b \rVert by the same factor cc (or by 1). The order of the distances, the index j(a)j(a) and the truth of d1<rd2d_1 < r d_2 do not change. □\square

Lemma 4 (monotone in r). If r≤r′r \le r', every pair kept with rr is kept with r′r'.

Proof. d1<rd2≤r′d2d_1 < r d_2 \le r' d_2. □\square

Lemma 5 (ambiguity is rejected). If two entries of BB are at the same smallest distance from aa, in particular if BB holds the nearest vector twice, then aa is rejected for every r≤1r \le 1. With r=1r = 1, a query is kept exactly when its nearest neighbor is unique.

Proof. Then d1=d2d_1 = d_2, and d1<rd1d_1 < r d_1 is false for r≤1r \le 1. With r=1r = 1 the test is d1<d2d_1 < d_2, which holds exactly when one entry is strictly closer than all others. □\square

Lemma 6 (not a matching). The kept pairs can use the same jj for several ii.

Proof. Take B={(0),(10)}B = \{(0), (10)\} and A={(1),(−1)}A = \{(1), (-1)\}. Both queries have d1=1d_1 = 1 at index 0 and d2=9d_2 = 9 or 1111, so both are kept with r=0.8r = 0.8. □\square

Theorem. ratio_test_match returns, in order of ii, exactly the pairs (i,j(ai))(i, j(a_i)) with d1(ai)<r d2(ai)d_1(a_i) < r \, d_2(a_i), together with the two distances. The kept set does not change under a common scaling, translation or rotation of the descriptors, grows with rr, never contains a query with a tie for the nearest, and is not always a matching.

Proof. Lemma 1 gives the values, Lemma 2 shows that the test of line L3 is the ratio test, and Lemmas 3 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.

lowe_ratio.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lowe-ratio-test/. The authors are listed in prov/GBD07V.jsonl.

"""Lowe's ratio test on top of exact nearest neighbor search (Lowe 2004, Section 7.1).

For each descriptor a_i of A, find the nearest descriptor b_j of B, at
Euclidean distance d1, and the distance d2 to the second nearest. Keep the
pair (i, j) only when d1 < r * d2. The test compares squared distances with r^2,
which gives the same result and needs no square root.

Precondition: B has at least two descriptors, all of the same length as those
of A, and 0 < r <= 1. Cost: O(|A| |B| D) time for descriptors of length D, with
exact search; O(1) extra space per query. Ties for the nearest go to the
smaller index of B.
"""

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_two(a: Vec, B: Sequence[Vec]) -> Tuple[int, float, float]:
    """Return (j1, d1^2, d2^2): the nearest index and the two smallest squared distances."""
    j1, best, second = -1, float("inf"), float("inf")
    for j, b in enumerate(B):
        d = sqdist(a, b)
        if d < best:
            j1, best, second = j, d, best
        elif d < second:
            second = d
    return j1, best, second


def ratio_test_match(A: Sequence[Vec], B: Sequence[Vec], r: float = 0.8) -> List[Tuple[int, int, float, float]]:
    """Return the kept pairs as (i, j, d1, d2) with Euclidean distances d1 < r * d2."""
    if len(B) < 2:
        raise ValueError("the ratio test needs at least two descriptors in B")
    if not 0.0 < r <= 1.0:
        raise ValueError("the ratio r must be in (0, 1]")
    out = []
    for i, a in enumerate(A):  # @line L1
        j, d1, d2 = nearest_two(a, B)  # @line L2
        if d1 < r * r * d2:  # @line L3
            out.append((i, j, d1 ** 0.5, d2 ** 0.5))  # @line L4
    return out
lowe_ratio_test.py 9 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lowe-ratio-test/. The authors are listed in prov/GBD07V.jsonl.

"""Entry point named after the slug. The code is in lowe_ratio.py,
because the tools treat a file whose name ends in _test as a test file."""

from lowe_ratio import nearest_two, ratio_test_match, sqdist

__all__ = ["nearest_two", "ratio_test_match", "sqdist"]
test_lowe_ratio_test.py 85 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lowe-ratio-test/. The authors are listed in prov/GBD07V.jsonl.

import math
import random

import pytest

from lowe_ratio_test import nearest_two, ratio_test_match


def brute(A, B, r):
    out = []
    for i, a in enumerate(A):
        ds = sorted((math.dist(a, b), j) for j, b in enumerate(B))
        (d1, j), (d2, _) = ds[0], ds[1]
        if d1 < r * d2:
            out.append((i, j))
    return out


def test_worked_example():
    A = [(0.0, 0.0), (5.0, 5.0), (2.1, 0.0)]
    B = [(1.0, 0.0), (3.0, 0.0), (5.0, 4.0), (5.0, 6.2)]
    got = ratio_test_match(A, B, 0.8)
    assert [(i, j) for i, j, _, _ in got] == [(0, 0)]
    i, j, d1, d2 = got[0]
    assert abs(d1 - 1.0) < 1e-12 and abs(d2 - 3.0) < 1e-12
    # with a looser ratio the other queries pass too: 0.9 / 1.1 = 0.818 and 1 / 1.2 = 0.833
    assert [(i, j) for i, j, _, _ in ratio_test_match(A, B, 0.82)] == [(0, 0), (2, 1)]
    assert [(i, j) for i, j, _, _ in ratio_test_match(A, B, 0.85)] == [(0, 0), (1, 2), (2, 1)]


def test_many_small_inputs_against_sorting():
    rng = random.Random(1)
    for _ in range(600):
        d = rng.randint(1, 4)
        A = [tuple(rng.randint(0, 5) for _ in range(d)) for _ in range(rng.randint(0, 6))]
        B = [tuple(rng.randint(0, 5) for _ in range(d)) for _ in range(rng.randint(2, 7))]
        # with integer coordinates no distance ratio equals these r exactly, so rounding cannot decide
        r = rng.choice((0.61, 0.71, 0.83, 0.93, 1.0))
        got = ratio_test_match(A, B, r)
        want = brute(A, B, r)
        assert [i for i, _, _, _ in got] == [i for i, _ in want]
        for (i, j, d1, d2), (_, wj) in zip(got, want):
            assert math.dist(A[i], B[j]) == pytest.approx(math.dist(A[i], B[wj]))
            assert d1 < r * d2


def test_scale_of_all_descriptors_does_not_matter():
    rng = random.Random(2)
    A = [tuple(rng.random() for _ in range(8)) for _ in range(30)]
    B = [tuple(rng.random() for _ in range(8)) for _ in range(40)]
    base = [(i, j) for i, j, _, _ in ratio_test_match(A, B, 0.9)]
    for c in (0.25, 4.0, 1000.0):
        A2 = [tuple(c * x for x in a) for a in A]
        B2 = [tuple(c * x for x in b) for b in B]
        assert [(i, j) for i, j, _, _ in ratio_test_match(A2, B2, 0.9)] == base


def test_duplicate_of_the_nearest_is_rejected():
    A = [(0.0, 0.0)]
    B = [(1.0, 1.0), (1.0, 1.0), (9.0, 9.0)]
    assert nearest_two(A[0], B) == (0, 2.0, 2.0)
    assert ratio_test_match(A, B, 1.0) == []
    assert ratio_test_match(A, B[1:], 0.8) == [(0, 0, math.sqrt(2.0), math.sqrt(162.0))]


def test_kept_set_grows_with_the_ratio():
    rng = random.Random(3)
    A = [tuple(rng.random() for _ in range(4)) for _ in range(50)]
    B = [tuple(rng.random() for _ in range(4)) for _ in range(50)]
    prev = set()
    for r in (0.3, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0):
        cur = {(i, j) for i, j, _, _ in ratio_test_match(A, B, r)}
        assert prev <= cur
        prev = cur


def test_bad_input():
    with pytest.raises(ValueError):
        ratio_test_match([(0.0,)], [(1.0,)], 0.8)
    with pytest.raises(ValueError):
        ratio_test_match([(0.0,)], [(1.0,), (2.0,)], 0.0)
    assert ratio_test_match([], [(1.0,), (2.0,)]) == []

References

  1. David G. Lowe, Distinctive image features from scale-invariant keypoints, International Journal of Computer Vision 60(2), 2004, Section 7.1, keypoint matching: the ratio of the closest to the second-closest neighbor, the threshold 0.8 and its measured effect on correct and false matches
  2. Krystian Mikolajczyk and Cordelia Schmid, A performance evaluation of local descriptors, IEEE Transactions on Pattern Analysis and Machine Intelligence 27(10), 2005, the comparison of matching strategies, a distance threshold, the nearest neighbor and the nearest neighbor distance ratio
  3. Richard Szeliski, Computer Vision: Algorithms and Applications, 2nd edition, Springer, 2022, Section 7.1.3, feature matching: matching strategies, the nearest neighbor distance ratio and efficient matching

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/GBD07V/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