Algorithmadvanced
Quick shift
Also called quick shift superpixels.
Mode seeking that links each pixel to its nearest neighbor of higher density in joint space and color, which builds a tree whose cut gives superpixels.
- Solves
- Image segmentation
- Time
- O(W H k) worst · average · best
- Space
- O(W H) extra
- Where
- H = the image height in pixels; W = the image width in pixels; k = the number of pixels in the density window and the link window together
- Model
- Real RAM
- Properties
- deterministichierarchicalnot iterativemode seeking
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Andrea Vedaldi, Stefano Soatto, 2008
Quick shift groups the pixels of an image by the modes of a density. It estimates the density of each pixel in the joint space of position and color. Then it links each pixel to the nearest pixel that has a higher density, if that pixel is close enough. The links form a forest, and each tree is one segment, often used as a superpixel. Vedaldi and Soatto (2008) proposed it. Mean shift and mean shift segmentation move each point uphill by many small gradient steps until it stops at a mode. Quick shift makes one jump per pixel, to a real pixel, and never iterates. It is not a gradient method, so the mean shift convergence results do not apply to it, and it does not need them.
In plain words
Think of the image as a landscape. A pixel that has many similar pixels near it is high ground. A pixel that is unlike its neighbors is low ground. Each pixel looks around and points to the closest pixel that stands higher than itself. If no higher pixel is close enough, the pixel is a hilltop.
Follow the arrows from any pixel and you climb until you reach a hilltop. All pixels that end at the same hilltop form one segment. If you allow longer arrows, hilltops join, and you get fewer and larger segments. With no limit on the length, every pixel ends at the highest point, and you get one tree for the whole image.
The problem
The input is an image of pixels. A pixel is , with the column and the row, and it has the gray value (for color, use three values). The output is a partition of the pixels into segments, with a root pixel for each segment. This is a form of image segmentation into many small regions. Quick shift has three parameters:
- , the standard deviation of the Gaussian kernel of the density, in feature units;
- , the largest length of a link, in feature units (VLFeat calls it the maximum distance);
- , the weight of color against position in the feature.
The algorithm
The feature of pixel is . The density is a kernel density estimate with a Gaussian kernel, without the normalizing constant. The sum runs over a square window of radius , outside of which the kernel is below . The key of pixel is the pair , so two pixels with equal densities are ordered by their index .
QUICK-SHIFT(I, sigma, tau, lambda)- 1
for each pixel i do f_i ← (u_i, v_i, lambda · I_i) - 2
for each pixel i do - 3
P_i ← sum of exp(-||f_i - f_j||^2 / (2 sigma^2)) over the pixels j with |u_j - u_i| ≤ ⌈3 sigma⌉ and |v_j - v_i| ≤ ⌈3 sigma⌉ - 4
for each pixel i do - 5
parent_i ← i; d_i ← ∞ - 6
for each pixel j with |u_j - u_i| ≤ ⌈tau⌉ and |v_j - v_i| ≤ ⌈tau⌉, in raster order do - 7
if (P_j, j) > (P_i, i) and ||f_i - f_j|| ≤ tau then - 8
if ||f_i - f_j|| < d_i then parent_i ← j; d_i ← ||f_i - f_j|| - 9
for each pixel i do root_i ← the end of the walk i, parent_i, parent_(parent_i), ... - 10
return root, parent, d
The window of line L6 is large enough: a pixel within feature distance is within in and in . With the window is the whole image.
Example
Take one row of 7 pixels with the values , and , , . The feature of pixel is , and the density window has radius 3. For pixel 1 the window holds pixels 0 to 4, at squared distances 2, 0, 1, 5 and 25, so
| pixel | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| 0 | 1 | 1 | 0 | 5 | 6 | 5 | |
| 1.4611 | 2.05650 | 2.05654 | 1.4611 | 1.5033 | 1.7358 | 1.5032 | |
| parent for | 1 | 2 | 2 (root) | 2 | 5 | 5 (root) | 5 |
| link length | 1 | none | none |
Pixels 1 and 2 have nearly equal densities. Pixel 2 is a little higher, because its window reaches pixels 4 and 5 at squared distances 20 and 34. So pixel 1 links to pixel 2. Pixel 3 has two higher pixels at distance and , and it takes pixel 2. The bright pixel 5 has no higher pixel within distance 2: pixel 2 is at distance . So there are two segments, and .
With , pixel 5 links to pixel 2 with length , and the whole row is one tree. Cut the links longer than 2 in that tree, and the two segments come back. The test file checks all these numbers.
Correctness
The full proof is in proofs/correctness.md. The main steps:
- The window of line L6 holds every pixel within feature distance , so the window search finds the nearest pixel with a larger key within , with ties of distance broken by the smaller index.
- The key strictly increases along each link, and keys are distinct because indices are. So the links have no cycle, every walk reaches a root, and the segments are well defined.
- A pixel is a root exactly when no pixel within distance has a larger key, so roots are local maxima of the density at scale .
- For , the forest for is the forest for with the links longer than cut. So one run with a large gives the segmentations for all smaller values, and they are nested.
These are properties of the procedure. Whether the segments follow object boundaries depends on the image and on , and . That is a heuristic matter, measured on benchmarks.
Proof: Correctness of quick shiftfull
This proof covers lines L1 to L10 of the main page. The input is a gray image of pixels, the kernel width , the link limit (possibly ) and the color weight . Pixel has the feature and the density of line L3. The key of pixel is the pair , compared in lexicographic order. The proof says what the output is. It does not say that the segments match objects; that is a matter of the image and the parameters.
Definition (the quick shift forest). For each pixel , let be the set of pixels with and . If is empty, is a root and . Otherwise is the with the least distance , and among equal distances the least index .
Lemma 1 (the window search finds the defined parent). Lines L4 to L8 set for each pixel .
Proof. If , then and , because these are two of the three coordinates of . The differences are integers, so they are at most , and lies in the square window of line L6. For the window is the whole image. So the loop of L6 visits every member of . Line L7 keeps exactly the members of . The window is visited in raster order, which is increasing index order, and line L8 replaces the best pixel only on a strictly smaller distance. So the loop ends with the nearest member of and, among equal distances, the one with the least index. If is empty, the loop keeps and the distance .
Lemma 2 (the links form a forest). Along each link the key strictly increases. So the links have no cycle, every walk along the links reaches a root after fewer than steps, and each pixel belongs to the tree of exactly one root.
Proof. A link needs by line L7. Keys are pairwise distinct, because the indices are. A cycle would need a key larger than itself. A walk along the links visits pixels with strictly increasing keys, so it visits each pixel at most once and stops at a pixel without a link, which is a root.
Lemma 3 (labels). Line L9 gives each pixel the root of its tree, and line L10 returns the label map of these roots.
Proof. The loop of L9 walks from until it meets a pixel whose root is already known or a root. By Lemma 2 the walk stops. It then gives the found root to every pixel on the walk. Each of these pixels is on the walk from to that root, so the root is correct for all of them. Each pixel enters a walk list at most once, because after that its root is known.
Lemma 4 (roots are local maxima of the density). A pixel is a root if and only if no pixel within feature distance has a larger key. For there is exactly one root, the pixel with the largest key.
Proof. This is the definition of . For every pixel except the one with the largest key has a pixel with a larger key, and all pixels are within distance .
Theorem (one tree gives all the segmentations). Let . For each pixel , if , and otherwise. So cutting the links longer than in the forest for gives the forest for , and each segment for lies inside one segment for .
Proof. The densities do not depend on . . If the nearest member of is within , it is also the nearest member of , with the same tie rule. If it is farther than , every member of is farther than , so is empty and is a root for . Each link of the forest for is a link of the forest for , so each tree for lies inside one tree for .
With the forest is one tree over the whole image (Lemma 4), and the theorem says that the segmentations for all smaller come from it by cutting long links. This is the hierarchy that Vedaldi and Soatto describe.
Cost. Let and . Lines L2 and L3 do work per pixel, and lines L4 to L8 do work per pixel. Line L9 is in total by Lemma 3. With , the total is time in the real-RAM model, with one exponential and one square root counted as , and extra space.
Complexity
Let , the number of pixels in the two windows. Lines L2 and L3 and lines L4 to L8 cost per pixel, and line L9 costs in total if each pixel stores its root once found. The total is time and extra space in the real-RAM model, with an exponential and a square root at unit cost. The cost has no iteration count, unlike mean shift, where each pixel climbs for a number of steps that depends on the data.
Vedaldi and Soatto compare quick shift with medoid shift, which moves each point to the data point that maximizes a local criterion and needs work for points with the Euclidean distance. On an image, the spatial windows make quick shift linear in the number of pixels for fixed and . With the link window is the whole image and the cost is .
Properties
- No iterations. Each pixel computes its density and its parent once.
- Hierarchy. One forest for a large holds the segmentations for all smaller . Cutting links never merges segments.
- Modes are pixels. Each root is a real pixel, a local maximum of the density. Mean shift modes are points of the feature space that need not be pixels.
- No control of the number of segments. The number of roots depends on the image and on and . SLIC asks for a target number of superpixels instead.
- Segments need not be compact. A segment follows the density, so it can be long and thin.
Variants and improvements
- Color images. Use with a color space such as CIELAB. The proof does not change.
- Other features. Quick shift works on any set of points with a distance, not only on images. Then the link search needs a neighbor structure such as a kd-tree instead of a pixel window. Vedaldi and Soatto also give a kernel version, in which the distances come from a kernel matrix.
- Medoid shift. The method that quick shift replaces. Each point moves to the data point with the best local criterion, and the step repeats. It can split one mode into many pieces, which quick shift avoids by linking to any higher point.
- GPU versions. Each pixel computes its density and its parent alone, so the method is easy to run in parallel.
When to use it
Use quick shift when you need superpixels or an over-segmentation as a first step, you can accept segments of irregular size and shape, and you want a method with no iterations and a simple hierarchy over . Use SLIC when you need a set number of compact superpixels, and Felzenszwalb-Huttenlocher segmentation when you need a fast graph-based method with one scale parameter. Use mean shift segmentation when you want the modes in feature space rather than at pixels.
Pitfalls
- Ties. On a flat region many pixels have equal or nearly equal densities. Without a strict tie rule a pixel may have no higher neighbor and become a root, and a flat region breaks into many segments. This page uses the key . Other codes break ties in other ways, so results can differ between libraries.
- Units. and act on the joint feature, so they mix pixels and gray levels. If the gray values are in and the positions in pixels, the color hardly counts unless is large.
- Link window and cost. A large makes the link window large, and the cost grows with . VLFeat says that can be infinite, which gives one tree, but that small values are much faster.
- Segments can be split in space. A link can jump over pixels, up to distance . So a segment is not always 4-connected. Run a connected component pass if the next step needs connected regions.
- Border effects. The density window is cut at the image border, so border pixels get lower densities and are rarely roots.
- Floating point. Two densities that are equal in exact arithmetic can differ in the last bit when they are summed in a different order. This changes the parent of a pixel. Compare densities with care in tests, or use symmetric sums.
Implementations
The Python code in impl/python/quick_shift.py implements lines L1 to L10 for gray images, and a function that cuts the links longer than a given length. The tests compare the window search with a search over all pixels, check that keys increase along links, check that cutting the tree for gives the forest for each smaller , check the example above, and check that adding a constant to the image changes nothing.
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/quick-shift/. The authors are listed in prov/5E6C9Y.jsonl.
"""Quick shift on a gray image.
A pixel (u, v) has the value img[v][u] and the feature f = (u, v, lam * img[v][u]).
The density of a pixel is a sum of Gaussian kernels of standard deviation sigma
over the pixels in a square window of radius ceil(3 sigma). Each pixel links to
the nearest pixel, in feature distance, with a larger key (density, index),
if that pixel is at distance at most tau. Pixels with no link are roots, and
each tree is one segment.
"""
import math
def quick_shift(img, sigma, tau, lam=1.0):
"""Return (labels, parent, dist, dens).
labels[v][u] is the index v * w + u of the root of the tree of (u, v).
parent[i] is the parent of pixel i (i itself for a root), dist[i] is the
feature distance to the parent (inf for a root) and dens[i] the density.
"""
h, w = len(img), len(img[0])
n = w * h
feat = [(u, v, lam * img[v][u]) for v in range(h) for u in range(w)] # @line L1
rs = math.ceil(3 * sigma)
two_s2 = 2.0 * sigma * sigma
dens = [0.0] * n
for i in range(n): # @line L2
u, v, c = feat[i]
s = 0.0
for y in range(max(0, v - rs), min(h, v + rs + 1)):
for x in range(max(0, u - rs), min(w, u + rs + 1)):
fu, fv, fc = feat[y * w + x]
s += math.exp(-((fu - u) ** 2 + (fv - v) ** 2 + (fc - c) ** 2) / two_s2) # @line L3
dens[i] = s
rt = max(w, h) if math.isinf(tau) else math.ceil(tau)
parent = list(range(n))
dist = [math.inf] * n
for i in range(n): # @line L4
u, v, c = feat[i]
best, bj = math.inf, i # @line L5
for y in range(max(0, v - rt), min(h, v + rt + 1)): # @line L6
for x in range(max(0, u - rt), min(w, u + rt + 1)):
j = y * w + x
if (dens[j], j) > (dens[i], i): # @line L7
fu, fv, fc = feat[j]
d = math.sqrt((fu - u) ** 2 + (fv - v) ** 2 + (fc - c) ** 2)
if d <= tau and d < best:
best, bj = d, j # @line L8
parent[i], dist[i] = bj, best
return roots_of(parent, w, h), parent, dist, dens
def roots_of(parent, w, h):
"""Follow the links to the root of each pixel and return the root index as a label map."""
n = w * h
root = [-1] * n
for i in range(n): # @line L9
path = []
j = i
while root[j] < 0 and parent[j] != j:
path.append(j)
j = parent[j]
r = root[j] if root[j] >= 0 else j
root[j] = r
for k in path:
root[k] = r
return [[root[v * w + u] for u in range(w)] for v in range(h)] # @line L10
def cut(parent, dist, t, w, h):
"""Cut every link longer than t and return the label map of the remaining trees."""
p = [j if dist[i] <= t else i for i, j in enumerate(parent)]
return roots_of(p, w, h)
test_quick_shift.py 100 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/quick-shift/. The authors are listed in prov/5E6C9Y.jsonl.
import math
import random
from quick_shift import cut, quick_shift
def brute_parents(img, dens, tau, lam):
"""Search all pixels, not a window, for the nearest pixel with a larger key."""
h, w = len(img), len(img[0])
feat = [(u, v, lam * img[v][u]) for v in range(h) for u in range(w)]
out = []
for i, fi in enumerate(feat):
cands = [(math.dist(fi, fj), j) for j, fj in enumerate(feat) if (dens[j], j) > (dens[i], i)]
cands = [c for c in cands if c[0] <= tau]
out.append(min(cands)[1] if cands else i)
return out
def random_image(rng, w, h, levels):
return [[rng.randrange(levels) for _ in range(w)] for _ in range(h)]
def test_row_example():
img = [[0, 1, 1, 0, 5, 6, 5]]
lab, parent, dist, dens = quick_shift(img, 1.0, 2.0)
expected = [1.4611, 2.0565, 2.0565, 1.4611, 1.5033, 1.7358, 1.5032]
assert all(abs(a - b) < 1e-4 for a, b in zip(dens, expected))
assert 0 < dens[2] - dens[1] < 1e-4 # pixel 2 sees the bright pixels a little more
assert parent == [1, 2, 2, 2, 5, 5, 5]
assert lab == [[2, 2, 2, 2, 5, 5, 5]]
lab, parent, dist, _ = quick_shift(img, 1.0, math.inf)
assert parent == [1, 2, 2, 2, 5, 2, 5]
assert abs(dist[5] - math.sqrt(34)) < 1e-12
assert lab == [[2] * 7]
assert cut(parent, dist, 2.0, 7, 1) == [[2, 2, 2, 2, 5, 5, 5]]
def test_equal_densities_are_broken_by_the_index():
lab, parent, dist, dens = quick_shift([[3, 3]], 1.0, 2.0)
assert dens[0] == dens[1]
assert parent == [1, 1] and dist[0] == 1.0 and lab == [[1, 1]]
def test_window_search_equals_brute_force():
rng = random.Random(7)
for _ in range(12):
img = random_image(rng, 6, 5, 4)
sigma = rng.choice([0.7, 1.0, 1.5])
tau = rng.choice([1.0, 1.5, 2.5, 4.0])
lam = rng.choice([0.5, 1.0, 2.0])
_, parent, _, dens = quick_shift(img, sigma, tau, lam)
assert parent == brute_parents(img, dens, tau, lam)
def test_links_form_a_forest_with_increasing_keys():
rng = random.Random(8)
for _ in range(10):
img = random_image(rng, 7, 6, 5)
lab, parent, dist, dens = quick_shift(img, 1.0, 3.0)
w = 7
for i, j in enumerate(parent):
if j != i:
assert (dens[j], j) > (dens[i], i)
assert dist[i] <= 3.0
else:
assert dist[i] == math.inf
for i in range(len(parent)):
r = lab[i // w][i % w]
assert parent[r] == r
def test_cut_of_the_full_tree_equals_a_smaller_tau():
rng = random.Random(9)
for _ in range(8):
img = random_image(rng, 6, 6, 6)
_, parent, dist, _ = quick_shift(img, 1.0, math.inf)
roots = {r for row in quick_shift(img, 1.0, math.inf)[0] for r in row}
assert len(roots) == 1
for t in (1.0, 1.5, 2.0, 3.0):
assert cut(parent, dist, t, 6, 6) == quick_shift(img, 1.0, t)[0]
def test_two_flat_regions_give_two_segments():
img = [[0] * 4 + [1] * 4 for _ in range(6)]
lab, _, _, _ = quick_shift(img, 2.0, 4.0, lam=10.0)
left = {lab[v][u] for v in range(6) for u in range(4)}
right = {lab[v][u] for v in range(6) for u in range(4, 8)}
assert len(left) == 1 and len(right) == 1 and left != right
def test_adding_a_constant_to_the_image_changes_nothing():
rng = random.Random(10)
img = random_image(rng, 6, 5, 5)
brighter = [[x + 7 for x in row] for row in img]
a = quick_shift(img, 1.0, 2.0)
b = quick_shift(brighter, 1.0, 2.0)
assert a[0] == b[0] and a[1] == b[1]
History
Vedaldi and Soatto (2008) proposed quick shift together with a kernel form of medoid shift. Medoid shift (Sheikh, Khan and Kanade 2007) had replaced the mean shift step by a step to a data point. Quick shift kept the step to a data point and dropped the iteration. The VLFeat library made it a common superpixel method, and later superpixel papers, such as the SLIC paper, compare against it.
References
- Andrea Vedaldi and Stefano Soatto, Quick shift and kernel methods for mode seeking, ECCV 2008, LNCS 5305, 705-718, The sections on medoid shift and quick shift
- VLFeat API documentation, Quick shift image segmentation, Overview and parameters (kernel size and maximum distance)
- Dorin Comaniciu and Peter Meer, Mean shift, a robust approach toward feature space analysis, IEEE TPAMI 24(5), 603-619, 2002, Mean shift segmentation in the joint spatial and range domain
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 5E6C9Y Edit this page History Report an error Markdown