AI Wiki中文/EN

HOG features

HOG 特征

Build overlapping gradient histograms, derive 3780 dimensions, and test which contrast changes they ignore.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A question to test

A person wearing a dark coat against a bright wall can produce the opposite contrast from a person wearing a bright coat against a dark wall. Some shape information survives that reversal. HOG describes how much gradient energy points in different directions within local regions, then normalizes overlapping groups of those regions.

Histograms of Oriented Gradients are features. A vector of HOG values is not already a trained pedestrian detector. Dalal and Triggs combined such features with a classifier and an evaluation protocol. Here we construct a grayscale descriptor, inspect its dimensions and test what happens when contrast changes.

The model and its derivation

The paper’s default rectangular HOG configuration uses nine unsigned orientation bins, eight-by-eight pixel cells, two-by-two cell blocks and an eight-pixel block stride. Its 64-by-128 pixel detection window therefore contains seven horizontal by fifteen vertical blocks. Each block contributes 36 entries:

Bx=W−168+1,By=H−168+1,D=36BxBy.B_x=\frac{W-16}{8}+1,\qquad B_y=\frac{H-16}{8}+1,\qquad D=36B_xB_y.

For W=64 and H=128, D=3780. A cell can occur in several blocks with different normalization contexts; those occurrences are deliberately retained, not deduplicated. These dimensions describe one configuration, not the definition of every HOG implementation. Histograms of Oriented Gradients for Human Detection

Our finite differences use the filter [−1,0,1][-1,0,1]. Let mm be gradient magnitude. Unsigned orientation treats opposite gradients as the same direction:

m=Ix2+Iy2,θ=atan2⁡(Iy,Ix) mod π.m=\sqrt{I_x^2+I_y^2},\qquad \theta=\operatorname{atan2}(I_y,I_x)\bmod\pi.

Nine bins span a half-turn, so adjacent bin centres are twenty degrees apart. A ninety-degree gradient lies halfway between the eighty- and hundred-degree bins and splits its vote equally. Spatial interpolation similarly distributes a sample across neighbouring cell centres. A Gaussian window gives more weight to the block centre. Our implementation combines these weights in each sixteen-by-sixteen block.

Block histograms are flattened into a nonnegative vector h and normalized with L2-Hys:

Nε(h)=h∥h∥22+ε2,b=Nε(min⁡(Nε(h),0.2)).N_\varepsilon(h)=\frac{h}{\sqrt{\lVert h\rVert_2^2+\varepsilon^2}},\qquad b=N_\varepsilon\bigl(\min(N_\varepsilon(h),0.2)\bigr).

The epsilon is 10−1210^{-12} here. Clipping is followed by another normalization, so final entries are not bounded by 0.2. Dalal and Triggs describe this choice in relation to Lowe’s clipped normalization; the same algebra does not imply the two descriptors are identical. Histograms of Oriented Gradients for Human Detection Distinctive Image Features from Scale-Invariant Keypoints — author version

For a uniform horizontal ramp in a single symmetric block, each of the four cells has equal mass in its zero-degree bin. After normalization, those four entries are each approximately 0.5. A vertical ramp divides that mass between two orientation bins per cell; the eight equal nonzero entries are approximately 1/81/\sqrt8. These closed-form patterns give a reference independent of the loop implementation.

Run a small experiment

Run the complete program with Python 3.12 and NumPy 1.26.4. Input dimensions must be multiples of eight and at least sixteen. Boundaries repeat edge values; spatial votes outside a block are discarded. Gaussian sigma is eight pixels. No color-channel selection, trained classifier or sliding-window score is included.

import numpy as np

def normalise(values):
    scale=max(float(np.max(np.abs(values),initial=0)),1e-12)
    scaled=values/scale
    return scaled/np.sqrt(np.dot(scaled,scaled)+(1e-12/scale)**2)

def l2_hys(values):
    return normalise(np.minimum(normalise(values),.2))

def hog(image):
    a=np.asarray(image,dtype=float)
    if a.ndim!=2 or min(a.shape,default=0)<16 or any(n%8 for n in a.shape) or not np.isfinite(a).all():
        raise ValueError('finite grayscale dimensions must be multiples of 8 and at least 16')
    p=np.pad(a,1,mode='edge')
    gx=p[1:-1,2:]-p[1:-1,:-2];gy=p[2:,1:-1]-p[:-2,1:-1]
    magnitude=np.hypot(gx,gy)
    angle=np.mod(np.arctan2(gy,gx),np.pi)*9/np.pi
    blocks=[]
    for top in range(0,a.shape[0]-15,8):
        for left in range(0,a.shape[1]-15,8):
            hist=np.zeros((2,2,9))
            for y in range(16):
                for x in range(16):
                    cy,cx=(y+.5)/8-.5,(x+.5)/8-.5
                    by,bx=int(np.floor(cy)),int(np.floor(cx))
                    o=angle[top+y,left+x];bo=int(np.floor(o));fo=o-bo
                    fy,fx=cy-by,cx-bx
                    weight=magnitude[top+y,left+x]*np.exp(-((x-7.5)**2+(y-7.5)**2)/(2*8**2))
                    for iy,wy in ((by,1-fy),(by+1,fy)):
                        for ix,wx in ((bx,1-fx),(bx+1,fx)):
                            if 0<=iy<2 and 0<=ix<2:
                                hist[iy,ix,bo%9] += weight*wy*wx*(1-fo)
                                hist[iy,ix,(bo+1)%9] += weight*wy*wx*fo
            blocks.append(l2_hys(hist.ravel()))
    return np.concatenate(blocks)

if __name__=='__main__':
    ramp=np.tile(np.arange(16,dtype=float),(16,1))
    print('one block dimensions:',hog(ramp).size)
    print('64x128 window dimensions:',hog(np.zeros((128,64))).size)
    print('contrast reversal:',np.allclose(hog(ramp),hog(20-ramp)))
    print('constant window norm:',np.linalg.norm(hog(np.ones((16,16)))))
one block dimensions: 36
64x128 window dimensions: 3780
contrast reversal: True
constant window norm: 0.0

Contrast reversal changes each gradient’s sign, but modulo-pi orientation identifies the two directions. Magnitudes remain the same. Thus the descriptor of the ramp and its reversed version agree within numerical tolerance. This is different from arbitrary rotation: rotating a scene can change both its spatial arrangement and its unsigned orientation bins.

The checks include the horizontal and vertical closed-form ramps,36/72/3780 dimensional cases, constant windows, positive gain, contrast reversal, a large finite gain and invalid dimensions. Scaled normalization avoids unnecessary squared-norm overflow, but it does not make all earlier image arithmetic safe for arbitrary extremes.

With fixed blocks and stride, work and storage grow as O(HW), including the output. The straightforward Python loops repeat some overlapping work and are intended for small teaching images. A production implementation can share calculations or use vectorized kernels; its timing must be measured rather than inferred from descriptor length.

Where the method breaks

The original default detector uses color gradients selected across channels; our grayscale version intentionally differs. Boundary treatment, interpolation support, epsilon and preprocessing also affect exact values. Do not compare this vector element-for-element with another library without matching all conventions.

A detector additionally needs positive and negative examples, training, a score threshold, scale handling, duplicate-detection suppression and evaluation. Splitting nearby frames of the same person across train and test can make performance look better than deployment. Report the dataset split and the metric’s denominator: false positives per window and false positives per image are different quantities.

Fixed-window HOG can be sensitive to pose and alignment. Unsigned orientation discards contrast polarity, which helps some tasks and loses information for others. It does not erase background structure or identify an object by itself. The numerical examples do not reproduce the paper’s pedestrian-detection results.

Exercises with answers

1. How many features come from a 32-by-32 window under this configuration?

Answer. There are 3×3 blocks, each 36-dimensional, giving 324 entries.

2. Why does a 90-degree gradient split across two bins?

Answer. Bin centres occur every 20 degrees. Ninety lies halfway between 80 and 100, so linear orientation interpolation gives equal weights.

3. Does contrast-reversal invariance imply rotation invariance?

Answer. No. Reversal adds 180 degrees without moving spatial features; a physical rotation changes locations and generally changes unsigned angles too.

4. You have 3780 numbers. Can you now report pedestrian-detection accuracy?

Answer. No. You still need a trained decision rule and an evaluated dataset/protocol. Descriptor dimensionality is not evidence of detection quality.

Sources and next steps

Read the HOG paper’s default configuration and method sections, especially the distinction between cells and normalized blocks. Lowe’s descriptor discussion supplies context for clipping and the contrasting signed orientation choice. Histograms of Oriented Gradients for Human Detection Distinctive Image Features from Scale-Invariant Keypoints — author version

Compare SIFT at the level of coordinate frames, spatial support and orientation conventions. Return to model evaluation before interpreting a feature extractor as an end-to-end application.

Make a prediction, then check

A64-by-128 window has 7×15 blocks of 36 values. Its descriptor length is?

Choose one answer

Learning objectives

  • Derive descriptor dimensions from block size and stride.
  • Separate feature invariances from detector performance.

Prerequisites & connections

Explore related knowledge →

References

  1. Histograms of Oriented Gradients for Human Detection
    Navneet Dalal; Bill Triggs · 2005
  2. Distinctive Image Features from Scale-Invariant Keypoints — author version
    David G. Lowe · 2004

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: bounded primary-source passages, explicit camera, filter, descriptor and local-motion models, executed programs, independent mathematical references, input boundaries and bilingual alignment. Not independent human or second-agent review; no full-system research reproduction claimed.

  • Single-agent authored technical review; runnable example, exact or literal reference checks, explicit assumptions and matching bilingual equations/exercises. Automated execution and rendering results recorded separately.
  • 6 tests: closed-form horizontal/vertical ramps,36/72/3780 dimensions, constants, gain and unsigned reversal including10^200, clipping and invalid shape. Grayscale conventions explicit; no bit-exact library or trained detector reproduction.
  • Single AI author compared all six sections, formulas, examples, source scopes and four exercise/answer pairs across both languages.35 tests across six chapters passed before freezing; no independent human review claimed.
  • Complete bilingual prose and corresponding exercises promoted with formal status and SHA binding. Algorithm tests read formal MDX; historical essays claim no executable program or computational tests.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.