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.
- Solves
- Object detection
- 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
- Model
- Real RAM
- Properties
- deterministicexact
- Evidence
- Proof sketchCode in 1 languages
- 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 and a reference point in it, and an image of width and height , both as arrays with the column and the row. A threshold on the gradient magnitude and a number of direction bins (here ).
Edge points. The gradient at a pixel comes from the Sobel operator, and it is 0 on the border of the image. A pixel is an edge point if and the gradient is not zero. Its bin is with , so the bins are centered at the multiples of . The template gives edge points and the image gives edge points .
Output. The accumulator on the pixel grid,
the number of pairs of a template edge point and an image edge point with the same bin that put the reference point at . Also the cell with the largest count, with ties to the smallest , then the smallest .
The algorithm
GHT(template edges, c, image edges) ▷ R[0..B-1] are empty lists- 1
for each template edge point (x, b) do - 2
append the offset c - x to R[b] - 3
A ← 0 on the W by H grid - 4
for each image edge point (y, b) do - 5
for each offset r in R[b] do - 6
p ← y + r - 7
if p is inside the grid then A[p] ← A[p] + 1 - 8
return 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 . For a rotation and a scale , the shape edge point that now has bin had bin in the template, so line L5 reads for a rotation of bins, and line L6 becomes . The code does this in vote_rotations, with one accumulator for each pair . 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 image with a square of value 1 at , and , the center of the square. With , every pixel of the block around the square has a nonzero gradient, except the center, so . 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 , , and above the square, so
Paste the template into a blank image of pixels with its top left pixel at . The point of the template is now at , with bin 2. It votes at , , and . Only the last one is the true center . The 24 edge points of the copy all vote at , so the peak is . The second largest count in 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 of the problem statement: each pair of a template edge point and an image edge point with the same bin adds one vote, at , if that cell is inside the grid.
Theorem 2 (a translated copy gives a peak of at least ). If the image edge points include for all template edge points and is inside the grid, then . If the image edge points are exactly these points, then . This holds when the image is the template moved by 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 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 . So the rotated copy gives in the accumulator for the rotation of bins, where is the rotated reference point.
What is not claimed: the peak at 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 for , the image edge points are for , the reference point is , and is the set of grid cells of the image. All points are integer pairs .
Theorem 1 (the votes count matching pairs). After lines L1 to L7, for every ,
Proof. After lines L1 and L2, is the list of the offsets over the indices with , one entry for each such (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 . Lines L4 and L5 visit each pair with exactly once. For such a pair, line L6 computes , and line L7 adds 1 to if and does nothing otherwise. No other line changes . So is the number of pairs with and , for every .
Theorem 2 (translated copy). Let be an integer vector. Suppose that for each , is an image edge point, and that . Then . If, in addition, the image edge points are exactly for , then .
Proof. For each , let be the index of the image edge point . Then and , so the pair is counted in by Theorem 1. The pairs are distinct since their first indices are distinct. So .
For the equality, every image edge point is with for one . A pair is counted in if and only if and , that is, , that is, , since distinct template edge points are distinct pixels. So for each exactly one pair is counted, and .
Lemma 1 (when the image edges are the translated template edges). Suppose the template of size is 0 on its two outer rows and columns on each side, the image satisfies for all template pixels, is 0 at all other pixels, and the copy satisfies , , and . Then the image edge points are exactly .
Proof. The Sobel gradient at a pixel that is not on the border of its array depends only on the neighborhood of the pixel. Take a pixel of the image and consider three cases. (a) for a template pixel that is not on the border of : its neighborhood in is the translate of its neighborhood in , and is not on the border of by the conditions on , so the gradients are equal and is an edge point with bin if and only if is one with bin . (b) for on the border of : the gradient of in is 0 by convention. The neighborhood of in consists of pixels of the two outer rings of the copy and pixels outside the copy, all 0, so the gradient of is 0. (c) 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 is on the border of . In both cases the gradient is 0. So the edge points of are exactly the translates of the edge points of , with the same bins.
Lemma 1 with Theorem 2 gives for a clean copy, which is the example of the page and the first test.
Theorem 3 (rotation by 90 degrees). Let , the rotation by 90 degrees in the frame, and let be a multiple of 4. Suppose that each template edge point appears in the image as the edge point , and that . Let be the accumulator of lines L3 to L7 when line L5 reads and line L6 uses . Then .
Proof. The image edge point has bin , so it reads , which holds . Since is linear, it votes at . The template points give distinct pairs, as in Theorem 2.
Lemma 2 (the hypothesis of Theorem 3 holds for a rotated image). Let be the image rotated by 90 degrees, , so that the pixel moves to . If is the Sobel gradient of at an interior pixel , then the Sobel gradient of at the image of is , and its bin is the bin of plus modulo .
Proof. Write with . The Sobel operator is a finite difference along an axis with smoothing across it. Let . A unit step along at corresponds to the step at , and a step along at corresponds to at . So is the Sobel difference of at along , which is , and is the Sobel difference along , which is ; the smoothing weights are symmetric, so they match. The magnitude is unchanged, so is an edge point if and only if is one. The angle grows by , so modulo , and since is an integer, the floor of the value plus grows by exactly .
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 bins, the rotated reference point gets votes. The code rounds and of to 0 and 1, so its rotated offsets are exactly .
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 , and the edge detection costs for each image. Line L3 costs . An image edge point with bin makes votes, so lines L4 to L7 cost , where . The peak search in line L8 costs . The space is for and for the table.
With rotations and scales, time and accumulator space grow by the factor . 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 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 , and the template does not match. Use the direction modulo 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag GZ6ZY6 Edit this page History Report an error Markdown