Algorithm Search⌘K

Algorithmadvanced

Random walker segmentation

Also called Grady random walker.

Label each pixel with the seed label that a random walk from it most likely reaches first. The probabilities solve a sparse Laplacian system with the seeds as boundary values.

Time
O(W^3 H^3 + K W^2 H^2) worst · averageO(K W H) best
Space
O(W^2 H^2 + K W H) extra
Where
H = the image height in pixels; K = the number of labels; W = the image width in pixels
Properties
deterministicexactinteractivemulti labelsoft output
Origin
Leo Grady, 2006

Random walker segmentation is an algorithm that splits an image into KK regions from a few pixels that the user marks with labels, the seeds. Picture a walker that starts at an unmarked pixel and steps to a neighbor at random. It prefers steps between pixels of similar brightness. Each pixel gets the label of the seed that its walker most likely reaches first. These probabilities need no simulation: they solve one sparse linear system per label, with the graph Laplacian of the image and the seeds as fixed values. The result is a probability for each pixel and label, and it is the exact solution of the system, not a local optimum.

In plain words

The user marks a few pixels inside each object and a few in the background. Now think of the image as a field of small rooms with doors between neighbors. A door is wide when the two pixels have similar brightness, and narrow when there is an edge between them. A person starts in an unmarked room and walks through doors at random until they reach a marked room. They pass wide doors more often than narrow ones.

For each unmarked pixel, the program finds how likely the walk ends at each kind of mark. The pixel joins the mark with the best chance. Strong edges hold walkers back, so the borders between regions follow the edges. The program finds all chances at once by solving one set of equations.

The problem

The input is a gray image II with n=WHn = WH pixels, a set MM of seed pixels, a label ℓ(j)∈{1,…,K}\ell(j) \in \{1, \dots, K\} for each seed jj, and a parameter β>0\beta > 0. The pixels are the nodes of a 4-connected grid graph. The output is, for each pixel ii and label ss, the probability xisx^s_i that a random walk from ii reaches a seed of label ss before any other seed, and the label arg⁡max⁡sxis\arg\max_s x^s_i. The problem is interactive segmentation with labels as seeds.

The walk moves from ii to a neighbor jj with probability wij/diw_{ij} / d_i, where di=∑jwijd_i = \sum_j w_{ij} is the degree. Grady (2006, equation 1) uses the weights

wij=exp⁡(−β (gi−gj)2),w_{ij} = \exp\bigl(-\beta\, (g_i - g_j)^2\bigr),

where gig_i is the gray value. He normalizes the squared differences first but does not fix how. The code of this page divides them by the largest squared difference in the image, so β\beta does not depend on the gray scale.

The algorithm

Order the pixels with the seeds MM first and the free pixels UU after them. The Laplacian L=D−WL = D - W then has the blocks

L=(LMBBTLU).L = \begin{pmatrix} L_M & B \\ B^T & L_U \end{pmatrix}.

For a label ss, the vector msm^s on the seeds has mjs=1m^s_j = 1 if ℓ(j)=s\ell(j) = s and 00 otherwise. The probabilities of label ss on the free pixels solve (Grady 2006, equation 10)

LU xUs=−BTms.L_U\, x^s_U = -B^T m^s .
  1. RANDOM-WALKER(I, seeds, β)
  2. 1for each grid edge {i, j} do w_ij ← exp(-β (g_i - g_j)² / max (g_p - g_q)²)
  3. 2L ← D - W ▷ sparse, 5 entries per row
  4. 3split the pixels into seeds M and free pixels U; take the blocks L_U and B
  5. 4for s ← 1 to K - 1 do m^s_j ← 1 if ℓ(j) = s else 0, for j in M
  6. 5for s ← 1 to K - 1 do solve L_U x^s_U = -B^T m^s
  7. 6x^K ← 1 - Σ_{s<K} x^s
  8. 7for each pixel i do label_i ← argmax_s x^s_i
  9. 8return x, label

Line L6 saves one solve: the probabilities of each pixel sum to 1, so the last label needs no system of its own (Theorem 1 of the proof). All K−1K - 1 systems in line L5 have the same matrix, so one factorization serves all of them.

Example

Take one row of five pixels with the gray values 10,20,60,70,8010, 20, 60, 70, 80, a seed of label 0 at pixel 0, a seed of label 1 at pixel 4, and β=2\beta = 2. The squared differences are 100,1600,100,100100, 1600, 100, 100. Divided by the largest, they are 1/16,1,1/16,1/161/16, 1, 1/16, 1/16, so the weights are

e−1/8=0.8825,e−2=0.1353,0.8825,0.8825.e^{-1/8} = 0.8825,\quad e^{-2} = 0.1353,\quad 0.8825,\quad 0.8825 .

On a chain the system is a set of resistors in series. Each edge is a resistor of resistance 1/w1 / w: 1.13311.1331, 7.38917.3891, 1.13311.1331, 1.13311.1331, with the sum 10.788510.7885. The probability of label 1 at a pixel is the resistance between pixel 0 and that pixel, divided by the total:

pixel 0 1 2 3 4
value 10 20 60 70 80
x1x^1 0 0.1050 0.7899 0.8950 1
label 0 0 1 1 1

The big step of the probability is at the weak edge between pixels 1 and 2, where the gray value jumps by 40. The labels are 0,0,1,1,10, 0, 1, 1, 1. The test file checks these numbers, and it checks the resistor formula.

Correctness

The full proof is in proofs/correctness.md. It needs positive weights and at least one seed in each connected part of the graph. A grid is connected, so one seed is enough there.

  • Theorem (one solution). LUL_U is symmetric positive definite, so each system of line L5 has exactly one solution.
  • Theorem (energy). The solution is the only minimizer of the Dirichlet energy D[x]=12∑wij(xi−xj)2D[x] = \frac12 \sum w_{ij} (x_i - x_j)^2 with the seeds fixed. This is equation 6 of the paper.
  • Theorem (random walk). The solution equals the probability that the walk from ii first reaches a seed of label ss.
  • Theorem (range and sum). Each xisx^s_i lies in [0,1][0, 1], by the maximum principle, and ∑sxis=1\sum_s x^s_i = 1, which justifies line L6.
  • Theorem (two labels give connected segments). With K=2K = 2, each pixel with label ss is joined to a seed of label ss through pixels with label ss. This is Proposition 1 of the paper for K=2K = 2.

For K≥3K \ge 3 that last statement is false, although Grady states it for any KK. The proof file gives a graph of seven nodes where a node gets label 0 and none of its neighbors does. The test file builds the same pattern on a 2×52 \times 5 image.

Proof: Correctness of random walker segmentationfull

This proof covers lines L1 to L8 of the main page. The graph has the node set VV with n=∣V∣n = |V|, undirected edges with weights wij>0w_{ij} > 0, and the degrees di=∑jwijd_i = \sum_j w_{ij}. Line L1 gives wij=e−βdij>0w_{ij} = e^{-\beta d_{ij}} > 0 for every grid edge, so this holds. The Laplacian of line L2 is L=D−WL = D - W: Lii=diL_{ii} = d_i, Lij=−wijL_{ij} = -w_{ij} for an edge and 00 otherwise. The seeded nodes MM are not empty, and each seed j∈Mj \in M has a label ℓ(j)∈{1,…,K}\ell(j) \in \{1, \dots, K\}. The free nodes are U=V∖MU = V \setminus M. Order the nodes with MM first, so that

L=(LMBBTLU).L = \begin{pmatrix} L_M & B \\ B^T & L_U \end{pmatrix}.

For a label ss, the boundary vector msm^s on MM has mjs=1m^s_j = 1 if ℓ(j)=s\ell(j) = s and 00 otherwise. The hypothesis is: each connected component of the graph holds at least one seed. A grid graph is connected, so one seed is enough there.

Lemma 1 (the system has one solution)

LUL_U is symmetric positive definite.

Proof. For y∈RUy \in \mathbb R^U, extend it by 00 on MM to a vector yˉ\bar y. Then

yTLUy=yˉTLyˉ=∑{i,j}∈Ewij(yˉi−yˉj)2≥0.y^T L_U y = \bar y^T L \bar y = \sum_{\{i, j\} \in E} w_{ij} (\bar y_i - \bar y_j)^2 \ge 0.

The identity yˉTLyˉ=∑{i,j}wij(yˉi−yˉj)2\bar y^T L \bar y = \sum_{\{i,j\}} w_{ij} (\bar y_i - \bar y_j)^2 follows from L=D−WL = D - W by expanding the square. If the sum is 00, then yˉ\bar y is constant on each connected component of the graph, because every weight is positive. Each component holds a seed, where yˉ=0\bar y = 0, so yˉ=0\bar y = 0 and y=0y = 0. □\square

So the system LUxU=−BTmsL_U x_U = -B^T m^s of line L5 has exactly one solution xUsx^s_U. Write xsx^s for the full vector with xMs=msx^s_M = m^s.

Lemma 2 (mean value property)

For each free node ii, xis=1di∑jwijxjsx^s_i = \frac{1}{d_i} \sum_j w_{ij} x^s_j.

Proof. Row ii of LUxU+BTms=0L_U x_U + B^T m^s = 0 reads dixis−∑jwijxjs=0d_i x^s_i - \sum_j w_{ij} x^s_j = 0, where the sum runs over all neighbors, free or seeded. □\square

A vector with this property on UU is called harmonic on UU.

Lemma 3 (minimum of the Dirichlet energy)

Among all xx with xM=msx_M = m^s, the vector xsx^s is the only minimizer of D[x]=12xTLx=12∑{i,j}wij(xi−xj)2D[x] = \frac12 x^T L x = \frac12 \sum_{\{i,j\}} w_{ij} (x_i - x_j)^2.

Proof. With xM=msx_M = m^s fixed,

D[x]=12(ms)TLMms+xUTBTms+12xUTLUxU.D[x] = \tfrac12 (m^s)^T L_M m^s + x_U^T B^T m^s + \tfrac12 x_U^T L_U x_U.

This is a quadratic function of xUx_U with the Hessian LUL_U, which is positive definite by Lemma 1. So it is strictly convex, and its only minimizer is the zero of the gradient LUxU+BTmsL_U x_U + B^T m^s, which is xUsx^s_U. □\square

Lemma 4 (maximum principle)

Let xx be harmonic on UU. Then min⁡Mx≤xi≤max⁡Mx\min_M x \le x_i \le \max_M x for each ii. In particular 0≤xis≤10 \le x^s_i \le 1.

Proof. Let c=max⁡Vxc = \max_V x, and suppose c>max⁡Mxc > \max_M x. The set S={i:xi=c}S = \{i : x_i = c\} is not empty and lies in UU. Take i∈Si \in S. By Lemma 2, xix_i is a weighted mean of its neighbors with positive weights, and no neighbor is above cc, so every neighbor equals cc and is in SS. So SS is closed under taking neighbors, and SS is a whole connected component of the graph. That component holds a seed, which is in MM, a contradiction. The bound from below is the same argument for −x-x. □\square

Lemma 5 (the random walk)

Take the walk that moves from node ii to a neighbor jj with probability wij/diw_{ij} / d_i and stops at the first seed it reaches. For a free start node ii, let hih_i be the probability that the walk stops at a seed of label ss, and let hj=mjsh_j = m^s_j on MM. Then h=xsh = x^s.

Proof. First, the walk stops with probability 1. From each free node there is a path to a seed with at most nn steps, by the hypothesis. Each step of that path has probability at least p=min⁡i,jwij/di>0p = \min_{i,j} w_{ij} / d_i > 0. So in each block of nn steps the walk stops with probability at least pnp^n, and the probability that it never stops is at most lim⁡k(1−pn)k=0\lim_k (1 - p^n)^k = 0.

Next, condition on the first step. From a free node ii the walk goes to jj with probability wij/diw_{ij} / d_i and then behaves as a walk from jj, so hi=∑j(wij/di)hjh_i = \sum_j (w_{ij} / d_i) h_j. This is the property of Lemma 2, with the same values on MM. The difference h−xsh - x^s is harmonic on UU and 00 on MM, so it is 00 by Lemma 4. □\square

Theorem 1 (the sum rule of line L6)

∑s=1Kxs=1\sum_{s=1}^K x^s = \mathbf 1. So the vector xK=1−∑s<Kxsx^K = \mathbf 1 - \sum_{s < K} x^s of line L6 equals the solution of the system for label KK.

Proof. The rows of LL sum to 00, so L1=0L \mathbf 1 = 0, and its rows in UU give LU1U+BT1M=0L_U \mathbf 1_U + B^T \mathbf 1_M = 0. Each seed has exactly one label, so ∑sms=1M\sum_s m^s = \mathbf 1_M. The systems are linear with the same matrix, so ∑sxUs\sum_s x^s_U solves LUy=−BT1ML_U y = -B^T \mathbf 1_M. By Lemma 1 that solution is unique, and it is 1U\mathbf 1_U. So ∑sxs=1\sum_s x^s = \mathbf 1, and xK=1−∑s<Kxsx^K = \mathbf 1 - \sum_{s<K} x^s. □\square

Theorem 2 (the output)

Lines L1 to L8 return, for each pixel ii and each label ss, the probability xisx^s_i of Lemma 5 that a walker from ii first reaches a seed of label ss, and the label of largest probability.

Proof. Lines L1 to L4 build LL, the partition and the vectors msm^s. Line L5 solves the systems for s<Ks < K, which have one solution each by Lemma 1. Line L6 gives xKx^K by Theorem 1. Line L7 takes the argmax. The values are the walk probabilities by Lemma 5 and lie in [0,1][0, 1] by Lemma 4. □\square

Proposition 1 (connected segments, two labels)

Let K=2K = 2, and give node ii the label ss only if xis>xifx^s_i > x^f_i for the other label ff. Then each node with label ss is joined to a seed of label ss by a path of nodes with label ss.

Proof. With K=2K = 2, xf=1−xsx^f = \mathbf 1 - x^s, so node ii has label ss exactly when xis>1/2x^s_i > 1/2. Let PP be a connected component of the set {i:xis>1/2}\{i : x^s_i > 1/2\}, and suppose that PP has no seed. Seeds of the other label have xs=0x^s = 0, so P⊆UP \subseteq U. Let c=max⁡Pxsc = \max_P x^s and S={i∈P:xis=c}S = \{i \in P : x^s_i = c\}. Take i∈Si \in S. Each neighbor jj of ii either is in PP, with xjs≤cx^s_j \le c, or has xjs≤1/2<cx^s_j \le 1/2 < c. By Lemma 2, xisx^s_i is a weighted mean of its neighbors with positive weights, so every neighbor has xjs=c>1/2x^s_j = c > 1/2, is in PP, and is in SS. So SS is a whole connected component of the graph, and it holds a seed. That seed is in PP, a contradiction. □\square

This is Proposition 1 of Grady (2006) in the case K=2K = 2.

Remark: more than two labels

For K≥3K \ge 3 the statement is false. Take seven nodes: node 0 joins nodes 1 and 2 with weight 1; node 1 joins a seed of label 0 with weight 1 and a seed of label 1 with weight 1.2; node 2 joins another seed of label 0 with weight 1 and a seed of label 2 with weight 1.2. By symmetry x00=x10=x20=px^0_0 = x^0_1 = x^0_2 = p, and the equation at node 1 gives p(1+1.2+1)=p+1p (1 + 1.2 + 1) = p + 1, so p=1/2.2≈0.4545p = 1/2.2 \approx 0.4545. Then x01=x02=(1−p)/2≈0.2727x^1_0 = x^2_0 = (1 - p)/2 \approx 0.2727, so node 0 has label 0. At node 1, x11=(0.2727+1.2)/3.2≈0.4602>px^1_1 = (0.2727 + 1.2)/3.2 \approx 0.4602 > p, so node 1 has label 1, and node 2 has label 2 in the same way. Node 0 has label 0, but none of its neighbors does. The test file checks this graph, and a 2×52 \times 5 image with the same pattern.

The proof in the paper shows, for each other label ff separately, that some neighbor of the component has xs>xfx^s > x^f. For K=2K = 2 that is enough. For K≥3K \ge 3 the neighbor can differ from one ff to the next, and it can have a third label, as in the example.

What is not proved

Nothing here says that the segments match the objects the user has in mind. That depends on the weights, on β\beta and on the seeds. Lemma 1 needs exact arithmetic. In floating point a large β\beta gives weights near 00, and then LUL_U is close to singular. The test file uses moderate values of β\beta for this reason.

Complexity

The cost model is the real-RAM, with exact arithmetic on real numbers. Let n=WHn = WH. Lines L1 to L4 and L6 to L7 cost O(Kn)O(Kn) time. Line L5 dominates.

  • Dense elimination, as in the code. One LU factorization of LUL_U costs O(n3)O(n^3) time and O(n2)O(n^2) space, and each of the K−1K - 1 right sides costs O(n2)O(n^2). The total is O(W3H3+KW2H2)O(W^3 H^3 + K W^2 H^2), the bound in the front matter. The best case is when almost all pixels are seeds, so that LUL_U is tiny. This is a theorem about the code.
  • Sparse direct solve. LUL_U has at most 5 nonzeros per row. With nested dissection on a 2D grid, the factorization costs O(n3/2)O(n^{3/2}) time and O(nlog⁡n)O(n \log n) space (George 1973). This is a theorem for grid graphs.
  • Conjugate gradients. Each iteration costs O(n)O(n). The number of iterations to reduce the error by a factor ϵ\epsilon is O(κlog⁡(1/ϵ))O(\sqrt{\kappa} \log(1/\epsilon)), where κ\kappa is the condition number of LUL_U. This is a theorem, but κ\kappa grows with β\beta and with the image size, so the bound gives no fixed count.
  • Multigrid. Grady writes that algebraic multigrid gives near-optimal performance on these systems. That is a claim from experience, not a bound.

Grady reports 2.5 seconds for a 256×256256 \times 256 image with two seeds with a direct sparse solver in MATLAB on a 2.4 GHz Xeon. That is a benchmark result.

Properties

  • Soft output. Each pixel gets a probability for each label, not only a label. The probabilities show where the result is uncertain.
  • Any number of labels. One extra solve per label, with the same matrix.
  • Weak edges. Where an edge has a gap, the probability changes smoothly across the gap, and the border tends to close it in a natural way.
  • Less pull toward short borders. The cut of Boykov-Jolly can wrap tightly around a small seed, because short cuts are cheap. The random walker has no cost that grows with the length of the border, so this effect is weaker. That is a heuristic observation, not a theorem.
  • Harmonic. At each free pixel, each xsx^s is the weighted mean of its neighbors.
  • Seeds matter. The result depends on where the seeds are, not only on the image. In a flat region, a pixel tends to take the label of the nearest seeds.

Variants and improvements

  • Color and other features. Replace (gi−gj)2(g_i - g_j)^2 by ∥gi−gj∥2\lVert g_i - g_j \rVert^2 for color vectors, as the paper suggests.
  • Solvers. Preconditioned conjugate gradients, algebraic multigrid and GPU solvers. Grady's Section 3.6 lists these options.
  • Matting. The closed-form matting method solves the same kind of system, with a different Laplacian, to get a soft alpha matte.
  • Link to cuts. Later work views the random walker, the graph cut and shortest path methods as one energy with different powers on the weights and on the differences.

When to use it

Use it for interactive segmentation with several labels, for images with weak or broken edges, and when a probability per pixel is useful, as in medical images. Use Boykov-Jolly graph cuts for two labels when a hard, short boundary is wanted and the edges are strong. Use intelligent scissors when the user prefers to trace the boundary. For soft borders such as hair, use image matting.

Pitfalls

  • A large β\beta gives a near-singular system. Weights such as e−30e^{-30} make LUL_U close to singular, and the solution loses digits. The test file uses moderate values of β\beta; Grady used β=900\beta = 900 with his own normalization.
  • Normalization of the differences. The value of β\beta only means something together with the scale of (gi−gj)2(g_i - g_j)^2. State the normalization with the value.
  • A part of the graph without seeds. If some connected part has no seed, LUL_U is singular. A grid is connected, but a graph with zero weights, or a mask that cuts the image, can break this.
  • Ties. When two labels have equal probability at a pixel, the argmax picks one by its rule. Grady's connectivity result needs strict inequality.
  • More than two labels. A segment need not touch a seed of its own label, as the correctness section shows.
  • Dense matrices. The code of this page uses a dense matrix, so it suits small images only. Real images need a sparse solver.

Implementations

The Python code in impl/python/random_walker_segmentation.py builds the weights and the Laplacian of lines L1 and L2 on a 4-connected grid and solves line L5 with the dense solver of cvla.py. It also has a function that solves all KK systems, a conjugate gradient solver, the Dirichlet energy and a Monte Carlo simulation of the walk. The tests check the resistor example above, the sum rule against KK separate solves, the range [0,1][0, 1], the mean value property, the minimum of the Dirichlet energy, the agreement with simulated walks, the connectivity for two labels, the counterexample for three labels, and the agreement of conjugate gradients with the direct solve.

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.

cvla.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for the computer vision pages.

A matrix is a list of rows. A vector is a flat list. The functions do not
change their arguments. Entries are floats, but zeros, eye, transpose, add,
sub, scale, mul, matvec, dot, cross, skew, solve, inv and det also work with
fractions.Fraction entries and then give exact results.

Tolerances:
- solve, inv and det raise ValueError only on an exact zero pivot. A matrix
  that is close to singular gives large entries; check the condition yourself.
- sym_eig and svd stop a Jacobi sweep when every off-diagonal term is below
  1e-15 times the size of its pair (at most 100 sweeps).
- polyroots_real keeps a root z when |Im z| <= imag_tol * max(1, |z|), with
  imag_tol = 1e-6 by default. Roots of multiplicity k are found with an error
  of about 1e-16^(1/k) relative, so a double root keeps an imaginary part near
  1e-8.

This module holds no algorithm of a computer vision page.
"""

from __future__ import annotations

import cmath
import math
from typing import List, Sequence, Tuple

Matrix = List[List[float]]
Vector = List[float]

_JACOBI_EPS = 1e-15
_MAX_SWEEPS = 100


# ---------------------------------------------------------------- basics

def zeros(m: int, n: int) -> Matrix:
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n: int) -> Matrix:
    """The n x n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a) -> bool:
    return len(a) > 0 and isinstance(a[0], (list, tuple))


def transpose(a: Sequence[Sequence[float]]) -> Matrix:
    """The transpose of a matrix."""
    return [list(col) for col in zip(*a)]


def add(a, b):
    """a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, c):
    """c times a, for a vector or a matrix a and a number c."""
    if _is_matrix(a):
        return [[c * x for x in row] for row in a]
    return [c * x for x in a]


def mul(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> Matrix:
    """The matrix product a b."""
    if len(a[0]) != len(b):
        raise ValueError("mul: shapes do not match")
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a: Sequence[Sequence[float]], x: Sequence[float]) -> Vector:
    """The product a x of a matrix and a vector."""
    if len(a[0]) != len(x):
        raise ValueError("matvec: shapes do not match")
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x: Sequence[float], y: Sequence[float]) -> float:
    """The inner product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(a) -> float:
    """The Euclidean norm of a vector, or the Frobenius norm of a matrix."""
    if _is_matrix(a):
        return math.sqrt(sum(float(x) * float(x) for row in a for x in row))
    return math.sqrt(sum(float(x) * float(x) for x in a))


def cross(a: Sequence[float], b: Sequence[float]) -> Vector:
    """The cross product a x b of two 3-vectors."""
    return [a[1] * b[2] - a[2] * b[1],
            a[2] * b[0] - a[0] * b[2],
            a[0] * b[1] - a[1] * b[0]]


def skew(a: Sequence[float]) -> Matrix:
    """The skew matrix [a]_x, with skew(a) b = cross(a, b)."""
    z = a[0] - a[0]
    return [[z, -a[2], a[1]],
            [a[2], z, -a[0]],
            [-a[1], a[0], z]]


# ---------------------------------------------------- Gaussian elimination

def _eliminate(a: Matrix, b: Matrix) -> Tuple[Matrix, Matrix, int]:
    """Reduce [a | b] to upper triangular form with partial pivoting.

    Works in place on copies made by the caller. Returns a, b and the sign
    of the row permutation.
    """
    n = len(a)
    sign = 1
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(a[i][k]))
        if a[p][k] == 0:
            raise ValueError("singular matrix")
        if p != k:
            a[k], a[p] = a[p], a[k]
            b[k], b[p] = b[p], b[k]
            sign = -sign
        piv = a[k][k]
        for i in range(k + 1, n):
            f = a[i][k] / piv
            if f == 0:
                continue
            ai, ak = a[i], a[k]
            for j in range(k, n):
                ai[j] = ai[j] - f * ak[j]
            bi, bk = b[i], b[k]
            for j in range(len(bi)):
                bi[j] = bi[j] - f * bk[j]
    return a, b, sign


def solve(a: Sequence[Sequence[float]], b):
    """Solve a x = b for a square a, by Gaussian elimination with partial
    pivoting. b is a vector or a matrix (several right-hand sides); the
    result has the same form. Raises ValueError on an exact zero pivot."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("solve: matrix is not square")
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: shapes do not match")
    u, c, _ = _eliminate([list(row) for row in a], rhs)
    m = len(c[0]) if n else 0
    x = [[0.0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            s = c[i][j]
            for k in range(i + 1, n):
                s = s - u[i][k] * x[k][j]
            x[i][j] = s / u[i][i]
    return [row[0] for row in x] if vec else x


def inv(a: Sequence[Sequence[float]]) -> Matrix:
    """The inverse of a square matrix. Raises ValueError if it is singular."""
    n = len(a)
    one = a[0][0] - a[0][0] + 1 if n else 1.0
    ident = [[one if i == j else one - one for j in range(n)] for i in range(n)]
    return solve(a, ident)


def det(a: Sequence[Sequence[float]]) -> float:
    """The determinant of a square matrix, by Gaussian elimination."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("det: matrix is not square")
    if n == 0:
        return 1.0
    try:
        u, _, sign = _eliminate([list(row) for row in a], [[] for _ in range(n)])
    except ValueError:
        return a[0][0] - a[0][0]
    d = u[0][0] - u[0][0] + sign
    for i in range(n):
        d = d * u[i][i]
    return d


# ------------------------------------------------------- Jacobi methods

def sym_eig(a: Sequence[Sequence[float]]) -> Tuple[Vector, Matrix]:
    """Eigenvalues and eigenvectors of a real symmetric matrix by the cyclic
    Jacobi method. Returns (w, V): w ascending, and column j of V is a unit
    eigenvector for w[j], so a = V diag(w) V^T. Only the upper triangle of
    a is read (the lower triangle is taken as its mirror)."""
    n = len(a)
    s = [[float(a[min(i, j)][max(i, j)]) for j in range(n)] for i in range(n)]
    v = eye(n)
    for _ in range(_MAX_SWEEPS):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                apq = s[p][q]
                if apq == 0.0:
                    continue
                app, aqq = s[p][p], s[q][q]
                if abs(apq) <= _JACOBI_EPS * math.sqrt(abs(app * aqq)) or \
                        abs(apq) < 1e-300:
                    s[p][q] = s[q][p] = 0.0
                    continue
                rotated = True
                theta = (aqq - app) / (2.0 * apq)
                t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    skp, skq = s[k][p], s[k][q]
                    s[k][p] = c * skp - sn * skq
                    s[k][q] = sn * skp + c * skq
                for k in range(n):
                    spk, sqk = s[p][k], s[q][k]
                    s[p][k] = c * spk - sn * sqk
                    s[q][k] = sn * spk + c * sqk
                s[p][q] = s[q][p] = 0.0
                for k in range(n):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p] = c * vkp - sn * vkq
                    v[k][q] = sn * vkp + c * vkq
        if not rotated:
            break
    order = sorted(range(n), key=lambda i: s[i][i])
    w = [s[i][i] for i in order]
    vs = [[v[k][i] for i in order] for k in range(n)]
    return w, vs


def _complete_basis(cols: List[Vector], m: int, need: List[int]) -> None:
    """Replace the columns with index in need by unit vectors orthogonal to
    all other columns (Gram-Schmidt on the standard basis)."""
    keep = [c for i, c in enumerate(cols) if i not in need]
    for i in need:
        best, best_norm = None, -1.0
        for e in range(m):
            x = [0.0] * m
            x[e] = 1.0
            for _ in range(2):
                for c in keep:
                    d = dot(c, x)
                    x = [xi - d * ci for xi, ci in zip(x, c)]
            nx = norm(x)
            if nx > best_norm:
                best, best_norm = x, nx
        u = [xi / best_norm for xi in best]
        cols[i] = u
        keep.append(u)


def _svd_tall(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
    m, n = len(a), len(a[0])
    cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
    vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    for _ in range(_MAX_SWEEPS):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                cp, cq = cols[p], cols[q]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cq)
                gamma = sum(x * y for x, y in zip(cp, cq))
                if gamma == 0.0 or abs(gamma) <= _JACOBI_EPS * math.sqrt(alpha * beta):
                    continue
                rotated = True
                zeta = (beta - alpha) / (2.0 * gamma)
                t = (1.0 if zeta >= 0 else -1.0) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
                c = 1.0 / math.sqrt(1.0 + t * t)
                s = c * t
                cols[p] = [c * x - s * y for x, y in zip(cp, cq)]
                cols[q] = [s * x + c * y for x, y in zip(cp, cq)]
                vp, vq = vcols[p], vcols[q]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vq)]
                vcols[q] = [s * x + c * y for x, y in zip(vp, vq)]
        if not rotated:
            break
    sv = [norm(c) for c in cols]
    order = sorted(range(n), key=lambda i: -sv[i])
    sv = [sv[i] for i in order]
    cols = [cols[i] for i in order]
    vcols = [vcols[i] for i in order]
    smax = sv[0] if sv else 0.0
    ucols: List[Vector] = []
    need: List[int] = []
    for i, c in enumerate(cols):
        if sv[i] > 1e-13 * smax and sv[i] > 1e-300:
            ucols.append([x / sv[i] for x in c])
        else:
            ucols.append([0.0] * m)
            need.append(i)
    if need:
        _complete_basis(ucols, m, need)
    return transpose(ucols), sv, transpose(vcols)


def svd(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
    """Thin singular value decomposition by the one-sided Jacobi method.

    For an m x n matrix a with k = min(m, n), returns (U, S, V) with U of
    size m x k, S a list of k values in descending order and V of size
    n x k, such that a = U diag(S) V^T. U and V have orthonormal columns.
    For m >= n, V is square (n x n)."""
    m, n = len(a), len(a[0])
    if m >= n:
        return _svd_tall(a)
    u, s, v = _svd_tall(transpose(a))
    return v, s, u


def nullvec(a: Sequence[Sequence[float]]) -> Vector:
    """A unit vector x that minimizes ||a x||: the right singular vector of
    the smallest singular value. If a has fewer rows than columns, zero rows
    are added first, so the result is in the null space. The sign is not
    fixed."""
    m, n = len(a), len(a[0])
    rows = [list(map(float, r)) for r in a] + [[0.0] * n for _ in range(n - m)]
    _, _, v = _svd_tall(rows)
    return [v[i][n - 1] for i in range(n)]


# ---------------------------------------------- orthogonal factorizations

def qr(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """QR factorization by Householder reflections. For an m x n matrix a,
    returns Q (m x m, orthogonal) and R (m x n, upper triangular) with
    a = Q R. The signs are chosen so that the diagonal of R is >= 0."""
    m, n = len(a), len(a[0])
    r = [[float(x) for x in row] for row in a]
    q = eye(m)
    for k in range(min(m - 1, n)):
        x = [r[i][k] for i in range(k, m)]
        nx = norm(x)
        if nx == 0.0:
            continue
        alpha = -nx if x[0] >= 0 else nx
        v = list(x)
        v[0] -= alpha
        nv = norm(v)
        if nv == 0.0:
            continue
        v = [vi / nv for vi in v]
        for j in range(n):
            d = sum(v[i - k] * r[i][j] for i in range(k, m))
            if d != 0.0:
                for i in range(k, m):
                    r[i][j] -= 2.0 * v[i - k] * d
        for i in range(m):
            d = sum(q[i][l] * v[l - k] for l in range(k, m))
            if d != 0.0:
                for l in range(k, m):
                    q[i][l] -= 2.0 * d * v[l - k]
    for k in range(min(m, n)):
        if r[k][k] < 0:
            r[k] = [-x for x in r[k]]
            for i in range(m):
                q[i][k] = -q[i][k]
    for i in range(m):
        for j in range(min(i, n)):
            r[i][j] = 0.0
    return q, r


def rq(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """RQ factorization of a square matrix: returns R (upper triangular,
    with a diagonal >= 0) and Q (orthogonal) with a = R Q. It is computed
    from the QR factorization of the transpose of the row-reversed matrix."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("rq: matrix is not square")
    flipped = transpose([list(row) for row in reversed(a)])
    q1, r1 = qr(flipped)
    rt = transpose(r1)
    r = [list(reversed(row)) for row in reversed(rt)]
    q = [list(row) for row in reversed(transpose(q1))]
    return r, q


def cholesky(a: Sequence[Sequence[float]]) -> Matrix:
    """The lower triangular L with a = L L^T, for a symmetric positive
    definite a. Raises ValueError if a pivot is not positive."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(low[j][k] * low[j][k] for k in range(j))
        if d <= 0:
            raise ValueError("cholesky: matrix is not positive definite")
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return low


# ---------------------------------------------------------- polynomials

def _horner(c: Sequence[complex], x):
    p = 0.0
    for ci in c:
        p = p * x + ci
    return p


def polyroots_real(coeffs: Sequence[float], imag_tol: float = 1e-6) -> Vector:
    """Real roots of the polynomial with the given coefficients, highest
    power first. All complex roots are found by the Durand-Kerner method.
    A root z is kept as real when |Im z| <= imag_tol * max(1, |z|); its real
    part is then polished by Newton steps on the real polynomial. Returns
    the real roots in ascending order, with repeats for multiple roots."""
    c = [float(x) for x in coeffs]
    while c and c[0] == 0.0:
        c.pop(0)
    n = len(c) - 1
    if n < 1:
        return []
    c = [x / c[0] for x in c]
    rho = max([abs(c[i]) ** (1.0 / i) for i in range(1, n + 1)] + [0.0])
    if rho == 0.0:
        return [0.0] * n
    z = [rho * cmath.exp(1j * (2.0 * math.pi * k / n + 0.4)) for k in range(n)]
    for _ in range(2000):
        moved = 0.0
        for k in range(n):
            den = 1.0 + 0j
            for j in range(n):
                if j != k:
                    den *= z[k] - z[j]
            if den == 0:
                den = 1e-12 * rho
            step = _horner(c, z[k]) / den
            z[k] -= step
            moved = max(moved, abs(step) / max(1.0, abs(z[k])))
        if moved <= 1e-15:
            break
    deriv = [c[i] * (n - i) for i in range(n)]
    roots = []
    for zk in z:
        if abs(zk.imag) > imag_tol * max(1.0, abs(zk)):
            continue
        x = zk.real
        px = _horner(c, x)
        for _ in range(8):
            dp = _horner(deriv, x)
            if dp == 0.0 or px == 0.0:
                break
            xn = x - px / dp
            pn = _horner(c, xn)
            if abs(pn) >= abs(px):
                break
            x, px = xn, pn
        roots.append(x)
    return sorted(roots)


# ------------------------------------------------------------ self-test

def self_test() -> None:
    """Check svd, sym_eig and polyroots_real. Raises AssertionError."""
    import random
    rng = random.Random(7)
    for _ in range(3):
        a = [[rng.uniform(-1, 1) for _ in range(5)] for _ in range(5)]
        u, s, v = svd(a)
        rec = mul(mul(u, [[s[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(v))
        assert norm(sub(rec, a)) <= 1e-10
        assert all(s[i] >= s[i + 1] for i in range(4))
        sym = add(a, transpose(a))
        w, vv = sym_eig(sym)
        rec = mul(mul(vv, [[w[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(vv))
        assert norm(sub(rec, sym)) <= 1e-10
        assert all(w[i] <= w[i + 1] for i in range(4))
    r = polyroots_real([1.0, -6.0, 11.0, -6.0])
    assert len(r) == 3
    assert all(abs(x - y) <= 1e-10 for x, y in zip(r, [1.0, 2.0, 3.0]))


if __name__ == "__main__":
    self_test()
random_walker_segmentation.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/random-walker-segmentation/. The authors are listed in prov/TCA3BR.jsonl.

"""Random walker segmentation of Grady (2006).

Pixel p = v * w + u is (u, v) with the gray value img[v][u]. The pixels form a
4-connected grid graph. The edge weight is w_pq = exp(-beta d_pq), where d_pq
is the squared gray difference divided by the largest squared difference in
the image. The seeds are a dict from pixel to label 0 .. K-1. For each label
s the probability x^s is the harmonic function that is 1 on the seeds of s,
0 on the other seeds, and solves L_U x_U = -B^T m on the free pixels. Each
pixel gets the label of largest probability. The dense solver of cvla is
used, so the code suits small images only.
"""

import math

from cvla import solve, zeros


def grid_edges(h, w):
    """The 4-connected pairs (p, q) with p < q."""
    edges = []
    for v in range(h):
        for u in range(w):
            p = v * w + u
            if u + 1 < w:
                edges.append((p, p + 1))
            if v + 1 < h:
                edges.append((p, p + w))
    return edges


def edge_weights(img, edges, beta):
    """w_pq = exp(-beta d_pq) with the normalized squared difference d_pq."""
    flat = [x for row in img for x in row]
    d2 = [(flat[p] - flat[q]) ** 2 for p, q in edges]
    top = max(d2) if d2 else 0.0
    if top <= 0:
        top = 1.0
    return [math.exp(-beta * d / top) for d in d2]


def laplacian(n, edges, weights):
    """The dense graph Laplacian L = D - W."""
    lap = zeros(n, n)
    for (p, q), wt in zip(edges, weights):
        lap[p][p] += wt
        lap[q][q] += wt
        lap[p][q] -= wt
        lap[q][p] -= wt
    return lap


def solve_labels(lap, n, seeds, labels, free=None):
    """Solve L_U X = -B^T M for the given labels; return {s: x^s over all pixels}."""
    marked = sorted(seeds)
    if free is None:
        free = [p for p in range(n) if p not in seeds]
    out = {s: [0.0] * n for s in labels}
    for p in marked:
        if seeds[p] in out:
            out[seeds[p]][p] = 1.0
    if not free or not labels:
        return out
    lu = [[lap[i][j] for j in free] for i in free]
    rhs = [[-sum(lap[i][p] for p in marked if seeds[p] == s) for s in labels] for i in free]
    xu = solve(lu, rhs)
    for r, p in enumerate(free):
        for c, s in enumerate(labels):
            out[s][p] = xu[r][c]
    return out


def random_walker(img, seeds, beta, nlabels=None):
    """Return (probs, labels): probs[s][p] is the probability that a walker
    from pixel p first reaches a seed of label s, and labels[p] is the argmax.
    Every connected part of the grid must hold a seed (a grid is connected)."""
    h, w = len(img), len(img[0])
    n = h * w
    k = nlabels if nlabels is not None else max(seeds.values()) + 1
    if k < 2:
        raise ValueError("need at least two labels")
    edges = grid_edges(h, w)
    weights = edge_weights(img, edges, beta)  # @line L1
    lap = laplacian(n, edges, weights)  # @line L2
    free = [p for p in range(n) if p not in seeds]  # @line L3
    first = list(range(k - 1))  # @line L4
    part = solve_labels(lap, n, seeds, first, free)  # @line L5
    probs = [part[s] for s in first]
    probs.append([1.0 - sum(probs[s][p] for s in first) for p in range(n)])  # @line L6
    labels = [max(range(k), key=lambda s: probs[s][p]) for p in range(n)]  # @line L7
    return probs, labels  # @line L8


def random_walker_all(img, seeds, beta, nlabels):
    """The same probabilities from K solves, without the sum rule. For tests."""
    h, w = len(img), len(img[0])
    n = h * w
    edges = grid_edges(h, w)
    lap = laplacian(n, edges, edge_weights(img, edges, beta))
    part = solve_labels(lap, n, seeds, list(range(nlabels)))
    return [part[s] for s in range(nlabels)]


def dirichlet_energy(edges, weights, x):
    """D[x] = 1/2 x^T L x = 1/2 sum over edges of w_pq (x_p - x_q)^2."""
    return 0.5 * sum(wt * (x[p] - x[q]) ** 2 for (p, q), wt in zip(edges, weights))


def conjugate_gradient(a, b, tol=1e-12, maxit=None):
    """Solve a x = b for a symmetric positive definite a by conjugate gradients."""
    n = len(b)
    x = [0.0] * n
    r = list(b)
    d = list(r)
    rr = sum(t * t for t in r)
    for _ in range(maxit or 10 * n):
        if math.sqrt(rr) <= tol:
            break
        ad = [sum(a[i][j] * d[j] for j in range(n)) for i in range(n)]
        step = rr / sum(d[i] * ad[i] for i in range(n))
        x = [x[i] + step * d[i] for i in range(n)]
        r = [r[i] - step * ad[i] for i in range(n)]
        rr_new = sum(t * t for t in r)
        d = [r[i] + (rr_new / rr) * d[i] for i in range(n)]
        rr = rr_new
    return x


def monte_carlo(img, seeds, beta, start, walks, rng):
    """Estimate the probabilities at pixel start by simulating walks."""
    h, w = len(img), len(img[0])
    edges = grid_edges(h, w)
    weights = edge_weights(img, edges, beta)
    nbr = [[] for _ in range(h * w)]
    for (p, q), wt in zip(edges, weights):
        nbr[p].append((q, wt))
        nbr[q].append((p, wt))
    k = max(seeds.values()) + 1
    hits = [0] * k
    for _ in range(walks):
        p = start
        while p not in seeds:
            total = sum(wt for _, wt in nbr[p])
            t = rng.random() * total
            for q, wt in nbr[p]:
                t -= wt
                if t <= 0:
                    break
            p = q
        hits[seeds[p]] += 1
    return [c / walks for c in hits]
test_random_walker_segmentation.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/random-walker-segmentation/. The authors are listed in prov/TCA3BR.jsonl.

import math
import random

from random_walker_segmentation import (
    conjugate_gradient,
    dirichlet_energy,
    edge_weights,
    grid_edges,
    laplacian,
    monte_carlo,
    random_walker,
    random_walker_all,
    solve_labels,
)


def random_case(rng, h, w, k):
    img = [[rng.choice((20, 90, 160, 230)) + rng.randrange(15) for _ in range(w)] for _ in range(h)]
    pix = list(range(h * w))
    rng.shuffle(pix)
    seeds = {}
    for s in range(k):
        seeds[pix[2 * s]] = s
        seeds[pix[2 * s + 1]] = s
    return img, seeds


def test_chain_is_resistors_in_series():
    img = [[10, 20, 60, 70, 80]]
    probs, labels = random_walker(img, {0: 0, 4: 1}, 2.0)
    w = edge_weights(img, grid_edges(1, 5), 2.0)
    res = [1.0 / x for x in w]
    total = sum(res)
    want = [sum(res[:i]) / total for i in range(5)]
    assert all(abs(a - b) < 1e-12 for a, b in zip(probs[1], want))
    assert [round(x, 4) for x in probs[1]] == [0.0, 0.105, 0.7899, 0.895, 1.0]
    assert labels == [0, 0, 1, 1, 1]


def test_sum_range_and_sum_rule():
    rng = random.Random(11)
    for _ in range(20):
        k = rng.randint(2, 4)
        img, seeds = random_case(rng, 4, 5, k)
        probs, _ = random_walker(img, seeds, 5.0)
        full = random_walker_all(img, seeds, 5.0, k)
        for p in range(20):
            assert abs(sum(full[s][p] for s in range(k)) - 1.0) < 1e-9
            for s in range(k):
                assert -1e-12 <= probs[s][p] <= 1.0 + 1e-12
                assert abs(probs[s][p] - full[s][p]) < 1e-9


def test_mean_value_property():
    rng = random.Random(5)
    for _ in range(10):
        img, seeds = random_case(rng, 4, 4, 3)
        h, w = 4, 4
        edges = grid_edges(h, w)
        wts = edge_weights(img, edges, 50.0)
        nbr = [[] for _ in range(h * w)]
        for (p, q), x in zip(edges, wts):
            nbr[p].append((q, x))
            nbr[q].append((p, x))
        probs, _ = random_walker(img, seeds, 50.0)
        for xs in probs:
            for p in range(h * w):
                if p in seeds:
                    continue
                avg = sum(x * xs[q] for q, x in nbr[p]) / sum(x for _, x in nbr[p])
                assert abs(xs[p] - avg) < 1e-9


def test_minimizes_dirichlet_energy():
    rng = random.Random(3)
    img, seeds = random_case(rng, 3, 4, 2)
    edges = grid_edges(3, 4)
    wts = edge_weights(img, edges, 20.0)
    probs, _ = random_walker(img, seeds, 20.0)
    best = dirichlet_energy(edges, wts, probs[0])
    for _ in range(200):
        y = [x if p in seeds else x + rng.uniform(-0.1, 0.1) for p, x in enumerate(probs[0])]
        assert dirichlet_energy(edges, wts, y) >= best - 1e-12


def test_two_labels_each_segment_part_touches_its_seed():
    rng = random.Random(8)
    h, w = 5, 5
    for _ in range(15):
        img, seeds = random_case(rng, h, w, 2)
        _, labels = random_walker(img, seeds, 20.0)
        for s in range(2):
            reach = [p for p in seeds if seeds[p] == s]
            seen = set(reach)
            while reach:
                p = reach.pop()
                u, v = p % w, p // w
                for uu, vv in ((u + 1, v), (u - 1, v), (u, v + 1), (u, v - 1)):
                    q = vv * w + uu
                    if 0 <= uu < w and 0 <= vv < h and q not in seen and labels[q] == s:
                        seen.add(q)
                        reach.append(q)
            assert seen == {p for p in range(h * w) if labels[p] == s}


def test_three_labels_can_give_a_part_without_seed():
    # Node 0 joins nodes 1 and 2. Node 1 joins a seed of label 0 and a seed
    # of label 1, node 2 a seed of label 0 and a seed of label 2.
    edges = [(0, 1), (0, 2), (1, 5), (1, 3), (2, 6), (2, 4)]
    lap = laplacian(7, edges, [1.0, 1.0, 1.2, 1.0, 1.2, 1.0])
    seeds = {3: 0, 4: 0, 5: 1, 6: 2}
    x = solve_labels(lap, 7, seeds, [0, 1, 2])
    label = [max(range(3), key=lambda s: x[s][p]) for p in range(3)]
    assert label == [0, 1, 2]
    assert abs(x[0][0] - 1 / 2.2) < 1e-12
    assert x[1][1] > x[0][1] and x[2][2] > x[0][2]
    # The same pattern on a 2 x 5 image: pixel 7 gets label 0, but its
    # neighbors 2, 6 and 8 get labels 1, 1 and 2.
    img = [[250, 90, 250, 90, 250], [100, 100, 110, 100, 100]]
    _, labels = random_walker(img, {1: 0, 3: 0, 5: 1, 9: 2, 2: 1}, 60.0)
    assert labels[7] == 0
    assert [labels[2], labels[6], labels[8]] == [1, 1, 2]


def test_agrees_with_simulated_walks():
    rng = random.Random(2024)
    img = [[20, 25, 200], [22, 180, 210], [30, 190, 220]]
    seeds = {0: 0, 8: 1}
    probs, _ = random_walker(img, seeds, 4.0)
    for start in (1, 4, 6):
        est = monte_carlo(img, seeds, 4.0, start, 3000, rng)
        assert abs(est[1] - probs[1][start]) < 0.04


def test_conjugate_gradient_matches_direct_solve():
    rng = random.Random(9)
    img, seeds = random_case(rng, 4, 4, 2)
    edges = grid_edges(4, 4)
    lap = laplacian(16, edges, edge_weights(img, edges, 10.0))
    free = [p for p in range(16) if p not in seeds]
    lu = [[lap[i][j] for j in free] for i in free]
    b = [-sum(lap[i][p] for p in seeds if seeds[p] == 1) for i in free]
    x = conjugate_gradient(lu, b)
    probs, _ = random_walker(img, seeds, 10.0)
    assert all(abs(x[r] - probs[1][p]) < 1e-8 for r, p in enumerate(free))
    assert math.isfinite(sum(x))

History

Kakutani (1945) linked the Dirichlet problem to Brownian motion: the solution at a point is the expected boundary value where a random path from that point first hits the boundary. Doyle and Snell (1984) explained the discrete version, with random walks on graphs and electric networks, in a short book. Grady and Funka-Lea (2004) used these potentials for multi-label segmentation of medical images, and Grady (2006) gave the full method, with the circuit analogy, the numerics and the properties. The method became a standard tool in medical image analysis and a reference point for later work that joins graph cuts, random walks and shortest paths in one framework.

References

  1. Leo Grady, Random walks for image segmentation, IEEE TPAMI 28(11), 1768-1783, 2006, Section 3.1 (edge weights, equation 1), Section 3.2 (combinatorial Dirichlet problem, equations 6 to 12), Section 3.6 (numerical practicalities), Section 3.7 (algorithm summary), Section 4.3 (properties and Proposition 1)
  2. Richard Szeliski, Computer Vision: Algorithms and Applications, 1st edition, Springer, 2011, Chapter 5, Segmentation

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example