Algorithm Search⌘K

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.

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
Properties
deterministicexactheuristicnot rotation invariantnot scale invariant
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 8×88 \times 8 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 2×22 \times 2 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 II with WW columns and HH rows, a cell size cc, a number of orientation bins BB and a block size of 2×22 \times 2 cells. A pixel is (u,v)(u, v), with uu the column (to the right) and vv the row (down). The gradient is

gu(u,v)=I(u+1,v)−I(u−1,v),gv(u,v)=I(u,v+1)−I(u,v−1),g_u(u, v) = I(u + 1, v) - I(u - 1, v), \qquad g_v(u, v) = I(u, v + 1) - I(u, v - 1),

the centered mask [−1,0,1][-1, 0, 1] with no smoothing. The magnitude is m=gu2+gv2m = \sqrt{g_u^2 + g_v^2}, and the unsigned orientation is φ=atan2⁡(gv,gu)\varphi = \operatorname{atan2}(g_v, g_u) folded into [0°,180°)[0°, 180°), 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 BB bins have the centers (b+12)⋅180°/B(b + \frac12) \cdot 180°/B for b=0,…,B−1b = 0, \dots, B - 1. A pixel votes mm into the two bins whose centers are nearest to φ\varphi 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 2×22 \times 2 cells gives a vector xx of 4B4B values, normalized by L2-Hys:

x←x∥x∥22+ε2,xk←min⁡(xk,0.2),x←x∥x∥22+ε2.x \leftarrow \frac{x}{\sqrt{\lVert x \rVert_2^2 + \varepsilon^2}}, \qquad x_k \leftarrow \min(x_k, 0.2), \qquad x \leftarrow \frac{x}{\sqrt{\lVert x \rVert_2^2 + \varepsilon^2}} .

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 64×12864 \times 128 pixels, c=8c = 8 and B=9B = 9, there are 8×168 \times 16 cells and 7×157 \times 15 blocks of 36 values, so the descriptor has 7×15×36=37807 \times 15 \times 36 = 3780 values.

The algorithm

  1. HOG(I, c, B) ▷ I is a W × H window
  2. 1g_u, g_v ← I filtered by [-1, 0, 1] in u and in v
  3. 2m ← sqrt(g_u^2 + g_v^2), φ ← atan2(g_v, g_u) mod 180°
  4. 3for each pixel, find the two orientation bins nearest to φ and their linear weights
  5. 4add m × (bin weight) × (bilinear cell weight) to the histograms of the four nearest cells
  6. 5for each block of 2 × 2 cells, moving by one cell do
  7. 6x ← the four cell histograms, one after the other
  8. 7x ← L2-Hys(x): divide by the L2 norm, clip at 0.2, divide by the L2 norm again; append x to the output
  9. 8return the output

The paper also weights the pixels of each block by a Gaussian window with σ\sigma 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 (C=0.01C = 0.01 with SVMLight) on the INRIA data, then search the negative images for hard false positives and train again.

Example

One vote. A pixel has gu=30g_u = 30 and gv=40g_v = 40. Its magnitude is 50 and its orientation is φ=atan2⁡(40,30)≈53.13°\varphi = \operatorname{atan2}(40, 30) \approx 53.13°. With B=9B = 9 the bin centers are 10°,30°,50°,…,170°10°, 30°, 50°, \dots, 170°. The angle lies between the centers 50°50° (bin 2) and 70°70° (bin 3), at 3.13/20≈0.1573.13 / 20 \approx 0.157 of the way. So bin 2 gets 50×0.843≈42.1750 \times 0.843 \approx 42.17 and bin 3 gets 50×0.157≈7.8350 \times 0.157 \approx 7.83. 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 gu=100g_u = 100 and gv=0g_v = 0, so φ=0°\varphi = 0°. The angle 0 lies half way between the centers 170°170° and 10°10°, 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 12,4,312, 4, 3 and 0 elsewhere has the L2 norm 13 (take ε=0\varepsilon = 0). After the first division it is 0.923,0.308,0.2310.923, 0.308, 0.231. All three are above 0.2 and are clipped to 0.2, and the second division gives 0.5770.577 for each. The clipping stops the one strong edge from dominating the block.

Length. A 64×6464 \times 64 window has 8×88 \times 8 cells and 7×77 \times 7 blocks, so 7×7×36=17647 \times 7 \times 36 = 1764 values; the 64×12864 \times 128 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 mm 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 a−Ia - I, since the gradient changes sign and the unsigned orientation does not.
  • A mirror image in uu maps the cell in column xx to the cell in column nx−1−xn_x - 1 - x and the bin bb to the bin B−1−bB - 1 - b.
  • With ε=0\varepsilon = 0, the L2-Hys output has norm 1 and does not change when the block is multiplied by a>0a > 0. With ε>0\varepsilon > 0 the change is small for blocks with a norm much larger than ε\varepsilon.

That HOG with a linear SVM detects people well is a benchmark result. Dalal and Triggs report miss rates at 10−410^{-4} false positives per window on their INRIA set of 1805 images of people of 64×12864 \times 128 pixels and on the MIT set.

Proof: Correctness of the histogram of oriented gradientsfull

Let II be a window with WW columns and HH rows, cc the cell size, BB the number of bins, nx=⌊W/c⌋n_x = \lfloor W / c \rfloor and ny=⌊H/c⌋n_y = \lfloor H / c \rfloor. The gradient, the magnitude mm, the unsigned angle φ∈[0°,180°)\varphi \in [0°, 180°) and the voting are as defined on the page, with the image extended by its edge pixels at the border. Let w=180°/Bw = 180° / B.

Lemma 1 (orientation weights). For each φ∈[0°,180°)\varphi \in [0°, 180°), line L3 gives two bins b0b_0 and b1=b0+1 mod Bb_1 = b_0 + 1 \bmod B with weights 1−f1 - f and ff, where f∈[0,1)f \in [0, 1). These are the two bins whose centers on the circle of 180 degrees are nearest to φ\varphi, and the weight of each bin is 1−d/w1 - d / w, where dd is the circular distance from φ\varphi to its center.

Proof. Let x=φ/w−12x = \varphi / w - \frac{1}{2}, k=⌊x⌋k = \lfloor x \rfloor and f=x−k∈[0,1)f = x - k \in [0, 1). The centers of the bins kk and k+1k + 1 are (k+12)w(k + \frac12) w and (k+32)w(k + \frac32) w, and φ=(k+12+f)w\varphi = (k + \frac12 + f) w lies between them, at the distance fwf w from the first and (1−f)w(1 - f) w from the second. Since x∈[−12,B−12)x \in [-\frac12, B - \frac12), kk is in {−1,…,B−1}\{-1, \dots, B - 1\}; taking kk and k+1k + 1 modulo BB maps the centers −12w-\frac12 w and (B+12)w(B + \frac12) w to the centers (B−12)w(B - \frac12) w and 12w\frac12 w, which are the same points on the circle of length Bw=180°B w = 180°. All other centers are at a distance of at least ww. So the weights 1−f=1−fw/w1 - f = 1 - f w / w and f=1−(1−f)w/wf = 1 - (1 - f) w / w are as claimed, and they are nonnegative and sum to 1. □\square

Lemma 2 (conservation of the votes). Without spatial voting, each pixel inside the nxc×nycn_x c \times n_y c grid adds exactly mm to the histogram of its cell. With spatial voting, a pixel (u,v)(u, v) whose coordinates x=(u+12)/c−12x = (u + \frac12)/c - \frac12 and y=(v+12)/c−12y = (v + \frac12)/c - \frac12 lie in [0,nx−1]×[0,ny−1][0, n_x - 1] \times [0, n_y - 1] adds exactly mm to the cells in total, and every other pixel adds between 0 and mm.

Proof. Without spatial voting, the pixel adds m(1−f)+mf=mm (1 - f) + m f = m to its cell by Lemma 1. With spatial voting, it adds m wywxwbm \, w_y w_x w_b for the cell weights wy∈{1−fy,fy}w_y \in \{1 - f_y, f_y\}, wx∈{1−fx,fx}w_x \in \{1 - f_x, f_x\} and the bin weights wbw_b. The sum over all four cells and both bins is m(1−fy+fy)(1−fx+fx)(1−f+f)=mm (1 - f_y + f_y)(1 - f_x + f_x)(1 - f + f) = m. If xx and yy are in the given range, the cells ⌊x⌋\lfloor x \rfloor, ⌊x⌋+1\lfloor x \rfloor + 1 (when its weight is nonzero) and the same in yy 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 mm. □\square

Lemma 3 (offset and negation). Let I′(u,v)=a+sI(u,v)I'(u, v) = a + s I(u, v) with a constant aa and s∈{1,−1}s \in \{1, -1\}. Then I′I' has the same magnitudes and unsigned angles as II, so the same cell histograms and the same descriptor.

Proof. Each gradient component is a difference of two pixel values, so gu′=sgug'_u = s g_u and gv′=sgvg'_v = s g_v, and the magnitude does not change. If s=−1s = -1, the vector (gu,gv)(g_u, g_v) turns by 180°180° when it is not zero, so atan2⁡\operatorname{atan2} changes by ±180°\pm 180°, and the angle modulo 180°180° does not change. Pixels with a zero gradient add nothing in both cases. So the cell histograms are equal, and so are the blocks. □\square

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 atan2⁡\operatorname{atan2}.

Lemma 4 (mirror). Let I′(u,v)=I(W−1−u,v)I'(u, v) = I(W - 1 - u, v) with W=nxcW = n_x c. Then the cell histograms satisfy hy,x′(b)=hy,nx−1−x(B−1−b)h'_{y, x}(b) = h_{y, n_x - 1 - x}(B - 1 - b).

Proof. At the pixel (u,v)(u, v) of I′I', the gradient is (−gu,gv)(-g_u, g_v) of II at (W−1−u,v)(W - 1 - u, v); the edge extension commutes with the mirror. The magnitude is the same. The angle of (−gu,gv)(-g_u, g_v) is 180°−φ180° - \varphi modulo 180°180°. The bin centers (b+12)w(b + \frac12) w map to 180°−(b+12)w=(B−1−b+12)w180° - (b + \frac12) w = (B - 1 - b + \frac12) w, so the circular distances from 180°−φ180° - \varphi to the center of B−1−bB - 1 - b equal those from φ\varphi to the center of bb, and by Lemma 1 the bin weights move from bb to B−1−bB - 1 - b. In space, x′=(W−1−u+12)/c−12=nx−1−xx' = (W - 1 - u + \frac12)/c - \frac12 = n_x - 1 - x, so the bilinear weight of the cell nx−1−x0n_x - 1 - x_0 for the mirrored pixel equals the weight of the cell x0x_0 for the original pixel. Summing over the pixels gives the claim. □\square

Lemma 5 (L2-Hys). Let z=L2-Hys(x)z = \text{L2-Hys}(x) with ε=0\varepsilon = 0, the clip value τ>0\tau > 0 and x≠0x \ne 0 with nonnegative entries. Then ∥z∥2=1\lVert z \rVert_2 = 1, and L2-Hys(ax)=z\text{L2-Hys}(a x) = z for every a>0a > 0.

Proof. After the first division y=x/∥x∥2y = x / \lVert x \rVert_2, which does not change when xx is replaced by axa x. The clip gives yk′=min⁡(yk,τ)y'_k = \min(y_k, \tau), which is not the zero vector because some yk>0y_k > 0 and τ>0\tau > 0. The second division gives a vector of norm 1. Each step depends only on yy, so the output does not depend on aa. □\square

With ε>0\varepsilon > 0, the first step gives x/∥x∥2+ε2x / \sqrt{\lVert x \rVert^2 + \varepsilon^2}, which differs from x/∥x∥x / \lVert x \rVert by a factor 1/1+ε2/∥x∥21 / \sqrt{1 + \varepsilon^2 / \lVert x \rVert^2}, close to 1 when ∥x∥≫ε\lVert x \rVert \gg \varepsilon; this is why a gain changes the descriptor only a little.

Theorem. HOG returns the concatenation, over the (nx−1)(ny−1)(n_x - 1)(n_y - 1) blocks of 2×22 \times 2 cells in row order, of the L2-Hys normalized cell histograms of the definition. The length is 4B(nx−1)(ny−1)4 B (n_x - 1)(n_y - 1). The descriptor does not change under a constant offset or under I↦a−II \mapsto a - I, and, with ε=0\varepsilon = 0, each block has norm 1 and does not change when the window is multiplied by a>0a > 0.

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 (nx−1)(ny−1)(n_x - 1)(n_y - 1) blocks; line L6 joins four histograms of BB values, and line L7 normalizes them, which gives the length. Lemma 3 gives the invariance to an offset and to negation. Multiplying II by aa multiplies every magnitude by aa and keeps every angle, so every block vector is multiplied by aa, and Lemma 5 gives the last claim. □\square

Complexity

The model is the real RAM, with the square root, atan2 and the floor in O(1)O(1) time.

  • Lines L1 and L2 take O(WH)O(W H) time.
  • Lines L3 and L4 take O(1)O(1) time per pixel, with 2 bins and at most 4 cells, so O(WH)O(W H) in total.
  • There are about (W/c)(H/c)(W/c)(H/c) blocks of 4B4B values. Lines L5 to L7 take O(WHB/c2)O(W H B / c^2) time.

The total time is O(WH+WHB/c2)O(W H + W H B / c^2), and the extra space is O(WH)O(W H) for the gradients and O(WHB/c2)O(W H B / c^2) 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 c×cc \times c 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, x/(∥x∥1+ε)\sqrt{x / (\lVert x \rVert_1 + \varepsilon)}. 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 O(1)O(1) 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 σ=2\sigma = 2 the recall at 10−410^{-4} false positives per window fell from 89 percent to 80 percent. The simple [−1,0,1][-1, 0, 1] mask worked best; the Sobel mask and larger masks did worse.
  • Unsigned angles. atan2⁡\operatorname{atan2} gives angles in (−180°,180°](-180°, 180°]. Fold them into [0°,180°)[0°, 180°), and treat the bins as a circle, or angles near 0 and 180 go to different ends.
  • Bin centers. Centers at (b+12) 20°(b + \frac12)\,20° and centers at b⋅20°b \cdot 20° 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 64×12864 \times 128 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.

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

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

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