Algorithm Search⌘K

Techniqueadvanced

RootSIFT

Also called Hellinger kernel SIFT.

L1-normalize a SIFT vector and take the square root of each entry, so that the dot product of two results equals the Hellinger kernel of the originals.

RootSIFT is a change of the descriptor, not of the matcher. Divide a SIFT vector by the sum of its entries (L1 normalization) and take the square root of each entry. For two vectors mapped this way, the dot product is the Hellinger kernel H(x,y)=∑ixˉiyˉiH(x, y) = \sum_i \sqrt{\bar x_i \bar y_i} of the original histograms, and the squared Euclidean distance is 2−2H2 - 2H. So every tool that uses Euclidean distance, such as a kd-forest, the ratio test or k-means for a visual vocabulary, compares the descriptors with the Hellinger kernel and needs no change. The map costs O(D)O(D) per descriptor of length DD and is done once, before storage. Arandjelovic and Zisserman (2012) proposed it and measured better retrieval with it.

In plain words

A SIFT descriptor is a histogram: it counts how much gradient points in each direction in each part of a patch. Plain Euclidean distance compares two histograms bin by bin, and a few large bins decide most of the result, so a small change in one strong edge can hide agreement in many weaker bins. Taking the square root makes large values smaller and small values larger, so all the bins count more evenly. Dividing by the sum first makes the result independent of the overall contrast. After this change you use the new vectors exactly as before, and the usual distance now measures how much two histograms overlap.

When it applies

  • The descriptors are histograms or other vectors with non-negative entries, such as SIFT, SURF or HOG. A descriptor with negative entries, such as one from a neural network, has no square root map of this kind.
  • The rest of the system uses Euclidean distance or dot products, and you want a histogram distance without changing that code.
  • You can store the mapped vectors, or map each descriptor when you read it. The map keeps the length DD.

The template

  1. ROOTSIFT-THEN(X, STEP)
  2. 1for each descriptor x in X: s ← Σ_i x_i
  3. 2if s = 0 then y ← x
  4. 3else y ← (sqrt(x_1 / s), …, sqrt(x_D / s))
  5. 4run STEP on the y vectors ▷ hole: matching, k-means, vocabulary tree

Lines L1 to L3 map one descriptor. Line L2 keeps the zero vector, which has no direction. The hole is line L4: any method that uses Euclidean distance or dot products, for example exact nearest neighbor matching with the ratio test, a vocabulary tree or a bag of visual words. The code in impl/python/rootsift.py maps a descriptor and finds a nearest neighbor with the mapped vectors. The proof in proofs/correctness.md shows that a mapped vector has unit length, that the dot product of two mapped vectors is the Hellinger kernel, that the squared distance is 2−2H2 - 2H, so the Euclidean nearest neighbor is the descriptor of largest Hellinger kernel, and that the result does not change when a descriptor is multiplied by a positive number.

Example. Take two-bin histograms q=(9,16)q = (9, 16), p1=(0,25)p_1 = (0, 25) and p2=(16,9)p_2 = (16, 9). Which one is nearer to qq?

after L2 normalization SIFT distance to qq after RootSIFT Hellinger kernel HH RootSIFT distance 2−2H\sqrt{2 - 2H}
qq (0.4903,0.8716)(0.4903, 0.8716) (0.6,0.8)(0.6, 0.8)
p1p_1 (0,1)(0, 1) 0.5068 (0,1)(0, 1) 0.80.8 0.6325
p2p_2 (0.8716,0.4903)(0.8716, 0.4903) 0.5393 (0.8,0.6)(0.8, 0.6) 0.6⋅0.8+0.8⋅0.6=0.960.6 \cdot 0.8 + 0.8 \cdot 0.6 = 0.96 0.2828

Plain SIFT with L2 normalization picks p1p_1, because the large second bin of qq is close to that of p1p_1. RootSIFT picks p2p_2, whose histogram overlaps more with qq in both bins. You can check every value by hand.

Classic examples

  • Object retrieval. Arandjelovic and Zisserman (2012) used RootSIFT in a bag of visual words system for image retrieval. On Oxford 105k, they report that the mean average precision goes from 0.515 to 0.581 with tf-idf ranking and from 0.581 to 0.642 with spatial reranking. These are measurements on that dataset in 2012, not guarantees.
  • Descriptor matching. Many structure from motion and image stitching systems apply RootSIFT before feature matching with the ratio test, because it changes only one line of code.
  • Aggregated descriptors. Encodings such as VLAD and Fisher vectors often take RootSIFT as input, and they apply the same signed square root idea to the final vector.

Variations

  • Square root of a different histogram. The same map applies to any histogram descriptor, such as HOG or color histograms.
  • Power normalization. Use xiαx_i^{\alpha} with 0<α<10 < \alpha < 1 in place of the square root, then normalize. The value α=1/2\alpha = 1/2 gives the Hellinger kernel; other values are tuned and have no such identity.
  • Signed square root. For vectors with negative entries, use sign⁡(xi)∣xi∣\operatorname{sign}(x_i) \sqrt{\lvert x_i \rvert}. This is a heuristic and does not give the Hellinger kernel.
  • With PCA. Apply principal component analysis after RootSIFT to make the vectors shorter. The PCA step is learned on a sample and changes the distances.

Pitfalls

  • L1, not L2, before the root. SIFT descriptors are usually stored after L2 normalization. RootSIFT needs L1 normalization before the root; with L2 normalization the mapped vectors do not have unit length and the identity with the Hellinger kernel fails.
  • Clipping and quantization. SIFT clips large entries and often stores bytes. The map still works, but it uses the clipped histogram, and if you store the mapped vectors as bytes you need a new scale.
  • Thresholds change. Distances of mapped vectors are in [0,2][0, \sqrt{2}] and have a different distribution. A distance threshold or a ratio test threshold tuned for plain SIFT must be tuned again.
  • Mixed databases. All descriptors in a database and all queries must use the same map. Comparing a RootSIFT vector with a plain SIFT vector gives no useful distance.
  • Not a better detector. RootSIFT changes only the descriptor distance. It does not add keypoints or fix wrong scales and orientations.
Proof: RootSIFT turns Euclidean distance into the Hellinger kernelfull

Let x,y∈RDx, y \in \mathbb{R}^D have non-negative entries and positive sums sx=∑ixis_x = \sum_i x_i and sy=∑iyis_y = \sum_i y_i. Write xˉ=x/sx\bar x = x / s_x and yˉ=y/sy\bar y = y / s_y for the L1-normalized vectors, and ⋅\sqrt{\cdot} entrywise. Lines L1 to L3 compute R(x)=xˉR(x) = \sqrt{\bar x}, and R(0)=0R(0) = 0. The Hellinger kernel is H(x,y)=∑ixˉiyˉiH(x, y) = \sum_i \sqrt{\bar x_i \bar y_i}.

Lemma 1 (unit norm). ∥R(x)∥2=1\lVert R(x) \rVert_2 = 1.

Proof. ∥R(x)∥22=∑ixˉi=1\lVert R(x) \rVert_2^2 = \sum_i \bar x_i = 1, because xˉ\bar x is non-negative with sum 1. □\square

Lemma 2 (inner product). ⟨R(x),R(y)⟩=H(x,y)\langle R(x), R(y) \rangle = H(x, y), and 0≤H(x,y)≤10 \le H(x, y) \le 1.

Proof. xˉiyˉi=xˉiyˉi\sqrt{\bar x_i}\sqrt{\bar y_i} = \sqrt{\bar x_i \bar y_i} for non-negative entries, so the sums agree. All terms are non-negative, and the Cauchy-Schwarz inequality with Lemma 1 gives H≤∥R(x)∥∥R(y)∥=1H \le \lVert R(x) \rVert \lVert R(y) \rVert = 1. □\square

Lemma 3 (distance). ∥R(x)−R(y)∥22=2−2H(x,y)\lVert R(x) - R(y) \rVert_2^2 = 2 - 2 H(x, y).

Proof. Expand: ∥R(x)∥2+∥R(y)∥2−2⟨R(x),R(y)⟩=1+1−2H(x,y)\lVert R(x) \rVert^2 + \lVert R(y) \rVert^2 - 2 \langle R(x), R(y) \rangle = 1 + 1 - 2 H(x, y) by Lemmas 1 and 2. □\square

So the Euclidean distance of RootSIFT vectors is 2\sqrt{2} times the Hellinger distance h(xˉ,yˉ)=1−H(x,y)h(\bar x, \bar y) = \sqrt{1 - H(x, y)} between the normalized histograms.

Lemma 4 (nearest neighbors). For a query qq and database vectors p1,…,pnp_1, \dots, p_n, all with positive sums, ∥R(q)−R(pj)∥<∥R(q)−R(pk)∥\lVert R(q) - R(p_j) \rVert < \lVert R(q) - R(p_k) \rVert if and only if H(q,pj)>H(q,pk)H(q, p_j) > H(q, p_k). So the nearest RootSIFT vector is a database vector of largest Hellinger kernel with the query, and every method that ranks by Euclidean distance ranks by the Hellinger kernel.

Proof. By Lemma 3, the distance is 2−2H\sqrt{2 - 2H}, a strictly decreasing function of HH on [0,1][0, 1]. □\square

Lemma 5 (scale). R(cx)=R(x)R(c x) = R(x) for every c>0c > 0.

Proof. cx/(csx)=x/sxc x / (c s_x) = x / s_x. □\square

Theorem. For non-negative descriptors with positive sums, RootSIFT gives unit vectors whose inner products are the Hellinger kernels and whose squared Euclidean distances are 2−2H2 - 2H. Euclidean nearest neighbor search on RootSIFT vectors returns the descriptor of largest Hellinger kernel, and the result does not change when a descriptor is multiplied by a positive number.

Proof. Lemmas 1 to 5. ■\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.

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

"""RootSIFT (Arandjelovic and Zisserman 2012).

Map a descriptor with non-negative entries, such as SIFT, to the square roots
of its L1-normalized entries. For L1-normalized x and y,
||sqrt(x) - sqrt(y)||^2 = 2 - 2 H(x, y) with H(x, y) = sum_i sqrt(x_i y_i),
the Hellinger kernel (the Bhattacharyya coefficient). So Euclidean nearest
neighbors of the mapped vectors are the neighbors of largest Hellinger kernel.

Precondition: all entries are non-negative. The zero vector maps to itself.
Cost: O(D) time and space for a descriptor of length D.
"""

import math
from typing import List, Sequence

Vec = Sequence[float]


def rootsift(x: Vec) -> List[float]:
    """Return the RootSIFT vector of x; it has unit Euclidean norm unless x is zero."""
    if any(t < 0 for t in x):
        raise ValueError("RootSIFT needs non-negative entries")
    s = sum(x)  # @line L1
    if s == 0:  # @line L2
        return [0.0] * len(x)
    return [math.sqrt(t / s) for t in x]  # @line L3


def hellinger_kernel(x: Vec, y: Vec) -> float:
    """H(x, y) = sum_i sqrt(x_i y_i) after L1 normalization of x and y."""
    sx, sy = sum(x), sum(y)
    return sum(math.sqrt(a * b / (sx * sy)) for a, b in zip(x, y))


def nearest_by_rootsift(q: Vec, database: Sequence[Vec]) -> int:
    """Index of the database descriptor whose RootSIFT vector is nearest to that of q."""
    rq = rootsift(q)
    best, arg = math.inf, -1
    for j, p in enumerate(database):  # @line L4
        d = math.dist(rq, rootsift(p))
        if d < best:
            best, arg = d, j
    return arg
test_rootsift.py 63 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rootsift/. The authors are listed in prov/5CC4QY.jsonl.

import math
import random

import pytest

from rootsift import hellinger_kernel, nearest_by_rootsift, rootsift


def l2_normalized(x):
    n = math.sqrt(sum(t * t for t in x))
    return [t / n for t in x]


def test_worked_example():
    q, p1, p2 = (9.0, 16.0), (0.0, 25.0), (16.0, 9.0)
    assert rootsift(q) == pytest.approx([0.6, 0.8])
    assert hellinger_kernel(q, p1) == pytest.approx(0.8)
    assert hellinger_kernel(q, p2) == pytest.approx(0.96)
    assert math.dist(rootsift(q), rootsift(p1)) == pytest.approx(math.sqrt(0.4))
    assert math.dist(rootsift(q), rootsift(p2)) == pytest.approx(math.sqrt(0.08))
    # plain SIFT matching with L2 normalization picks p1, RootSIFT picks p2
    e1 = math.dist(l2_normalized(q), l2_normalized(p1))
    e2 = math.dist(l2_normalized(q), l2_normalized(p2))
    assert e1 == pytest.approx(0.5068, abs=1e-4) and e2 == pytest.approx(0.5393, abs=1e-4)
    assert nearest_by_rootsift(q, [p1, p2]) == 1


def test_identity_and_unit_norm_on_many_inputs():
    rng = random.Random(1)
    for _ in range(600):
        d = rng.randint(1, 16)
        x = [float(rng.randint(0, 20)) for _ in range(d)]
        y = [float(rng.randint(0, 20)) for _ in range(d)]
        x[rng.randrange(d)] += 1.0
        y[rng.randrange(d)] += 1.0
        rx, ry = rootsift(x), rootsift(y)
        assert sum(t * t for t in rx) == pytest.approx(1.0)
        h = hellinger_kernel(x, y)
        assert 0.0 <= h <= 1.0 + 1e-12
        assert math.dist(rx, ry) ** 2 == pytest.approx(2.0 - 2.0 * h, abs=1e-12)
        assert sum(a * b for a, b in zip(rx, ry)) == pytest.approx(h)


def test_nearest_neighbor_is_the_largest_hellinger_kernel():
    rng = random.Random(2)
    for _ in range(200):
        d = rng.randint(2, 8)
        db = [[rng.random() for _ in range(d)] for _ in range(rng.randint(1, 10))]
        q = [rng.random() for _ in range(d)]
        j = nearest_by_rootsift(q, db)
        assert hellinger_kernel(q, db[j]) == pytest.approx(max(hellinger_kernel(q, p) for p in db))


def test_scale_invariance_zero_vector_and_bad_input():
    x = [3.0, 0.0, 1.0, 12.0]
    assert rootsift([7.5 * t for t in x]) == pytest.approx(rootsift(x))
    assert rootsift([0.0, 0.0, 0.0]) == [0.0, 0.0, 0.0]
    assert rootsift([5.0]) == [1.0]
    with pytest.raises(ValueError):
        rootsift([1.0, -0.5])

References

  1. Relja Arandjelovic and Andrew Zisserman, Three things everyone should know to improve object retrieval, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2012, Section 3, RootSIFT: the Hellinger kernel, the identity between the Euclidean distance of the square-rooted vectors and the kernel, and the retrieval results on Oxford 5k and Oxford 105k
  2. David G. Lowe, Distinctive image features from scale-invariant keypoints, International Journal of Computer Vision 60(2), 2004, the SIFT descriptor, a histogram of gradient orientations with non-negative entries

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/5CC4QY/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