Algorithmcore
Histogram of oriented gradients
Also called HOG, HOG descriptor.
Describe a window by histograms of gradient orientation over a grid of small cells, normalized over overlapping blocks of cells; with linear SVMs it became a standard pedestrian detector.
- Solves
- Object detection
- Time
- O(W H + W H B / c^2) worst · average · best
- Space
- O(W H + W H B / c^2) extra
- Where
- B = the number of orientation bins; H = the window height in pixels; W = the window width in pixels; c = the side of a cell in pixels
- Model
- Real RAM
- Properties
- deterministicexactheuristicnot rotation invariantnot scale invariant
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Navneet Dalal, Bill Triggs, 2005
The histogram of oriented gradients (HOG) describes the shape in an image window by the directions of its edges. It divides the window into small cells, for example pixels, and builds for each cell a histogram of gradient orientations weighted by the gradient magnitude. It then groups the cells into overlapping blocks of cells and normalizes each block, so that the descriptor does not depend much on the light and the contrast. Dalal and Triggs introduced HOG in 2005 for detecting people with a linear support vector machine, the Dalal-Triggs detector. It describes a whole window, not a keypoint, but it uses the same cells of gradient histograms as the SIFT descriptor.
In plain words
Cut an image window into a grid of small squares. In each square, find the direction of the edges at each pixel, from the change of brightness to the next pixel. Count the directions in 9 groups, from horizontal through vertical and back, and let strong edges count more than weak ones. The 9 counts of each square show which way the edges in that square go. A person standing upright gives many vertical edges at the sides of the body and a round outline at the head. Then take groups of 2 by 2 squares and scale the counts of each group so that they do not depend on how bright or how contrasted that part of the image is. Write all the scaled counts one after the other. A classifier learns which patterns of counts belong to a person.
The problem
The input is a gray window with columns and rows, a cell size , a number of orientation bins and a block size of cells. A pixel is , with the column (to the right) and the row (down). The gradient is
the centered mask with no smoothing. The magnitude is , and the unsigned orientation is folded into , so a dark-to-bright edge and a bright-to-dark edge with the same direction get the same orientation. For color images Dalal and Triggs take, at each pixel, the gradient of the color channel with the largest magnitude.
The bins have the centers for . A pixel votes into the two bins whose centers are nearest to on the circle of 180 degrees, with weights that fall linearly with the distance. With spatial interpolation, the vote is also split between the four nearest cell centers by bilinear weights; this is trilinear voting. A block of cells gives a vector of values, normalized by L2-Hys:
The blocks move by one cell, so each inner cell is in four blocks with four different normalizations. The output is the concatenation of all normalized blocks. For the default window of pixels, and , there are cells and blocks of 36 values, so the descriptor has values.
The algorithm
HOG(I, c, B) ▷ I is a W × H window- 1
g_u, g_v ← I filtered by [-1, 0, 1] in u and in v - 2
m ← sqrt(g_u^2 + g_v^2), φ ← atan2(g_v, g_u) mod 180° - 3
for each pixel, find the two orientation bins nearest to φ and their linear weights - 4
add m × (bin weight) × (bilinear cell weight) to the histograms of the four nearest cells - 5
for each block of 2 × 2 cells, moving by one cell do - 6
x ← the four cell histograms, one after the other - 7
x ← L2-Hys(x): divide by the L2 norm, clip at 0.2, divide by the L2 norm again; append x to the output - 8
return the output
The paper also weights the pixels of each block by a Gaussian window with equal to half the block width, 8 pixels for a block of 16 pixels. This makes the cell histograms differ from block to block. Our code leaves the Gaussian window out, so it computes each cell histogram once and shares it among the blocks; the page says where this matters below.
For detection, a linear classifier scores the descriptor of each window position at each scale of an image pyramid, which is sliding window detection. Dalal and Triggs train a soft linear SVM ( with SVMLight) on the INRIA data, then search the negative images for hard false positives and train again.
Example
One vote. A pixel has and . Its magnitude is 50 and its orientation is . With the bin centers are . The angle lies between the centers (bin 2) and (bin 3), at of the way. So bin 2 gets and bin 3 gets . Without spatial interpolation both votes go to the cell of the pixel.
A vertical edge. In a window that is 0 on the left half and 100 on the right half, the pixels next to the edge have and , so . The angle 0 lies half way between the centers and , so bins 8 and 0 each get 50. A row of 8 edge pixels in one cell gives 400 in bin 0 and 400 in bin 8. A black-to-white edge and a white-to-black edge give the same histogram.
L2-Hys. A block vector with the values and 0 elsewhere has the L2 norm 13 (take ). After the first division it is . All three are above 0.2 and are clipped to 0.2, and the second division gives for each. The clipping stops the one strong edge from dominating the block.
Length. A window has cells and blocks, so values; the window has 3780.
Correctness
HOG is a definition, so correctness means that the code computes the histograms and blocks as defined. The proof in proofs/correctness.md shows that:
- The two orientation weights of a pixel are nonnegative and sum to 1, and so do the four bilinear cell weights for a pixel whose four nearest cell centers are in the window. So such a pixel adds exactly to the cells in total.
- The descriptor does not change when a constant is added to the window, since the gradient does not change. It does not change when the window is replaced by , since the gradient changes sign and the unsigned orientation does not.
- A mirror image in maps the cell in column to the cell in column and the bin to the bin .
- With , the L2-Hys output has norm 1 and does not change when the block is multiplied by . With the change is small for blocks with a norm much larger than .
That HOG with a linear SVM detects people well is a benchmark result. Dalal and Triggs report miss rates at false positives per window on their INRIA set of 1805 images of people of pixels and on the MIT set.
Proof: Correctness of the histogram of oriented gradientsfull
Let be a window with columns and rows, the cell size, the number of bins, and . The gradient, the magnitude , the unsigned angle and the voting are as defined on the page, with the image extended by its edge pixels at the border. Let .
Lemma 1 (orientation weights). For each , line L3 gives two bins and with weights and , where . These are the two bins whose centers on the circle of 180 degrees are nearest to , and the weight of each bin is , where is the circular distance from to its center.
Proof. Let , and . The centers of the bins and are and , and lies between them, at the distance from the first and from the second. Since , is in ; taking and modulo maps the centers and to the centers and , which are the same points on the circle of length . All other centers are at a distance of at least . So the weights and are as claimed, and they are nonnegative and sum to 1.
Lemma 2 (conservation of the votes). Without spatial voting, each pixel inside the grid adds exactly to the histogram of its cell. With spatial voting, a pixel whose coordinates and lie in adds exactly to the cells in total, and every other pixel adds between 0 and .
Proof. Without spatial voting, the pixel adds to its cell by Lemma 1. With spatial voting, it adds for the cell weights , and the bin weights . The sum over all four cells and both bins is . If and are in the given range, the cells , (when its weight is nonzero) and the same in all exist, so no term is left out. Otherwise some terms are left out; all terms are nonnegative, so the sum is between 0 and .
Lemma 3 (offset and negation). Let with a constant and . Then has the same magnitudes and unsigned angles as , so the same cell histograms and the same descriptor.
Proof. Each gradient component is a difference of two pixel values, so and , and the magnitude does not change. If , the vector turns by when it is not zero, so changes by , and the angle modulo does not change. Pixels with a zero gradient add nothing in both cases. So the cell histograms are equal, and so are the blocks.
In floating point the offset case is exact for integer images, as in the tests; the negation case is equal up to the rounding of .
Lemma 4 (mirror). Let with . Then the cell histograms satisfy .
Proof. At the pixel of , the gradient is of at ; the edge extension commutes with the mirror. The magnitude is the same. The angle of is modulo . The bin centers map to , so the circular distances from to the center of equal those from to the center of , and by Lemma 1 the bin weights move from to . In space, , so the bilinear weight of the cell for the mirrored pixel equals the weight of the cell for the original pixel. Summing over the pixels gives the claim.
Lemma 5 (L2-Hys). Let with , the clip value and with nonnegative entries. Then , and for every .
Proof. After the first division , which does not change when is replaced by . The clip gives , which is not the zero vector because some and . The second division gives a vector of norm 1. Each step depends only on , so the output does not depend on .
With , the first step gives , which differs from by a factor , close to 1 when ; this is why a gain changes the descriptor only a little.
Theorem. HOG returns the concatenation, over the blocks of cells in row order, of the L2-Hys normalized cell histograms of the definition. The length is . The descriptor does not change under a constant offset or under , and, with , each block has norm 1 and does not change when the window is multiplied by .
Proof. Lines L1 and L2 compute the magnitude and the unsigned angle. By Lemma 1, lines L3 and L4 put each vote into the bins and cells of the definition, with the weights of the definition, and by Lemma 2 no part of a vote is lost except for the pixels near the border whose cell centers do not exist. The loop of line L5 runs over the blocks; line L6 joins four histograms of values, and line L7 normalizes them, which gives the length. Lemma 3 gives the invariance to an offset and to negation. Multiplying by multiplies every magnitude by and keeps every angle, so every block vector is multiplied by , and Lemma 5 gives the last claim.
Complexity
The model is the real RAM, with the square root, atan2 and the floor in time.
- Lines L1 and L2 take time.
- Lines L3 and L4 take time per pixel, with 2 bins and at most 4 cells, so in total.
- There are about blocks of values. Lines L5 to L7 take time.
The total time is , and the extra space is for the gradients and for the cells and the output. For dense detection, the cells are computed once for the whole image at each scale and shared by all windows, so the cost per window is only the reading of its blocks and the dot product with the SVM weights.
Properties
- Not rotation or scale invariant. HOG fixes the grid to the window. Detection gets scale invariance from an image pyramid, and people are mostly upright, so rotation invariance is not wanted.
- Robust to small shifts. Each cell pools the gradients of pixels, and trilinear voting removes the jumps at the cell borders.
- Light and contrast. The gradient removes a constant offset. The block normalization removes a gain, locally, which matters because shadows and backgrounds vary within a window.
- Redundant. Each inner cell appears in four blocks with four normalizations. Dalal and Triggs found that this overlap improved the miss rate considerably.
- Design choices. The cell size, the bins, the block size and the clip value 0.2 were chosen by experiments on the INRIA data. They are not optimal in general.
Variants and improvements
- Normalization schemes. Section 6.4 compares L2-norm, L2-Hys, L1-norm and L1-sqrt, . L2-Hys, L2-norm and L1-sqrt did about equally well, and L1-norm was worse.
- Signed orientation. Bins over 0 to 360 degrees keep the sign of the edge. For people it made the results worse, even with twice as many bins, because clothes can be darker or lighter than the background.
- R-HOG and C-HOG. The rectangular blocks above are R-HOG. C-HOG uses circular blocks with log-polar cells, similar to the shape context.
- Felzenszwalb HOG. The deformable part model uses cells of 8 pixels with both signed and unsigned bins and a reduced form of 31 values per cell.
- Fast HOG. An integral image per orientation bin gives the sum of any rectangle in time, which speeds up the search over many window sizes at the cost of the trilinear voting.
- Texture. HOG and local binary patterns are often concatenated for detection.
When to use it
Use HOG to describe windows of objects with a typical outline, such as people, cars and faces, for a linear classifier or as an input to a part model. It is fast, needs no learning of the features, and works well with a few thousand training examples. For keypoint matching between views, use a descriptor with a keypoint frame such as SIFT. For large detection tasks with many classes, learned network features have replaced HOG; it is still useful when data or compute are scarce.
Pitfalls
- Smoothing before the gradient. Dalal and Triggs found that smoothing hurts: with the recall at false positives per window fell from 89 percent to 80 percent. The simple mask worked best; the Sobel mask and larger masks did worse.
- Unsigned angles. gives angles in . Fold them into , and treat the bins as a circle, or angles near 0 and 180 go to different ends.
- Bin centers. Centers at and centers at are both used in libraries. They give different descriptors.
- Block order. Libraries differ in the order of cells inside a block and of blocks inside the window. A trained SVM only works with the order it was trained on.
- Window margin. The paper's window has a margin of about 16 pixels around the person. Cutting the margin to 8 pixels made the results worse, so the context counts.
- The Gaussian block window. The paper weights each block by a Gaussian. Our code leaves it out, which changes the values but not the structure.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/histogram-of-oriented-gradients/. The authors are listed in prov/DA8C98.jsonl.
"""Histogram of oriented gradients (HOG) for one detection window.
An image is a list of H rows of W numbers; pixel (u, v) is img[v][u], with u
the column (to the right) and v the row (down). The window is the whole image.
Steps, following the default detector of Dalal and Triggs (2005):
1. Gradients by the centered masks [-1, 0, 1] in u and in v, with no
smoothing. At the border the image is extended by its edge pixels.
2. Unsigned orientation phi = atan2(g_v, g_u) folded into [0, 180) degrees.
3. Each pixel votes its gradient magnitude into the two nearest of the B
orientation bins (centers at (b + 1/2) 180 / B degrees, circular), with
linear weights. With spatial=True it also splits its vote between the four
nearest cell centers with bilinear weights (trilinear voting).
4. Blocks of 2 x 2 cells, with a stride of one cell, are normalized by L2-Hys:
v / sqrt(|v|^2 + eps^2), values clipped at 0.2, then normalized again.
The Gaussian window over each block (sigma = half the block width) of the
paper is left out; so the cell histograms are shared by all blocks.
"""
import math
from typing import List, Sequence
Image = Sequence[Sequence[float]]
def gradients(img: Image):
"""Return (magnitude, angle in degrees in [0, 180)) for each pixel."""
h, w = len(img), len(img[0])
mag = [[0.0] * w for _ in range(h)]
ang = [[0.0] * w for _ in range(h)]
for v in range(h):
for u in range(w):
gu = img[v][min(u + 1, w - 1)] - img[v][max(u - 1, 0)] # @line L1
gv = img[min(v + 1, h - 1)][u] - img[max(v - 1, 0)][u]
mag[v][u] = math.hypot(gu, gv)
a = math.degrees(math.atan2(gv, gu)) % 180.0 # @line L2
ang[v][u] = 0.0 if a >= 180.0 else a
return mag, ang
def orientation_votes(angle: float, bins: int):
"""The two bins and their weights for an unsigned angle in [0, 180)."""
width = 180.0 / bins
x = angle / width - 0.5
b0 = math.floor(x)
f = x - b0
return (b0 % bins, 1.0 - f), ((b0 + 1) % bins, f)
def cell_histograms(img: Image, cell: int = 8, bins: int = 9, spatial: bool = True) -> List[List[List[float]]]:
"""Histograms hist[cy][cx][b] of the cells of size cell x cell."""
h, w = len(img), len(img[0])
ny, nx = h // cell, w // cell
hist = [[[0.0] * bins for _ in range(nx)] for _ in range(ny)]
mag, ang = gradients(img)
for v in range(ny * cell):
for u in range(nx * cell):
m = mag[v][u]
if m == 0.0:
continue
ov = orientation_votes(ang[v][u], bins) # @line L3
if not spatial:
cy, cx = v // cell, u // cell
for b, wb in ov:
hist[cy][cx][b] += m * wb
continue
# Cell centers are at (c + 1/2) cell - 1/2 in pixel coordinates.
x = (u + 0.5) / cell - 0.5
y = (v + 0.5) / cell - 0.5
x0, y0 = math.floor(x), math.floor(y)
fx, fy = x - x0, y - y0
for cy, wy in ((y0, 1.0 - fy), (y0 + 1, fy)):
if not 0 <= cy < ny or wy == 0.0:
continue
for cx, wx in ((x0, 1.0 - fx), (x0 + 1, fx)):
if not 0 <= cx < nx or wx == 0.0:
continue
for b, wb in ov:
hist[cy][cx][b] += m * wy * wx * wb # @line L4
return hist
def l2_hys(vec: List[float], eps: float = 1e-3, clip: float = 0.2) -> List[float]:
"""L2 normalization, clipping at clip, and L2 normalization again."""
n = math.sqrt(sum(x * x for x in vec) + eps * eps)
out = [min(x / n, clip) for x in vec]
n2 = math.sqrt(sum(x * x for x in out) + eps * eps)
return [x / n2 for x in out]
def hog(img: Image, cell: int = 8, bins: int = 9, block: int = 2, spatial: bool = True,
eps: float = 1e-3) -> List[float]:
"""The HOG descriptor of the window: the normalized blocks, row by row."""
hist = cell_histograms(img, cell, bins, spatial)
ny, nx = len(hist), len(hist[0]) if hist else 0
out: List[float] = []
for by in range(ny - block + 1): # @line L5
for bx in range(nx - block + 1):
vec: List[float] = []
for cy in range(by, by + block):
for cx in range(bx, bx + block):
vec.extend(hist[cy][cx]) # @line L6
out.extend(l2_hys(vec, eps)) # @line L7
return out # @line L8
def hog_length(width: int, height: int, cell: int = 8, bins: int = 9, block: int = 2) -> int:
"""Length of the descriptor of a width x height window with a stride of one cell."""
nx, ny = width // cell, height // cell
return (nx - block + 1) * (ny - block + 1) * block * block * bins
test_histogram_of_oriented_gradients.py 128 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/histogram-of-oriented-gradients/. The authors are listed in prov/DA8C98.jsonl.
import math
import random
from histogram_of_oriented_gradients import cell_histograms, gradients, hog, hog_length, l2_hys, orientation_votes
def random_image(rng, w, h):
return [[rng.randint(0, 255) for _ in range(w)] for _ in range(h)]
def close(a, b, tol=1e-9):
return len(a) == len(b) and all(abs(x - y) <= tol for x, y in zip(a, b))
def test_lengths():
assert hog_length(64, 128) == 3780
assert hog_length(64, 64) == 1764
rng = random.Random(1)
img = random_image(rng, 64, 64)
assert len(hog(img)) == 1764
img2 = random_image(rng, 32, 48)
assert len(hog(img2)) == hog_length(32, 48) == 3 * 5 * 36
def test_orientation_votes():
# Bin centers 10, 30, ..., 170 degrees.
(b0, w0), (b1, w1) = orientation_votes(10.0, 9)
assert (b0, b1) == (0, 1) and w0 == 1.0 and w1 == 0.0
(b0, w0), (b1, w1) = orientation_votes(25.0, 9)
assert (b0, b1) == (0, 1) and abs(w0 - 0.25) < 1e-12 and abs(w1 - 0.75) < 1e-12
(b0, w0), (b1, w1) = orientation_votes(0.0, 9)
assert (b0, b1) == (8, 0) and abs(w0 - 0.5) < 1e-12 and abs(w1 - 0.5) < 1e-12
(b0, w0), (b1, w1) = orientation_votes(175.0, 9)
assert (b0, b1) == (8, 0) and abs(w0 - 0.75) < 1e-12
def test_cells_match_direct_computation_without_spatial_voting():
rng = random.Random(2)
img = random_image(rng, 24, 16)
hist = cell_histograms(img, 8, 9, spatial=False)
for cy in range(2):
for cx in range(3):
want = [0.0] * 9
for v in range(cy * 8, cy * 8 + 8):
for u in range(cx * 8, cx * 8 + 8):
gu = img[v][min(u + 1, 23)] - img[v][max(u - 1, 0)]
gv = img[min(v + 1, 15)][u] - img[max(v - 1, 0)][u]
m = math.sqrt(gu * gu + gv * gv)
a = math.degrees(math.atan2(gv, gu))
if a < 0:
a += 180.0
if a >= 180.0:
a -= 180.0
# Distance to each bin center on the circle of 180 degrees.
for b in range(9):
c = 20.0 * b + 10.0
d = abs(a - c)
d = min(d, 180.0 - d)
if d < 20.0:
want[b] += m * (1.0 - d / 20.0)
assert close(hist[cy][cx], want, 1e-9)
def test_spatial_votes_keep_the_total_inside():
rng = random.Random(3)
img = random_image(rng, 32, 32)
mag, _ = gradients(img)
hist = cell_histograms(img, 8, 9, spatial=True)
# Pixels whose four cell centers all exist give all their weight to the cells.
inner = sum(mag[v][u] for v in range(4, 28) for u in range(4, 28))
total = sum(sum(sum(c) for c in row) for row in hist)
edge = sum(mag[v][u] for v in range(32) for u in range(32)) - inner
assert inner - 1e-6 <= total <= inner + edge + 1e-6
def test_step_edge_votes_split_between_bins_zero_and_eight():
img = [[0] * 8 + [100] * 8 for _ in range(16)]
hist = cell_histograms(img, 8, 9, spatial=False)
for row in hist:
for c in row:
assert c[0] == c[8]
assert all(c[b] == 0.0 for b in range(1, 8))
assert hist[0][0][0] == 8 * 100 * 0.5
def test_offset_and_negation_give_the_same_descriptor():
rng = random.Random(4)
img = random_image(rng, 32, 32)
base = hog(img)
assert hog([[x + 40 for x in row] for row in img]) == base
assert close(hog([[255 - x for x in row] for row in img]), base)
def test_gain_changes_little():
rng = random.Random(5)
img = random_image(rng, 32, 32)
a = hog(img)
b = hog([[3 * x for x in row] for row in img])
assert close(a, b, 1e-6)
def test_mirror_reverses_cells_and_bins():
rng = random.Random(6)
img = random_image(rng, 32, 24)
mir = [row[::-1] for row in img]
h1 = cell_histograms(img, 8, 9)
h2 = cell_histograms(mir, 8, 9)
for cy in range(3):
for cx in range(4):
assert close(h2[cy][3 - cx], [h1[cy][cx][8 - b] for b in range(9)], 1e-9)
def test_l2_hys_clips_and_normalizes():
v = [10.0, 0.0, 0.0, 0.0]
out = l2_hys(v, eps=0.0)
assert out == [1.0, 0.0, 0.0, 0.0]
w = [5.0, 1.0, 1.0, 1.0]
out = l2_hys(w, eps=0.0)
assert abs(sum(x * x for x in out) - 1.0) < 1e-12
first = l2_hys([5.0, 1.0, 1.0, 1.0], eps=0.0)
assert first[0] > first[1]
# The first value is clipped at 0.2 and the others are not, then all are scaled alike.
z = l2_hys([3.0] + [1.0] * 35, eps=0.0)
assert abs(sum(x * x for x in z) - 1.0) < 1e-12
assert abs(z[0] / z[1] - 0.2 / (1.0 / math.sqrt(44.0))) < 1e-9
History
Dalal and Triggs presented HOG at CVPR 2005. Their study tested each step on the new INRIA person data set: gamma and color, gradient masks, the number of bins, the size of cells and blocks, and the normalization. It made the cell-and-block descriptor with a linear SVM the standard pedestrian detector of its time. Earlier work had used edge orientation histograms, shape contexts and SIFT descriptors; HOG differs by its dense grid of overlapping, locally normalized blocks. Felzenszwalb and his coauthors built the deformable part model on HOG features, and HOG stayed a common baseline until learned network features took over around 2012.
References
- Navneet Dalal and Bill Triggs, Histograms of oriented gradients for human detection, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), vol. 1, 886-893, 2005, Section 4 (overview of the method), Section 6.1 (gamma and color), Section 6.2 (gradient masks), Section 6.3 (orientation binning), Section 6.4 (blocks and the L2-norm, L2-Hys, L1-norm and L1-sqrt schemes), Section 6.5 (the 64 x 128 window), Section 6.6 (the linear SVM)
- David G. Lowe, Distinctive image features from scale-invariant keypoints, International Journal of Computer Vision 60(2), 91-110, 2004, Section 6.1 (gradient histograms in cells, trilinear voting, the clipping at 0.2 that L2-Hys follows)
- 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), 1627-1645, 2010, Section 6 (the HOG features of the part model and the reduced form)
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 DA8C98 Edit this page History Report an error Markdown