Algorithm Search⌘K

Algorithmadvanced

Contour detection and hierarchical segmentation

Also called gPb-OWT-UCM, ultrametric contour map.

A boundary map whose thresholds give a nested hierarchy of segmentations. Build it from regions and edge strengths by merging the pair with the weakest mean boundary first.

Time
O(W H + R^2 log R) worst · averageO(W H + R log R) best
Space
O(W H + R^2) extra
Where
H = the image height in pixels; R = the number of initial regions; W = the image width in pixels
Properties
closed contoursdeterministicgreedyhierarchical
Origin
Pablo Arbelaez, Michael Maire, Charless Fowlkes, Jitendra Malik, 2006

An ultrametric contour map (UCM) is a boundary map of an image with one property: if you keep only the boundaries stronger than a threshold tt, the boundaries close into regions, and the regions for a larger tt are unions of the regions for a smaller tt. So one map stores a whole hierarchy of segmentations, from fine to coarse. Arbelaez defined the UCM in 2006. The name of this page is the title of the 2011 paper of Arbelaez, Maire, Fowlkes and Malik, whose pipeline (often called gPb-OWT-UCM) is the best known way to build one: a contour detector gives the strengths, an oriented watershed gives the first regions, and greedy merging gives the UCM. This page is about the last step and the map that it makes. A watershed gives one partition, not a hierarchy. Plain agglomerative clustering of pixels makes a dendrogram too, but its distances do not come from the strength of the shared boundary.

In plain words

Draw the borders of many small regions on a map, in pencil of many shades. A light line is a weak border and a dark line is a strong border. Now look for the lightest border between two neighbor regions and rub it out, so that the two regions become one. The new region has new borders with its neighbors, and each of those gets the average shade of its pieces. Do this again and again, until one region is left.

Write down, on each border piece, the moment when it was rubbed out. That number is the map. If you hide every piece with a number below some value, you see exactly the regions that existed at that moment. A low value shows many small regions. A high value shows a few large ones. Every border you see is closed, because it was the edge of a real region.

The problem

The input is a grid of W×HW \times H pixels with an initial label map, and a strength E(e)≥0E(e) \ge 0 on each grid edge ee between two 4-neighbor pixels. A pixel is (u,v)(u, v), where uu is the column and vv is the row. The boundaries of this page lie on the grid edges between pixels, so a region boundary has no width.

The output is a value UCM(e)\mathrm{UCM}(e) on each grid edge with these properties:

  • For each threshold tt, the connected components of the pixels, with the grid edges of value at most tt as links, form a partition P(t)\mathcal{P}(t).
  • If t≤t′t \le t', each region of P(t)\mathcal{P}(t) lies inside one region of P(t′)\mathcal{P}(t').
  • The edges inside one initial region have value 0, so P(0)\mathcal{P}(0) is the initial partition or a coarser one.

The distance d(p,q)d(p, q), the least tt at which pp and qq share a region, is then an ultrametric: d(p,r)≤max⁡(d(p,q),d(q,r))d(p, r) \le \max(d(p, q), d(q, r)). This is where the name comes from. See ultrametric for the general notion.

The algorithm

Arbelaez et al. (2011, Section 4.2) build the UCM by greedy merging on a graph whose nodes are the regions and whose edges are the common boundaries. The weight of an edge is the dissimilarity of the two regions, which they take as the average strength of their common boundary. The procedure below is that greedy merge on the grid edges. S[a,b]S[a, b] is the sum of the strengths of the grid edges between regions aa and bb, and n[a,b]n[a, b] is their number.

  1. UCM(lab, E) ▷ lab: initial labels; E: strength of each grid edge
  2. 1give each 4-connected component of lab its own region id; R ← their number
  3. 2for each grid edge e = (p, q) whose pixels are in two regions a ≠ b do
  4. 3S[a, b] ← S[a, b] + E(e); n[a, b] ← n[a, b] + 1
  5. 4Q ← min-heap of (S[a, b] / n[a, b], a, b) over the adjacent pairs with a < b
  6. 5while Q is not empty do
  7. 6pop (m, a, b) from Q; if a or b is no longer live then go to L5
  8. 7make the new region c = a ∪ b at level m; a and b are no longer live
  9. 8UCM(e) ← m for each grid edge e between a and b
  10. 9for each live region r next to a or b do
  11. 10S[c, r] ← S[a, r] + S[b, r]; n[c, r] ← n[a, r] + n[b, r]; push (S[c, r] / n[c, r], r, c)
  12. 11UCM(e) ← 0 for each grid edge e inside one region of L1
  13. 12return UCM

Each region id is used once, so a heap entry is out of date exactly when one of its regions has merged, and line L6 drops it. Ties go to the smallest pair (a,b)(a, b); the new region gets the next free id.

Example

The grid is 4×44 \times 4 with four initial regions of 2×22 \times 2 pixels, AA and BB on top and CC and DD below. Each boundary has two grid edges. The strengths are 0.2 and 0.4 between AA and BB, 0.6 and 0.6 between CC and DD, 0.9 and 0.7 between AA and CC, and 0.5 and 0.9 between BB and DD.

A A | B B
A A | B B
---------
C C | D D
C C | D D
step mean strengths of the live pairs merge level
1 AB 0.3, CD 0.6, BD 0.7, AC 0.8 A∪B=EA \cup B = E 0.3
2 CD 0.6, ED 0.7, EC 0.8 C∪D=FC \cup D = F 0.6
3 EF =(0.9+0.7+0.5+0.9)/4=0.75= (0.9 + 0.7 + 0.5 + 0.9) / 4 = 0.75 E∪FE \cup F 0.75

The UCM is 0.3 on the two edges between AA and BB, 0.6 on the two edges between CC and DD, and 0.75 on the four horizontal edges in the middle. A threshold below 0.3 gives 4 regions, a threshold in [0.3,0.6)[0.3, 0.6) gives 3, one in [0.6,0.75)[0.6, 0.75) gives 2, and one of 0.75 or more gives 1. The middle edges had strengths 0.9, 0.7, 0.5 and 0.9, but they all get 0.75: the UCM value of an edge is the level of a merge, not its input strength. The test file checks these numbers with exact fractions.

Correctness

The full proof is in proofs/correctness.md. The main steps:

  • The records always hold the true sums SS and nn of the current regions, because a grid edge between c=a∪bc = a \cup b and rr lies between aa and rr or between bb and rr, and not both.
  • Each accepted pop is the least mean over the live pairs. After a merge at level mm, the mean of a new pair (c,r)(c, r) is a weighted mean of the old means of (a,r)(a, r) and (b,r)(b, r), which are at least mm. So the merge levels never go down.
  • Because the levels never go down, the merges at level at most tt are a prefix of the merge sequence. By induction on that prefix, the components of the edges with value at most tt are exactly the regions after those merges (Theorem 1 of the proof). So every threshold gives closed contours and the partitions are nested.
  • Nesting gives the ultrametric inequality, and d(p,q)d(p, q) is the minimax value over paths from pp to qq of the largest UCM value on the path.

With the mean as the dissimilarity, monotone levels need the argument above. Arbelaez et al. make the same point for their dissimilarity (Section 4.2). A rule that can lower the dissimilarity after a merge would break the hierarchy.

Proof: Correctness of the greedy ultrametric contour mapfull

This proof covers lines L1 to L12 of the main page. The input is a label map on a grid of W×HW \times H pixels and a real strength E(e)≥0E(e) \ge 0 on each grid edge ee between two 4-neighbors. The output gives a value UCM(e)\mathrm{UCM}(e) to each grid edge. Nothing here says that the strengths come from a good contour detector. The proof is about the merge process on any strengths.

Notation. A region is a set of pixels that is connected in the 4-neighbor grid graph. For two adjacent regions aa and bb, let S(a,b)S(a, b) be the sum of E(e)E(e) over the grid edges ee with one pixel in aa and one in bb, and let n(a,b)≥1n(a, b) \ge 1 be the number of such edges. The mean strength is μ(a,b)=S(a,b)/n(a,b)\mu(a, b) = S(a, b) / n(a, b). The algorithm keeps a partition Pk\mathcal{P}_k of the pixels after kk merges. P0\mathcal{P}_0 is the partition of line L1, and its regions are the initial regions.

Lemma 1 (the records hold the true sums). After line L4, and after each pass of lines L5 to L10, each pair (a,b)(a, b) of adjacent live regions has a record with exactly S(a,b)S(a, b), n(a,b)n(a, b) and the list of the adjacent pairs {x,y}\{x, y\} of initial regions with x⊆ax \subseteq a and y⊆by \subseteq b. The heap holds an entry (μ(a,b),a,b)(\mu(a, b), a, b) for it. No record exists for a pair that is not adjacent.

Proof. Lines L2 and L3 visit each grid edge once and add its strength to the record of the pair of regions on its two sides, so the claim holds after L4, where each record lists its own pair. Suppose the claim holds before a merge of aa and bb into cc. A grid edge with one side in cc and the other side in a region r∉{a,b}r \notin \{a, b\} has its first side in aa or in bb, and not in both, because a∩b=∅a \cap b = \emptyset. So S(c,r)=S(a,r)+S(b,r)S(c, r) = S(a, r) + S(b, r) and n(c,r)=n(a,r)+n(b,r)n(c, r) = n(a, r) + n(b, r), where a missing record counts as zero, and the list of (c,r)(c, r) is the union of the lists of (a,r)(a, r) and (b,r)(b, r). Lines L9 and L10 compute exactly these, and the push after L10 adds the heap entry. Pairs that do not involve aa or bb keep their records, and their sums do not change, because their regions do not change. □\square

Lemma 2 (each accepted pop is a minimum over the live pairs). The entry that passes line L6 has the least (μ,a,b)(\mu, a, b) over all pairs of adjacent live regions.

Proof. A region id is never reused, and the record of a pair of live regions never changes while both regions live (Lemma 1). So every heap entry whose two regions are live holds the current mean of its pair, and every live pair has such an entry. Line L6 skips the entries with a dead region. The heap pops entries in the order of (μ,a,b)(\mu, a, b), so the first entry that passes L6 is the least over the live pairs. □\square

Lemma 3 (the levels do not decrease). Let m1,m2,…m_1, m_2, \ldots be the levels of the merges in the order of the loop. Then m1≤m2≤⋯m_1 \le m_2 \le \cdots.

Proof. Let merge kk join aa and bb at level mkm_k. By Lemma 2, μ(x,y)≥mk\mu(x, y) \ge m_k for every live pair before the merge. After the merge, the pairs without cc are unchanged. For a pair (c,r)(c, r),

μ(c,r)=S(a,r)+S(b,r)n(a,r)+n(b,r)=n(a,r) μ(a,r)+n(b,r) μ(b,r)n(a,r)+n(b,r),\mu(c, r) = \frac{S(a, r) + S(b, r)}{n(a, r) + n(b, r)} = \frac{n(a, r)\,\mu(a, r) + n(b, r)\,\mu(b, r)}{n(a, r) + n(b, r)},

a weighted mean with nonnegative weights of values that are at least mkm_k (a missing record has weight zero). So μ(c,r)≥mk\mu(c, r) \ge m_k, and every live pair after the merge has mean at least mkm_k. By Lemma 2, mk+1≥mkm_{k+1} \ge m_k. □\square

Lemma 4 (termination). The loop stops after exactly R−1R - 1 merges, where RR is the number of initial regions, and it ends with one region.

Proof. Each accepted pop replaces two live regions by one, so there are at most R−1R - 1 merges. Each pass pops one entry, and a finite number of entries is pushed, so the loop stops. When it stops, the heap is empty, so by Lemma 1 no two live regions are adjacent. The grid graph is connected, so a partition into more than one region always has two adjacent regions. Hence one region is left, after R−1R - 1 merges. □\square

Lemma 5 (the value of a grid edge). Let e=(p,q)e = (p, q) be a grid edge. If pp and qq are in the same initial region, then UCM(e)=0\mathrm{UCM}(e) = 0. Otherwise UCM(e)=mk\mathrm{UCM}(e) = m_k, where merge kk is the first merge after which pp and qq are in one region. That merge joins a region that contains pp and a region that contains qq.

Proof. Let xx and yy be the initial regions of pp and qq, with x≠yx \ne y. Before merge kk, xx and yy lie in two different live regions a⊇xa \supseteq x and b⊇yb \supseteq y, and merge kk joins exactly these two. The pair {x,y}\{x, y\} is adjacent, because ee joins them, so by Lemma 1 it is in the list of the record (a,b)(a, b), and line L8 sets its value to mkm_k. A pair is in the list of one record only, and line L8 runs once for the record (a,b)(a, b), so no other line writes this value. Line L11 copies the value of {x,y}\{x, y\} to ee. Edges inside one initial region keep the value 0. □\square

Theorem 1 (thresholds give the partitions of the hierarchy). Let t≥0t \ge 0 and let k(t)k(t) be the number of merges with level at most tt. The connected components of the graph on the pixels with the grid edges ee such that UCM(e)≤t\mathrm{UCM}(e) \le t are exactly the regions of Pk(t)\mathcal{P}_{k(t)}.

Proof. By Lemma 3, the merges with level at most tt are the first k(t)k(t) merges. Take a grid edge e=(p,q)e = (p, q) with UCM(e)≤t\mathrm{UCM}(e) \le t. By Lemma 5, either pp and qq share an initial region, or they share a region after merge kk with mk≤tm_k \le t, so k≤k(t)k \le k(t). In both cases they share a region of Pk(t)\mathcal{P}_{k(t)}, and so does each pair of pixels joined by a path of such edges. So each component lies inside one region.

For the other direction, we show by induction on j≤k(t)j \le k(t) that each region of Pj\mathcal{P}_j is connected by edges with value at most tt. For j=0j = 0, each region is a connected set of pixels with equal labels, and the edges inside it have value 0 by Lemma 5. Merge jj joins two adjacent regions aa and bb at level mj≤tm_j \le t. By Lemma 5, every grid edge between aa and bb gets the value mjm_j, and there is at least one such edge, because aa and bb are adjacent. With the induction hypothesis for aa and for bb, the region a∪ba \cup b is connected by edges with value at most tt. So each region lies inside one component. □\square

Corollary (closed contours and nesting). For t≤t′t \le t', each region of the partition at tt lies inside one region of the partition at t′t', because Pk(t′)\mathcal{P}_{k(t')} comes from Pk(t)\mathcal{P}_{k(t)} by more merges. The set of grid edges with UCM(e)>t\mathrm{UCM}(e) > t is exactly the set of edges between two different regions of Pk(t)\mathcal{P}_{k(t)}. So the boundary at each threshold is a union of closed region boundaries, with no loose ends inside a region.

Theorem 2 (the UCM is an ultrametric). For pixels pp and qq, let d(p,q)d(p, q) be the least t≥0t \ge 0 such that pp and qq are in one component at threshold tt. Then d(p,p)=0d(p, p) = 0, d(p,q)=d(q,p)d(p, q) = d(q, p), and

d(p,r)≤max⁡(d(p,q),d(q,r))d(p, r) \le \max(d(p, q), d(q, r))

for all pixels p,q,rp, q, r. Also d(p,q)=min⁡πmax⁡e∈πUCM(e)d(p, q) = \min_{\pi} \max_{e \in \pi} \mathrm{UCM}(e), where π\pi runs over the paths from pp to qq in the grid graph.

Proof. Symmetry and d(p,p)=0d(p, p) = 0 are clear. Let t=max⁡(d(p,q),d(q,r))t = \max(d(p, q), d(q, r)). At threshold tt, pp and qq are in one component, and qq and rr are in one component, because the partitions are nested (the corollary). So pp and rr are in one component at tt, and d(p,r)≤td(p, r) \le t. For the path form, pp and qq are in one component at threshold tt if and only if some path joins them with all its edges at most tt, which holds if and only if the minimax value of the paths is at most tt. □\square

dd is an ultrametric on the initial regions. On single pixels it is a pseudo-ultrametric, because two pixels of one initial region have distance 0. With one initial region per pixel it is an ultrametric on the pixels.

Cost. Let RR be the number of initial regions and PP the number of adjacent pairs among them. Lines L1 to L4 take O(WH+P)O(WH + P) time. The region adjacency graph is planar, because the regions are connected sets of pixels in the plane, and merging two adjacent regions keeps it planar. So P≤3R−6P \le 3R - 6 for R≥3R \ge 3, and the same bound holds after each merge. A merge of aa and bb costs O((deg⁡a+deg⁡b)log⁡Q)O((\deg a + \deg b) \log Q) for the records and the heap, where QQ is the number of heap entries. Each degree is less than RR, and Q=O(R2)Q = O(R^2), so the merges cost O(R2log⁡R)O(R^2 \log R) in the worst case and O(Rlog⁡R)O(R \log R) when all degrees stay bounded by a constant. Line L10 appends the shorter list to the longer one, so a pair of initial regions moves only to a list at least twice the size of its old list, at most log⁡2P\log_2 P times. The lists cost O(Plog⁡P)O(P \log P) in total. Line L11 takes O(WH)O(WH) time. The total is O(WH+R2log⁡R)O(WH + R^2 \log R) time and O(WH+R2)O(WH + R^2) space in the worst case, in the real-RAM model, where R≤WHR \le WH.

Complexity

Let RR be the number of initial regions. Lines L1 to L4 take O(WH)O(WH) time. The region adjacency graph is planar, so it has at most 3R−63R - 6 edges when R≥3R \ge 3, before and after each merge. A merge of aa and bb costs O((deg⁡a+deg⁡b)log⁡R)O((\deg a + \deg b) \log R) for the records and the heap. A degree can be as large as R−1R - 1, so the merges cost O(R2log⁡R)O(R^2 \log R) in the worst case, and O(Rlog⁡R)O(R \log R) when every degree stays bounded by a constant. Line L10 adds the shorter list of grid edge pairs to the longer one, so the lists cost O(Rlog⁡R)O(R \log R) in total. The total is O(WH+R2log⁡R)O(WH + R^2 \log R) time and O(WH+R2)O(WH + R^2) extra space, in the real-RAM model. In practice the initial regions come from a watershed and RR is much smaller than WHWH.

The pipeline of Arbelaez et al. spends far more time on the contour detector (gPb) than on the merging. Its spectral part solves a generalized eigenproblem on a pixel affinity graph. That cost is outside this page.

Properties

  • Hierarchy. One map stores RR nested partitions, one for each merge level, and the threshold picks one.
  • Closed contours. Every threshold gives boundaries that are unions of closed region boundaries. A raw edge map, such as the output of the Canny detector, has no such property.
  • Ultrametric. The distance d(p,q)d(p, q) satisfies the ultrametric inequality, and it equals the minimax path value of the UCM.
  • Greedy. The merge order is fixed by the means. No step is undone, so an error in the initial regions or an early wrong merge stays in the hierarchy.
  • Deterministic. With a fixed tie rule the output depends only on the input.

Variants and improvements

  • The gPb-OWT-UCM pipeline (Arbelaez et al. 2011). The strengths come from gPb, which combines local brightness, color and texture gradients at several scales with a spectral signal from the eigenvectors of a pixel affinity matrix, in the style of normalized cuts. The oriented watershed transform (OWT, Section 4.1) runs a watershed on the contour signal and then gives each watershed arc the strength of the contour at the orientation of that arc, which removes artifacts of the plain watershed. The UCM step is the greedy merge above.
  • Other dissimilarities. If the dissimilarity is the minimum strength on the common boundary, the merge is single-linkage clustering on the region graph, and the hierarchy is the one of a minimum spanning tree. Mean and minimum both give monotone levels, because a merge cannot lower them. Single linkage is known to chain regions through one weak spot of a boundary; the mean is less sensitive to one weak edge.
  • Region features. Other merge criteria use region statistics, such as color histograms. Such a criterion can give a lower dissimilarity after a merge. Then the levels must be forced to be monotone, for example by taking the running maximum, or the map is not an ultrametric.
  • Graph-based segmentation. Felzenszwalb-Huttenlocher segmentation also merges regions greedily along a minimum spanning tree order, but it returns one partition for one parameter value.

When to use it

Use a UCM when a later step needs regions at several scales, for example when an object detector or a user picks the scale per object, or when you must report a segmentation benchmark over all thresholds. Use it when closed region boundaries matter, because a thresholded edge map can have gaps. Do not use it when you need one partition from a learned semantic model; the hierarchy carries no class labels. Do not use it when the initial regions already merge two objects, because merging cannot split them.

Pitfalls

  • The UCM is not the input. A UCM value is a merge level. An edge with a high input strength can get a low value if it sits between two regions whose mean boundary is weak, and the reverse.
  • Monotone levels are not free. If you change the merge criterion, check that a merge can never lower the dissimilarity of a remaining pair. If it can, the thresholds stop giving nested partitions.
  • Ties and rounding. Two pairs with the same mean can merge in either order, and floating point sums in a different order can change which mean is smaller. Fix a tie rule, and test with exact fractions.
  • Where the boundary lies. This page puts boundaries on the grid edges between pixels. Many codes put them on pixels, which makes boundaries one pixel thick and needs care at junctions. The code of Arbelaez et al. stores the map on a grid of doubled resolution for this reason.
  • Threshold direction. A region boundary at threshold tt is the set of edges with value strictly above tt. Off-by-one errors in this test merge or split regions at exactly the merge levels.
  • Connectivity. The initial regions must be connected. A label that appears in two separate places must give two regions, as line L1 does; otherwise a "region" can be adjacent to itself.

Implementations

The Python code in impl/python/ultrametric_contour_map.py implements lines L1 to L12 on a given label map and given edge strengths. It does not compute gPb or the oriented watershed. Strengths can be int, float or Fraction. The tests compare the merge sequence with a naive method that recomputes all means before each merge, check that the levels never go down, check Theorem 1 at every level, and check the ultrametric inequality and the minimax path form by Floyd-Warshall on small grids.

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.

ultrametric_contour_map.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ultrametric-contour-map/. The authors are listed in prov/6B2NMJ.jsonl.

"""Ultrametric contour map from an initial partition and edge strengths.

The image is a grid of w columns and h rows. A pixel is (u, v), and a value at
(u, v) is img[v][u]. Boundaries lie on the grid edges between 4-neighbors:
eh[v][u] is the strength of the edge between (u, v) and (u + 1, v), and
ev[v][u] is the strength of the edge between (u, v) and (u, v + 1).

The algorithm merges, one pair at a time, the two adjacent regions whose
common boundary has the least mean strength. The level of a merge is that mean.
The UCM value of a grid edge is the level of the merge that first puts its two
pixels in one region. Strengths may be int, float or Fraction.
"""

import heapq


def components(labels):
    """Return (comp, r): the 4-connected components of equal labels, numbered 0 .. r - 1 in raster order."""
    h, w = len(labels), len(labels[0])
    comp = [[-1] * w for _ in range(h)]
    r = 0
    for v0 in range(h):
        for u0 in range(w):
            if comp[v0][u0] >= 0:
                continue
            comp[v0][u0] = r
            stack = [(u0, v0)]
            while stack:
                u, v = stack.pop()
                for x, y in ((u + 1, v), (u - 1, v), (u, v + 1), (u, v - 1)):
                    if 0 <= x < w and 0 <= y < h and comp[y][x] < 0 and labels[y][x] == labels[v][u]:
                        comp[y][x] = r
                        stack.append((x, y))
            r += 1
    return comp, r


def grid_edges(w, h):
    """Yield (kind, u, v, p, q) for each 4-neighbor edge; kind 0 is horizontal (eh), kind 1 is vertical (ev)."""
    for v in range(h):
        for u in range(w - 1):
            yield 0, u, v, (u, v), (u + 1, v)
    for v in range(h - 1):
        for u in range(w):
            yield 1, u, v, (u, v), (u, v + 1)


def ultrametric_contour_map(labels, eh, ev):
    """Return (uh, uv, merges).

    uh and uv have the shapes of eh and ev and hold the UCM value of each grid
    edge. merges is the list of (level, a, b, c): regions a and b merge into the
    new region c at the given level. The initial regions are 0 .. r - 1 and the
    new regions get the next free ids. Ties go to the smallest pair (a, b).
    """
    h, w = len(labels), len(labels[0])
    strength = (eh, ev)
    comp, r0 = components(labels)  # @line L1
    # adj[a][b] = [S, n, keys] is shared by a and b. keys lists the pairs of
    # initial regions whose common grid edges lie between a and b.
    adj = [dict() for _ in range(r0)]
    for kind, u, v, (u1, v1), (u2, v2) in grid_edges(w, h):  # @line L2
        a, b = comp[v1][u1], comp[v2][u2]
        if a != b:
            rec = adj[a].get(b)
            if rec is None:
                rec = [0, 0, [(min(a, b), max(a, b))]]
                adj[a][b] = rec
                adj[b][a] = rec
            rec[0] += strength[kind][v][u]  # @line L3
            rec[1] += 1
    heap = [(rec[0] / rec[1], a, b) for a in range(r0) for b, rec in adj[a].items() if a < b]  # @line L4
    heapq.heapify(heap)
    alive = [True] * r0
    value = {}
    merges = []
    while heap:  # @line L5
        m, a, b = heapq.heappop(heap)
        if not (alive[a] and alive[b]):  # @line L6
            continue
        c = len(alive)  # @line L7
        alive[a] = alive[b] = False
        alive.append(True)
        merges.append((m, a, b, c))
        for key in adj[a][b][2]:
            value[key] = m  # @line L8
        merged = {}
        for x in (a, b):  # @line L9
            for r, rec in adj[x].items():
                if r == a or r == b:
                    continue
                del adj[r][x]
                acc = merged.get(r)
                if acc is None:
                    merged[r] = rec
                else:
                    acc[0] += rec[0]  # @line L10
                    acc[1] += rec[1]
                    if len(acc[2]) < len(rec[2]):
                        acc[2], rec[2] = rec[2], acc[2]
                    acc[2].extend(rec[2])
            adj[x] = None
        adj.append(merged)
        for r, rec in merged.items():
            adj[r][c] = rec
            heapq.heappush(heap, (rec[0] / rec[1], r, c))
    uh = [[0] * (w - 1) for _ in range(h)]
    uv = [[0] * w for _ in range(h - 1)]
    out = (uh, uv)
    for kind, u, v, (u1, v1), (u2, v2) in grid_edges(w, h):  # @line L11
        a, b = comp[v1][u1], comp[v2][u2]
        if a != b:
            out[kind][v][u] = value[(min(a, b), max(a, b))]
    return uh, uv, merges  # @line L12


def threshold(uh, uv, t):
    """Return a label map of the components of the grid edges with UCM value at most t."""
    h, w = len(uh), len(uh[0]) + 1
    parent = list(range(w * h))

    def find(i):
        while parent[i] != i:
            parent[i] = parent[parent[i]]
            i = parent[i]
        return i

    for kind, u, v, (u1, v1), (u2, v2) in grid_edges(w, h):
        val = uh[v][u] if kind == 0 else uv[v][u]
        if val <= t:
            parent[find(v1 * w + u1)] = find(v2 * w + u2)
    return [[find(v * w + u) for u in range(w)] for v in range(h)]
test_ultrametric_contour_map.py 171 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ultrametric-contour-map/. The authors are listed in prov/6B2NMJ.jsonl.

import random
from fractions import Fraction as F

from ultrametric_contour_map import components, grid_edges, threshold, ultrametric_contour_map


def quadrant_example():
    """A 4 x 4 grid with four 2 x 2 regions A B / C D, as on the page."""
    labels = [[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]
    eh = [[F(0)] * 3 for _ in range(4)]
    ev = [[F(0)] * 4 for _ in range(3)]
    eh[0][1], eh[1][1] = F(2, 10), F(4, 10)  # A | B
    eh[2][1], eh[3][1] = F(6, 10), F(6, 10)  # C | D
    ev[1][0], ev[1][1] = F(9, 10), F(7, 10)  # A over C
    ev[1][2], ev[1][3] = F(5, 10), F(9, 10)  # B over D
    return labels, eh, ev


def random_case(rng, w, h, nlab):
    labels = [[rng.randrange(nlab) for _ in range(w)] for _ in range(h)]
    eh = [[F(rng.randint(0, 10), 10) for _ in range(w - 1)] for _ in range(h)]
    ev = [[F(rng.randint(0, 10), 10) for _ in range(w)] for _ in range(h - 1)]
    return labels, eh, ev


def naive_merges(labels, eh, ev):
    """Recompute every mean boundary strength from scratch before each merge."""
    h, w = len(labels), len(labels[0])
    comp, r0 = components(labels)
    region = {(u, v): comp[v][u] for v in range(h) for u in range(w)}
    nxt = r0
    merges = []
    while True:
        sums = {}
        for kind, u, v, p, q in grid_edges(w, h):
            a, b = region[p], region[q]
            if a == b:
                continue
            key = (min(a, b), max(a, b))
            s, n = sums.get(key, (0, 0))
            sums[key] = (s + (eh[v][u] if kind == 0 else ev[v][u]), n + 1)
        if not sums:
            return merges
        m, a, b = min((s / n, a, b) for (a, b), (s, n) in sums.items())
        merges.append((m, a, b, nxt))
        for p in region:
            if region[p] in (a, b):
                region[p] = nxt
        nxt += 1


def partition(lab):
    groups = {}
    for v, row in enumerate(lab):
        for u, x in enumerate(row):
            groups.setdefault(x, set()).add((u, v))
    return {frozenset(g) for g in groups.values()}


def partition_after(labels, merges, t):
    """The partition after all merges of level at most t, replayed with plain sets."""
    h, w = len(labels), len(labels[0])
    comp, _ = components(labels)
    sets = {}
    for v in range(h):
        for u in range(w):
            sets.setdefault(comp[v][u], set()).add((u, v))
    for m, a, b, c in merges:
        if m <= t:
            sets[c] = sets.pop(a) | sets.pop(b)
    return {frozenset(s) for s in sets.values()}


def test_quadrant_example():
    labels, eh, ev = quadrant_example()
    uh, uv, merges = ultrametric_contour_map(labels, eh, ev)
    assert [m for m, _, _, _ in merges] == [F(3, 10), F(3, 5), F(3, 4)]
    assert [(a, b, c) for _, a, b, c in merges] == [(0, 1, 4), (2, 3, 5), (4, 5, 6)]
    assert uh[0][1] == uh[1][1] == F(3, 10)
    assert uh[2][1] == uh[3][1] == F(3, 5)
    assert uv[1] == [F(3, 4)] * 4
    assert uh[0][0] == uv[0][0] == 0
    assert len(partition(threshold(uh, uv, F(1, 4)))) == 4
    assert len(partition(threshold(uh, uv, F(1, 2)))) == 3
    assert len(partition(threshold(uh, uv, F(7, 10)))) == 2
    assert len(partition(threshold(uh, uv, F(3, 4)))) == 1


def test_levels_do_not_decrease():
    rng = random.Random(1)
    for _ in range(40):
        labels, eh, ev = random_case(rng, 6, 5, 3)
        _, _, merges = ultrametric_contour_map(labels, eh, ev)
        levels = [m for m, _, _, _ in merges]
        assert levels == sorted(levels)
        _, r0 = components(labels)
        assert len(merges) == r0 - 1


def test_matches_naive_recompute():
    rng = random.Random(2)
    for _ in range(40):
        labels, eh, ev = random_case(rng, 5, 5, 4)
        _, _, merges = ultrametric_contour_map(labels, eh, ev)
        assert merges == naive_merges(labels, eh, ev)


def test_threshold_gives_the_partition_of_each_level():
    rng = random.Random(3)
    for _ in range(25):
        labels, eh, ev = random_case(rng, 5, 4, 3)
        uh, uv, merges = ultrametric_contour_map(labels, eh, ev)
        levels = sorted({m for m, _, _, _ in merges} | {F(0)})
        previous = None
        for t in levels:
            p = partition(threshold(uh, uv, t))
            assert p == partition_after(labels, merges, t)
            if previous is not None:
                # Nested: each region at the lower level lies inside one region here.
                assert all(any(r <= s for s in p) for r in previous)
            previous = p


def test_ultrametric_and_minimax_paths():
    rng = random.Random(4)
    for _ in range(10):
        w, h = 4, 3
        labels = [[v * w + u for u in range(w)] for v in range(h)]  # one region per pixel
        eh = [[F(rng.randint(1, 9), 10) for _ in range(w - 1)] for _ in range(h)]
        ev = [[F(rng.randint(1, 9), 10) for _ in range(w)] for _ in range(h - 1)]
        uh, uv, merges = ultrametric_contour_map(labels, eh, ev)
        n = w * h
        inf = F(10)
        d = [[F(0) if i == j else inf for j in range(n)] for i in range(n)]
        for kind, u, v, (u1, v1), (u2, v2) in grid_edges(w, h):
            val = uh[v][u] if kind == 0 else uv[v][u]
            i, j = v1 * w + u1, v2 * w + u2
            d[i][j] = d[j][i] = val
        for k in range(n):  # Floyd-Warshall with (min, max): the minimax path value
            for i in range(n):
                for j in range(n):
                    via = max(d[i][k], d[k][j])
                    if via < d[i][j]:
                        d[i][j] = via
        # The merge tree gives the same distance: the level where i and j first share a region.
        owner = list(range(n))
        tree = [[0] * n for _ in range(n)]
        for m, a, b, c in merges:
            for i in range(n):
                for j in range(n):
                    if owner[i] == a and owner[j] == b or owner[i] == b and owner[j] == a:
                        tree[i][j] = m
            owner = [c if o in (a, b) else o for o in owner]
        assert d == tree
        for i in range(n):
            for j in range(n):
                for k in range(n):
                    assert d[i][k] <= max(d[i][j], d[j][k])


def test_edges_inside_a_region_are_zero_and_float_input_works():
    labels = [[0, 0, 1], [0, 0, 1]]
    eh = [[0.5, 0.2], [0.7, 0.4]]
    ev = [[0.9, 0.9, 0.1]]
    uh, uv, merges = ultrametric_contour_map(labels, eh, ev)
    assert uh[0][0] == uh[1][0] == 0 and uv[0] == [0, 0, 0]
    assert merges == [((0.2 + 0.4) / 2, 0, 1, 2)]
    assert abs(uh[0][1] - 0.3) < 1e-12 and abs(uh[1][1] - 0.3) < 1e-12

History

Arbelaez (2006) defined the ultrametric contour map as a boundary representation of a hierarchy of regions, and built it by merging regions of an initial partition. Arbelaez, Maire, Fowlkes and Malik (2011) combined it with the gPb contour detector and the oriented watershed transform, and evaluated the result on the Berkeley segmentation data sets with the boundary F-measure and region measures. The link between ultrametrics and hierarchical clustering is older and comes from numerical taxonomy.

References

  1. Pablo Arbelaez, Boundary extraction in natural images using ultrametric contour maps, CVPR Workshop on Perceptual Organization in Computer Vision, 2006, Definition of the ultrametric contour map and its construction by region merging
  2. Pablo Arbelaez, Michael Maire, Charless Fowlkes and Jitendra Malik, Contour detection and hierarchical image segmentation, IEEE TPAMI 33(5), 898-916, 2011, Section 4.1 (oriented watershed transform), Section 4.2 (ultrametric contour map, equations 15 and 16)
  3. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 7.5, Segmentation

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