Module 2/15 · Weeks 2 · 9 h

Feature extraction and image classification

UAT 456 Artificial Intelligence, Machine Learning and Computer Vision for UAS

About 90 minDraft, awaiting reviewLast updated 1 October 2026

Lesson

By the end of this module you will be able to

  1. Explain three groups of image features (colour, edges and texture, shape) and why each is chosen
  2. Compute a cell's gradient-orientation histogram and the HOG vector length of an image window
  3. Build an image classifier from features with standardisation and an SVM
  4. Read a confusion matrix and per-class precision, recall and F1, and find which feature is missing
  5. Explain how hand-designed features relate to the features deep networks learn for themselves

Prerequisites: Module 1 of this course

Why this matters

On our farm, what makes the system miscount most often is not cattle it cannot see but things that look like cattle. Termite mounds in north-eastern pastures have the same red earth colour as red-brown cattle, and bushes cast long shadows shaped like an animal. If the system cannot tell these apart, the head count is too high every morning. Telling them apart needs suitable features, numbers that summarise what is in the image, which a classifier then uses to decide what it is.

Although most work now uses deep neural networks, understanding features still matters. The first layers of a network learn things resembling edge detectors and colour blobs (Yosinski et al., 2014). When the system fails, a developer who knows which features separate the classes finds the cause faster, and small systems that must run on edge devices or have little data can still use hand-designed features well.

Image features

A good feature separates different classes and does not change with irrelevant things, such as the brightness of the sun or the direction a cow faces. Image features fall into three main groups (Szeliski, 2022).

GroupExamplesSeparates wellWeakness
ColourMean and spread of H, S, V; colour histogramsGrass, soil, water, bushesDifferent things of the same colour; colour changes with light
Edges and textureHOG; edge strengthLong versus round shapes; surface patternsDepends on object size in the image
ShapeArea, length-to-width ratio, roundnessObjects that stand out clearly from the groundThe object must be segmented first

The HSV colour space splits colour into hue (H), saturation (S) and value (V). When sunlight weakens, V changes a lot but H changes little, so it tolerates lighting better than raw R, G, B. OpenCV stores images in B, G, R order, and H runs from 0 to 179.

Histograms of oriented gradients (HOG)

HOG (histogram of oriented gradients) describes shape by counting which way the edges in each region point. Dalal and Triggs (2005) used HOG with a linear SVM to detect pedestrians and found that good settings were a gradient filter with no prior smoothing, unsigned orientation from 0 to 180 degrees in 9 bins, 8 × 8-pixel cells, blocks of 2 × 2 cells stepped 8 pixels apart, and normalisation of each block. The steps are:

  1. Compute the horizontal gradient and vertical gradient of every pixel, giving magnitude and orientation
  2. In each cell, each pixel votes its into the bin of its orientation, giving a 9-bin histogram
  3. Join four neighbouring cells into a block (36 values) and divide by the vector’s length, so it does not depend on brightness or contrast
  4. Concatenate all block vectors into the feature of the image window

Unsigned orientation treats a dark-to-bright edge and a bright-to-dark edge as the same direction, which suits cattle that may be brighter or darker than the ground.

Example 1 The histogram of a cell containing a cow’s back corner

An 8 × 8-pixel cell has a bright cow back (value 200) in its lower-right corner on dark grass (value 60). The team writes a simplified HOG function (each pixel votes into one bin only, with no sharing between bins, and L2 normalisation) to see where the numbers come from, then counts the vector length for 32- and 64-pixel windows.

import numpy as np, cv2
# HOG feature of one 8 x 8-pixel cell: a bright corner of a cow's back on darker grass (assumed)
cell = np.full((8, 8), 60.0)
cell[4:, 4:] = 200.0
p = np.pad(cell, 1, mode="edge")
gx = p[1:-1, 2:] - p[1:-1, :-2]           # [-1, 0, 1] filter, horizontal
gy = p[2:, 1:-1] - p[:-2, 1:-1]           # vertical (y axis points down)
mag = np.hypot(gx, gy)
ang = np.degrees(np.arctan2(gy, gx)) % 180   # unsigned orientation, 0-180 degrees
def cell_hist(mag, ang):
    h = np.zeros(9)
    np.add.at(h, (ang // 20).astype(int) % 9, mag)   # vote into one bin (simplified, no sharing between bins)
    return h
print("bins (deg):", [f"{20 * i}-{20 * i + 20}" for i in range(9)])
print("votes     :", np.round(cell_hist(mag.ravel(), ang.ravel()), 1).tolist())

def hog(gray):
    """Simplified HOG: 8 x 8 cells, 9 bins, 2 x 2-cell blocks stepped one cell, L2 normalisation"""
    p = np.pad(gray.astype(float), 1, mode="edge")
    gx, gy = p[1:-1, 2:] - p[1:-1, :-2], p[2:, 1:-1] - p[:-2, 1:-1]
    mag, ang = np.hypot(gx, gy), np.degrees(np.arctan2(gy, gx)) % 180
    ny, nx = gray.shape[0] // 8, gray.shape[1] // 8
    H = np.array([[cell_hist(mag[8*i:8*i+8, 8*j:8*j+8].ravel(), ang[8*i:8*i+8, 8*j:8*j+8].ravel())
                   for j in range(nx)] for i in range(ny)])
    out = [H[i:i+2, j:j+2].ravel() for i in range(ny - 1) for j in range(nx - 1)]
    return np.concatenate([b / np.sqrt((b ** 2).sum() + 1e-6) for b in out])

for win in (32, 64):
    print(f"window {win} px: {(win // 8 - 1) ** 2} blocks x 36 = {hog(np.zeros((win, win))).size} features")
bins (deg): ['0-20', '20-40', '40-60', '60-80', '80-100', '100-120', '120-140', '140-160', '160-180']
votes     : [980.0, 0.0, 198.0, 0.0, 980.0, 0.0, 0.0, 0.0, 0.0]
window 32 px: 9 blocks x 36 = 324 features
window 64 px: 49 blocks x 36 = 1764 features

The vertical edge of the cow’s back (brightness changing horizontally) gives a total of 980 in the 0 to 20 degree bin, the horizontal edge 980 in the 80 to 100 degree bin, and the corner pixel, whose gradient points at 45 degrees with magnitude , falls in the 40 to 60 degree bin. The histogram therefore says this region holds two edges at right angles. A round object such as a termite mound spreads its votes over all bins instead. A 32-pixel window gives a 324-value vector and a 64-pixel window 1,764 values, following .

Nine vertical bars by orientation bin from 0 to 180 degrees: the 0 to 20 bin reaches 980, the 40 to 60 bin 198, the 80 to 100 bin 980, and the others are zero
Figure 1 Gradient orientation histogram of the cow-back corner cell

Real libraries share each pixel’s vote between the two nearest bins to reduce rounding effects, and clip large values before renormalising (L2-Hys), but the principle is the same as the code above.

Shape features come from an object’s mask, for example area (pixel count) and the length-to-width ratio from second-order moments. Seen from above a cow is about 2.5 times as long as it is wide, while a termite mound is close to 1. The object must first be separated from the ground, which is the job of image segmentation in module 4.

Classifying images from features

Image classification says which class an image or part of an image belongs to. This system uses it in two ways: first, screening tiles for whether they contain cattle before passing them to the detector, which saves time when most tiles are empty pasture; second, re-checking whether a box the detector proposes is really a cow or a termite mound. Classification from features has four steps:

  1. Extract features from each image
  2. Standardise the features with training-set values (module 1), because features differ greatly in scale; V runs up to 255 while HOG values are at most 1
  3. Train a classifier such as a support vector machine (SVM), which finds the boundary that separates classes with the largest margin; an RBF kernel lets the boundary curve (Géron, 2025)
  4. Evaluate on a test set not used for training

Evaluation looks beyond overall accuracy. A confusion matrix shows what each true class (row) was predicted as (column). From it come precision , the share of things predicted as this class that are right, and recall , the share of real members of the class that are found, combined as . The macro average weights every class equally, so large classes do not hide small ones (scikit-learn developers).

Example 2 Is colour alone enough to tell cattle from termite mounds?

The team generates 32 × 32-pixel synthetic images of four classes, 150 each: cows (white or red-brown, random heading, with a shadow), termite mounds (round, the same colour as red-brown cattle, with a shadow), bushes and bare soil, on green or dry grass. It compares 6 colour features with colour plus HOG, using an RBF-kernel SVM and the hog function from Example 1 (all images are synthetic).

import numpy as np, cv2
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import confusion_matrix, classification_report

rng = np.random.default_rng(470)
CLASSES = ["cow", "mound", "bush", "soil"]

def patch(c):
    """Synthetic 32 x 32-pixel top-down image (all assumed); colours in OpenCV BGR order"""
    img = np.zeros((32, 32, 3), np.float32)
    img[:] = (70, 130, 80) if rng.random() < 0.6 else (100, 140, 150)    # green grass or dry grass
    x, y = (int(v) for v in rng.integers(13, 19, 2))
    brown = (60, 95, 150)
    if c == "cow":
        col = (175, 195, 210) if rng.random() < 0.5 else brown           # white or red-brown cow
        ang = int(rng.integers(0, 180))
        cv2.ellipse(img, (x + 2, y + 2), (11, 4), ang, 0, 360, (35, 60, 45), -1)   # shadow
        cv2.ellipse(img, (x, y), (11, 4), ang, 0, 360, col, -1)
    elif c == "mound":                                                    # termite mound, same colour as a red cow
        cv2.circle(img, (x + 2, y + 2), 7, (35, 60, 45), -1)
        cv2.circle(img, (x, y), 7, brown, -1)
    elif c == "bush":
        for _ in range(5):
            dx, dy = (int(v) for v in rng.integers(-5, 6, 2))
            cv2.circle(img, (x + dx, y + dy), 4, (30, 75, 35), -1)
    else:
        img[:] = (95, 125, 150)
    img += rng.normal(0, 12, img.shape)
    return np.clip(img, 0, 255).astype(np.uint8)

def features(img):
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)[8:24, 8:24].reshape(-1, 3).astype(float)
    colour = np.r_[hsv.mean(0), hsv.std(0)]                               # 6 colour values
    edges = hog(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))                    # 324 HOG values (Example 1)
    return colour, edges

y = np.repeat(np.arange(4), 150)
F = [features(patch(CLASSES[k])) for k in y]
for name, parts in (("colour", [0]), ("colour + HOG", [0, 1])):
    X = np.array([np.concatenate([f[i] for i in parts]) for f in F])
    Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
    clf = make_pipeline(StandardScaler(), SVC(C=10)).fit(Xtr, ytr)
    pred = clf.predict(Xte)
    print(f"{name}: {X.shape[1]} features, accuracy {np.mean(pred == yte):.3f}")
    print(confusion_matrix(yte, pred))
print(classification_report(yte, pred, target_names=CLASSES, digits=2))
colour: 6 features, accuracy 0.933
[[33 12  0  0]
 [ 0 45  0  0]
 [ 0  0 45  0]
 [ 0  0  0 45]]
colour + HOG: 330 features, accuracy 0.989
[[43  2  0  0]
 [ 0 45  0  0]
 [ 0  0 45  0]
 [ 0  0  0 45]]
              precision    recall  f1-score   support

         cow       1.00      0.96      0.98        45
       mound       0.96      1.00      0.98        45
        bush       1.00      1.00      1.00        45
        soil       1.00      1.00      1.00        45

    accuracy                           0.99       180
   macro avg       0.99      0.99      0.99       180
weighted avg       0.99      0.99      0.99       180

Colour alone reaches 93.3% accuracy, which looks good, but the matrix shows 12 of 45 cows predicted as mounds, so cow recall is only and mound precision . The errors cluster on red-brown cattle, which share the mounds’ colour by design; bushes and soil are separated perfectly by colour. Adding HOG, which captures the long shape of a cow against the round shape of a mound, raises accuracy to 98.9% with only 2 cows wrong and cow recall 0.96. This is how a confusion matrix is used in practice: find which pair of classes the errors cluster on, then ask which feature separates that pair. Beware that these synthetic images are far easier than real ones; real accuracy must be measured on the farm’s images in a test set split by paddock.

Two 4 by 4 confusion matrices; rows are true classes and columns predicted classes: cow, mound, bush, soil. Left, colour only, 93.3 percent: 33 cows correct and 12 predicted as mound in a pink cell. Right, colour plus HOG, 98.9 percent: 43 correct and 2 predicted as mound. Diagonal cells of 45 are green
Figure 2 Confusion matrices of the four-class classifier

From designed features to learned features

In Example 2 the developer had to decide to use colour and HOG. A convolutional neural network (CNN) learns its own filters from data: the first layer ends up with filters resembling edge detectors and colour blobs that are general to almost any image task, while deeper layers learn more task-specific patterns (Yosinski et al., 2014). CNN detection of cattle in drone images works well even in far-from-ideal conditions (Barbedo et al., 2019), so it is the main option for the system in modules 3 to 5.

AspectDesigned features with a classical classifierCNN
Data neededHundreds of imagesThousands or more, or start from a pretrained model (module 5)
ComputationLight; runs on a CPUHeavy; usually needs a GPU or accelerator
Explaining resultsYou can see which features matterHarder to explain
Accuracy on complex imagesLimitedMuch higher with enough data

Real systems therefore often combine them, for example using a CNN to detect and simple features such as area and colour to reject impossible boxes, such as boxes smaller than a calf or larger than three cows.

Module lab

Lab: features and a classifier for cattle and look-alikes

  1. Cut 32 × 32 or 64 × 64-pixel patches from the module 1 dataset, at least 4 classes with 50 patches each
  2. Compute one cell’s histogram by hand and with the code in Example 1, and compare
  3. Extract colour and HOG features and train an SVM with the code in Example 2, splitting the test set by paddock or date
  4. Read the confusion matrix, find the most confused pair of classes, then propose and test one additional feature
  5. Report per-class precision, recall and F1 and the macro average before and after adding the feature

Common mistakes

Watch out

  • Looking only at overall accuracy without the confusion matrix, so you never learn which class the errors cluster in
  • Not standardising features, so large-valued features swamp the others in the SVM
  • Using R, G, B instead of HSV when light changes a lot between morning and midday
  • Choosing a HOG window that does not match object size, so cells are too large and key edges are averaged away
  • Mixing up rows and columns of the confusion matrix, swapping precision and recall
  • Trusting results from synthetic images or randomly split test sets as field performance

Summary

  • Features come in three groups: colour, edges and texture, and shape; good features separate classes and ignore irrelevant changes
  • HOG sums gradient magnitude by orientation in 8 × 8-pixel cells with 9 bins and normalises per block; the vector length is
  • Classifying from features means extracting features, standardising, training a classifier and evaluating on a held-out test set
  • The confusion matrix and per-class precision, recall and F1 reveal which feature is missing
  • CNNs learn their own features and are more accurate with enough data; real systems often combine them with simple features

Check your understanding

  1. A 48 × 48-pixel HOG window with 8-pixel cells and 2 × 2 blocks stepped one cell gives how many values?
  2. A gradient points at 200 degrees. With 9 unsigned bins, which bin does it fall in?
  3. A classifier predicts “cow” 50 times and is right 45 times; there are 60 real cows. What are cow precision and recall?
  4. Why can colour alone not separate red-brown cattle from termite mounds, while HOG can help?
  5. Why does HSV tolerate changing light better than R, G, B?
Answers
  1. values
  2. degrees, so the 20 to 40 degree bin
  3. Precision ; recall
  4. Both have the same colour, so their colour features match, but their shapes differ: a long cow has strong edges in two directions while a round mound has edges in every direction, and HOG captures that difference in edge orientation
  5. Stronger or weaker light mainly changes V (value) while H (hue) changes little, whereas in R, G, B all three channels change together

Key formulas

Gradient magnitude and orientation
HOG vector length (8-pixel cells, 2 x 2 blocks, one-cell stride)
Precision and recall
F1

Key references

  1. Dalal, N., & Triggs, B. (2005). Histograms of oriented gradients for human detection. In 2005 IEEE Computer Society Conference on Computer Vision and Pattern Recognition (CVPR'05) (Vol. 1, pp. 886–893). IEEE. https://doi.org/10.1109/CVPR.2005.177 link
  2. Szeliski, R. (2022). Computer vision: Algorithms and applications (2nd ed.). Springer. link
  3. scikit-learn developers. Metrics and scoring: Quantifying the quality of predictions (scikit-learn 1.9). link
  4. Géron, A. (2025). Hands-on machine learning with Scikit-Learn and PyTorch. O'Reilly. link
  5. Barbedo, J. G. A., Koenigkan, L. V., Santos, T. T., & Santos, P. M. (2019). A study on the detection of cattle in UAV images using deep learning. Sensors, 19(24), 5436. https://doi.org/10.3390/s19245436 link
  6. Yosinski, J., Clune, J., Bengio, Y., & Lipson, H. (2014). How transferable are features in deep neural networks? In Advances in Neural Information Processing Systems 27 (NIPS 2014). arXiv:1411.1792. link

Further reading

Study the assigned knowledge units in advance, review media and take the module quiz

In class / field

Lab or field practice from worksheets with a safety checklist

Learning evidence: Checked worksheets and quiz results

Module quiz

This is a formative self-check, not a graded exam

Knowledge domain: Artificial intelligence and computer vision