Algorithmadvanced
Selective search
Also called hierarchical grouping proposals.
Generate object proposals by greedily merging the most similar adjacent regions of an over-segmentation under several color spaces and similarity measures.
- Time
- O(p + n^2 (b + log n)) worst
- Space
- O(p + n b + n^2) extra
- Where
- b = the number of histogram bins; n = the number of initial regions; p = the number of pixels
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Koen E. A. van de Sande, Jasper R. R. Uijlings, Theo Gevers, Arnold W. M. Smeulders, 2011
Selective search finds object proposals by grouping. It starts from many small regions of an over-segmentation, made by Felzenszwalb-Huttenlocher segmentation, and merges the two most similar neighboring regions again and again until one region is left. Every region that appears on the way, small or large, gives one box. Since objects come at all sizes, the hierarchy holds boxes at all sizes. The similarity mixes colour, texture, size and how well two regions fill their joint box. To catch objects that one rule misses, the method runs several grouping strategies, with different colour spaces, similarity mixes and starting segmentations, and combines their boxes. With starting regions one strategy gives boxes for a connected image. R-CNN and Fast R-CNN used it to get about 2000 proposals per image.
In plain words
Cut a photo into many small patches of nearly the same colour. A real object, such as a person, is made of several patches: a face, a shirt, trousers. So keep joining the two neighboring patches that look most alike, and write down the box around each new joined patch. Small patches join first, then bigger parts, and at the end the whole photo is one patch. Each box on the list is a guess where an object could be. Some objects are found by colour, others by texture or by the way their parts fit together, so run the joining several times with different rules and colour views, and merge the lists. The method learns nothing, so it is fast to set up and works for any kind of object.
The problem
The input is an image of pixels and an over-segmentation into regions, given as a label map. Two regions are neighbors when a pixel of one is 4-connected to a pixel of the other. The output is a ranked list of boxes, each the bounding box of a union of regions, that covers as many objects as possible at IoU 0.5 or more, for as few boxes as possible. This is the object proposal problem; there is no exact optimum to compute, so the method is a heuristic. A box is with one past the last column.
The algorithm
For a region let be its pixel count, its box, and its colour histogram: 25 bins per channel, normalized to sum 1. For neighbors and in an image of pixels, the paper defines
where is the box around both, and with each . Each of the four lies in . The size term makes small regions merge first, so that one large region does not eat its neighbors one by one. The fill term prefers pairs that fit well into one box, such as a region and a hole in it.
SELECTIVE-SEARCH(I, R_0, a) ▷ image, initial regions, similarity weights- 1
compute size, box, histogram and neighbors of each region of R_0 - 2
S ← { s(r_i, r_j) : r_i, r_j neighbors in R_0 } ▷ a max-priority queue - 3
L ← the boxes of R_0 - 4
while S is not empty - 5
(r_i, r_j) ← the pair of largest s in S (ties: the smaller pair of ids) - 6
r_t ← r_i ∪ r_j with size_i + size_j, BB_ij and C_t = (size_i C_i + size_j C_j)/(size_i + size_j) - 7
remove from S every pair that holds r_i or r_j - 8
for each neighbor r_k of r_i or r_j, other than r_i and r_j: insert s(r_k, r_t) into S - 9
the neighbors of r_t are those r_k; append the box of r_t to L - 10
return L
Line L6 gets the histogram of the union without reading its pixels: a histogram normalized to sum 1 is the count vector divided by the size, so the size-weighted mean of the two normalized histograms is the normalized count vector of the union. The same holds for the texture histogram of the paper. The code keeps the queue as a binary heap and does line L7 lazily: a popped pair whose regions are gone is skipped.
Diversification. One strategy is one choice of colour space, starting segmentation and weights . The paper uses colour spaces with different invariance properties (RGB, intensity, Lab, rgI, HSV, normalized rg, the opponent space C and the hue H), several values of the parameter of the starting segmentation, and the mixes C+T+S+F, T+S+F, F and S. Its "fast" setting has 8 strategies: HSV and Lab, C+T+S+F and T+S+F, and .
Ranking. Within one hierarchy the region made last, the whole image, gets position 1, the one before it position 2, and so on. Each box gets the score RND times its position, with RND uniform in , the boxes of all strategies are sorted by that score, and duplicates are removed. So large regions tend to come first, but the order is mixed between strategies, and a box found by several strategies has several chances to come early. A budget of proposals takes the first boxes.
Example
Take a grayscale image with a bright top half and a dark bottom half, given with five starting regions:
| row | pixels | labels |
|---|---|---|
| 0 | 200 205 210 205 210 215 | 0 0 0 1 1 1 |
| 1 | 200 205 210 205 210 215 | 0 0 0 1 1 1 |
| 2 | 20 30 100 105 30 40 | 2 2 3 3 4 4 |
| 3 | 20 30 100 110 30 40 | 2 2 3 3 4 4 |
With 25 bins, the bin of a value is . Region 0 has 1/3 of its pixels in bin 19 and 2/3 in bin 20; region 1 has all in bin 20. So . The image has pixels. With all weights 1 (no texture), the neighbor pairs score:
| pair | colour | size | fill | total |
|---|---|---|---|---|
| 0, 1 | 2/3 | 1/2 | 1 | 13/6 |
| 2, 3 | 0 | 2/3 | 1 | 5/3 |
| 3, 4 | 0 | 2/3 | 1 | 5/3 |
| 0, 2 and 1, 4 | 0 | 7/12 | 11/12 | 3/2 |
| 0, 3 and 1, 3 | 0 | 7/12 | 3/4 | 4/3 |
The run goes:
- Merge 0 and 1 into region 5, the top half, box .
- Pairs (2, 3) and (3, 4) tie at 5/3, and the smaller pair wins: merge 2 and 3 into region 6, box , histogram 1/4 in each of the bins 1, 2, 9 and 10.
- Pair (4, 6) scores , since both have a quarter of their pixels in bin 2 and they fill their box exactly. Pairs (5, 6) and (4, 5) score 1. Merge 4 and 6 into region 7, the bottom half.
- Merge 5 and 7 into region 8, the whole image.
The list has boxes. With the size term alone the merges are (2, 3), (1, 4), (0, 5) and (6, 7): the small regions go first.
Correctness
There is no optimal output to compare with, so correctness here means that the code does what lines L1 to L10 say. The claims are proved in the proof page.
- Hierarchy. If the neighbor graph of has connected parts, the loop makes exactly merges and returns boxes, and each box is the bounding box of the union of the starting regions below it. The neighbor sets stay correct after each merge: two current regions are neighbors exactly when some of their starting regions are.
- Exact features. The histogram of line L6 equals the normalized histogram of the pixels of the union, and every similarity lies in for weights in .
- Lazy deletion. The heap version merges the same pairs in the same order as a version that scans all current pairs at each step, since the similarity of a pair of live regions never changes and stale pairs are skipped.
The tests check the first and third claims against a direct computation from the label map and against the scan version, on random label maps.
Proof: Selective search merges each connected part down to one region, keeps exact boxes, histograms and neighbors, and its heap gives the same merges as a full scanfull
Let be the starting regions, given by a label map on an image of pixels with channels, and let be the neighbor graph: two starting regions are joined when a pixel of one is 4-connected to a pixel of the other. Let be the number of connected parts of . The proofs follow lines L1 to L10 of the page and the Python code, where line L7 is done lazily: a popped pair with a region that is no longer alive is skipped.
For a region that the run has made, let be the starting regions below it: for , and when line L6 makes from and . Let be the set of pixels whose label is in . A region is alive from the moment it is made until it is merged. For pixels let be the count vector of the histogram, with bins, so that the histogram of the page is , which sums to 1.
Invariant. Before each pass of line L4, with the set of alive regions:
- the sets for partition ;
- for every , the size of is , its box is the bounding box of , and its histogram is ;
- for every , the neighbor set of is the set of , , such that some region of is joined in to some region of ;
- for every pair of alive neighbors the heap holds exactly one entry whose regions are both alive, and the heap holds no other entry whose regions are both alive.
Proof. By induction on the passes.
Start. Line L1 reads each pixel and its right and lower neighbor, which visits every 4-connected pair of pixels once. The code first makes an empty record for every label and only then adds neighbors, in both directions, so the neighbor sets are those of and are symmetric; this is item 3. Items 1 and 2 hold since each record counts exactly the pixels of its label and the code divides the counts by times the size. Line L2 pushes one entry for each pair of neighbors, which is item 4.
Step. If the popped entry has a region that is not alive, nothing changes except that a stale entry leaves the heap, and items 1 to 4 still hold. Otherwise the entry is with , and by item 4 they are neighbors. Line L6 makes with a new id, larger than every id so far.
- Item 1: replaces and , which keeps a partition.
- Item 2: and are disjoint, so is a disjoint union and . The bounding box of a union of two sets is the box that spans both of their boxes, which is . For the histogram, , so with and ,
The code computes this with exact fractions, so the equality holds exactly.
- Item 3: by item 3 for and for , the set is the set of alive with a region of joined to a region of , which is the correct neighbor set of . The relation in item 3 is symmetric, so an alive is in this set exactly when or is in . For such the code removes and from and adds , which is correct. For any other alive , holds neither nor and gains no new neighbor, so it stays correct. Pairs of alive regions other than and keep their member sets, so their relation does not change.
- Item 4: entries with or are now stale. For each new neighbor of the code pushes , with since is the largest id, and is new, so this entry is the only live one for that pair. Every other live pair was a live pair before, with the same two regions, so its entry is still there and still correct.
Claim 1 (hierarchy). The loop ends after exactly merges, and returns boxes. Each box is the bounding box of the pixels of the starting regions below it.
Proof. Each pass pops one entry, and only a merge pushes entries, at most of them, so the loop ends. By item 3, the graph on whose edges are the neighbor relation is with each set contracted to one vertex. Contracting a connected set of vertices keeps the number of connected parts, and is connected in since it is made by joining neighbors. So this graph always has parts. A merge lowers by 1. The loop ends when the heap is empty, and by item 4 that happens only when no two alive regions are neighbors, that is, when each of the parts is one region. So at the end and there were merges. Line L3 gives boxes and each merge one more, in total. The box claim is item 2.
Claim 2 (similarity ranges). For neighbors and , each of , and lies in , so lies in .
Proof. Histograms are nonnegative and sum to 1, so . Both regions are nonempty and disjoint, so and . The box holds all pixels of both regions and lies in the image, so and the fraction in lies in , which puts in .
Item 2 is why these bounds keep holding after merges: the merged region has the features of its pixels, so it is the same as a starting region with those pixels.
Claim 3 (heap equals scan). The heap version and the version that scans all current neighbor pairs at each step, with the same tie rule, make the same merges with the same ids and return the same boxes.
Proof. The similarity of a pair depends only on the sizes, boxes and histograms of its two regions, and these are set once at line L6 and never changed. So the key of a live entry stays correct for as long as both regions are alive. The scan keeps a table of the live pairs with their similarities and picks the pair with the smallest , that is the largest , then the smaller , then the smaller . The heap orders its entries by the same tuple. By item 4 its live entries are exactly the live pairs with their correct similarities, and a stale entry is dropped without effect, so the first live entry that leaves the heap is the smallest live tuple, which is the pair the scan picks. Both versions then make the same region with the same next id and update neighbors in the same way, so by induction they agree at every step.
Ranking. With position and an independent RND uniform in , the score is uniform in , so a box with a smaller position is more likely to come first, and no order is fixed between strategies. The ranking step then sorts and keeps the first copy of each box, so its output holds each distinct box of the input exactly once. This is the property that the ranking test checks.
Complexity
Line L1 reads each pixel once and costs , plus for the histograms. Each of the at most merges costs for the new histogram, and for each neighbor of the new region, where is the queue size. A region can have up to neighbors, and every push adds one entry to the queue, so and the worst case is in the real RAM model. When each starting region is connected, as with Felzenszwalb-Huttenlocher segments, the neighbor graph is planar, and merging two neighbors keeps it planar, so at every step there are at most neighbor pairs among regions; on real images the degrees stay small, and the merges cost far less than the worst case. Space is for the labels, for the histograms of the regions, and for the queue in the worst case. A run of strategies costs times as much, plus one starting segmentation for each colour space and value of . On a CPU the fast setting takes seconds per image.
Properties
- Deterministic for one strategy. With exact similarities and a fixed tie rule the merges are a function of the input. The ranking across strategies is random by design.
- Not exact. It is a heuristic for a problem with no exact optimum, and a missed object cannot be found later by the detector.
- Class-agnostic and training-free. No part is learned, so it works for any object class. The paper trains a classifier only for the detection step that comes after the proposals.
- Recall over precision. The output holds many boxes that are not objects, by design.
- All scales. The hierarchy has regions of every size, from the starting regions to the image, with no image pyramid.
- Greedy. Each merge is final, as in agglomerative clustering. Unlike single-linkage clustering, the similarity of a merged region is recomputed from its features.
Variants and improvements
- Fast and quality settings. The paper's fast setting (8 strategies, about 2000 boxes per image) and quality setting (80 strategies, about 10000 boxes) trade time for recall.
- Single strategy. A single colour space and one mix of similarities is the cheapest variant and loses some recall.
- Texture. The full method adds , a histogram intersection of SIFT-like histograms of Gaussian derivatives in 8 orientations and 10 bins per channel. The code of this page leaves it out.
- Other starting regions. SLIC superpixels or a watershed can replace the Felzenszwalb-Huttenlocher segments.
- Learned grouping. MCG and similar methods group a contour hierarchy and rank the regions with a learned model. The region proposal network of Faster R-CNN replaced selective search in most detectors, since it shares the network and runs much faster.
When to use it
Use it when a detector needs class-agnostic proposals and no training data for them is at hand, or as a baseline for a proposal method. It suits images where objects differ from the background in colour or texture. Prefer a learned proposal network inside a detector that is trained end to end, and a single-stage detector when speed matters, since selective search takes seconds per image on a CPU.
Pitfalls
- The starting segmentation decides the finest boxes. A region that spans two objects cannot be split later, so an object smaller than the starting regions has no box. Use a small and several values.
- Histograms must be normalized. Unnormalized counts make large regions look similar to everything.
- Neighbor bookkeeping. After a merge, every former neighbor of or must point to . An asymmetric neighbor set, such as one filled while reading the label map in one pass and reset on the first pixel of a region, gives wrong pairs and can make the loop work on dead regions.
- Ties. Small integer images give exact ties, and the merge order then depends on the tie rule. Fix it.
- Duplicates. Different strategies give the same boxes many times. Remove them after the ranking, or the budget fills with copies.
- Proposals near the border and tiny boxes. R-CNN-style detectors often drop boxes below a minimum size; say so when reporting recall.
Implementations
The Python code takes an image (gray or with channels) and a label map, and implements lines L1 to L10 with exact fractions for the histograms and similarities, a heap with lazy deletion, and the tie rule of the smaller pair of ids. It also has a slow version that scans all pairs at each step, the 4-connected components of equal values as a simple source of starting regions, and the ranking by RND times position with removal of duplicates. It does not have the Felzenszwalb-Huttenlocher segmentation, which has its own page, or the texture similarity. The tests check the example above, the heap version against the scan version, the number of merges and every box against the label map, the propagated histogram against one counted from the pixels, the range of the similarities, and the ranking.
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/selective-search/. The authors are listed in prov/RBM5RD.jsonl.
"""Selective search: hierarchical grouping of an over-segmentation into box proposals.
The input is an image (a list of rows; a pixel is an int in 0..255 or a tuple
of such ints, one per channel) and an initial label map of the same size,
where each label is one region. The paper starts from the segmentation of
Felzenszwalb and Huttenlocher; this file only has equal_value_regions, the
4-connected components of equal pixels, as a simple stand-in. Regions are
neighbors when two of their pixels are 4-connected.
The similarity is a_c s_colour + a_s s_size + a_f s_fill with the colour
histograms of the paper (25 bins per channel, L1 normalized, histogram
intersection). The texture similarity of the paper (Gaussian derivatives in
8 orientations) is left out. All similarities are exact Fractions, so ties
are exact and broken by the smaller pair of region ids. A box is
(x1, y1, x2, y2) with x2 = last column + 1. Standard library only.
"""
import heapq
from collections import deque
from fractions import Fraction
BINS = 25
def channels(pixel):
return pixel if isinstance(pixel, tuple) else (pixel,)
def equal_value_regions(image):
"""Label map of the 4-connected components of equal pixel values, labels 0, 1, ..."""
h, w = len(image), len(image[0])
labels = [[-1] * w for _ in range(h)]
nxt = 0
for r in range(h):
for c in range(w):
if labels[r][c] >= 0:
continue
labels[r][c] = nxt
queue = deque([(r, c)])
while queue:
y, x = queue.popleft()
for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
yy, xx = y + dy, x + dx
if 0 <= yy < h and 0 <= xx < w and labels[yy][xx] < 0 and image[yy][xx] == image[y][x]:
labels[yy][xx] = nxt
queue.append((yy, xx))
nxt += 1
return labels
class Region:
__slots__ = ("size", "box", "hist", "nbrs")
def __init__(self, size, box, hist, nbrs):
self.size, self.box, self.hist, self.nbrs = size, box, hist, nbrs
def initial_regions(image, labels):
"""Size, box, normalized colour histogram, neighbors and member set of each initial region."""
h, w = len(image), len(image[0])
nch = len(channels(image[0][0]))
counts, boxes, sizes, nbrs = {}, {}, {}, {}
for r in range(h):
for c in range(w):
k = labels[r][c]
if k not in sizes:
sizes[k], boxes[k], counts[k], nbrs[k] = 0, [c, r, c + 1, r + 1], [0] * (BINS * nch), set()
for r in range(h):
for c in range(w):
k = labels[r][c]
sizes[k] += 1
b = boxes[k]
b[0], b[1], b[2], b[3] = min(b[0], c), min(b[1], r), max(b[2], c + 1), max(b[3], r + 1)
for ch, v in enumerate(channels(image[r][c])):
counts[k][ch * BINS + v * BINS // 256] += 1
for rr, cc in ((r + 1, c), (r, c + 1)):
if rr < h and cc < w and labels[rr][cc] != k:
nbrs[k].add(labels[rr][cc])
nbrs[labels[rr][cc]].add(k)
regions = {}
for k in sizes:
total = sizes[k] * nch
regions[k] = Region(sizes[k], tuple(boxes[k]), [Fraction(n, total) for n in counts[k]],
set(nbrs[k]))
return regions
def box_union(a, b):
return (min(a[0], b[0]), min(a[1], b[1]), max(a[2], b[2]), max(a[3], b[3]))
def box_area(b):
return (b[2] - b[0]) * (b[3] - b[1])
def similarity(ri, rj, im_size, weights):
"""a_c s_colour + a_s s_size + a_f s_fill of two regions (weights in {0, 1} in the paper)."""
ac, a_s, af = weights
s = Fraction(0)
if ac:
s += ac * sum(min(p, q) for p, q in zip(ri.hist, rj.hist))
if a_s:
s += a_s * (1 - Fraction(ri.size + rj.size, im_size))
if af:
s += af * (1 - Fraction(box_area(box_union(ri.box, rj.box)) - ri.size - rj.size, im_size))
return s
def merge(ri, rj, i, j):
"""The union region; the histogram is the size-weighted mean of the two."""
size = ri.size + rj.size
hist = [(ri.size * p + rj.size * q) / size for p, q in zip(ri.hist, rj.hist)]
return Region(size, box_union(ri.box, rj.box), hist, (ri.nbrs | rj.nbrs) - {i, j})
def selective_search(image, labels, weights=(1, 1, 1)):
"""One grouping strategy. Returns (boxes, merges): the boxes of all regions in creation order
(initial regions by label, then each merged region) and the list of merged pairs (i, j, t)."""
im_size = len(image) * len(image[0])
regions = initial_regions(image, labels) # @line L1
heap = []
for i in regions: # @line L2
for j in regions[i].nbrs:
if i < j:
heapq.heappush(heap, (-similarity(regions[i], regions[j], im_size, weights), i, j))
boxes = [regions[k].box for k in sorted(regions)] # @line L3
alive = set(regions)
merges = []
nxt = max(regions) + 1
while heap: # @line L4
neg_s, i, j = heapq.heappop(heap) # @line L5
if i not in alive or j not in alive:
continue # a stale pair: lazy deletion stands for line L7
t = nxt
nxt += 1
rt = merge(regions[i], regions[j], i, j) # @line L6
alive -= {i, j} # @line L7
for k in rt.nbrs:
regions[k].nbrs -= {i, j}
regions[k].nbrs.add(t)
heapq.heappush(heap, (-similarity(regions[k], rt, im_size, weights), k, t)) # @line L8
regions[t] = rt # @line L9
alive.add(t)
boxes.append(rt.box)
merges.append((i, j, t))
return boxes, merges # @line L10
def selective_search_scan(image, labels, weights=(1, 1, 1)):
"""The same grouping with a full scan for the best pair at each step; a slow reference."""
im_size = len(image) * len(image[0])
regions = initial_regions(image, labels)
pairs = {(i, j): similarity(regions[i], regions[j], im_size, weights)
for i in regions for j in regions[i].nbrs if i < j}
boxes = [regions[k].box for k in sorted(regions)]
merges = []
nxt = max(regions) + 1
while pairs:
i, j = min(pairs, key=lambda p: (-pairs[p], p))
t = nxt
nxt += 1
rt = merge(regions[i], regions[j], i, j)
pairs = {p: v for p, v in pairs.items() if i not in p and j not in p}
for k in rt.nbrs:
regions[k].nbrs -= {i, j}
regions[k].nbrs.add(t)
pairs[(k, t)] = similarity(regions[k], rt, im_size, weights)
regions[t] = rt
boxes.append(rt.box)
merges.append((i, j, t))
return boxes, merges
def hierarchy_ranks(boxes, merges, n_initial):
"""Position of each box in its hierarchy: 1 for the last region made, larger lower down.
The paper gives the region at the top of the hierarchy position 1. Here a
region made later gets a smaller number; initial regions come last.
"""
order = list(range(n_initial + len(merges) - 1, -1, -1))
return [(pos + 1, boxes[k]) for pos, k in enumerate(order)]
def rank_proposals(strategy_outputs, rng):
"""Combine strategies: score = RND * position, sort by score, drop duplicate boxes."""
scored = []
for ranked in strategy_outputs:
for pos, box in ranked:
scored.append((rng.random() * pos, box))
scored.sort(key=lambda x: x[0])
seen, out = set(), []
for _, box in scored:
if box not in seen:
seen.add(box)
out.append(box)
return out
test_selective_search.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/selective-search/. The authors are listed in prov/RBM5RD.jsonl.
import random
from fractions import Fraction
from selective_search import (
BINS,
equal_value_regions,
hierarchy_ranks,
initial_regions,
rank_proposals,
selective_search,
selective_search_scan,
similarity,
)
IMG = [[200, 205, 210, 205, 210, 215],
[200, 205, 210, 205, 210, 215],
[20, 30, 100, 105, 30, 40],
[20, 30, 100, 110, 30, 40]]
LAB = [[0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 1, 1],
[2, 2, 3, 3, 4, 4],
[2, 2, 3, 3, 4, 4]]
def random_case(rng, h, w, levels, colour=False):
coarse = [[rng.randrange(levels) for _ in range(w)] for _ in range(h)]
labels = equal_value_regions(coarse)
if colour:
img = [[tuple(rng.randrange(256) for _ in range(3)) for _ in range(w)] for _ in range(h)]
else:
img = [[rng.randrange(256) for _ in range(w)] for _ in range(h)]
return img, labels
def components(labels):
"""The number of connected parts of the region adjacency graph."""
h, w = len(labels), len(labels[0])
parent = {}
def find(x):
while parent.setdefault(x, x) != x:
x = parent[x]
return x
for r in range(h):
for c in range(w):
find(labels[r][c])
for rr, cc in ((r + 1, c), (r, c + 1)):
if rr < h and cc < w:
a, b = find(labels[r][c]), find(labels[rr][cc])
if a != b:
parent[a] = b
return len({find(x) for x in parent})
def test_page_example():
r = initial_regions(IMG, LAB)
assert r[0].hist[19] == Fraction(1, 3) and r[0].hist[20] == Fraction(2, 3)
assert similarity(r[0], r[1], 24, (1, 0, 0)) == Fraction(2, 3)
assert similarity(r[0], r[1], 24, (1, 1, 1)) == Fraction(13, 6)
assert similarity(r[2], r[3], 24, (1, 1, 1)) == Fraction(5, 3)
boxes, merges = selective_search(IMG, LAB)
assert merges == [(0, 1, 5), (2, 3, 6), (4, 6, 7), (5, 7, 8)]
assert boxes[5:] == [(0, 0, 6, 2), (0, 2, 4, 4), (0, 2, 6, 4), (0, 0, 6, 4)]
# Size alone merges the small regions first.
assert selective_search(IMG, LAB, (0, 1, 0))[1] == [(2, 3, 5), (1, 4, 6), (0, 5, 7), (6, 7, 8)]
def test_equal_value_regions():
assert equal_value_regions([[1, 1, 2], [3, 1, 2]]) == [[0, 0, 1], [2, 0, 1]]
def test_heap_matches_full_scan():
rng = random.Random(1)
for k in range(16):
img, labels = random_case(rng, rng.randint(2, 7), rng.randint(2, 7), 3, colour=k % 8 == 0)
for weights in [(1, 1, 1), (1, 0, 0), (0, 0, 1)]:
assert selective_search(img, labels, weights) == selective_search_scan(img, labels, weights)
def test_hierarchy_shape_and_boxes():
rng = random.Random(2)
for _ in range(25):
img, labels = random_case(rng, rng.randint(2, 8), rng.randint(2, 8), 3)
n = 1 + max(max(row) for row in labels)
boxes, merges = selective_search(img, labels)
assert len(merges) == n - components(labels)
assert len(boxes) == n + len(merges)
members = {k: {k} for k in range(n)}
for i, j, t in merges:
assert i in members and j in members
members[t] = members.pop(i) | members.pop(j)
cells = [(r, c) for r in range(len(labels)) for c in range(len(labels[0])) if labels[r][c] in members[t]]
box = (min(c for _, c in cells), min(r for r, _ in cells),
max(c for _, c in cells) + 1, max(r for r, _ in cells) + 1)
assert boxes[t] == box
def test_propagated_histogram_is_exact():
rng = random.Random(3)
for _ in range(20):
img, labels = random_case(rng, 6, 7, 3)
regions = initial_regions(img, labels)
im = 42
ids = sorted(regions)
a, b = ids[0], next(iter(regions[ids[0]].nbrs))
from selective_search import merge
rt = merge(regions[a], regions[b], a, b)
counts = [0] * BINS
size = 0
for r in range(6):
for c in range(7):
if labels[r][c] in (a, b):
counts[img[r][c] * BINS // 256] += 1
size += 1
assert rt.hist == [Fraction(k, size) for k in counts]
assert sum(rt.hist) == 1
assert 0 <= similarity(regions[a], regions[b], im, (1, 0, 0)) <= 1
def test_similarity_ranges():
rng = random.Random(4)
for _ in range(10):
img, labels = random_case(rng, 6, 6, 3, colour=True)
regions = initial_regions(img, labels)
for i in regions:
for j in regions[i].nbrs:
for weights in [(1, 0, 0), (0, 1, 0), (0, 0, 1)]:
s = similarity(regions[i], regions[j], 36, weights)
assert 0 <= s <= 1
def test_ranking_combines_and_dedups():
boxes, merges = selective_search(IMG, LAB)
ranked = hierarchy_ranks(boxes, merges, 5)
assert ranked[0] == (1, (0, 0, 6, 4))
other = hierarchy_ranks(*selective_search(IMG, LAB, (0, 1, 0)), 5)
out = rank_proposals([ranked, other], random.Random(5))
all_boxes = {b for _, b in ranked} | {b for _, b in other}
assert len(out) == len(all_boxes) and set(out) == all_boxes
assert out == rank_proposals([ranked, other], random.Random(5))
History
Before 2011, object detection was mostly done by sliding windows with cheap classifiers, and segmentation was seen as a separate problem. Alexe, Deselaers and Ferrari (2010) scored windows by an objectness measure, and Carreira and Sminchisescu (CPMC) and Endres and Hoiem proposed regions from many figure-ground segmentations. Van de Sande, Uijlings, Gevers and Smeulders presented selective search at ICCV 2011, joining bottom-up grouping with the goal of high recall for detection, and the journal version of 2013 by Uijlings et al. gives the full evaluation. Girshick et al. used its fast mode for R-CNN in 2014, and Fast R-CNN kept it, until the region proposal network of Faster R-CNN in 2015 made proposals part of the network.
References
- Jasper R. R. Uijlings, Koen E. A. van de Sande, Theo Gevers and Arnold W. M. Smeulders, Selective search for object recognition, International Journal of Computer Vision 104(2), 2013, 154-171, Section 3.1, Hierarchical grouping (Algorithm 1); Section 3.2, Diversification strategies (colour spaces, the similarities s_colour, s_texture, s_size and s_fill, starting regions); Section 3.3, Combining locations (the ranking RND times position); Tables 4 and 5
- Pedro F. Felzenszwalb and Daniel P. Huttenlocher, Efficient graph-based image segmentation, International Journal of Computer Vision 59(2), 2004, 167-181, Section 4 (the segmentation used for the initial regions, with its scale parameter k)
- Ross Girshick, Jeff Donahue, Trevor Darrell and Jitendra Malik, Rich feature hierarchies for accurate object detection and semantic segmentation, CVPR 2014, 580-587, Section 2.1, Module design (about 2000 region proposals per image from the fast mode of selective search)
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 6.3, Object detection
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag RBM5RD Edit this page History Report an error Markdown