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.
- Solves
- Interactive segmentation
- 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
- Model
- Real RAM
- Properties
- deterministicexactinteractivemulti labelsoft output
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Leo Grady, 2006
Random walker segmentation is an algorithm that splits an image into 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 with pixels, a set of seed pixels, a label for each seed , and a parameter . The pixels are the nodes of a 4-connected grid graph. The output is, for each pixel and label , the probability that a random walk from reaches a seed of label before any other seed, and the label . The problem is interactive segmentation with labels as seeds.
The walk moves from to a neighbor with probability , where is the degree. Grady (2006, equation 1) uses the weights
where 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 does not depend on the gray scale.
The algorithm
Order the pixels with the seeds first and the free pixels after them. The Laplacian then has the blocks
For a label , the vector on the seeds has if and otherwise. The probabilities of label on the free pixels solve (Grady 2006, equation 10)
RANDOM-WALKER(I, seeds, β)- 1
for each grid edge {i, j} do w_ij ← exp(-β (g_i - g_j)² / max (g_p - g_q)²) - 2
L ← D - W ▷ sparse, 5 entries per row - 3
split the pixels into seeds M and free pixels U; take the blocks L_U and B - 4
for s ← 1 to K - 1 do m^s_j ← 1 if ℓ(j) = s else 0, for j in M - 5
for s ← 1 to K - 1 do solve L_U x^s_U = -B^T m^s - 6
x^K ← 1 - Σ_{s<K} x^s - 7
for each pixel i do label_i ← argmax_s x^s_i - 8
return 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 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 , a seed of label 0 at pixel 0, a seed of label 1 at pixel 4, and . The squared differences are . Divided by the largest, they are , so the weights are
On a chain the system is a set of resistors in series. Each edge is a resistor of resistance : , , , , with the sum . 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 |
| 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 . 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). 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 with the seeds fixed. This is equation 6 of the paper.
- Theorem (random walk). The solution equals the probability that the walk from first reaches a seed of label .
- Theorem (range and sum). Each lies in , by the maximum principle, and , which justifies line L6.
- Theorem (two labels give connected segments). With , each pixel with label is joined to a seed of label through pixels with label . This is Proposition 1 of the paper for .
For that last statement is false, although Grady states it for any . 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 image.
Proof: Correctness of random walker segmentationfull
This proof covers lines L1 to L8 of the main page. The graph has the node set with , undirected edges with weights , and the degrees . Line L1 gives for every grid edge, so this holds. The Laplacian of line L2 is : , for an edge and otherwise. The seeded nodes are not empty, and each seed has a label . The free nodes are . Order the nodes with first, so that
For a label , the boundary vector on has if and 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)
is symmetric positive definite.
Proof. For , extend it by on to a vector . Then
The identity follows from by expanding the square. If the sum is , then is constant on each connected component of the graph, because every weight is positive. Each component holds a seed, where , so and .
So the system of line L5 has exactly one solution . Write for the full vector with .
Lemma 2 (mean value property)
For each free node , .
Proof. Row of reads , where the sum runs over all neighbors, free or seeded.
A vector with this property on is called harmonic on .
Lemma 3 (minimum of the Dirichlet energy)
Among all with , the vector is the only minimizer of .
Proof. With fixed,
This is a quadratic function of with the Hessian , which is positive definite by Lemma 1. So it is strictly convex, and its only minimizer is the zero of the gradient , which is .
Lemma 4 (maximum principle)
Let be harmonic on . Then for each . In particular .
Proof. Let , and suppose . The set is not empty and lies in . Take . By Lemma 2, is a weighted mean of its neighbors with positive weights, and no neighbor is above , so every neighbor equals and is in . So is closed under taking neighbors, and is a whole connected component of the graph. That component holds a seed, which is in , a contradiction. The bound from below is the same argument for .
Lemma 5 (the random walk)
Take the walk that moves from node to a neighbor with probability and stops at the first seed it reaches. For a free start node , let be the probability that the walk stops at a seed of label , and let on . Then .
Proof. First, the walk stops with probability 1. From each free node there is a path to a seed with at most steps, by the hypothesis. Each step of that path has probability at least . So in each block of steps the walk stops with probability at least , and the probability that it never stops is at most .
Next, condition on the first step. From a free node the walk goes to with probability and then behaves as a walk from , so . This is the property of Lemma 2, with the same values on . The difference is harmonic on and on , so it is by Lemma 4.
Theorem 1 (the sum rule of line L6)
. So the vector of line L6 equals the solution of the system for label .
Proof. The rows of sum to , so , and its rows in give . Each seed has exactly one label, so . The systems are linear with the same matrix, so solves . By Lemma 1 that solution is unique, and it is . So , and .
Theorem 2 (the output)
Lines L1 to L8 return, for each pixel and each label , the probability of Lemma 5 that a walker from first reaches a seed of label , and the label of largest probability.
Proof. Lines L1 to L4 build , the partition and the vectors . Line L5 solves the systems for , which have one solution each by Lemma 1. Line L6 gives by Theorem 1. Line L7 takes the argmax. The values are the walk probabilities by Lemma 5 and lie in by Lemma 4.
Proposition 1 (connected segments, two labels)
Let , and give node the label only if for the other label . Then each node with label is joined to a seed of label by a path of nodes with label .
Proof. With , , so node has label exactly when . Let be a connected component of the set , and suppose that has no seed. Seeds of the other label have , so . Let and . Take . Each neighbor of either is in , with , or has . By Lemma 2, is a weighted mean of its neighbors with positive weights, so every neighbor has , is in , and is in . So is a whole connected component of the graph, and it holds a seed. That seed is in , a contradiction.
This is Proposition 1 of Grady (2006) in the case .
Remark: more than two labels
For 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 , and the equation at node 1 gives , so . Then , so node 0 has label 0. At node 1, , 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 image with the same pattern.
The proof in the paper shows, for each other label separately, that some neighbor of the component has . For that is enough. For the neighbor can differ from one 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 and on the seeds. Lemma 1 needs exact arithmetic. In floating point a large gives weights near , and then is close to singular. The test file uses moderate values of for this reason.
Complexity
The cost model is the real-RAM, with exact arithmetic on real numbers. Let . Lines L1 to L4 and L6 to L7 cost time. Line L5 dominates.
- Dense elimination, as in the code. One LU factorization of costs time and space, and each of the right sides costs . The total is , the bound in the front matter. The best case is when almost all pixels are seeds, so that is tiny. This is a theorem about the code.
- Sparse direct solve. has at most 5 nonzeros per row. With nested dissection on a 2D grid, the factorization costs time and space (George 1973). This is a theorem for grid graphs.
- Conjugate gradients. Each iteration costs . The number of iterations to reduce the error by a factor is , where is the condition number of . This is a theorem, but grows with 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 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 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 by 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 gives a near-singular system. Weights such as make close to singular, and the solution loses digits. The test file uses moderate values of ; Grady used with his own normalization.
- Normalization of the differences. The value of only means something together with the scale of . State the normalization with the value.
- A part of the graph without seeds. If some connected part has no seed, 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 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 separate solves, the range , 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.
# 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag TCA3BR Edit this page History Report an error Markdown