Algorithmcore
Boykov-Jolly interactive graph cuts
Also called interactive graph cut segmentation.
Segment an object from user seeds by a minimum s-t cut. Seeds are hard constraints, and new seeds reuse the old flow, so each correction gives a new global optimum fast.
- Solves
- Interactive segmentation
- Time
- O(W^3 H^3) worst · averageO(W H) best
- Space
- O(W H) extra
- Where
- H = the image height in pixels; W = the image width in pixels
- Model
- Real RAM
- Properties
- binary labelsdeterministicexactglobal optimuminteractive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Yuri Boykov, Marie Pierre Jolly, 2001
Boykov-Jolly interactive graph cuts is an algorithm that cuts one object out of an image, or out of a 3D volume, from pixels that the user marks as object or background. These marks, the seeds, are hard constraints. Among all labelings that obey them, a minimum cut of one graph finds a labeling of least energy, where the energy adds a region term (how well each pixel fits the object or the background) and a boundary term (a cost for cutting between similar neighbors). When the user adds seeds, the algorithm continues from the old maximum flow instead of starting again. This page covers the hard constraints, the constant and the interactive loop. The general energy-to-cut construction is on image segmentation via graph cuts, and the method that refits color models in a loop is GrabCut.
In plain words
The user paints a few strokes on the object and a few on the background. The program learns the typical brightness of each from the strokes. Then it looks for the best split of the image into two parts. A good split puts each pixel with the side it looks like, and it runs along strong edges, where neighbor pixels differ a lot. The program never moves a painted pixel to the wrong side.
The best split is found exactly, by a classic method for networks of pipes. Pipes join neighbor pixels and join each pixel to an object tap and a background drain. The weakest set of pipes that stops all flow is the best split.
If the result is wrong somewhere, the user paints one more stroke there. The program keeps the old flow and only adds what the new stroke changes, so the answer comes back fast.
The problem
The input is an image with the pixel set , pixels in 2D, a neighbor system (8 neighbors in 2D and 26 in 3D in the paper), the object seeds and the background seeds with , and a weight . A labeling gives each pixel (object) or (background). The energy is (Boykov and Jolly 2001, equations 1 to 3)
with the hard constraints (equations 4 and 5)
The output is a labeling that satisfies the constraints and has the least energy among those that do. The paper writes "obj" and "bkg" for the labels 1 and 0 and for the background seeds; this page uses to keep for the boundary term.
The region term in the paper is and , from intensity histograms of the seeds. The boundary term is
with set like the camera noise. Boykov and Jolly call this term ad hoc: it is a modeling choice, not derived from a model of the image. The method needs only , so other region and boundary terms work too.
The algorithm
The first block is the segmentation from the first seeds. The second block is the update when the user adds an object seed at a pixel ; a background seed is the mirror case. is the object terminal and the background terminal.
BOYKOV-JOLLY(I, O, G, λ, σ)- 1
R_p(1) ← -ln Pr(I_p | histogram of O), R_p(0) ← -ln Pr(I_p | histogram of G) - 2
for each pair {p, q} in N do B_pq ← exp(-(I_p - I_q)² / (2σ²)) / dist(p, q) - 3
K ← 1 + max_p Σ_q B_pq - 4
make nodes P ∪ {S, T}; for each pair {p, q} add arcs p → q and q → p of capacity B_pq - 5
for each p in O do c(S, p) ← K, c(p, T) ← 0 - 6
for each p in G do c(S, p) ← 0, c(p, T) ← K - 7
for each other p do c(S, p) ← λ R_p(0), c(p, T) ← λ R_p(1) - 8
f ← a maximum flow from S to T - 9
A_p ← 1 if p is reachable from S in the residual graph of f, else 0 - 10
return A
ADD-OBJECT-SEED(p) ▷ p is a free pixel; f is the current flow- 1
c_p ← λ (R_p(1) + R_p(0)) - 2
c(S, p) ← K + c_p, c(p, T) ← c_p ▷ both capacities grow - 3
continue the max flow from f, then relabel as in L9 and L10
The constant is larger than the total boundary weight at any pixel. A cut through a seed's arc always costs more than any change of that pixel's boundary terms, so a minimum cut never puts a seed on the wrong side. Line L12 is the hard constraint with added to both terminal arcs. Every cut contains exactly one of the two arcs, so the shift adds the same to every cut. The shift makes both capacities at least their old values, so the old flow is still feasible and line L13 only adds flow.
Example
Take one row of 5 pixels with the gray values , the object seed , the background seed , and . The histograms have 4 bins of width 64 with add-one smoothing, so a value in the bin of the seed has probability and other values have :
| pixel | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| value | 20 | 40 | 140 | 200 | 220 |
| 1.6094 | 1.6094 | 1.6094 | 0.9163 | 0.9163 | |
| 0.9163 | 0.9163 | 1.6094 | 1.6094 | 1.6094 |
The boundary weights of the pairs (0,1), (1,2), (2,3), (3,4) are , , , , and . Pixel 2 has equal region costs, so the boundary term decides. A cut between pixels 1 and 2 costs , and a cut between 2 and 3 costs . The maximum flow is , and the labels are . Theorem 1 of the correctness section says that the flow is the energy minus the region terms of the seeds: , and the seeds add .
The user now says that pixel 2 is background. Line L11 gives . Line L12 raises from to and from to . Line L13 pushes more flow, up to , and the new labels are . The flow minus the shift, , equals the maximum flow of a new graph built from zero with the seeds and . Brute force over the labelings of the free pixels gives the same labels. The test file checks these numbers.
Correctness
The full proof is in proofs/correctness.md. The facts that are proved, for , and :
- Lemma (feasibility). A minimum cut never cuts a arc of a seed, because moving the seed to its own side saves and costs less than . This is Lemma 1 of the paper.
- Theorem (optimality). For each labeling that obeys the seeds, the cut that puts the object pixels on the side of costs minus the region terms of the seeds, a constant. So a minimum cut gives a minimum of under the hard constraints. This is Theorem 1 of the paper. Negative region costs are handled by adding a constant to both terms of a pixel.
- The reachable set from in the residual graph of a maximum flow is a minimum cut (max-flow min-cut theorem).
- Flow reuse. After line L12 all capacities are at least the old ones, so the old flow is feasible. The shift adds the same constant to every cut, so the minimum cut does not change. Continuing the max flow from the old flow gives the new optimum.
What is not proved: that the minimum energy labeling is the object the user has in mind. With few seeds, a short cut around a seed can win. That is a property of the energy, not of the algorithm.
Proof: Correctness of Boykov-Jolly interactive graph cutsfull
This proof covers lines L1 to L13 of the main page. The image has the pixel set with , a neighbor system of unordered pairs, the object seeds and the background seeds , with . A labeling gives each pixel the label 1 (object) or 0 (background). The energy is
and is feasible if for and for . The hypotheses are , and . Line L1 gives , and line L2 gives . If some is negative, add the same constant to and ; this changes by a constant and does not change the minimizers. Nothing here says that the minimum energy labeling is the object the user wants. That depends on the model and the seeds.
The network
The network has the nodes . Each pair gives two arcs and with capacity . Each pixel has the arcs and with the capacities of lines L5 to L7:
| pixel | ||
|---|---|---|
| other |
with (line L3). An S-T cut is a set of nodes with and . Its cost is the sum of the capacities of the arcs that leave . Write for the labeling with if and only if .
Lemma 1 (cost of a cut). For every cut ,
Proof. Count the arcs that leave . For a pixel , the arc leaves and the arc does not. For , the arc leaves and does not. So each pixel adds exactly one of its two terminal capacities. For a free pixel this is if and if . For it is if and if not; for it is if and if not. For a pair , one of the two arcs leaves exactly when one end is in and the other is not, and then it adds .
Lemma 2 (a minimum cut is feasible). If is a minimum cut, then is feasible.
Proof. Suppose and . Let . By Lemma 1 the term of goes away, the terminal term of becomes , and only the pairs that contain change. They add at most . So , and is not minimum. The case , is the same with .
Theorem 1 (Boykov and Jolly 2001, Theorem 1). Let be a minimum cut. Then minimizes over the feasible labelings, and
Proof. For a feasible labeling , take . The terms of Lemma 1 are zero, so with the constant , the region terms of the seeds that the network does not hold. This map from feasible labelings to cuts is one to one. By Lemma 2 a minimum cut is one of these cuts, so it is a minimum of over the feasible .
The max flow
Lemma 3 (lines L8 and L9 find a minimum cut). Line L8 stops with a maximum flow . The set of nodes reachable from in the residual graph of is a minimum cut, and its cost is the value of .
Proof. The code augments along a shortest path in the residual graph (Edmonds-Karp). The Edmonds-Karp analysis bounds the number of augmentations by for any start flow and any real capacities, because it uses only the residual graph: the BFS distance from to each node never decreases, and each augmentation saturates an arc that then cannot be on a shortest path again until the distance of one of its ends grows. When no augmenting path is left, . Every arc that leaves is saturated, and every arc that enters carries no flow, otherwise its tail would be reachable. So the value of equals . Every flow is at most the cost of every cut, so is maximum and is minimum. This is the max-flow min-cut theorem.
Lemmas 2 and 3 and Theorem 1 give the correctness of lines L1 to L10: the labeling of line L9 satisfies the seeds and has the least energy among the labelings that satisfy them.
Adding a seed
Lines L11 to L13 make a free pixel an object seed after a flow was found. The histograms do not change. Let . Line L12 sets the capacities of to and . The background case is the mirror image, with and .
Lemma 4 (the old flow stays feasible). The new capacities are at least the old ones, so is a feasible flow in the new network.
Proof. and . All other capacities are the same. A flow that satisfies the capacity bounds and the conservation law still does both when bounds grow. In the residual graph, the residual capacity of each changed arc grows by the same amount as its capacity, which is what line L12 adds.
Lemma 5 (the shift does not change the minimum cut). Let be the network of lines L4 to L7 for the seeds and , and let be the network after line L12. For every cut , .
Proof. In the terminal capacities of are and ; in they are and . By the proof of Lemma 1, every cut contains exactly one of the two terminal arcs of , so every cut cost grows by . Nothing else differs.
By Lemma 4, line L13 continues Edmonds-Karp from a feasible flow, and Lemma 3 holds for any start flow. So it stops with a maximum flow of and a minimum cut of . By Lemma 5, is also a minimum cut of , so by Theorem 1 the new labels are a minimum of under the new seeds. The code keeps the sum of the shifts in offset, and the flow minus the offset is the minimum cut of . The test file checks it against a new computation from zero flow.
What is not proved
The histograms of line L1 and the boundary term of line L2 are modeling choices of Boykov and Jolly; they call the boundary term ad hoc. The add-one smoothing of the histograms is a choice of this code. If the histograms are computed again after a new seed, every terminal capacity can change, some can decrease, and Lemma 4 no longer holds; the code does not do this. The GrabCut page covers a method that refits the color models.
Complexity
The graph has nodes. With 8 neighbors it has about neighbor pairs, so arcs in all. The cost model is the real-RAM: the capacities are real numbers. Lines L1 to L7 cost time, plus the number of histogram bins. The max flow of line L8 dominates. With Edmonds-Karp, as in the code of this page, it costs time in the worst case. Push-relabel has the bound , the same order here. The paper uses the augmenting path algorithm of Boykov and Kolmogorov (2004). Its worst case bound depends on the cost of the minimum cut, so it is not strongly polynomial, but on 2D grids it was faster than the other methods in their tests. That is a benchmark result on their graphs, not a bound.
After a new seed, line L13 starts from the old flow. The worst case bound is the same, but only the flow that the new seed changes must be found. Boykov and Jolly report that the update is fast in practice; that is a measurement. The extra space is for the graph and the flow. The front matter gives the bound of the code. The best case is a graph where one search finds no augmenting path.
Properties
- Global optimum for two labels. The result is an exact minimum of the energy under the seeds, not a local one, unlike active contours.
- Hard constraints. Seeds always keep their labels, so the user has direct control.
- Any dimension. Only the neighbor system changes from 2D to 3D, as in the medical volumes of the paper.
- Topology is free. The object can have holes and several parts. Each part does not need a seed.
- Shrinking bias. The boundary term adds up along the cut, so short boundaries are cheaper. Thin parts of an object can be cut off.
- Binary. The exact result is for two labels. With more labels the Potts energy is NP-hard, and methods such as alpha-expansion give approximations.
Variants and improvements
- GrabCut (Rother, Kolmogorov and Blake 2004) replaces the seeds by a box, the histograms by color Gaussian mixtures, and refits the mixtures between cuts. See GrabCut.
- Lazy Snapping (Li, Sun, Tang and Shum 2004) runs the cut on presegmented regions instead of pixels, which makes the graph small enough for very fast interaction.
- Other boundary terms. The term can use color, gradients in 3D, or a metric that approximates a geometric length when the neighbor system is large enough.
- Other max flow methods. Push-relabel, or the Boykov-Kolmogorov method, in the Boykov-Kolmogorov max flow page.
- Other energies. The same cut works for every regular pairwise binary energy, see graph representable energies.
When to use it
Use it to cut out one object when the user can mark a few pixels inside and outside, and when the object differs from the background in brightness or color, or has a clear edge. It suits 3D medical volumes as well as photos. Use intelligent scissors when the user prefers to trace the boundary, and the random walker when there are more than two labels or weak edges, where the shrinking bias of the cut hurts. Use GrabCut when the user gives only a box.
Pitfalls
- K must be larger than the boundary weight at any pixel. A smaller value can let a cut move a seed to the wrong side.
- Directed terminal arcs. The arc from goes to , and the arc to comes from . Swapping and on them inverts the region term.
- Empty histogram bins. A bin with no seed gives . Smoothing (add-one in the code) or a floor avoids infinite costs.
- Histograms from few seeds. A few strokes give a poor model, and needs tuning. The paper shows results for several values of .
- Refitting the histograms. If the histograms change after a new seed, all terminal capacities change and some can decrease. The old flow may then be infeasible, and the flow reuse of line L13 no longer applies.
- Floating point. Capacities are real numbers. Use a small tolerance when the code tests for a residual capacity of zero.
Implementations
The Python code in impl/python/boykov_jolly_graph_cuts.py builds the graph of lines L1 to L7 for a gray image with 4 or 8 neighbors, finds the maximum flow with Edmonds-Karp, and supports adding object or background seeds with flow reuse (lines L11 to L13). The tests compare the labels with brute force over all labelings of the free pixels on images of up to 12 pixels, check the identity of Theorem 1 between the flow and the energy, check that the reused flow equals a flow computed from zero after each new seed, and check the example above.
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/boykov-jolly-graph-cuts/. The authors are listed in prov/DCZHC7.jsonl.
"""Boykov-Jolly interactive graph cuts for a gray image.
Pixel p = v * w + u is (u, v) with the gray value img[v][u]. A labeling A
gives each pixel 1 (object) or 0 (background). The energy is
E(A) = lam * sum_p R_p(A_p) + sum_{p,q neighbors} B_pq [A_p != A_q],
with the hard constraints A_p = 1 on the object seeds O and A_p = 0 on the
background seeds G. The minimum cut of the graph of Boykov and Jolly (2001)
gives a labeling of minimum energy. The max flow is Edmonds-Karp on a small
residual graph; it can continue from an old flow after a seed is added.
"""
import itertools
import math
from collections import deque
def neighbor_pairs(w, h, eight=True):
"""Return the neighbor pairs (p, q) with p < q and their distance."""
steps = [(1, 0), (0, 1)]
if eight:
steps += [(1, 1), (-1, 1)]
out = []
for v in range(h):
for u in range(w):
for du, dv in steps:
uu, vv = u + du, v + dv
if 0 <= uu < w and 0 <= vv < h:
out.append((v * w + u, vv * w + uu, math.hypot(du, dv)))
return out
def histogram_costs(img, seeds, nbins, vmax):
"""Return -ln Pr(I_p | seeds) for every pixel, from a histogram with add-one smoothing."""
w = len(img[0])
counts = [0] * nbins
def bin_of(val):
return min(nbins - 1, int(val * nbins / (vmax + 1)))
for p in seeds:
counts[bin_of(img[p // w][p % w])] += 1
total = len(seeds) + nbins
return [-math.log((counts[bin_of(val)] + 1) / total) for row in img for val in row]
def boundary_weights(img, sigma, eight=True):
"""Return a list of (p, q, B_pq) with B_pq = exp(-(I_p - I_q)^2 / (2 sigma^2)) / dist(p, q)."""
h, w = len(img), len(img[0])
flat = [val for row in img for val in row]
return [(p, q, math.exp(-((flat[p] - flat[q]) ** 2) / (2 * sigma * sigma)) / d)
for p, q, d in neighbor_pairs(w, h, eight)]
class FlowGraph:
"""A residual graph with Edmonds-Karp augmentation that can be resumed."""
def __init__(self, n):
self.n = n
self.res = [dict() for _ in range(n)]
self.flow = 0.0
def add_capacity(self, a, b, c):
self.res[a][b] = self.res[a].get(b, 0.0) + c
self.res[b].setdefault(a, 0.0)
def max_flow(self, s, t, eps=1e-12):
"""Augment along shortest paths until no s-t path is left; return the total flow."""
while True:
parent = {s: None}
queue = deque([s])
while queue and t not in parent:
a = queue.popleft()
for b, c in self.res[a].items():
if c > eps and b not in parent:
parent[b] = a
queue.append(b)
if t not in parent:
return self.flow
path = []
b = t
while parent[b] is not None:
path.append((parent[b], b))
b = parent[b]
delta = min(self.res[a][b] for a, b in path)
for a, b in path:
self.res[a][b] -= delta
self.res[b][a] += delta
self.flow += delta
def source_side(self, s, eps=1e-12):
"""Return the set of nodes reachable from s in the residual graph."""
seen = {s}
queue = deque([s])
while queue:
a = queue.popleft()
for b, c in self.res[a].items():
if c > eps and b not in seen:
seen.add(b)
queue.append(b)
return seen
class InteractiveCut:
"""Boykov-Jolly segmentation with seeds that can be added after the first cut."""
def __init__(self, img, obj, bkg, lam, sigma, nbins=4, vmax=255, eight=True, region=None):
h, w = len(img), len(img[0])
n = w * h
self.n, self.lam = n, lam
self.obj, self.bkg = set(obj), set(bkg)
if self.obj & self.bkg:
raise ValueError("a pixel cannot be an object seed and a background seed")
if region is None:
r_obj = histogram_costs(img, sorted(self.obj), nbins, vmax) # @line L1
r_bkg = histogram_costs(img, sorted(self.bkg), nbins, vmax)
else:
r_obj, r_bkg = region
self.r_obj, self.r_bkg = r_obj, r_bkg
self.pairs = boundary_weights(img, sigma, eight) # @line L2
deg = [0.0] * n
for p, q, b in self.pairs:
deg[p] += b
deg[q] += b
self.K = 1.0 + max(deg) # @line L3
self.s, self.t = n, n + 1
g = FlowGraph(n + 2) # @line L4
for p, q, b in self.pairs:
g.add_capacity(p, q, b)
g.add_capacity(q, p, b)
for p in range(n):
if p in self.obj: # @line L5
g.add_capacity(self.s, p, self.K)
g.add_capacity(p, self.t, 0.0)
elif p in self.bkg: # @line L6
g.add_capacity(self.s, p, 0.0)
g.add_capacity(p, self.t, self.K)
else: # @line L7
g.add_capacity(self.s, p, lam * r_bkg[p])
g.add_capacity(p, self.t, lam * r_obj[p])
self.g = g
self.offset = 0.0
self.augment()
def augment(self):
self.g.max_flow(self.s, self.t) # @line L8
side = self.g.source_side(self.s)
self.labels = [1 if p in side else 0 for p in range(self.n)] # @line L9
return self.labels # @line L10
def cut_value(self):
"""The minimum cut of the original construction, without the offsets of added seeds."""
return self.g.flow - self.offset
def add_seed(self, p, label):
"""Make pixel p a hard object (label 1) or background (label 0) seed and resume the flow."""
if p in self.obj or p in self.bkg:
if (p in self.obj) == (label == 1):
return self.labels
raise ValueError("pixel already has the other seed label")
c = self.lam * (self.r_obj[p] + self.r_bkg[p]) # @line L11
if label == 1:
self.g.res[self.s][p] += self.K + c - self.lam * self.r_bkg[p] # @line L12
self.g.res[p][self.t] += c - self.lam * self.r_obj[p]
self.obj.add(p)
else:
self.g.res[self.s][p] += c - self.lam * self.r_bkg[p]
self.g.res[p][self.t] += self.K + c - self.lam * self.r_obj[p]
self.bkg.add(p)
self.offset += c
return self.augment() # @line L13
def energy(labels, r_obj, r_bkg, pairs, lam):
"""E(A) = lam * sum_p R_p(A_p) + sum B_pq [A_p != A_q]."""
e = sum(lam * (r_obj[p] if a == 1 else r_bkg[p]) for p, a in enumerate(labels))
return e + sum(b for p, q, b in pairs if labels[p] != labels[q])
def brute_force(n, obj, bkg, r_obj, r_bkg, pairs, lam):
"""Return the minimum energy and all minimizing labelings that satisfy the seeds."""
free = [p for p in range(n) if p not in obj and p not in bkg]
best, arg = math.inf, []
for bits in itertools.product((0, 1), repeat=len(free)):
lab = [1 if p in obj else 0 for p in range(n)]
for p, a in zip(free, bits):
lab[p] = a
e = energy(lab, r_obj, r_bkg, pairs, lam)
if e < best - 1e-9:
best, arg = e, [lab]
elif abs(e - best) <= 1e-9:
arg.append(lab)
return best, arg
def seed_constant(obj, bkg, r_obj, r_bkg, lam):
"""The energy of the seeds' region terms, which the cut does not see (Theorem 1)."""
return sum(lam * r_obj[p] for p in obj) + sum(lam * r_bkg[p] for p in bkg)
test_boykov_jolly_graph_cuts.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boykov-jolly-graph-cuts/. The authors are listed in prov/DCZHC7.jsonl.
import math
import random
import pytest
from boykov_jolly_graph_cuts import (
InteractiveCut,
boundary_weights,
brute_force,
energy,
histogram_costs,
seed_constant,
)
def random_case(rng, w, h, nseed):
img = [[rng.choice((20, 60, 140, 220)) + rng.randrange(20) for _ in range(w)] for _ in range(h)]
pix = list(range(w * h))
rng.shuffle(pix)
obj = pix[:nseed]
bkg = pix[nseed:2 * nseed]
return img, obj, bkg
def test_row_example():
img = [[20, 40, 140, 200, 220]]
c = InteractiveCut(img, [4], [0], 1.0, 30.0)
assert abs(c.r_obj[0] - 1.6094) < 1e-4 and abs(c.r_obj[4] - 0.9163) < 1e-4
assert abs(c.pairs[1][2] - 0.0039) < 1e-4 and abs(c.pairs[2][2] - 0.1353) < 1e-4
assert abs(c.K - 1.9361) < 1e-4
assert c.labels == [0, 0, 1, 1, 1]
assert abs(c.g.flow - 3.4459) < 1e-4
e = energy(c.labels, c.r_obj, c.r_bkg, c.pairs, 1.0)
assert abs(e - 5.2785) < 1e-4
assert c.add_seed(2, 0) == [0, 0, 0, 1, 1]
assert abs(c.g.flow - 5.1868) < 1e-4
assert abs(c.cut_value() - 1.9679) < 1e-4
def test_cut_is_constrained_minimum():
rng = random.Random(1)
for trial in range(25):
w, h = rng.choice(((3, 3), (4, 3), (3, 4)))
img, obj, bkg = random_case(rng, w, h, rng.randint(1, 2))
lam = rng.choice((0.1, 0.5, 1.0, 3.0))
eight = trial % 2 == 0
c = InteractiveCut(img, obj, bkg, lam, 25.0, eight=eight)
for p in obj:
assert c.labels[p] == 1
for p in bkg:
assert c.labels[p] == 0
best, _ = brute_force(w * h, set(obj), set(bkg), c.r_obj, c.r_bkg, c.pairs, lam)
e = energy(c.labels, c.r_obj, c.r_bkg, c.pairs, lam)
assert abs(e - best) < 1e-9
const = seed_constant(obj, bkg, c.r_obj, c.r_bkg, lam)
assert abs(c.g.flow - (best - const)) < 1e-9
def test_given_region_costs_four_neighbors():
rng = random.Random(2)
for _ in range(15):
w, h = 4, 3
img = [[rng.randrange(256) for _ in range(w)] for _ in range(h)]
r_obj = [rng.uniform(0, 3) for _ in range(w * h)]
r_bkg = [rng.uniform(0, 3) for _ in range(w * h)]
c = InteractiveCut(img, [0], [11], 1.0, 40.0, eight=False, region=(r_obj, r_bkg))
best, arg = brute_force(w * h, {0}, {11}, r_obj, r_bkg, c.pairs, 1.0)
assert abs(energy(c.labels, r_obj, r_bkg, c.pairs, 1.0) - best) < 1e-9
assert len(arg) >= 1
def test_added_seeds_reuse_flow():
rng = random.Random(3)
for _ in range(10):
w, h = 4, 3
img, obj, bkg = random_case(rng, w, h, 1)
c = InteractiveCut(img, obj, bkg, 1.0, 25.0)
free = [p for p in range(w * h) if p not in obj and p not in bkg]
rng.shuffle(free)
for p in free[:4]:
label = rng.randrange(2)
c.add_seed(p, label)
o = [q for q in range(w * h) if q in c.obj]
g = [q for q in range(w * h) if q in c.bkg]
fresh = InteractiveCut(img, o, g, 1.0, 25.0, region=(c.r_obj, c.r_bkg))
assert abs(c.cut_value() - fresh.g.flow) < 1e-9
assert c.labels[p] == label
best, _ = brute_force(w * h, set(o), set(g), c.r_obj, c.r_bkg, c.pairs, 1.0)
assert abs(energy(c.labels, c.r_obj, c.r_bkg, c.pairs, 1.0) - best) < 1e-9
for a in range(w * h + 2):
for cap in c.g.res[a].values():
assert cap >= -1e-12
def test_large_lambda_follows_region_term():
rng = random.Random(4)
w, h = 4, 3
img = [[rng.randrange(256) for _ in range(w)] for _ in range(h)]
r_obj = [rng.uniform(0, 3) for _ in range(w * h)]
r_bkg = [rng.uniform(0, 3) for _ in range(w * h)]
c = InteractiveCut(img, [0], [11], 1000.0, 40.0, region=(r_obj, r_bkg))
for p in range(1, 11):
assert c.labels[p] == (1 if r_obj[p] < r_bkg[p] else 0)
def test_helpers_and_errors():
img = [[0, 0], [255, 255]]
costs = histogram_costs(img, [0, 1], 2, 255)
assert abs(costs[0] + math.log(3 / 4)) < 1e-12
assert abs(costs[2] + math.log(1 / 4)) < 1e-12
pairs = boundary_weights(img, 10.0, eight=False)
assert len(pairs) == 4
with pytest.raises(ValueError):
InteractiveCut(img, [0], [0], 1.0, 10.0)
c = InteractiveCut(img, [0], [3], 1.0, 10.0)
with pytest.raises(ValueError):
c.add_seed(0, 0)
History
Greig, Porteous and Seheult (1989) showed that a minimum cut gives the exact maximum a posteriori estimate of a binary image under an Ising prior. For a decade after that, graph cuts in vision were used mostly for stereo and restoration. Boykov and Jolly (2001) turned the cut into an interactive tool: the user's seeds became hard constraints, the region term came from the seeds, and the flow was reused after each correction. They showed results on photos and on medical images, among them a kidney in a 3D MR angiography volume. Boykov and Kolmogorov (2004) published the max flow algorithm that made such cuts fast on image grids. GrabCut and Lazy Snapping followed in 2004.
References
- Yuri Y. Boykov and Marie-Pierre Jolly, Interactive graph cuts for optimal boundary and region segmentation of objects in N-D images, ICCV 2001, vol. I, 105-112, Section 2 (energy with hard constraints, equations 1 to 5), Section 3 (graph, Lemma 1 and Theorem 1, the update for new seeds), Section 4 (examples)
- Yuri Boykov and Vladimir Kolmogorov, An experimental comparison of min-cut/max-flow algorithms for energy minimization in vision, IEEE TPAMI 26(9), 1124-1137, 2004, The augmenting path algorithm used for the max flow, and its timings on vision graphs
- Richard Szeliski, Computer Vision: Algorithms and Applications, 1st edition, Springer, 2011, Section 5.5, Graph cuts and energy-based methods
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 DCZHC7 Edit this page History Report an error Markdown