Algorithmcore
Dalal-Triggs pedestrian detector
Also called HOG-SVM detector.
Detect people by a linear SVM on HOG descriptors of sliding windows over an image pyramid, with hard negative mining during training.
- Solves
- Object detection
- Time
- O(m d + k^2) worst · averageO(m d) best
- Space
- O(m + d) extra
- Where
- d = the length of the HOG vector of one window (3780 by default); k = the number of windows that score above the threshold; m = the number of pixels of the input image
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Navneet Dalal, Bill Triggs, 2005
The Dalal-Triggs detector finds people in an image by scoring every window of a fixed size, at every position and scale, with a linear support vector machine on a histogram of oriented gradients (HOG) of the window. Windows that score above a threshold are reported as boxes, and non-maximum suppression merges the boxes around each person. Dalal and Triggs (2005) studied each step of this chain on a new data set of people in varied poses and backgrounds, and the default settings they found became a standard for sliding-window detection until convolutional networks replaced it.
In plain words
A person in a photo has a typical outline: a round head, two shoulders, a vertical body and legs. The detector does not look at colours or exact brightness. It cuts the window into small squares and, for each square, counts in which directions the edges run. A person gives many vertical edges on both sides of the body and curved edges at the head and shoulders, in about the same squares every time.
These counts go into a simple scoring rule learned from thousands of pictures with and without people. The detector slides the window over the image, and over smaller copies of the image to find larger people, and reports the places where the score is high. Training adds a second pass: it looks for the background windows that the first rule wrongly scored high, adds them to the training set, and learns the rule again.
The problem
The input is an image and a trained model: a window of pixels (64 by 128 for people), the HOG parameters, a weight vector and a bias . The output is a list of boxes with scores, one box for each person that the detector finds. Training takes a set of positive windows, each with one centred person, and a set of images with no people. This is an instance of object detection for one class.
The algorithm
DETECT(I, w, b, τ)- 1
for each level of the image pyramid of I, with scale σ do - 2
compute the gradient of every pixel with the masks [-1, 0, 1] and its transpose - 3
vote each magnitude into 9 orientation bins over 0 to 180 degrees of its cells, bilinear in angle and position - 4
normalize every block of 2 × 2 cells with L2-Hys - 5
for each window position p on the cell grid do - 6
f ← w · φ(p) + b ▷ φ = the blocks of the window, in order - 7
if f > τ then add the box of p, scaled by σ, with the score f - 8
K ← GREEDY-NMS of the added boxes - 9
return K TRAIN(P, N, r) ▷ P: person windows, N: images without people- 10
X ← HOG of every window in P and of its mirror image, label +1 - 11
add HOG of random windows of N, label -1 - 12
(w, b) ← linear SVM on X - 13
repeat r times ▷ Dalal and Triggs use one round - 14
H ← every window of every level of N with w · φ + b > -1 - 15
add H to X with label -1, (w, b) ← linear SVM on X - 16
return (w, b)
The default chain of the paper is as follows. Pixels are RGB with no gamma correction; for each pixel the gradient of the colour channel with the largest magnitude is used. Gradients use the centred masks with no smoothing. The orientation is unsigned and goes into 9 bins over 0 to 180 degrees. Cells have pixels and blocks have cells, with a stride of 8 pixels, so each cell is in four blocks. Each block is weighted with a Gaussian window of pixels and normalized with L2-Hys: an L2 normalization , a clip of every entry at 0.2, and a second L2 normalization. The window has pixels, and the classifier is a linear soft-margin SVM (SVMLight with ).
Line L14 uses the margin : a background window is "hard" when the SVM does not push it past the margin. Dalal and Triggs search the negative images exhaustively for false positives and train once more on the enlarged set.
Example
The size of the vector. A window of pixels has cells, so blocks. Each block has entries, and has entries. At scale 1, a image has window positions on the cell grid; the smaller levels of the pyramid add more.
One vote. A pixel at column 10 and row 5, with cells of 8 pixels and the gradient , has the magnitude 5 and the angle degrees. The bin centres are at degrees, so the angle is of the way from the centre of bin 2 (50 degrees) to the centre of bin 3 (70 degrees). The pixel centre is at , and the cell centres are at in each axis, so the pixel is of the way from cell column 0 to cell column 1 and of the way from cell row 0 to cell row 1. The pixel adds to the cell in row 0 and column 1, split as to bin 2 and to bin 3, and smaller amounts to the three other cells. The eight weights sum to 1.
One block. If a block before normalization were , L2 normalization gives , the clip gives , and the second normalization gives . The clip stops one strong edge from taking over the whole block.
Correctness
A detector has no correctness theorem: its error rate is measured on a test set. The correctness file proves what the program computes. The vector has entries, 3780 for the default window. Each pixel inside the grid gives its full magnitude to the histograms, with the tent weights of trilinear interpolation. The HOG vector does not change when the image brightness is changed by with , up to the effect of . The scan of lines L5 to L7 scores every window position of every level. For mining, the argument of Felzenszwalb et al. (2010) shows that when no negative outside the training cache violates the margin, the SVM on the cache is the SVM on all negatives, so repeated mining reaches the SVM of the whole negative set; one round, as in the paper, does not guarantee this.
Proof: The detector scores every window of the pyramid, its HOG vector has the stated size and invariances, and mining reaches the SVM of all negativesfull
We use the notation of the page. A pyramid level is a gray image with whole cells of pixels; the window has cells; the histograms have orientation bins of width degrees; a block is cells and blocks start at every cell. The detector is a linear function of the HOG vector of a window . A detector is not "correct" in the sense of a theorem: its error rate is a benchmark result. What can be proved is that the program computes the function that the page describes, and that its training loop reaches the SVM that it claims to reach.
Claim 1 (the size of the vector). has entries. For the default window of pixels, and , this is .
Proof. Blocks start at every cell whose block of cells lies inside the window, so there are block columns and block rows. Each block is the concatenation of four histograms of entries.
Claim 2 (the votes). Every pixel whose centre lies at least half a cell from the border of the cell grid adds exactly its gradient magnitude to the sum of all histogram entries. Its vote goes to at most two bins and at most four cells, with the bilinear (tent) weights in each spatial axis and in angle, where is the circular distance from the angle of the pixel to the bin centre.
Proof. In the axis, write and , . The cell centres and are the two nearest centres to the pixel centre , at distances and , and the code gives them the weights and , which are the tent weights; every other cell centre is at least away and has tent weight 0. The same holds in the axis and, with the circular distance on , in angle, where the index is taken modulo . The three pairs of weights each sum to 1, so the eight products sum to 1. When the pixel is at least half a cell inside the grid, both cell neighbours in each axis exist, and no vote is dropped.
The tests compare the code with a direct sum of the three tent functions over all pixels, cells and bins, which is the definition of the trilinear vote and shares no index arithmetic with the code.
Claim 3 (contrast). If every pixel value is replaced by with , every block vector before normalization is multiplied by , and with the normalized block vector, and so , does not change. With the change is at most of the order of in each block.
Proof. The centred differences cancel and scale by , so the angles do not change and the magnitudes scale by . The votes are linear in the magnitude. L2-Hys divides by the norm, clips at , and divides by the norm again; for each step maps to the same vector as , because . With the factor differs from by a relative amount of order .
Claim 4 (the scan is exhaustive). For each pyramid level, line L5 of DETECT visits every window position on the cell grid, of them, and line L6 computes with equal to the HOG vector of that window, computed as if the window were cut out of the level with its surrounding pixels.
Proof. The loops of line L5 range over all top-left cells with the window inside the grid. The block grid of line L4 is computed once for the whole level, and the window reads the blocks that start inside it, in the same order as Claim 1. Each block depends only on its four cells, and each cell histogram only on the pixels within one cell of it, so the vector is that of the window in its surroundings. It differs from the vector of the window cut out alone only in the outer half cell, where the cut-out window would repeat its own border pixels; this is why the tests compare shifted crops only away from the crop borders.
Claim 5 (mining). Let be a finite pool of negative windows, the positives, and for a set let be the minimizer of
with and the bias as an extra feature. If no has , then . The loop of TRAIN-WITH-MINING that adds all such and trains again stops after at most rounds with .
Proof. is strictly convex because of the term , so it has one minimizer. For every , , since adds nonnegative terms. Under the hypothesis, every has at and adds , so . Then for every , , so minimizes , and by uniqueness it is . Each round that does not stop adds at least one new element of to the cache, so there are at most such rounds, and the round that stops meets the hypothesis. This is the argument of Felzenszwalb et al. (2010), Section 4.4.
With an approximate solver, the result is up to the tolerance of the solver; the tests check the duality gap of the solver and compare the mined SVM with the SVM on the whole pool. The detector of Dalal and Triggs makes one round of mining, so it does not reach the hypothesis of Claim 5 in general, and its SVM is only the SVM of the cache.
Claim 6 (the output). Line L8 returns the boxes of greedy non-maximum suppression, so no two kept boxes overlap with IoU above the threshold, and every window above the score threshold is either kept or overlaps a kept box with a higher score above the threshold. This is the correctness claim of box non-maximum suppression.
Cost. For a level of pixels, lines L2 and L3 cost (a constant number of votes per pixel), line L4 costs , and lines L5 to L7 cost windows times for each dot product. A pyramid with scale step has a total of at most pixels, so the whole scan is for the votes and for the scores. Line L8 adds the cost of greedy NMS on the windows above the threshold.
Complexity
For an image of pixels, lines L2 and L3 do a constant amount of work per pixel, , and line L4 is smaller. There are window positions per level, and each dot product costs , so the scores cost in the real RAM, with for the default cells. A pyramid with scale step has at most times as many pixels as the image, a constant factor. Line L8 costs in the worst case for boxes above the threshold. The dot products dominate: for each window the cost is the 3780 multiplications of the default vector. The vector of a window is never stored on its own; the block grid of each level takes space. Dalal and Triggs report that their implementation needs less than a second for a image with about 4000 windows (2005 hardware). Training costs one SVM solve on the initial set, a scan of all negative images, and a second solve.
Properties
- Deterministic. The detector is a fixed function of the image and the model.
- Linear in the features. The score is a dot product, so the detector can be written as a filter: each block of is a template that is correlated with the block grid. The deformable part model uses this view.
- Invariant to contrast up to , by the block normalization.
- Not invariant to rotation or aspect ratio. The window is upright with a fixed shape. People who lie down, or who are partly hidden, score low.
- Dense and overlapping. Each cell is in four blocks with different normalizations, and the paper finds that this overlap improves the results.
- Each step was chosen by experiment. The paper reports the effect of each change on the miss rate at false positives per window (FPPW), on the INRIA test set. These choices are benchmark results, not theorems.
Variants and improvements
- Mean-shift fusion. Dalal's thesis (2006) fuses detections by finding modes in position and scale with mean shift instead of the greedy suppression of line L8.
- Faster features. Computing the cell grid once per level, as the code of this page does, and integral histograms make the scan much faster than computing each window alone.
- Cascades. A cascade of HOG classifiers on blocks of different sizes, in the style of the Viola-Jones detector, rejects most windows after a few blocks.
- Parts. The deformable part model of Felzenszwalb et al. adds parts at twice the resolution on springs, mixtures of models for different views, a latent SVM, and a 31-dimensional variant of HOG.
- Learned features. R-CNN and later detectors replace HOG and the linear SVM with convolutional features and a network head.
When to use it
Use it for a rigid, mostly upright object class with a typical outline, such as pedestrians, and when a small, fast, explainable detector is enough, for example on hardware without a GPU or as a baseline. It needs only a few thousand labelled windows. For many classes, large changes of pose, or strong occlusion, use a part-based model or a convolutional detector.
Pitfalls
- Smoothing the image. The paper finds that Gaussian smoothing before the gradient makes the results worse; the plain mask is the best of the masks it tests.
- Too few bins or signed orientation. Fewer than about 9 bins loses shape information, and for people the sign of the gradient carries little information, because clothes and background can be lighter or darker.
- Skipping hard negatives. The paper reports a gain of 5 percent in miss rate at FPPW from one round of retraining on hard examples. Without it, the classifier sees too few of the background patterns that look like people.
- Window margin. The positive windows keep a band of background around the person. The paper finds that a smaller margin makes the detector worse, because the outline of the body against the background is the signal.
- Comparing curves. DET curves per window and precision-recall curves per image measure different things; detection mean average precision depends on NMS and on the matching rule, a per-window curve does not.
- Scale range. The smallest person that can be found is the window size; people smaller than 64 by 128 pixels need an upsampled level of the pyramid.
Implementations
The Python code implements the chain on gray images: centred gradients with repeated borders, trilinear voting into 9 unsigned bins, -cell blocks with L2-Hys, a cell grid per pyramid level with bilinear downsampling, a linear SVM trained by dual coordinate descent with the bias as an extra feature, hard-negative mining, and greedy NMS. It leaves out the colour channel choice and the Gaussian block window. The tests check the 3780 entries of the default vector, the bins of ramps at 0, 45 and 90 degrees, the voting against a direct sum of tent functions, L2-Hys, the invariance to brightness and contrast, the duality gap of the SVM, the equality of mined training with training on all negatives, the shift of the score map by whole cells, and the detection of a synthetic object at two scales.
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/dalal-triggs-detector/. The authors are listed in prov/7BC4KB.jsonl.
"""The Dalal-Triggs detector: HOG features, a linear SVM, a sliding window
over an image pyramid, hard-negative mining, and greedy non-maximum
suppression.
An image is a list of rows of floats (gray levels). The HOG part follows the
default chain of Dalal and Triggs (2005): centred [-1, 0, 1] gradients,
unsigned orientation in `bins` bins over 0 to 180 degrees, each pixel voting
with its gradient magnitude bilinearly in orientation and in position into
the four nearest cells, blocks of 2 x 2 cells with a stride of one cell, and
L2-Hys normalization of each block. Two simplifications: one gray channel
instead of the colour channel with the largest gradient, and no Gaussian
weight inside a block. The cell grid of a pyramid level is computed once,
and every window reads its blocks from it, so windows move in steps of one
cell. The SVM is trained by dual coordinate descent on the hinge loss.
Standard library only.
"""
import math
import random
# ----------------------------------------------------------------- HOG part
def gradients(img):
"""Centred differences with the border pixel repeated."""
h, w = len(img), len(img[0])
gx = [[img[y][min(x + 1, w - 1)] - img[y][max(x - 1, 0)] for x in range(w)] for y in range(h)]
gy = [[img[min(y + 1, h - 1)][x] - img[max(y - 1, 0)][x] for x in range(w)] for y in range(h)]
return gx, gy
def cell_histograms(img, cell=8, bins=9):
"""Orientation histograms of the cells of the image (whole cells only).
A pixel at (x, y) has its centre at (x + 0.5, y + 0.5); it votes its
gradient magnitude into the two nearest orientation bins and the four
nearest cell centres with bilinear weights. Votes for cells outside the
grid are dropped.
"""
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)]
gx, gy = gradients(img) # @line L2
width = 180.0 / bins
for y in range(ny * cell):
ty = (y + 0.5) / cell - 0.5
cy0 = math.floor(ty)
fy = ty - cy0
for x in range(nx * cell):
dx, dy = gx[y][x], gy[y][x]
mag = math.hypot(dx, dy)
if mag == 0.0:
continue
ang = math.degrees(math.atan2(dy, dx)) % 180.0
t = ang / width - 0.5
b0 = math.floor(t)
fb = t - b0
b1 = (b0 + 1) % bins
b0 %= bins
tx = (x + 0.5) / cell - 0.5
cx0 = math.floor(tx)
fx = tx - cx0
for cy, wy in ((cy0, 1.0 - fy), (cy0 + 1, fy)):
if wy == 0.0 or not 0 <= cy < ny:
continue
row = hist[cy]
for cx, wx in ((cx0, 1.0 - fx), (cx0 + 1, fx)):
if wx == 0.0 or not 0 <= cx < nx:
continue
v = mag * wy * wx
hc = row[cx]
hc[b0] += v * (1.0 - fb) # @line L3
hc[b1] += v * fb
return hist
def l2_hys(v, clip=0.2, eps=1e-3):
"""L2 norm, clip every entry at `clip`, L2 norm again."""
n = math.sqrt(sum(a * a for a in v) + eps * eps)
u = [min(a / n, clip) for a in v]
n = math.sqrt(sum(a * a for a in u) + eps * eps)
return [a / n for a in u]
def block_grid(hist, clip=0.2, eps=1e-3):
"""Normalized 2 x 2 blocks of cells with a stride of one cell."""
ny, nx = len(hist), len(hist[0]) if hist else 0
return [[l2_hys(hist[by][bx] + hist[by][bx + 1] + hist[by + 1][bx] + hist[by + 1][bx + 1], clip, eps)
for bx in range(nx - 1)] for by in range(ny - 1)]
def window_vector(blocks, by, bx, wcells, hcells):
"""The HOG vector of the window whose top-left cell is (by, bx)."""
v = []
for i in range(hcells - 1):
row = blocks[by + i]
for j in range(wcells - 1):
v.extend(row[bx + j])
return v
def hog_descriptor(img, cell=8, bins=9):
"""HOG vector of a whole window image."""
blocks = block_grid(cell_histograms(img, cell, bins))
return window_vector(blocks, 0, 0, len(img[0]) // cell, len(img) // cell)
def descriptor_length(width, height, cell=8, bins=9):
return (width // cell - 1) * (height // cell - 1) * 4 * bins
# --------------------------------------------------------------- images
def mirror(img):
return [list(reversed(row)) for row in img]
def downscale(img, s):
"""Resize by 1/s with bilinear sampling at pixel centres."""
h, w = len(img), len(img[0])
nh, nw = int(round(h / s)), int(round(w / s))
out = []
for y in range(nh):
sy = min(max((y + 0.5) * s - 0.5, 0.0), h - 1.0)
y0 = int(sy)
y1 = min(y0 + 1, h - 1)
fy = sy - y0
r0, r1 = img[y0], img[y1]
row = []
for x in range(nw):
sx = min(max((x + 0.5) * s - 0.5, 0.0), w - 1.0)
x0 = int(sx)
x1 = min(x0 + 1, w - 1)
fx = sx - x0
top = r0[x0] * (1 - fx) + r0[x1] * fx
bot = r1[x0] * (1 - fx) + r1[x1] * fx
row.append(top * (1 - fy) + bot * fy)
out.append(row)
return out
def pyramid(img, min_w, min_h, step=1.2):
"""Yield (scale, image) from scale 1 up, while the window still fits."""
s = 1.0
while True:
level = img if s == 1.0 else downscale(img, s)
if not level or len(level) < min_h or len(level[0]) < min_w:
return
yield s, level
s *= step
# ------------------------------------------------------------ linear SVM
def dot(a, b):
return sum(p * q for p, q in zip(a, b))
def train_linear_svm(X, y, C=0.01, bias=1.0, tol=1e-6, max_epochs=2000, seed=0):
"""Hinge-loss linear SVM, min 0.5 |w|^2 + C sum max(0, 1 - y (w.x + b)),
with the bias as an extra feature of value `bias` (so it is regularized),
by dual coordinate descent. Returns (w, b, alpha).
"""
Xa = [list(x) + [bias] for x in X]
n = len(Xa)
d = len(Xa[0]) if n else 1
q = [dot(x, x) for x in Xa]
alpha = [0.0] * n
w = [0.0] * d
rng = random.Random(seed)
order = list(range(n))
for _ in range(max_epochs):
rng.shuffle(order)
lo, hi = math.inf, -math.inf
for i in order:
g = y[i] * dot(w, Xa[i]) - 1.0
a = alpha[i]
pg = min(g, 0.0) if a == 0.0 else (max(g, 0.0) if a == C else g)
lo, hi = min(lo, pg), max(hi, pg)
if pg != 0.0 and q[i] > 0.0:
new = min(max(a - g / q[i], 0.0), C)
if new != a:
step = (new - a) * y[i]
xi = Xa[i]
for k in range(d):
w[k] += step * xi[k]
alpha[i] = new
if n == 0 or hi - lo < tol:
break
return w[:-1], w[-1] * bias, alpha
def primal_objective(w, b, X, y, C, bias=1.0):
reg = 0.5 * (dot(w, w) + (b / bias) ** 2)
return reg + C * sum(max(0.0, 1.0 - yi * (dot(w, x) + b)) for x, yi in zip(X, y))
def dual_objective(alpha, X, y, bias=1.0):
d = len(X[0]) + 1
v = [0.0] * d
for a, x, yi in zip(alpha, X, y):
for k, xk in enumerate(list(x) + [bias]):
v[k] += a * yi * xk
return sum(alpha) - 0.5 * dot(v, v)
def train_with_mining(pos, neg_pool, start, C=0.01, rounds=None, tol=1e-6):
"""Train on the positives and a cache of negatives; add every negative of
the pool that violates the margin (score above -1) and is not cached;
repeat until there is none (or for `rounds` rounds). Returns (w, b, cache).
"""
cache = sorted(set(start))
r = 0
while True:
X = pos + [neg_pool[i] for i in cache]
y = [1] * len(pos) + [-1] * len(cache)
w, b, _ = train_linear_svm(X, y, C, tol=tol)
if rounds is not None and r == rounds:
return w, b, cache
have = set(cache)
hard = [i for i, x in enumerate(neg_pool) if i not in have and dot(w, x) + b > -1.0]
if not hard:
return w, b, cache
cache = sorted(have | set(hard))
r += 1
# -------------------------------------------------------------- detection
def iou(a, b):
iw = min(a[2], b[2]) - max(a[0], b[0])
ih = min(a[3], b[3]) - max(a[1], b[1])
inter = iw * ih if iw > 0 and ih > 0 else 0
union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
return inter / union if union > 0 else 0
def greedy_nms(boxes, scores, threshold=0.5):
order = sorted(range(len(boxes)), key=lambda i: (-scores[i], i))
keep, removed = [], [False] * len(boxes)
for pos, i in enumerate(order):
if removed[i]:
continue
keep.append(i)
for j in order[pos + 1:]:
if not removed[j] and iou(boxes[i], boxes[j]) > threshold:
removed[j] = True
return keep
class Model:
def __init__(self, w, b, wcells, hcells, cell=8, bins=9):
self.w, self.b = w, b
self.wcells, self.hcells, self.cell, self.bins = wcells, hcells, cell, bins
def scan_level(level, model):
"""Scores of every window position of one pyramid level, as a dict
(cell row, cell column) -> score."""
hist = cell_histograms(level, model.cell, model.bins)
blocks = block_grid(hist)
out = {}
ny, nx = len(hist), len(hist[0]) if hist else 0
for by in range(ny - model.hcells + 1):
for bx in range(nx - model.wcells + 1):
v = window_vector(blocks, by, bx, model.wcells, model.hcells)
out[(by, bx)] = dot(model.w, v) + model.b
return out
def detect(img, model, threshold=0.0, step=1.2, nms_threshold=0.5):
"""Return a list of (box, score), box = (x1, y1, x2, y2) in the input image."""
cw, ch = model.wcells * model.cell, model.hcells * model.cell
boxes, scores = [], []
for s, level in pyramid(img, cw, ch, step): # @line L1
hist = cell_histograms(level, model.cell, model.bins)
blocks = block_grid(hist) # @line L4
ny, nx = len(hist), len(hist[0])
for by in range(ny - model.hcells + 1): # @line L5
for bx in range(nx - model.wcells + 1):
v = window_vector(blocks, by, bx, model.wcells, model.hcells)
f = dot(model.w, v) + model.b # @line L6
if f > threshold: # @line L7
x1, y1 = bx * model.cell * s, by * model.cell * s
boxes.append((x1, y1, x1 + cw * s, y1 + ch * s))
scores.append(f)
keep = greedy_nms(boxes, scores, nms_threshold) # @line L8
return [(boxes[i], scores[i]) for i in keep] # @line L9
def negative_windows(images, model, rng, count):
"""Random windows of the negative images, at random pyramid levels."""
cw, ch = model.wcells * model.cell, model.hcells * model.cell
out = []
levels = [lv for img in images for _, lv in pyramid(img, cw, ch)]
for _ in range(count):
lv = rng.choice(levels)
y = rng.randrange(len(lv) - ch + 1)
x = rng.randrange(len(lv[0]) - cw + 1)
out.append(hog_descriptor([row[x:x + cw] for row in lv[y:y + ch]], model.cell, model.bins))
return out
def hard_negatives(images, model, step=1.2):
"""HOG vectors of all windows of the negative images with a score above -1."""
cw, ch = model.wcells * model.cell, model.hcells * model.cell
out = []
for img in images:
for _, level in pyramid(img, cw, ch, step):
hist = cell_histograms(level, model.cell, model.bins)
blocks = block_grid(hist)
for by in range(len(hist) - model.hcells + 1):
for bx in range(len(hist[0]) - model.wcells + 1):
v = window_vector(blocks, by, bx, model.wcells, model.hcells)
if dot(model.w, v) + model.b > -1.0:
out.append(v)
return out
def train_detector(pos_windows, neg_images, cell=8, bins=9, C=0.01, n_random=100,
rounds=1, seed=0, tol=1e-3):
"""Train a detector from positive window images and negative images.
Positives are used with their mirror images. The first SVM sees random
negative windows; each round then adds every window of the negative
images with a score above -1 and trains again.
"""
rng = random.Random(seed)
hc, wc = len(pos_windows[0]) // cell, len(pos_windows[0][0]) // cell
model = Model(None, 0.0, wc, hc, cell, bins)
pos = [hog_descriptor(p, cell, bins) for p in pos_windows] # @line L10
pos += [hog_descriptor(mirror(p), cell, bins) for p in pos_windows]
neg = negative_windows(neg_images, model, rng, n_random) # @line L11
X, y = pos + neg, [1] * len(pos) + [-1] * len(neg)
model.w, model.b, _ = train_linear_svm(X, y, C, tol=tol) # @line L12
for _ in range(rounds): # @line L13
hard = hard_negatives(neg_images, model) # @line L14
if not hard:
break
X, y = X + hard, y + [-1] * len(hard) # @line L15
model.w, model.b, _ = train_linear_svm(X, y, C, tol=tol)
return model # @line L16
test_dalal_triggs_detector.py 213 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dalal-triggs-detector/. The authors are listed in prov/7BC4KB.jsonl.
import math
import random
from dalal_triggs_detector import (Model, block_grid, cell_histograms, descriptor_length, detect,
dot, downscale, dual_objective, gradients, hog_descriptor,
iou, l2_hys, primal_objective, scan_level, train_detector,
train_linear_svm, train_with_mining)
def noise(rng, h, w, top=0.3):
return [[rng.random() * top for _ in range(w)] for _ in range(h)]
def paste(img, x, y, w, h, v=1.0):
for yy in range(y, y + h):
for xx in range(x, x + w):
img[yy][xx] = v
def close(a, b, tol=1e-9):
return all(abs(p - q) <= tol for p, q in zip(a, b)) and len(a) == len(b)
def test_default_descriptor_length_is_3780():
assert descriptor_length(64, 128) == 7 * 15 * 36 == 3780
rng = random.Random(1)
img = noise(rng, 128, 64, 1.0)
assert len(hog_descriptor(img)) == 3780
def test_orientation_bins():
# A ramp along y has gradient angle 90 degrees, the centre of bin 4.
ramp_y = [[float(y) for x in range(16)] for y in range(16)]
for row in cell_histograms(ramp_y, 8, 9):
for h in row:
assert h[4] > 0 and all(h[b] == 0 for b in range(9) if b != 4)
# A ramp along x has angle 0, half way between the centres of bins 8
# and 0 (10 and 170 degrees): the vote is split equally, with wrap-around.
ramp_x = [[float(x) for x in range(16)] for y in range(16)]
for row in cell_histograms(ramp_x, 8, 9):
for h in row:
assert abs(h[0] - h[8]) < 1e-9 and h[0] > 0 and sum(h[1:8]) == 0
# 45 degrees: t = 45 / 20 - 0.5 = 1.75, so bin 2 gets 3 times bin 1.
# Only the middle cell is checked: the repeated border pixels have
# another angle, and they vote only into the outer cells.
diag = [[float(x + y) for x in range(24)] for y in range(24)]
h = cell_histograms(diag, 8, 9)[1][1]
assert abs(h[2] - 3 * h[1]) < 1e-9 and h[1] > 0 and h[0] == 0 and sum(h[3:]) == 0
def reference_histograms(img, cell, bins):
"""Trilinear voting written with tent functions, pixel by cell by bin."""
h, w = len(img), len(img[0])
ny, nx = h // cell, w // cell
gx, gy = gradients(img)
width = 180.0 / bins
out = [[[0.0] * bins for _ in range(nx)] for _ in range(ny)]
for y in range(ny * cell):
for x in range(nx * cell):
mag = math.hypot(gx[y][x], gy[y][x])
if mag == 0:
continue
ang = math.degrees(math.atan2(gy[y][x], gx[y][x])) % 180.0
for cy in range(ny):
wy = max(0.0, 1 - abs((y + 0.5) - (cy + 0.5) * cell) / cell)
for cx in range(nx):
wx = max(0.0, 1 - abs((x + 0.5) - (cx + 0.5) * cell) / cell)
for b in range(bins):
d = abs(ang - (b + 0.5) * width)
d = min(d, 180.0 - d)
wb = max(0.0, 1 - d / width)
out[cy][cx][b] += mag * wy * wx * wb
return out
def test_cell_histograms_match_tent_reference():
rng = random.Random(2)
for trial in range(3):
img = noise(rng, 12, 16, 1.0)
got = cell_histograms(img, 4, 9)
ref = reference_histograms(img, 4, 9)
for r1, r2 in zip(got, ref):
for h1, h2 in zip(r1, r2):
assert close(h1, h2, 1e-9)
def test_l2_hys():
v = l2_hys([3.0, 1.0, 0.0, 0.0], eps=0.0)
assert close(v, [math.sqrt(0.5), math.sqrt(0.5), 0.0, 0.0], 1e-12)
rng = random.Random(3)
for trial in range(50):
u = [rng.random() for _ in range(36)]
a = l2_hys(u, eps=1e-9)
b = l2_hys([7.5 * x for x in u], eps=1e-9)
assert close(a, b, 1e-9)
assert abs(math.sqrt(sum(x * x for x in a)) - 1) < 1e-6
assert l2_hys([0.0] * 36) == [0.0] * 36
def test_invariant_to_affine_intensity_change():
rng = random.Random(4)
img = noise(rng, 24, 16, 1.0)
brighter = [[3.0 * p + 10.0 for p in row] for row in img]
a, b = hog_descriptor(img, 4), hog_descriptor(brighter, 4)
assert close(a, b, 1e-5)
def test_downscale():
rng = random.Random(5)
img = noise(rng, 8, 8, 1.0)
assert downscale(img, 1.0) == img
half = downscale(img, 2.0)
for y in range(4):
for x in range(4):
m = (img[2 * y][2 * x] + img[2 * y][2 * x + 1] + img[2 * y + 1][2 * x] + img[2 * y + 1][2 * x + 1]) / 4
assert abs(half[y][x] - m) < 1e-12
def test_svm_duality_gap():
rng = random.Random(6)
X = [[rng.gauss(1 if i < 15 else -1, 1.0) for _ in range(4)] for i in range(30)]
y = [1] * 15 + [-1] * 15
for C in (0.01, 1.0, 10.0):
w, b, alpha = train_linear_svm(X, y, C, tol=1e-9, max_epochs=20000)
p, d = primal_objective(w, b, X, y, C), dual_objective(alpha, X, y)
assert d <= p + 1e-12
assert p - d < 1e-6 * max(1.0, p)
assert all(0 <= a <= C for a in alpha)
def test_mining_gives_the_same_svm_as_all_negatives():
# The cache argument of Felzenszwalb et al.: once no negative outside the
# cache violates the margin, the SVM on the cache is the SVM on the pool.
rng = random.Random(7)
pos = [[rng.gauss(1.0, 1.0) for _ in range(5)] for _ in range(15)]
pool = [[rng.gauss(-1.0, 1.0) for _ in range(5)] for _ in range(120)]
C = 0.5
w1, b1, cache = train_with_mining(pos, pool, range(10), C, tol=1e-9)
w2, b2, _ = train_linear_svm(pos + pool, [1] * 15 + [-1] * 120, C, tol=1e-9)
assert len(cache) < len(pool)
assert close(w1 + [b1], w2 + [b2], 1e-4)
p1 = primal_objective(w1, b1, pos + pool, [1] * 15 + [-1] * 120, C)
p2 = primal_objective(w2, b2, pos + pool, [1] * 15 + [-1] * 120, C)
assert abs(p1 - p2) < 1e-6 * p2
def test_score_map_moves_with_a_whole_cell_shift():
rng = random.Random(8)
big = noise(rng, 32, 40, 1.0)
cell = 4
a = [row[0:36] for row in big]
b = [row[cell:40] for row in big]
w = [rng.uniform(-1, 1) for _ in range(descriptor_length(12, 24, cell))]
model = Model(w, 0.25, 3, 6, cell)
sa, sb = scan_level(a, model), scan_level(b, model)
# Windows that keep one cell away from the left and right borders of
# both crops see the same pixels and the same gradients.
nx = 36 // cell
for (by, bx), v in sb.items():
if bx >= 1 and bx + 3 <= nx - 2:
assert abs(v - sa[(by, bx + 1)]) < 1e-9
def make_data(rng):
def pos_window():
im = noise(rng, 24, 12)
paste(im, 4 + rng.randint(-1, 1), 4 + rng.randint(-1, 1), 4, 16)
return im
def neg_image():
im = noise(rng, 40, 40)
for _ in range(2):
paste(im, rng.randint(0, 24), rng.randint(0, 34), rng.randint(8, 16), 4)
paste(im, rng.randint(0, 26), rng.randint(0, 6), 12, 32) # a wide bar
return im
return [pos_window() for _ in range(20)], [neg_image() for _ in range(4)]
def test_detects_a_synthetic_object_at_two_scales():
rng = random.Random(1)
pos, neg = make_data(rng)
model = train_detector(pos, neg, cell=4, C=1.0, n_random=40, rounds=1, seed=3)
for trial in range(2):
img = noise(rng, 48, 48)
x, y = 4 * rng.randint(0, 6), 4 * rng.randint(0, 5)
paste(img, x + 4, y + 4, 4, 16)
found = detect(img, model)
assert found and iou(found[0][0], (x, y, x + 12, y + 24)) > 0.5
# Twice as large: found on the pyramid level of scale 2.
img = noise(rng, 64, 64)
paste(img, 16, 16, 8, 32)
found = detect(img, model, step=2.0)
assert found and iou(found[0][0], (8, 8, 32, 56)) > 0.5
# Kept detections do not overlap above the NMS threshold.
for i in range(len(found)):
for j in range(i + 1, len(found)):
assert iou(found[i][0], found[j][0]) <= 0.5
def test_window_scores_are_dot_products():
rng = random.Random(9)
img = noise(rng, 24, 12, 1.0)
w = [rng.uniform(-1, 1) for _ in range(descriptor_length(12, 24, 4))]
model = Model(w, -0.5, 3, 6, 4)
s = scan_level(img, model)
assert list(s) == [(0, 0)]
assert abs(s[(0, 0)] - (dot(w, hog_descriptor(img, 4)) - 0.5)) < 1e-12
assert block_grid(cell_histograms(img, 4))[0][0] == l2_hys(
sum((cell_histograms(img, 4)[i][j] for i in (0, 1) for j in (0, 1)), []))
History
Before 2005, detectors of people and faces used Haar wavelets, as in the work of Papageorgiou and Poggio and the Viola-Jones detector, or edge templates. Dalal and Triggs (2005) introduced dense histograms of oriented gradients, inspired by the orientation histograms of SIFT and of earlier work on shape contexts, and showed on the new INRIA person data set that they reduce false positives by more than an order of magnitude compared with the Haar wavelet detector they tested. The INRIA set has 1239 positive training images, used with their mirror images as 2478 windows, and 12180 negative windows taken from 1218 images without people. Felzenszwalb, Girshick, McAllester and Ramanan (2010) state that the Dalal-Triggs detector won the 2006 PASCAL object detection challenge, and they built the deformable part model on it. HOG with a linear SVM remained a standard baseline until convolutional detectors such as R-CNN (2014) took over.
References
- Navneet Dalal and Bill Triggs, Histograms of oriented gradients for human detection, CVPR 2005, vol. 1, 886-893, Figure 1 (the chain), Section 4 (the INRIA data set and hard examples), Section 6 (the study of each step: gradients, orientation bins, blocks, normalization, window size, SVM), Section 7 (summary of the default detector)
- 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), 2010, 1627-1645, Section 4.4 (data mining of hard examples, Theorem 1 and Theorem 2), and the Dalal-Triggs detector as the root filter
- Corinna Cortes and Vladimir Vapnik, Support-vector networks, Machine Learning 20(3), 1995, 273-297, The soft-margin support vector machine
- Cho-Jui Hsieh, Kai-Wei Chang, Chih-Jen Lin, S. Sathiya Keerthi and S. Sundararajan, A dual coordinate descent method for large-scale linear SVM, ICML 2008, The dual coordinate descent method for the hinge-loss linear SVM, used by the code of this page
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 6.3.2, Pedestrian detection
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 7BC4KB Edit this page History Report an error Markdown