TExcelTAD
Home › ML Projects: 15 End-to-End Builds › Project 8: Image Classification with a CNN

Project 8: Image Classification with a CNN

A steel mill sells brushed stainless sheet, and a camera above the line photographs every sheet. The quality team wants a model that looks at each 48 x 48 pixel patch of the photo and says ok, scratch, spot or crack: a defective patch must not slip through, a good one should not be thrown away without reason, and the defect type tells the engineers which machine to check. The level is intermediate; the main skills are building a labelled image set, a classical baseline, a small CNN in PyTorch, an augmentation ablation, choosing an operating threshold for unequal costs, an error analysis and an export that runs without PyTorch.

You have trained image classifiers twice before: three architectures on the 8 x 8 digits in the deep learning mini project, and a shape classifier on noisy backgrounds in the computer vision classification project. Both had an object in the middle of an empty frame. Here the background is a texture that looks like a defect everywhere, the defect is a few pixels anywhere in the patch, the two kinds of error have different costs, and the result has to leave the notebook as a file. Project 9 continues with the same data on a second production line.

camerasheet photo patches48 x 48 grey CNN4 class probs P(ok) < 0.6 ?threshold reject+ defect type pass yesno green = built and chosen in this project

Goal and success criteria

Fixed with the quality team before any model was trained:

Criterion Target Measured on
escape rate: defective patches passed as ok at most 0.02 800 test patches, used once
false reject rate: good patches rejected at most 0.05 the same
macro recall over the four classes (right defect type) at least 0.90 the same
better than the best classical baseline higher validation accuracy 400 validation patches
cost training under 30 s on a CPU, model under 1 MB, inference without PyTorch the recorded runs

An escape costs far more than a false reject (a customer complaint against a re-inspection), which is why the two are separate targets and why the threshold in Step 4 is not simply the most likely class (thresholds and costs).

The data

Real patches would come from the line camera and be labelled by the quality inspectors, with a written guideline for borderline cases (ground truth and annotation). The images belong to the company and may be confidential (they show its process), but they contain no people. Real defects are rare, perhaps one patch in a few hundred, so a labelled set is usually enriched with defects, as here.

This project generates the patches instead. make_defect draws brushed steel (noise smeared horizontally, so it streaks), adds uneven lighting, and then one defect:

Class Drawn as Size Contrast
ok nothing
scratch a straight bright line, 1 pixel wide, any angle 18 to 40 px long +12 to +45 grey levels
spot a small dark disc, blurred edge radius 1.5 to 5 px -15 to -55
crack a dark jagged walk of 5 to 9 steps of 3 px 15 to 27 px -15 to -50

It also returns each defect's length and contrast, facts a real data set would not have and which make the error analysis in Step 4 possible. The argument line="B" draws the second production line of Project 9; this project uses only line A. The class shares are 40 % ok and 20 % for each defect. Training (1,200), validation (400) and test (800) patches are drawn one after another from one generator seeded with 8, so every step can rebuild exactly the same sets, and no patch is in two sets. Every score in this lesson is a score on this generator, not a promise about real steel.

Step 1: look at the data

Each step is a complete program: the generator comes first in every one of them.

python · try it yourself
import numpy as np, cv2

CLASSES = ["ok", "scratch", "spot", "crack"]

def make_defect(rng, c, size=48, line="A"):
    """One grey surface patch (uint8, size x size) of class c from production line "A" or "B".
    Also returns the defect's length in pixels and its contrast in grey levels (0, 0 for "ok")."""
    if line == "A":                                   # brushed steel: horizontal streaks
        streak = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=8, sigmaY=0.7)
        img = 135 + 9 * streak / streak.std() + rng.normal(0, 5, (size, size))
    else:                                             # cast aluminium: darker and grainy
        grain = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=1.5)
        img = 95 + 10 * grain / grain.std() + rng.normal(0, 4, (size, size))
    img += np.linspace(-1, 1, size)[None, :] * rng.uniform(-12, 12)    # uneven lighting
    m = np.zeros((size, size), np.float32)
    length, contrast = 0.0, 0.0
    if c == 1:                                        # scratch: long, straight, thin, bright
        length = rng.uniform(18, 40); a = rng.uniform(0, np.pi)
        cx, cy = rng.uniform(14, size - 14, 2)
        dx, dy = np.cos(a) * length / 2, np.sin(a) * length / 2
        cv2.line(m, (int(cx - dx), int(cy - dy)), (int(cx + dx), int(cy + dy)), 1.0, 1, cv2.LINE_AA)
        contrast = rng.uniform(12, 45)
    elif c == 2:                                      # spot: small, round, dark
        r = rng.uniform(1.5, 5); length = 2 * r
        cv2.circle(m, tuple(int(v) for v in rng.uniform(8, size - 8, 2)), int(round(r)), 1.0, -1, cv2.LINE_AA)
        m = cv2.GaussianBlur(m, (0, 0), 0.8)
        contrast = -rng.uniform(15, 55)
    elif c == 3:                                      # crack: jagged dark random walk
        p = rng.uniform(12, size - 12, 2); a = rng.uniform(0, 2 * np.pi)
        steps = int(rng.integers(5, 10))
        for _ in range(steps):
            a += rng.normal(0, 0.6)
            q = np.clip(p + 3 * np.array([np.cos(a), np.sin(a)]), 1, size - 2)
            cv2.line(m, (int(p[0]), int(p[1])), (int(q[0]), int(q[1])), 1.0, 1, cv2.LINE_AA)
            p = q
        length = 3.0 * steps
        contrast = -rng.uniform(15, 50)
    img = img + contrast * m
    return np.clip(img, 0, 255).astype(np.uint8), length, abs(contrast)

def make_set(rng, n, line="A", p=(0.4, 0.2, 0.2, 0.2)):
    """n patches with class shares p; returns images (n, 48, 48), labels, defect lengths, contrasts."""
    y = rng.choice(4, size=n, p=p)
    out = [make_defect(rng, int(c), line=line) for c in y]
    return np.stack([o[0] for o in out]), y, np.array([o[1] for o in out]), np.array([o[2] for o in out])

rng = np.random.default_rng(8)
X_tr, y_tr, len_tr, con_tr = make_set(rng, 1200)
X_va, y_va, len_va, con_va = make_set(rng, 400)
X_te, y_te, len_te, con_te = make_set(rng, 800)
print("images:", X_tr.shape, X_tr.dtype)
for name, y in [("train", y_tr), ("val", y_va), ("test", y_te)]:
    print(f"{name:5s} {len(y):4d} images, per class", dict(zip(CLASSES, np.bincount(y, minlength=4).tolist())))

print("class    mean grey  darkest  brightest  length  contrast   (train)")
for c, name in enumerate(CLASSES):
    X = X_tr[y_tr == c].reshape(-1, 48 * 48).astype(float)
    print(f"{name:8s} {X.mean():9.1f} {np.percentile(X.min(1), 50):8.0f} {np.percentile(X.max(1), 50):10.0f}"
          f" {len_tr[y_tr == c].mean():7.1f} {con_tr[y_tr == c].mean():9.1f}")

import matplotlib.pyplot as plt
fig, axes = plt.subplots(4, 6, figsize=(7.2, 5))
for c in range(4):
    for i, idx in enumerate(np.flatnonzero(y_tr == c)[:6]):
        axes[c, i].imshow(X_tr[idx], cmap="gray", vmin=60, vmax=210)
        axes[c, i].set_xticks([]); axes[c, i].set_yticks([])
    axes[c, 0].set_ylabel(CLASSES[c])
fig.suptitle("Line A: six training patches per class")
plt.tight_layout()
images: (1200, 48, 48) uint8
train 1200 images, per class {'ok': 479, 'scratch': 282, 'spot': 242, 'crack': 197}
val    400 images, per class {'ok': 157, 'scratch': 86, 'spot': 79, 'crack': 78}
test   800 images, per class {'ok': 337, 'scratch': 165, 'spot': 143, 'crack': 155}
class    mean grey  darkest  brightest  length  contrast   (train)
ok           134.5       97        171     0.0       0.0
scratch      134.8       97        181    29.1      28.2
spot         133.8       87        171     6.8      34.7
crack        134.3       86        171    20.7      31.2

The class shares are close to 40/20/20/20 in every split. The table is the first warning: the mean grey level is the same for every class (133.8 to 134.8), and the darkest and brightest pixels overlap. A spot moves the darkest pixel of a patch from about 97 to 87, less than the lighting changes between patches. Whatever the model is, it has to find a local pattern and ignore the streaks, wherever the defect sits. The figure (under the output) shows why it is not trivial: faint scratches almost vanish in the streaks.

Step 2: baselines

Before a network, three baselines on the validation set (error analysis starts here):

  1. Always "ok": the accuracy of doing nothing.
  2. HOG + logistic regression: histograms of gradient directions in a 5 x 5 grid of blocks (classical features), 900 numbers.
  3. Pooled residual features: subtract a horizontal blur to remove the streaks, then keep only position-free summaries: for each of 8 gradient directions its largest and mean strength over the 36 cells, five percentiles of the residual and the number of very dark and very bright pixels. 23 numbers, designed with knowledge of the defects (image filtering).

C is chosen on validation; the test set is not even generated in this program.

python · try it yourself
import numpy as np, cv2

CLASSES = ["ok", "scratch", "spot", "crack"]

def make_defect(rng, c, size=48, line="A"):
    """One grey surface patch (uint8, size x size) of class c from production line "A" or "B".
    Also returns the defect's length in pixels and its contrast in grey levels (0, 0 for "ok")."""
    if line == "A":                                   # brushed steel: horizontal streaks
        streak = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=8, sigmaY=0.7)
        img = 135 + 9 * streak / streak.std() + rng.normal(0, 5, (size, size))
    else:                                             # cast aluminium: darker and grainy
        grain = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=1.5)
        img = 95 + 10 * grain / grain.std() + rng.normal(0, 4, (size, size))
    img += np.linspace(-1, 1, size)[None, :] * rng.uniform(-12, 12)    # uneven lighting
    m = np.zeros((size, size), np.float32)
    length, contrast = 0.0, 0.0
    if c == 1:                                        # scratch: long, straight, thin, bright
        length = rng.uniform(18, 40); a = rng.uniform(0, np.pi)
        cx, cy = rng.uniform(14, size - 14, 2)
        dx, dy = np.cos(a) * length / 2, np.sin(a) * length / 2
        cv2.line(m, (int(cx - dx), int(cy - dy)), (int(cx + dx), int(cy + dy)), 1.0, 1, cv2.LINE_AA)
        contrast = rng.uniform(12, 45)
    elif c == 2:                                      # spot: small, round, dark
        r = rng.uniform(1.5, 5); length = 2 * r
        cv2.circle(m, tuple(int(v) for v in rng.uniform(8, size - 8, 2)), int(round(r)), 1.0, -1, cv2.LINE_AA)
        m = cv2.GaussianBlur(m, (0, 0), 0.8)
        contrast = -rng.uniform(15, 55)
    elif c == 3:                                      # crack: jagged dark random walk
        p = rng.uniform(12, size - 12, 2); a = rng.uniform(0, 2 * np.pi)
        steps = int(rng.integers(5, 10))
        for _ in range(steps):
            a += rng.normal(0, 0.6)
            q = np.clip(p + 3 * np.array([np.cos(a), np.sin(a)]), 1, size - 2)
            cv2.line(m, (int(p[0]), int(p[1])), (int(q[0]), int(q[1])), 1.0, 1, cv2.LINE_AA)
            p = q
        length = 3.0 * steps
        contrast = -rng.uniform(15, 50)
    img = img + contrast * m
    return np.clip(img, 0, 255).astype(np.uint8), length, abs(contrast)

def make_set(rng, n, line="A", p=(0.4, 0.2, 0.2, 0.2)):
    """n patches with class shares p; returns images (n, 48, 48), labels, defect lengths, contrasts."""
    y = rng.choice(4, size=n, p=p)
    out = [make_defect(rng, int(c), line=line) for c in y]
    return np.stack([o[0] for o in out]), y, np.array([o[1] for o in out]), np.array([o[2] for o in out])
from skimage.feature import hog
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline

rng = np.random.default_rng(8)
X_tr, y_tr, _, _ = make_set(rng, 1200)
X_va, y_va, _, _ = make_set(rng, 400)           # the test set is not even generated here

def report(name, pred):
    recall = [float((pred[y_va == c] == c).mean()) for c in range(4)]
    escape = float((pred[y_va > 0] == 0).mean())        # defective patches passed as ok
    reject = float((pred[y_va == 0] > 0).mean())        # good patches thrown away
    print(f"{name:32s} acc {(pred == y_va).mean():.3f}  escape {escape:.3f}  false reject {reject:.3f}  "
          f"recall", " ".join(f"{r:.2f}" for r in recall))

def hog_features(X):                            # 5 x 5 blocks of 2 x 2 cells, 9 orientations: 900 numbers
    return np.array([hog(x, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(2, 2)) for x in X])

def pooled_features(X):
    """Position-free: remove the streaks, then keep only "how much of each kind of edge" and
    "how dark / bright is the most extreme pixel", wherever it is."""
    out = []
    for x in X.astype(np.float32):
        r = x - cv2.blur(x, (15, 3))            # residual: the image minus its local horizontal average
        h = hog(r, orientations=8, pixels_per_cell=(8, 8), cells_per_block=(1, 1), feature_vector=False).reshape(-1, 8)
        out.append(np.concatenate([h.max(0), h.mean(0), np.percentile(r, [0.5, 2, 50, 98, 99.5]),
                                   [(r < -12).sum(), (r > 12).sum()]]))
    return np.array(out)

report("always 'ok'", np.zeros_like(y_va))
for name, f in [("HOG + logistic", hog_features), ("pooled residual + logistic", pooled_features)]:
    F_tr, F_va = f(X_tr), f(X_va)
    scores = {}
    for C in [0.01, 0.1, 1, 10]:
        model = make_pipeline(StandardScaler(), LogisticRegression(C=C, max_iter=5000)).fit(F_tr, y_tr)
        scores[C] = (model.score(F_va, y_va), model)
    C = max(scores, key=lambda k: scores[k][0])
    print(f"{name}: {F_tr.shape[1]} features, val accuracy by C", {k: round(v[0], 3) for k, v in scores.items()})
    report(f"{name} (C={C})", scores[C][1].predict(F_va))
always 'ok'                      acc 0.393  escape 1.000  false reject 0.000  recall 1.00 0.00 0.00 0.00
HOG + logistic: 900 features, val accuracy by C {0.01: 0.463, 0.1: 0.435, 1: 0.41, 10: 0.398}
HOG + logistic (C=0.01)          acc 0.463  escape 0.280  false reject 0.268  recall 0.73 0.45 0.23 0.17
pooled residual + logistic: 23 features, val accuracy by C {0.01: 0.792, 0.1: 0.812, 1: 0.83, 10: 0.83}
pooled residual + logistic (C=1) acc 0.830  escape 0.152  false reject 0.045  recall 0.96 0.87 0.61 0.76

HOG with a linear model reaches only 0.463: its 900 numbers describe where each edge is, and a scratch in the top-left corner and one in the bottom-right give unrelated vectors, so 1,200 examples cannot teach a linear model that both mean "scratch". Pooling over positions fixes exactly that and jumps to 0.830 with 23 features; it misses mostly spots (recall 0.61) and cracks (0.76), and 15 % of the defects escape. That is the bar the CNN has to clear.

Step 3: a small CNN and an augmentation ablation

A convolution layer is the learned version of Step 2's filters: the same small kernel slides over every position, so a scratch detector learned in one corner works in all of them (convolution layers). In the lab, pick the Laplacian ("edge") kernel: it answers strongly to thin lines and small blobs and gives zero on flat areas, the kind of kernel the first layer of a defect classifier tends to learn.

Input image (0–9)111111111111111111115511188881115511188881115511188881115511188881115511111111115511111911111111111191111111111119111111111111911111111111191111Kernel−1−1−1−18−1−1−1−1productsdoneFeature map 10 × 10−14−21−21−14−70−82020−835212135−140−121212−12210021−210−121212−12210021−210−121212−1235212135−140−121212−12−14−29−29−22−70−82020−80−856−16−80−4−8−8−40−8−1648−16−8000000−8−1648−16−8000000−8−1648−16−800red > 0, blue < 0; max |value| 56

The network has three 3 x 3 convolution blocks (16, 32, 64 channels, each with batch norm and ReLU, two 2 x 2 max-pools), then global max pooling and one linear layer: 23,780 parameters. Max pooling over the whole map asks "does this pattern occur anywhere?", the question a defect detector asks; average pooling would dilute a 3-pixel spot among 144 positions (pooling and receptive fields, the CNN classifier lesson). Training: Adam, learning rate 3e-3, batches of 32, 12 epochs, and the epoch with the best validation accuracy restored (early stopping and checkpointing).

The ablation compares three augmentation policies (image augmentation): none; random left-right and up-down flips, which keep the streaks horizontal and every defect a valid defect; and flips plus a random transpose, which turns the streaks vertical, something the camera never sees. Same seed, same epochs, only the policy changes. This is a recorded example (PyTorch, CPU, about 25 s for the three runs).

python · try it yourself
import numpy as np, cv2

CLASSES = ["ok", "scratch", "spot", "crack"]

def make_defect(rng, c, size=48, line="A"):
    """One grey surface patch (uint8, size x size) of class c from production line "A" or "B".
    Also returns the defect's length in pixels and its contrast in grey levels (0, 0 for "ok")."""
    if line == "A":                                   # brushed steel: horizontal streaks
        streak = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=8, sigmaY=0.7)
        img = 135 + 9 * streak / streak.std() + rng.normal(0, 5, (size, size))
    else:                                             # cast aluminium: darker and grainy
        grain = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=1.5)
        img = 95 + 10 * grain / grain.std() + rng.normal(0, 4, (size, size))
    img += np.linspace(-1, 1, size)[None, :] * rng.uniform(-12, 12)    # uneven lighting
    m = np.zeros((size, size), np.float32)
    length, contrast = 0.0, 0.0
    if c == 1:                                        # scratch: long, straight, thin, bright
        length = rng.uniform(18, 40); a = rng.uniform(0, np.pi)
        cx, cy = rng.uniform(14, size - 14, 2)
        dx, dy = np.cos(a) * length / 2, np.sin(a) * length / 2
        cv2.line(m, (int(cx - dx), int(cy - dy)), (int(cx + dx), int(cy + dy)), 1.0, 1, cv2.LINE_AA)
        contrast = rng.uniform(12, 45)
    elif c == 2:                                      # spot: small, round, dark
        r = rng.uniform(1.5, 5); length = 2 * r
        cv2.circle(m, tuple(int(v) for v in rng.uniform(8, size - 8, 2)), int(round(r)), 1.0, -1, cv2.LINE_AA)
        m = cv2.GaussianBlur(m, (0, 0), 0.8)
        contrast = -rng.uniform(15, 55)
    elif c == 3:                                      # crack: jagged dark random walk
        p = rng.uniform(12, size - 12, 2); a = rng.uniform(0, 2 * np.pi)
        steps = int(rng.integers(5, 10))
        for _ in range(steps):
            a += rng.normal(0, 0.6)
            q = np.clip(p + 3 * np.array([np.cos(a), np.sin(a)]), 1, size - 2)
            cv2.line(m, (int(p[0]), int(p[1])), (int(q[0]), int(q[1])), 1.0, 1, cv2.LINE_AA)
            p = q
        length = 3.0 * steps
        contrast = -rng.uniform(15, 50)
    img = img + contrast * m
    return np.clip(img, 0, 255).astype(np.uint8), length, abs(contrast)

def make_set(rng, n, line="A", p=(0.4, 0.2, 0.2, 0.2)):
    """n patches with class shares p; returns images (n, 48, 48), labels, defect lengths, contrasts."""
    y = rng.choice(4, size=n, p=p)
    out = [make_defect(rng, int(c), line=line) for c in y]
    return np.stack([o[0] for o in out]), y, np.array([o[1] for o in out]), np.array([o[2] for o in out])

import copy
import torch
from torch import nn

def to_tensor(X):                                 # uint8 (n, 48, 48) -> float (n, 1, 48, 48), about -1..1
    return torch.tensor((X.astype(np.float32) - 128) / 32)[:, None]

def make_cnn():
    block = lambda i, o: [nn.Conv2d(i, o, 3, padding=1), nn.BatchNorm2d(o), nn.ReLU()]
    return nn.Sequential(*block(1, 16), nn.MaxPool2d(2), *block(16, 32), nn.MaxPool2d(2), *block(32, 64),
                         nn.AdaptiveMaxPool2d(1), nn.Flatten(), nn.Linear(64, 4))   # max: "is it anywhere?"

def augment(xb, aug):
    if aug in ("flips", "flips + transpose"):
        if torch.rand(1).item() < 0.5: xb = xb.flip(3)        # left-right
        if torch.rand(1).item() < 0.5: xb = xb.flip(2)        # up-down
    if aug == "flips + transpose" and torch.rand(1).item() < 0.5:
        xb = xb.transpose(2, 3)                                # streaks become vertical
    return xb

def train_cnn(Xt, yt, Xv, yv, aug="flips", epochs=12, seed=0):
    """Adam 3e-3, batches of 32; returns the model at the epoch with the best validation accuracy."""
    torch.manual_seed(seed)
    model = make_cnn(); opt = torch.optim.Adam(model.parameters(), lr=3e-3)
    best = (-1.0, None, 0)
    for epoch in range(1, epochs + 1):
        model.train()
        for idx in torch.randperm(len(yt)).split(32):
            loss = nn.functional.cross_entropy(model(augment(Xt[idx], aug)), yt[idx])
            opt.zero_grad(); loss.backward(); opt.step()
        model.eval()
        with torch.no_grad():
            acc = (model(Xv).argmax(1) == yv).float().mean().item()
        if acc > best[0]:
            best = (acc, copy.deepcopy(model.state_dict()), epoch)
    model.load_state_dict(best[1]); model.eval()
    return model, best[2]

rng = np.random.default_rng(8)
X_tr, y_tr, _, _ = make_set(rng, 1200)
X_va, y_va, _, _ = make_set(rng, 400)
Xt, Xv, yt, yv = to_tensor(X_tr), to_tensor(X_va), torch.tensor(y_tr), torch.tensor(y_va)
print("CNN parameters:", sum(p.numel() for p in make_cnn().parameters()))

for aug in ["none", "flips", "flips + transpose"]:
    model, epoch = train_cnn(Xt, yt, Xv, yv, aug=aug)
    with torch.no_grad():
        pred = model(Xv).argmax(1).numpy()
    recall = " ".join(f"{(pred[y_va == c] == c).mean():.2f}" for c in range(4))
    print(f"augmentation {aug:17s} best epoch {epoch:2d}  val acc {(pred == y_va).mean():.3f}  "
          f"escape {(pred[y_va > 0] == 0).mean():.3f}  recall {recall}")
CNN parameters: 23780
augmentation none              best epoch  7  val acc 0.968  escape 0.049  recall 1.00 0.92 0.96 0.96
augmentation flips             best epoch  6  val acc 0.988  escape 0.012  recall 0.99 0.98 1.00 0.99
augmentation flips + transpose best epoch 12  val acc 0.955  escape 0.066  recall 0.99 0.91 0.91 0.97

All three CNNs beat the best baseline (0.830) by a wide margin. Flips help: 0.988 against 0.968, with the escape rate down from 0.049 to 0.012. The transpose hurts (0.955): it spends capacity on vertical streaks that never occur and makes a vertical streak look like a scratch. Augmentation is a statement about which changes leave the label and the data distribution unchanged; "more augmentation" is not automatically better. One caveat: 400 validation patches and one seed; the gap between flips and none (8 patches) is large enough to act on, but a careful study would repeat it over seeds (robustness testing).

Step 4: an operating threshold, then the test set once

The CNN outputs four probabilities. Taking the most likely class treats an escape and a false reject as equally bad. Instead, a patch is rejected when P(ok) < t, and a rejected patch gets the most likely defect type. The threshold t is chosen on validation: the smallest t whose validation escape rate is at most 0.01, half the target, because a rate measured on 243 defective patches is itself uncertain. Only then is the test set touched.

python · try it yourself
import numpy as np, cv2

CLASSES = ["ok", "scratch", "spot", "crack"]

def make_defect(rng, c, size=48, line="A"):
    """One grey surface patch (uint8, size x size) of class c from production line "A" or "B".
    Also returns the defect's length in pixels and its contrast in grey levels (0, 0 for "ok")."""
    if line == "A":                                   # brushed steel: horizontal streaks
        streak = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=8, sigmaY=0.7)
        img = 135 + 9 * streak / streak.std() + rng.normal(0, 5, (size, size))
    else:                                             # cast aluminium: darker and grainy
        grain = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=1.5)
        img = 95 + 10 * grain / grain.std() + rng.normal(0, 4, (size, size))
    img += np.linspace(-1, 1, size)[None, :] * rng.uniform(-12, 12)    # uneven lighting
    m = np.zeros((size, size), np.float32)
    length, contrast = 0.0, 0.0
    if c == 1:                                        # scratch: long, straight, thin, bright
        length = rng.uniform(18, 40); a = rng.uniform(0, np.pi)
        cx, cy = rng.uniform(14, size - 14, 2)
        dx, dy = np.cos(a) * length / 2, np.sin(a) * length / 2
        cv2.line(m, (int(cx - dx), int(cy - dy)), (int(cx + dx), int(cy + dy)), 1.0, 1, cv2.LINE_AA)
        contrast = rng.uniform(12, 45)
    elif c == 2:                                      # spot: small, round, dark
        r = rng.uniform(1.5, 5); length = 2 * r
        cv2.circle(m, tuple(int(v) for v in rng.uniform(8, size - 8, 2)), int(round(r)), 1.0, -1, cv2.LINE_AA)
        m = cv2.GaussianBlur(m, (0, 0), 0.8)
        contrast = -rng.uniform(15, 55)
    elif c == 3:                                      # crack: jagged dark random walk
        p = rng.uniform(12, size - 12, 2); a = rng.uniform(0, 2 * np.pi)
        steps = int(rng.integers(5, 10))
        for _ in range(steps):
            a += rng.normal(0, 0.6)
            q = np.clip(p + 3 * np.array([np.cos(a), np.sin(a)]), 1, size - 2)
            cv2.line(m, (int(p[0]), int(p[1])), (int(q[0]), int(q[1])), 1.0, 1, cv2.LINE_AA)
            p = q
        length = 3.0 * steps
        contrast = -rng.uniform(15, 50)
    img = img + contrast * m
    return np.clip(img, 0, 255).astype(np.uint8), length, abs(contrast)

def make_set(rng, n, line="A", p=(0.4, 0.2, 0.2, 0.2)):
    """n patches with class shares p; returns images (n, 48, 48), labels, defect lengths, contrasts."""
    y = rng.choice(4, size=n, p=p)
    out = [make_defect(rng, int(c), line=line) for c in y]
    return np.stack([o[0] for o in out]), y, np.array([o[1] for o in out]), np.array([o[2] for o in out])

import copy
import torch
from torch import nn

def to_tensor(X):                                 # uint8 (n, 48, 48) -> float (n, 1, 48, 48), about -1..1
    return torch.tensor((X.astype(np.float32) - 128) / 32)[:, None]

def make_cnn():
    block = lambda i, o: [nn.Conv2d(i, o, 3, padding=1), nn.BatchNorm2d(o), nn.ReLU()]
    return nn.Sequential(*block(1, 16), nn.MaxPool2d(2), *block(16, 32), nn.MaxPool2d(2), *block(32, 64),
                         nn.AdaptiveMaxPool2d(1), nn.Flatten(), nn.Linear(64, 4))   # max: "is it anywhere?"

def augment(xb, aug):
    if aug in ("flips", "flips + transpose"):
        if torch.rand(1).item() < 0.5: xb = xb.flip(3)        # left-right
        if torch.rand(1).item() < 0.5: xb = xb.flip(2)        # up-down
    if aug == "flips + transpose" and torch.rand(1).item() < 0.5:
        xb = xb.transpose(2, 3)                                # streaks become vertical
    return xb

def train_cnn(Xt, yt, Xv, yv, aug="flips", epochs=12, seed=0):
    """Adam 3e-3, batches of 32; returns the model at the epoch with the best validation accuracy."""
    torch.manual_seed(seed)
    model = make_cnn(); opt = torch.optim.Adam(model.parameters(), lr=3e-3)
    best = (-1.0, None, 0)
    for epoch in range(1, epochs + 1):
        model.train()
        for idx in torch.randperm(len(yt)).split(32):
            loss = nn.functional.cross_entropy(model(augment(Xt[idx], aug)), yt[idx])
            opt.zero_grad(); loss.backward(); opt.step()
        model.eval()
        with torch.no_grad():
            acc = (model(Xv).argmax(1) == yv).float().mean().item()
        if acc > best[0]:
            best = (acc, copy.deepcopy(model.state_dict()), epoch)
    model.load_state_dict(best[1]); model.eval()
    return model, best[2]

rng = np.random.default_rng(8)
X_tr, y_tr, _, _ = make_set(rng, 1200)
X_va, y_va, _, _ = make_set(rng, 400)
X_te, y_te, len_te, con_te = make_set(rng, 800)
Xt, Xv, yt, yv = to_tensor(X_tr), to_tensor(X_va), torch.tensor(y_tr), torch.tensor(y_va)
model, epoch = train_cnn(Xt, yt, Xv, yv, aug="flips")          # the configuration chosen in Step 3

def probs(X):
    with torch.no_grad():
        return torch.softmax(model(to_tensor(X)), 1).numpy()

# 1. Operating point on VALIDATION: reject a patch when P(ok) < t.
p_va = probs(X_va)
print("t      val escape  val false reject")
for t in [0.3, 0.5, 0.6, 0.7, 0.8, 0.9]:
    rej = p_va[:, 0] < t
    print(f"{t:<6} {(~rej[y_va > 0]).mean():11.3f} {rej[y_va == 0].mean():17.3f}")
t = next(t for t in [0.3, 0.5, 0.6, 0.7, 0.8, 0.9] if (p_va[y_va > 0, 0] >= t).mean() <= 0.01)
print("chosen t =", t, "(smallest with val escape <= 0.01)")

# 2. The test set, once.
p_te = probs(X_te)
reject = p_te[:, 0] < t
kind = np.where(reject, p_te[:, 1:].argmax(1) + 1, 0)          # defect type for rejected patches
print("test confusion (rows true, cols predicted):", CLASSES)
cm = np.zeros((4, 4), int)
np.add.at(cm, (y_te, kind), 1)
for c in range(4):
    print(f"  {CLASSES[c]:8s}", cm[c].tolist())
print(f"test accuracy {(kind == y_te).mean():.3f}  escape {(~reject[y_te > 0]).mean():.3f} "
      f"({(~reject[y_te > 0]).sum()} of {(y_te > 0).sum()})  false reject {reject[y_te == 0].mean():.3f} "
      f"({reject[y_te == 0].sum()} of {(y_te == 0).sum()})")
print("macro recall", round(float(np.mean([(kind[y_te == c] == c).mean() for c in range(4)])), 3))

# 3. Error analysis: which defects escape or get the wrong type?
d = y_te > 0
for lo, hi in [(0, 20), (20, 35), (35, 60)]:
    band = d & (con_te >= lo) & (con_te < hi)
    print(f"contrast {lo:2d}-{hi:2d}: {band.sum():3d} defects, caught {reject[band].mean():.3f}, right type {(kind[band] == y_te[band]).mean():.3f}")
fr = (y_te == 0) & reject
print("false rejects by predicted type:", {CLASSES[c]: int((kind[fr] == c).sum()) for c in (1, 2, 3)})
print("defects that escaped or got the wrong type:")
for i in np.flatnonzero(d & (kind != y_te)):
    print(f"  #{i:3d} true {CLASSES[y_te[i]]:7s} predicted {CLASSES[kind[i]]:7s} P(ok) {p_te[i, 0]:.3f} "
          f"length {len_te[i]:4.1f} contrast {con_te[i]:4.1f}")
t      val escape  val false reject
0.3          0.029             0.013
0.5          0.012             0.013
0.6          0.008             0.019
0.7          0.004             0.025
0.8          0.004             0.153
0.9          0.004             0.433
chosen t = 0.6 (smallest with val escape <= 0.01)
test confusion (rows true, cols predicted): ['ok', 'scratch', 'spot', 'crack']
  ok       [328, 3, 4, 2]
  scratch  [5, 160, 0, 0]
  spot     [1, 0, 140, 2]
  crack    [0, 1, 0, 154]
test accuracy 0.978  escape 0.013 (6 of 463)  false reject 0.027 (9 of 337)
macro recall 0.979
contrast  0-20:  79 defects, caught 0.937, right type 0.924
contrast 20-35: 183 defects, caught 0.995, right type 0.984
contrast 35-60: 201 defects, caught 1.000, right type 1.000
false rejects by predicted type: {'scratch': 3, 'spot': 4, 'crack': 2}
defects that escaped or got the wrong type:
  #306 true spot    predicted ok      P(ok) 0.641 length  4.9 contrast 20.8
  #310 true scratch predicted ok      P(ok) 0.613 length 37.9 contrast 14.8
  #330 true spot    predicted crack   P(ok) 0.200 length  4.0 contrast 21.0
  #343 true scratch predicted ok      P(ok) 0.601 length 23.4 contrast 18.9
  #436 true crack   predicted scratch P(ok) 0.286 length 21.0 contrast 17.3
  #518 true spot    predicted crack   P(ok) 0.071 length  4.4 contrast 21.7
  #646 true scratch predicted ok      P(ok) 0.668 length 38.9 contrast 12.2
  #694 true scratch predicted ok      P(ok) 0.803 length 21.4 contrast 12.7
  #771 true scratch predicted ok      P(ok) 0.745 length 30.5 contrast 13.3

On validation, t = 0.5 (the plain argmax) lets 1.2 % of defects through; t = 0.6 brings that to 0.8 % for a false reject rate of 1.9 %, and from 0.8 on the false rejects explode (15 % and more): the model is confident on most good patches, and a few are borderline. With t = 0.6, the single test run gives:

Criterion Target Test result
escape rate at most 0.02 0.013 (6 of 463) met
false reject rate at most 0.05 0.027 (9 of 337) met
macro recall at least 0.90 0.979 met
accuracy 0.978

The escape rate on test (0.013) is higher than on validation (0.008), as expected when a threshold is tuned on one sample and applied to another; the margin built into the rule kept it under the target.

Error analysis. All six escapes are scratches or spots, and five of them are faint scratches (contrast 12 to 19 grey levels, while the streaks alone vary by about 9 grey levels); the miss rate falls from 6 % in the lowest contrast band to 0 % above 35. Two spots were called cracks (short dark marks look alike) and one crack a scratch. The nine false rejects are spread over all three defect types, i.e. streak patterns that look like a defect. The next improvements are therefore about faint scratches: more of them in training (or a generator that oversamples low contrast), a camera setting with more contrast, or a second look at patches with P(ok) between 0.6 and 0.8 by a person. Check with the inspectors whether a scratch of contrast 12 is a defect at all: below some contrast it is not visible to the customer either, and the label guideline should say so.

Step 5: export and a loader

The inspection station runs a small C++ or Python service, not a notebook: it needs the network as a file, the preprocessing and the threshold next to it, and a loader that does not import PyTorch. The model is exported to ONNX with a softmax added, so the file outputs probabilities (ONNX export), and the metadata goes into a JSON file next to it (model artefacts and signatures). This image has no onnxscript, so the export uses the older TorchScript-based exporter (dynamo=False) and hides its deprecation warning.

python · try it yourself
import numpy as np, cv2

CLASSES = ["ok", "scratch", "spot", "crack"]

def make_defect(rng, c, size=48, line="A"):
    """One grey surface patch (uint8, size x size) of class c from production line "A" or "B".
    Also returns the defect's length in pixels and its contrast in grey levels (0, 0 for "ok")."""
    if line == "A":                                   # brushed steel: horizontal streaks
        streak = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=8, sigmaY=0.7)
        img = 135 + 9 * streak / streak.std() + rng.normal(0, 5, (size, size))
    else:                                             # cast aluminium: darker and grainy
        grain = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=1.5)
        img = 95 + 10 * grain / grain.std() + rng.normal(0, 4, (size, size))
    img += np.linspace(-1, 1, size)[None, :] * rng.uniform(-12, 12)    # uneven lighting
    m = np.zeros((size, size), np.float32)
    length, contrast = 0.0, 0.0
    if c == 1:                                        # scratch: long, straight, thin, bright
        length = rng.uniform(18, 40); a = rng.uniform(0, np.pi)
        cx, cy = rng.uniform(14, size - 14, 2)
        dx, dy = np.cos(a) * length / 2, np.sin(a) * length / 2
        cv2.line(m, (int(cx - dx), int(cy - dy)), (int(cx + dx), int(cy + dy)), 1.0, 1, cv2.LINE_AA)
        contrast = rng.uniform(12, 45)
    elif c == 2:                                      # spot: small, round, dark
        r = rng.uniform(1.5, 5); length = 2 * r
        cv2.circle(m, tuple(int(v) for v in rng.uniform(8, size - 8, 2)), int(round(r)), 1.0, -1, cv2.LINE_AA)
        m = cv2.GaussianBlur(m, (0, 0), 0.8)
        contrast = -rng.uniform(15, 55)
    elif c == 3:                                      # crack: jagged dark random walk
        p = rng.uniform(12, size - 12, 2); a = rng.uniform(0, 2 * np.pi)
        steps = int(rng.integers(5, 10))
        for _ in range(steps):
            a += rng.normal(0, 0.6)
            q = np.clip(p + 3 * np.array([np.cos(a), np.sin(a)]), 1, size - 2)
            cv2.line(m, (int(p[0]), int(p[1])), (int(q[0]), int(q[1])), 1.0, 1, cv2.LINE_AA)
            p = q
        length = 3.0 * steps
        contrast = -rng.uniform(15, 50)
    img = img + contrast * m
    return np.clip(img, 0, 255).astype(np.uint8), length, abs(contrast)

def make_set(rng, n, line="A", p=(0.4, 0.2, 0.2, 0.2)):
    """n patches with class shares p; returns images (n, 48, 48), labels, defect lengths, contrasts."""
    y = rng.choice(4, size=n, p=p)
    out = [make_defect(rng, int(c), line=line) for c in y]
    return np.stack([o[0] for o in out]), y, np.array([o[1] for o in out]), np.array([o[2] for o in out])

import copy
import torch
from torch import nn

def to_tensor(X):                                 # uint8 (n, 48, 48) -> float (n, 1, 48, 48), about -1..1
    return torch.tensor((X.astype(np.float32) - 128) / 32)[:, None]

def make_cnn():
    block = lambda i, o: [nn.Conv2d(i, o, 3, padding=1), nn.BatchNorm2d(o), nn.ReLU()]
    return nn.Sequential(*block(1, 16), nn.MaxPool2d(2), *block(16, 32), nn.MaxPool2d(2), *block(32, 64),
                         nn.AdaptiveMaxPool2d(1), nn.Flatten(), nn.Linear(64, 4))   # max: "is it anywhere?"

def augment(xb, aug):
    if aug in ("flips", "flips + transpose"):
        if torch.rand(1).item() < 0.5: xb = xb.flip(3)        # left-right
        if torch.rand(1).item() < 0.5: xb = xb.flip(2)        # up-down
    if aug == "flips + transpose" and torch.rand(1).item() < 0.5:
        xb = xb.transpose(2, 3)                                # streaks become vertical
    return xb

def train_cnn(Xt, yt, Xv, yv, aug="flips", epochs=12, seed=0):
    """Adam 3e-3, batches of 32; returns the model at the epoch with the best validation accuracy."""
    torch.manual_seed(seed)
    model = make_cnn(); opt = torch.optim.Adam(model.parameters(), lr=3e-3)
    best = (-1.0, None, 0)
    for epoch in range(1, epochs + 1):
        model.train()
        for idx in torch.randperm(len(yt)).split(32):
            loss = nn.functional.cross_entropy(model(augment(Xt[idx], aug)), yt[idx])
            opt.zero_grad(); loss.backward(); opt.step()
        model.eval()
        with torch.no_grad():
            acc = (model(Xv).argmax(1) == yv).float().mean().item()
        if acc > best[0]:
            best = (acc, copy.deepcopy(model.state_dict()), epoch)
    model.load_state_dict(best[1]); model.eval()
    return model, best[2]
import json, os, tempfile, warnings
import onnxruntime as ort

rng = np.random.default_rng(8)
X_tr, y_tr, _, _ = make_set(rng, 1200)
X_va, y_va, _, _ = make_set(rng, 400)
X_te, y_te, _, _ = make_set(rng, 800)
model, epoch = train_cnn(to_tensor(X_tr), torch.tensor(y_tr), to_tensor(X_va), torch.tensor(y_va), aug="flips")

# Export: the network as ONNX, everything else the caller needs as JSON next to it.
out = tempfile.mkdtemp()
export = nn.Sequential(model, nn.Softmax(dim=1)).eval()          # ship probabilities, not logits
with warnings.catch_warnings():
    warnings.simplefilter("ignore", DeprecationWarning)         # legacy exporter: no onnxscript in this image
    torch.onnx.export(export, torch.zeros(1, 1, 48, 48), f"{out}/defects.onnx", input_names=["patch"],
                      output_names=["probs"], dynamic_axes={"patch": {0: "n"}, "probs": {0: "n"}}, dynamo=False)
meta = {"model": "defect-cnn", "version": "1.0.0", "classes": CLASSES, "input": "grey uint8 48x48, (x - 128) / 32",
        "reject_if_p_ok_below": 0.6, "trained_on": "line A, generator seed 8, 1200 patches", "best_epoch": epoch,
        "test": {"accuracy": 0.978, "escape": 0.013, "false_reject": 0.027, "n": 800}}
json.dump(meta, open(f"{out}/defects.json", "w"), indent=1)
print("files:", sorted(os.listdir(out)))

# A separate loader, as the inspection station would use it: no PyTorch, only ONNX Runtime and NumPy.
class Inspector:
    def __init__(self, folder):
        self.meta = json.load(open(f"{folder}/defects.json"))
        self.session = ort.InferenceSession(f"{folder}/defects.onnx", providers=["CPUExecutionProvider"])
    def __call__(self, patches):
        x = ((np.asarray(patches, np.float32) - 128) / 32)[:, None]
        p = self.session.run(None, {"patch": x})[0]
        reject = p[:, 0] < self.meta["reject_if_p_ok_below"]
        kind = np.where(reject, p[:, 1:].argmax(1) + 1, 0)
        return [self.meta["classes"][k] for k in kind], p

inspect = Inspector(out)
labels, p_onnx = inspect(X_te)
with torch.no_grad():
    p_torch = torch.softmax(model(to_tensor(X_te)), 1).numpy()
print("ONNX and PyTorch probabilities agree within 1e-5 on 800 test patches:", bool(np.abs(p_onnx - p_torch).max() < 1e-5))
print(f"model file: {os.path.getsize(out + '/defects.onnx') / 1024:.0f} KB")
print("decisions identical:", labels == [CLASSES[k] for k in np.where(p_torch[:, 0] < 0.6, p_torch[:, 1:].argmax(1) + 1, 0)])
new, y_new, _, _ = make_set(np.random.default_rng(2026), 5)      # five patches from tomorrow's production
print("new patches:", inspect(new)[0], "| truth:", [CLASSES[c] for c in y_new])
files: ['defects.json', 'defects.onnx']
ONNX and PyTorch probabilities agree within 1e-5 on 800 test patches: True
model file: 94 KB
decisions identical: True
new patches: ['ok', 'spot', 'scratch', 'ok', 'ok'] | truth: ['ok', 'spot', 'scratch', 'ok', 'ok']

The ONNX file is 94 KB, ONNX Runtime gives the same probabilities as PyTorch within 1e-5 on all 800 test patches, so every decision is identical, and the five new patches are inspected correctly. The Inspector class is all the station needs: two files and a fixed preprocessing. The JSON records the threshold and the test results the model was accepted with, so a later model can be compared with the same numbers, and a model registry can store both files as one version.

Extensions

  • Faint scratches: oversample low-contrast scratches in training or weight them in the loss, and check the escape rate by contrast band again (class weights).
  • Whole-sheet inspection: slide the classifier over a full photo with overlapping patches, or switch to a detector that outputs boxes, as in Project 10.
  • Calibration: the threshold rule assumes the probabilities mean something; check a reliability diagram on validation (calibration).
  • Smaller and faster: quantise the ONNX model to 8-bit integers and compare decisions (quantization).
  • Monitoring: log P(ok) per patch in production; a shift in its distribution warns before the escape rate does (monitoring).

Write-up template

text
Project: surface defect classifier, line <A>, <date>
Data: source (camera, resolution), period, labelling guideline and who labelled, class shares
Split: train <n> / validation <n> / test <n>, drawn how, no patch from one sheet in two splits
Baselines: always-ok <acc>, HOG + LR <acc>, pooled features + LR <acc> (validation)
Model: <architecture, parameters>, training recipe, augmentation chosen by <ablation, validation numbers>
Operating point: reject if P(ok) < <t>, chosen on validation by <rule>
Test (once): escape <x> (n of N), false reject <x>, macro recall <x>, accuracy <x>
Errors: escapes by type and contrast <...>, confusions <...>, false rejects <...>
Deployment: <format>, size <KB>, loader <...>, metadata stored <...>
Limits: synthetic or real data, one line, lighting, defect types not in the label set

Practice

  1. In Step 2 the HOG baseline got 0.463 with 900 features and the pooled features 0.830 with 23. Give a one-sentence reason, and name the CNN layer that does the same job as the pooling.
Answer

HOG keeps the position of every edge, so the same defect at different places gives different vectors, while pooling keeps only "how much of this pattern, anywhere"; in the CNN, AdaptiveMaxPool2d(1) (global max pooling) plays that role after the convolutions have computed the patterns at every position.

  1. The quality team now says a false reject costs almost nothing (the patch is just looked at again) but an escape is very expensive. What changes in Step 4, and what stays fixed?
Answer

Only the threshold rule changes: demand a lower validation escape rate (for example at most 0.004, t = 0.7 in the table, with 2.5 % false rejects on validation) and accept more false rejects. The model, the training and the test-once rule stay the same; the new t must still be chosen on validation, never on the test set.

  1. A colleague adds random 90-degree rotations to the training augmentation and reports a better validation score on a new validation set made with the same augmentation. What is wrong?
Answer

The validation set must look like production data. Rotating it turns the streaks vertical, which the camera never produces, so the score measures performance on a distribution that does not exist. Step 3 showed that the transpose, which also turns the streaks, lowered accuracy on the real (unrotated) validation set from 0.988 to 0.955.

  1. Why does the exported model include a softmax, and why is the threshold stored in the JSON file and not in the code of the station?
Answer

With the softmax the file outputs probabilities, the quantity the threshold is defined on, so no caller can forget the softmax or apply it twice. The threshold belongs to the model version: it was chosen on that model's validation probabilities, so a retrained model ships with its own threshold, and the station's code does not change.

Test yourself

Why is the decision rule 'reject if P(ok) < t' instead of 'take the most likely class'?

  1. It is faster
  2. An escape costs far more than a false reject, and t lets the validation set set that trade-off
  3. The argmax does not work with four classes
  4. It makes the model more accurate on every class

Which augmentation lowered validation accuracy in Step 3, and why?

  1. Left-right flips, because scratches change direction
  2. The transpose, because it turns the horizontal streaks vertical, which the camera never sees
  3. Up-down flips, because spots move
  4. None of them changed the score

The test escape rate was 0.013 although the threshold gave 0.008 on validation. What does this show?

  1. The test set is wrong
  2. A rate tuned on one sample is optimistic on another, which is why the rule aimed at half the target
  3. The model overfitted the test set
  4. The threshold should be tuned on the test set

Most escapes in Step 4 have something in common. What?

  1. They are large cracks
  2. They are faint scratches, contrast below 20 grey levels
  3. They are at the patch border
  4. They are all spots