1. Feature Extraction & Matching

Color spaces, edges, SIFT, HOG, Harris corners, Hough transform, feature matching

Contents
1. Color Systems 2. Features and Image Matching 3. Canny Edge Detection 4. HOG Descriptor 5. SIFT 6. Feature Matching 7. Hough Transform 8. Harris Corner Detector 9. Haar-like Features Interactive: Feature Matching & Ratio Test Interactive: SIFT Walkthrough Interactive: Canny Walkthrough Interactive: Convolution Step-Through Interactive: Hough Transform Voting Interactive: Harris Corner Explorer Flashcards

1. Color Systems

Before extracting features, we need to understand how images encode color. Different color systems emphasize different properties of light, and choosing the right one can make feature extraction more robust.

RGB (Red, Green, Blue)

The human eye has three cone types responding to long (~570nm, red), medium (~540nm, green), and short (~440nm, blue) wavelengths. Camera sensors replicate this with a Bayer filter pattern: 2 green, 1 blue, 1 red cell per pixel (green doubled because human vision is most sensitive to green).

Bayer filter pattern on a camera sensor
Bayer filter mosaic on a camera sensor array.

HSV (Hue, Saturation, Value)

HSV separates color from lighting, making it more useful for many CV tasks:

RGB to HSV Conversion
$V = \max(R, G, B)$,   $S = \frac{\max - \min}{\max}$,   $H = 60 \times \text{(depends on which channel is max)}$
RGB color cube and HSV cylinder
RGB cube and HSV cylinder representations.
Other color systems: CMYK, YUV

CMYK (Cyan, Magenta, Yellow, Black) is a subtractive model used in printing. Mixing colors subtracts wavelengths from white light.

YUV separates luminance (Y) from chrominance (U, V). The human eye is more sensitive to brightness than color, which is exploited in video compression.

Key insight
HSV is often preferred in computer vision because it separates color (hue) from lighting conditions (value), making algorithms more robust to illumination changes.

2. Features and Image Matching

The core problem: given two or more images, how do we determine if they show the same scene? This is image matching, and it requires extracting features — pieces of information relevant to solving a computational task.

Image Matching Pipeline

  1. Extract features invariant to geometric (translation, rotation, scale) and photometric (brightness) transformations
  2. Compute descriptors — mathematical representations of local image regions
  3. Match descriptors between images by comparing their vector representations

Requirements for Good Features

RequirementExplanation
DiscriminativeCaptures important nuances distinguishing image regions
Descriptive powerAllows rich mathematical descriptions (high-dimensional vectors)
Sufficient quantityHundreds or thousands per image
Low computation costReal-time performance achievable
GeneralityFound in various image types, not limited to specific scenes

3. Canny Edge Detection

An edge is a location with a significant change (gradient) in pixel intensity, corresponding to boundaries, texture changes, or shadows. The Canny detector was designed to satisfy three criteria: optimal detection (low error rate), good localization, and single response per edge.

Canny edge detection result
Original image (left) and Canny edge detection result (right).
Definition — Convolution
A kernel $K$ slides over the image $I$. At each position: $g(x,y) = \sum_i \sum_j K(i,j) \cdot I(x+i, y+j)$
Convolution operation
Convolution: source matrix, kernel, and resulting output.
Interactive -- Convolution Step-Through

Edit the image grid values, choose a kernel, then step through (or animate) to see convolution computed cell by cell.

Input Image (5x5)
*
Kernel (3x3)
=
Output (3x3)
Sobel filter kernels

Sobel filters compute gradients in X and Y directions:

$G_x = \begin{bmatrix} -1 & 0 & 1 \\ -2 & 0 & 2 \\ -1 & 0 & 1 \end{bmatrix} \quad G_y = \begin{bmatrix} -1 & -2 & -1 \\ 0 & 0 & 0 \\ 1 & 2 & 1 \end{bmatrix}$

$G_x$ detects vertical edges. $G_y$ detects horizontal edges. Combined: $G = \sqrt{G_x^2 + G_y^2}$, $\theta = \arctan(G_y / G_x)$.

Sobel filter kernels

4. HOG Descriptor (Histogram of Oriented Gradients)

Edges alone have limited descriptive power and are not rotation-invariant. HOG captures the distribution of gradient orientations in local regions, providing a richer, rotation-invariant feature.

HOG Pipeline

  1. Split image into 8x8 blocks
  2. Compute gradients (magnitude + orientation) at each pixel
  3. Create 4x4 sub-windows, quantize gradients into 8 direction bins
  4. Build histogram per sub-window (8 bins, weighted by magnitude)
  5. Find dominant orientation of the block
  6. Normalize the descriptor relative to the dominant orientation (rotation invariance)
  7. Concatenate histograms into the HOG feature vector
HOG pipeline overview
HOG pipeline: Image to cell division to gradient orientation to histogram to vectorization.
HOG gradient overlay on silhouette
HOG gradient direction roses overlaid on a person silhouette.
PropertyHOG
DescriptiveYes — captures gradient distribution
Rotation-invariantYes — dominant orientation normalization
Scale-invariantNo — key limitation
Key insight
HOG's dominant orientation concept is reused in SIFT (Step 4) for rotation invariance. The Sobel filters used in Canny are also the foundation for computing gradients in HOG.

5. SIFT (Scale Invariant Feature Transform)

Edge points lack descriptive power. HOG is descriptive and rotation-invariant but not scale-invariant. SIFT addresses all three: scale invariance, rotation invariance, and rich 128-dimensional descriptors.

SIFT Descriptor — 128 dimensions
A 16x16 pixel region around the keypoint is divided into a 4x4 grid. Each cell gets an 8-bin gradient orientation histogram. Total: $4 \times 4 \times 8 = 128$ dimensions.
SIFT descriptor construction
SIFT descriptor: 4x4 gradient windows, 8 orientation bins, Gaussian weighting, yielding 128-D vector.
PropertyEdgeHarrisHOGSIFT
DescriptiveLowLowHighHighest (128-D)
Rotation-invariantNoYesYesYes
Scale-invariantNoNoNoYes

6. Feature Matching

Given features from two images, find correspondences by comparing descriptor vectors.

Euclidean Distance Matching

For each feature $\mathbf{f}_1$ in Image 1, compute the L2 distance to every feature $\mathbf{f}_2$ in Image 2:

$d(\mathbf{f}_1, \mathbf{f}_2) = \sqrt{\sum_{i=1}^{n}(f_{1,i} - f_{2,i})^2}$

The closest match (smallest distance) is the candidate correspondence. Complexity: $O(N \times M \times D)$.

Improving Match Quality

Feature detection on building
Detected local features shown as colored squares on a building facade.
Interactive — Feature Matching and Lowe's Ratio Test
Image 1 — query features
Image 2 — candidate matches
Press "Generate Features" to create random feature descriptors.

7. Hough Transform — Line Detection

After edge detection, edge pixels are fragmented. The Hough Transform detects geometric shapes (especially lines) by converting the problem to a voting scheme in parameter space.

Polar Line Parameterization

Instead of $y = mx + c$ (fails for vertical lines), use: $\rho = x\cos\theta + y\sin\theta$, where $\rho$ is the perpendicular distance from origin to the line, and $\theta$ is the angle of that perpendicular.

Hough transform parameterization
Line parameterization: rho is perpendicular distance, theta is angle.

The Voting Algorithm

  1. Run Canny to get edge pixels $(x_i, y_i)$
  2. For each edge pixel, compute $\rho = x_i\cos\theta + y_i\sin\theta$ for all $\theta \in [0, 360)$
  3. Increment the accumulator cell at $(\rho, \theta)$ for each computation
  4. Peaks in the accumulator = detected lines (many collinear edge pixels voted for the same $(\rho, \theta)$)
Hough transform voting
Three edge points generate votes; collinear points share the same (rho, theta) pair.
Key insight
A single point in image space maps to a sinusoidal curve in $(\rho, \theta)$ space. Two collinear points have curves that intersect at the line's parameters. The accumulator counts these intersections.
Interactive -- Hough Transform Voting

Click in the image space (left) to place edge points. Each point generates a sinusoidal curve in the parameter space (right). Where curves intersect, a line is detected and drawn back in image space.

Image Space $(x, y)$
Parameter Space $(\theta, \rho)$
Click to place up to 10 edge points.
Post-processing and limitations

Post-processing: Extract top candidates by vote count, cluster nearby lines, select the strongest per cluster, filter false detections.

Strengths: Robust to gaps, detects multiple lines simultaneously, extensible to circles/ellipses.

Limitations: Computational cost scales with parameter space dimensionality. Quantization effects and accidental alignments can produce false lines.

8. Harris Corner Detector

Interest points are locations with distinctive local properties. Corners are ideal because they have intensity changes in multiple directions, making them unique and repeatable.

Corner detection on checkerboard
Corners detected where intensity changes in multiple directions.

The Mathematics

Intensity change when shifting a window by $(u, v)$:

$E(u,v) = \sum_{x,y} w(x,y)[I(x+u, y+v) - I(x,y)]^2$

Using Taylor expansion for small shifts, this becomes:

$E(u,v) \approx \begin{bmatrix} u & v \end{bmatrix} M \begin{bmatrix} u \\ v \end{bmatrix}$

where $M$ is the structure tensor:

$M = \sum_{x,y} w(x,y) \begin{bmatrix} I_x^2 & I_x I_y \\ I_x I_y & I_y^2 \end{bmatrix}$
Harris Corner Response
$R = \det(M) - k \cdot (\text{trace}(M))^2 = \lambda_1\lambda_2 - k(\lambda_1 + \lambda_2)^2$, where $k \approx 0.04$–$0.06$.

Interpreting R via Eigenvalues

Region$\lambda_1$$\lambda_2$$R$
FlatSmallSmall$|R| \approx 0$
EdgeLargeSmall$R < 0$ (negative)
CornerLargeLarge, $\lambda_1 \approx \lambda_2$$R > 0$ (positive)
Interactive -- Harris Corner Explorer

Click on a region in the image below to inspect its structure tensor eigenvalues and Harris response. Adjust $k$ to see how the corner response changes.

Click a region
Eigenvalue Ellipse
Select a region to see eigenvalues and Harris response.
Harris corner response heatmap
Corner response R heatmap: red/yellow = high corner response.

Harris Detector Workflow

  1. Compute gradients $I_x$, $I_y$ (Sobel filters)
  2. Compute structure tensor $M$ at each pixel
  3. Compute $R = \det(M) - k(\text{trace}(M))^2$
  4. Threshold: keep pixels where $R > \text{threshold}$
  5. Non-maximum suppression: take only local maxima
Key insight
Harris corners are not scale-invariant and their $R$ values alone are not very descriptive. But they are excellent seed points for building rich descriptors like SIFT or HOG. The corner is the anchor; the descriptor is the feature.
TransformationHarris invariant?
TranslationYes
RotationYes (eigenvalues unchanged)
ScaleNo (motivates SIFT's pyramid)

9. Haar-like Features

Haar-like features use simple rectangular masks to capture basic intensity patterns in images. The idea is to detect regions where there is a significant difference in intensity between adjacent rectangular sub-regions.

Definition
A Haar-like feature computes the weighted sum of pixel intensities over a rectangular region: pixels under a white rectangle contribute $+1$, pixels under a black rectangle contribute $-1$. A feature is detected when $|\text{white sum} - \text{black sum}| > \text{threshold}$.

Types of Haar-like Features

Three main types exist:

  1. Edge features: Two adjacent rectangles (one white, one black) — detect horizontal or vertical edges
  2. Line features: Three rectangles (white-black-white or black-white-black) — detect line-like structures
  3. Four-rectangle features: A $2 \times 2$ checkerboard pattern — detect diagonal structures
Haar-like feature types: (a) edge features, (b) line features, (c) four-rectangle features
The three types of Haar-like features. White and black regions are assigned weights $+1$ and $-1$ respectively.

Computation

  1. Assign weight $+1$ to white pixels and $-1$ to black pixels in the mask
  2. Slide the mask over the image at all positions and scales
  3. At each position compute the difference: $\text{white sum} - \text{black sum}$
  4. If $|\text{difference}| > \text{threshold}$: a Haar feature is detected at this position
Worked numerical example

Given a $5 \times 5$ image and a $4 \times 4$ edge-feature mask (threshold = 10):

  • Position 1: $|13 - 12| = 1 < 10$ $\rightarrow$ No feature
  • Position 2: $|28 - 24| = 4 < 10$ $\rightarrow$ No feature
  • Position 5: $|9 - 43| = 34 > 10$ $\rightarrow$ Feature detected
  • Position 6: $|8 - 18| = 10 = 10$ $\rightarrow$ Feature detected

The masks are applied in thousands of different sizes and positions across the image.

Cascaded Detection

In practice, Haar features are organised into a cascade of stages. Early stages use very few features and quickly reject non-face regions; later stages use more features to verify candidates. This makes detection fast in practice.

Haar cascade stages for face detection: Stage 0 uses 3 features, Stage 1 uses 10 more, through Stage 21 with 206+ features
Haar cascade for face detection. Stage 0 uses 3 features, Stage 1 adds 10 more, and later stages accumulate 200+ features. Regions failing any stage are immediately discarded.

Properties

ProsCons
Inexpensive computation (especially with integral images) Weak classifiers — the same feature can describe many different things
Obtainable at any scale Features are not invariant to rotation or scale
Too many generated — costly if used without selection
Connection to AdaBoost (Module 3)
Because each Haar feature is a weak classifier on its own, a boosting algorithm such as AdaBoost is used to select the most discriminative features from thousands of candidates and combine them into a single strong cascade classifier.

Flashcards