Algorithm Search⌘K

Algorithmcore

Generalized Hough transform

Also called Ballard generalized Hough transform, R-table voting.

Detect an arbitrary shape by having each edge point vote, through a table indexed by gradient direction, for the positions of the shape reference point.

Time
O(e m + W H) worstO(e k + W H) best
Space
O(W H + m) extra
Where
H = the image height; W = the image width; e = the number of image edge points; k = the largest number of R-table entries in one direction bin; m = the number of template edge points
Properties
deterministicexact
Origin
Dana H. Ballard, 1981

The generalized Hough transform finds a shape of any form in an image. It does not need a formula for the shape. It needs only one example, the template. Each edge point of the template has a gradient direction and an offset to a fixed reference point. The R-table stores these offsets, sorted by gradient direction. In a new image, each edge point looks up its gradient direction in the R-table and votes for all the reference positions that the table allows. A copy of the shape makes many votes agree on one cell, and that cell gives its position. This page builds on the Hough transform for lines and covers only what the generalization adds.

In plain words

Draw the outline of a shape and mark one point inside it, the center. For each point of the outline, note in which direction the outline faces there and where the center is from that point. Keep these notes in a book, with one page for each direction.

To find the shape in a picture, take each outline point of the picture. Look at the page for its direction. For each note on that page, put a mark where the center would be. Where the shape really is, many marks fall on the same spot. Other outline points scatter their marks. The spot with the most marks is the answer.

The problem

Input. A template image TT and a reference point cc in it, and an image II of width WW and height HH, both as arrays img[v][u]\mathrm{img}[v][u] with uu the column and vv the row. A threshold τ>0\tau > 0 on the gradient magnitude and a number BB of direction bins (here B=8B = 8).

Edge points. The gradient (gu,gv)(g_u, g_v) at a pixel comes from the Sobel operator, and it is 0 on the border of the image. A pixel yy is an edge point if gu2+gv2≥τ2g_u^2 + g_v^2 \ge \tau^2 and the gradient is not zero. Its bin is b(y)=⌊φ/(2π/B)+1/2⌋ mod Bb(y) = \lfloor \varphi / (2\pi / B) + 1/2 \rfloor \bmod B with φ=atan2(gv,gu)\varphi = \mathrm{atan2}(g_v, g_u), so the bins are centered at the multiples of 2π/B2\pi / B. The template gives mm edge points (xi,bi)(x_i, b_i) and the image gives ee edge points (yj,bj)(y_j, b_j).

Output. The accumulator AA on the pixel grid,

A[p]=#{(i,j):bi=bj and yj+(c−xi)=p},A[p] = \#\{(i, j) : b_i = b_j \text{ and } y_j + (c - x_i) = p\},

the number of pairs of a template edge point and an image edge point with the same bin that put the reference point at pp. Also the cell with the largest count, with ties to the smallest vv, then the smallest uu.

The algorithm

  1. GHT(template edges, c, image edges) ▷ R[0..B-1] are empty lists
  2. 1for each template edge point (x, b) do
  3. 2append the offset c - x to R[b]
  4. 3A ← 0 on the W by H grid
  5. 4for each image edge point (y, b) do
  6. 5for each offset r in R[b] do
  7. 6p ← y + r
  8. 7if p is inside the grid then A[p] ← A[p] + 1
  9. 8return the cell p with the largest A[p], and A

Lines L1 and L2 build the R-table once for each template. Lines L3 to L7 are the voting. Line L8 takes the peak. A real detector takes all the local maxima above a vote threshold, after non-maximum suppression, to find several copies.

Rotation and scale. Ballard extends the accumulator to four parameters (p,θ,s)(p, \theta, s). For a rotation θ\theta and a scale ss, the shape edge point that now has bin bb had bin b−θb - \theta in the template, so line L5 reads R[(b−k) mod B]R[(b - k) \bmod B] for a rotation of kk bins, and line L6 becomes p←y+s rotθ(r)p \leftarrow y + s\, \mathrm{rot}_\theta(r). The code does this in vote_rotations, with one accumulator for each pair (k,s)(k, s). It is exact for rotations by multiples of 90 degrees. For other angles, the rounding of the offsets and the width of the bins spread the votes.

Example

The template is a 7×77 \times 7 image with a 3×33 \times 3 square of value 1 at u,v∈{2,3,4}u, v \in \{2, 3, 4\}, and c=(3,3)c = (3, 3), the center of the square. With τ=1\tau = 1, every pixel of the 5×55 \times 5 block around the square has a nonzero gradient, except the center, so m=24m = 24. The gradient points to the square. The counts in the bins 0 to 7 are 4, 2, 4, 2, 4, 2, 4, 2: the sides give the bins of the axis directions, and the corners give the diagonal bins. Bin 2 (gradient down) holds the points (2,1)(2, 1), (3,1)(3, 1), (4,1)(4, 1) and (3,2)(3, 2) above the square, so

R[2]={(1,2),(0,2),(−1,2),(0,1)}.R[2] = \{(1, 2), (0, 2), (-1, 2), (0, 1)\}.

Paste the template into a blank image of 12×1012 \times 10 pixels with its top left pixel at t=(4,2)t = (4, 2). The point (3,2)(3, 2) of the template is now at (7,4)(7, 4), with bin 2. It votes at (8,6)(8, 6), (7,6)(7, 6), (6,6)(6, 6) and (7,5)(7, 5). Only the last one is the true center c+t=(7,5)c + t = (7, 5). The 24 edge points of the copy all vote at (7,5)(7, 5), so the peak is A[(7,5)]=24=mA[(7, 5)] = 24 = m. The second largest count in AA is 6, at cells next to the peak. The tests check these numbers.

Correctness

The proof in the correctness file shows three facts.

Theorem 1 (the votes count matching pairs). Lines L1 to L7 compute exactly the AA of the problem statement: each pair of a template edge point and an image edge point with the same bin adds one vote, at y+c−xy + c - x, if that cell is inside the grid.

Theorem 2 (a translated copy gives a peak of at least mm). If the image edge points include (xi+t,bi)(x_i + t, b_i) for all mm template edge points and c+tc + t is inside the grid, then A[c+t]≥mA[c + t] \ge m. If the image edge points are exactly these mm points, then A[c+t]=mA[c + t] = m. This holds when the image is the template moved by tt on a blank background and the template has a blank border of 2 pixels, since the Sobel gradient of a pixel depends only on its 3×33 \times 3 neighborhood.

Theorem 3 (rotation by 90 degrees). Rotating the image by 90 degrees rotates the Sobel gradient by 90 degrees and moves each bin by B/4B/4. So the rotated copy gives AB/4[c′]≥mA_{B/4}[c' ] \ge m in the accumulator for the rotation of B/4B/4 bins, where c′c' is the rotated reference point.

What is not claimed: the peak at c+tc + t is not always the largest cell. Clutter can put more votes on another cell, and the bins make some wrong pairs agree. That the peak wins in practice is a heuristic, supported by experiments.

Proof: The R-table votes count matching edge pairs, and a translated or 90 degree rotated copy of the template gets at least m votes at its reference pointfull

We use the notation of the page. The template edge points are (xi,bi)(x_i, b_i) for i=1,…,mi = 1, \ldots, m, the image edge points are (yj,bj)(y_j, b_j) for j=1,…,ej = 1, \ldots, e, the reference point is cc, and GG is the set of grid cells of the image. All points are integer pairs (u,v)(u, v).

Theorem 1 (the votes count matching pairs). After lines L1 to L7, for every p∈Gp \in G,

A[p]=#{(i,j):bi=bj, yj+c−xi=p}.A[p] = \#\{(i, j) : b_i = b_j,\ y_j + c - x_i = p\}.

Proof. After lines L1 and L2, R[b]R[b] is the list of the offsets c−xic - x_i over the indices ii with bi=bb_i = b, one entry for each such ii (two template points give two entries even if the offsets are equal, since the points differ, and in fact the offsets differ too). Line L3 sets A=0A = 0. Lines L4 and L5 visit each pair (j,i)(j, i) with bi=bjb_i = b_j exactly once. For such a pair, line L6 computes p=yj+c−xip = y_j + c - x_i, and line L7 adds 1 to A[p]A[p] if p∈Gp \in G and does nothing otherwise. No other line changes AA. So A[p]A[p] is the number of pairs with bi=bjb_i = b_j and yj+c−xi=py_j + c - x_i = p, for every p∈Gp \in G. □\square

Theorem 2 (translated copy). Let tt be an integer vector. Suppose that for each ii, (xi+t,bi)(x_i + t, b_i) is an image edge point, and that c+t∈Gc + t \in G. Then A[c+t]≥mA[c + t] \ge m. If, in addition, the image edge points are exactly (xi+t,bi)(x_i + t, b_i) for i=1,…,mi = 1, \ldots, m, then A[c+t]=mA[c + t] = m.

Proof. For each ii, let j(i)j(i) be the index of the image edge point xi+tx_i + t. Then bj(i)=bib_{j(i)} = b_i and yj(i)+c−xi=c+ty_{j(i)} + c - x_i = c + t, so the pair (i,j(i))(i, j(i)) is counted in A[c+t]A[c + t] by Theorem 1. The mm pairs are distinct since their first indices are distinct. So A[c+t]≥mA[c + t] \ge m.

For the equality, every image edge point is yj=xi′+ty_j = x_{i'} + t with bj=bi′b_j = b_{i'} for one i′i'. A pair (i,j)(i, j) is counted in A[c+t]A[c + t] if and only if bi=bjb_i = b_j and xi′+t+c−xi=c+tx_{i'} + t + c - x_i = c + t, that is, xi=xi′x_i = x_{i'}, that is, i=i′i = i', since distinct template edge points are distinct pixels. So for each jj exactly one pair is counted, and A[c+t]=e=mA[c + t] = e = m. □\square

Lemma 1 (when the image edges are the translated template edges). Suppose the template TT of size Wt×HtW_t \times H_t is 0 on its two outer rows and columns on each side, the image II satisfies I[v+tv][u+tu]=T[v][u]I[v + t_v][u + t_u] = T[v][u] for all template pixels, II is 0 at all other pixels, and the copy satisfies tu≥1t_u \ge 1, tv≥1t_v \ge 1, tu+Wt≤W−1t_u + W_t \le W - 1 and tv+Ht≤H−1t_v + H_t \le H - 1. Then the image edge points are exactly (xi+t,bi)(x_i + t, b_i).

Proof. The Sobel gradient at a pixel that is not on the border of its array depends only on the 3×33 \times 3 neighborhood of the pixel. Take a pixel zz of the image and consider three cases. (a) z=x+tz = x + t for a template pixel xx that is not on the border of TT: its neighborhood in II is the translate of its neighborhood in TT, and zz is not on the border of II by the conditions on tt, so the gradients are equal and zz is an edge point with bin bb if and only if xx is one with bin bb. (b) z=x+tz = x + t for xx on the border of TT: the gradient of xx in TT is 0 by convention. The neighborhood of zz in II consists of pixels of the two outer rings of the copy and pixels outside the copy, all 0, so the gradient of zz is 0. (c) zz is not in the copy: its neighborhood consists of pixels outside the copy and pixels of the outer ring of the copy, all 0, or zz is on the border of II. In both cases the gradient is 0. So the edge points of II are exactly the translates of the edge points of TT, with the same bins. □\square

Lemma 1 with Theorem 2 gives A[c+t]=mA[c + t] = m for a clean copy, which is the example of the page and the first test.

Theorem 3 (rotation by 90 degrees). Let ρ(u,v)=(−v,u)\rho(u, v) = (-v, u), the rotation by 90 degrees in the (u,v)(u, v) frame, and let BB be a multiple of 4. Suppose that each template edge point (xi,bi)(x_i, b_i) appears in the image as the edge point (ρ(xi)+t,(bi+B/4) mod B)(\rho(x_i) + t, (b_i + B/4) \bmod B), and that c′=ρ(c)+t∈Gc' = \rho(c) + t \in G. Let A′A' be the accumulator of lines L3 to L7 when line L5 reads R[(b−B/4) mod B]R[(b - B/4) \bmod B] and line L6 uses p←y+ρ(r)p \leftarrow y + \rho(r). Then A′[c′]≥mA'[c'] \ge m.

Proof. The image edge point y=ρ(xi)+ty = \rho(x_i) + t has bin b=bi+B/4(modB)b = b_i + B/4 \pmod B, so it reads R[bi]R[b_i], which holds c−xic - x_i. Since ρ\rho is linear, it votes at ρ(xi)+t+ρ(c−xi)=ρ(c)+t=c′\rho(x_i) + t + \rho(c - x_i) = \rho(c) + t = c'. The mm template points give mm distinct pairs, as in Theorem 2. □\square

Lemma 2 (the hypothesis of Theorem 3 holds for a rotated image). Let I′I' be the image II rotated by 90 degrees, I′[u][H−1−v]=I[v][u]I'[u][H - 1 - v] = I[v][u], so that the pixel (u,v)(u, v) moves to (H−1−v,u)=ρ(u,v)+(H−1,0)(H - 1 - v, u) = \rho(u, v) + (H - 1, 0). If (gu,gv)(g_u, g_v) is the Sobel gradient of II at an interior pixel zz, then the Sobel gradient of I′I' at the image of zz is (−gv,gu)=ρ(gu,gv)(-g_v, g_u) = \rho(g_u, g_v), and its bin is the bin of zz plus B/4B/4 modulo BB.

Proof. Write I′(w)=I(ρ−1(w−s))I'(w) = I(\rho^{-1}(w - s)) with s=(H−1,0)s = (H - 1, 0). The Sobel operator is a finite difference along an axis with smoothing (1,2,1)(1, 2, 1) across it. Let w=ρ(z)+sw = \rho(z) + s. A unit step along +u+u at ww corresponds to the step ρ−1(1,0)=(0,−1)\rho^{-1}(1, 0) = (0, -1) at zz, and a step along +v+v at ww corresponds to ρ−1(0,1)=(1,0)\rho^{-1}(0, 1) = (1, 0) at zz. So gu′(w)g'_u(w) is the Sobel difference of II at zz along −v-v, which is −gv(z)-g_v(z), and gv′(w)g'_v(w) is the Sobel difference along +u+u, which is gu(z)g_u(z); the smoothing weights are symmetric, so they match. The magnitude is unchanged, so ww is an edge point if and only if zz is one. The angle grows by π/2\pi/2, so φ′/(2π/B)=φ/(2π/B)+B/4\varphi' / (2\pi / B) = \varphi / (2\pi / B) + B/4 modulo BB, and since B/4B/4 is an integer, the floor of the value plus 1/21/2 grows by exactly B/4B/4. □\square

With Lemma 1 applied to the rotated template (it also has a blank border of 2 pixels), Lemma 2 and Theorem 3 give the rotation test: in the accumulator for the shift of B/4B/4 bins, the rotated reference point gets mm votes. The code rounds cos⁡\cos and sin⁡\sin of π/2\pi/2 to 0 and 1, so its rotated offsets are exactly ρ(r)\rho(r).

What is not claimed. Theorem 2 gives a lower bound at the true cell, not that the true cell is the largest. Edge points of clutter, or of the shape itself in a wrong pairing, can add votes to another cell, and nothing bounds them in general. For rotations that are not multiples of 90 degrees, the rotated offsets are rounded and the bins do not shift by an integer, so the votes spread and Theorem 3 does not apply. That the peak is the true position in real images is a heuristic, supported by experiments.

Complexity

In the real RAM, lines L1 and L2 cost O(m)O(m), and the edge detection costs O(WH)O(W H) for each image. Line L3 costs O(WH)O(W H). An image edge point with bin bb makes ∣R[b]∣|R[b]| votes, so lines L4 to L7 cost ∑j∣R[bj]∣≤e k≤e m\sum_j |R[b_j]| \le e\, k \le e\, m, where k=max⁡b∣R[b]∣k = \max_b |R[b]|. The peak search in line L8 costs O(WH)O(W H). The space is O(WH)O(W H) for AA and O(m)O(m) for the table.

With nθn_\theta rotations and nsn_s scales, time and accumulator space grow by the factor nθnsn_\theta n_s. This is the main cost of the method, and it is why most systems search position only, or a coarse grid of rotations and scales.

Properties

  • Any shape. The shape needs no formula. Holes and several separate parts are allowed, since the table lists all the edge points.
  • Robust to occlusion. A copy with only a part of its outline visible still gets one vote from each visible edge point. The peak is lower but in the correct place.
  • Linear in the votes. The accumulator of an image is the sum of the accumulators of its edge points. Two copies of the shape give two peaks.
  • Invariant to brightness change. The Sobel gradient does not change when a constant is added to the image, and its direction does not change when the image is multiplied by a positive constant. So the bins are the same. The threshold τ\tau must be scaled with the contrast.
  • Not invariant to rotation and scale. The basic table is for one rotation and one scale. Each extra rotation or scale needs one more accumulator.

Variants and improvements

  • Weighted votes. Votes can be weighted by the gradient magnitude, or by how rare the direction is in the template, so that frequent directions count less.
  • Coarse to fine. A coarse accumulator finds candidate cells, then a finer one refines them.
  • Rotation without a full 4D search. Pairs of edge points give a rotation invariant (the difference of their gradient directions), at a higher voting cost. This is a heuristic with no exact guarantee.
  • Votes from learned parts. The implicit shape model replaces the edge points by local features matched to a codebook, and each codebook entry stores the center offsets seen in the training images. It uses the same voting step for categories of objects.
  • Votes from features. With local features such as SIFT, one match gives position, rotation and scale, and a coarse Hough grid over these four parameters groups the matches before alignment checks them.

When to use it

Use the generalized Hough transform to find a known rigid shape of fixed size and orientation in an image, for example a part in industrial inspection, a logo, or a mark on a document. It works well when the outline is clear and when parts of it can be hidden. For a shape with a formula (a line or a circle), the standard Hough transform has fewer parameters. For a gray-level pattern, template matching uses all the pixels, not only the edges. For an edge template under small deformation, chamfer matching is smoother. For objects with textured surfaces, local features with geometric hashing or alignment handle rotation and scale at lower cost.

Pitfalls

  • Bins too fine or too coarse. Noise moves the gradient direction across the bin boundary, and the vote goes to the wrong table entry. Many bins make this happen often. Few bins make each entry list long and add wrong votes. Votes into the two nearest bins help.
  • Gradient sign. A dark shape on a light background has the opposite gradient of a light shape on a dark background. The bins differ by B/2B/2, and the template does not match. Use the direction modulo π\pi if both polarities can occur.
  • Cost of the extension. Rotation and scale multiply the time and the memory. A full search over 36 angles and 10 scales costs 360 times more than position alone.
  • Peak spread. Rounding, the bin width and small changes of the shape spread the votes over several cells. Smooth the accumulator, or sum it over a small window, before the peak search.
  • Clutter in textured areas. Many edge points in a textured area give many random votes, and a false peak can win. Check each peak, for example by counting how many template edge points fall on image edge points at the found pose.

Implementations

The Python code has the integer Sobel gradient, the direction bins, the R-table, the voting, the peak with the tie rule of this page, and the extension to rotation by bins and to scale. It also has helpers to rotate an image by 90 degrees and to paste a template into an image. The tests check the example of this page, a translated non-symmetric template with and without clutter far from it, the equality of the votes with a direct count over all pairs, the rotation by 90 degrees through the bin shift, the scaled offsets, and the invariance of the edge points to a brightness change.

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.

generalized_hough_transform.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-hough-transform/. The authors are listed in prov/GZ6ZY6.jsonl.
"""The generalized Hough transform of Ballard (1981) for a shape given by a template image.

An image is a list of rows, img[v][u], with u the column (to the right) and v
the row (down). Edge points come from the Sobel gradient: a pixel is an edge
point when gx^2 + gy^2 >= t^2. The gradient direction phi = atan2(gy, gx) is
put into one of B bins centered at the multiples of 2 pi / B. For B = 8 the
bin edges are at 22.5 + 45 j degrees; integer gradients never lie exactly on
them, since tan(22.5 degrees) is irrational.

R-table: for each template edge point x with bin b, store r = c - x in R[b],
where c is the reference point. Detection: each image edge point y with bin b
votes at y + r for every r in R[b]. A copy of the template moved by t gives
at least m votes at c + t, where m is the number of template edge points.
The rotation extension rotates r and shifts the bin; it is exact for 90 degree
steps. Standard library only. Cost: O(e m_max) votes for e image edge
points and at most m_max entries per bin.
"""

import math


def sobel(img):
    """Sobel gradients (gx along u, gy along v); 0 on the one-pixel border."""
    H, W = len(img), len(img[0])
    gx = [[0] * W for _ in range(H)]
    gy = [[0] * W for _ in range(H)]
    for v in range(1, H - 1):
        a, b, c = img[v - 1], img[v], img[v + 1]
        for u in range(1, W - 1):
            gx[v][u] = (a[u + 1] + 2 * b[u + 1] + c[u + 1]) - (a[u - 1] + 2 * b[u - 1] + c[u - 1])
            gy[v][u] = (c[u - 1] + 2 * c[u] + c[u + 1]) - (a[u - 1] + 2 * a[u] + a[u + 1])
    return gx, gy


def direction_bin(gx, gy, B=8):
    """Bin of the gradient direction: round(phi / (2 pi / B)) mod B."""
    phi = math.atan2(gy, gx)
    return int(math.floor(phi / (2.0 * math.pi / B) + 0.5)) % B


def edge_points(img, threshold, B=8):
    """List of (u, v, bin) for the pixels whose gradient magnitude is at least the threshold."""
    gx, gy = sobel(img)
    t2 = threshold * threshold
    out = []
    for v in range(len(img)):
        for u in range(len(img[0])):
            x, y = gx[v][u], gy[v][u]
            if x * x + y * y >= t2 and (x != 0 or y != 0):
                out.append((u, v, direction_bin(x, y, B)))
    return out


def build_r_table(template_edges, ref, B=8):
    """R[b] = list of offsets ref - x for the template edge points x in bin b."""
    R = [[] for _ in range(B)]
    for u, v, b in template_edges:  # @line L1
        R[b].append((ref[0] - u, ref[1] - v))  # @line L2
    return R


def vote(edges, R, W, H):
    """Accumulator A[v][u] of size H x W: the votes of the image edge points."""
    A = [[0] * W for _ in range(H)]  # @line L3
    for u, v, b in edges:  # @line L4
        for du, dv in R[b]:  # @line L5
            cu, cv = u + du, v + dv  # @line L6
            if 0 <= cu < W and 0 <= cv < H:
                A[cv][cu] += 1  # @line L7
    return A


def peak(A):
    """(votes, u, v) of the largest cell; ties go to the smallest v, then the smallest u."""
    best = (-1, 0, 0)
    for v, row in enumerate(A):
        for u, a in enumerate(row):
            if a > best[0]:
                best = (a, u, v)
    return best  # @line L8


def detect(img, R, threshold, B=8):
    """Edge points of img, votes, and the peak (votes, u, v)."""
    A = vote(edge_points(img, threshold, B), R, len(img[0]), len(img))
    return peak(A), A


def rotate_offset(r, steps, B):
    """Rotate (du, dv) by steps * 2 pi / B, rounded to integers (exact for 90 degree steps)."""
    a = steps * 2.0 * math.pi / B
    c, s = math.cos(a), math.sin(a)
    du, dv = r
    return (int(round(c * du - s * dv)), int(round(s * du + c * dv)))


def vote_rotations(edges, R, W, H, B=8, steps=None, scales=(1.0,)):
    """Votes over (rotation step, scale, v, u): the 4D accumulator of the extension.

    An edge point with bin b, under the rotation by k steps, reads R[(b - k) mod B]
    and votes at y + s * rot_k(r). Returns {(k, s): accumulator}.
    """
    steps = range(B) if steps is None else steps
    out = {}
    for k in steps:
        for s in scales:
            rows = []
            for b in range(B):
                rb = R[(b - k) % B]
                rows.append([rotate_offset((s * du, s * dv), k, B) for du, dv in rb])
            out[(k, s)] = vote(edges, rows, W, H)
    return out


def rotate90(img):
    """Rotate the image content by +90 degrees in the (u, v) frame: (u, v) -> (H - 1 - v, u)."""
    H, W = len(img), len(img[0])
    out = [[0] * H for _ in range(W)]
    for v in range(H):
        for u in range(W):
            out[u][H - 1 - v] = img[v][u]
    return out


def paste(canvas, img, du, dv):
    """Copy img into canvas with its top left pixel at (du, dv)."""
    for v, row in enumerate(img):
        for u, val in enumerate(row):
            canvas[dv + v][du + u] = val
    return canvas
test_generalized_hough_transform.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-hough-transform/. The authors are listed in prov/GZ6ZY6.jsonl.

import math
import random

from generalized_hough_transform import (build_r_table, detect, direction_bin,
                                         edge_points, paste, peak, rotate90,
                                         sobel, vote, vote_rotations)

SQUARE = [[1 if 2 <= u <= 4 and 2 <= v <= 4 else 0 for u in range(7)] for v in range(7)]


def l_shape():
    """A 9 x 9 template with an L-shaped blob (no rotational symmetry), margin 2."""
    img = [[0] * 9 for _ in range(9)]
    for v in range(2, 7):
        img[v][2] = img[v][3] = 5
    for u in range(4, 7):
        img[5][u] = img[6][u] = 5
    return img


def blank(W, H):
    return [[0] * W for _ in range(H)]


def test_example_of_the_page():
    E = edge_points(SQUARE, 1)
    assert len(E) == 24
    R = build_r_table(E, (3, 3))
    assert [len(R[b]) for b in range(8)] == [4, 2, 4, 2, 4, 2, 4, 2]
    assert sorted(R[2]) == [(-1, 2), (0, 1), (0, 2), (1, 2)]
    img = paste(blank(12, 10), SQUARE, 4, 2)
    (votes, u, v), A = detect(img, R, 1)
    assert (votes, u, v) == (24, 7, 5)
    others = sorted((a for row in A for a in row), reverse=True)
    assert others[1] == 6


def test_translated_copy_with_clutter():
    T = l_shape()
    E = edge_points(T, 1)
    m = len(E)
    ref = (4, 4)
    R = build_r_table(E, ref)
    clean = paste(blank(30, 24), T, 13, 9)
    (votes, u, v), _ = detect(clean, R, 1)
    assert (votes, u, v) == (m, ref[0] + 13, ref[1] + 9)
    rng = random.Random(1)
    noisy = paste(blank(30, 24), T, 13, 9)
    for _ in range(40):
        uu, vv = rng.randrange(1, 29), rng.randrange(1, 23)
        if not (10 <= uu <= 23 and 6 <= vv <= 19):
            noisy[vv][uu] = rng.randint(1, 9)
    (votes, u, v), A = detect(noisy, R, 1)
    assert A[ref[1] + 9][ref[0] + 13] >= m
    assert (u, v) == (ref[0] + 13, ref[1] + 9)


def test_votes_equal_direct_count():
    rng = random.Random(2)
    T = l_shape()
    R = build_r_table(edge_points(T, 1), (4, 4))
    tmpl = edge_points(T, 1)
    img = [[rng.randint(0, 3) for _ in range(14)] for _ in range(12)]
    E = edge_points(img, 2)
    A = vote(E, R, 14, 12)
    direct = [[0] * 14 for _ in range(12)]
    for u, v, b in E:
        for tu, tv, tb in tmpl:
            if tb == b:
                pu, pv = u + 4 - tu, v + 4 - tv
                if 0 <= pu < 14 and 0 <= pv < 12:
                    direct[pv][pu] += 1
    assert A == direct


def test_bins_never_on_a_boundary_for_integer_gradients():
    for gx in range(-30, 31):
        for gy in range(-30, 31):
            if gx == 0 and gy == 0:
                continue
            q = math.atan2(gy, gx) / (math.pi / 4)
            assert abs(q - math.floor(q) - 0.5) > 1e-4
            assert direction_bin(-gy, gx) == (direction_bin(gx, gy) + 2) % 8
    assert direction_bin(1, 0) == 0 and direction_bin(0, 1) == 2
    assert direction_bin(-1, 0) == 4 and direction_bin(0, -1) == 6


def test_sobel_rotates_with_the_image():
    rng = random.Random(3)
    img = [[rng.randint(0, 9) for _ in range(7)] for _ in range(6)]
    H = len(img)
    gx, gy = sobel(img)
    rot = rotate90(img)
    rx, ry = sobel(rot)
    for v in range(1, H - 1):
        for u in range(1, 6):
            assert (rx[u][H - 1 - v], ry[u][H - 1 - v]) == (-gy[v][u], gx[v][u])


def test_rotation_by_90_degrees():
    T = l_shape()
    ref = (4, 4)
    E = edge_points(T, 1)
    m = len(E)
    R = build_r_table(E, ref)
    rot = rotate90(T)
    ref_rot = (len(T) - 1 - ref[1], ref[0])
    img = paste(blank(26, 22), rot, 9, 6)
    acc = vote_rotations(edge_points(img, 1), R, 26, 22, steps=[0, 2, 4, 6])
    best = max((peak(A), k) for (k, s), A in acc.items())
    assert best == ((m, ref_rot[0] + 9, ref_rot[1] + 6), 2)
    assert peak(acc[(0, 1.0)])[0] < m


def test_scale_two_offsets():
    R = [[(1, 0)], [], [], [], [], [], [], []]
    acc = vote_rotations([(5, 5, 0)], R, 12, 12, steps=[0], scales=(1.0, 2.0))
    assert acc[(0, 1.0)][5][6] == 1 and acc[(0, 2.0)][5][7] == 1


def test_affine_intensity_change_keeps_edges():
    T = l_shape()
    brighter = [[3 * a + 7 for a in row] for row in T]
    assert edge_points(T, 1) == edge_points(brighter, 1)

History

The Hough transform comes from a 1962 patent of Paul Hough for bubble chamber tracks. Duda and Hart (1972) gave the bounded parameterization for lines and extended the voting to other analytic curves. Ballard (1981) removed the need for a formula: the R-table from the gradient direction to the offsets of a reference point describes any shape, and the same table, rotated and scaled, gives the search over rotation and scale. Illingworth and Kittler (1988) surveyed the many variants. Later, Leibe, Leonardis and Schiele used the same voting for object categories in the implicit shape model.

References

  1. Dana H. Ballard, Generalizing the Hough transform to detect arbitrary shapes, Pattern Recognition 13(2), 1981, 111-122, The R-table indexed by the gradient direction, the voting for the reference point, and the extension of the parameter space to rotation and scale
  2. Richard O. Duda and Peter E. Hart, Use of the Hough transformation to detect lines and curves in pictures, Communications of the ACM 15(1), 1972, 11-15, The voting scheme for lines in the normal parameterization and its extension to other analytic curves
  3. John Illingworth and Josef Kittler, A survey of the Hough transform, Computer Vision, Graphics, and Image Processing 44(1), 1988, 87-116, The survey of the generalized Hough transform and its variants

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 proofH1 sketch
  • 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
  • a scene preset for the example