Classical Features: Corners, Keypoints and HOG
Before CNNs learned their own features, vision systems were built from hand-designed ones, and many still are: panorama stitching, visual odometry on drones, augmented reality markers, document alignment and, until about 2012, pedestrian detection. Two families matter. Local features find distinctive points (corners, blobs) and describe the patch around each, so the same physical point can be found again in another image, after a rotation, a zoom or a change of viewpoint. Dense descriptors such as HOG summarise the gradient structure of a whole window into a fixed-length vector that a linear classifier can use. This lesson builds the Harris corner detector and HOG from scratch, matches them to OpenCV and scikit-image, and uses ORB keypoints with RANSAC to recover a known rotation. HOG returns in image classification (HOG + SVM) and in Project 2 (OpenCV's HOG people detector).
What makes a point distinctive
Slide a small window over the image. In a flat region, moving it in any direction changes nothing. On an edge, moving it along the edge changes nothing, so its position along the edge is ambiguous (the aperture problem). At a corner, every direction of movement changes the content: the point is well localised in both directions. The change for a small shift is captured, to first order, by the structure tensor (second-moment matrix) of the gradients in the window, weighted by a Gaussian :
The eigenvalues of (eigenvalues) are the change along the most and least changing directions: both small means flat, one large means edge, both large means corner. Harris and Stephens (1988) avoided the eigen-decomposition with the response
which is large and positive at corners, negative on edges and near zero in flat areas. Shi and Tomasi (1994) use directly (cv2.goodFeaturesToTrack), the usual choice for tracking.
Harris from scratch
import numpy as np
import cv2
cv2.setLogLevel(0)
img = np.zeros((80, 80), np.float32)
img[20:50, 15:45] = 1.0 # a square: 4 corners
cv2.fillPoly(img, [np.array([[55, 75], [75, 75], [65, 55]], np.int32)], 1.0) # a triangle: 3 corners
img = cv2.GaussianBlur(img, (0, 0), 1)
gx = cv2.Sobel(img, cv2.CV_32F, 1, 0, ksize=3); gy = cv2.Sobel(img, cv2.CV_32F, 0, 1, ksize=3)
Sxx = cv2.GaussianBlur(gx * gx, (0, 0), 1.5) # structure tensor entries,
Syy = cv2.GaussianBlur(gy * gy, (0, 0), 1.5) # summed with a Gaussian window
Sxy = cv2.GaussianBlur(gx * gy, (0, 0), 1.5)
k = 0.04
R = Sxx * Syy - Sxy ** 2 - k * (Sxx + Syy) ** 2
def peaks(R, rel=0.01, nms=7):
"""Local maxima in a 7 x 7 neighbourhood above 1 % of the strongest response, as (x, y)."""
m = (R == cv2.dilate(R, np.ones((nms, nms), np.uint8))) & (R > rel * R.max())
return sorted([(int(x), int(y)) for y, x in np.argwhere(m)])
print("from scratch, corners (x, y):", peaks(R))
for name, (x, y) in [("corner", (15, 20)), ("edge", (30, 20)), ("flat", (30, 35)), ("flat outside", (5, 5))]:
T = np.array([[Sxx[y, x], Sxy[y, x]], [Sxy[y, x], Syy[y, x]]])
l1, l2 = np.linalg.eigvalsh(T)[::-1]
print(f"{name:12s} ({x}, {y}): lambda1 {l1:7.3f} lambda2 {l2:7.3f} R {R[y, x]:8.3f}")
Rcv = cv2.cornerHarris(img, blockSize=3, ksize=3, k=0.04) # box window of 3 x 3
print("cv2.cornerHarris corners:", peaks(Rcv))from scratch, corners (x, y): [(16, 21), (16, 48), (43, 21), (43, 48), (56, 74), (65, 57), (73, 74)]
corner (15, 20): lambda1 2.480 lambda2 0.857 R 1.679
edge (30, 20): lambda1 3.607 lambda2 0.000 R -0.521
flat (30, 35): lambda1 0.000 lambda2 0.000 R 0.000
flat outside (5, 5): lambda1 0.000 lambda2 0.000 R 0.000
cv2.cornerHarris corners: [(16, 21), (16, 48), (43, 21), (43, 48), (56, 74), (65, 56), (74, 74)]
Both find exactly seven corners: the square's four, one pixel inside the true corners at and (the blur and the window pull the peak inwards), and the triangle's three, about two pixels from its vertices. They differ by one pixel at two triangle corners because cornerHarris sums the tensor over a box instead of a Gaussian. The eigenvalues tell the story of the figure: 2.48 and 0.86 at the corner, 3.61 and 0.00 on the edge (one direction changes, the other does not, so ), zero in flat regions.
Harris corners are invariant to rotation (eigenvalues do not care about direction) and to adding a constant brightness, but not to scale: a corner seen at twice the size can look like a smooth curve to a fixed window. Multi-scale detectors (the Laplacian of Gaussian from edge detection, SIFT's difference of Gaussians, FAST on an image pyramid in ORB) search over scales too.
Keypoints and descriptors: ORB
A keypoint is a position, a scale and an orientation; a descriptor is a vector that describes the patch around it, so that the same point in two images gets nearly the same vector. SIFT (Lowe, 2004) uses 128 floats built from gradient histograms; it is in OpenCV as cv2.SIFT_create since its patent expired. ORB (Rublee et al., 2011) is the fast, free alternative: FAST corners on an image pyramid, ranked by the Harris response; an orientation from the patch's intensity centroid; and a binary descriptor of 256 bits, each the result of one brightness comparison between two pixels of the rotated patch. Binary descriptors are compared with the Hamming distance (the number of differing bits), one XOR and a popcount.
Matching then needs care, because repeated texture produces confident wrong matches. Lowe's ratio test keeps a match only if its best distance is clearly smaller than the second-best (ratio below about 0.75; Lowe's paper used 0.8), and RANSAC fits a geometric model (here a homography) to random minimal subsets of matches and keeps the one most matches agree with, which rejects the remaining outliers. The test below rotates the camera image by 30 degrees and scales it by 0.8 with a known matrix, so every match can be checked:
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)
img = data.camera()
h, w = img.shape
M = cv2.getRotationMatrix2D((w / 2, h / 2), 30, 0.8) # the known transform
warped = cv2.warpAffine(img, M, (w, h))
orb = cv2.ORB_create(nfeatures=500)
k1, d1 = orb.detectAndCompute(img, None)
k2, d2 = orb.detectAndCompute(warped, None)
print("keypoints:", len(k1), len(k2), "| descriptor", d1.shape, d1.dtype)
print("first keypoint: pt", [round(v, 1) for v in k1[0].pt], "size", round(k1[0].size, 1), "angle", round(k1[0].angle, 1), "octave", k1[0].octave)
bf = cv2.BFMatcher(cv2.NORM_HAMMING)
knn = bf.knnMatch(d1, d2, k=2) # best and second-best match
pairs = [p for p in knn if len(p) == 2]
good = [m for m, n in pairs if m.distance < 0.75 * n.distance] # Lowe's ratio test
m0 = good[0]
print("Hamming from scratch:", int(np.unpackbits(d1[m0.queryIdx] ^ d2[m0.trainIdx]).sum()), "| matcher says", int(m0.distance))
p1 = np.float32([k.pt for k in k1]); p2 = np.float32([k.pt for k in k2])
truth = cv2.transform(p1[None], M)[0] # where each point really went
def correct(ms):
return sum(np.linalg.norm(truth[m.queryIdx] - p2[m.trainIdx]) < 3 for m in ms)
best = [p[0] for p in pairs]
print(f"nearest neighbour only: {len(best)} matches, {correct(best)} correct ({correct(best) / len(best):.0%})")
print(f"ratio test 0.75: {len(good)} matches, {correct(good)} correct ({correct(good) / len(good):.0%})")
src = np.float32([k1[m.queryIdx].pt for m in good]); dst = np.float32([k2[m.trainIdx].pt for m in good])
H, inl = cv2.findHomography(src, dst, cv2.RANSAC, 3.0)
print("RANSAC inliers:", int(inl.sum()), "of", len(good))
print("recovered H:"); print(H.round(3))
print("true affine:"); print(np.vstack([M, [0, 0, 1]]).round(3))
corners = np.float32([[0, 0], [w, 0], [w, h], [0, h]])
err = np.linalg.norm(cv2.perspectiveTransform(corners[None], H)[0] - cv2.transform(corners[None], M)[0], axis=1)
print("corner error (px):", [round(float(e), 2) for e in err])
print(f"recovered angle {np.degrees(np.arctan2(-H[1, 0], H[0, 0])):.2f} deg, scale {np.hypot(H[0, 0], H[1, 0]):.3f}")keypoints: 500 500 | descriptor (500, 32) uint8
first keypoint: pt [385.0, 474.0] size 31.0 angle 248.8 octave 0
Hamming from scratch: 29 | matcher says 29
nearest neighbour only: 500 matches, 390 correct (78%)
ratio test 0.75: 279 matches, 270 correct (97%)
RANSAC inliers: 271 of 279
recovered H:
[[ 0.683 0.402 -22.69 ]
[ -0.403 0.692 180.757]
[ -0. 0. 1. ]]
true affine:
[[ 0.693 0.4 -23.762]
[ -0.4 0.693 181.038]
[ 0. 0. 1. ]]
corner error (px): [1.11, 2.54, 1.96, 3.9]
recovered angle 30.54 deg, scale 0.793
Each descriptor is 32 bytes (256 bits), and the Hamming distance is literally the count of set bits in the XOR. Taking every nearest neighbour gives 78 % correct matches (within 3 pixels of where the point really went); the ratio test keeps 279 matches, 97 % of them correct. RANSAC then keeps 271 inliers and recovers the transform: 30.54 degrees and scale 0.793 against the true 30 and 0.8, with the image corners off by 1.1 to 3.9 pixels. That is good enough to stitch the two images, and the residual comes from keypoint positions quantised to the pyramid level they were found on. A homography has 8 degrees of freedom and the true transform only 4, so cv2.estimateAffinePartial2D (rotation, scale, shift) would fit this case more tightly; choose the simplest model that covers the real motion.
HOG: histograms of oriented gradients
Dalal and Triggs (2005) designed HOG for pedestrian detection: describe a window by how much gradient there is in each direction, in each small region, normalised locally so that lighting and contrast do not matter. The recipe:
- Gradients with in and ; magnitude and unsigned orientation (a dark-to-light and a light-to-dark edge count the same).
- Cells of pixels: a 9-bin histogram of (20 degrees per bin), each pixel voting with its magnitude.
- Blocks of cells, overlapping with a stride of one cell: concatenate the 4 histograms (36 numbers) and normalise with L2-Hys: , clip at 0.2, normalise again.
- Concatenate all blocks.
import numpy as np
from skimage import data, color
from skimage.feature import hog
from skimage.transform import resize
def hog_scratch(img, n_bins=9, cell=8, block=2, eps=1e-5):
g_row = np.zeros_like(img); g_col = np.zeros_like(img)
g_row[1:-1, :] = img[2:, :] - img[:-2, :] # [-1, 0, 1] gradients, 0 at the border
g_col[:, 1:-1] = img[:, 2:] - img[:, :-2]
mag = np.hypot(g_col, g_row)
ori = np.rad2deg(np.arctan2(g_row, g_col)) % 180 # unsigned orientation
bins = np.minimum((ori // (180 / n_bins)).astype(int), n_bins - 1)
n_r, n_c = img.shape[0] // cell, img.shape[1] // cell
hist = np.zeros((n_r, n_c, n_bins))
for i in range(n_r):
for j in range(n_c):
sl = (slice(i * cell, (i + 1) * cell), slice(j * cell, (j + 1) * cell))
hist[i, j] = np.bincount(bins[sl].ravel(), weights=mag[sl].ravel(), minlength=n_bins) / cell ** 2
out = []
for i in range(n_r - block + 1): # overlapping 2 x 2 blocks
for j in range(n_c - block + 1):
v = hist[i:i + block, j:j + block].ravel()
v = v / np.sqrt((v ** 2).sum() + eps ** 2) # L2-Hys
v = np.minimum(v, 0.2)
out.append(v / np.sqrt((v ** 2).sum() + eps ** 2))
return np.concatenate(out), hist
gray = color.rgb2gray(data.astronaut())
win = resize(gray[0:512, 64:320], (128, 64), anti_aliasing=True) # a 64 x 128 window (W x H)
ours, hist = hog_scratch(win)
ref = hog(win, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(2, 2), block_norm="L2-Hys")
print("window", win.shape, "| cells", hist.shape[:2], "| blocks", (hist.shape[0] - 1, hist.shape[1] - 1))
print("feature length: ours", ours.size, "| skimage", ref.size, "| 15 * 7 * 2 * 2 * 9 =", 15 * 7 * 36)
print(f"max |ours - skimage| = {np.abs(ours - ref).max():.2e}")
edge = np.zeros((16, 16)); edge[:, 8:] = 1.0 # a vertical edge between columns 7 and 8
_, h_edge = hog_scratch(edge)
print("vertical edge, cell (0, 0) histogram:", h_edge[0, 0].round(3).tolist(), "| cell (0, 1):", h_edge[0, 1].round(3).tolist())
diag = np.fromfunction(lambda r, c: (r + c > 15).astype(float), (16, 16)) # a diagonal edge
_, h_diag = hog_scratch(diag)
print("diagonal edge: gradient energy per cell", h_diag.sum(-1).round(3).tolist(), "| strongest bin per cell", h_diag.argmax(-1).tolist())window (128, 64) | cells (16, 8) | blocks (15, 7)
feature length: ours 3780 | skimage 3780 | 15 * 7 * 2 * 2 * 9 = 3780
max |ours - skimage| = 4.22e-08
vertical edge, cell (0, 0) histogram: [0.125, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] | cell (0, 1): [0.125, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
diagonal edge: gradient energy per cell [[0.0, 0.303], [0.303, 0.022]] | strongest bin per cell [[0, 2], [2, 2]]
The from-scratch HOG equals scikit-image's to better than (float rounding), and the window gives the classic 3,780 numbers. The two small tests show what a cell histogram encodes. A vertical edge has a horizontal gradient (0 degrees), so all its energy is in bin 0 (0–20 degrees), split between the two cells that contain the edge's two gradient columns. A diagonal edge (brighter to the lower right) has gradients at 45 degrees, bin 2 (40–60 degrees): most of its energy (0.303 each) is in the two cells the edge runs through, a little (0.022) in the lower-right cell next to it, and the top-left cell has no gradient at all, so its "strongest bin" 0 means nothing, which is why the energy is printed too.
scikit-image's hog votes each pixel into one bin, as above; Dalal and Triggs (and OpenCV's HOGDescriptor) spread each vote over the two nearest bins and neighbouring cells (trilinear interpolation) and weight pixels by a Gaussian over the block, which makes the descriptor smoother against small shifts. The numbers therefore differ between libraries: train and detect with the same implementation. HOG is not rotation-invariant (a lying person has a different HOG), and it needs a fixed window size, so detectors slide the window over an image pyramid (detection basics counts what that costs).
Pitfalls
- Harris without non-maximum suppression. is large in a small area around each corner; take local maxima, or every corner turns into a blob of points.
- Thresholds relative to the maximum. "1 % of the strongest response" adapts to contrast, but one very strong corner hides weak real ones;
goodFeaturesToTrack'sminDistanceand per-tile limits spread points out. - Matching without checks. Nearest neighbours alone were 22 % wrong; use the ratio test (or cross-checking) and a geometric model with RANSAC.
- Wrong distance. Binary descriptors (ORB, BRIEF, AKAZE) need
NORM_HAMMING; float descriptors (SIFT) needNORM_L2. - Over-general models. Fitting a homography where the motion is a rotation and scale wastes degrees of freedom and tolerates bad matches; use the simplest model that fits.
- Different HOG implementations. Cell size, binning, interpolation and normalisation change the vector; a classifier trained on scikit-image HOG does not work on OpenCV HOG.
Practice
- At a pixel the structure tensor is . Compute with and classify the pixel.
Answer
, , . Negative: an edge (one large eigenvalue, 4, one small, 0.1).
- Two 8-bit descriptor bytes are
0b10110010and0b10011011. What is their Hamming distance?
Answer
XOR: 0b00101001, which has 3 set bits: distance 3.
- How long is the HOG vector of a 64 x 64 window with 8 x 8 cells, 9 bins and 2 x 2 blocks with stride one cell?
Answer
cells, blocks, numbers.
- Why does Lowe's ratio test help more than a fixed threshold on the match distance?
Answer
A fixed threshold cannot tell a unique match from a match in repetitive texture, where many candidates are almost equally close. The ratio of best to second-best distance measures how distinctive the match is: a correct match is usually much closer than any other candidate, a wrong one is not.
Test yourself
The structure tensor at a pixel has eigenvalues 3.6 and 0.0. What kind of point is it?
- A corner
- An edge
- A flat region
- A blob
What does ORB's descriptor consist of?
- 128 floating-point gradient histogram values
- 256 bits, each a brightness comparison between two pixels of the rotated patch
- The raw pixels of the patch
- A 9-bin orientation histogram
In the lesson, what did the ratio test change?
- It doubled the number of matches
- It cut the matches from 500 to 279 and raised the share of correct ones from 78 % to 97 %
- It made RANSAC unnecessary
- It changed the descriptor
How many numbers does HOG produce for a 64 x 128 window with 8 x 8 cells, 9 bins and 2 x 2 blocks?
- 1152
- 3780
- 4608
- 128