Algorithm Search⌘K

Algorithmadvanced

Shape context

Also called shape context descriptor.

Describe each point of a shape by the log-polar histogram of the other points around it, then match two shapes by the least-cost assignment of chi-square costs between histograms.

Time
O(n^2 + m^2 + n m K + (n + m)^3) worst · average · best
Space
O((n + m)^2 + (n + m) K) extra
Where
K = the number of bins of a histogram; m = the number of points of the second shape; n = the number of points of the first shape
Properties
deterministicexactnot heuristicnot rotation invariantscale invarianttranslation invariant
Origin
Serge Belongie, Jitendra Malik, Jan Puzicha, 2000

The shape context is a descriptor for a point on a shape, where a shape is a finite set of points, for example points sampled from the edges of an image. For a point pip_i it counts the other points of the shape in bins that are uniform in log distance and in angle around pip_i. The histogram tells where the rest of the shape is, as seen from pip_i, with more detail near pip_i than far away. To match two shapes, the method computes a chi-square cost between each histogram of one shape and each histogram of the other, and finds the one-to-one matching of least total cost with the Hungarian algorithm. Belongie, Malik and Puzicha then aligned the shapes with a thin plate spline and used the matching cost for recognition of digits, objects and trademarks.

In plain words

Stand on one point of a drawing and look around. Draw rings at growing distances, each ring twice as far as the one before or so, and cut the rings into 12 slices like a pie. Count how many points of the drawing fall into each piece. The counts form the description of the point where you stand. A point at the tip of the letter A sees most of the letter below it. A point at the foot sees most of it above and to one side. To compare two drawings, find the pairing of their points that makes the descriptions of paired points most alike in total. If the drawings show the same shape, the pairs are the same parts of the shape.

The problem

The input is two finite point sets P={p1,…,pn}P = \{p_1, \dots, p_n\} and Q={q1,…,qm}Q = \{q_1, \dots, q_m\} in the plane, the numbers of bins nrn_r and nθn_\theta, the radial range [rin,rout)[r_{\mathrm{in}}, r_{\mathrm{out}}) and an optional dummy cost εd\varepsilon_d. Let αP\alpha_P be the mean distance between the n2n^2 ordered pairs of points of PP, as in Section 3.3 of the paper. For pip_i and j≠ij \ne i, let

rij=∥pj−pi∥αP,θij=atan2⁡(yj−yi, xj−xi)∈[0,2π).r_{ij} = \frac{\lVert p_j - p_i \rVert}{\alpha_P}, \qquad \theta_{ij} = \operatorname{atan2}(y_j - y_i,\, x_j - x_i) \in [0, 2\pi).

The radial bin of rr is ⌊nrlog⁡(r/rin)/log⁡(rout/rin)⌋\lfloor n_r \log(r / r_{\mathrm{in}}) / \log(r_{\mathrm{out}} / r_{\mathrm{in}}) \rfloor, and the angle bin of θ\theta is ⌊nθθ/2π⌋\lfloor n_\theta \theta / 2\pi \rfloor. The shape context of pip_i is the histogram hih_i of the bins of the vectors pj−pip_j - p_i with rin≤rij<routr_{\mathrm{in}} \le r_{ij} < r_{\mathrm{out}}, divided by its total. The paper uses nr=5n_r = 5, nθ=12n_\theta = 12 and the range from 0.1250.125 to 22, which gives K=60K = 60 bins and the bin edges 0.125,0.218,0.379,0.660,1.149,20.125, 0.218, 0.379, 0.660, 1.149, 2 in units of the mean distance.

The cost of matching pip_i with qjq_j is the chi-square statistic

Cij=12∑k=1K(hi(k)−hj(k))2hi(k)+hj(k),C_{ij} = \frac{1}{2} \sum_{k=1}^{K} \frac{(h_i(k) - h_j(k))^2}{h_i(k) + h_j(k)},

with 0/00/0 taken as 00. Since hih_i and hjh_j sum to 1, 0≤Cij≤10 \le C_{ij} \le 1. For n=mn = m the output is the permutation π\pi that minimizes ∑iCiπ(i)\sum_i C_{i \pi(i)}, which is the assignment problem. With dummy nodes, each point can stay unmatched at the cost εd\varepsilon_d, and the cost matrix is padded to a square.

The algorithm

  1. SHAPE-CONTEXT-MATCH(P, Q, ε_d)
  2. 1α ← the mean of ‖p_j - p_i‖ over all n^2 ordered pairs of P ▷ the same for Q
  3. 2for each point p_i of P do ▷ the same for Q
  4. 3for each j ≠ i, find the log r bin and the θ bin of (p_j - p_i) / α
  5. 4add 1 to that bin of h_i if r is in [r_in, r_out)
  6. 5divide h_i by its total
  7. 6C_ij ← 1/2 Σ_k (h_i(k) - h_j(k))^2 / (h_i(k) + h_j(k)) for each p_i of P and q_j of Q
  8. 7if n ≠ m or ε_d is given then pad C to a square matrix with dummy rows and columns of cost ε_d
  9. 8π ← the least-cost assignment of C, by the Hungarian method
  10. 9return π, with the points matched to dummies left unmatched, and its cost

Line L8 uses the shortest augmenting path form of the Hungarian method with row and column potentials, which takes O(N3)O(N^3) time for an N×NN \times N matrix. The paper uses the faster algorithm of Jonker and Volgenant, see the Jonker-Volgenant algorithm, which solves the same problem.

With εd\varepsilon_d given, our code pads to (n+m)×(n+m)(n + m) \times (n + m): a real row and a dummy column, or a dummy row and a real column, cost εd\varepsilon_d, and two dummies cost 00. So each unmatched point of either shape costs εd\varepsilon_d, and a point stays unmatched exactly when no real partner is cheaper, as the paper says. Without εd\varepsilon_d and with n≠mn \ne m, the smaller side is padded with the cost 1, which every assignment pays the same number of times.

Alignment and shape distance

In the paper, the matching is one step of a loop. From the matched pairs, the method fits a regularized thin plate spline that maps one shape onto the other, warps the shape, and computes new shape contexts and a new matching, for a few iterations. The shape distance used for recognition is a weighted sum of the shape context cost, an appearance cost and the bending energy of the spline. The page implements the descriptor and the matching; the spline fit is a separate step.

Example

Take the five points (0,0)(0, 0), (1,0)(1, 0), (0,1)(0, 1), (−1,0)(-1, 0) and (0,−1)(0, -1), a plus sign. The 25 ordered pairs have the distances 0 five times, 1 eight times, 2\sqrt 2 eight times and 2 four times, so

α=8+82+825≈1.0925.\alpha = \frac{8 + 8\sqrt 2 + 8}{25} \approx 1.0925 .

From the center, the four points are at r=1/α≈0.915r = 1/\alpha \approx 0.915, which is in the radial bin 3 (counted from 0), between 0.660 and 1.149. Their angles 0, 90, 180 and 270 degrees fall into the angle bins 0, 3, 6 and 9 of 30 degrees each. So the shape context of the center has 1/41/4 in each of the bins (3,0)(3, 0), (3,3)(3, 3), (3,6)(3, 6) and (3,9)(3, 9).

From (1,0)(1, 0), the center is at r=0.915r = 0.915 and angle 180 degrees, bin (3,6)(3, 6). The point (−1,0)(-1, 0) is at r=2/α≈1.831r = 2/\alpha \approx 1.831 and 180 degrees, bin (4,6)(4, 6). The points (0,1)(0, 1) and (0,−1)(0, -1) are at r=2/α≈1.294r = \sqrt 2/\alpha \approx 1.294 and the angles 135 and 225 degrees, bins (4,4)(4, 4) and (4,7)(4, 7). The two histograms share only the bin (3,6)(3, 6), where both hold 1/41/4. Each of the other six bins holds 1/41/4 in one histogram and 0 in the other, and adds (1/4)2/(1/4)=1/4(1/4)^2 / (1/4) = 1/4 to the sum. So C=12⋅64=0.75C = \frac{1}{2} \cdot \frac{6}{4} = 0.75. Two opposite arm ends, (1,0)(1, 0) and (−1,0)(-1, 0), share no bin, and their cost is the largest possible value, 1.

If the second shape is the same plus sign scaled by 0.50.5, moved, and with the points listed in another order, the histograms are the same as before, the cost of the true matching is 0, and the Hungarian method returns that permutation.

Correctness

The proof in proofs/correctness.md shows that:

  • The histograms do not change under a translation and under a scaling by s>0s > 0 of a shape, since the vectors pj−pip_j - p_i do not change under a translation, and both the distances and α\alpha are multiplied by ss.
  • 0≤Cij≤10 \le C_{ij} \le 1, and Cij=0C_{ij} = 0 exactly when the two histograms are equal.
  • The Hungarian method returns an assignment of least total cost, by the duality of the assignment problem.
  • With the padding of line L7, an optimal assignment of the padded matrix gives an optimal partial matching in which each unmatched point costs εd\varepsilon_d.

Whether the least-cost matching pairs the right parts of two different drawings of a shape is not a theorem. It is the measured behavior of the descriptor, reported in Sections 4.2 and 6 of the paper.

Proof: Correctness of shape context matchingfull

Let P={p1,…,pn}P = \{p_1, \dots, p_n\} with n≥2n \ge 2 distinct points, αP=1n2∑i,j∥pj−pi∥>0\alpha_P = \frac{1}{n^2}\sum_{i, j} \lVert p_j - p_i \rVert > 0, and hih_i the normalized log-polar histogram of pip_i as defined on the page. The cost of two histograms aa and bb with nonnegative entries that sum to 1 (or are all 0) is C(a,b)=12∑k(ak−bk)2/(ak+bk)C(a, b) = \frac{1}{2}\sum_k (a_k - b_k)^2 / (a_k + b_k) with 0/0=00/0 = 0.

Lemma 1 (translation and scale). Let P′={spi+t}P' = \{s p_i + t\} with s>0s > 0. Then hi′=hih'_i = h_i for each ii.

Proof. pj′−pi′=s(pj−pi)p'_j - p'_i = s (p_j - p_i), so each distance is multiplied by ss, and so is the mean α\alpha. So rij′=s∥pj−pi∥/(sαP)=rijr'_{ij} = s \lVert p_j - p_i \rVert / (s \alpha_P) = r_{ij}. The direction of s(pj−pi)s (p_j - p_i) is the direction of pj−pip_j - p_i since s>0s > 0, so θij′=θij\theta'_{ij} = \theta_{ij}. Each vector falls into the same bin or is left out in both cases, so the counts and their total are the same, and so are the normalized histograms. □\square

In floating point the lemma holds exactly when ss is a power of 2 and the translation keeps the coordinates exact, as in the tests; otherwise a vector very close to a bin edge can change bins.

Lemma 2 (the cost). 0≤C(a,b)≤10 \le C(a, b) \le 1, and C(a,b)=0C(a, b) = 0 exactly when a=ba = b.

Proof. Each term with ak+bk>0a_k + b_k > 0 is a square divided by a positive number, so it is ≥0\ge 0, and it is 0 exactly when ak=bka_k = b_k. Terms with ak+bk=0a_k + b_k = 0 have ak=bk=0a_k = b_k = 0. So C≥0C \ge 0, with equality exactly when a=ba = b. For ak,bk≥0a_k, b_k \ge 0 we have (ak−bk)2≤(ak+bk)2(a_k - b_k)^2 \le (a_k + b_k)^2, so each term is at most ak+bka_k + b_k, and C≤12∑k(ak+bk)≤12(1+1)=1C \le \frac{1}{2}\sum_k (a_k + b_k) \le \frac{1}{2}(1 + 1) = 1. □\square

Lemma 3 (the Hungarian method is optimal). For an N×NN \times N matrix CC, the procedure of line L8 returns a permutation π\pi with the least ∑iCiπ(i)\sum_i C_{i \pi(i)}.

Proof. The procedure keeps potentials uiu_i and vjv_j with ui+vj≤Ciju_i + v_j \le C_{ij} for all i,ji, j (dual feasibility) and a partial matching that uses only tight pairs, those with ui+vj=Ciju_i + v_j = C_{ij}. It adds the rows one at a time. For a new row it grows a tree of alternating paths over tight pairs; when no tight pair leaves the tree, it changes the potentials by the smallest slack δ\delta of a pair from a row in the tree to a column outside it. Adding δ\delta to uu on the rows of the tree and subtracting it from vv on the columns of the tree keeps every pair of the tree and of the matching tight, keeps dual feasibility by the choice of δ\delta, and makes at least one new pair tight. So after at most NN such changes the tree reaches a free column, and the matching grows by one along the path. After NN rows, π\pi is a perfect matching of tight pairs, so ∑iCiπ(i)=∑iui+∑jvj\sum_i C_{i\pi(i)} = \sum_i u_i + \sum_j v_j. For any permutation σ\sigma, dual feasibility gives ∑iCiσ(i)≥∑i(ui+vσ(i))=∑iui+∑jvj\sum_i C_{i\sigma(i)} \ge \sum_i (u_i + v_{\sigma(i)}) = \sum_i u_i + \sum_j v_j. So π\pi is optimal. This is the argument of Kuhn (1955), in the form with shortest augmenting paths. □\square

Lemma 4 (dummies). Let CC be n×mn \times m and ε≥0\varepsilon \ge 0. Pad it to (n+m)×(n+m)(n + m) \times (n + m) with the cost ε\varepsilon between a real row and a dummy column or a dummy row and a real column, and 0 between two dummies. Then the least cost of the padded assignment equals the least cost, over all partial matchings MM of rows to columns, of ∑(i,j)∈MCij+ε(n+m−2∣M∣)\sum_{(i, j) \in M} C_{ij} + \varepsilon (n + m - 2|M|).

Proof. Take an assignment of the padded matrix, and let MM be its pairs of a real row and a real column. The other n−∣M∣n - |M| real rows go to dummy columns, and the other m−∣M∣m - |M| real columns get dummy rows, each at the cost ε\varepsilon. The remaining dummy rows go to dummy columns at the cost 0. So the cost of the assignment is the cost of MM in the formula. Conversely, given a partial matching MM, assign the unmatched real rows to distinct dummy columns, the unmatched real columns to distinct dummy rows, and the remaining ∣M∣|M| dummy rows to the remaining ∣M∣|M| dummy columns. There are nn dummy rows and mm dummy columns, so this is possible, and the cost is the cost of MM in the formula. So the two minima are equal, and an optimal padded assignment gives an optimal partial matching. □\square

Theorem. SHAPE-CONTEXT-MATCH returns a matching of least total chi-square cost between the shape contexts of PP and QQ, with each point matched to a dummy costing εd\varepsilon_d when dummies are used. The result does not change under a translation or a scaling by s>0s > 0 of either shape, and if QQ is a translated and scaled copy of PP with its points permuted by σ\sigma, the matching σ\sigma has cost 0 and is optimal.

Proof. Lines L1 to L5 compute the histograms of the definition, and line L6 the costs. By Lemma 3 line L8 returns an optimal assignment of the matrix, and by Lemma 4 it is an optimal partial matching when dummies are used. By Lemma 1 the histograms, and so the costs and the matching, do not change under translation and scaling. If QQ is such a copy, Lemma 1 gives hσ(i)Q=hiPh^Q_{\sigma(i)} = h^P_i, so by Lemma 2 the matching σ\sigma has cost 0, which is the least possible cost since all costs are ≥0\ge 0. □\square

Complexity

The model is the real RAM, with log⁡\log and atan2⁡\operatorname{atan2} in O(1)O(1) time. Let K=nrnθK = n_r n_\theta.

  • Line L1 takes O(n2)O(n^2) time for PP and O(m2)O(m^2) for QQ.
  • Lines L2 to L5 take O(n2+nK)O(n^2 + n K) time for PP and O(m2+mK)O(m^2 + m K) for QQ.
  • Line L6 takes O(nmK)O(n m K) time.
  • Line L8 takes O(N3)O(N^3) time with N=max⁡(n,m)N = \max(n, m), or N=n+mN = n + m with dummies.

So the total time is O(n2+m2+nmK+(n+m)3)O(n^2 + m^2 + n m K + (n + m)^3), and the assignment dominates for KK fixed. The extra space is O((n+m)2)O((n + m)^2) for the cost matrix and O((n+m)K)O((n + m) K) for the histograms. The paper samples about 100 points per shape. It reports that one comparison with three iterations of matching and spline fitting took about 200 ms on a 500 MHz Pentium III; this is a measurement from 2002, not a bound.

Properties

  • Translation and scale invariance. Exact, by the normalization with the mean distance.
  • Rotation. Not invariant in the plain form. The relative frame of Section 3.3 measures angles from the tangent at each point and gives full rotation invariance, which the paper notes is wrong for tasks such as telling 6 from 9.
  • Locality and global context. Each histogram covers the whole shape out to twice the mean distance, so it is a rich descriptor, but it is sensitive to occlusion of large parts.
  • Log-polar bins. The bins are finer near the point. The paper explains this as a positional uncertainty that grows linearly with the distance.
  • Outliers. Dummy nodes let outliers stay unmatched. Outliers still change the histograms of the other points and the mean distance.
  • The sampling. The points are samples of the shape, not special points. Different samplings of the same contour give similar, not equal, histograms.

Variants and improvements

  • Tangent frame. Measure angles relative to the tangent at each point for rotation invariance.
  • Appearance and tangent terms. For MNIST the paper adds a tangent angle term with weight 0.1 to the cost.
  • Inner-distance shape context. Ling and Jacobs replace the Euclidean distance by the shortest path inside the shape, which helps with articulated shapes.
  • 3D shape context. Frome and coauthors use spherical bins on range data.
  • Fast pruning. For retrieval in large sets, later work of Mori, Belongie and Malik prunes candidates by comparing a few representative shape contexts before the full matching.
  • Other matchings. The Jonker-Volgenant algorithm solves the same assignment faster in practice. A greedy matching is cheaper but not optimal.
  • Related distances. The chamfer distance compares shapes without correspondences, and the generalized Hough transform votes for a pose.

When to use it

Use shape contexts to match and compare silhouettes, contours, handwritten characters and logos, where the shape carries more information than the texture. They are a good choice when you need point correspondences between two shapes, for example to start a non-rigid registration. The cubic cost of the assignment limits the number of points to a few hundred. For keypoint matching between photographs, a descriptor of the image patch is a better choice.

Pitfalls

  • The mean distance. The paper divides by the mean over the n2n^2 pairs, which includes the nn zero distances. Some codes take the mean over pairs with i≠ji \ne j, which is larger by the factor n/(n−1)n / (n - 1). The bins then shift. Use the same rule on both shapes.
  • Points outside the range. Points nearer than rinr_{\mathrm{in}} or farther than routr_{\mathrm{out}} are not counted in our code. Some codes put them into the first or the last bin. The histograms of a shape with many close points can then be quite different.
  • Image coordinates. With vv pointing down, the angle goes clockwise on the screen. This does not matter if both shapes use the same rule.
  • Empty histograms. A point with no other point in range has an empty histogram. The chi-square cost against another empty histogram is 0.
  • Ties in the assignment. Symmetric shapes, such as the plus sign, have several matchings of equal cost. Any of them is optimal.
  • The dummy cost. If εd\varepsilon_d is too small, all points go to dummies. If εd>1/2\varepsilon_d > 1/2, an optimal solution never leaves a point of each shape unmatched, because matching the two costs at most 1 and leaving both costs 2εd2\varepsilon_d. Then the dummies only take the extra points of the larger shape.

Implementations

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.

shape_context.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shape-context/. The authors are listed in prov/A629T3.jsonl.

"""Shape context descriptors and shape matching by assignment.

Points are (x, y) pairs. For a point p_i, the shape context is the histogram
of the vectors p_j - p_i, j != i, in log-polar bins. Distances are divided by
the mean distance over all n^2 ordered pairs (Belongie, Malik and Puzicha 2002,
Section 3.3), and the radial bins are uniform in log r over [1/8, 2), as in
Appendix A of the paper. Vectors outside that range are not counted. The angle
is atan2(dy, dx) in [0, 2 pi), cut into equal bins. Each histogram is divided
by its total so that it sums to 1 (it stays 0 if no vector falls in a bin).

The cost of matching p_i with q_j is the chi-square statistic
C_ij = 1/2 sum_k (h_i(k) - h_j(k))^2 / (h_i(k) + h_j(k)), with 0/0 taken as 0.
The matching is the assignment of least total cost, found by the Hungarian
method in O(N^3) time. Dummy rows or columns with the constant cost eps_d make
the matrix square and let outliers stay unmatched.
"""

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

Point = Tuple[float, float]


def mean_distance(points: Sequence[Point]) -> float:
    """Mean distance over all n^2 ordered pairs, including i = j."""
    n = len(points)
    total = 0.0
    for a in points:
        for b in points:
            total += math.hypot(b[0] - a[0], b[1] - a[1])
    return total / (n * n)


def shape_contexts(points: Sequence[Point], n_r: int = 5, n_theta: int = 12,
                   r_inner: float = 0.125, r_outer: float = 2.0) -> List[List[float]]:
    """Normalized log-polar histograms, one for each point, with n_r * n_theta bins."""
    n = len(points)
    alpha = mean_distance(points)  # @line L1
    log_in = math.log(r_inner)
    log_span = math.log(r_outer) - log_in
    out = []
    for i in range(n):  # @line L2
        h = [0.0] * (n_r * n_theta)
        xi, yi = points[i]
        for j in range(n):
            if j == i:
                continue
            dx, dy = points[j][0] - xi, points[j][1] - yi
            r = math.hypot(dx, dy) / alpha
            if r < r_inner or r >= r_outer:
                continue
            kr = int(n_r * (math.log(r) - log_in) / log_span)  # @line L3
            kr = min(kr, n_r - 1)
            t = math.atan2(dy, dx) % (2.0 * math.pi)
            kt = min(int(n_theta * t / (2.0 * math.pi)), n_theta - 1)
            h[kr * n_theta + kt] += 1.0  # @line L4
        s = sum(h)
        if s > 0:
            h = [x / s for x in h]  # @line L5
        out.append(h)
    return out


def chi2_cost(h1: Sequence[float], h2: Sequence[float]) -> float:
    """The chi-square cost 1/2 sum (a - b)^2 / (a + b), with 0/0 = 0."""
    c = 0.0
    for a, b in zip(h1, h2):
        if a + b > 0:
            c += (a - b) * (a - b) / (a + b)
    return 0.5 * c


def hungarian(cost: Sequence[Sequence[float]]) -> List[int]:
    """Least-cost assignment of a square matrix: row i goes to column result[i].

    The shortest augmenting path form of the Hungarian method with row and
    column potentials, O(n^3) time.
    """
    n = len(cost)
    inf = float("inf")
    u = [0.0] * (n + 1)
    v = [0.0] * (n + 1)
    p = [0] * (n + 1)  # p[j]: the row matched to column j (1-based), 0 if none
    way = [0] * (n + 1)
    for i in range(1, n + 1):
        p[0] = i
        j0 = 0
        minv = [inf] * (n + 1)
        used = [False] * (n + 1)
        while True:
            used[j0] = True
            i0 = p[j0]
            delta = inf
            j1 = 0
            for j in range(1, n + 1):
                if not used[j]:
                    cur = cost[i0 - 1][j - 1] - u[i0] - v[j]
                    if cur < minv[j]:
                        minv[j] = cur
                        way[j] = j0
                    if minv[j] < delta:
                        delta = minv[j]
                        j1 = j
            for j in range(n + 1):
                if used[j]:
                    u[p[j]] += delta
                    v[j] -= delta
                else:
                    minv[j] -= delta
            j0 = j1
            if p[j0] == 0:
                break
        while True:
            j1 = way[j0]
            p[j0] = p[j1]
            j0 = j1
            if j0 == 0:
                break
    result = [0] * n
    for j in range(1, n + 1):
        result[p[j] - 1] = j - 1
    return result


def match_shapes(p: Sequence[Point], q: Sequence[Point], eps_d: Optional[float] = None,
                 **kw) -> Tuple[List[int], float]:
    """Match the points of p to the points of q.

    Returns (m, total): m[i] is the index in q matched to p[i], or -1 when p[i]
    goes to a dummy, and total is the cost of the real pairs plus eps_d for each
    point of the larger set (or both) that goes to a dummy.
    """
    hp = shape_contexts(p, **kw)
    hq = shape_contexts(q, **kw)
    m = len(q)
    c = [[chi2_cost(a, b) for b in hq] for a in hp]  # @line L6
    return assign_with_dummies(c, m, eps_d)


def pad_with_dummies(c: Sequence[Sequence[float]], m: int, eps_d: Optional[float]) -> List[List[float]]:
    """Make the n x m cost matrix square with dummy rows and columns.

    With eps_d given, the result is (n + m) x (n + m): each real point can go
    to a dummy at the cost eps_d, and a dummy pair costs 0. Without eps_d, the
    smaller side is padded to max(n, m) with the cost 1, the largest possible
    chi-square cost, which is then the same for every assignment.
    """
    n = len(c)
    if eps_d is None and n == m:
        return [list(row) for row in c]
    eps = 1.0 if eps_d is None else eps_d
    size = n + m if eps_d is not None else max(n, m)
    full = [[0.0] * size for _ in range(size)]
    for i in range(size):
        for j in range(size):
            if i < n and j < m:
                full[i][j] = c[i][j]
            elif i < n or j < m:
                full[i][j] = eps
    return full


def assign_with_dummies(c: Sequence[Sequence[float]], m: int, eps_d: Optional[float] = None) -> Tuple[List[int], float]:
    """Least-cost matching of rows to the m columns of c, with dummies; -1 means a dummy."""
    n = len(c)
    full = pad_with_dummies(c, m, eps_d)  # @line L7
    assign = hungarian(full)  # @line L8
    total = sum(full[i][assign[i]] for i in range(len(full)))
    out = [assign[i] if assign[i] < m else -1 for i in range(n)]
    return out, total  # @line L9
test_shape_context.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shape-context/. The authors are listed in prov/A629T3.jsonl.

import itertools
import math
import random

from shape_context import assign_with_dummies, chi2_cost, hungarian, match_shapes, mean_distance, shape_contexts


def brute_assignment(cost):
    n = len(cost)
    best = None
    for perm in itertools.permutations(range(n)):
        s = sum(cost[i][perm[i]] for i in range(n))
        if best is None or s < best:
            best = s
    return best


def random_shape(rng, n):
    pts = set()
    while len(pts) < n:
        pts.add((rng.randint(-20, 20), rng.randint(-20, 20)))
    return sorted(pts)


def test_hungarian_matches_brute_force():
    rng = random.Random(1)
    for n in range(1, 8):
        for _ in range(12):
            cost = [[rng.randint(0, 30) for _ in range(n)] for _ in range(n)]
            a = hungarian(cost)
            assert sorted(a) == list(range(n))
            assert sum(cost[i][a[i]] for i in range(n)) == brute_assignment(cost)


def test_hungarian_with_float_costs():
    rng = random.Random(2)
    for n in (5, 6):
        cost = [[rng.random() for _ in range(n)] for _ in range(n)]
        a = hungarian(cost)
        assert abs(sum(cost[i][a[i]] for i in range(n)) - brute_assignment(cost)) < 1e-12


def test_mean_distance_by_hand():
    pts = [(0, 0), (3, 4)]
    # Ordered pairs: 0, 5, 5, 0, so the mean over n^2 = 4 pairs is 2.5.
    assert mean_distance(pts) == 2.5


def test_histograms_sum_to_one_and_count_by_hand():
    pts = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (-1.0, 0.0), (0.0, -1.0)]
    h = shape_contexts(pts)
    assert all(abs(sum(x) - 1.0) < 1e-12 for x in h)
    # The mean distance is (8 * 1 + 4 * (2 + 2 * sqrt(2))) / 25.
    alpha = (8 + 4 * (2 + 2 * math.sqrt(2))) / 25
    assert abs(mean_distance(pts) - alpha) < 1e-12
    # From the center, the four points are at r = 1 / alpha, angles 0, 90, 180 and 270 degrees.
    r = 1 / alpha
    kr = int(5 * (math.log(r) - math.log(0.125)) / math.log(16))
    expected = [0.0] * 60
    for kt in (0, 3, 6, 9):
        expected[kr * 12 + kt] = 0.25
    assert h[0] == expected


def test_chi2_cost_properties():
    a = [0.5, 0.5, 0.0]
    b = [0.0, 0.5, 0.5]
    assert chi2_cost(a, a) == 0.0
    assert abs(chi2_cost(a, b) - 0.5) < 1e-12
    assert abs(chi2_cost([1.0, 0.0], [0.0, 1.0]) - 1.0) < 1e-12


def test_translation_and_scale_do_not_change_the_descriptors():
    rng = random.Random(3)
    pts = random_shape(rng, 20)
    h = shape_contexts(pts)
    moved = [(4 * x + 17, 4 * y - 9) for x, y in pts]
    h2 = shape_contexts(moved)
    for a, b in zip(h, h2):
        assert max(abs(x - y) for x, y in zip(a, b)) < 1e-12


def test_permuted_scaled_copy_is_matched_exactly():
    rng = random.Random(4)
    pts = random_shape(rng, 18)
    perm = list(range(18))
    rng.shuffle(perm)
    q = [None] * 18
    for i, j in enumerate(perm):
        x, y = pts[i]
        q[j] = (0.5 * x + 3.0, 0.5 * y + 1.0)
    m, total = match_shapes(pts, q)
    assert m == perm
    assert total < 1e-12


def test_noisy_copy_is_mostly_matched():
    rng = random.Random(5)
    pts = [(10 * math.cos(2 * math.pi * k / 24), 6 * math.sin(2 * math.pi * k / 24)) for k in range(24)]
    pts += [(-3.0 + k, 0.0) for k in range(7)]
    q = [(x + rng.gauss(0, 0.15), y + rng.gauss(0, 0.15)) for x, y in pts]
    m, _ = match_shapes(pts, q)
    right = sum(1 for i, j in enumerate(m) if i == j)
    assert right >= 24


def brute_partial(cost, m, eps):
    """Best partial matching: each unmatched row or column costs eps."""
    n = len(cost)
    best = None
    for k in range(min(n, m) + 1):
        for rows in itertools.combinations(range(n), k):
            for cols in itertools.permutations(range(m), k):
                s = sum(cost[r][c] for r, c in zip(rows, cols)) + eps * (n - k + m - k)
                if best is None or s < best:
                    best = s
    return best


def test_dummies_match_brute_force_partial_matching():
    rng = random.Random(6)
    for n, m in ((3, 3), (4, 2), (2, 5), (4, 4)):
        for _ in range(6):
            cost = [[rng.random() for _ in range(m)] for _ in range(n)]
            eps = rng.choice([0.1, 0.3, 0.5])
            out, total = assign_with_dummies(cost, m, eps)
            assert abs(total - brute_partial(cost, m, eps)) < 1e-12
            used = [j for j in out if j >= 0]
            assert len(used) == len(set(used))


def test_outlier_row_goes_to_a_dummy():
    cost = [[0.05, 0.9, 0.9], [0.9, 0.1, 0.9], [0.95, 0.9, 0.97]]
    out, total = assign_with_dummies(cost, 3, eps_d=0.4)
    assert out == [0, 1, -1]
    assert abs(total - (0.05 + 0.1 + 0.4 + 0.4)) < 1e-12
    out2, _ = assign_with_dummies([[0.2, 0.5], [0.4, 0.1], [0.3, 0.3]], 2)
    assert out2 == [0, 1, -1]

History

Belongie, Malik and Puzicha introduced shape contexts in a 2000 conference paper and gave the full method in IEEE TPAMI in 2002. They used about 100 points sampled from Canny edges, the Jonker-Volgenant assignment algorithm and regularized thin plate splines. On MNIST, with 20,000 training digits and a 3-nearest-neighbor classifier, they reported a test error of 0.63 percent, a benchmark result of 2002. Shape contexts were also used for trademark retrieval and for 3D object recognition from views.

References

  1. Serge Belongie, Jitendra Malik and Jan Puzicha, Shape matching and object recognition using shape contexts, IEEE Transactions on Pattern Analysis and Machine Intelligence 24(4), 509-522, 2002, Section 3.1 (the log-polar histogram, 5 bins for log r and 12 for the angle, the chi-square cost), Section 3.2 (bipartite matching in O(N^3), dummy nodes), Section 3.3 (normalization by the mean distance, the tangent frame), Section 4 (modeling transformations, regularized thin plate splines), Section 4.3 (computational demands), Section 6.1 (MNIST), Appendix A (the radial range 0.125 to 2)
  2. Harold W. Kuhn, The Hungarian method for the assignment problem, Naval Research Logistics Quarterly 2(1-2), 83-97, 1955, the whole paper (the assignment algorithm)

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