Algorithm Search⌘K

Algorithmcore

Intelligent scissors

Also called live wire, Mortensen-Barrett live wire.

Trace an object boundary interactively. A least cost path on the pixel graph, from a seed point to the cursor, snaps to edges; the cost mixes Laplacian zero crossings, gradient size and direction.

Time
O(W H log(W H)) worst · averageO(W H) best
Space
O(W H) extra
Where
H = the image height in pixels; W = the image width in pixels
Properties
deterministicexactinteractivenonnegative costs
Origin
Eric N. Mortensen, William A. Barrett, 1995

Intelligent scissors, also called live wire, is an interactive algorithm that traces the boundary of an object as a least cost path on the graph of pixels. The user clicks a seed point on the boundary. The algorithm then computes, with Dijkstra's algorithm, the least cost path from the seed to every pixel. As the user moves the cursor, the path from the seed to the cursor is shown at once, and it snaps to nearby edges because the link costs are low on edges. Mortensen and Barrett (1995) defined the cost from the Laplacian zero crossings, the gradient magnitude and the gradient direction. The user fixes a piece of the path by clicking a new seed, and goes on around the object.

In plain words

You want to cut a person out of a photo. Tracing the outline by hand needs a steady hand and a lot of time. With intelligent scissors you click once on the outline. Then, when you move the mouse near the outline, a wire appears from your click to the mouse, and it clings to the outline by itself. The wire is the cheapest route between the two points, where walking along a strong edge is cheap and walking across smooth areas is costly. When the wire looks right, you click again to fix that piece, and continue. A few clicks go around the whole object. The program computes the cheapest route to every pixel right after each click, so the wire can follow the mouse without delay.

The problem

The input is a gray image II of W×HW \times H pixels and a seed pixel ss. The graph has one node per pixel and a directed link from each pixel pp to each of its 8 neighbors qq, with a cost l(p,q)≥0l(p, q) \ge 0. The output is, for each pixel tt, the least total cost g(t)g(t) of a path from ss to tt, and back pointers that give such a path. The boundary piece shown to the user is the path from ss to the cursor. This is the single-source shortest path problem on a grid graph with n=WHn = WH nodes and at most 8n8n links.

The local cost of Mortensen and Barrett (1995, Section 3.1, equation 1) is

l(p,q)=ωZfZ(q)+ωGfG(q)+ωDfD(p,q),l(p, q) = \omega_Z f_Z(q) + \omega_G f_G(q) + \omega_D f_D(p, q),

with the weights printed in the paper: ωZ=0.43\omega_Z = 0.43, ωG=0.43\omega_G = 0.43 and ωD=0.14\omega_D = 0.14. The three features are:

  • Laplacian zero crossing fZ(q)f_Z(q): 00 if qq lies on a zero crossing of the Laplacian of the image, else 11. On the discrete grid the Laplacian rarely equals zero, so of two neighbors with opposite signs, the one closer to zero is the crossing.
  • Gradient magnitude fG(q)=1−G(q)/max⁡Gf_G(q) = 1 - G(q)/\max G with G=Iu2+Iv2G = \sqrt{I_u^2 + I_v^2}, so strong edges are cheap. It is scaled by 11 when qq is a diagonal neighbor of pp and by 1/21/\sqrt 2 when qq is a horizontal or vertical neighbor. This weights the cost by the length of the link and keeps the maximum at 1.
  • Gradient direction fD(p,q)=23π(arccos⁡(D(p)⋅L)+arccos⁡(L⋅D(q)))f_D(p, q) = \frac{2}{3\pi} \bigl(\arccos(D(p) \cdot L) + \arccos(L \cdot D(q))\bigr). Here D(p)=(Iv(p),−Iu(p))/G(p)D(p) = (I_v(p), -I_u(p)) / G(p) is the unit vector along the edge, the gradient turned by 90 degrees. LL is the unit vector of the link from pp to qq, or its negative, chosen so that D(p)⋅L≥0D(p) \cdot L \ge 0. The cost is low when the link runs along the edge at both ends, and high at sharp turns.

The weights are design choices that the authors tuned. They are not derived from a model.

The algorithm

The first block is the "live-wire 2D dynamic programming" search of Mortensen and Barrett (1995, Section 3.2). It is Dijkstra's algorithm. The active list L\mathcal L holds the pixels with a tentative cost, and e(q)e(q) marks the expanded pixels.

  1. LIVE-WIRE(s, l)
  2. 1g(s) ← 0; 𝓛 ← {s}; e(q) ← false for every pixel q
  3. 2while 𝓛 is not empty do
  4. 3q ← the pixel in 𝓛 with the least g; remove q from 𝓛
  5. 4e(q) ← true
  6. 5for each neighbor r of q with e(r) = false do
  7. 6g_tmp ← g(q) + l(q, r)
  8. 7if r is in 𝓛 and g_tmp < g(r) then remove r from 𝓛
  9. 8if r is not in 𝓛 then g(r) ← g_tmp; ptr(r) ← q; insert r in 𝓛
  10. 9return g and ptr ▷ the path to a free point t follows ptr from t to s

The second block computes the cost of one link before the search.

  1. LOCAL-COST(p, q)
  2. 1f_Z(q) ← 0 if the Laplacian has a zero crossing at q, else 1
  3. 2f_G(q) ← (1 - G(q) / max G) · (1 if q is diagonal to p, else 1/√2)
  4. 3f_D(p, q) ← (2 / 3π) (arccos(D(p) · L) + arccos(L · D(q)))
  5. 4return 0.43 f_Z(q) + 0.43 f_G(q) + 0.14 f_D(p, q)

The search runs once per seed and gives paths to all pixels. Moving the cursor only follows pointers, which costs the length of the path. Mortensen and Barrett sort the active list with an O(n)O(n) method: the costs are integers in a small range, so the list is a bucket queue, as in Dial's algorithm.

Example

Take this 5×55 \times 5 image, with a dark area on the left, a bright area on the right and a step in the edge between rows 1 and 2:

u = 0 1 2 3 4
v = 0 10 10 10 90 90
v = 1 10 10 10 90 90
v = 2 10 10 90 90 90
v = 3 10 10 90 90 90
v = 4 10 10 90 90 90

The code uses central differences and the 4-neighbor Laplacian, with the border pixels repeated. The Laplacian changes sign across the edge, and column 2 holds a zero crossing in every row, so fZ=0f_Z = 0 there. The largest gradient is G=402≈56.57G = 40\sqrt 2 \approx 56.57, at (2,1)(2, 1) and (2,2)(2, 2), where the edge turns.

Seed s=(2,0)s = (2, 0). The link down to (2,1)(2, 1) has fZ=0f_Z = 0 and fG=0f_G = 0. At the seed the gradient is (40,0)(40, 0), so D(s)=(0,−1)D(s) = (0, -1), and L=(0,−1)L = (0, -1) after the sign rule. At (2,1)(2, 1) the gradient is (40,40)(40, 40), so D=(0.7071,−0.7071)D = (0.7071, -0.7071). Then fD=23π(arccos⁡1+arccos⁡0.7071)=23π⋅π4=16f_D = \frac{2}{3\pi}(\arccos 1 + \arccos 0.7071) = \frac{2}{3\pi} \cdot \frac{\pi}{4} = \frac16, and l=0.14/6≈0.0233l = 0.14 / 6 \approx 0.0233. The other links from the seed cost 0.82740.8274 to (1,0)(1, 0), 0.18240.1824 to (3,0)(3, 0), 0.93000.9300 to (1,1)(1, 1) and 0.17260.1726 to (3,1)(3, 1).

The search gives these least costs gg from the seed:

u = 0 1 2 3 4
v = 0 1.655 0.827 0 0.173 1.000
v = 1 1.103 0.827 0.023 0.173 1.000
v = 2 1.000 0.173 0.070 0.874 1.103
v = 3 1.047 0.219 0.182 1.010 1.827
v = 4 1.136 0.308 0.271 1.099 1.926

With the cursor at (2,4)(2, 4), the pointers give the path (2,0),(2,1),(2,2),(2,3),(2,4)(2, 0), (2, 1), (2, 2), (2, 3), (2, 4) with the link costs 0.02330.0233, 0.04670.0467, 0.11240.1124, 0.08910.0891, total 0.27140.2714. The path runs along the zero crossings of the edge. The test file checks these numbers and compares the search with Bellman-Ford.

Correctness

The full proof is in proofs/correctness.md. The facts that are proved:

  • Every link cost is in [0,1][0, 1]. The three features are in [0,1][0, 1] and the weights are nonnegative with sum 1. The sign rule for LL keeps the direction term at most 1.
  • With nonnegative costs, a pixel taken from the active list at line L3 has its final least cost. This is the classical invariant of Dijkstra's algorithm. So line L9 gives least cost paths from the seed to every pixel.
  • Removing and inserting again at lines L7 and L8 has the same effect as the lazy deletion in the code.
  • With integer costs in 0,…,C0, \dots, C, a circular array of C+1C + 1 buckets returns the pixels in the same order as a heap.

What is not proved: that the least cost path is the object boundary. The cost function is a heuristic, and its weights are tuned values.

Proof: Correctness of intelligent scissorsfull

This proof covers lines L1 to L13 of the main page. The graph has one node per pixel and a directed link p→qp \to q for each of the 8 neighbors qq of pp. The image has n=WHn = WH pixels, so the graph has nn nodes and at most 8n8n links. The search finds, for a seed ss, the least total cost of a path from ss to every pixel, and a path that has this cost. Whether that path is the boundary the user wants is a question of the cost function, which the proof does not address.

The local cost is in [0, 1]

Lemma 1. For every link, 0≤l(p,q)≤10 \le l(p, q) \le 1.

Proof. fZ(q)∈{0,1}f_Z(q) \in \{0, 1\} by line L10. By line L11, fG(q)=1−G(q)/max⁡G∈[0,1]f_G(q) = 1 - G(q)/\max G \in [0, 1] because 0≤G(q)≤max⁡G0 \le G(q) \le \max G, and the scale is 11 or 1/21/\sqrt 2. For line L12, the link vector LL is chosen so that D(p)⋅L≥0D(p) \cdot L \ge 0. If D(p)D(p) is a unit vector, then D(p)⋅L∈[0,1]D(p) \cdot L \in [0, 1] and its arccosine is in [0,π/2][0, \pi/2]. If the gradient at pp is zero, the code sets D(p)=0D(p) = 0 and the arccosine is π/2\pi/2. The second dot product is in [−1,1][-1, 1], so its arccosine is in [0,π][0, \pi]. So fD∈[0,23π⋅3π2]=[0,1]f_D \in [0, \frac{2}{3\pi} \cdot \frac{3\pi}{2}] = [0, 1]. The weights 0.430.43, 0.430.43 and 0.140.14 are nonnegative and sum to 11, so l(p,q)l(p, q) is a convex combination of numbers in [0,1][0, 1] and lies in [0,1][0, 1]. □\square

The important part is l≥0l \ge 0: the search below needs nonnegative link costs.

The search finds least cost paths

Write δ(q)\delta(q) for the least cost of a path from ss to qq. Each pixel is reachable from ss, because the 8-neighbor grid is connected, so δ(q)\delta(q) is finite.

Lemma 2 (invariants). At every point of lines L1 to L9:

  1. For each pixel rr with a finite g(r)g(r), there is a path from ss to rr of cost g(r)g(r) that follows the back pointers, so g(r)≥δ(r)g(r) \ge \delta(r).
  2. For each pixel rr that is not expanded, g(r)g(r) is the least cost of a path from ss to rr whose nodes, except rr, are all expanded.

Proof. Line L1 makes both true for ss, and every other gg is infinite. Line L8 sets g(r)=g(q)+l(q,r)g(r) = g(q) + l(q, r) and the pointer of rr to qq, which extends the path of qq by one link, so part 1 holds. Part 2: when qq is expanded at line L4, the paths to a pixel rr whose inner nodes are expanded gain those that end with the link q→rq \to r; lines L5 to L8 compare their cost g(q)+l(q,r)g(q) + l(q, r) with the old value and keep the smaller. A path with an inner node that is expanded later is not counted yet. □\square

Theorem 1 (Dijkstra). When line L3 removes qq from the active list, g(q)=δ(q)g(q) = \delta(q).

Proof. Suppose not, and let qq be the first pixel removed with g(q)>δ(q)g(q) > \delta(q). Take a least cost path from ss to qq, and let yy be the first node on it that is not expanded; it exists because qq is not expanded yet. All nodes before yy are expanded, so by part 2 of Lemma 2 and the choice of qq, g(y)≤δ(y)g(y) \le \delta(y). The costs are nonnegative (Lemma 1), so δ(y)≤δ(q)\delta(y) \le \delta(q). So g(y)≤δ(y)≤δ(q)<g(q)g(y) \le \delta(y) \le \delta(q) < g(q). But yy is in the active list with this value, because a finite g(y)g(y) was inserted at line L8, and line L3 takes the least gg, so it would take yy before qq. This is a contradiction. □\square

The loop ends when the active list is empty. Every pixel is reachable, so every pixel is expanded, and by Theorem 1 and part 1 of Lemma 2, g(t)=δ(t)g(t) = \delta(t) for every pixel tt, and the back pointers from tt give a path of that cost. This proves that line L9 returns least cost paths to all pixels at once, so the free point can move to any pixel without a new search. This is the standard proof for Dijkstra's algorithm.

Removing a worse entry. The paper removes rr from the active list when a lower cost is found, then inserts it again (lines L7 and L8). The code keeps old entries in the heap and skips an entry when it is popped with a value larger than the current gg. Both forms take the same pixels in the same order of gg, so the result is the same.

The bucket queue

Lemma 3. If every link cost is an integer in 0,…,C0, \dots, C, a circular array of C+1C + 1 buckets, indexed by g mod (C+1)g \bmod (C + 1), gives the same result as the heap.

Proof. Let cc be the value of the pixel being expanded. Every value in the active list is at least cc, by Theorem 1 and the order of removal, and at most c+Cc + C, because each value is g(q)+l(q,r)g(q) + l(q, r) for an expanded qq with g(q)≤cg(q) \le c. So the values in the list lie in a window of C+1C + 1 consecutive integers, and two different values never share a bucket. Scanning the buckets from cc upward finds the least value. □\square

The code rounds the costs to integers for this test. With rounded costs the search is exact for the rounded costs, and the path can differ from the path for the real costs. Mortensen and Barrett use integer costs for this reason.

What is not proved

The weights 0.430.43, 0.430.43 and 0.140.14 are design choices of the paper, not results. Path cooling and on-the-fly training are heuristics. The theorem says the path is of least cost, not that it is the object boundary: a short path across a weak region can cost less than a long path along a true edge.

Complexity

The graph has n=WHn = WH nodes and at most 8n8n links. In the real-RAM model with a binary heap, the search costs O(nlog⁡n)=O(WHlog⁡(WH))O(n \log n) = O(WH \log(WH)) time, as each link causes at most one insertion. The local costs take O(WH)O(WH) time before the search: a few filters and 8 costs per pixel. The best case O(WH)O(WH) in the front matter is for the bucket queue below with a fixed cost range.

With integer costs in 0,…,C0, \dots, C (a word-RAM model), the bucket queue makes the search O(n+D)O(n + D), where D≤(n−1)CD \le (n - 1) C is the largest path cost, since the scan over buckets never goes back. For a fixed CC, such as costs scaled to 0 to 255, this is the O(n)O(n) of the paper. The extra space is O(WH)O(WH) for gg, the pointers, the expanded flags and the active list. After the search, each cursor move costs O(k)O(k) for a path of kk pixels.

Properties

  • Exact for its cost. The path is a global least cost path, not a local optimum as in active contours.
  • Interactive. One search per seed gives the path to every cursor position.
  • Directed costs. l(p,q)l(p, q) and l(q,p)l(q, p) differ, because fZf_Z and fGf_G are evaluated at the end pixel. The graph is directed.
  • Invariant to brightness and contrast. An affine change of intensity I→aI+bI \to aI + b with a≠0a \ne 0 does not change fZf_Z, fGf_G or fDf_D. A negative aa flips both D(p)D(p) and the chosen LL, so the dot products stay the same. The tests check it.
  • Short paths win. The total cost grows with length, so the path can cut a corner across a weak region instead of following a long, faint boundary.

Variants and improvements

  • Path cooling (Section 3.4 of the 1995 paper). When a piece of the path near the seed stays the same for some time, the program fixes it and sets a new seed there, so the user needs fewer clicks. This is a heuristic.
  • On-the-fly training (Section 3.5 of the 1995 paper). The gradient magnitude cost is replaced by a cost learned from the boundary piece just accepted, so the wire prefers edges like the last one and not simply the strongest edge nearby. This is a heuristic.
  • Other costs. Color gradients, or a Laplacian of Gaussian at several scales, instead of the plain Laplacian.
  • Scissors with regions. Boykov-Jolly graph cuts use seeds inside and outside instead of points on the boundary, and find the whole boundary at once.
  • Continuous paths. Geodesic active contours and minimal path methods with fast marching compute least cost curves in the continuous plane. They are related methods, not the same algorithm.

When to use it

Use intelligent scissors when the user can follow the boundary with the mouse, when the boundary has good edges in most places, and when the object is thin or has a long outline. It gives exact control of the boundary with few clicks. Use a region method such as Boykov-Jolly graph cuts or the random walker when the object is large and its edges are weak or noisy, or when the data is 3D, where a boundary is a surface and a path does not suffice.

Pitfalls

  • Weight order. The paper prints ωZ=0.43\omega_Z = 0.43, ωG=0.43\omega_G = 0.43 and ωD=0.14\omega_D = 0.14. The small weight is on the gradient direction, not on the gradient magnitude.
  • Zero gradient. D(p)D(p) is undefined where the gradient is zero. The code uses the zero vector, which gives the arccosine π/2\pi/2.
  • Flat regions and the Laplacian. The Laplacian is zero in flat regions. Treating every zero as a crossing makes flat regions cheap. The code counts only sign changes.
  • Noise. A raw Laplacian finds crossings in noise. Smooth the image first, for example with a Gaussian filter.
  • Scale of the gradient cost. fGf_G divides by the largest gradient of the image. One very strong edge makes all other edges look weak.
  • Shortcut paths. Without enough seeds, the wire jumps across a weak gap to a nearby strong edge. Add a seed before such a place.

Implementations

The Python code in impl/python/intelligent_scissors.py computes the three cost features with central differences and the 4-neighbor Laplacian, runs the search of lines L1 to L9 with a binary heap and lazy deletion, and follows the pointers to a free point. It also has a bucket queue search for integer costs and Bellman-Ford as a reference. The tests check the example, that the costs lie in [0,1][0, 1], that the search equals Bellman-Ford and that each path has the cost gg, that the bucket queue gives the same costs as the heap, the invariance to affine intensity changes, and that the path follows a straight step edge.

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.

intelligent_scissors.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/intelligent-scissors/. The authors are listed in prov/EF89RD.jsonl.

"""Intelligent scissors (live wire) of Mortensen and Barrett (1995).

Pixel p = v * w + u is (u, v) with the gray value img[v][u]. Each pixel links
to its 8 neighbors. The directed local cost of the link p -> q is

    l(p, q) = wZ fZ(q) + wG fG(q) s(p, q) + wD fD(p, q),

with wZ = 0.43, wG = 0.43 and wD = 0.14 as printed in the paper, the
Laplacian zero-crossing cost fZ, the gradient magnitude cost fG, the scale
s = 1 for diagonal and 1 / sqrt(2) for horizontal or vertical links, and the
gradient direction cost fD. live_wire is the 2D dynamic programming search of
the paper, which is Dijkstra's algorithm from the seed point.
"""

import heapq
import math

STEPS = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]


def _at(img, u, v):
    h, w = len(img), len(img[0])
    return img[min(max(v, 0), h - 1)][min(max(u, 0), w - 1)]


def gradients(img):
    """Central differences with replicated borders: Iu, Iv and G = sqrt(Iu^2 + Iv^2)."""
    h, w = len(img), len(img[0])
    iu = [[(_at(img, u + 1, v) - _at(img, u - 1, v)) / 2.0 for u in range(w)] for v in range(h)]
    iv = [[(_at(img, u, v + 1) - _at(img, u, v - 1)) / 2.0 for u in range(w)] for v in range(h)]
    g = [[math.hypot(iu[v][u], iv[v][u]) for u in range(w)] for v in range(h)]
    return iu, iv, g


def laplacian(img):
    """The 4-neighbor discrete Laplacian with replicated borders."""
    h, w = len(img), len(img[0])
    return [[_at(img, u + 1, v) + _at(img, u - 1, v) + _at(img, u, v + 1) + _at(img, u, v - 1)
             - 4 * img[v][u] for u in range(w)] for v in range(h)]


def zero_crossing_cost(lap):
    """fZ(q) = 0 if the Laplacian changes sign between q and a 4-neighbor r and q is the one closer to zero."""
    h, w = len(lap), len(lap[0])
    fz = [[1.0] * w for _ in range(h)]
    for v in range(h):
        for u in range(w):
            a = lap[v][u]
            for du, dv in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                uu, vv = u + du, v + dv
                if 0 <= uu < w and 0 <= vv < h:
                    b = lap[vv][uu]
                    if a * b < 0 and abs(a) <= abs(b):
                        fz[v][u] = 0.0
    return fz


def local_costs(img, wz=0.43, wg=0.43, wd=0.14):
    """Return adj[p] = list of (q, l(p, q)) for the 8-connected pixel graph."""
    h, w = len(img), len(img[0])
    iu, iv, g = gradients(img)
    gmax = max(max(row) for row in g)
    fz = zero_crossing_cost(laplacian(img))  # @line L10
    dvec = []
    for v in range(h):
        for u in range(w):
            gg = g[v][u]
            dvec.append((iv[v][u] / gg, -iu[v][u] / gg) if gg > 0 else (0.0, 0.0))
    adj = [[] for _ in range(w * h)]
    for v in range(h):
        for u in range(w):
            p = v * w + u
            for du, dv in STEPS:
                uu, vv = u + du, v + dv
                if not (0 <= uu < w and 0 <= vv < h):
                    continue
                q = vv * w + uu
                fg = 1.0 - g[vv][uu] / gmax if gmax > 0 else 1.0  # @line L11
                scale = 1.0 if du != 0 and dv != 0 else 1.0 / math.sqrt(2.0)
                length = math.hypot(du, dv)
                link = (du / length, dv / length)
                dp = dvec[p]
                if dp[0] * link[0] + dp[1] * link[1] < 0:
                    link = (-link[0], -link[1])
                dq = dvec[q]
                a = max(-1.0, min(1.0, dp[0] * link[0] + dp[1] * link[1]))
                b = max(-1.0, min(1.0, link[0] * dq[0] + link[1] * dq[1]))
                fd = 2.0 / (3.0 * math.pi) * (math.acos(a) + math.acos(b))  # @line L12
                adj[p].append((q, wz * fz[vv][uu] + wg * fg * scale + wd * fd))  # @line L13
    return adj


def live_wire(adj, seed):
    """Least total cost g and back pointers from the seed to every pixel (Dijkstra)."""
    n = len(adj)
    g = [math.inf] * n
    back = [None] * n
    expanded = [False] * n
    g[seed] = 0.0  # @line L1
    active = [(0.0, seed)]
    while active:  # @line L2
        gq, q = heapq.heappop(active)  # @line L3
        if expanded[q] or gq > g[q]:
            continue
        expanded[q] = True  # @line L4
        for r, cost in adj[q]:  # @line L5
            if expanded[r]:
                continue
            gtmp = gq + cost  # @line L6
            if gtmp < g[r]:  # @line L7
                g[r] = gtmp  # @line L8
                back[r] = q
                heapq.heappush(active, (gtmp, r))
    return g, back  # @line L9


def path_to(back, seed, t):
    """Follow the back pointers from the free point t to the seed; return the path seed ... t."""
    path = [t]
    while path[-1] != seed:
        nxt = back[path[-1]]
        if nxt is None:
            raise ValueError("t is not reachable from the seed")
        path.append(nxt)
    return path[::-1]


def path_cost(adj, path):
    total = 0.0
    for p, q in zip(path, path[1:]):
        total += dict(adj[p])[q]
    return total


def bellman_ford(adj, seed):
    """Reference shortest path costs, O(n m)."""
    n = len(adj)
    g = [math.inf] * n
    g[seed] = 0.0
    for _ in range(n - 1):
        changed = False
        for p in range(n):
            if g[p] == math.inf:
                continue
            for q, c in adj[p]:
                if g[p] + c < g[q] - 1e-15:
                    g[q] = g[p] + c
                    changed = True
        if not changed:
            break
    return g


def quantize(adj, levels):
    """Round each link cost to an integer in 0 .. levels, as the paper does for its bucket queue."""
    return [[(q, int(round(c * levels))) for q, c in row] for row in adj]


def live_wire_buckets(adj_int, seed, cmax):
    """Dijkstra with a circular bucket queue for integer costs in 0 .. cmax (Dial's method)."""
    n = len(adj_int)
    g = [math.inf] * n
    back = [None] * n
    done = [False] * n
    nb = cmax + 1
    buckets = [[] for _ in range(nb)]
    g[seed] = 0
    buckets[0].append(seed)
    left, cur = 1, 0
    while left:
        while not buckets[cur % nb]:
            cur += 1
        q = buckets[cur % nb].pop()
        left -= 1
        if done[q] or g[q] != cur:
            continue
        done[q] = True
        for r, c in adj_int[q]:
            if not done[r] and cur + c < g[r]:
                g[r] = cur + c
                back[r] = q
                buckets[(cur + c) % nb].append(r)
                left += 1
    return g, back
test_intelligent_scissors.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/intelligent-scissors/. The authors are listed in prov/EF89RD.jsonl.

import random

from intelligent_scissors import (
    bellman_ford,
    laplacian,
    live_wire,
    live_wire_buckets,
    local_costs,
    path_cost,
    path_to,
    quantize,
    zero_crossing_cost,
)

STAIR = [
    [10, 10, 10, 90, 90],
    [10, 10, 10, 90, 90],
    [10, 10, 90, 90, 90],
    [10, 10, 90, 90, 90],
    [10, 10, 90, 90, 90],
]


def random_image(rng, w, h):
    return [[rng.randrange(256) for _ in range(w)] for _ in range(h)]


def test_staircase_example():
    adj = local_costs(STAIR)
    costs = dict(adj[2])
    assert abs(costs[7] - 0.0233) < 1e-4
    assert abs(costs[7] - 0.14 / 6) < 1e-12
    assert abs(costs[3] - 0.1824) < 1e-4
    assert abs(costs[1] - 0.8274) < 1e-4
    g, back = live_wire(adj, 2)
    assert path_to(back, 2, 22) == [2, 7, 12, 17, 22]
    assert abs(g[22] - 0.2714) < 1e-4
    fz = zero_crossing_cost(laplacian(STAIR))
    assert [row[2] for row in fz] == [0.0] * 5


def test_costs_in_unit_interval():
    rng = random.Random(1)
    for _ in range(5):
        adj = local_costs(random_image(rng, 7, 6))
        for row in adj:
            for _, c in row:
                assert -1e-12 <= c <= 1.0 + 1e-12


def test_matches_bellman_ford():
    rng = random.Random(2)
    for _ in range(6):
        w, h = 7, 6
        adj = local_costs(random_image(rng, w, h))
        seed = rng.randrange(w * h)
        g, back = live_wire(adj, seed)
        ref = bellman_ford(adj, seed)
        for t in range(w * h):
            assert abs(g[t] - ref[t]) < 1e-9
            path = path_to(back, seed, t)
            assert path[0] == seed and path[-1] == t
            assert abs(path_cost(adj, path) - g[t]) < 1e-9


def test_bucket_queue_matches_dijkstra():
    rng = random.Random(3)
    for _ in range(5):
        w, h = 8, 6
        adj = quantize(local_costs(random_image(rng, w, h)), 255)
        seed = rng.randrange(w * h)
        gb, back = live_wire_buckets(adj, seed, 255)
        gd, _ = live_wire([[(q, float(c)) for q, c in row] for row in adj], seed)
        assert gb == [int(x) for x in gd]
        for t in range(w * h):
            assert path_cost(adj, path_to(back, seed, t)) == gb[t]


def test_affine_intensity_invariance():
    rng = random.Random(4)
    img = random_image(rng, 6, 5)
    base = local_costs(img)
    for a, b in ((2.0, 7.0), (-1.0, 255.0), (0.5, -3.0)):
        other = local_costs([[a * x + b for x in row] for row in img])
        for r1, r2 in zip(base, other):
            for (q1, c1), (q2, c2) in zip(r1, r2):
                assert q1 == q2 and abs(c1 - c2) < 1e-9


def test_path_follows_straight_edge():
    img = [[0 if u < 3 else 100 for u in range(7)] for _ in range(7)]
    adj = local_costs(img)
    g, back = live_wire(adj, 3)
    path = path_to(back, 3, 6 * 7 + 3)
    assert all(p % 7 in (2, 3) for p in path)
    assert len(path) == 7

History

Least cost paths for boundary tracing are older than live wire: Montanari (1971) and Martelli (1976) traced curves with dynamic programming and heuristic graph search, but these methods needed a fixed start and end, or a search band. The name "live wire" and the search over all pixels appear first in a 1992 paper on cardiac images by Mortensen, Morse, Barrett and Udupa, which the 1995 paper cites. Mortensen and Barrett (1995) made it a general tool for image composition. They computed the paths from the seed to all pixels at once, so the end point could follow the cursor, and they added path cooling and on-the-fly training (Sections 3.4 and 3.5). The 1998 journal paper of Mortensen and Barrett gives a longer account.

References

  1. Eric N. Mortensen and William A. Barrett, Intelligent scissors for image composition, SIGGRAPH 95, 191-198, 1995, Section 3.1 (local costs, equations 1 to 5, weights), Section 3.2 (2D dynamic programming search and its pseudocode), Section 3.4 (path cooling), Section 3.5 (on-the-fly training)
  2. Eric N. Mortensen and William A. Barrett, Interactive segmentation with intelligent scissors, Graphical Models and Image Processing 60(5), 349-384, 1998, The journal version, with more cost features and training
  3. Richard Szeliski, Computer Vision: Algorithms and Applications, 1st edition, Springer, 2011, Section 5.1.3, Scissors

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