Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 nn starting regions one strategy gives 2n−12n - 1 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 pp pixels and an over-segmentation into nn 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 (x1,y1,x2,y2)(x_1, y_1, x_2, y_2) with x2x_2 one past the last column.

The algorithm

For a region rr let size⁡(r)\operatorname{size}(r) be its pixel count, BB(r)BB(r) its box, and C(r)C(r) its colour histogram: 25 bins per channel, normalized to sum 1. For neighbors rir_i and rjr_j in an image of pp pixels, the paper defines

scolour(ri,rj)=∑kmin⁡(cik,cjk),ssize(ri,rj)=1−size⁡(ri)+size⁡(rj)p,s_{colour}(r_i, r_j) = \sum_{k} \min(c_i^k, c_j^k), \qquad s_{size}(r_i, r_j) = 1 - \frac{\operatorname{size}(r_i) + \operatorname{size}(r_j)}{p},
sfill(ri,rj)=1−size⁡(BBij)−size⁡(ri)−size⁡(rj)p,s_{fill}(r_i, r_j) = 1 - \frac{\operatorname{size}(BB_{ij}) - \operatorname{size}(r_i) - \operatorname{size}(r_j)}{p},

where BBijBB_{ij} is the box around both, and s=a1scolour+a2stexture+a3ssize+a4sfills = a_1 s_{colour} + a_2 s_{texture} + a_3 s_{size} + a_4 s_{fill} with each ak∈{0,1}a_k \in \{0, 1\}. Each of the four lies in [0,1][0, 1]. 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.

  1. SELECTIVE-SEARCH(I, R_0, a) ▷ image, initial regions, similarity weights
  2. 1compute size, box, histogram and neighbors of each region of R_0
  3. 2S ← { s(r_i, r_j) : r_i, r_j neighbors in R_0 } ▷ a max-priority queue
  4. 3L ← the boxes of R_0
  5. 4while S is not empty
  6. 5(r_i, r_j) ← the pair of largest s in S (ties: the smaller pair of ids)
  7. 6r_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)
  8. 7remove from S every pair that holds r_i or r_j
  9. 8for 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
  10. 9the neighbors of r_t are those r_k; append the box of r_t to L
  11. 10return 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 aa. 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 kk 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 k∈{50,100}k \in \{50, 100\}.

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 [0,1][0, 1], 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 NN proposals takes the first NN boxes.

Example

Take a 4×64 \times 6 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 vv is ⌊25v/256⌋\lfloor 25 v / 256 \rfloor. 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 scolour(0,1)=2/3s_{colour}(0, 1) = 2/3. The image has p=24p = 24 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:

  1. Merge 0 and 1 into region 5, the top half, box (0,0,6,2)(0, 0, 6, 2).
  2. Pairs (2, 3) and (3, 4) tie at 5/3, and the smaller pair wins: merge 2 and 3 into region 6, box (0,2,4,4)(0, 2, 4, 4), histogram 1/4 in each of the bins 1, 2, 9 and 10.
  3. Pair (4, 6) scores 1/4+1/2+1=7/41/4 + 1/2 + 1 = 7/4, since both have a quarter of their pixels in bin 2 and they fill their box (0,2,6,4)(0, 2, 6, 4) exactly. Pairs (5, 6) and (4, 5) score 1. Merge 4 and 6 into region 7, the bottom half.
  4. Merge 5 and 7 into region 8, the whole image.

The list has 2⋅5−1=92 \cdot 5 - 1 = 9 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.

  1. Hierarchy. If the neighbor graph of R0R_0 has cc connected parts, the loop makes exactly n−cn - c merges and returns 2n−c2n - c 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.
  2. Exact features. The histogram of line L6 equals the normalized histogram of the pixels of the union, and every similarity lies in [0,1][0, 1] for weights in {0,1}\{0, 1\}.
  3. 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 R0R_0 be the nn starting regions, given by a label map on an image of pp pixels with mm channels, and let G0G_0 be the neighbor graph: two starting regions are joined when a pixel of one is 4-connected to a pixel of the other. Let cc be the number of connected parts of G0G_0. 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 tt that the run has made, let M(t)⊆R0M(t) \subseteq R_0 be the starting regions below it: M(r)={r}M(r) = \{r\} for r∈R0r \in R_0, and M(t)=M(i)∪M(j)M(t) = M(i) \cup M(j) when line L6 makes tt from ii and jj. Let P(t)P(t) be the set of pixels whose label is in M(t)M(t). A region is alive from the moment it is made until it is merged. For pixels PP let h(P)h(P) be the count vector of the histogram, with 25m25m bins, so that the histogram of the page is C(P)=h(P)/(m∣P∣)C(P) = h(P) / (m |P|), which sums to 1.

Invariant. Before each pass of line L4, with AA the set of alive regions:

  1. the sets M(t)M(t) for t∈At \in A partition R0R_0;
  2. for every t∈At \in A, the size of tt is ∣P(t)∣|P(t)|, its box is the bounding box of P(t)P(t), and its histogram is C(P(t))C(P(t));
  3. for every t∈At \in A, the neighbor set of tt is the set of u∈Au \in A, u≠tu \ne t, such that some region of M(t)M(t) is joined in G0G_0 to some region of M(u)M(u);
  4. for every pair u<vu < v of alive neighbors the heap holds exactly one entry (−s(u,v),u,v)(-s(u, v), u, v) 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 G0G_0 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 mm times the size. Line L2 pushes one entry for each pair i<ji < j 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 (−s(i,j),i,j)(-s(i, j), i, j) with i,j∈Ai, j \in A, and by item 4 they are neighbors. Line L6 makes tt with a new id, larger than every id so far.

  • Item 1: M(t)=M(i)∪M(j)M(t) = M(i) \cup M(j) replaces M(i)M(i) and M(j)M(j), which keeps a partition.
  • Item 2: M(i)M(i) and M(j)M(j) are disjoint, so P(t)=P(i)∪P(j)P(t) = P(i) \cup P(j) is a disjoint union and ∣P(t)∣=∣P(i)∣+∣P(j)∣|P(t)| = |P(i)| + |P(j)|. The bounding box of a union of two sets is the box that spans both of their boxes, which is BBijBB_{ij}. For the histogram, h(P(t))=h(P(i))+h(P(j))h(P(t)) = h(P(i)) + h(P(j)), so with si=∣P(i)∣s_i = |P(i)| and sj=∣P(j)∣s_j = |P(j)|,
siC(P(i))+sjC(P(j))si+sj=h(P(i))/m+h(P(j))/msi+sj=h(P(t))m∣P(t)∣=C(P(t)).\frac{s_i C(P(i)) + s_j C(P(j))}{s_i + s_j} = \frac{h(P(i)) / m + h(P(j)) / m}{s_i + s_j} = \frac{h(P(t))}{m |P(t)|} = C(P(t)).

The code computes this with exact fractions, so the equality holds exactly.

  • Item 3: by item 3 for ii and for jj, the set (N(i)∪N(j))∖{i,j}(N(i) \cup N(j)) \setminus \{i, j\} is the set of alive u≠i,ju \ne i, j with a region of M(u)M(u) joined to a region of M(i)∪M(j)=M(t)M(i) \cup M(j) = M(t), which is the correct neighbor set of tt. The relation in item 3 is symmetric, so an alive kk is in this set exactly when ii or jj is in N(k)N(k). For such kk the code removes ii and jj from N(k)N(k) and adds tt, which is correct. For any other alive kk, N(k)N(k) holds neither ii nor jj and gains no new neighbor, so it stays correct. Pairs of alive regions other than ii and jj keep their member sets, so their relation does not change.
  • Item 4: entries with ii or jj are now stale. For each new neighbor kk of tt the code pushes (−s(k,t),k,t)(-s(k, t), k, t), with k<tk < t since tt is the largest id, and tt 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. □\square

Claim 1 (hierarchy). The loop ends after exactly n−cn - c merges, and returns 2n−c2n - c 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 nn of them, so the loop ends. By item 3, the graph on AA whose edges are the neighbor relation is G0G_0 with each set M(t)M(t) contracted to one vertex. Contracting a connected set of vertices keeps the number of connected parts, and M(t)M(t) is connected in G0G_0 since it is made by joining neighbors. So this graph always has cc parts. A merge lowers ∣A∣|A| 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 cc parts is one region. So ∣A∣=c|A| = c at the end and there were n−cn - c merges. Line L3 gives nn boxes and each merge one more, 2n−c2n - c in total. The box claim is item 2. □\square

Claim 2 (similarity ranges). For neighbors rir_i and rjr_j, each of scolours_{colour}, ssizes_{size} and sfills_{fill} lies in [0,1][0, 1], so ss lies in [0,a1+a3+a4][0, a_1 + a_3 + a_4].

Proof. Histograms are nonnegative and sum to 1, so 0≤∑kmin⁡(cik,cjk)≤∑kcik=10 \le \sum_k \min(c_i^k, c_j^k) \le \sum_k c_i^k = 1. Both regions are nonempty and disjoint, so 2≤si+sj≤p2 \le s_i + s_j \le p and 0≤1−(si+sj)/p<10 \le 1 - (s_i + s_j)/p < 1. The box BBijBB_{ij} holds all pixels of both regions and lies in the image, so si+sj≤size⁡(BBij)≤ps_i + s_j \le \operatorname{size}(BB_{ij}) \le p and the fraction in sfills_{fill} lies in [0,1)[0, 1), which puts sfills_{fill} in (0,1](0, 1]. □\square

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 (−s,i,j)(-s, i, j), that is the largest ss, then the smaller ii, then the smaller jj. 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. □\square

Ranking. With position q≥1q \ge 1 and an independent RND uniform in [0,1][0, 1], the score RND⋅q\text{RND} \cdot q is uniform in [0,q][0, q], 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 O(p)O(p), plus O(nb)O(nb) for the histograms. Each of the at most n−1n - 1 merges costs O(b)O(b) for the new histogram, and O(b+log⁡Q)O(b + \log Q) for each neighbor of the new region, where QQ is the queue size. A region can have up to n−1n - 1 neighbors, and every push adds one entry to the queue, so Q=O(n2)Q = O(n^2) and the worst case is O(p+n2(b+log⁡n))O(p + n^2 (b + \log n)) 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 3m−63m - 6 neighbor pairs among mm regions; on real images the degrees stay small, and the merges cost far less than the worst case. Space is O(p)O(p) for the labels, O(nb)O(nb) for the histograms of the 2n−12n - 1 regions, and O(n2)O(n^2) for the queue in the worst case. A run of ss strategies costs ss times as much, plus one starting segmentation for each colour space and value of kk. 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 stextures_{texture}, 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 kk 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 rir_i or rjr_j must point to rtr_t. 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.

selective_search.pyI0RawGitHub
# 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

  1. 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
  2. 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)
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
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)
WritingW2 basic
  • a scene preset for the example