Algorithmcore
Maximally stable extremal regions
Also called MSER.
Find connected regions of a thresholded image whose area changes least as the threshold moves, computed for all thresholds with a union-find sweep.
- Solves
- Feature detection
- Time
- O(N α(N) + M T) worst · average · best
- Space
- O(N + M T) extra
- Where
- M = the number of gray levels; N = the number of pixels; T = the number of tracks (at most N)
- Model
- Word RAM
- Properties
- affine covariant regionsdeterministicexactheuristicinvariant to intensity offset
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jiri Matas, Ondrej Chum, Martin Urban, Tomas Pajdla, 2002
Maximally stable extremal regions (MSER) solve feature detection by finding regions instead of points. Threshold a gray image at a level : the pixels with form connected components, the dark extremal regions, and the pixels with form the bright ones. As rises, dark regions appear, grow and merge. A region is maximally stable when its area changes least, relative to its size, as the threshold moves by . These regions have sharp borders of high contrast, and a change of viewpoint that maps the scene by an affine map, or by any continuous map, carries each region to the corresponding region in the other view. One sweep over the levels with a disjoint-set forest finds the regions at all thresholds. With pixels, gray levels and tracks of nested regions, the cost is .
In plain words
Think of the image as a landscape, where dark pixels are low and bright pixels are high. Fill it with water slowly. Lakes appear in the low places, grow, and join when the water passes over the ridges between them. Some lakes stay almost the same size while the water rises a lot, because steep walls hold them. Those lakes are the regions we want: their shape depends on the scene, not on the exact water level. The method notes the size of every lake at every water level in one pass, and then picks each lake at the level where its size changes most slowly. Doing the same with the image turned upside down gives the bright regions.
The problem
The input is a gray digital image with pixels and integer values in . A pixel has coordinates : is the column and goes right, is the row and goes down. Two pixels are neighbours when they share a side (4-connectivity). The parameters are the step , the smallest and largest area and , and an optional largest variation .
A dark extremal region at level is a connected component of . Two such regions are either disjoint or nested, so they form a tree, the component tree. This page follows the regions along tracks. A track starts when a new component appears. When components merge at level , the track whose region had the larger area at level continues with the merged region, and the older track wins a tie; the other tracks end at . Let be the area of the region of track at level , with before the track starts, and let be the area of the region at level that contains it. The stability of the region is
This is the measure of Matas and others, applied along a track. The output is each region where has a strict local minimum along its track, with and ; a run of equal values that is lower than both neighbours counts once, at its first level. Each region is reported as its level and a seed pixel, the first pixel of its track. The bright regions are the dark regions of .
The algorithm
MSER(I, Δ, a_min, a_max, v_max) ▷ I has N pixels with values in 0, …, M - 1- 1
sort the pixels by gray level with counting sort - 2
for g ← 0 to M - 1 do - 3
for each pixel p with I(p) = g, in index order do - 4
make p a set of its own; R ← the distinct sets of its 4-neighbours that are already added - 5
if R is empty then start a new track with seed p and birth g - 6
else join p and all sets of R; the track with the largest a(g - 1) continues (the older on ties) and the others end at g - 1 - 7
for each live track T do a_T(g) ← the size of its set - 8
for each track T and each g from its birth to min(its end, M - 1 - Δ) do q_T(g) ← (A_T(g + Δ) - a_T(g - Δ)) / a_T(g) - 9
for each run of equal values of q_T with larger values on both sides do report (first level of the run, seed of T) if a_min ≤ a_T ≤ a_max and q_T ≤ v_max - 10
do the same for M - 1 - I to get the bright regions, and return all regions
Line L1 is a counting sort, . Lines L3 to L6 are the union-find form of connected component labeling, run once while the threshold rises: each pixel is added once and joined with its neighbours. A track that ended at level was absorbed by another track, so follows these links until it reaches the track that is live at . Line L9 compares exact fractions. The region of a reported pair is the component of that contains ; any flood fill gets its pixels.
Example
Take a image with background , a square of at , a square of inside it at , the pixel set to , and two lone pixels, at and at . Take . The track that starts at has the area for , for , for (the square of side 6 and the lone pixel next to it), and from on. Its stability is:
| 30 to 39 | 40 to 49 | 50 to 109 | 110 to 119 | 120 to 129 | 130 to 189 | 190 to 199 | 200 to 209 | 210 to 245 | |
|---|---|---|---|---|---|---|---|---|---|
| 9 | 8/9 | 0 | 28/9 | 28/37 | 0 | 63/37 | 63/100 | 0 |
The two runs of with larger values on both sides give the dark regions at , the square with area , and at , the pixels of the large square and the pixel. The last run reaches the top of the range of , so it has no larger value on its right and gives no region. The lone pixels give the dark regions at and at , each with area . The bright regions, of , have the areas , , and , at , , and . With and only the two squares remain.
Correctness
The proof in proofs/correctness.md shows that after level the sets of the forest are exactly the connected components of , that each live track holds one of them and contains its seed, and that the recorded areas and the values of are the ones of the definition. The selection of line L9 then reports exactly the strict local minima along each track. Two invariance facts follow from the definition. The set of extremal regions does not change under a strictly increasing change of the gray values; adding a constant to the image shifts every level and leaves the result the same. And a continuous one-to-one map of the image plane maps connected components to connected components and keeps the order of inclusion, so a region in one view maps to the corresponding region in the other view. The areas change by the same factor under an affine map, so and the selection do not change.
Proof: Correctness of the MSER sweepfull
We prove that the sweep of lines L1 to L7 builds the connected components of every threshold set, that the tracks and their areas are the ones of the definition, and that lines L8 and L9 report exactly the maximally stable regions. Write and call a connected component of a region at level .
Lemma 1 (the forest). After the pixels of level have been processed, the sets of the disjoint-set forest are exactly the regions at level .
Proof. By induction on . Before level no pixel is added and is empty. Assume the claim after level . Line L1 sorts by gray level, so at level lines L3 and L4 add exactly the pixels of . Each added pixel is joined with the sets of all its neighbours that are already added. Two pixels of are in one region exactly when a path of neighbours in joins them. Every step of such a path is an edge between two pixels of , and when the later of its two pixels is added, the earlier one is already added, so line L6 joins their sets. So every region is inside one set. Conversely, every join is along an edge between two pixels of , so every set is connected in . After the last pixel of level the sets are the regions at level .
Lemma 2 (the tracks). After level , each set of the forest belongs to exactly one live track, and that track's seed is in the set. Line L7 records , the size of the region of at level .
Proof. A new set from line L5 gets a new track whose seed is its only pixel. When line L6 joins sets, the merged set takes the track of one of them, and that track's seed is in the merged set; the other tracks are no longer live. No other line changes sets or tracks. So the claim holds after each pixel, and line L7 reads the size of the set of each live track, which by Lemma 1 is a region at level .
The choice of line L6 uses , the last area recorded for each track before level , which is for a track born at level . This choice does not depend on the order in which the joins of level happen: the continuing track of a group of sets is the one with the largest pair , and taking a maximum of pairs is associative. So the tracks are a function of the image alone. A new track born at level gets its index in the order of its seed, and its seed is the first pixel of its region in index order, because that pixel has no added neighbour inside the region when it is added.
Lemma 3 (the stability values). For each track and each level from the birth of to , line L8 computes , where is the area of the region at level that contains the region of at level .
Proof. and are read from the areas recorded by line L7, with before the birth. For : regions at different levels are nested, so the region at level that contains the region of at is the one that contains the seed of . If is live at , this is the region of by Lemma 2. Otherwise ended at a level and was joined, at level , into the set of a track , which contains the seed of from then on. Following the links reaches the track that is live at and whose set holds the seed of , and its recorded area is . Each link goes to a track that ends later, so the walk stops. The value is a quotient of two integers with , computed exactly.
Theorem. MSER returns exactly the pairs (level, seed) such that the region of a track at level is the first level of a maximal run of equal values of , both neighbouring values along the track exist and are larger, and ; it does this for and for . The returned region of a pair is the component of that contains for a dark region, and the component of that contains for a bright one.
Proof. By Lemma 3 the values are exact. Line L9 walks the values of each track in the order of and splits them into maximal runs of equal values. A run is reported, at its first level, exactly when it has a value on each side and both are larger, and when the area and variation filters hold; nothing else is reported. By Lemma 2 the region of at level is the component of that holds the seed. For the bright regions, line L10 runs the same steps on , whose values are again in . The set is , so the region found at level of is the bright region at level of , which is the level that is returned.
Complexity
The model is the word RAM, with gray levels that fit in a word.
- Line L1 is .
- Lines L3 to L6 make additions and at most find operations with union by size and path compression, in total. Choosing the continuing track is per neighbour.
- Line L7 runs once per level for each live track. A track is live for at most levels, so this is .
- Lines L8 and L9 do work per recorded area, plus the links followed for , which is over all tracks.
The total is , with space for the forest and the areas. For 8-bit images . Recording areas only at the levels where a track changes, as most implementations do, removes the factor . Nister and Stewenius give an algorithm in linear time that processes the pixels in the order of a flood fill and needs only one stack of components.
Properties
- Regions, not points. Each MSER is a set of pixels of any shape. For matching, an ellipse with the same second moments is fitted, and a descriptor is computed on the normalized ellipse.
- Affine covariance. The regions follow any continuous one-to-one change of the image plane, so in particular affine maps. No iteration is needed, unlike the Harris-affine detector.
- Intensity. The extremal regions are the same under any strictly increasing change of the gray values. The selection depends on in gray levels, so an offset does not change it and a change of contrast can.
- Nested results. Regions from one track or from nested tracks can be nested or almost equal. Many implementations remove regions that are too similar to their parent.
- Exact. For a given image and parameters, the result follows from the definition without any approximation, since all values are integers and fractions.
Variants and improvements
- Linear time MSER. Nister and Stewenius flood the image from one pixel and keep a stack of growing components, so the time is linear in and the memory is small.
- Diversity filter. Drop a region when its parent region has almost the same area. This removes most duplicates.
- Color MSER. Grow regions on a color image by joining neighbours in the order of their color distance, instead of the gray value.
- Ellipse fit. Report the mean and covariance of the pixels of each region, which give an affine frame for a descriptor.
- Other stability measures. Use only the change above, , as several libraries do. This changes which levels are chosen but not the set of extremal regions.
When to use it
Use it for matching images of flat or almost flat objects under large changes of viewpoint, such as buildings, signs and documents, and for finding text, where letters are often stable dark or bright regions. It is fast, needs no smoothing and gives few, distinct regions. On images of natural scenes with soft texture and blur, the regions are less stable, and corner or blob detectors such as SIFT find more useful points.
Pitfalls
- Only one polarity. Dark and bright regions need two sweeps, on and on .
- Connectivity. 4-connectivity and 8-connectivity give different regions. Use the same one in all views.
- Blur. A blurred border makes the area grow steadily with , and no level is stable. Small or blurred structures are lost.
- Too small a . With few gray levels between neighbour regions, the stability is undefined or noisy. With , values from 5 to 10 are common.
- Huge regions. The background and its big parts are stable too. Set , for example to a fraction of the image.
- Plateaus. Many levels can have the same . Report one region per run of equal values, or the same region comes out many times.
Implementations
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/maximally-stable-extremal-regions/. The authors are listed in prov/C7478H.jsonl.
"""Maximally stable extremal regions (MSER) with a union-find sweep over the gray levels.
An image is a list of H rows of W integers in 0, ..., M - 1; pixel (u, v) is
img[v][u], with u the column and v the row. Regions are 4-connected.
A dark extremal region at level g is a connected component of the pixels with
I <= g. Raising g grows and merges these components. A track is a chain of
regions, one per level: it starts when a component appears, and at a merge the
track whose region had the larger area at level g - 1 continues (the older
track on ties). With a_T(g) the area of track T at level g (0 before the track
starts), and A(g + delta) the area of the region at level g + delta that
contains it,
q_T(g) = (A(g + delta) - a_T(g - delta)) / a_T(g).
A region is maximally stable when q_T has a strict local minimum there along
the track; a run of equal values that is lower than both of its neighbours
counts once, at its first level. Bright regions are the dark regions of
M - 1 - I.
"""
from fractions import Fraction
from typing import List, Optional, Sequence, Tuple
Region = Tuple[str, int, int, int, int] # (polarity, level, u, v, area)
def _find(parent: List[int], x: int) -> int:
root = x
while parent[root] != root:
root = parent[root]
while parent[x] != root:
parent[x], x = root, parent[x]
return root
def sweep(img: Sequence[Sequence[int]], levels: int):
"""Build the tracks of the dark extremal regions.
Returns (births, seeds, ends, absorbed, areas): track t lives from births[t]
to ends[t], its region at level g is the component of {I <= g} that holds
pixel seeds[t] (an index v * W + u), it has the area areas[t][g - births[t]],
and after ends[t] it is part of track absorbed[t].
"""
h, w = len(img), len(img[0])
n = h * w
buckets: List[List[int]] = [[] for _ in range(levels)]
for idx in range(n): # @line L1
buckets[img[idx // w][idx % w]].append(idx)
parent = [-1] * n
size = [0] * n
track_of = [0] * n
births, seeds, ends, absorbed, areas = [], [], [], [], []
live = []
def prev_area(t: int, g: int) -> int:
return areas[t][-1] if births[t] < g and areas[t] else 0
for g in range(levels): # @line L2
for p in buckets[g]: # @line L3
parent[p], size[p] = p, 1 # @line L4
u, v = p % w, p // w
roots = []
for q, ok in ((p - 1, u > 0), (p + 1, u < w - 1), (p - w, v > 0), (p + w, v < h - 1)):
if ok and parent[q] != -1:
r = _find(parent, q)
if r not in roots:
roots.append(r)
if not roots: # @line L5
track_of[p] = len(births)
births.append(g)
seeds.append(p)
ends.append(levels - 1)
absorbed.append(-1)
areas.append([])
live.append(track_of[p])
continue
tracks = [track_of[r] for r in roots]
best = max(tracks, key=lambda t: (prev_area(t, g), -t)) # @line L6
root = max(roots, key=lambda r: size[r])
for r in roots:
if r != root:
parent[r] = root
size[root] += size[r]
parent[p] = root
size[root] += 1
track_of[root] = best
for t in tracks:
if t != best:
ends[t], absorbed[t] = g - 1, best
live.remove(t)
for t in live: # @line L7
areas[t].append(size[_find(parent, seeds[t])])
return births, seeds, ends, absorbed, areas
def _area_at(births, ends, absorbed, areas, t: int, g: int) -> int:
while ends[t] < g:
t = absorbed[t]
return areas[t][g - births[t]]
def dark_regions(img: Sequence[Sequence[int]], delta: int, levels: int) -> List[Tuple[int, int, int, Fraction]]:
"""All maximally stable dark regions as (level, seed index, area, q), without filters."""
births, seeds, ends, absorbed, areas = sweep(img, levels)
out = []
for t in range(len(births)):
lo, hi = births[t], min(ends[t], levels - 1 - delta)
if hi - lo < 2:
continue
q = {}
for g in range(lo, hi + 1): # @line L8
big = _area_at(births, ends, absorbed, areas, t, g + delta)
small = areas[t][g - delta - births[t]] if g - delta >= births[t] else 0
q[g] = Fraction(big - small, areas[t][g - births[t]])
g = lo + 1
while g < hi: # @line L9
end = g
while end + 1 <= hi and q[end + 1] == q[g]:
end += 1
if end < hi and q[g - 1] > q[g] and q[end + 1] > q[g]:
out.append((g, seeds[t], areas[t][g - births[t]], q[g]))
g = end + 1
return out
def mser(img: Sequence[Sequence[int]], delta: int = 5, min_area: int = 1, max_area: Optional[int] = None,
max_variation: Optional[Fraction] = None, levels: int = 256) -> List[Region]:
"""Return the dark and bright MSERs as (polarity, level, u, v, area), sorted.
A dark region is the 4-connected component of {I <= level} that holds (u, v);
a bright region is the component of {I >= level} that holds (u, v).
Precondition: img is a non-empty rectangle of integers in 0, ..., levels - 1, delta >= 1.
"""
w = len(img[0])
max_area = len(img) * w if max_area is None else max_area
found = []
for polarity in ("dark", "bright"):
src = img if polarity == "dark" else [[levels - 1 - x for x in row] for row in img]
for g, seed, area, q in dark_regions(src, delta, levels):
if min_area <= area <= max_area and (max_variation is None or q <= max_variation):
level = g if polarity == "dark" else levels - 1 - g
found.append((polarity, level, seed % w, seed // w, area))
return sorted(found) # @line L10
test_maximally_stable_extremal_regions.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximally-stable-extremal-regions/. The authors are listed in prov/C7478H.jsonl.
import random
from fractions import Fraction
from maximally_stable_extremal_regions import dark_regions, mser
def component(img, seed, inside):
"""The 4-connected component of the pixels where inside(value) holds that contains seed, by BFS."""
h, w = len(img), len(img[0])
if not inside(img[seed // w][seed % w]):
return frozenset()
seen, stack = {seed}, [seed]
while stack:
p = stack.pop()
u, v = p % w, p // w
for q, ok in ((p - 1, u > 0), (p + 1, u < w - 1), (p - w, v > 0), (p + w, v < h - 1)):
if ok and q not in seen and inside(img[q // w][q % w]):
seen.add(q)
stack.append(q)
return frozenset(seen)
def oracle(img, delta, levels):
"""Maximally stable dark regions from the definition, with components found by BFS at every level."""
h, w = len(img), len(img[0])
comps = []
for g in range(levels):
done, level = set(), []
for p in range(h * w):
if p not in done and img[p // w][p % w] <= g:
c = component(img, p, lambda x, g=g: x <= g)
done |= c
level.append(c)
comps.append(level)
tracks = {} # key (birth, seed) -> {level: region}
current = {} # region at the previous level -> key
for g in range(levels):
nxt = {}
for c in comps[g]:
children = [d for d in current if d <= c]
if not children:
key = (g, min(c))
tracks[key] = {}
else:
key = min((current[d] for d in children),
key=lambda k: (-len(next(d for d in children if current[d] == k)), k))
tracks[key][g] = c
nxt[c] = key
current = nxt
out = []
for (birth, seed), regs in tracks.items():
last = max(regs)
q = {}
for g in range(birth, min(last, levels - 1 - delta) + 1):
big = len(component(img, seed, lambda x: x <= g + delta))
small = len(regs[g - delta]) if g - delta >= birth else 0
q[g] = Fraction(big - small, len(regs[g]))
gs = sorted(q)
for i in range(1, len(gs) - 1):
g = gs[i]
if q[gs[i - 1]] <= q[g]:
continue
j = i
while j + 1 < len(gs) and q[gs[j + 1]] == q[g]:
j += 1
if j + 1 < len(gs) and q[gs[j + 1]] > q[g]:
out.append((g, seed, len(regs[g]), q[g]))
return sorted(out)
def example():
img = [[200] * 10 for _ in range(10)]
for v in range(2, 8):
for u in range(2, 8):
img[v][u] = 120
for v in range(3, 6):
for u in range(3, 6):
img[v][u] = 40
img[4][4] = 30
img[6][8] = 90
img[8][1] = 150
return img
def pixel_set(img, region, levels=256):
pol, level, u, v, _ = region
inside = (lambda x: x <= level) if pol == "dark" else (lambda x: x >= level)
return component(img, v * len(img[0]) + u, inside)
def test_against_the_definition():
rng = random.Random(2002)
for _ in range(600):
h, w, levels = rng.randint(1, 5), rng.randint(1, 5), rng.randint(4, 12)
img = [[rng.randrange(levels) for _ in range(w)] for _ in range(h)]
delta = rng.randint(1, 3)
assert sorted(dark_regions(img, delta, levels)) == oracle(img, delta, levels)
def test_regions_are_the_reported_components():
rng = random.Random(5)
for _ in range(100):
img = [[rng.randrange(8) for _ in range(6)] for _ in range(5)]
for r in mser(img, delta=1, levels=8):
assert len(pixel_set(img, r)) == r[4]
def test_worked_example():
img = example()
assert mser(img, delta=10) == [
("bright", 80, 0, 0, 91), ("bright", 110, 0, 0, 90), ("bright", 140, 0, 0, 63), ("bright", 190, 0, 0, 62),
("dark", 50, 4, 4, 9), ("dark", 100, 8, 6, 1), ("dark", 130, 4, 4, 37), ("dark", 160, 1, 8, 1)]
q = {g: v for g, _, _, v in dark_regions(img, 10, 256)}
assert q[50] == 0 and q[130] == 0
assert mser(img, delta=10, min_area=4, max_area=50) == [("dark", 50, 4, 4, 9), ("dark", 130, 4, 4, 37)]
def test_flat_image_and_single_pixel():
assert mser([[7] * 5 for _ in range(4)], delta=2) == []
assert mser([[3]], delta=1, levels=8) == []
def test_offset_and_rotation():
img = example()
shifted = [[x + 10 for x in row] for row in img]
a = [(p, lv + 10, u, v, s) for p, lv, u, v, s in mser(img, delta=10)]
assert mser(shifted, delta=10) == a
h, w = len(img), len(img[0])
rot = [[img[h - 1 - j][i] for j in range(h)] for i in range(w)]
sets = {(r[0], r[1], frozenset((p % w, p // w) for p in pixel_set(img, r))) for r in mser(img, delta=10)}
rsets = set()
for r in mser(rot, delta=10):
# rot pixel (u', v') holds img pixel (v', h - 1 - u')
rsets.add((r[0], r[1], frozenset((p // h, h - 1 - p % h) for p in pixel_set(rot, r))))
assert sets == rsets
History
Jiri Matas, Ondrej Chum, Martin Urban and Tomas Pajdla introduced maximally stable extremal regions at BMVC 2002, to find correspondences in wide-baseline stereo, and published the journal version in 2004. They enumerate the extremal regions with a union-find structure over the pixels sorted by gray level, as in the flooding view of the watershed transform. In the 2005 comparison of affine region detectors by Mikolajczyk and others, MSER was one of the six detectors studied. David Nister and Henrik Stewenius gave a linear time algorithm in 2008.
References
- Jiri Matas, Ondrej Chum, Martin Urban and Tomas Pajdla, Robust wide baseline stereo from maximally stable extremal regions, Proceedings of the British Machine Vision Conference (BMVC 2002), 384-393, 2002, the section on maximally stable extremal regions (the definition of extremal regions, the stability measure and the enumeration algorithm)
- Jiri Matas, Ondrej Chum, Martin Urban and Tomas Pajdla, Robust wide-baseline stereo from maximally stable extremal regions, Image and Vision Computing 22(10), 761-767, 2004, the section on maximally stable extremal regions
- David Nister and Henrik Stewenius, Linear time maximally stable extremal regions, European Conference on Computer Vision (ECCV 2008), 2008, the description of the linear time algorithm
- Krystian Mikolajczyk, Tinne Tuytelaars, Cordelia Schmid, Andrew Zisserman, Jiri Matas, Frederik Schaffalitzky, Timor Kadir and Luc Van Gool, A comparison of affine region detectors, International Journal of Computer Vision 65(1-2), 43-72, 2005, the section on the MSER detector and the evaluation
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 C7478H Edit this page History Report an error Markdown