Algorithm Search⌘K

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.

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
Properties
binary labelsdeterministicexactglobal optimuminteractive
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 KK 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 II with the pixel set PP, n=WHn = WH pixels in 2D, a neighbor system N\mathcal N (8 neighbors in 2D and 26 in 3D in the paper), the object seeds O⊂PO \subset P and the background seeds G⊂PG \subset P with O∩G=∅O \cap G = \emptyset, and a weight λ≥0\lambda \ge 0. A labeling AA gives each pixel Ap=1A_p = 1 (object) or Ap=0A_p = 0 (background). The energy is (Boykov and Jolly 2001, equations 1 to 3)

E(A)=λ∑p∈PRp(Ap)+∑{p,q}∈NBpq [Ap≠Aq],E(A) = \lambda \sum_{p \in P} R_p(A_p) + \sum_{\{p, q\} \in \mathcal N} B_{pq}\, [A_p \ne A_q],

with the hard constraints (equations 4 and 5)

Ap=1 for p∈O,Ap=0 for p∈G.A_p = 1 \text{ for } p \in O, \qquad A_p = 0 \text{ for } p \in G.

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 B\mathcal B for the background seeds; this page uses GG to keep BB for the boundary term.

The region term in the paper is Rp(1)=−ln⁡Pr⁡(Ip∣O)R_p(1) = -\ln \Pr(I_p \mid O) and Rp(0)=−ln⁡Pr⁡(Ip∣G)R_p(0) = -\ln \Pr(I_p \mid G), from intensity histograms of the seeds. The boundary term is

Bpq=1dist⁡(p,q)exp⁡(−(Ip−Iq)22σ2),B_{pq} = \frac{1}{\operatorname{dist}(p, q)} \exp\Bigl(-\frac{(I_p - I_q)^2}{2 \sigma^2}\Bigr),

with σ\sigma 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 Bpq≥0B_{pq} \ge 0, 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 pp; a background seed is the mirror case. SS is the object terminal and TT the background terminal.

  1. BOYKOV-JOLLY(I, O, G, λ, σ)
  2. 1R_p(1) ← -ln Pr(I_p | histogram of O), R_p(0) ← -ln Pr(I_p | histogram of G)
  3. 2for each pair {p, q} in N do B_pq ← exp(-(I_p - I_q)² / (2σ²)) / dist(p, q)
  4. 3K ← 1 + max_p Σ_q B_pq
  5. 4make nodes P ∪ {S, T}; for each pair {p, q} add arcs p → q and q → p of capacity B_pq
  6. 5for each p in O do c(S, p) ← K, c(p, T) ← 0
  7. 6for each p in G do c(S, p) ← 0, c(p, T) ← K
  8. 7for each other p do c(S, p) ← λ R_p(0), c(p, T) ← λ R_p(1)
  9. 8f ← a maximum flow from S to T
  10. 9A_p ← 1 if p is reachable from S in the residual graph of f, else 0
  11. 10return A
  1. ADD-OBJECT-SEED(p) ▷ p is a free pixel; f is the current flow
  2. 1c_p ← λ (R_p(1) + R_p(0))
  3. 2c(S, p) ← K + c_p, c(p, T) ← c_p ▷ both capacities grow
  4. 3continue the max flow from f, then relabel as in L9 and L10

The constant KK is larger than the total boundary weight at any pixel. A cut through a seed's KK 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 (K,0)(K, 0) with cpc_p added to both terminal arcs. Every cut contains exactly one of the two arcs, so the shift adds the same cpc_p 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 20,40,140,200,22020, 40, 140, 200, 220, the object seed O={4}O = \{4\}, the background seed G={0}G = \{0\}, λ=1\lambda = 1 and σ=30\sigma = 30. The histograms have 4 bins of width 64 with add-one smoothing, so a value in the bin of the seed has probability 2/52/5 and other values have 1/51/5:

pixel 0 1 2 3 4
value 20 40 140 200 220
Rp(1)R_p(1) 1.6094 1.6094 1.6094 0.9163 0.9163
Rp(0)R_p(0) 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 0.80070.8007, 0.00390.0039, 0.13530.1353, 0.80070.8007, and K=1+0.1353+0.8007=1.9361K = 1 + 0.1353 + 0.8007 = 1.9361. Pixel 2 has equal region costs, so the boundary term decides. A cut between pixels 1 and 2 costs 0.00390.0039, and a cut between 2 and 3 costs 0.13530.1353. The maximum flow is 3.44593.4459, and the labels are 0,0,1,1,10, 0, 1, 1, 1. Theorem 1 of the correctness section says that the flow is the energy minus the region terms of the seeds: E=5.2785E = 5.2785, and the seeds add 0.9163+0.9163=1.83260.9163 + 0.9163 = 1.8326.

The user now says that pixel 2 is background. Line L11 gives c2=3.2189c_2 = 3.2189. Line L12 raises c(S,2)c(S, 2) from 1.60941.6094 to 3.21893.2189 and c(2,T)c(2, T) from 1.60941.6094 to K+c2=5.1550K + c_2 = 5.1550. Line L13 pushes more flow, up to 5.18685.1868, and the new labels are 0,0,0,1,10, 0, 0, 1, 1. The flow minus the shift, 5.1868−3.2189=1.96795.1868 - 3.2189 = 1.9679, equals the maximum flow of a new graph built from zero with the seeds {4}\{4\} and {0,2}\{0, 2\}. 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 λ≥0\lambda \ge 0, Rp≥0R_p \ge 0 and Bpq≥0B_{pq} \ge 0:

  • Lemma (feasibility). A minimum cut never cuts a KK arc of a seed, because moving the seed to its own side saves KK and costs less than KK. This is Lemma 1 of the paper.
  • Theorem (optimality). For each labeling AA that obeys the seeds, the cut that puts the object pixels on the side of SS costs E(A)E(A) minus the region terms of the seeds, a constant. So a minimum cut gives a minimum of EE 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 SS 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 cpc_p 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 PP with n=∣P∣n = |P|, a neighbor system N\mathcal N of unordered pairs, the object seeds OO and the background seeds GG, with O∩G=∅O \cap G = \emptyset. A labeling AA gives each pixel the label 1 (object) or 0 (background). The energy is

E(A)=λ∑pRp(Ap)+∑{p,q}∈NBpq [Ap≠Aq],E(A) = \lambda \sum_{p} R_p(A_p) + \sum_{\{p, q\} \in \mathcal N} B_{pq}\, [A_p \ne A_q],

and AA is feasible if Ap=1A_p = 1 for p∈Op \in O and Ap=0A_p = 0 for p∈Gp \in G. The hypotheses are λ≥0\lambda \ge 0, Rp(⋅)≥0R_p(\cdot) \ge 0 and Bpq≥0B_{pq} \ge 0. Line L1 gives Rp=−ln⁡Pr⁡≥0R_p = -\ln \Pr \ge 0, and line L2 gives Bpq>0B_{pq} > 0. If some RpR_p is negative, add the same constant to Rp(0)R_p(0) and Rp(1)R_p(1); this changes EE 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 P∪{S,T}P \cup \{S, T\}. Each pair {p,q}∈N\{p, q\} \in \mathcal N gives two arcs p→qp \to q and q→pq \to p with capacity BpqB_{pq}. Each pixel has the arcs S→pS \to p and p→Tp \to T with the capacities of lines L5 to L7:

pixel c(S,p)c(S, p) c(p,T)c(p, T)
p∈Op \in O KK 00
p∈Gp \in G 00 KK
other λRp(0)\lambda R_p(0) λRp(1)\lambda R_p(1)

with K=1+max⁡p∑q:{p,q}∈NBpqK = 1 + \max_p \sum_{q : \{p, q\} \in \mathcal N} B_{pq} (line L3). An S-T cut is a set XX of nodes with S∈XS \in X and T∉XT \notin X. Its cost c(X)c(X) is the sum of the capacities of the arcs that leave XX. Write AXA^X for the labeling with ApX=1A^X_p = 1 if and only if p∈Xp \in X.

Lemma 1 (cost of a cut). For every cut XX,

c(X)=∑p∉O∪GλRp(ApX)+∑p∈OK [ApX=0]+∑p∈GK [ApX=1]+∑{p,q}∈NBpq [ApX≠AqX].c(X) = \sum_{p \notin O \cup G} \lambda R_p(A^X_p) + \sum_{p \in O} K\,[A^X_p = 0] + \sum_{p \in G} K\,[A^X_p = 1] + \sum_{\{p, q\} \in \mathcal N} B_{pq}\, [A^X_p \ne A^X_q].

Proof. Count the arcs that leave XX. For a pixel p∈Xp \in X, the arc p→Tp \to T leaves XX and the arc S→pS \to p does not. For p∉Xp \notin X, the arc S→pS \to p leaves XX and p→Tp \to T does not. So each pixel adds exactly one of its two terminal capacities. For a free pixel this is λRp(1)\lambda R_p(1) if ApX=1A^X_p = 1 and λRp(0)\lambda R_p(0) if ApX=0A^X_p = 0. For p∈Op \in O it is 00 if p∈Xp \in X and KK if not; for p∈Gp \in G it is KK if p∈Xp \in X and 00 if not. For a pair {p,q}\{p, q\}, one of the two arcs leaves XX exactly when one end is in XX and the other is not, and then it adds BpqB_{pq}. □\square

Lemma 2 (a minimum cut is feasible). If XX is a minimum cut, then AXA^X is feasible.

Proof. Suppose p∈Op \in O and p∉Xp \notin X. Let X′=X∪{p}X' = X \cup \{p\}. By Lemma 1 the term KK of pp goes away, the terminal term of pp becomes 00, and only the pairs that contain pp change. They add at most ∑qBpq≤K−1\sum_q B_{pq} \le K - 1. So c(X′)≤c(X)−K+K−1<c(X)c(X') \le c(X) - K + K - 1 < c(X), and XX is not minimum. The case p∈Gp \in G, p∈Xp \in X is the same with X′=X∖{p}X' = X \setminus \{p\}. □\square

Theorem 1 (Boykov and Jolly 2001, Theorem 1). Let XX be a minimum cut. Then AXA^X minimizes EE over the feasible labelings, and

c(X)=E(AX)−λ∑p∈ORp(1)−λ∑p∈GRp(0).c(X) = E(A^X) - \lambda \sum_{p \in O} R_p(1) - \lambda \sum_{p \in G} R_p(0).

Proof. For a feasible labeling AA, take X={S}∪{p:Ap=1}X = \{S\} \cup \{p : A_p = 1\}. The KK terms of Lemma 1 are zero, so c(X)=E(A)−C0c(X) = E(A) - C_0 with the constant C0=λ∑p∈ORp(1)+λ∑p∈GRp(0)C_0 = \lambda \sum_{p \in O} R_p(1) + \lambda \sum_{p \in G} R_p(0), 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 E(A)−C0E(A) - C_0 over the feasible AA. □\square

The max flow

Lemma 3 (lines L8 and L9 find a minimum cut). Line L8 stops with a maximum flow ff. The set XX of nodes reachable from SS in the residual graph of ff is a minimum cut, and its cost is the value of ff.

Proof. The code augments along a shortest path in the residual graph (Edmonds-Karp). The Edmonds-Karp analysis bounds the number of augmentations by O(∣V∣∣E∣)O(|V||E|) for any start flow and any real capacities, because it uses only the residual graph: the BFS distance from SS 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, T∉XT \notin X. Every arc that leaves XX is saturated, and every arc that enters XX carries no flow, otherwise its tail would be reachable. So the value of ff equals c(X)c(X). Every flow is at most the cost of every cut, so ff is maximum and XX is minimum. This is the max-flow min-cut theorem. □\square

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 pp an object seed after a flow ff was found. The histograms do not change. Let cp=λ(Rp(1)+Rp(0))≥0c_p = \lambda (R_p(1) + R_p(0)) \ge 0. Line L12 sets the capacities of pp to c′(S,p)=K+cpc'(S, p) = K + c_p and c′(p,T)=cpc'(p, T) = c_p. The background case is the mirror image, with c′(S,p)=cpc'(S, p) = c_p and c′(p,T)=K+cpc'(p, T) = K + c_p.

Lemma 4 (the old flow stays feasible). The new capacities are at least the old ones, so ff is a feasible flow in the new network.

Proof. c′(S,p)−λRp(0)=K+λRp(1)≥0c'(S, p) - \lambda R_p(0) = K + \lambda R_p(1) \ge 0 and c′(p,T)−λRp(1)=λRp(0)≥0c'(p, T) - \lambda R_p(1) = \lambda R_p(0) \ge 0. 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. □\square

Lemma 5 (the shift does not change the minimum cut). Let N1N_1 be the network of lines L4 to L7 for the seeds O∪{p}O \cup \{p\} and GG, and let N2N_2 be the network after line L12. For every cut XX, cN2(X)=cN1(X)+cpc_{N_2}(X) = c_{N_1}(X) + c_p.

Proof. In N1N_1 the terminal capacities of pp are KK and 00; in N2N_2 they are K+cpK + c_p and cpc_p. By the proof of Lemma 1, every cut contains exactly one of the two terminal arcs of pp, so every cut cost grows by cpc_p. Nothing else differs. □\square

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 N2N_2 and a minimum cut XX of N2N_2. By Lemma 5, XX is also a minimum cut of N1N_1, so by Theorem 1 the new labels are a minimum of EE under the new seeds. The code keeps the sum of the shifts cpc_p in offset, and the flow minus the offset is the minimum cut of N1N_1. 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 V=WH+2V = WH + 2 nodes. With 8 neighbors it has about 4WH4WH neighbor pairs, so E=O(WH)E = O(WH) arcs in all. The cost model is the real-RAM: the capacities are real numbers. Lines L1 to L7 cost O(WH)O(WH) 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 O(VE2)=O(W3H3)O(V E^2) = O(W^3 H^3) time in the worst case. Push-relabel has the bound O(V3)O(V^3), 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 O(WH)O(WH) for the graph and the flow. The front matter gives the bound of the code. The best case O(WH)O(WH) 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 SS goes to pp, and the arc to TT comes from pp. Swapping Rp(0)R_p(0) and Rp(1)R_p(1) on them inverts the region term.
  • Empty histogram bins. A bin with no seed gives −ln⁡0-\ln 0. Smoothing (add-one in the code) or a floor avoids infinite costs.
  • Histograms from few seeds. A few strokes give a poor model, and λ\lambda needs tuning. The paper shows results for several values of λ\lambda.
  • 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.

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

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

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