Algorithm Search⌘K

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.

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)
Properties
affine covariant regionsdeterministicexactheuristicinvariant to intensity offset
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 gg: the pixels with I≤gI \le g form connected components, the dark extremal regions, and the pixels with I≥gI \ge g form the bright ones. As gg 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 ±Δ\pm\Delta. 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 NN pixels, MM gray levels and TT tracks of nested regions, the cost is O(Nα(N)+MT)O(N\alpha(N) + MT).

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 II with NN pixels and integer values in 0,…,M−10, \dots, M - 1. A pixel has coordinates (u,v)(u, v): uu is the column and goes right, vv is the row and goes down. Two pixels are neighbours when they share a side (4-connectivity). The parameters are the step Δ≥1\Delta \ge 1, the smallest and largest area amin⁡a_{\min} and amax⁡a_{\max}, and an optional largest variation vmax⁡v_{\max}.

A dark extremal region at level gg is a connected component of {I≤g}\{I \le g\}. 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 gg, the track whose region had the larger area at level g−1g - 1 continues with the merged region, and the older track wins a tie; the other tracks end at g−1g - 1. Let aT(g)a_T(g) be the area of the region of track TT at level gg, with aT(g)=0a_T(g) = 0 before the track starts, and let AT(g+Δ)A_T(g + \Delta) be the area of the region at level g+Δg + \Delta that contains it. The stability of the region is

qT(g)=AT(g+Δ)−aT(g−Δ)aT(g).q_T(g) = \frac{A_T(g + \Delta) - a_T(g - \Delta)}{a_T(g)}.

This is the measure ∣Qg+Δ∖Qg−Δ∣/∣Qg∣\lvert Q_{g + \Delta} \setminus Q_{g - \Delta} \rvert / \lvert Q_g \rvert of Matas and others, applied along a track. The output is each region where qTq_T has a strict local minimum along its track, with amin⁡≤aT(g)≤amax⁡a_{\min} \le a_T(g) \le a_{\max} and qT(g)≤vmax⁡q_T(g) \le v_{\max}; 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 M−1−IM - 1 - I.

The algorithm

  1. MSER(I, Δ, a_min, a_max, v_max) ▷ I has N pixels with values in 0, …, M - 1
  2. 1sort the pixels by gray level with counting sort
  3. 2for g ← 0 to M - 1 do
  4. 3for each pixel p with I(p) = g, in index order do
  5. 4make p a set of its own; R ← the distinct sets of its 4-neighbours that are already added
  6. 5if R is empty then start a new track with seed p and birth g
  7. 6else 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
  8. 7for each live track T do a_T(g) ← the size of its set
  9. 8for 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)
  10. 9for 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
  11. 10do the same for M - 1 - I to get the bright regions, and return all regions

Line L1 is a counting sort, O(N+M)O(N + M). 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 ee was absorbed by another track, so AT(g+Δ)A_T(g + \Delta) follows these links until it reaches the track that is live at g+Δg + \Delta. Line L9 compares exact fractions. The region of a reported pair (g,p)(g, p) is the component of {I≤g}\{I \le g\} that contains pp; any flood fill gets its pixels.

Example

Take a 10×1010 \times 10 image with background 200200, a 6×66 \times 6 square of 120120 at 2≤u,v≤72 \le u, v \le 7, a 3×33 \times 3 square of 4040 inside it at 3≤u,v≤53 \le u, v \le 5, the pixel (4,4)(4, 4) set to 3030, and two lone pixels, 9090 at (8,6)(8, 6) and 150150 at (1,8)(1, 8). Take Δ=10\Delta = 10. The track that starts at (4,4)(4, 4) has the area 11 for 30≤g≤3930 \le g \le 39, 99 for 40≤g≤11940 \le g \le 119, 3737 for 120≤g≤199120 \le g \le 199 (the square of side 6 and the lone 9090 pixel next to it), and 100100 from 200200 on. Its stability is:

gg 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
q(g)q(g) 9 8/9 0 28/9 28/37 0 63/37 63/100 0

The two runs of 00 with larger values on both sides give the dark regions at g=50g = 50, the 3×33 \times 3 square with area 99, and at g=130g = 130, the 3737 pixels of the large square and the 9090 pixel. The last run reaches the top of the range of qq, so it has no larger value on its right and gives no region. The lone pixels give the dark regions (8,6)(8, 6) at g=100g = 100 and (1,8)(1, 8) at g=160g = 160, each with area 11. The bright regions, of {I≥g}\{I \ge g\}, have the areas 9191, 9090, 6363 and 6262, at g=80g = 80, 110110, 140140 and 190190. With amin⁡=4a_{\min} = 4 and amax⁡=50a_{\max} = 50 only the two squares remain.

Correctness

The proof in proofs/correctness.md shows that after level gg the sets of the forest are exactly the connected components of {I≤g}\{I \le g\}, that each live track holds one of them and contains its seed, and that the recorded areas and the values of qq 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 qq 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 Xg={p:I(p)≤g}X_g = \{p : I(p) \le g\} and call a connected component of XgX_g a region at level gg.

Lemma 1 (the forest). After the pixels of level gg have been processed, the sets of the disjoint-set forest are exactly the regions at level gg.

Proof. By induction on gg. Before level 00 no pixel is added and X−1X_{-1} is empty. Assume the claim after level g−1g - 1. Line L1 sorts by gray level, so at level gg lines L3 and L4 add exactly the pixels of Xg∖Xg−1X_g \setminus X_{g-1}. Each added pixel pp is joined with the sets of all its neighbours that are already added. Two pixels of XgX_g are in one region exactly when a path of neighbours in XgX_g joins them. Every step of such a path is an edge between two pixels of XgX_g, 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 XgX_g, so every set is connected in XgX_g. After the last pixel of level gg the sets are the regions at level gg. □\square

Lemma 2 (the tracks). After level gg, each set of the forest belongs to exactly one live track, and that track's seed is in the set. Line L7 records aT(g)a_T(g), the size of the region of TT at level gg.

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 gg. □\square

The choice of line L6 uses a(g−1)a(g - 1), the last area recorded for each track before level gg, which is 00 for a track born at level gg. This choice does not depend on the order in which the joins of level gg happen: the continuing track of a group of sets is the one with the largest pair (a(g−1),−index)(a(g - 1), -\text{index}), and taking a maximum of pairs is associative. So the tracks are a function of the image alone. A new track born at level gg 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 TT and each level gg from the birth of TT to min⁡(end(T),M−1−Δ)\min(\text{end}(T), M - 1 - \Delta), line L8 computes qT(g)=(AT(g+Δ)−aT(g−Δ))/aT(g)q_T(g) = (A_T(g + \Delta) - a_T(g - \Delta)) / a_T(g), where AT(g+Δ)A_T(g + \Delta) is the area of the region at level g+Δg + \Delta that contains the region of TT at level gg.

Proof. aT(g)a_T(g) and aT(g−Δ)a_T(g - \Delta) are read from the areas recorded by line L7, with 00 before the birth. For ATA_T: regions at different levels are nested, so the region at level g+Δg + \Delta that contains the region of TT at gg is the one that contains the seed of TT. If TT is live at g+Δg + \Delta, this is the region of TT by Lemma 2. Otherwise TT ended at a level e<g+Δe < g + \Delta and was joined, at level e+1e + 1, into the set of a track T′T', which contains the seed of TT from then on. Following the links T→T′→…T \to T' \to \dots reaches the track that is live at g+Δg + \Delta and whose set holds the seed of TT, and its recorded area is AT(g+Δ)A_T(g + \Delta). Each link goes to a track that ends later, so the walk stops. The value is a quotient of two integers with aT(g)≥1a_T(g) \ge 1, computed exactly. □\square

Theorem. MSER returns exactly the pairs (level, seed) such that the region of a track TT at level gg is the first level of a maximal run of equal values of qTq_T, both neighbouring values along the track exist and are larger, amin⁡≤aT(g)≤amax⁡a_{\min} \le a_T(g) \le a_{\max} and qT(g)≤vmax⁡q_T(g) \le v_{\max}; it does this for II and for M−1−IM - 1 - I. The returned region of a pair (g,p)(g, p) is the component of {I≤g}\{I \le g\} that contains pp for a dark region, and the component of {I≥g}\{I \ge g\} that contains pp for a bright one.

Proof. By Lemma 3 the values qT(g)q_T(g) are exact. Line L9 walks the values of each track in the order of gg 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 TT at level gg is the component of XgX_g that holds the seed. For the bright regions, line L10 runs the same steps on I′=M−1−II' = M - 1 - I, whose values are again in 0,…,M−10, \dots, M - 1. The set {I′≤g}\{I' \le g\} is {I≥M−1−g}\{I \ge M - 1 - g\}, so the region found at level gg of I′I' is the bright region at level M−1−gM - 1 - g of II, which is the level that is returned. ■\blacksquare

Complexity

The model is the word RAM, with gray levels that fit in a word.

  • Line L1 is O(N+M)O(N + M).
  • Lines L3 to L6 make NN additions and at most 4N4N find operations with union by size and path compression, O(Nα(N))O(N\alpha(N)) in total. Choosing the continuing track is O(1)O(1) per neighbour.
  • Line L7 runs once per level for each live track. A track is live for at most MM levels, so this is O(MT)O(MT).
  • Lines L8 and L9 do O(1)O(1) work per recorded area, plus the links followed for ATA_T, which is O(MT)O(MT) over all tracks.

The total is O(Nα(N)+MT)O(N\alpha(N) + MT), with O(N+MT)O(N + MT) space for the forest and the areas. For 8-bit images M=256M = 256. Recording areas only at the levels where a track changes, as most implementations do, removes the factor MM. 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 Δ\Delta 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 NN 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, (AT(g+Δ)−aT(g))/aT(g)(A_T(g + \Delta) - a_T(g)) / a_T(g), 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 II and on M−1−IM - 1 - I.
  • 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 gg, and no level is stable. Small or blurred structures are lost.
  • Too small a Δ\Delta. With few gray levels between neighbour regions, the stability is undefined or noisy. With M=256M = 256, values from 5 to 10 are common.
  • Huge regions. The background and its big parts are stable too. Set amax⁡a_{\max}, for example to a fraction of the image.
  • Plateaus. Many levels can have the same qq. 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.

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

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • 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