Algorithm Search⌘K

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 nn parts v1,…,vnv_1, \ldots, v_n. A location lil_i of part ii is a point of a discrete set L\mathcal{L} of hh values: a position (x,y)(x, y), and in some models also a scale and an orientation. A configuration is L=(l1,…,ln)L = (l_1, \ldots, l_n).

Appearance. For each part, a match cost mi(l)m_i(l) says how badly the image fits part ii at location ll; 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 G=(V,E)G = (V, E) on the parts has a deformation cost dij(li,lj)d_{ij}(l_i, l_j) for each edge. Felzenszwalb and Huttenlocher use a Mahalanobis distance dij(li,lj)=(Tij(li)−Tji(lj))⊤Mij−1(Tij(li)−Tji(lj))d_{ij}(l_i, l_j) = (T_{ij}(l_i) - T_{ji}(l_j))^\top M_{ij}^{-1} (T_{ij}(l_i) - T_{ji}(l_j)) with a diagonal MijM_{ij}, where the maps TijT_{ij} and TjiT_{ji} take each location to the place of the joint between the two parts. For positions only, with the child jj resting at an offset uu from its parent ii, this is

dij(li,lj)=wx(xj−xi−ux)2+wy(yj−yi−uy)2.d_{ij}(l_i, l_j) = w_x (x_j - x_i - u_x)^2 + w_y (y_j - y_i - u_y)^2.

The energy. The best configuration minimizes

E(L)=∑i=1nmi(li)+∑(vi,vj)∈Edij(li,lj).E(L) = \sum_{i = 1}^{n} m_i(l_i) + \sum_{(v_i, v_j) \in E} d_{ij}(l_i, l_j).

In the statistical form of the model, exp⁡(−mi)\exp(-m_i) is a likelihood for the image near each part and exp⁡(−dij)\exp(-d_{ij}) is a Markov random field prior on the configuration, so the minimum of EE is the maximum a posteriori configuration.

What it counts

The cost of matching is the number of operations to find min⁡LE(L)\min_L E(L) and a configuration that attains it, as a function of nn and hh, in the real RAM. For a tree, the minimum is computed by tree dynamic programming: each part sends to its parent a message Bj(li)B_j(l_i), the best cost of its whole subtree for each location lil_i of the parent. Computing one message by trying every pair of locations costs Θ(h2)\Theta(h^2), so the direct method costs Θ(nh2)\Theta(n h^2). With hh in the hundreds of thousands, for positions, scales and angles, this is too slow, and the quadratic form of dijd_{ij} is what brings it down to O(nh)O(nh). The model also counts the cost of learning: estimating the mim_i, the dijd_{ij} 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 nn. 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 GG and arbitrary costs, minimizing EE is NP-hard, as Felzenszwalb and Huttenlocher (2005) note in Section 4.1; with nn parts the brute-force search tries hnh^n configurations.

Trees in O(nh2)O(nh^2). 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 O(nh2)O(n h^2) time for arbitrary pairwise costs.

Trees with quadratic springs in O(nh)O(nh). When dijd_{ij} is a squared distance after the maps TijT_{ij}, each message is a generalized distance transform Df(x)=min⁡y(ρ(x,y)+f(y))D_f(x) = \min_y \big(\rho(x, y) + f(y)\big) of the function ff that the subtree sends up. The Felzenszwalb distance transform computes it for ρ(x,y)=w(x−y)2\rho(x, y) = w (x - y)^2 in linear time by building the lower envelope of the parabolas w(x−q)2+f(q)w(x - q)^2 + f(q), one for each qq, and the transform is separable over the coordinates. The whole match then costs O(nh)O(nh):

  1. DT1(f, w, u) ▷ D(p) = min over q of f(q) + w (q - p - u)^2
  2. 1k ← 0; v[0] ← 0; z[0] ← -∞; z[1] ← +∞
  3. 2for q ← 1 to N - 1 do
  4. 3s ← ((f(q) + w q^2) - (f(v[k]) + w v[k]^2)) / (2 w (q - v[k]))
  5. 4if s ≤ z[k] then k ← k - 1 and go back to L3
  6. 5k ← k + 1; v[k] ← q; z[k] ← s; z[k + 1] ← +∞
  7. 6k ← 0
  8. 7for p ← 0 to N - 1 do
  9. 8while z[k + 1] < p + u do k ← k + 1
  10. 9D(p) ← w (p + u - v[k])^2 + f(v[k]); A(p) ← v[k]
  11. MATCH(tree, m, springs)
  12. 10for each part j in postorder (children before parents) do
  13. 11f_j ← m_j + the sum of B_c over the children c of j
  14. 12if 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
  15. 13l_root ← a location that minimizes f_root
  16. 14for each part j in preorder, below the root do l_j ← A_j(l_parent(j))
  17. 15return 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 f=(3,0,5,1,4)f = (3, 0, 5, 1, 4) on the positions 0,…,40, \ldots, 4, with w=1w = 1 and u=0u = 0. The transform is D=(1,0,1,1,2)D = (1, 0, 1, 1, 2) with the minimizers (1,1,1,3,3)(1, 1, 1, 3, 3): for p=0p = 0 the best is q=1q = 1 with 0+1=10 + 1 = 1, and for p=4p = 4 it is q=3q = 3 with 1+1=21 + 1 = 2. For a three-part star on six positions in a row, with a torso as the root, the match costs torso (2,1,3,0,2,4)(2, 1, 3, 0, 2, 4), head (1,3,0,2,4,1)(1, 3, 0, 2, 4, 1) resting one position to the right of the torso, and leg (3,2,2,0,1,0)(3, 2, 2, 0, 1, 0) resting one position to the left, all with w=1w = 1, the messages are Bhead=(1,0,1,2,1,2)B_{\mathrm{head}} = (1, 0, 1, 2, 1, 2) and Bleg=(4,3,2,1,0,1)B_{\mathrm{leg}} = (4, 3, 2, 1, 0, 1). The torso total is (7,4,6,3,3,7)(7, 4, 6, 3, 3, 7). The smallest value is 3, first reached at position 3; going back down, the head goes to position 5 (cost 1+11 + 1) and the leg to position 3 (cost 0+10 + 1). The energy is 0+2+1=30 + 2 + 1 = 3, and a search over all 636^3 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 qq, 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 nn parts on a tree with root rr; each part j≠rj \ne r has a parent p(j)p(j). Each part has a match cost mj(l)m_j(l) for every location ll of a set L\mathcal{L} of hh grid cells, and each edge has the spring cost

dj(lp,lj)=wx(xj−xp−ux)2+wy(yj−yp−uy)2,wx,wy>0.d_j(l_{p}, l_j) = w_x (x_j - x_p - u_x)^2 + w_y (y_j - y_p - u_y)^2, \qquad w_x, w_y > 0.

The energy of a configuration L=(l1,…,ln)L = (l_1, \ldots, l_n) is E(L)=∑jmj(lj)+∑j≠rdj(lp(j),lj)E(L) = \sum_j m_j(l_j) + \sum_{j \ne r} d_j(l_{p(j)}, l_j).

Claim. MATCH returns a configuration of minimum energy, and the energy it reports is that minimum. With the distance transform it takes O(nh)O(nh) time.

Lemma 1 (the one-dimensional transform). For f:{0,…,N−1}→Rf : \{0, \ldots, N-1\} \to \mathbb{R}, w>0w > 0 and a real uu, DT1 returns D(p)=min⁡qf(q)+w(q−p−u)2D(p) = \min_q f(q) + w(q - p - u)^2 for every pp, and a minimizing qq.

Proof. For each qq, the function t↦f(q)+w(q−t)2t \mapsto f(q) + w(q - t)^2 is a parabola with the same leading coefficient ww. Two such parabolas, for q<q′q < q', cross at exactly one point

s=(f(q′)+wq′2)−(f(q)+wq2)2w(q′−q),s = \frac{(f(q') + w q'^2) - (f(q) + w q^2)}{2 w (q' - q)},

and the parabola of q′q' is the lower one to the right of ss. 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 q+1q + 1 parabolas from that of the first qq: the new parabola of qq is lowest to the right of its crossing ss with the last piece; if s≤z[k]s \le z[k], the start of the last piece, then the last piece is nowhere lowest any more and line L4 removes it. When the loop stops, s>z[k]s > z[k], the last piece keeps the part [z[k],s][z[k], s], and the new piece covers [s,∞)[s, \infty). This is the invariant that v[0..k]v[0..k] are the indices of the envelope pieces and z[i],z[i+1]z[i], z[i+1] bound piece ii. Lines L6 to L9 then evaluate the envelope at t=p+ut = p + u: since tt grows with pp and the pieces are ordered, the pointer of line L8 moves forward to the piece that contains tt, and line L9 evaluates that parabola, which is the minimum over all qq. □\square

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 k≤Nk \le N times, so DT1 takes O(N)O(N) time.

Lemma 2 (the two-dimensional transform). DT2 returns D(x,y)=min⁡x′,y′f(x′,y′)+wx(x′−x−ux)2+wy(y′−y−uy)2D(x, y) = \min_{x', y'} f(x', y') + w_x (x' - x - u_x)^2 + w_y (y' - y - u_y)^2 and a minimizer, in O(h)O(h) time.

Proof. The cost is a sum of a term in x′x' and a term in y′y', so

D(x,y)=min⁡y′(wy(y′−y−uy)2+min⁡x′(f(x′,y′)+wx(x′−x−ux)2)).D(x, y) = \min_{y'} \Big( w_y (y' - y - u_y)^2 + \min_{x'} \big( f(x', y') + w_x (x' - x - u_x)^2 \big) \Big).

The inner minimum is DT1 along row y′y', and the outer one is DT1 along column xx of the result. The minimizer is the y′y' of the outer transform and the x′x' that the inner transform stored for row y′y' and column xx. Each of the two passes calls DT1 on lines of total length hh. □\square

Lemma 3 (the messages). For a part jj, let TjT_j be the subtree rooted at jj, and define

fj(l)=mj(l)+∑c child of jBc(l),Bc(l)=min⁡l′(fc(l′)+dc(l,l′)).f_j(l) = m_j(l) + \sum_{c \text{ child of } j} B_c(l), \qquad B_c(l) = \min_{l'} \big( f_c(l') + d_c(l, l') \big).

Then fj(l)f_j(l) is the minimum, over all placements of the parts of TjT_j with jj at ll, of the energy restricted to TjT_j (the match costs of its parts and the springs of its edges).

Proof. By induction on the height of TjT_j. For a leaf, fj=mjf_j = m_j. For an inner part with jj fixed at ll, the energy of TjT_j is mj(l)m_j(l) plus, for each child cc, the spring dc(l,lc)d_c(l, l_c) plus the energy of TcT_c. Once ll 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 cc, the minimum over the placements of TcT_c with cc at l′l' is fc(l′)f_c(l') by induction, and the minimum over l′l' of fc(l′)+dc(l,l′)f_c(l') + d_c(l, l') is Bc(l)B_c(l). □\square

Proof of the claim. Line L10 visits the parts in postorder, so the messages of all children of jj exist when line L11 forms fjf_j. Line L12 computes BjB_j with Lemma 2, with the parent location as the query point and the spring of jj, and stores the minimizer Aj(l)A_j(l) for each parent location ll. By Lemma 3 with TrT_r the whole tree, min⁡lfr(l)\min_l f_r(l) is the minimum energy, and line L13 picks a location lrl_r that attains it. Line L14 goes down the tree and sets lc=Ac(lp(c))l_c = A_c(l_{p(c)}). By induction from the root, the placement of each subtree TcT_c that this builds attains fc(lc)f_c(l_c), because Ac(lp(c))A_c(l_{p(c)}) attains the minimum that defines Bc(lp(c))B_c(l_{p(c)}). So the returned configuration has energy fr(lr)f_r(l_r), the minimum.

Cost: each part other than the root costs O(h)O(h) for line L11, counting each child once at its parent, and O(h)O(h) for line L12 by Lemma 2. Lines L13 and L14 cost O(h+n)O(h + n). The total is O(nh)O(nh). With a general cost djd_j instead of a squared distance, line L12 would need O(h2)O(h^2) time for each part. □\square

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.

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

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

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/ZNK7K3/proof-correctness.yaml
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)
WritingW4 complete
  • a review of the text: no review record reviews/ZNK7K3/text.yaml