Algorithmadvanced
Spatial pyramid matching
Also called spatial pyramid kernel.
Compare images by histograms of visual words over grids of finer and finer cells, combined by a weighted histogram intersection kernel.
- Solves
- Object recognition
- Time
- O(M 4^L) denseO(n L) sparse
- Space
- O(n L) extra
- Where
- L = the finest pyramid level; M = the number of visual words; n = the total number of features of the two images
- Model
- Real RAM
- Properties
- deterministicexactpositive semidefinitesymmetric
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Svetlana Lazebnik, Cordelia Schmid, Jean Ponce, Kristen Grauman, Trevor Darrell, 2006
Spatial pyramid matching compares two images through their visual words and the rough places where those words occur. It cuts the image into a , , , ... grid of cells, counts the words in each cell, and adds up the histogram intersections of the levels with weights that favor matches in small cells. The result is a positive semidefinite kernel, used mostly with a support vector machine for scene and object classification. It is a classification method, not an image retrieval method, and its level 0 is the plain bag of words.
In plain words
A bag of words forgets where things are in the picture. A beach photo has sky at the top and sand at the bottom, and the bag of words cannot see that.
Spatial pyramid matching counts the words again in each half, each quarter and so on, of the image. Two photos get points when they have the same word in the whole image, more points when the word also appears in the same quarter, and still more when it appears in the same small cell. Points for a match are given once, at the finest level where it is found. The total is a similarity that a classifier can use directly.
The problem
Input. Two images of size (columns by rows), each given as a set of features : a position with and ( the column, the row, origin at the top left), and a visual word . The finest level .
Cells. Level cuts the image into equal cells. A feature at is in cell
The minimum puts points on the right or bottom edge into the last cell. A bin at level is a pair (cell, word). is the number of features of in bin .
Output. With the histogram intersection (Lazebnik et al., Eq. 1), the kernel is (Eq. 2)
The second form is Eq. 3. Lazebnik et al. write the kernel for one channel (one word) and add the channels (Eq. 4); taking the word as part of the bin, as here, gives the same sum.
The algorithm
SPM-KERNEL(X, Y, L, W, H)- 1
for l = 0 to L do - 2
H_X^l ← the counts of X over the bins (cell at level l, word) - 3
H_Y^l ← the counts of Y over the same bins - 4
I^l ← the sum over the bins b of min(H_X^l(b), H_Y^l(b)) - 5
kappa ← I^L - 6
for l = 0 to L - 1 do kappa ← kappa + (I^l - I^(l+1)) / 2^(L-l) - 7
return kappa
In practice each image is stored once as a single long vector: the histograms of all levels, each multiplied by its weight in Eq. 3, concatenated. The histogram intersection of two such vectors is , because for . The vector has entries; for and this is 4,200, the size Lazebnik et al. give. They also divide each histogram by the number of features of the image, so that images with many features do not get larger values.
Example
Take a image, two words and , and .
| features | |
|---|---|
| , , , | |
| , , , |
- Level 0, one cell. Both images have two and two , so . The bag of words sees two equal images.
- Level 1, cells of size 2. has twice in cell , in and in . has in , in , in and in . The common bins are with and with 1, so .
- Level 2, cells of size 1. No bin is shared, so .
By Eq. 2, . By Eq. 3, . Two matches are new at level 1 and count each, and two are new at level 0 and count each. For comparison, , so the layout costs more than half of the similarity. With the histograms divided by the 4 features, the kernel is . With instead, .
Correctness
The proof in the correctness file shows four facts. First, Eq. 2 and Eq. 3 are equal, by collecting the coefficient of each . Second, : each bin at level is the union of four bins at level with the same word, and ; so is the number of matches that are new at level , and each new match has a nonnegative weight. Third, is the size of a largest one-to-one matching between and that pairs only features with the same word in the same level- cell; the tests compare it with a matching by augmenting paths. Fourth, is a positive semidefinite kernel, because for makes each intersection an inner product, and a sum of such kernels with nonnegative weights is again one. Grauman and Darrell (2005) prove the same for their pyramid match.
Proof: The spatial pyramid kernel counts new matches per level with nonnegative weights and is positive semidefinitefull
We use the notation of the page. and are finite sets of features . At level , a bin is a pair (cell, word), is the number of features of in bin , and . Lines L1 to L4 compute exactly these counts and sums, by the definitions, so the claims below are about the values that SPM-KERNEL returns.
Lemma 1 (the cells nest). For , every bin of level lies inside exactly one bin of level with the same word, and every bin of level is the union of the four bins of level inside it with the same word.
Proof. Let and the column index at level , and the one at level . We show for . If , then and with , and . If , then and , and . The same holds for the rows. So the level- cell of a feature is a function of its level- cell, and each level- cell contains the four cells , . The word is the same at all levels.
Theorem 1 (the two forms agree). .
Proof. Collect the coefficient of each on the left. appears once, in the term , with . For , appears with in term and with in term , so its coefficient is . appears with alone and in term , so its coefficient is . If both sides are .
Lemma 2 (intersection is a maximum matching). Call a matching at level a set of disjoint pairs such that and are in the same bin of level . Then the largest such matching has exactly pairs.
Proof. The pairs never connect different bins, so a matching is a union of matchings inside the bins. Inside bin any pairing of features with features has at most pairs, and pairing them in any order reaches this number. Summing over the bins gives .
Lemma 3 (monotone). for .
Proof. By Lemma 1, a matching at level pairs features that are in the same bin at level , so also in the same bin at level . So it is also a matching at level , and by Lemma 2 . In terms of counts: if a bin at level splits into bins with counts and , then , since the right side is at most and at most .
So is the number of matches at the finest level, and is the number of matches that a largest matching gains when the cells grow from level to level . The kernel gives weight 1 to the finest matches and to those new at level , as the page says.
Theorem 2 (positive semidefinite). For any finite list of feature sets , the matrix is symmetric and positive semidefinite. The same holds when each histogram is first divided by the number of features of its image.
Proof. Symmetry is clear since is symmetric. For , , where is 1 if the condition holds and 0 otherwise. So for reals and one bin of level , with ,
So is a positive semidefinite kernel for each bin. A sum of positive semidefinite kernels is positive semidefinite, so is one, and so is for . By Theorem 1, has this form with the positive weights and . Dividing the histograms of image by replaces by , and the same argument applies.
Corollary (the concatenated vector). Let be the concatenation, over the levels, of the histograms of level multiplied by and for . Then .
Proof. For , . Summing over the entries of level gives , and Theorem 1 gives the claim.
What is not claimed. The weights are a design choice taken from the pyramid match kernel. Nothing here says that the kernel classifies well; that is a benchmark result.
Complexity
In the real RAM with a hash table or a direct index for the bins, lines L2 and L3 cost per level for features in total, and line L4 costs per level with sparse histograms, since at most bins are nonzero. The whole kernel costs time and space. With dense vectors of length it costs . For classification, an SVM needs the kernel between all pairs of training images, so the Gram matrix costs kernel evaluations. This cost is the main limit of the method at scale.
The cell index needs one multiplication and one floor per level and coordinate. Quantizing the descriptors to words, which comes before this algorithm, costs with a linear scan over centers of dimension .
Properties
- Exact on integers. The weights are powers of and the counts are integers, so the kernel is a dyadic rational. The code uses exact fractions.
- Symmetric and positive semidefinite. So it is a valid SVM kernel. The tests check the Gram matrices of random sets with exact elimination.
- without normalization, and 1 with it. The kernel is largest for identical images when the counts are equal.
- Level 0 is the bag of words. is the histogram intersection of the word histograms.
- Not translation invariant. The grid is fixed to the image frame. An object that moves by half a cell can change the counts of every finer level. This is wanted for scenes, whose layout is fairly stable, and a weakness for objects at random positions.
- The weights are a design choice. The weight of a new match at level follows the pyramid match of Grauman and Darrell. It is a heuristic, not derived from a model of the data.
Variants and improvements
- Pyramid match kernel (Grauman and Darrell 2005). The pyramid is over the descriptor space, with bins that double in width, and there is no image layout. Spatial pyramid matching is the same weighting with the image plane as the space and the words as channels.
- Other features per cell. Any per-cell vector can be pooled in the pyramid, for example HOG like gradient features, Fisher vectors or VLAD. With such vectors the cells are usually concatenated and compared with a linear kernel.
- Other pyramids. A level of horizontal bands is common for scenes, since sky, objects and ground lie in bands.
- Max pooling and sparse coding. Later work replaces the counts by the maximum of soft assignments or of sparse codes over each cell and uses a linear SVM.
- Explicit feature maps. The intersection kernel can be approximated by a finite-dimensional feature map, so that a linear SVM can be trained on large data.
When to use it
Use the spatial pyramid for whole-image classification, especially of scenes, where the layout of a category is stable: sky above, ground below. For object instances at arbitrary positions and scales it helps less, and spatial verification is a better way to use geometry. As a classical pipeline (dense SIFT, words, a pyramid, an SVM) it is a strong baseline. Convolutional networks later replaced it on most benchmarks.
Pitfalls
- Points on the far edge. Without the minimum in the cell index, a point with falls into a cell that does not exist.
- Different image sizes. Use the size of each image for its own cells. The pyramid then compares relative positions, which assumes that the two images frame the scene in a similar way.
- Forgetting the normalization by the number of features. Without it, images with many features get large kernel values with every other image.
- Counting a match twice. Eq. 2 counts each match once, at its finest level. If the weights of Eq. 2 are put on the themselves instead of on the differences, a match found at level is counted again at every coarser level.
- Too many levels. At fine levels the cells hold few features and the intersections are almost zero; they add noise and cost. Lazebnik et al. found little gain beyond on their data, which is a benchmark observation.
Implementations
The Python code builds sparse histograms per level, computes the level intersections and the kernel by Eq. 2 and by Eq. 3, and builds the concatenated weighted vector, all with exact fractions. The tests check the example of this page, the cell rule at the far edge, the agreement of the three forms on random sets, the equality of each with a maximum matching found by augmenting paths, the decrease of with the level, the self kernel, level 0 as the bag of words, and the positive semidefiniteness of Gram matrices by exact elimination.
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/spatial-pyramid-matching/. The authors are listed in prov/QX9B5V.jsonl.
"""Spatial pyramid matching (Lazebnik, Schmid and Ponce, CVPR 2006).
A feature is a triple (u, v, m): a position in a W x H image (u the column,
v the row, 0 <= u <= W and 0 <= v <= H) and a visual word m in 0..M-1.
Level l of the pyramid cuts the image into 2^l x 2^l equal cells; a feature
falls into cell (min(floor(u 2^l / W), 2^l - 1), min(floor(v 2^l / H), 2^l - 1)).
I^l is the histogram intersection of the two images at level l over the bins
(cell, word), and the kernel is
K = I^L + sum_{l=0}^{L-1} (I^l - I^{l+1}) / 2^(L - l).
Histograms are sparse dicts, so the cost is O(n L) for n features, plus the
size of the smaller dict per intersection. Weights are exact Fractions, so
the kernel is exact on integer counts. Standard library only.
"""
from fractions import Fraction
def cell_of(u, v, level, W, H):
"""The cell (cu, cv) of position (u, v) at a level; points on the far edge go to the last cell."""
s = 1 << level
cu = min(int((u * s) // W), s - 1)
cv = min(int((v * s) // H), s - 1)
return cu, cv
def level_histogram(features, level, W, H, weight=1):
"""Sparse histogram {(cu, cv, m): weight times count} of the features at one level."""
h = {}
for u, v, m in features:
key = cell_of(u, v, level, W, H) + (m,)
h[key] = h.get(key, 0) + weight
return h
def intersection(h1, h2):
"""Histogram intersection: the sum over bins of min(h1[b], h2[b])."""
if len(h2) < len(h1):
h1, h2 = h2, h1
return sum(min(c, h2[b]) for b, c in h1.items() if b in h2)
def level_intersections(X, Y, L, W, H, normalize=False):
"""The list I^0, ..., I^L. With normalize, each histogram is divided by its number of features."""
wx = Fraction(1, len(X)) if normalize and X else 1
wy = Fraction(1, len(Y)) if normalize and Y else 1
out = []
for level in range(L + 1): # @line L1
hx = level_histogram(X, level, W, H, wx) # @line L2
hy = level_histogram(Y, level, W, H, wy) # @line L3
out.append(intersection(hx, hy)) # @line L4
return out
def spm_kernel(X, Y, L, W, H, normalize=False):
"""The spatial pyramid match kernel, Eq. (2) of Lazebnik et al."""
I = level_intersections(X, Y, L, W, H, normalize)
kappa = Fraction(I[L]) # @line L5
for level in range(L): # @line L6
kappa += Fraction(I[level] - I[level + 1]) / (1 << (L - level))
return kappa # @line L7
def level_weight(level, L):
"""Weight of level l in Eq. (3): 1/2^L for l = 0, and 1/2^(L - l + 1) for l >= 1."""
if level == 0:
return Fraction(1, 1 << L)
return Fraction(1, 1 << (L - level + 1))
def spm_kernel_eq3(X, Y, L, W, H, normalize=False):
"""The same kernel as a weighted sum of the level intersections, Eq. (3)."""
I = level_intersections(X, Y, L, W, H, normalize)
return sum(level_weight(level, L) * I[level] for level in range(L + 1))
def pyramid_vector(X, M, L, W, H, normalize=False):
"""The concatenated weighted histograms as a dense list of length M (4^(L+1) - 1) / 3.
The histogram intersection of two such vectors is the pyramid kernel.
"""
wx = Fraction(1, len(X)) if normalize and X else 1
out = []
for level in range(L + 1):
s = 1 << level
h = level_histogram(X, level, W, H, wx)
a = level_weight(level, L)
for cv in range(s):
for cu in range(s):
for m in range(M):
out.append(a * h.get((cu, cv, m), 0))
return out
def dense_intersection(p, q):
return sum(min(a, b) for a, b in zip(p, q))
test_spatial_pyramid_matching.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spatial-pyramid-matching/. The authors are listed in prov/QX9B5V.jsonl.
import random
from fractions import Fraction
from spatial_pyramid_matching import (cell_of, dense_intersection, intersection,
level_histogram, level_intersections,
pyramid_vector, spm_kernel, spm_kernel_eq3)
X = [(0.5, 0.5, 0), (1.5, 0.5, 0), (3.5, 3.5, 1), (2.5, 0.5, 1)]
Y = [(0.5, 1.5, 0), (3.5, 0.5, 0), (3.5, 2.5, 1), (0.5, 3.5, 1)]
def random_features(rng, n, M, W, H):
return [(rng.randrange(W), rng.randrange(H), rng.randrange(M)) for _ in range(n)]
def max_matching(X, Y, level, W, H):
"""Brute force: the largest one-to-one matching of X to Y that pairs only
features with the same word in the same cell, by augmenting paths."""
ok = [[cell_of(x[0], x[1], level, W, H) == cell_of(y[0], y[1], level, W, H) and x[2] == y[2]
for y in Y] for x in X]
match_of_y = [-1] * len(Y)
def augment(i, seen):
for j in range(len(Y)):
if ok[i][j] and not seen[j]:
seen[j] = True
if match_of_y[j] < 0 or augment(match_of_y[j], seen):
match_of_y[j] = i
return True
return False
return sum(1 for i in range(len(X)) if augment(i, [False] * len(Y)))
def is_psd(G):
"""Exact test with Fractions: symmetric Gaussian elimination (LDL^T)."""
A = [[Fraction(t) for t in row] for row in G]
n = len(A)
for p in range(n):
if A[p][p] < 0:
return False
if A[p][p] == 0:
if any(A[p][j] != 0 for j in range(p + 1, n)):
return False
continue
for i in range(p + 1, n):
f = A[i][p] / A[p][p]
for j in range(p + 1, n):
A[i][j] -= f * A[p][j]
return True
def test_example_of_the_page():
assert level_intersections(X, Y, 2, 4, 4) == [4, 2, 0]
assert spm_kernel(X, Y, 2, 4, 4) == Fraction(3, 2)
assert spm_kernel(X, Y, 1, 4, 4) == 3
assert spm_kernel(X, X, 2, 4, 4) == 4
assert spm_kernel(X, Y, 2, 4, 4, normalize=True) == Fraction(3, 8)
def test_cell_rule_and_far_edge():
assert cell_of(0, 0, 2, 8, 8) == (0, 0)
assert cell_of(1.99, 2.0, 2, 8, 8) == (0, 1)
assert cell_of(8, 8, 2, 8, 8) == (3, 3)
assert cell_of(7, 3, 0, 8, 8) == (0, 0)
def test_two_forms_and_the_vector_agree():
rng = random.Random(1)
for _ in range(30):
M, L, W, H = rng.randint(1, 4), rng.randint(0, 3), rng.choice([8, 12]), rng.choice([8, 16])
A = random_features(rng, rng.randint(0, 12), M, W, H)
B = random_features(rng, rng.randint(0, 12), M, W, H)
for norm in (False, True):
k2 = spm_kernel(A, B, L, W, H, norm)
assert k2 == spm_kernel_eq3(A, B, L, W, H, norm)
assert k2 == dense_intersection(pyramid_vector(A, M, L, W, H, norm), pyramid_vector(B, M, L, W, H, norm))
def test_intersection_is_a_maximum_matching():
rng = random.Random(2)
for _ in range(40):
M, W, H = rng.randint(1, 3), 8, 8
A = random_features(rng, rng.randint(0, 8), M, W, H)
B = random_features(rng, rng.randint(0, 8), M, W, H)
I = level_intersections(A, B, 3, W, H)
for level in range(4):
assert I[level] == max_matching(A, B, level, W, H)
def test_intersections_decrease_with_the_level():
rng = random.Random(3)
for _ in range(50):
A = random_features(rng, 15, 3, 16, 16)
B = random_features(rng, 15, 3, 16, 16)
I = level_intersections(A, B, 4, 16, 16)
assert all(I[level] >= I[level + 1] for level in range(4))
def test_self_kernel_and_level_zero_is_bag_of_words():
rng = random.Random(4)
A = random_features(rng, 9, 3, 8, 8)
B = random_features(rng, 7, 3, 8, 8)
assert spm_kernel(A, A, 3, 8, 8) == 9
assert spm_kernel(A, A, 3, 8, 8, normalize=True) == 1
bow_a, bow_b = {}, {}
for _, _, m in A:
bow_a[m] = bow_a.get(m, 0) + 1
for _, _, m in B:
bow_b[m] = bow_b.get(m, 0) + 1
assert spm_kernel(A, B, 0, 8, 8) == intersection(bow_a, bow_b)
def test_gram_matrices_are_positive_semidefinite():
rng = random.Random(5)
for _ in range(4):
sets = [random_features(rng, rng.randint(1, 8), 2, 8, 8) for _ in range(7)]
for norm in (False, True):
G = [[spm_kernel(a, b, 2, 8, 8, norm) for b in sets] for a in sets]
assert is_psd(G)
assert not is_psd([[1, 2], [2, 1]])
def test_layout_matters_only_above_level_zero():
moved = [(3.5 - u, 3.5 - v, m) for u, v, m in X]
assert level_intersections(X, moved, 0, 4, 4) == [4]
assert spm_kernel(X, moved, 2, 4, 4) < spm_kernel(X, X, 2, 4, 4)
def test_vector_length():
assert len(pyramid_vector([], 200, 2, 8, 8)) == 4200
assert len(level_histogram(X, 2, 4, 4)) == 4
History
Grauman and Darrell (2005) proposed the pyramid match kernel, an approximate optimal matching of two sets of feature vectors through histograms with bins that double in size. Lazebnik, Schmid and Ponce (2006) applied the same idea to the image plane, with one channel per visual word. On the 15 scene categories data set with words, they report a mean recognition rate of 72.2 percent for the bag of words () and 81.1 percent for the pyramid with , and 64.6 percent on Caltech-101 with 30 training images per class (Section 5). These are benchmark results for their features and training splits. The spatial pyramid then became a standard part of image classification systems, including those built on Fisher vectors and sparse codes.
References
- Svetlana Lazebnik, Cordelia Schmid and Jean Ponce, Beyond bags of features: spatial pyramid matching for recognizing natural scene categories, CVPR 2006, vol. 2, 2169-2178, Section 3.1 (histogram intersection, Eq. 1, and the pyramid match kernel, Eq. 2 and 3), Section 3.2 (one channel per visual word, Eq. 4, and the concatenated weighted histograms), Section 5 (results on the 15 scene categories and Caltech-101)
- Kristen Grauman and Trevor Darrell, The pyramid match kernel: discriminative classification with sets of image features, ICCV 2005, vol. 2, 1458-1465, The pyramid match kernel over a multi-resolution histogram in feature space, and its proof that it is a Mercer kernel
- Jorge Sanchez, Florent Perronnin, Thomas Mensink and Jakob Verbeek, Image classification with the Fisher vector: theory and practice, International Journal of Computer Vision 105(3), 2013, 222-245, The use of spatial pyramids with Fisher vectors
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 6.2, Image classification
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag QX9B5V Edit this page History Report an error Markdown