TExcelTAD
Home › Computer Vision: Images to Detection, Segmentation & Tracking › Image Classification: Pipeline and Classical Baselines

Image Classification: Pipeline and Classical Baselines

Image classification answers one question per image: which of KK classes is it? It is the simplest vision task to state and the one every other task builds on, because detectors and segmenters are classifiers applied to regions or pixels. Before any neural network, this lesson builds the whole pipeline with classical tools that run in your browser: a nearest-centroid classifier from scratch, raw pixels with logistic regression, and HOG features with a linear SVM. These are the baselines a CNN must beat (the next lesson trains one on the same data), and the way they fail (a slightly rotated image is enough) explains why convolutional networks took over.

The pipeline

datalabels, split preprocesssize, scale featurespixels, HOG, CNN classifierLR, SVM, softmax evaluatetest set only classical: features designed by hand, classifier learned CNN: features and classifier learned together, end to end
  1. Data. Images with one label each, split before anything is fitted into training, validation and test parts, so that no test image (or a near-copy of one) influences any choice (split strategies, leakage rules).
  2. Preprocessing. A fixed size, a fixed channel order, values scaled to a fixed range (image preparation). Any statistic (mean, standard deviation) is computed on the training part only.
  3. Features. Numbers that describe the image. Raw pixels are features too, just bad ones: a shape moved by 3 pixels has completely different pixel values.
  4. Classifier. Maps features to class scores. For KK classes with feature vector x\mathbf{x}, a linear classifier computes one score per class, sk=wk⊤x+bks_k = \mathbf{w}_k^\top \mathbf{x} + b_k, and predicts arg⁡max⁡ksk\arg\max_k s_k; logistic regression turns the scores into probabilities with the softmax.
  5. Evaluation. Accuracy, the confusion matrix and per-class precision and recall (classification metrics) on the test set, plus robustness tests: the same test images, transformed in ways that should not change the label.

The data: shape crops

The lessons of this section use generated 32 x 32 colour crops, each with one square, circle or triangle on a noisy grey background, at a random position, size (circumradius 7 to 10 pixels) and colour, turned by at most about 11 degrees. The shape's centre is drawn inside a disc around the image centre, small enough that any rotation of the whole crop about its centre keeps the shape in the frame, which the robustness tests below rely on. The generator is a one-object variant of the course's make_scene. Generated data has an exact label for every image and costs nothing; its limit is that it is far simpler than photographs, so the numbers here say which method is more robust, not how well any of them would do on real images.

python · try it yourself
import numpy as np, cv2
import matplotlib.pyplot as plt

CLASSES = ["square", "circle", "triangle"]

def make_crop(rng, c, size=32, hard=False):
    """Lesson variant of make_scene: ONE shape of class c on a noisy grey background, size x size RGB uint8.
    hard=True (Project 1) adds any rotation, a wider size range and strong pixel noise."""
    img = rng.normal(110, 12, (size, size, 3))
    r = rng.uniform(5, 13) if hard else rng.uniform(7, 10)          # circumradius in pixels
    a, d = rng.uniform(0, 2 * np.pi), rng.uniform(0, size / 2 - r - 1)
    cx, cy = size / 2 + d * np.cos(a), size / 2 + d * np.sin(a)     # inside a disc: rotations keep it in the frame
    turn = rng.uniform(0, 2 * np.pi) if hard else rng.uniform(-0.2, 0.2)
    m = np.zeros((size, size), np.uint8)
    if c == 1:
        cv2.circle(m, (int(round(cx)), int(round(cy))), int(round(r)), 1, -1)
    else:
        k = 4 if c == 0 else 3
        t = turn + (np.pi / 4 if c == 0 else -np.pi / 2) + np.arange(k) * 2 * np.pi / k
        cv2.fillPoly(m, [np.round(np.stack([cx + r * np.cos(t), cy + r * np.sin(t)], 1)).astype(np.int32)], 1)
    img[m > 0] = rng.integers(0, 256, 3)
    if hard:
        img = img + rng.normal(0, 20, img.shape)
    return img.clip(0, 255).astype(np.uint8)

def make_set(rng, n, hard=False):
    y = rng.integers(0, 3, n)
    return np.array([make_crop(rng, int(c), hard=hard) for c in y]), y

rng = np.random.default_rng(0)
X_train, y_train = make_set(rng, 900)
X_test, y_test = make_set(rng, 600)
print("train", X_train.shape, X_train.dtype, "| test", X_test.shape)
print("train images per class:", np.bincount(y_train).tolist(), "| test:", np.bincount(y_test).tolist())

# from scratch: nearest centroid on grey pixels scaled to 0..1
grey = lambda X: X.mean(axis=3).reshape(len(X), -1) / 255
G_train, G_test = grey(X_train), grey(X_test)
centroids = np.array([G_train[y_train == k].mean(0) for k in range(3)])     # the "average square", ...
dist = ((G_test[:, None, :] - centroids[None]) ** 2).sum(-1)               # (600, 3) squared distances
pred = dist.argmin(1)
print(f"nearest centroid on pixels: test accuracy {(pred == y_test).mean():.3f} (chance {1 / 3:.3f})")

fig, axes = plt.subplots(2, 8, figsize=(8, 2.3))
for i, ax in enumerate(axes.flat[:12]):
    ax.imshow(X_train[i]); ax.set_title(CLASSES[y_train[i]], fontsize=7); ax.axis("off")
for k, ax in enumerate(axes.flat[12:15]):
    ax.imshow(centroids[k].reshape(32, 32), cmap="gray"); ax.set_title("mean " + CLASSES[k], fontsize=7); ax.axis("off")
axes.flat[15].axis("off")
plt.tight_layout()
train (900, 32, 32, 3) uint8 | test (600, 32, 32, 3)
train images per class: [287, 286, 327] | test: [193, 191, 216]
nearest centroid on pixels: test accuracy 0.367 (chance 0.333)

The 900 training and 600 test crops are roughly balanced (287, 286 and 327 training images per class). The nearest-centroid classifier reaches 0.367 test accuracy, barely above chance (0.333), and the mean images in the last panels show why: because the shapes appear anywhere and in any colour, brighter or darker than the background, the "average square" and the "average circle" are both a soft blob in the middle; only the average triangle keeps a faint point. A classifier that compares pixel by pixel has little to go on.

Raw pixels with logistic regression vs HOG with a linear SVM

A learned linear classifier on the 3,072 raw RGB values does better than the centroid, because it can weight pixels, but it still sees a shape at position A and the same shape at position B as unrelated inputs. HOG (histogram of oriented gradients, built from scratch in classical features) describes each 8 x 8 cell by a histogram of edge directions and normalises it over blocks of cells. That throws away colour and absolute brightness, keeps shape, and tolerates small shifts within a cell. With 99 orientation bins, 8×88 \times 8 cells and 2×22 \times 2 cells per block on a 32 x 32 image, there are 3×33 \times 3 block positions and

3⋅3 blocks×2⋅2 cells×9 bins=324 features3 \cdot 3 \ \text{blocks} \times 2 \cdot 2 \ \text{cells} \times 9 \ \text{bins} = 324 \ \text{features}

The regularisation strength C of each model is chosen by 3-fold cross-validation on the training set; the test set is used once, at the end.

python · try it yourself
import numpy as np, cv2
from skimage.feature import hog
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import confusion_matrix, classification_report

CLASSES = ["square", "circle", "triangle"]

def make_crop(rng, c, size=32, hard=False):
    """Lesson variant of make_scene: ONE shape of class c on a noisy grey background, size x size RGB uint8.
    hard=True (Project 1) adds any rotation, a wider size range and strong pixel noise."""
    img = rng.normal(110, 12, (size, size, 3))
    r = rng.uniform(5, 13) if hard else rng.uniform(7, 10)          # circumradius in pixels
    a, d = rng.uniform(0, 2 * np.pi), rng.uniform(0, size / 2 - r - 1)
    cx, cy = size / 2 + d * np.cos(a), size / 2 + d * np.sin(a)     # inside a disc: rotations keep it in the frame
    turn = rng.uniform(0, 2 * np.pi) if hard else rng.uniform(-0.2, 0.2)
    m = np.zeros((size, size), np.uint8)
    if c == 1:
        cv2.circle(m, (int(round(cx)), int(round(cy))), int(round(r)), 1, -1)
    else:
        k = 4 if c == 0 else 3
        t = turn + (np.pi / 4 if c == 0 else -np.pi / 2) + np.arange(k) * 2 * np.pi / k
        cv2.fillPoly(m, [np.round(np.stack([cx + r * np.cos(t), cy + r * np.sin(t)], 1)).astype(np.int32)], 1)
    img[m > 0] = rng.integers(0, 256, 3)
    if hard:
        img = img + rng.normal(0, 20, img.shape)
    return img.clip(0, 255).astype(np.uint8)

def make_set(rng, n, hard=False):
    y = rng.integers(0, 3, n)
    return np.array([make_crop(rng, int(c), hard=hard) for c in y]), y

def hog_features(X):
    return np.array([hog(im, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(2, 2),
                         channel_axis=-1) for im in X])          # strongest gradient over R, G, B

rng = np.random.default_rng(0)
X_train, y_train = make_set(rng, 900)
X_test, y_test = make_set(rng, 600)
P_train, P_test = X_train.reshape(900, -1) / 255, X_test.reshape(600, -1) / 255
H_train, H_test = hog_features(X_train), hog_features(X_test)
print("features per image: pixels", P_train.shape[1], "| HOG", H_train.shape[1])

models = {
    "pixels + logistic": (make_pipeline(StandardScaler(), LogisticRegression(max_iter=300)),
                          {"logisticregression__C": [1e-6, 1e-5, 1e-4, 1e-3, 1e-2]}, P_train, P_test),
    "HOG + linear SVM": (make_pipeline(StandardScaler(), LinearSVC()),
                         {"linearsvc__C": [1e-4, 1e-3, 1e-2, 1e-1]}, H_train, H_test),
}
for name, (pipe, grid, F_train, F_test) in models.items():
    search = GridSearchCV(pipe, grid, cv=3).fit(F_train, y_train)
    pred = search.predict(F_test)
    C = list(search.best_params_.values())[0]
    print(f"\n{name}: best C {C}, CV accuracy {search.best_score_:.3f}, TEST accuracy {(pred == y_test).mean():.3f}")
    print("confusion matrix (rows = true square, circle, triangle):")
    print(confusion_matrix(y_test, pred))
print()
print(classification_report(y_test, pred, target_names=CLASSES, digits=3))
features per image: pixels 3072 | HOG 324

pixels + logistic: best C 0.0001, CV accuracy 0.438, TEST accuracy 0.418
confusion matrix (rows = true square, circle, triangle):
[[ 34  35 124]
 [ 36  67  88]
 [ 49  17 150]]

HOG + linear SVM: best C 0.001, CV accuracy 0.923, TEST accuracy 0.940
confusion matrix (rows = true square, circle, triangle):
[[179   8   6]
 [ 11 173   7]
 [  4   0 212]]

              precision    recall  f1-score   support

      square      0.923     0.927     0.925       193
      circle      0.956     0.906     0.930       191
    triangle      0.942     0.981     0.961       216

    accuracy                          0.940       600
   macro avg      0.940     0.938     0.939       600
weighted avg      0.940     0.940     0.940       600

Raw pixels reach only 0.418 test accuracy (cross-validation said 0.438 and picked a strongly regularised C = 0.0001), and the confusion matrix shows the model mostly predicting "triangle". HOG + SVM reaches 0.940 (cross-validation 0.923: close, as they should be when nothing leaked). Read the confusion matrices row by row: each row is a true class, each column a predicted one, so off-diagonal entries are the confusions. The classification report under them is for the last model, HOG + SVM, with precision, recall and F1 per class on the 600 test images (about 200 per class, so one image is half a percentage point of recall). Triangles are recognised best (recall 0.981); most HOG errors are squares and circles taken for each other (8 and 11 images).

A robustness check

A test score says how a model does on images like the training images. Deployment brings other images: a camera tilted by a few degrees, a brighter room, a noisier sensor. A cheap robustness test applies such label-preserving changes to the test set and measures again (robustness testing treats this systematically). The transforms below never touch the training data.

python · try it yourself
import numpy as np, cv2
from skimage.feature import hog
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline

CLASSES = ["square", "circle", "triangle"]

def make_crop(rng, c, size=32, hard=False):
    """Lesson variant of make_scene: ONE shape of class c on a noisy grey background, size x size RGB uint8.
    hard=True (Project 1) adds any rotation, a wider size range and strong pixel noise."""
    img = rng.normal(110, 12, (size, size, 3))
    r = rng.uniform(5, 13) if hard else rng.uniform(7, 10)          # circumradius in pixels
    a, d = rng.uniform(0, 2 * np.pi), rng.uniform(0, size / 2 - r - 1)
    cx, cy = size / 2 + d * np.cos(a), size / 2 + d * np.sin(a)     # inside a disc: rotations keep it in the frame
    turn = rng.uniform(0, 2 * np.pi) if hard else rng.uniform(-0.2, 0.2)
    m = np.zeros((size, size), np.uint8)
    if c == 1:
        cv2.circle(m, (int(round(cx)), int(round(cy))), int(round(r)), 1, -1)
    else:
        k = 4 if c == 0 else 3
        t = turn + (np.pi / 4 if c == 0 else -np.pi / 2) + np.arange(k) * 2 * np.pi / k
        cv2.fillPoly(m, [np.round(np.stack([cx + r * np.cos(t), cy + r * np.sin(t)], 1)).astype(np.int32)], 1)
    img[m > 0] = rng.integers(0, 256, 3)
    if hard:
        img = img + rng.normal(0, 20, img.shape)
    return img.clip(0, 255).astype(np.uint8)

def make_set(rng, n, hard=False):
    y = rng.integers(0, 3, n)
    return np.array([make_crop(rng, int(c), hard=hard) for c in y]), y

def hog_features(X):
    return np.array([hog(im, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(2, 2),
                         channel_axis=-1) for im in X])

def rotate(X, deg):
    M = cv2.getRotationMatrix2D((15.5, 15.5), deg, 1.0)
    return np.array([cv2.warpAffine(im, M, (32, 32), borderMode=cv2.BORDER_REFLECT_101) for im in X])

rng = np.random.default_rng(0)
X_train, y_train = make_set(rng, 900)
X_test, y_test = make_set(rng, 600)
pix = make_pipeline(StandardScaler(), LogisticRegression(C=1e-4, max_iter=300))     # C chosen by CV above
hogsvm = make_pipeline(StandardScaler(), LinearSVC(C=1e-3))
pix.fit(X_train.reshape(900, -1) / 255, y_train)
hogsvm.fit(hog_features(X_train), y_train)

noise_rng = np.random.default_rng(1)
tests = {
    "original": X_test,
    "rotated 20 deg": rotate(X_test, 20),
    "rotated 45 deg": rotate(X_test, 45),
    "brighter (+40)": np.clip(X_test.astype(int) + 40, 0, 255).astype(np.uint8),
    "noise sigma 25": np.clip(X_test + noise_rng.normal(0, 25, X_test.shape), 0, 255).astype(np.uint8),
    "blurred 3 x 3": np.array([cv2.GaussianBlur(im, (3, 3), 0) for im in X_test]),
}
print(f"{'test condition':16s} {'pixels+LR':>10s} {'HOG+SVM':>9s}")
for name, X in tests.items():
    a = (pix.predict(X.reshape(len(X), -1) / 255) == y_test).mean()
    b = (hogsvm.predict(hog_features(X)) == y_test).mean()
    print(f"{name:16s} {a:10.3f} {b:9.3f}")
sq = y_test == 0
print("HOG+SVM on squares rotated 45 deg, predicted as:",
      np.bincount(hogsvm.predict(hog_features(rotate(X_test[sq], 45))), minlength=3).tolist(), "(square, circle, triangle)")
test condition    pixels+LR   HOG+SVM
original              0.418     0.940
rotated 20 deg        0.423     0.742
rotated 45 deg        0.405     0.302
brighter (+40)        0.317     0.943
noise sigma 25        0.410     0.550
blurred 3 x 3         0.442     0.905
HOG+SVM on squares rotated 45 deg, predicted as: [0, 163, 30] (square, circle, triangle)

The pixel model is poor everywhere, so it has little to lose; it is even hurt by brightness, because a brighter background moves every pixel value. HOG + SVM ignores a brightness change (0.943 against 0.940), because gradients do not change when a constant is added, and survives a light blur (0.905). But it falls to 0.742 when the test images turn by 20 degrees and to 0.302, below chance, at 45 degrees: the training squares had horizontal and vertical edges, a square turned by 45 degrees has only diagonal ones, and of the squares 163 become circles and 30 triangles, none stays a square. Strong pixel noise (0.550) also hurts, because HOG's gradients are computed from single neighbouring pixels. None of this showed in the test score of 0.940: the test set was drawn exactly like the training set. Both weaknesses (rotation and noise) are what Project 1 attacks with augmentation and a CNN.

Pitfalls

  • Fitting preprocessing on all the data. The scaler, the PCA, the vocabulary of a bag of visual words: fit them on the training part only, inside a pipeline, so cross-validation refits them per fold.
  • Near-duplicates across the split. Frames of one video, crops of one photo, the same product photographed twice: split by the source, not by the image, or the test score is inflated (split strategies).
  • Reporting only accuracy. With unbalanced classes accuracy hides a class that is never predicted; read the confusion matrix and per-class recall.
  • Testing only on clean images. A model can score well on a test set drawn like the training set and fail on a 20-degree rotation. Add the transformations deployment will bring to the test, never to the choice of hyperparameters on the test set.
  • Augmenting with label-changing transforms. A rotated 6 is a 9, a mirrored "b" is a "d"; only transformations that keep the label are augmentations (image augmentation).

Practice

  1. How many HOG features would a 64 x 64 image give with the same settings (9 bins, 8 x 8 cells, 2 x 2 cells per block, blocks moving by one cell)?
  2. In the robustness table, which model is hurt most by rotation, and why does HOG help only partly?
  3. How would you make the HOG + SVM model robust to rotations of any angle, without changing the features?
Answer
  1. 8×88 \times 8 cells, so 7×77 \times 7 block positions; 49⋅4⋅9=176449 \cdot 4 \cdot 9 = 1764 features.
  2. HOG + SVM loses most: from 0.940 to 0.742 at 20 degrees and 0.302 at 45. The pixel model was close to chance already, so it has little to lose. HOG keeps gradient directions, and rotation changes exactly those: a square turned by 45 degrees has diagonal edges, which the SVM has only seen on triangles and on the round outline of circles. HOG tolerates small shifts within a cell and brightness changes, not rotation.
  3. Train on rotated copies (augmentation with rotations of any angle, a label-preserving transform for these shapes), so the classifier sees every edge direction for every class. A CNN with the same augmentation does this better, which is part of the next lesson.

Test yourself

Why does a linear classifier on raw pixels do poorly on these shape crops?

  1. Because pixels are integers
  2. Because the same shape at another position or in another colour gives completely different pixel values, so the classifier cannot weight pixels in a way that works for all positions
  3. Because 32 x 32 is too small
  4. Because logistic regression needs grey images

The C of each model was chosen by cross-validation on the training set. Why not choose it on the test set?

  1. It would be slower
  2. Choosing on the test set makes the test score optimistic: it is then part of the tuning, not an independent measurement
  3. Cross-validation gives a larger C
  4. The test set has no labels

How many features does HOG give for a 32 x 32 image with 9 bins, 8 x 8 pixel cells and 2 x 2 cells per block?

  1. 36
  2. 144
  3. 324
  4. 1024

What is a robustness test for an image classifier?

  1. Training longer
  2. Measuring the trained model again on test images changed in label-preserving ways (rotation, brightness, noise, blur) that deployment may bring
  3. Testing on the training set
  4. Using a larger model