TExcelTAD
Home › ML Projects: 15 End-to-End Builds › Project 10: YOLO Object Detection

Project 10: YOLO Object Detection

The defect classifier of Project 8 answers "is something wrong in this patch?". The mill now wants where: a box around every scratch, spot and crack on a 128 x 128 pixel view of a steel panel, so that a robot can mark it and the engineers can count defects per square metre. That is object detection, and with Ultralytics YOLO the training itself is a few lines. The hard and expensive part of a real detection project is everything around it: the labels. This project is therefore built annotation first: write the data set in YOLO format, check the label files, measure how much two annotators agree, write your own evaluator and learn what its numbers can mean for objects a few pixels wide, and only then fine-tune YOLOv8n and analyse its errors. The level is advanced.

You used YOLO before: pretrained COCO models and a 3-epoch training run in the Ultralytics lesson, and person detection with AP in the human detection project. Those projects took their boxes as given. Here the labels are made, checked and doubted, and the objects are small and low-contrast, which changes what a good score is.

panelsgenerator, seed 10 2 annotatorsYOLO .txt files label QAformat + IoU data setpng, txt, yaml YOLOv8nfine-tune, CPU own APevaluator error analysissize, contrast, class fix the guideline

Goal and success criteria

Fixed before any label or model was looked at:

Criterion Target Measured on
label files 0 format errors before training; every warning seen by a person every .txt file
annotator agreement class agreement at least 0.9; median box IoU at least 0.6 for every class 60 panels labelled twice
evaluator reproduces a hand-computed AP; differences to Ultralytics' numbers explained a small hand example, the validation split
detector mAP@0.5 at least 0.7; recall at least 0.8 at the operating threshold 0.25 100 test panels, used once
cost CPU only, one recorded training run under 30 s the recorded run

The detector criteria are what a first production version would need. The training run here is deliberately tiny (7 epochs on 200 panels, on a CPU), so expect to see the gap and to use the error analysis to say what would close it.

The data

make_panel draws a 128 x 128 panel of line-A brushed steel (the texture of Project 8) with 0 to 4 non-touching defects: scratches (straight bright lines in a 20 to 40 pixel square), spots (dark discs of radius 2 to 5, in a 10 to 14 pixel square) and cracks (jagged dark walks). The generator knows each defect's exact box, the tightest rectangle around the pixels it changed by more than a quarter of the defect's contrast, and its contrast. A real project has neither: its boxes are drawn by people, and that is what Steps 2 and 3 are about. 200 training, 60 validation and 100 test panels come from one stream seeded with 10. Real panel images would come from the line camera; the labels from the quality inspectors under a written guideline, with the image rights of the plant (ground truth and annotation, annotation tasks).

Step 1: the data set in YOLO format

Ultralytics expects images/<split>/name.png and labels/<split>/name.txt with the same names, one line class cx cy w h per object, normalised by the image size, an empty file for an image without objects, and a YAML file with the paths and class names (box formats). The program writes all of it to a temporary folder and prints what a reviewer should check first: counts, empty images, box sizes.

python · try it yourself
import numpy as np, cv2

CLASSES = ["scratch", "spot", "crack"]          # YOLO class ids 0, 1, 2

def draw_defect(rng, m, c, x0, y0, s):
    """Draws defect c (0 scratch, 1 spot, 2 crack) into the float mask m, inside the s x s square at (x0, y0)."""
    if c == 0:                                  # long, straight, thin
        a = rng.uniform(0, np.pi); half = rng.uniform(0.35, 0.5) * s
        cx, cy = x0 + s / 2, y0 + s / 2
        cv2.line(m, (int(cx - np.cos(a) * half), int(cy - np.sin(a) * half)),
                 (int(cx + np.cos(a) * half), int(cy + np.sin(a) * half)), 1.0, 1, cv2.LINE_AA)
    elif c == 1:                                # small, round
        r = rng.uniform(2, 5)
        cv2.circle(m, (int(x0 + s / 2), int(y0 + s / 2)), int(round(r)), 1.0, -1, cv2.LINE_AA)
    else:                                       # jagged random walk
        p = np.array([x0 + s / 2, y0 + s / 2]); a = rng.uniform(0, 2 * np.pi)
        for _ in range(int(rng.integers(5, 10))):
            a += rng.normal(0, 0.6)
            q = np.clip(p + 3 * np.array([np.cos(a), np.sin(a)]), [x0, y0], [x0 + s - 1, y0 + s - 1])
            cv2.line(m, (int(p[0]), int(p[1])), (int(q[0]), int(q[1])), 1.0, 1, cv2.LINE_AA)
            p = q

def make_panel(rng, size=128, max_defects=4):
    """A line-A steel panel with 0..max_defects defects that do not touch. Returns the grey uint8 image,
    the exact boxes (n, 4) as pixel corners [x1, y1, x2, y2] (x2, y2 exclusive), classes (n,), contrasts (n,)."""
    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))
    img += np.linspace(-1, 1, size)[None, :] * rng.uniform(-12, 12)
    boxes, labels, contrasts = [], [], []
    for _ in range(int(rng.integers(0, max_defects + 1))):
        c = int(rng.integers(0, 3)); s = int(rng.integers(10, 15)) if c == 1 else int(rng.integers(20, 41))
        for _ in range(30):                     # find a free place
            x0, y0 = (int(v) for v in rng.integers(2, size - s - 2, 2))
            if all(x0 > b[2] + 2 or x0 + s < b[0] - 2 or y0 > b[3] + 2 or y0 + s < b[1] - 2 for b in boxes):
                break
        else:
            continue
        m = np.zeros((size, size), np.float32)
        draw_defect(rng, m, c, x0, y0, s)
        if c == 1:
            m = cv2.GaussianBlur(m, (0, 0), 0.8)
        contrast = rng.uniform(12, 45) if c == 0 else -rng.uniform(15, 55)
        img += contrast * m
        ys, xs = np.nonzero(m > 0.25)
        boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
        labels.append(c); contrasts.append(abs(contrast))
    return (np.clip(img, 0, 255).astype(np.uint8), np.array(boxes, int).reshape(-1, 4),
            np.array(labels, int), np.array(contrasts))
import os, tempfile
import matplotlib.pyplot as plt

def yolo_line(box, label, size=128):
    x1, y1, x2, y2 = box
    return f"{label} {(x1 + x2) / 2 / size:.6f} {(y1 + y2) / 2 / size:.6f} {(x2 - x1) / size:.6f} {(y2 - y1) / size:.6f}"

root = tempfile.mkdtemp()
rng = np.random.default_rng(10)
data = {}
for split, n in [("train", 200), ("val", 60), ("test", 100)]:
    os.makedirs(f"{root}/images/{split}"); os.makedirs(f"{root}/labels/{split}")
    data[split] = [make_panel(rng) for _ in range(n)]
    for i, (img, boxes, labels, _) in enumerate(data[split]):
        cv2.imwrite(f"{root}/images/{split}/{i:04d}.png", img)
        with open(f"{root}/labels/{split}/{i:04d}.txt", "w") as f:     # empty file = a panel without defects
            f.write("".join(yolo_line(b, l) + "\n" for b, l in zip(boxes, labels)))
with open(f"{root}/panels.yaml", "w") as f:
    f.write(f"path: {root}\ntrain: images/train\nval: images/val\ntest: images/test\n"
            "names:\n  0: scratch\n  1: spot\n  2: crack\n")

for split in ["train", "val", "test"]:
    labels = np.concatenate([l for _, _, l, _ in data[split]])
    sizes = np.concatenate([np.sqrt((b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1])) for _, b, _, _ in data[split]])
    empty = sum(len(l) == 0 for _, _, l, _ in data[split])
    print(f"{split:5s} {len(os.listdir(f'{root}/images/{split}')):3d} images, {empty:2d} empty, "
          f"objects per class {np.bincount(labels, minlength=3).tolist()}, "
          f"box size (sqrt area) {sizes.min():.0f} to {sizes.max():.0f} px, median {np.median(sizes):.1f}")
print("labels/train/0000.txt:")
print(open(f"{root}/labels/train/0000.txt").read().rstrip())
print("exact boxes of train image 0:", data["train"][0][1].tolist())

fig, axes = plt.subplots(1, 4, figsize=(9, 2.6))
colours = [(230, 60, 60), (60, 180, 60), (60, 110, 240)]
for ax, (img, boxes, labels, _) in zip(axes, data["train"][:4]):
    rgb = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
    for (x1, y1, x2, y2), l in zip(boxes, labels):
        cv2.rectangle(rgb, (int(x1), int(y1)), (int(x2) - 1, int(y2) - 1), colours[l], 1)
    ax.imshow(rgb); ax.set_xticks([]); ax.set_yticks([])
fig.suptitle("Training panels with their boxes: red scratch, green spot, blue crack")
plt.tight_layout()
train 200 images, 40 empty, objects per class [156, 131, 113], box size (sqrt area) 5 to 26 px, median 11.0
val    60 images,  6 empty, objects per class [46, 43, 48], box size (sqrt area) 5 to 27 px, median 10.8
test  100 images, 26 empty, objects per class [70, 63, 59], box size (sqrt area) 5 to 26 px, median 10.6
labels/train/0000.txt:
1 0.746094 0.285156 0.054688 0.054688
0 0.500000 0.218750 0.078125 0.187500
1 0.214844 0.699219 0.039062 0.039062
exact boxes of train image 0: [[92, 33, 99, 40], [59, 16, 69, 40], [25, 87, 30, 92]]

The three classes are roughly balanced (156, 131 and 113 objects in training), and 40 of the 200 training panels are empty, which teaches the model that a clean panel exists. The boxes are small: 5 to 27 pixels (square root of the area), median 11, on a 128 pixel image. The first label line of panel 0 is a spot whose exact box [92, 33, 99, 40] becomes centre (0.746, 0.285), size 0.055 x 0.055: 7 pixels. One pixel is 0.0078 in these units, which matters in Step 3.

Step 2: two annotators and the label QA

To know how reliable the labels are, a sample is labelled twice, independently (label quality). Here two simulated inspectors label the 60 validation panels. Both place each edge with some random error; A is careful (about 0.7 px, misses 30 % of faint defects, calls 5 % of cracks scratches), B is quicker (about 1.2 px, misses half the faint ones, 20 % crack-scratch confusion). B's files also get five typical slips: a zero-width box, an unknown class id, a box sticking out of the image, a duplicated line and a line in pixels instead of normalised units.

The QA has three parts: format checks on every line (errors are removed until fixed; a warning, here "thinner than 2 px", is kept and shown to a person), agreement between the two annotators (boxes paired by IoU, then the IoU and the class compared), and, possible only because the data is generated, a comparison with the exact boxes.

python · try it yourself
import numpy as np, cv2

CLASSES = ["scratch", "spot", "crack"]          # YOLO class ids 0, 1, 2

def draw_defect(rng, m, c, x0, y0, s):
    """Draws defect c (0 scratch, 1 spot, 2 crack) into the float mask m, inside the s x s square at (x0, y0)."""
    if c == 0:                                  # long, straight, thin
        a = rng.uniform(0, np.pi); half = rng.uniform(0.35, 0.5) * s
        cx, cy = x0 + s / 2, y0 + s / 2
        cv2.line(m, (int(cx - np.cos(a) * half), int(cy - np.sin(a) * half)),
                 (int(cx + np.cos(a) * half), int(cy + np.sin(a) * half)), 1.0, 1, cv2.LINE_AA)
    elif c == 1:                                # small, round
        r = rng.uniform(2, 5)
        cv2.circle(m, (int(x0 + s / 2), int(y0 + s / 2)), int(round(r)), 1.0, -1, cv2.LINE_AA)
    else:                                       # jagged random walk
        p = np.array([x0 + s / 2, y0 + s / 2]); a = rng.uniform(0, 2 * np.pi)
        for _ in range(int(rng.integers(5, 10))):
            a += rng.normal(0, 0.6)
            q = np.clip(p + 3 * np.array([np.cos(a), np.sin(a)]), [x0, y0], [x0 + s - 1, y0 + s - 1])
            cv2.line(m, (int(p[0]), int(p[1])), (int(q[0]), int(q[1])), 1.0, 1, cv2.LINE_AA)
            p = q

def make_panel(rng, size=128, max_defects=4):
    """A line-A steel panel with 0..max_defects defects that do not touch. Returns the grey uint8 image,
    the exact boxes (n, 4) as pixel corners [x1, y1, x2, y2] (x2, y2 exclusive), classes (n,), contrasts (n,)."""
    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))
    img += np.linspace(-1, 1, size)[None, :] * rng.uniform(-12, 12)
    boxes, labels, contrasts = [], [], []
    for _ in range(int(rng.integers(0, max_defects + 1))):
        c = int(rng.integers(0, 3)); s = int(rng.integers(10, 15)) if c == 1 else int(rng.integers(20, 41))
        for _ in range(30):                     # find a free place
            x0, y0 = (int(v) for v in rng.integers(2, size - s - 2, 2))
            if all(x0 > b[2] + 2 or x0 + s < b[0] - 2 or y0 > b[3] + 2 or y0 + s < b[1] - 2 for b in boxes):
                break
        else:
            continue
        m = np.zeros((size, size), np.float32)
        draw_defect(rng, m, c, x0, y0, s)
        if c == 1:
            m = cv2.GaussianBlur(m, (0, 0), 0.8)
        contrast = rng.uniform(12, 45) if c == 0 else -rng.uniform(15, 55)
        img += contrast * m
        ys, xs = np.nonzero(m > 0.25)
        boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
        labels.append(c); contrasts.append(abs(contrast))
    return (np.clip(img, 0, 255).astype(np.uint8), np.array(boxes, int).reshape(-1, 4),
            np.array(labels, int), np.array(contrasts))

def iou(a, b):
    w = min(a[2], b[2]) - max(a[0], b[0]); h = min(a[3], b[3]) - max(a[1], b[1])
    inter = max(w, 0) * max(h, 0)
    return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)

def annotate(rng, boxes, labels, contrasts, jitter, p_miss_faint, p_crack_as_scratch):
    """A simulated inspector: every edge off by about `jitter` pixels, faint defects (contrast < 20)
    missed with probability p_miss_faint, cracks sometimes called scratches. Returns YOLO lines."""
    lines = []
    for b, l, c in zip(boxes, labels, contrasts):
        if c < 20 and rng.random() < p_miss_faint:
            continue
        x1, y1, x2, y2 = np.round(b + rng.normal(0, jitter, 4)).astype(int)
        if l == 2 and rng.random() < p_crack_as_scratch:
            l = 0
        lines.append(f"{l} {(x1 + x2) / 256:.6f} {(y1 + y2) / 256:.6f} {(x2 - x1) / 128:.6f} {(y2 - y1) / 128:.6f}")
    return lines

rng = np.random.default_rng(10)
panels = [make_panel(rng) for _ in range(60)]                   # 60 panels, each labelled by two inspectors
ann = np.random.default_rng(1)
files_a = [annotate(ann, b, l, c, 0.7, 0.3, 0.05) for _, b, l, c in panels]
files_b = [annotate(ann, b, l, c, 1.2, 0.5, 0.2) for _, b, l, c in panels]
files_b[3].append("1 0.500000 0.500000 0.000000 0.046875")       # typical tool and copy-paste slips
files_b[7].append("3 0.400000 0.400000 0.100000 0.100000")
files_b[12].append("0 0.990000 0.300000 0.080000 0.100000")
files_b[20].append(files_b[20][0])
files_b[31].append("2 41 77 12 15")

# 1. Format checks on every line, before anything else. Flagged lines are left out until a person fixes them.
def check(files, name, n_classes=3, size=128):
    kept, flagged = [], 0
    for i, lines in enumerate(files):
        boxes = []
        for k, line in enumerate(lines, 1):
            f = line.split()
            c, cx, cy, w, h = int(f[0]), *map(float, f[1:])
            issue = ("class id out of range" if not 0 <= c < n_classes else
                     "not normalised (pixels?)" if max(cx, cy, w, h) > 1 else
                     "box leaves the image" if min(cx - w / 2, cy - h / 2) < 0 or max(cx + w / 2, cy + h / 2) > 1 else
                     "empty box" if min(w, h) == 0 else
                     "thinner than 2 px" if min(w, h) * size < 2 else
                     "duplicate line" if line in lines[:k - 1] else None)
            if issue:
                print(f"  {name} {i:04d}.txt line {k}: {issue:24s} | {line}"); flagged += 1
            if issue in (None, "thinner than 2 px"):                # a warning: a person looks at it
                boxes.append((c, np.array([cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2]) * size))
        kept.append(boxes)
    print(f"{name}: {sum(map(len, files))} boxes, {flagged} flagged")
    return kept

A = check(files_a, "annotator A"); B = check(files_b, "annotator B")

# 2. Agreement between the two annotators: pair boxes of one panel greedily by IoU (>= 0.3 = same defect).
pairs, only_a, only_b = [], 0, 0
for a, b in zip(A, B):
    cand = sorted(((iou(x[1], y[1]), i, j) for i, x in enumerate(a) for j, y in enumerate(b)), reverse=True)
    ua, ub = set(), set()
    for v, i, j in cand:
        if v >= 0.3 and i not in ua and j not in ub:
            ua.add(i); ub.add(j); pairs.append((a[i][0], b[j][0], v))
    only_a += len(a) - len(ua); only_b += len(b) - len(ub)
pairs = np.array(pairs)
print(f"pairs {len(pairs)}, only A {only_a}, only B {only_b}, same class {np.mean(pairs[:, 0] == pairs[:, 1]):.3f}")
for c in range(3):
    v = pairs[pairs[:, 0] == c, 2]
    print(f"  A says {CLASSES[c]:7s}: {len(v):2d} pairs, IoU median {np.median(v):.2f}, "
          f"share >= 0.5 {np.mean(v >= 0.5):.2f}, >= 0.75 {np.mean(v >= 0.75):.2f}")
print("class confusion (rows A, cols B):", [[int(((pairs[:, 0] == i) & (pairs[:, 1] == j)).sum()) for j in range(3)] for i in range(3)])

# 3. Only possible here: compare each annotator with the generator's exact boxes.
for name, boxes in [("A", A), ("B", B)]:
    hit, faint = [], []
    for (_, gb, gl, gc), mine in zip(panels, boxes):
        for g, l, c in zip(gb, gl, gc):
            hit.append(any(k == l and iou(b, g) >= 0.5 for k, b in mine)); faint.append(c < 20)
    hit, faint = np.array(hit), np.array(faint)
    print(f"annotator {name} vs exact: found {hit.mean():.3f} of {len(hit)} defects (class right, IoU >= 0.5); "
          f"faint ones {hit[faint].mean():.3f}")
  annotator A 0044.txt line 2: thinner than 2 px        | 0 0.546875 0.542969 0.281250 0.007812
annotator A: 127 boxes, 1 flagged
  annotator B 0003.txt line 5: empty box                | 1 0.500000 0.500000 0.000000 0.046875
  annotator B 0007.txt line 3: class id out of range    | 3 0.400000 0.400000 0.100000 0.100000
  annotator B 0012.txt line 2: box leaves the image     | 0 0.990000 0.300000 0.080000 0.100000
  annotator B 0020.txt line 5: duplicate line           | 0 0.734375 0.660156 0.265625 0.070312
  annotator B 0031.txt line 1: not normalised (pixels?) | 2 41 77 12 15
annotator B: 126 boxes, 5 flagged
pairs 116, only A 11, only B 5, same class 0.957
  A says scratch: 47 pairs, IoU median 0.73, share >= 0.5 0.87, >= 0.75 0.45
  A says spot   : 35 pairs, IoU median 0.61, share >= 0.5 0.77, >= 0.75 0.20
  A says crack  : 34 pairs, IoU median 0.68, share >= 0.5 0.88, >= 0.75 0.32
class confusion (rows A, cols B): [[46, 0, 1], [0, 35, 0], [4, 0, 30]]
annotator A vs exact: found 0.946 of 130 defects (class right, IoU >= 0.5); faint ones 0.800
annotator B vs exact: found 0.777 of 130 defects (class right, IoU >= 0.5); faint ones 0.450
  • Format. All five slips in B's files are caught. The warning in A's files is a real case: a nearly horizontal scratch has a box 1 pixel tall. That is correct, and the check is right to ask; a rule that silently deleted thin boxes would delete correct scratches.
  • Agreement. 116 pairs; 11 defects only A labelled and 5 only B. The classes agree on 0.957 of the pairs, and all disagreements are crack against scratch (4 + 1): a short straight crack looks like a scratch, and the guideline must say how to tell them apart. Box agreement depends on size: median IoU 0.73 for scratches, 0.68 for cracks, but 0.61 for spots, and only 20 % of the spot pairs reach IoU 0.75. Two careful people do not agree to IoU 0.75 on a 7-pixel box.
  • Against the exact boxes. A finds 0.946 of the defects with the right class and IoU at least 0.5, B 0.777; on faint defects 0.800 and 0.450. Missing faint defects is the main label error, and it is invisible in a format check.

Against the criteria: class agreement (0.957) and median IoU (0.61 to 0.73) pass. The disagreements go to adjudication (a third, senior inspector decides), the guideline gets a sentence on cracks against scratches and one on faint defects, and B is re-briefed. For the rest of the project the training labels are the adjudicated ones; in this lesson the generator's exact boxes stand in for them, a shortcut you would not have with real data.

Step 3: your own evaluator, and what it can measure

Before trusting any mAP, own the code that computes it (detection metrics). average_precision sorts the detections of one class by score, matches each to the best unmatched ground-truth box of that class if their IoU reaches the threshold, and sums precision over the recall steps after taking the precision envelope (VOC-style all-point AP). Two checks: a case small enough to do by hand, and the exact boxes themselves moved by one or two pixels, with random scores, as if a detector found every defect but placed it slightly off.

python · try it yourself
import numpy as np, cv2

CLASSES = ["scratch", "spot", "crack"]          # YOLO class ids 0, 1, 2

def draw_defect(rng, m, c, x0, y0, s):
    """Draws defect c (0 scratch, 1 spot, 2 crack) into the float mask m, inside the s x s square at (x0, y0)."""
    if c == 0:                                  # long, straight, thin
        a = rng.uniform(0, np.pi); half = rng.uniform(0.35, 0.5) * s
        cx, cy = x0 + s / 2, y0 + s / 2
        cv2.line(m, (int(cx - np.cos(a) * half), int(cy - np.sin(a) * half)),
                 (int(cx + np.cos(a) * half), int(cy + np.sin(a) * half)), 1.0, 1, cv2.LINE_AA)
    elif c == 1:                                # small, round
        r = rng.uniform(2, 5)
        cv2.circle(m, (int(x0 + s / 2), int(y0 + s / 2)), int(round(r)), 1.0, -1, cv2.LINE_AA)
    else:                                       # jagged random walk
        p = np.array([x0 + s / 2, y0 + s / 2]); a = rng.uniform(0, 2 * np.pi)
        for _ in range(int(rng.integers(5, 10))):
            a += rng.normal(0, 0.6)
            q = np.clip(p + 3 * np.array([np.cos(a), np.sin(a)]), [x0, y0], [x0 + s - 1, y0 + s - 1])
            cv2.line(m, (int(p[0]), int(p[1])), (int(q[0]), int(q[1])), 1.0, 1, cv2.LINE_AA)
            p = q

def make_panel(rng, size=128, max_defects=4):
    """A line-A steel panel with 0..max_defects defects that do not touch. Returns the grey uint8 image,
    the exact boxes (n, 4) as pixel corners [x1, y1, x2, y2] (x2, y2 exclusive), classes (n,), contrasts (n,)."""
    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))
    img += np.linspace(-1, 1, size)[None, :] * rng.uniform(-12, 12)
    boxes, labels, contrasts = [], [], []
    for _ in range(int(rng.integers(0, max_defects + 1))):
        c = int(rng.integers(0, 3)); s = int(rng.integers(10, 15)) if c == 1 else int(rng.integers(20, 41))
        for _ in range(30):                     # find a free place
            x0, y0 = (int(v) for v in rng.integers(2, size - s - 2, 2))
            if all(x0 > b[2] + 2 or x0 + s < b[0] - 2 or y0 > b[3] + 2 or y0 + s < b[1] - 2 for b in boxes):
                break
        else:
            continue
        m = np.zeros((size, size), np.float32)
        draw_defect(rng, m, c, x0, y0, s)
        if c == 1:
            m = cv2.GaussianBlur(m, (0, 0), 0.8)
        contrast = rng.uniform(12, 45) if c == 0 else -rng.uniform(15, 55)
        img += contrast * m
        ys, xs = np.nonzero(m > 0.25)
        boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
        labels.append(c); contrasts.append(abs(contrast))
    return (np.clip(img, 0, 255).astype(np.uint8), np.array(boxes, int).reshape(-1, 4),
            np.array(labels, int), np.array(contrasts))

def iou(a, b):
    """IoU of two boxes [x1, y1, x2, y2]."""
    w = min(a[2], b[2]) - max(a[0], b[0]); h = min(a[3], b[3]) - max(a[1], b[1])
    inter = max(w, 0) * max(h, 0)
    return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)

def average_precision(gts, dets, cls, thr=0.5):
    """gts: per image (boxes, labels); dets: per image (boxes, labels, scores). All-point interpolated AP
    for one class: detections sorted by score, each matched to the best unmatched ground truth of that class."""
    n_gt = sum(int((l == cls).sum()) for _, l in gts)
    rows = [(s, i, b) for i, (bb, ll, ss) in enumerate(dets) for b, l, s in zip(bb, ll, ss) if l == cls]
    rows.sort(key=lambda r: -r[0])
    used = [np.zeros(len(l), bool) for _, l in gts]
    tp = []
    for s, i, b in rows:
        gb, gl = gts[i]
        cand = [(iou(b, g), j) for j, (g, l) in enumerate(zip(gb, gl)) if l == cls and not used[i][j]]
        best = max(cand, default=(0, -1))
        if best[0] >= thr:
            used[i][best[1]] = True; tp.append(1)
        else:
            tp.append(0)
    if n_gt == 0 or not tp:
        return 0.0
    tp = np.array(tp); ctp = np.cumsum(tp)
    recall = ctp / n_gt; precision = ctp / np.arange(1, len(tp) + 1)
    env = np.maximum.accumulate(precision[::-1])[::-1]          # highest precision at this recall or more
    return float(np.sum(np.diff(np.concatenate([[0], recall])) * env))

# 1. A case small enough to check by hand: one image, two scratches, three detections.
gts = [(np.array([[10, 10, 40, 20], [60, 60, 70, 90]]), np.array([0, 0]))]
dets = [(np.array([[11, 10, 41, 20], [0, 0, 8, 8], [60, 62, 70, 90]]), np.array([0, 0, 0]), np.array([0.9, 0.8, 0.6]))]
print("hand example AP@0.5:", round(average_precision(gts, dets, 0), 3))

# 2. How much AP does a box that is 1 or 2 pixels off cost? The exact boxes of 100 panels, moved, as "detections".
rng = np.random.default_rng(10)
panels = [make_panel(rng) for _ in range(100)]
gts = [(b, l) for _, b, l, _ in panels]
score_rng = np.random.default_rng(0)
for shift in [0, 1, 2]:
    dets = [(b + shift, l, score_rng.random(len(l))) for b, l in gts]      # every box moved right and down
    print(f"shift {shift} px: " + "  ".join(
        f"{CLASSES[c]} AP@0.5 {average_precision(gts, dets, c, 0.5):.2f} AP@0.75 {average_precision(gts, dets, c, 0.75):.2f}"
        for c in range(3)))
hand example AP@0.5: 0.833
shift 0 px: scratch AP@0.5 1.00 AP@0.75 1.00  spot AP@0.5 1.00 AP@0.75 1.00  crack AP@0.5 1.00 AP@0.75 1.00
shift 1 px: scratch AP@0.5 0.83 AP@0.75 0.31  spot AP@0.5 0.53 AP@0.75 0.00  crack AP@0.5 1.00 AP@0.75 0.05
shift 2 px: scratch AP@0.5 0.51 AP@0.75 0.00  spot AP@0.5 0.06 AP@0.75 0.00  crack AP@0.5 0.24 AP@0.75 0.00

By hand: the detections are a true positive (score 0.9, IoU 0.94), a false positive (0.8) and a true positive (0.6, IoU 0.93). Precision after each is 1, 0.5 and 0.667 at recall 0.5, 0.5 and 1; the envelope is 1 up to recall 0.5 and 0.667 after it, so AP = 0.5 x 1 + 0.5 x 0.667 = 0.833, as printed.

Shifted boxes show how unforgiving IoU is for tiny objects. Moving every box one pixel right and down keeps cracks at AP@0.5 1.00 but drops spots to 0.53 and to 0.00 at IoU 0.75. A 7 x 7 box moved by one pixel in both directions has IoU 36 / 62 = 0.58; a scratch that is almost horizontal is 1 or 2 pixels tall and loses even more. Together with Step 2 this sets realistic expectations: AP@0.75 on these defects mostly measures label noise, not the detector. The report will use AP@0.5 as the main metric and quote AP@0.75 only with this warning.

Step 4: fine-tune YOLOv8n, test once, analyse the errors

The training uses the course's pattern for a CPU (Ultralytics lesson): COCO-pretrained yolov8n.pt, imgsz=128 (the panel's own size, so no detail is lost to scaling), 7 epochs, batches of 16, val=False during training to save time, a fixed seed, plots and MLflow logging off. The program then:

  1. evaluates the validation split with Ultralytics' model.val and with our evaluator on model.predict outputs (confidence 0.001, as an evaluator should use);
  2. evaluates the test split once, at IoU 0.5 and 0.75;
  3. matches the detections above the operating threshold 0.25 to the exact boxes and breaks the recall down by box size, class and contrast.

Recorded: Ultralytics 8.4, CPU, about 30 s.

python · try it yourself
import os
os.environ["YOLO_VERBOSE"] = "False"
import tempfile
import numpy as np, cv2

CLASSES = ["scratch", "spot", "crack"]          # YOLO class ids 0, 1, 2

def draw_defect(rng, m, c, x0, y0, s):
    """Draws defect c (0 scratch, 1 spot, 2 crack) into the float mask m, inside the s x s square at (x0, y0)."""
    if c == 0:                                  # long, straight, thin
        a = rng.uniform(0, np.pi); half = rng.uniform(0.35, 0.5) * s
        cx, cy = x0 + s / 2, y0 + s / 2
        cv2.line(m, (int(cx - np.cos(a) * half), int(cy - np.sin(a) * half)),
                 (int(cx + np.cos(a) * half), int(cy + np.sin(a) * half)), 1.0, 1, cv2.LINE_AA)
    elif c == 1:                                # small, round
        r = rng.uniform(2, 5)
        cv2.circle(m, (int(x0 + s / 2), int(y0 + s / 2)), int(round(r)), 1.0, -1, cv2.LINE_AA)
    else:                                       # jagged random walk
        p = np.array([x0 + s / 2, y0 + s / 2]); a = rng.uniform(0, 2 * np.pi)
        for _ in range(int(rng.integers(5, 10))):
            a += rng.normal(0, 0.6)
            q = np.clip(p + 3 * np.array([np.cos(a), np.sin(a)]), [x0, y0], [x0 + s - 1, y0 + s - 1])
            cv2.line(m, (int(p[0]), int(p[1])), (int(q[0]), int(q[1])), 1.0, 1, cv2.LINE_AA)
            p = q

def make_panel(rng, size=128, max_defects=4):
    """A line-A steel panel with 0..max_defects defects that do not touch. Returns the grey uint8 image,
    the exact boxes (n, 4) as pixel corners [x1, y1, x2, y2] (x2, y2 exclusive), classes (n,), contrasts (n,)."""
    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))
    img += np.linspace(-1, 1, size)[None, :] * rng.uniform(-12, 12)
    boxes, labels, contrasts = [], [], []
    for _ in range(int(rng.integers(0, max_defects + 1))):
        c = int(rng.integers(0, 3)); s = int(rng.integers(10, 15)) if c == 1 else int(rng.integers(20, 41))
        for _ in range(30):                     # find a free place
            x0, y0 = (int(v) for v in rng.integers(2, size - s - 2, 2))
            if all(x0 > b[2] + 2 or x0 + s < b[0] - 2 or y0 > b[3] + 2 or y0 + s < b[1] - 2 for b in boxes):
                break
        else:
            continue
        m = np.zeros((size, size), np.float32)
        draw_defect(rng, m, c, x0, y0, s)
        if c == 1:
            m = cv2.GaussianBlur(m, (0, 0), 0.8)
        contrast = rng.uniform(12, 45) if c == 0 else -rng.uniform(15, 55)
        img += contrast * m
        ys, xs = np.nonzero(m > 0.25)
        boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
        labels.append(c); contrasts.append(abs(contrast))
    return (np.clip(img, 0, 255).astype(np.uint8), np.array(boxes, int).reshape(-1, 4),
            np.array(labels, int), np.array(contrasts))

def iou(a, b):
    """IoU of two boxes [x1, y1, x2, y2]."""
    w = min(a[2], b[2]) - max(a[0], b[0]); h = min(a[3], b[3]) - max(a[1], b[1])
    inter = max(w, 0) * max(h, 0)
    return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)

def average_precision(gts, dets, cls, thr=0.5):
    """gts: per image (boxes, labels); dets: per image (boxes, labels, scores). All-point interpolated AP
    for one class: detections sorted by score, each matched to the best unmatched ground truth of that class."""
    n_gt = sum(int((l == cls).sum()) for _, l in gts)
    rows = [(s, i, b) for i, (bb, ll, ss) in enumerate(dets) for b, l, s in zip(bb, ll, ss) if l == cls]
    rows.sort(key=lambda r: -r[0])
    used = [np.zeros(len(l), bool) for _, l in gts]
    tp = []
    for s, i, b in rows:
        gb, gl = gts[i]
        cand = [(iou(b, g), j) for j, (g, l) in enumerate(zip(gb, gl)) if l == cls and not used[i][j]]
        best = max(cand, default=(0, -1))
        if best[0] >= thr:
            used[i][best[1]] = True; tp.append(1)
        else:
            tp.append(0)
    if n_gt == 0 or not tp:
        return 0.0
    tp = np.array(tp); ctp = np.cumsum(tp)
    recall = ctp / n_gt; precision = ctp / np.arange(1, len(tp) + 1)
    env = np.maximum.accumulate(precision[::-1])[::-1]          # highest precision at this recall or more
    return float(np.sum(np.diff(np.concatenate([[0], recall])) * env))
from ultralytics import YOLO, settings
settings.update({"mlflow": False})

root = tempfile.mkdtemp()
rng = np.random.default_rng(10)                                 # the same panels as in Step 1
data = {}
for split, n in [("train", 200), ("val", 60), ("test", 100)]:
    os.makedirs(f"{root}/images/{split}"); os.makedirs(f"{root}/labels/{split}")
    data[split] = [make_panel(rng) for _ in range(n)]
    for i, (img, boxes, labels, _) in enumerate(data[split]):
        cv2.imwrite(f"{root}/images/{split}/{i:04d}.png", img)
        with open(f"{root}/labels/{split}/{i:04d}.txt", "w") as f:
            for (x1, y1, x2, y2), l in zip(boxes, labels):
                f.write(f"{l} {(x1 + x2) / 256:.6f} {(y1 + y2) / 256:.6f} {(x2 - x1) / 128:.6f} {(y2 - y1) / 128:.6f}\n")
with open(f"{root}/panels.yaml", "w") as f:
    f.write(f"path: {root}\ntrain: images/train\nval: images/val\ntest: images/test\nnames:\n  0: scratch\n  1: spot\n  2: crack\n")

model = YOLO("yolov8n.pt")                                      # COCO weights: no defect classes yet
model.train(data=f"{root}/panels.yaml", epochs=7, imgsz=128, batch=16, val=False, workers=0, device="cpu", seed=0,
            deterministic=True, plots=False, amp=False, project=root, name="run", exist_ok=True)

def predict(split):                                             # what the application sees, at a low threshold
    out = []
    for img, *_ in data[split]:
        r = model.predict(cv2.cvtColor(img, cv2.COLOR_GRAY2BGR), imgsz=128, conf=0.001, verbose=False)[0]
        out.append((r.boxes.xyxy.numpy(), r.boxes.cls.numpy().astype(int), r.boxes.conf.numpy()))
    return out

# 1. Our evaluator next to Ultralytics' on the validation split.
m = model.val(data=f"{root}/panels.yaml", split="val", imgsz=128, batch=16, device="cpu", plots=False)
gts_va = [(b, l) for _, b, l, _ in data["val"]]
ours = [average_precision(gts_va, predict("val"), c) for c in range(3)]
print("val AP@0.5  Ultralytics:", np.round(m.box.ap50, 3).tolist(), "| ours:", np.round(ours, 3).tolist())

# 2. The test split, once.
gts = [(b, l) for _, b, l, _ in data["test"]]
dets = predict("test")
for thr in [0.5, 0.75]:
    aps = [average_precision(gts, dets, c, thr) for c in range(3)]
    print(f"test AP@{thr}: " + "  ".join(f"{n} {a:.3f}" for n, a in zip(CLASSES, aps)) + f"  | mAP {np.mean(aps):.3f}")

# 3. Error analysis at the operating threshold conf = 0.25: which defects are missed, what is found by mistake?
found, size, cls, con, fps = [], [], [], [], 0
for (_, gb, gl, gc), (db, dl, ds) in zip(data["test"], dets):
    keep = ds >= 0.25; db, dl = db[keep], dl[keep]
    used = np.zeros(len(db), bool)
    for g, l, c in zip(gb, gl, gc):
        best = max([(iou(d, g), k) for k, d in enumerate(db) if dl[k] == l and not used[k]], default=(0, -1))
        if best[0] >= 0.5:
            used[best[1]] = True
        found.append(best[0] >= 0.5); size.append(np.sqrt((g[2] - g[0]) * (g[3] - g[1]))); cls.append(l); con.append(c)
    fps += int((~used).sum())
found, size, cls, con = map(np.array, (found, size, cls, con))
print(f"conf 0.25: recall {found.mean():.3f} of {len(found)} defects, {fps} false positives on {len(dets)} panels")
for lo, hi in [(0, 8), (8, 14), (14, 30)]:
    k = (size >= lo) & (size < hi)
    print(f"  box size {lo:2d}-{hi:2d} px: {k.sum():3d} defects, recall {found[k].mean():.3f}")
for c in range(3):
    k = cls == c
    print(f"  {CLASSES[c]:8s} recall {found[k].mean():.3f}  (contrast < 20: {found[k & (con < 20)].mean():.3f} "
          f"of {(k & (con < 20)).sum()}, >= 20: {found[k & (con >= 20)].mean():.3f} of {(k & (con >= 20)).sum()})")
val AP@0.5  Ultralytics: [0.616, 0.78, 0.556] | ours: [0.607, 0.663, 0.58]
test AP@0.5: scratch 0.494  spot 0.698  crack 0.693  | mAP 0.628
test AP@0.75: scratch 0.226  spot 0.188  crack 0.045  | mAP 0.153
conf 0.25: recall 0.615 of 192 defects, 89 false positives on 100 panels
  box size  0- 8 px:  37 defects, recall 0.324
  box size  8-14 px: 115 defects, recall 0.661
  box size 14-30 px:  40 defects, recall 0.750
  scratch  recall 0.471  (contrast < 20: 0.150 of 20, >= 20: 0.600 of 50)
  spot     recall 0.651  (contrast < 20: 0.077 of 13, >= 20: 0.800 of 50)
  crack    recall 0.746  (contrast < 20: 0.333 of 6, >= 20: 0.792 of 53)

Two evaluators, two numbers. On validation, our AP@0.5 agrees with Ultralytics' for scratches and cracks within 0.03, but is 0.117 lower for spots. Ultralytics' validator differs from the predictions an application sees in three ways (all visible in its source): its NMS lets one box propose several classes (multi_label=True), it matches detections to ground truth in order of IoU rather than score, and it samples the PR curve at 101 points as COCO does. On tiny, crowded candidates such as spots, these choices add up. Neither number is wrong; the rule is to pick one evaluator, write down its definition, and never compare numbers from two.

The test run, once: mAP@0.5 = 0.628 (scratch 0.494, spot 0.698, crack 0.693) and mAP@0.75 = 0.153. At confidence 0.25 the detector finds 0.615 of the 192 test defects and makes 89 false detections on 100 panels. Both detector criteria (0.7 and 0.8) are not met.

Where the errors are:

Slice Defects Recall at 0.25
box under 8 px 37 0.324
box 8 to 14 px 115 0.661
box 14 px and more 40 0.750
scratches / spots / cracks, contrast under 20 20 / 13 / 6 0.150 / 0.077 / 0.333
scratches / spots / cracks, contrast 20 and more 50 / 50 / 53 0.600 / 0.800 / 0.792

The misses are concentrated where the annotators also struggled: small and faint defects. A box under 8 pixels is found one time in three, a faint spot almost never. Scratches are the weakest class overall (recall 0.471): thin diagonal lines give boxes that are mostly background, and with 7 epochs the network has not learned them well. The mAP@0.75 of 0.153 says little, as Step 3 showed.

What to fix, in order of expected gain:

  1. Train properly. 7 epochs is a smoke test; the Ultralytics default is 100 epochs, which needs a GPU or patience. Check the training loss curve before anything else (fine-tuning recipe).
  2. More pixels per defect. Train and predict at imgsz=256 (the panel upscaled), or cut the full sheet photo into tiles at the camera's native resolution: small objects at low resolution are a known weak spot of one-stage detectors (YOLO and one-stage detectors).
  3. Faint defects in the labels. Annotators missed 20 to 55 % of them; a detector trained on such labels learns to ignore them. Adjudicate, and add an explicit rule to the guideline.
  4. Then compare a larger model (yolo11n, yolov8s) on the same validation data with the same evaluator.

Extensions

  • Label noise as an experiment: train once on annotator B's labels and once on the exact boxes, and measure the AP difference on the same test set.
  • Tiling: generate 512 x 512 sheets, cut them into overlapping 128 pixel tiles, predict, shift boxes back and merge duplicates across tile borders with NMS.
  • Agreement as a ceiling: compute the AP of annotator A against the exact boxes as if A were a detector with score 1 for every box; no model trained on A-quality labels should be expected to beat it.
  • Counting: defects per panel is what the engineers want; compare predicted and true counts per panel at the operating threshold, which can look fine even when boxes are off.
  • Deployment: export the trained model to ONNX and run it with your own letterbox and box decoding, as in ONNX export.

Write-up template

text
Project: steel defect detector, <date>
Data: <n> panels (train/val/test), source and image rights, classes and their definitions
Labelling: guideline version <...>, annotators <n>, doubly labelled sample <n> panels
Label QA: format errors found <n> (types), warnings reviewed <n>, class agreement <x>, median IoU per class <...>
Evaluator: definition (matching, interpolation, IoU thresholds), hand check passed, difference to <tool> explained
Model: <weights>, imgsz <...>, epochs <...>, hardware, time
Test (once): AP@0.5 per class <...>, mAP@0.5 <...>, recall and false positives per panel at conf <t>
Errors: by size <...>, by contrast <...>, by class <...>
Next: <ordered list with the expected gain of each>
Limits: synthetic panels, exact boxes used as adjudicated labels, one seed, short CPU training

Practice

  1. A label line reads 2 0.990000 0.300000 0.080000 0.100000. Which check fails, and what are the box's pixel corners on a 128 x 128 image?
Answer

"Box leaves the image": the centre is at x = 0.99 and the half width 0.04, so the right edge is at 1.03. In pixels: centre (126.7, 38.4), size 10.2 x 12.8, corners about [121.6, 32.0, 131.8, 44.8]. The right edge is 3.8 pixels outside the image: either the centre or the width is wrong, and only a person looking at the image can tell which.

  1. Compute the IoU of a spot's exact box [10, 10, 17, 17] with a box moved by 1 pixel right only, and with one moved by 1 pixel right and 1 down.
Answer

Right only: overlap 6 x 7 = 42, union 49 + 49 - 42 = 56, IoU 0.75. Right and down: overlap 6 x 6 = 36, union 98 - 36 = 62, IoU 0.58. One pixel of disagreement in one direction puts a 7-pixel box exactly at the AP@0.75 limit.

  1. Our evaluator gave a spot AP@0.5 of 0.663 on validation, Ultralytics 0.78. A colleague wants to report the higher number because "it is the official tool". What do you answer?
Answer

Report whichever you like, but say which, define it, and use the same one for every model and every later report. The two differ because Ultralytics' validator uses multi-label NMS, IoU-ordered matching and 101-point sampling; neither is official for this project. Since the application uses model.predict outputs, our evaluator measures what the robot will actually see.

  1. Recall on test was 0.615 at confidence 0.25. Should you lower the threshold to 0.1 to reach the 0.8 target?
Answer

Not by looking at the test set: the threshold is chosen on validation. Lowering it raises recall and false positives together (there were already 89 on 100 panels), so check the trade-off on validation first. The error analysis suggests the misses are mostly small and faint defects the model barely scores at all; a lower threshold will not find those, better training and more pixels will.

Test yourself

A YOLO label file for an image with no defects should be...

  1. left out
  2. an empty .txt file
  3. a line with class -1
  4. a box covering the whole image

Two careful annotators reached a median IoU of 0.61 on spots, and a 1-pixel shift dropped spot AP@0.75 to 0. What follows for the report?

  1. Use AP@0.75 as the main metric
  2. AP@0.75 on these tiny objects mostly measures label noise, so AP@0.5 is the main metric
  3. Spots should be removed from the data
  4. IoU does not apply to small boxes

Why did our AP@0.5 for spots differ from Ultralytics' model.val on the same model?

  1. One of them has a bug
  2. Ultralytics' validator uses multi-label NMS, IoU-ordered matching and 101-point sampling; ours scores the predictions the application sees
  3. Ultralytics uses IoU 0.75
  4. Our evaluator ignores small boxes

Which defects did the detector miss most often at confidence 0.25?

  1. Large cracks
  2. Small (under 8 px) and faint (contrast under 20) defects
  3. Defects near the image centre
  4. Bright scratches with high contrast