Definitionadvanced
Boundary F-measure
Also called BSDS boundary benchmark, boundary precision and recall.
The harmonic mean of precision and recall of predicted boundary pixels matched to human boundaries within a small distance by bipartite matching.
The boundary F-measure scores a boundary map against human boundary maps. A predicted boundary pixel is correct if it can be paired with a human boundary pixel within a small distance, and each human pixel can be used only once. The pairs come from a maximum bipartite matching. Precision is the share of predicted pixels that are matched, recall is the share of human pixels that are matched, and the F-measure is their harmonic mean. Martin, Fowlkes and Malik (2004) defined it for the Berkeley Segmentation Data Set (BSDS), and it is the standard score of edge detection and of the boundaries of segmentations.
Definition
Let be the set of predicted boundary pixels of an image, the set of human boundary pixels, and a distance tolerance in pixels. The graph has an edge between and when . Let be the size of a maximum matching of . Then
This page sets when is empty, when is empty, and when .
BSDS has several human segmentations of each image. The counts are then summed: a predicted pixel counts for precision if it is matched to at least one human map, and recall is the number of matched human pixels over the number of all human pixels.
BOUNDARY-F(B, G, d)- 1
E ← the pairs (b, g) with b ∈ B, g ∈ G and ‖b - g‖ ≤ d - 2
M ← a maximum matching of the bipartite graph (B, G, E), by augmenting paths - 3
P ← |M| / |B| ; R ← |M| / |G| - 4
return P, R and 2 P R / (P + R) BSDS-COUNTS(B, G_1, ..., G_H, d)- 5
A ← ∅ ; c_R ← 0 ; s_R ← 0 - 6
for h ← 1 to H do - 7
M ← a maximum matching of the graph for B, G_h and d - 8
A ← A ∪ (the pixels of B matched in M) ; c_R ← c_R + |M| ; s_R ← s_R + |G_h| - 9
return (|A|, |B|, c_R, s_R) ▷ P = |A| / |B|, R = c_R / s_R
The proof file shows that line L2 finds a maximum matching, so that and are the largest values that any one-to-one rule within the tolerance can give (a theorem). Larger never lowers them, and swapping and swaps and . With several humans the recall does not depend on which maximum matching is found, but the precision can, so a program must fix the rule.
The tolerance in the benchmark code is a fraction of the image diagonal, 0.0075 by default, which is about 4 pixels for the BSDS images of pixels. A detector gives a soft map , and a threshold gives . Arbelaez et al. (2011) report three numbers over a range of thresholds:
- ODS, the optimal data set scale: the counts of all images are summed at each , and the best over is reported.
- OIS, the optimal image scale: each image gets its own best , and the counts at those thresholds are summed.
- AP, the average precision: the area under the precision and recall curve over .
The Python code of this page uses augmenting paths, which take time for edges, with . The Hopcroft-Karp algorithm needs . The reference code of the benchmark solves an assignment problem on the same graph.
Examples and non-examples
- A double edge. The human boundary is a vertical line of 4 pixels in column 2. The prediction is two lines, in columns 1 and 3, with . Every predicted pixel is within distance 1 of a human pixel, but each human pixel can take only one of its two neighbors. So , , and . A rule that only asks for a human pixel within would give and reward thick or doubled edges.
- Tolerance. The same line moved by one pixel gives for and for . On a image the default tolerance is pixels, so only exact positions match. The tolerance must be stated with the score.
- Two humans. The prediction is the line in column 2. One human drew it in column 2 and another in column 4, with . All 4 predicted pixels match the first human, so . Recall is , and .
- ODS against OIS. Two images of one row of 4 pixels, each with one human pixel at position 0, and . The soft maps are and , with thresholds 0.5 and 0.7. At 0.5 the sums are 2 matched pixels of 3 predicted and 2 human pixels, so . At 0.7 they are 1 of 1 and 2, so . ODS is at 0.5. OIS takes 0.7 for the first image and 0.5 for the second, and gets . OIS is often above ODS, but the proof file gives a case where it is below.
- Not a region score. The boundary F-measure ignores the labels of regions. A segmentation with the right boundaries but one missing piece of boundary loses only a little recall, while it merges two regions. Region scores such as the mean intersection over union for labels, or the Rand index for partitions, see this.
- Not the Hausdorff distance. The Hausdorff distance gives the worst distance between the two sets and is ruled by one outlier. The boundary F-measure counts pixels within a fixed tolerance and ignores how far the unmatched ones are.
Related definitions
Precision and recall are the general ratios, and the boundary F-measure computes them on pixels with a tolerance and a one-to-one rule. The matching is a maximum bipartite matching, and with distances as costs it becomes an assignment problem. A distance transform of the human map gives a faster test of whether some human pixel is within , but it does not enforce the one-to-one rule. The ultrametric contour map gives a soft boundary map whose thresholds are segmentations, and its quality is reported with ODS, OIS and AP. For a learned or classical detector such as Canny, the threshold sweep gives the precision and recall curve. Scores for segmentations as partitions, such as segmentation covering and the variation of information, appear in the same benchmark next to the boundary F-measure.
The Python code of this page computes the matching, the scores for one and for several humans, and ODS and OIS with exact fractions. Its tests compare the matching with a brute-force maximum matching on small random maps.
Proof: The matching gives the largest one-to-one count, and properties of boundary precision and recallfull
We use the notation of the page. is the set of machine boundary pixels and the set of human boundary pixels, both finite sets of integer points. For a tolerance the graph has the left vertices , the right vertices , and an edge when in the Euclidean norm. A matching is a set of edges with no shared end. The procedure BOUNDARY-F builds the edges in line L1, finds a matching in line L2 and returns , and in lines L3 and L4.
Lemma 1 (the edges). Line L1 lists exactly the edges of .
Proof. If for integers and , then , so , and the same for . So the scan of the offsets in meets every edge, and the test keeps exactly the edges.
Lemma 2 (the matching is maximum). After line L2, is a maximum matching of .
Proof. Number the machine pixels in the order of the loop, and let be the subgraph with left vertices and all of . We show by induction on that after the search from , the matching is a maximum matching of . For the empty matching is maximum.
Step . Let be maximum in . One more vertex raises the size of a maximum matching by at most 1, so the maximum in is or . By Berge's theorem, it is exactly when has an augmenting path for : a path that alternates between edges outside and inside and joins a free left vertex to a free right vertex. Such a path has one left end and one right end. If it does not contain , it lies in , which is impossible since is maximum there. If it contains , then is free and has degree at most 1 on the path, so is its left end.
The search from is a depth-first search in the directed graph that goes from a left vertex to a right vertex along an edge outside , and from a matched right vertex to its partner along . It marks each right vertex at most once, and it stops when it reaches a free right vertex. A depth-first search reaches every vertex that is reachable from its start, so it finds a free right vertex if and only if one is reachable from , that is, if and only if an augmenting path from exists. A reachable vertex is reached along a simple path, and the search flips the edges of that path, which raises by 1 and keeps a matching. So after step , is maximum in .
Theorem 1 (the scores). Let be the size of a maximum matching of , with and not empty.
- and , and does not depend on which maximum matching is found.
- No assignment of machine pixels to distinct human pixels within distance has more than correct pixels. So and are the largest values that any one-to-one rule within the tolerance can give.
- if and only if , that is, if has a perfect matching.
- Swapping and swaps and and keeps .
- If , then the and for are at least those for .
Proof. (1) . All maximum matchings have the same size. (2) Such an assignment is a matching of . (3) is the harmonic mean of and , which is 1 exactly when both are 1. (4) The graph is the same with the sides swapped. (5) is a subgraph of , so a matching of the first is a matching of the second.
The value of is not the score of a nearest-neighbor rule. If each machine pixel is called correct when some human pixel is within , without the one-to-one rule, then a double line of machine pixels on both sides of a human line gets the precision 1. With the matching it gets , as in the example of the page.
Several humans. BSDS-COUNTS takes human maps . For each one it finds a maximum matching in line L7. The precision is with the set of machine pixels matched in at least one , and the recall is .
Proposition 2. With several humans, . The recall does not depend on the choice of the maximum matchings, but the precision can.
Proof. and give the range. Each is the same for all maximum matchings. For the second claim, let , and with . The graph for has the edge from only. For , both machine pixels are at distance 1, and either one can be matched. If is chosen for , then and ; if is chosen, then and .
A program must fix the rule that picks the matching. The rule of this page is the order of the loop of line L2. The reference BSDS code computes the matching in another way, and its precision can differ in such ties.
Thresholds. For a soft boundary map and a threshold , let . ODS sums the four counts of every image at a common and takes the with the largest of the sums. OIS takes for each image the with the largest of that image and sums the counts at those thresholds.
Proposition 3. On a data set of one image, ODS equals OIS. On larger data sets OIS can be above ODS or below it.
Proof. With one image both choose the threshold that maximizes the of that image. With one human map per image the counts are , where is the size of the matching, and , and then .
The example of the page has OIS 1 above ODS . For the other direction take , so only equal pixels match, the thresholds 0.3, 0.6 and 0.9, and two images of one row of 6 pixels. Image 1 has and human pixels at positions 0, 2 and 4. Image 2 has and human pixels at positions 0, 3 and 5. The pairs at the three thresholds are , and for image 1, and , and for image 2, with for both. The values of are , , for image 1 and , , for image 2, so OIS picks 0.3 for image 1 and 0.9 for image 2, each the unique best. The sums are , , , so OIS is . At the common threshold 0.3 the sums are , , , with . So ODS is at least , above OIS.
That OIS is above ODS on BSDS for the methods in the literature is a benchmark result, not a theorem.
Cost. Each machine pixel has at most candidate neighbors, so line L1 takes time with a hash set of . Each search of line L2 takes time with edges, so line L2 takes in the worst case. The Hopcroft-Karp algorithm reduces this to .
Code
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/boundary-f-measure/. The authors are listed in prov/87X9C9.jsonl.
"""Boundary precision, recall and F-measure with one-to-one matching within a distance.
A boundary map is a list of rows of 0 and 1, bmap[v][u]. Two boundary pixels
can be matched if their Euclidean distance is at most d. The number of correct
pixels is the size of a maximum matching of the bipartite graph of such pairs,
found with augmenting paths (Kuhn's method). Counts are integers and scores are
Fractions. An empty map gives precision or recall 0, and F is 0 when both are 0.
Standard library only.
"""
import math
from fractions import Fraction
def points(bmap):
return [(u, v) for v, row in enumerate(bmap) for u, x in enumerate(row) if x]
def boundary_of(labels):
"""Pixel (u, v) is a boundary pixel if its right or lower neighbor has another label."""
h, w = len(labels), len(labels[0])
out = [[0] * w for _ in range(h)]
for v in range(h):
for u in range(w):
if (u + 1 < w and labels[v][u + 1] != labels[v][u]) or (v + 1 < h and labels[v + 1][u] != labels[v][u]):
out[v][u] = 1
return out
def max_matching(bpts, gpts, d):
"""Return a maximum matching as a dict from index in bpts to index in gpts."""
r = int(math.floor(d))
where = {p: j for j, p in enumerate(gpts)}
adj = []
for (u, v) in bpts: # @line L1
nb = []
for dv in range(-r, r + 1):
for du in range(-r, r + 1):
if du * du + dv * dv <= d * d and (u + du, v + dv) in where:
nb.append(where[(u + du, v + dv)])
adj.append(nb)
owner = {}
def augment(i, seen):
for j in adj[i]:
if j not in seen:
seen.add(j)
if j not in owner or augment(owner[j], seen):
owner[j] = i
return True
return False
for i in range(len(bpts)): # @line L2
augment(i, set())
return {i: j for j, i in owner.items()}
def f_of(p, r):
return 2 * p * r / (p + r) if p + r > 0 else Fraction(0)
def boundary_f(bmap, gmap, d):
"""Return (precision, recall, F) of the boundary map bmap against one human map gmap."""
bpts, gpts = points(bmap), points(gmap)
m = max_matching(bpts, gpts, d)
p = Fraction(len(m), len(bpts)) if bpts else Fraction(0) # @line L3
r = Fraction(len(m), len(gpts)) if gpts else Fraction(0)
return p, r, f_of(p, r) # @line L4
def bsds_counts(bmap, gmaps, d):
"""Counts over several human maps: (matched machine pixels, machine pixels, matched human pixels, human pixels)."""
bpts = points(bmap)
acc = set() # @line L5
cnt_r = sum_r = 0
for gmap in gmaps: # @line L6
gpts = points(gmap)
m = max_matching(bpts, gpts, d) # @line L7
acc |= set(m) # @line L8
cnt_r += len(m)
sum_r += len(gpts)
return len(acc), len(bpts), cnt_r, sum_r # @line L9
def scores(cnt_p, sum_p, cnt_r, sum_r):
p = Fraction(cnt_p, sum_p) if sum_p else Fraction(0)
r = Fraction(cnt_r, sum_r) if sum_r else Fraction(0)
return p, r, f_of(p, r)
def threshold(soft, t):
return [[1 if x >= t else 0 for x in row] for row in soft]
def ods_ois(softs, gmaps_list, thresholds, d):
"""ODS: one threshold for the whole data set. OIS: the best threshold of each image, then summed counts.
Return (ODS F, ODS threshold, OIS F).
"""
table = [[bsds_counts(threshold(s, t), g, d) for t in thresholds] for s, g in zip(softs, gmaps_list)]
best_f, best_t = Fraction(-1), None
for k, t in enumerate(thresholds):
tot = [sum(row[k][q] for row in table) for q in range(4)]
f = scores(*tot)[2]
if f > best_f:
best_f, best_t = f, t
tot = [0, 0, 0, 0]
for row in table:
k = max(range(len(thresholds)), key=lambda k: (scores(*row[k])[2], -k))
tot = [a + b for a, b in zip(tot, row[k])]
return best_f, best_t, scores(*tot)[2]
test_boundary_f_measure.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boundary-f-measure/. The authors are listed in prov/87X9C9.jsonl.
import random
from fractions import Fraction
from boundary_f_measure import (boundary_f, boundary_of, bsds_counts, max_matching, ods_ois, points, scores,
threshold)
def line(u, w=6, h=4):
return [[1 if x == u else 0 for x in range(w)] for _ in range(h)]
def brute_matching_size(bpts, gpts, d):
def best(i, used):
if i == len(bpts):
return 0
top = best(i + 1, used)
(u, v) = bpts[i]
for j, (x, y) in enumerate(gpts):
if j not in used and (u - x) ** 2 + (v - y) ** 2 <= d * d:
top = max(top, 1 + best(i + 1, used | {j}))
return top
return best(0, frozenset())
def random_map(rng, w, h, rate):
return [[1 if rng.random() < rate else 0 for _ in range(w)] for _ in range(h)]
def test_double_line_example():
b = [[1 if x in (1, 3) else 0 for x in range(6)] for _ in range(4)]
assert boundary_f(b, line(2), 1) == (Fraction(1, 2), 1, Fraction(2, 3))
assert boundary_f(b, line(2), 0.5) == (0, 0, 0)
def test_two_humans_example():
assert scores(*bsds_counts(line(2), [line(2), line(4)], 1)) == (1, Fraction(1, 2), Fraction(2, 3))
def test_matching_is_maximum_and_valid():
rng = random.Random(41)
for _ in range(60):
b, g = random_map(rng, 5, 4, 0.3), random_map(rng, 5, 4, 0.3)
bp, gp = points(b), points(g)
if len(bp) > 7 or len(gp) > 7:
continue
d = rng.choice([0.5, 1, 1.5, 2.3])
m = max_matching(bp, gp, d)
assert len(set(m.values())) == len(m)
for i, j in m.items():
assert (bp[i][0] - gp[j][0]) ** 2 + (bp[i][1] - gp[j][1]) ** 2 <= d * d
assert len(m) == brute_matching_size(bp, gp, d)
def test_identity_symmetry_and_shift():
rng = random.Random(42)
for _ in range(10):
b, g = random_map(rng, 8, 8, 0.2), random_map(rng, 8, 8, 0.2)
if not points(b) or not points(g):
continue
assert boundary_f(b, b, 1)[2] == 1
p, r, f = boundary_f(b, g, 1.5)
q, s, f2 = boundary_f(g, b, 1.5)
assert (p, r, f) == (s, q, f2)
assert boundary_f(line(3), line(2), 1)[2] == 1
assert boundary_f(line(3), line(2), 0.99)[2] == 0
def test_larger_tolerance_never_lowers_scores():
rng = random.Random(43)
b, g = random_map(rng, 10, 10, 0.15), random_map(rng, 10, 10, 0.15)
last = (0, 0)
for d in (0, 1, 1.5, 2, 3, 5):
p, r, _ = boundary_f(b, g, d)
assert p >= last[0] and r >= last[1]
last = (p, r)
def test_boundary_of_two_regions():
labels = [[0, 0, 1, 1] for _ in range(3)]
assert boundary_of(labels) == [[0, 1, 0, 0] for _ in range(3)]
def test_ods_and_ois_example():
s1, s2 = [[0.9, 0.6, 0.0, 0.0]], [[0.6, 0.0, 0.0, 0.0]]
g = [[[1, 0, 0, 0]]]
assert bsds_counts(threshold(s1, 0.5), g, 0.5) == (1, 2, 1, 1)
assert ods_ois([s1, s2], [g, g], [0.5, 0.7], 0.5) == (Fraction(4, 5), 0.5, 1)
f_ods, _, f_ois = ods_ois([s1], [g], [0.5, 0.7], 0.5)
assert f_ods == f_ois == 1
def test_ois_can_be_below_ods():
s1, g1 = [[0, 0.9, 0.3, 0.9, 0.6, 0.3]], [[[1, 0, 1, 0, 1, 0]]]
s2, g2 = [[0.9, 0, 0.6, 0.9, 0.6, 0.3]], [[[1, 0, 0, 1, 0, 1]]]
assert ods_ois([s1, s2], [g1, g2], [0.3, 0.6, 0.9], 0.5) == (Fraction(5, 8), 0.3, Fraction(8, 13))
def test_empty_maps():
z = [[0] * 4 for _ in range(4)]
assert boundary_f(z, line(1, 4, 4), 1) == (0, 0, 0)
assert boundary_f(line(1, 4, 4), z, 1) == (0, 0, 0)
References
- David R. Martin, Charless C. Fowlkes and Jitendra Malik, Learning to detect natural image boundaries using local brightness, color, and texture cues, IEEE Transactions on Pattern Analysis and Machine Intelligence 26(5), 2004, 530-549, the evaluation methodology (the correspondence of machine and human boundary pixels within a distance tolerance as a bipartite assignment, precision, recall and the F-measure, several human segmentations per image)
- Pablo Arbelaez, Michael Maire, Charless Fowlkes and Jitendra Malik, Contour detection and hierarchical image segmentation, IEEE Transactions on Pattern Analysis and Machine Intelligence 33(5), 2011, 898-916, Section 4.3 and Section 4.4.1 (precision and recall of boundaries, the F-measure at the optimal data set scale ODS, at the optimal image scale OIS, and the average precision AP)
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 7.5, Image segmentation (the evaluation of boundaries and regions on the Berkeley data set)
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 | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 87X9C9 Edit this page History Report an error Markdown