Modeladvanced
Pictorial structures
Also called Fischler-Elschlager model.
Model an object as parts joined by springs, and with a tree of springs find the best placement of all parts by dynamic programming over the tree.
A pictorial structure models an object as a set of parts, each with its own appearance, and a set of springs between pairs of parts that say where the parts usually sit relative to each other. A face is two eyes, a nose and a mouth on springs; a person is a head, a torso and limbs. Matching the model to an image means placing every part at once so that the parts fit the image well and the springs are not stretched much. Fischler and Elschlager (1973) introduced the model; Felzenszwalb and Huttenlocher (2005) showed that when the springs form a tree and their costs are quadratic, the best placement can be found exactly in time linear in the number of possible locations of a part.
The machine
Parts and locations. A model has parts . A location of part is a point of a discrete set of values: a position , and in some models also a scale and an orientation. A configuration is .
Appearance. For each part, a match cost says how badly the image fits part at location ; lower is better. In practice it comes from a filter, such as the correlation of a template with HOG features, or from a colour model of a limb.
Springs. A graph on the parts has a deformation cost for each edge. Felzenszwalb and Huttenlocher use a Mahalanobis distance with a diagonal , where the maps and take each location to the place of the joint between the two parts. For positions only, with the child resting at an offset from its parent , this is
The energy. The best configuration minimizes
In the statistical form of the model, is a likelihood for the image near each part and is a Markov random field prior on the configuration, so the minimum of is the maximum a posteriori configuration.
What it counts
The cost of matching is the number of operations to find and a configuration that attains it, as a function of and , in the real RAM. For a tree, the minimum is computed by tree dynamic programming: each part sends to its parent a message , the best cost of its whole subtree for each location of the parent. Computing one message by trying every pair of locations costs , so the direct method costs . With in the hundreds of thousands, for positions, scales and angles, this is too slow, and the quadratic form of is what brings it down to . The model also counts the cost of learning: estimating the , the and the tree from labelled examples.
Relation to other models
- Star models. A star is a tree with one root part and all other parts as its children. The deformable part model is a star pictorial structure on HOG features, with a root filter, part filters at twice the resolution, quadratic deformation costs, and discriminative training. The implicit shape model is another star model, in which local features vote for the position of the object centre and parts are not explicit.
- Constellation models. Generative part models with a full joint Gaussian shape model, such as the constellation models of Perona and his students, give each pair of parts a dependency; matching them costs exponentially more in . The tree drops most of these dependencies to get exact matching.
- Templates. A rigid template match is a pictorial structure with one part, or with springs of infinite stiffness. The Dalal-Triggs detector is such a rigid template on HOG features.
- Graphical models. The energy is a pairwise Markov random field on the parts. On a tree, the dynamic program is min-sum belief propagation. On a graph with cycles, loopy belief propagation and other approximate methods apply, but exactness is lost.
Known results in the model
General graphs are hard. For an arbitrary graph and arbitrary costs, minimizing is NP-hard, as Felzenszwalb and Huttenlocher (2005) note in Section 4.1; with parts the brute-force search tries configurations.
Trees in . For a tree, the recurrences of Felzenszwalb and Huttenlocher (Eq. (11) and (12)) compute the messages from the leaves to the root and the minimizing locations on the way back, in time for arbitrary pairwise costs.
Trees with quadratic springs in . When is a squared distance after the maps , each message is a generalized distance transform of the function that the subtree sends up. The Felzenszwalb distance transform computes it for in linear time by building the lower envelope of the parabolas , one for each , and the transform is separable over the coordinates. The whole match then costs :
DT1(f, w, u) ▷ D(p) = min over q of f(q) + w (q - p - u)^2- 1
k ← 0; v[0] ← 0; z[0] ← -∞; z[1] ← +∞ - 2
for q ← 1 to N - 1 do - 3
s ← ((f(q) + w q^2) - (f(v[k]) + w v[k]^2)) / (2 w (q - v[k])) - 4
if s ≤ z[k] then k ← k - 1 and go back to L3 - 5
k ← k + 1; v[k] ← q; z[k] ← s; z[k + 1] ← +∞ - 6
k ← 0 - 7
for p ← 0 to N - 1 do - 8
while z[k + 1] < p + u do k ← k + 1 - 9
D(p) ← w (p + u - v[k])^2 + f(v[k]); A(p) ← v[k] MATCH(tree, m, springs)- 10
for each part j in postorder (children before parents) do - 11
f_j ← m_j + the sum of B_c over the children c of j - 12
if j is not the root then (B_j, A_j) ← DT2 of f_j with the spring of j ▷ DT1 on rows, then on columns - 13
l_root ← a location that minimizes f_root - 14
for each part j in preorder, below the root do l_j ← A_j(l_parent(j)) - 15
return the configuration l and the energy f_root(l_root)
The correctness file proves that DT1 evaluates the lower envelope, that the two passes of DT2 give the two-dimensional transform, and that the messages give the minimum energy over each subtree, so the configuration is optimal.
A small example. Take the one-dimensional function on the positions , with and . The transform is with the minimizers : for the best is with , and for it is with . For a three-part star on six positions in a row, with a torso as the root, the match costs torso , head resting one position to the right of the torso, and leg resting one position to the left, all with , the messages are and . The torso total is . The smallest value is 3, first reached at position 3; going back down, the head goes to position 5 (cost ) and the leg to position 3 (cost ). The energy is , and a search over all configurations gives the same minimum.
Learning. Given labelled configurations, Felzenszwalb and Huttenlocher estimate the appearance models and the spring parameters of each pair by maximum likelihood, and choose the tree as a minimum spanning tree of the pairwise costs, computed with Kruskal's algorithm.
Sampling. Instead of one best configuration, the same messages, with sums in place of minima, let one draw configurations from the posterior distribution (Section 4.2); the distance transform is replaced by a Gaussian convolution. Several samples give several hypotheses, which later steps can check.
Uses. With a tree of body parts (torso, head and limb segments) and locations with position, scale and angle, Felzenszwalb and Huttenlocher matched articulated people in images. The star-shaped special case, trained discriminatively, became the deformable part model, which had the best average precision on 9 of the 20 classes of PASCAL VOC 2008 in its authors' comparison, and tree models of body parts became a standard approach to human pose estimation before convolutional networks.
The Python code of this page implements DT1, the separable DT2 with offsets and weights, and MATCH for any tree. Its tests compare DT1 with a direct minimum over all , DT2 with a quadratic search, and MATCH with a search over all configurations of up to four parts, and check the example above.
Proof: Tree dynamic programming with distance transforms finds a minimum-energy configuration in time linear in the number of locationsfull
We use the notation of the page. A model has parts on a tree with root ; each part has a parent . Each part has a match cost for every location of a set of grid cells, and each edge has the spring cost
The energy of a configuration is .
Claim. MATCH returns a configuration of minimum energy, and the energy it reports is that minimum. With the distance transform it takes time.
Lemma 1 (the one-dimensional transform). For , and a real , DT1 returns for every , and a minimizing .
Proof. For each , the function is a parabola with the same leading coefficient . Two such parabolas, for , cross at exactly one point
and the parabola of is the lower one to the right of . So the lower envelope of the parabolas is a sequence of pieces, with the indices of the pieces increasing from left to right. Lines L1 to L5 build the envelope of the first parabolas from that of the first : the new parabola of is lowest to the right of its crossing with the last piece; if , the start of the last piece, then the last piece is nowhere lowest any more and line L4 removes it. When the loop stops, , the last piece keeps the part , and the new piece covers . This is the invariant that are the indices of the envelope pieces and bound piece . Lines L6 to L9 then evaluate the envelope at : since grows with and the pieces are ordered, the pointer of line L8 moves forward to the piece that contains , and line L9 evaluates that parabola, which is the minimum over all .
Cost of Lemma 1. Each index is appended once in line L5 and removed at most once in line L4, and the pointer of line L8 moves at most times, so DT1 takes time.
Lemma 2 (the two-dimensional transform). DT2 returns and a minimizer, in time.
Proof. The cost is a sum of a term in and a term in , so
The inner minimum is DT1 along row , and the outer one is DT1 along column of the result. The minimizer is the of the outer transform and the that the inner transform stored for row and column . Each of the two passes calls DT1 on lines of total length .
Lemma 3 (the messages). For a part , let be the subtree rooted at , and define
Then is the minimum, over all placements of the parts of with at , of the energy restricted to (the match costs of its parts and the springs of its edges).
Proof. By induction on the height of . For a leaf, . For an inner part with fixed at , the energy of is plus, for each child , the spring plus the energy of . Once is fixed, the subtrees of different children share no part and no edge, so their terms can be minimized one at a time. For child , the minimum over the placements of with at is by induction, and the minimum over of is .
Proof of the claim. Line L10 visits the parts in postorder, so the messages of all children of exist when line L11 forms . Line L12 computes with Lemma 2, with the parent location as the query point and the spring of , and stores the minimizer for each parent location . By Lemma 3 with the whole tree, is the minimum energy, and line L13 picks a location that attains it. Line L14 goes down the tree and sets . By induction from the root, the placement of each subtree that this builds attains , because attains the minimum that defines . So the returned configuration has energy , the minimum.
Cost: each part other than the root costs for line L11, counting each child once at its parent, and for line L12 by Lemma 2. Lines L13 and L14 cost . The total is . With a general cost instead of a squared distance, line L12 would need time for each part.
Remark (cycles). Lemma 3 uses that the subtrees of different children are disjoint. If the parts form a graph with a cycle, this fails, and the minimization is NP-hard in general, as Felzenszwalb and Huttenlocher note for arbitrary graphs.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pictorial-structures/. The authors are listed in prov/ZNK7K3.jsonl.
"""Matching a tree-structured pictorial structure (Felzenszwalb and
Huttenlocher 2005) by dynamic programming with generalized distance
transforms.
Locations are the cells (x, y) of a W x H grid. Part i has a match cost
m[i][y][x] (lower is better). Each part j other than the root has a parent
p and a spring: the cost of placing j at (xj, yj) when p is at (xp, yp) is
wx * (xj - xp - ux)^2 + wy * (yj - yp - uy)^2 (wx, wy > 0),
so the child rests at the offset (ux, uy) from its parent. The energy of a
configuration is the sum of all match costs and all spring costs. With
integer costs, weights and offsets, every value here is exact.
Standard library only.
"""
from fractions import Fraction
from itertools import product
INF = float("inf")
def dt1d(f, w=1, u=0):
"""D[p] = min over q of f[q] + w * (q - p - u)^2, for p = 0..n-1, and the
minimizing q. Lower envelope of parabolas, O(n) time.
"""
n = len(f)
v, z, k = [0], [-INF, INF], 0 # @line L1
for q in range(1, n): # @line L2
while True:
s = Fraction((f[q] + w * q * q) - (f[v[k]] + w * v[k] * v[k]), 2 * w * (q - v[k])) # @line L3
if s <= z[k]: # @line L4
k -= 1
v.pop()
z.pop()
continue
break
k += 1 # @line L5
v.append(q)
z[k] = s
z.append(INF)
D, arg, k = [None] * n, [None] * n, 0 # @line L6
for p in range(n): # @line L7
t = p + u
while z[k + 1] < t: # @line L8
k += 1
D[p] = w * (t - v[k]) ** 2 + f[v[k]] # @line L9
arg[p] = v[k]
return D, arg
def dt1d_brute(f, w=1, u=0):
n = len(f)
D, arg = [], []
for p in range(n):
best = min(range(n), key=lambda q: (f[q] + w * (q - p - u) ** 2, q))
D.append(f[best] + w * (best - p - u) ** 2)
arg.append(best)
return D, arg
def dt2d(f, wx=1, wy=1, ux=0, uy=0):
"""D[y][x] = min over (x', y') of f[y'][x'] + wx (x' - x - ux)^2
+ wy (y' - y - uy)^2, and the minimizing (x', y'). Separable: rows
first, then columns, O(W H) time.
"""
H, W = len(f), len(f[0])
g, gx = [], []
for row in f:
d, a = dt1d(row, wx, ux)
g.append(d)
gx.append(a)
D = [[None] * W for _ in range(H)]
A = [[None] * W for _ in range(H)]
for x in range(W):
d, a = dt1d([g[y][x] for y in range(H)], wy, uy)
for y in range(H):
yy = a[y]
D[y][x] = d[y]
A[y][x] = (gx[yy][x], yy)
return D, A
def spring(edge, parent_loc, child_loc):
ux, uy, wx, wy = edge
(xp, yp), (xc, yc) = parent_loc, child_loc
return wx * (xc - xp - ux) ** 2 + wy * (yc - yp - uy) ** 2
def energy(costs, parent, edges, config):
"""Sum of match costs and spring costs of a configuration (list of (x, y))."""
e = 0
for i, (x, y) in enumerate(config):
e += costs[i][y][x]
if parent[i] is not None:
e += spring(edges[i], config[parent[i]], config[i])
return e
def _postorder(parent):
n = len(parent)
children = [[] for _ in range(n)]
root = None
for i, p in enumerate(parent):
if p is None:
root = i
else:
children[p].append(i)
order, stack = [], [(root, False)]
while stack:
node, done = stack.pop()
if done:
order.append(node)
else:
stack.append((node, True))
for c in children[node]:
stack.append((c, False))
return root, children, order
def match(costs, parent, edges, transform=dt2d):
"""Return (best energy, best configuration) of a tree-structured model.
parent[i] is None for the root; edges[i] = (ux, uy, wx, wy) is the
spring from parent[i] to i.
"""
root, children, order = _postorder(parent)
H, W = len(costs[0]), len(costs[0][0])
B, A = {}, {}
for j in order: # @line L10
f = [[costs[j][y][x] + sum(B[c][y][x] for c in children[j]) for x in range(W)]
for y in range(H)] # @line L11
if j == root:
break
ux, uy, wx, wy = edges[j]
B[j], A[j] = transform(f, wx, wy, ux, uy) # @line L12
best = min(((f[y][x], (x, y)) for y in range(H) for x in range(W)),
key=lambda t: (t[0], t[1][1], t[1][0])) # @line L13
config = [None] * len(parent)
config[root] = best[1]
stack = [root]
while stack: # @line L14
p = stack.pop()
x, y = config[p]
for c in children[p]:
config[c] = A[c][y][x]
stack.append(c)
return best[0], config # @line L15
def dt2d_quadratic(f, wx=1, wy=1, ux=0, uy=0):
"""The same transform by trying every pair of cells, O((W H)^2)."""
H, W = len(f), len(f[0])
D = [[None] * W for _ in range(H)]
A = [[None] * W for _ in range(H)]
for y in range(H):
for x in range(W):
best = None
for yy in range(H):
for xx in range(W):
v = f[yy][xx] + wx * (xx - x - ux) ** 2 + wy * (yy - y - uy) ** 2
if best is None or v < best:
best, A[y][x] = v, (xx, yy)
D[y][x] = best
return D, A
def match_brute(costs, parent, edges):
"""Try every configuration. Exponential in the number of parts."""
H, W = len(costs[0]), len(costs[0][0])
cells = [(x, y) for y in range(H) for x in range(W)]
best = None
for config in product(cells, repeat=len(parent)):
e = energy(costs, parent, edges, config)
if best is None or e < best[0]:
best = (e, list(config))
return best
test_pictorial_structures.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pictorial-structures/. The authors are listed in prov/ZNK7K3.jsonl.
import random
from pictorial_structures import (dt1d, dt1d_brute, dt2d, dt2d_quadratic, energy, match,
match_brute)
def random_costs(rng, parts, W, H, top=9):
return [[[rng.randint(0, top) for _ in range(W)] for _ in range(H)] for _ in range(parts)]
def random_tree(rng, parts):
parent = [None] + [rng.randrange(i) for i in range(1, parts)]
edges = [None] + [(rng.randint(-2, 2), rng.randint(-2, 2), rng.randint(1, 3), rng.randint(1, 3))
for _ in range(1, parts)]
return parent, edges
def test_page_examples():
assert dt1d([3, 0, 5, 1, 4]) == ([1, 0, 1, 1, 2], [1, 1, 1, 3, 3])
assert dt1d([3, 0, 5, 1, 4], 1, 2)[0] == [1, 1, 2, 5, 8]
costs = [[[2, 1, 3, 0, 2, 4]], [[1, 3, 0, 2, 4, 1]], [[3, 2, 2, 0, 1, 0]]]
parent, edges = [None, 0, 0], [None, (1, 0, 1, 1), (-1, 0, 1, 1)]
assert dt1d(costs[1][0], 1, 1)[0] == [1, 0, 1, 2, 1, 2]
assert dt1d(costs[2][0], 1, -1)[0] == [4, 3, 2, 1, 0, 1]
assert match(costs, parent, edges) == (3, [(3, 0), (5, 0), (3, 0)])
def test_dt1d_matches_brute_force():
rng = random.Random(31)
for trial in range(400):
n = rng.randint(1, 12)
f = [rng.randint(-5, 20) for _ in range(n)]
w, u = rng.randint(1, 4), rng.randint(-4, 4)
D, arg = dt1d(f, w, u)
Db, _ = dt1d_brute(f, w, u)
assert D == Db
assert all(f[arg[p]] + w * (arg[p] - p - u) ** 2 == D[p] for p in range(n))
def test_dt2d_matches_quadratic():
rng = random.Random(32)
for trial in range(60):
W, H = rng.randint(1, 6), rng.randint(1, 5)
f = [[rng.randint(0, 15) for _ in range(W)] for _ in range(H)]
wx, wy, ux, uy = rng.randint(1, 3), rng.randint(1, 3), rng.randint(-2, 2), rng.randint(-2, 2)
D, A = dt2d(f, wx, wy, ux, uy)
Dq, _ = dt2d_quadratic(f, wx, wy, ux, uy)
assert D == Dq
for y in range(H):
for x in range(W):
xx, yy = A[y][x]
assert f[yy][xx] + wx * (xx - x - ux) ** 2 + wy * (yy - y - uy) ** 2 == D[y][x]
def test_match_equals_brute_force():
rng = random.Random(33)
for trial in range(60):
parts = rng.randint(1, 4)
W, H = (4, 3) if parts <= 3 else (3, 3)
costs = random_costs(rng, parts, W, H)
parent, edges = random_tree(rng, parts)
e, config = match(costs, parent, edges)
eb, _ = match_brute(costs, parent, edges)
assert e == eb
assert energy(costs, parent, edges, config) == e
def test_distance_transform_and_quadratic_dp_agree_on_larger_grids():
rng = random.Random(34)
for trial in range(6):
parts = 5
costs = random_costs(rng, parts, 6, 5, top=30)
parent, edges = random_tree(rng, parts)
e1, c1 = match(costs, parent, edges)
e2, c2 = match(costs, parent, edges, transform=dt2d_quadratic)
assert e1 == e2
assert energy(costs, parent, edges, c1) == e1 == energy(costs, parent, edges, c2)
def test_envelope_is_linear():
# Every q is pushed once and popped at most once, and the query pointer
# only moves forward, so the work is O(n) even for adversarial input.
rng = random.Random(35)
f = [rng.randint(0, 10 ** 6) for _ in range(5000)]
D, arg = dt1d(f, 3, 7)
assert len(D) == 5000
assert all(arg[p] <= arg[p + 1] for p in range(4999)) # minimizers are monotone
References
- Martin A. Fischler and Robert A. Elschlager, The representation and matching of pictorial structures, IEEE Transactions on Computers C-22(1), 1973, 67-92, The model of components held by springs, the cost of a match, and the matching procedure similar to dynamic programming (abstract and main text)
- Pedro F. Felzenszwalb and Daniel P. Huttenlocher, Pictorial structures for object recognition, International Journal of Computer Vision 61(1), 2005, 55-79, Eq. (1) (the energy), Eq. (2) (the deformation cost as a Mahalanobis distance), Section 2 (the statistical framework with a tree-structured prior), Section 3 (learning, with the tree as a minimum spanning tree), Section 4.1 (NP-hardness for general graphs, the recurrences of Eq. (11) and (12), generalized distance transforms), Section 4.2 (sampling)
- Pedro F. Felzenszwalb and Daniel P. Huttenlocher, Distance transforms of sampled functions, Theory of Computing 8, 2012, 415-428, The lower envelope algorithm for the squared Euclidean distance transform of a sampled function in one dimension, and its separable use in two dimensions
- Pedro F. Felzenszwalb, Ross B. Girshick, David McAllester and Deva Ramanan, Object detection with discriminatively trained part-based models, IEEE Transactions on Pattern Analysis and Machine Intelligence 32(9), 2010, 1627-1645, Section 3 (a star-structured pictorial structure on HOG features), Eq. (8) (the distance transform in matching)
Where this leads
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 | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag ZNK7K3 Edit this page History Report an error Markdown