Module 13/15 · Weeks 13 · 9 h

Detection, classification and segmentation in applications

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

About 100 minDraft, awaiting reviewLast updated 1 October 2026

Lesson

By the end of this module you will be able to

  1. Choose between classification, detection and segmentation to match the output the task needs, using a decision table whose sensitivity to the weights is tested
  2. Build a patch classifier from colour and texture features (LBP) and choose the probability threshold on a validation set with realistic class proportions
  3. Detect repeated objects by template matching and evaluate with IoU, precision and recall
  4. Segment cracks with a black-hat filter and shape filtering, and evaluate with a tolerance-based metric suited to thin lines
  5. State when to move to a deep-learning model and what data to prepare

Prerequisites: Modules 11 and 12 of this course · UAT 306 Artificial intelligence for unmanned aircraft systems (recommended) · UAT 307 Computer vision and perception technology (module 1, choosing a threshold with Otsu)

Why this matters

Module 12 showed where on a concrete panel something has changed. The next question is what changed, and what kind of answer the job needs. If all that is needed is a flag saying that this panel looks suspicious, a classifier that says “normal” or “crack” for each image patch is enough. If every weep hole must be counted for an asset register, a box is needed for each hole. If the crack width must be measured, a pixel mask saying which pixels are crack is needed. These three kinds of output are classification, detection and segmentation, and choosing the wrong one wastes a whole project, for example using a box detector for a width measurement.

This module does not teach training deep networks; that belongs to modules 1–5 of this course. It teaches the classical toolkit that serves as the baseline you should always build first and, more importantly, the way to evaluate any model: IoU, precision, recall and metrics for thin lines. Every example uses small synthetic images, so the results can be rerun in a few seconds, but the numbers illustrate a way of thinking and are not results from real data.

Choosing a technique from the output the task needs

A practical decision has two steps. First, filter by the required output, which is a hard condition: methods that give a different kind of result are dropped at once. Second, score the remaining methods with weights that reflect the job.

MethodGivesNeeds labelsStrengthBreaks when
Template matchingBoxNoneFast, explainable, for objects of one fixed lookAppearance or size changes a lot
Patch classification with featuresA label per patchA moderate amountA quick baselineTexture and light differ from the training set
Black-hat and a thresholdMaskNoneA mask for measurement right awayVery rough texture, shadows
Deep detectorBoxA lotTolerates varied appearanceLittle data, hard to explain
Deep segmentationMaskA lot (pixel level)Accurate on complex cracksLittle data, power hungry

The five criteria commonly scored are: no labels needed, robust to appearance change, light compute, explainable, and quick to build. The result is a total , where is the weight of criterion (summing to 1) and is the score from 1 to 5 of method . This table organises the argument; it is not a measurement, because the scores are the team’s judgement, so you must test how much the weights can change before the result flips.

Example 1 A decision table and its sensitivity to the weights

Task A is an inventory of weep holes (boxes needed). Task B is crack-width measurement (a mask needed). The scores of each method are in the table above (assumed). Task A uses weights 0.30, 0.20, 0.15, 0.20 and 0.15 for the five criteria in order, then raises the weight of “robust to appearance” in steps of 0.05 to find where the result flips. Task B compares two situations: no labelled data yet, and 2,000 labelled images ready.

import numpy as np

criteria = ["no labels needed", "robust to appearance", "light compute", "explainable", "quick to build"]
# (scores 1-5 are the team's judgement, assumed)
methods = {
    "template matching":     dict(out="box",   s=[5, 2, 5, 5, 5]),
    "patch classifier":      dict(out="label", s=[2, 3, 5, 4, 3]),
    "black-hat + threshold": dict(out="mask",  s=[5, 2, 5, 5, 4]),
    "deep detector":         dict(out="box",   s=[1, 5, 2, 2, 2]),
    "deep segmentation":     dict(out="mask",  s=[1, 5, 2, 2, 1]),
}

def rank(need, weights):
    w = np.array(weights, float) / np.sum(weights)
    rows = [(float(np.dot(w, m["s"])), name) for name, m in methods.items() if m["out"] == need]   # filter by the output the task needs first
    return sorted(rows, reverse=True)

print("A weep-hole inventory (needs boxes), weights", [0.30, 0.20, 0.15, 0.20, 0.15])
for score, name in rank("box", [0.30, 0.20, 0.15, 0.20, 0.15]):
    print(f"  {name:22s} {score:.2f}")

for w_rob in np.arange(0.20, 0.71, 0.05):     # raise the weight of robustness to appearance
    rest = np.array([0.30, 0.15, 0.20, 0.15]) * (1 - w_rob) / 0.80   # rescale the others in proportion
    w = [rest[0], w_rob, rest[1], rest[2], rest[3]]
    if rank("box", w)[0][1] != "template matching":
        print(f"  the winner flips to {rank('box', w)[0][1]} when the robustness weight reaches {w_rob:.2f}")
        break

print("B crack width (needs a mask)")
for label, w in (("no labelled data yet", [0.30, 0.25, 0.10, 0.20, 0.15]), ("2,000 labelled images ready", [0.02, 0.55, 0.08, 0.15, 0.20])):
    best = rank("mask", w)
    print(f"  {label:27s}: " + ", ".join(f"{n} {s:.2f}" for s, n in best))
A weep-hole inventory (needs boxes), weights [0.3, 0.2, 0.15, 0.2, 0.15]
  template matching      4.40
  deep detector          2.30
  the winner flips to deep detector when the robustness weight reaches 0.55
B crack width (needs a mask)
  no labelled data yet       : black-hat + threshold 4.10, deep segmentation 2.30
  2,000 labelled images ready: deep segmentation 3.43, black-hat + threshold 3.15

For task A, template matching scores 4.40 and the deep detector 2.30. The result flips when the robustness weight reaches 0.55 in steps of 0.05 (the true crossing is computed as 0.53, as in Figure 1). So if the team expects the appearance to vary more than that, it should change method. For task B, without labels the black-hat method scores 4.10 and beats deep segmentation at 2.30, but with 2,000 labelled images (the weight of “no labels needed” drops to 0.02 and “robust to appearance” rises to 0.55) the result reverses to deep segmentation 3.43 against 3.15. The data on hand changes the answer; the team’s taste does not.

A graph with two lines. The horizontal axis is the weight of the criterion robust to appearance, 0.2 to 0.7, the vertical axis the weighted score. The green line for template matching falls from 4.4 to 2.9. The purple line for the deep detector rises from 2.3 to 4.0. They cross at about 0.53, marked by a dashed pink line.
Figure 1 Weighted score for task A as the weight of robustness to appearance rises. The result flips at about 0.53.

Classifying patches with colour and texture features

A widely used crack dataset, SDNET2018, cuts 230 photographs of bridge decks, walls and pavements into more than 56,000 patches of 256 × 256 pixels, each labelled as cracked or not (Dorafshan et al., 2018, the SDNET2018 dataset). Cutting a large image into patches and classifying each one is therefore a standard approach, and there is work that compares deep networks with classical edge detectors directly on concrete crack images (Dorafshan et al., 2018, the comparison study). For a classical baseline use five groups of features that are cheap to compute: the mean colour, the standard deviation of brightness, the extreme darkness (the median minus the 1st percentile), the fraction of pixels much darker than the median, and the elongation of the dark pixels (the ratio of the eigenvalues of the covariance of their coordinates: cracks are long, stains are round), plus a histogram of a rotation-invariant LBP (local binary pattern) proposed by Ojala et al. (2002), which compares each pixel with its eight neighbours and summarises the result in 10 patterns.

The classifier is the logistic regression of scikit-learn (Pedregosa et al., 2011) on scaled features. The most important problem is not the classifier but the class imbalance: cracks are only a few percent of patches, so a metric such as accuracy is misleading, and Saito and Rehmsmeier (2015) show that the precision-recall plot is more informative than the ROC plot on imbalanced data. The probability threshold that decides “crack” must be chosen on a validation set with realistic proportions, not on the test set, and the false-alarm rate must be converted into a count per concrete panel so that the people doing the work can understand it.

Example 2 A crack classifier and choosing the threshold

Synthetic 32 × 32 pixel patches of four kinds: sound, crack, stain and vegetation (standing in for real patches 128 pixels wide, which at a GSD of 0.289 mm are 37 mm, shrunk fourfold; assumed). The training set is balanced with 300 patches per kind, and the validation and test sets have realistic proportions, with 2% cracks. A concrete panel 5.0 m by 3.0 m is cut into 135 × 81 = 10,935 patches. The threshold chosen on the validation set is the lowest one that gives no more than 20 false alarms per concrete panel.

import cv2
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

def concrete(h, w, seed, contrast=1.0):       # synthetic concrete texture
    r = np.random.RandomState(seed)
    fine = cv2.GaussianBlur(r.normal(0, 1, (h, w)).astype(np.float32), (0, 0), 0.8)
    mid = cv2.GaussianBlur(r.normal(0, 1, (h, w)).astype(np.float32), (0, 0), 3.0)
    img = 150 + contrast * (25 * fine / fine.std() + 18 * mid / mid.std())
    return np.clip(img, 0, 255).astype(np.uint8)

def patch(kind, seed):                         # a 32x32 patch of each kind
    r = np.random.RandomState(seed)
    g = concrete(32, 32, seed, r.uniform(0.15, 0.30)).astype(np.float32)
    rgb = np.stack([g * 0.97, g, g * 1.01], axis=2)             # nearly grey BGR
    if kind == 1:                              # crack: a thin dark line of random depth (some very faint)
        pts = np.array([(r.randint(0, 6), r.randint(4, 28)), (16, r.randint(8, 24)), (r.randint(26, 32), r.randint(4, 28))], np.int32)
        m = np.zeros((32, 32), np.float32)
        cv2.polylines(m, [pts], False, 1.0, int(r.randint(1, 3)))
        rgb -= r.uniform(40, 90) * cv2.GaussianBlur(m, (0, 0), 0.7)[..., None]
    elif kind == 2:                            # stain: a broad smooth dark area
        m = np.zeros((32, 32), np.float32)
        cv2.circle(m, (r.randint(8, 24), r.randint(8, 24)), int(r.randint(6, 12)), 1.0, -1)
        rgb -= r.uniform(20, 50) * cv2.GaussianBlur(m, (0, 0), 3.0)[..., None]
    elif kind == 3:                            # vegetation: a green tint
        m = np.zeros((32, 32), np.float32)
        cv2.circle(m, (r.randint(8, 24), r.randint(8, 24)), int(r.randint(5, 10)), 1.0, -1)
        m = cv2.GaussianBlur(m, (0, 0), 1.5)[..., None]
        rgb = rgb * (1 - 0.7 * m) + np.array([60, 125, 70], np.float32) * 0.7 * m
    return np.clip(rgb + r.normal(0, 3, rgb.shape), 0, 255).astype(np.uint8)

def lbp_hist(gray):                            # rotation-invariant uniform LBP (riu2, P = 8), 10 bins
    c = gray[1:-1, 1:-1].astype(int)
    sh = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), (2, 1), (2, 0), (1, 0)]
    bits = np.stack([(gray[dy:dy + 30, dx:dx + 30].astype(int) >= c).astype(int) for dy, dx in sh])
    trans = np.abs(bits - np.roll(bits, 1, axis=0)).sum(axis=0)
    code = np.where(trans <= 2, bits.sum(axis=0), 9)
    return np.bincount(code.ravel(), minlength=10) / code.size

def features(p):
    g = cv2.cvtColor(p, cv2.COLOR_BGR2GRAY)
    med = np.median(g)
    gx, gy = cv2.Sobel(g, cv2.CV_32F, 1, 0), cv2.Sobel(g, cv2.CV_32F, 0, 1)
    dark = [(g < med - d).mean() for d in (20, 35)]            # fraction of pixels far darker than the median
    ys, xs = np.nonzero(g < med - 30)                         # elongation of the dark pixels: cracks are long, stains round
    if ys.size >= 8:
        ev = np.maximum(np.linalg.eigvalsh(np.cov(np.vstack([xs, ys]))), 1e-3)
        elong = float(min(np.sqrt(ev[1] / ev[0]), 12))
    else:
        elong = 1.0
    return np.r_[p.reshape(-1, 3).mean(axis=0), g.std(), med - np.percentile(g, 1), dark, np.hypot(gx, gy).mean(), elong, lbp_hist(g)]

def make_set(counts, seed0):
    X, y = [], []
    for kind, n in enumerate(counts):
        for i in range(n):
            X.append(features(patch(kind, seed0 + 10000 * kind + i))); y.append(kind)
    return np.array(X), np.array(y)

Xtr, ytr = make_set([300, 300, 300, 300], 1)           # balanced training set
Xva, yva = make_set([2880, 60, 30, 30], 900000)        # validation set to choose the threshold, at realistic prevalence
Xte, yte = make_set([5760, 120, 60, 60], 500000)       # test set at realistic prevalence: cracks 2%
print(f"test set: {len(yte)} patches, cracks {int((yte == 1).sum())} ({100 * (yte == 1).mean():.0f}%)")
print(f"always answering 'sound': accuracy {100 * (yte == 0).mean():.1f}%, crack recall 0%")

clf = make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000)).fit(Xtr, ytr)
pred = clf.predict(Xte)
print(f"classifier: accuracy {100 * (pred == yte).mean():.1f}%")
print("confusion (rows true, columns predicted: sound crack stain veg)")
for k, name in enumerate(["sound", "crack", "stain", "veg"]):
    print(f"  {name:6s}", np.bincount(pred[yte == k], minlength=4))

p_crack = clf.predict_proba(Xte)[:, 1]
crack = yte == 1
PATCHES_PER_PANEL = round(5.0 / 0.037) * round(3.0 / 0.037)   # a 5.0 x 3.0 m panel cut into 37 mm patches (128 px at GSD 0.289 mm)
print(f"patches per panel {PATCHES_PER_PANEL}")
print("crack threshold  recall  precision  false alarms per 1000 sound patches  per panel")
for thr in (0.5, 0.8, 0.95, 0.99):
    sel = p_crack >= thr
    tp, fp = int((sel & crack).sum()), int((sel & ~crack).sum())
    fpr = fp / (~crack).sum()
    print(f"{thr:15.2f} {100 * tp / crack.sum():6.1f}% {100 * tp / max(tp + fp, 1):9.1f}% {1000 * fpr:29.1f} {fpr * PATCHES_PER_PANEL:11.0f}")

pv, cv_ = clf.predict_proba(Xva)[:, 1], yva == 1       # lowest threshold with at most 20 false alarms per panel on the validation set
ok = [t for t in np.linspace(0.5, 0.99, 50) if ((pv >= t) & ~cv_).sum() / (~cv_).sum() * PATCHES_PER_PANEL <= 20]
thr = ok[0]
sel = p_crack >= thr
tp, fp = int((sel & crack).sum()), int((sel & ~crack).sum())
print(f"threshold {thr:.2f} chosen on validation -> test: recall {100 * tp / crack.sum():.1f}%, precision {100 * tp / (tp + fp):.1f}%, false alarms per panel {fp / (~crack).sum() * PATCHES_PER_PANEL:.0f}")
test set: 6000 patches, cracks 120 (2%)
always answering 'sound': accuracy 96.0%, crack recall 0%
classifier: accuracy 97.1%
confusion (rows true, columns predicted: sound crack stain veg)
  sound  [5591  112   57    0]
  crack  [  4 116   0   0]
  stain  [ 1  0 59  0]
  veg    [ 0  0  0 60]
patches per panel 10935
crack threshold  recall  precision  false alarms per 1000 sound patches  per panel
           0.50   96.7%      55.8%                          15.6         171
           0.80   90.8%      92.4%                           1.5          17
           0.95   84.2%      99.0%                           0.2           2
           0.99   74.2%     100.0%                           0.0           0
threshold 0.75 chosen on validation -> test: recall 91.7%, precision 85.9%, false alarms per panel 33

The test set has 6,000 patches, 120 of them cracks (2%). A classifier that always answers “sound” has an accuracy of 96.0% and a recall of 0%. The trained classifier has an accuracy of 97.1%, only 1.1 points higher, but its crack recall is 116 of 120 (96.7%). The confusion table shows that the main error is 112 sound patches flagged as cracks. At a threshold of 0.50 the precision is only 55.8% and there are 171 false alarms per concrete panel, which no inspector could work through. Raising the threshold to 0.80 gives a recall of 90.8%, a precision of 92.4% and 17 false alarms per panel. At 0.95 it is 2 per panel, but recall falls to 84.2%. The threshold of 0.75 chosen on the validation set gives on the test set a recall of 91.7%, a precision of 85.9% and 33 false alarms per panel, over the target of 20, because the validation set had only 2,880 sound patches, so the number of false-alarm events counted was small and the figure fluctuates. The conclusion is that the threshold must be chosen on a validation set large enough, and that a job needing very few false alarms per panel should use two stages, a light filter first and a more accurate decision after it.

Two sets of bars. The upper set is the crack recall at thresholds 0.50, 0.80, 0.95 and 0.99: 96.7, 90.8, 84.2 and 74.2 percent. The lower set is the false alarms per concrete panel: 171, 17, 2 and 0 respectively.
Figure 2 The probability threshold trades recall against false alarms per concrete panel

Detecting repeated objects by template matching

An object that looks the same every time, such as a weep hole or a survey mark, can be detected by template matching. The function cv2.matchTemplate slides the template across the image and compares the area under the template with the template. The result is a score image of size (W − w + 1) × (H − h + 1) for an image W wide and H high and a template w wide and h high. The maximum is the best match, except for TM_SQDIFF, where the minimum is the best match (OpenCV template matching tutorial). The method that suits outdoor work is TM_CCOEFF_NORMED, because it subtracts the mean and divides by the standard deviation of both patches, so it does not change when the image becomes darker or brighter in a linear way (). TM_SQDIFF compares brightness values directly, so it changes with the light.

After the score image is obtained you must find the local peaks above a threshold and avoid keeping peaks that are too close together, since the score image has broad peaks. The result is a list of boxes. Whether a detection is right is judged by the IoU (intersection over union), , of the detected box with the true box, and it counts as correct when the IoU is at least 0.5, matching one to one. TP, FP and FN are then counted and the precision and recall computed, which is the same method used to evaluate every kind of deep detector.

Example 3 Detecting weep holes with a template

A synthetic concrete panel of 480 × 360 pixels has 12 weep holes of radius 7 pixels and 25 small pits of radius 2 pixels that are not weep holes. The template is an ideal hole on average-coloured concrete. Several situations are tested: thresholds of 0.60 and 0.85; a different light (the image darkened to 0.6 times and then 20 added); SQDIFF; an image enlarged 1.3 times (a lower pass) with a one-scale template; and a multi-scale search from 0.8 to 1.5 times.

import cv2
import numpy as np

def draw_hole(img, cx, cy, r):                 # a weep hole: a dark disc with a soft edge
    m = np.zeros(img.shape, np.float32)
    cv2.circle(m, (int(round(cx)), int(round(cy))), int(round(r)), 1.0, -1)
    m = cv2.GaussianBlur(m, (0, 0), 1.0)
    img[:] = img * (1 - m) + 55 * m

rng = np.random.RandomState(12)
panel = concrete(360, 480, 31, 0.5).astype(np.float32)
holes = [(60 + 90 * i, 70 + 110 * j) for j in range(3) for i in range(5)][:12]   # 12 weep holes
for cx, cy in holes:
    draw_hole(panel, cx, cy, 7)
for _ in range(25):                            # small pits and dark specks that are not weep holes
    draw_hole(panel, rng.randint(15, 465), rng.randint(15, 345), 2)
panel = np.clip(panel + rng.normal(0, 3, panel.shape), 0, 255).astype(np.uint8)

def hole_template(scale):                      # template: an ideal hole on average concrete
    n = int(round(21 * scale)) | 1
    t = np.full((n, n), 150, np.float32)
    draw_hole(t, n // 2, n // 2, 7 * scale)
    return t.astype(np.uint8)

def iou(a, b):                                 # boxes as (cx, cy, size)
    ix = max(0, min(a[0] + a[2] / 2, b[0] + b[2] / 2) - max(a[0] - a[2] / 2, b[0] - b[2] / 2))
    iy = max(0, min(a[1] + a[2] / 2, b[1] + b[2] / 2) - max(a[1] - a[2] / 2, b[1] - b[2] / 2))
    return ix * iy / (a[2] ** 2 + b[2] ** 2 - ix * iy)

def detect(img, scales, method, thr):
    out = []
    for s in scales:
        t = hole_template(s)
        res = cv2.matchTemplate(img, t, method)
        good = 1 - res if method == cv2.TM_SQDIFF_NORMED else res          # larger is better
        keep = (good == cv2.dilate(good, np.ones((15, 15), np.uint8))) & (good >= (1 - thr if method == cv2.TM_SQDIFF_NORMED else thr))
        for y, x in zip(*np.nonzero(keep)):
            out.append((x + t.shape[1] / 2, y + t.shape[0] / 2, 17 * s, float(good[y, x])))
    out.sort(key=lambda d: -d[3])
    final = []
    for d in out:                              # merge scales: drop near-duplicates
        if all(np.hypot(d[0] - f[0], d[1] - f[1]) > 10 for f in final):
            final.append(d)
    return final

def score(dets, truth):                        # one-to-one matching at IoU >= 0.5
    left, tp = list(truth), 0
    for d in dets:
        best = max(left, key=lambda t: iou(d[:3], t), default=None)
        if best is not None and iou(d[:3], best) >= 0.5:
            tp += 1; left.remove(best)
    return tp, len(dets) - tp, len(truth) - tp

def run(name, img, scales, method, thr, k=1.0):
    dets = detect(img, scales, method, thr)
    tp, fp, fn = score(dets, [(x * k, y * k, 17 * k) for x, y in holes])
    print(f"{name:36s}: detections {len(dets):3d}, TP {tp:2d}, FP {fp:2d}, FN {fn:2d}, precision {tp / max(len(dets), 1):.2f}, recall {tp / len(holes):.2f}")

CC, SQ = cv2.TM_CCOEFF_NORMED, cv2.TM_SQDIFF_NORMED
run("normal light, CCOEFF_NORMED 0.60", panel, [1.0], CC, 0.60)
run("normal light, CCOEFF_NORMED 0.85", panel, [1.0], CC, 0.85)
dim = np.clip(panel.astype(np.float32) * 0.6 + 20, 0, 255).astype(np.uint8)    # a different light: darker with an offset
run("dim light, CCOEFF_NORMED 0.85", dim, [1.0], CC, 0.85)
run("dim light, SQDIFF_NORMED 0.20", dim, [1.0], SQ, 0.20)
near = cv2.resize(panel, None, fx=1.3, fy=1.3, interpolation=cv2.INTER_CUBIC)   # a lower pass, objects 1.3 times larger
run("1.3x larger, one scale, 0.85", near, [1.0], CC, 0.85, 1.3)
run("1.3x larger, scales 0.8-1.5, 0.85", near, [0.8, 1.0, 1.15, 1.3, 1.5], CC, 0.85, 1.3)
r1 = cv2.matchTemplate(near, hole_template(1.0), CC)                           # best score around the true holes with the single-scale template
r13 = cv2.matchTemplate(near, hole_template(1.3), CC)
best = lambda r, t: np.mean([r[max(int(y * 1.3 - t / 2) - 3, 0):int(y * 1.3 - t / 2) + 4, max(int(x * 1.3 - t / 2) - 3, 0):int(x * 1.3 - t / 2) + 4].max() for x, y in holes])
print(f"mean peak score on the true holes: template 1.0x {best(r1, 21):.2f}, template 1.3x {best(r13, 27):.2f}")
normal light, CCOEFF_NORMED 0.60    : detections  14, TP 12, FP  2, FN  0, precision 0.86, recall 1.00
normal light, CCOEFF_NORMED 0.85    : detections  12, TP 12, FP  0, FN  0, precision 1.00, recall 1.00
dim light, CCOEFF_NORMED 0.85       : detections  12, TP 12, FP  0, FN  0, precision 1.00, recall 1.00
dim light, SQDIFF_NORMED 0.20       : detections 454, TP 12, FP 442, FN  0, precision 0.03, recall 1.00
1.3x larger, one scale, 0.85        : detections   0, TP  0, FP  0, FN 12, precision 0.00, recall 0.00
1.3x larger, scales 0.8-1.5, 0.85   : detections  12, TP 12, FP  0, FN  0, precision 1.00, recall 1.00
mean peak score on the true holes: template 1.0x 0.82, template 1.3x 0.95

At a threshold of 0.60 all 12 holes are found, but with 2 false regions (precision 0.86). Raising the threshold to 0.85 gives 12 of 12 with no false regions, and the changed light has no effect at all, because the normalised CCOEFF does not change with linear light, but SQDIFF at a threshold of 0.20 gives 454 regions of which 442 are wrong (precision 0.03), which is unusable when the light changes. The worse problem is scale. When the objects are 1.3 times larger, the one-scale template finds no holes (recall 0.00), because the score at the true holes’ peaks averages 0.82, under the threshold of 0.85, while a template of scale 1.3 gives 0.95. The multi-scale search restores 12 of 12. So the threshold must be set from the measured scores of the real objects, not from a figure such as 0.8 seen in another example, and the range of scales must come from the real range of flight heights.

Segmenting cracks and evaluating thin lines

To measure crack width you need a pixel mask (a segmentation). UAT 307 taught Otsu, which picks one threshold for the whole image from the histogram. It fails on a crack under uneven light, because the brightness changes across the image by more than the crack does. The classical remedy is the black-hat operation of morphology, which is the difference between the closing of the image and the image itself and keeps only dark lines narrower than the kernel (OpenCV morphological transformations tutorial). Thin dark lines stand out while a wide gradual change of light removes itself. A threshold is then set from the median and a robust spread, and only long, thin pieces are kept (the diagonal of the bounding box at least 40 pixels and the area no more than 35% of the box), which removes random specks and round stains.

Evaluating thin lines needs special care, because a crack is only 2 or 3 pixels wide and an error of one pixel can leave less than half of it overlapping the truth. A recent study of crack inspection from drones finds that cracks represented by only a few pixels carry very large pixel-level segmentation uncertainty (Lee et al., 2026). The strict metrics (IoU and Dice) should therefore be read together with a tolerant metric, which counts a detected pixel as correct if it lies within 2 pixels of the truth.

Example 4 Segmenting cracks with black-hat and evaluating with tolerance

A synthetic 320 × 240 pixel image has two cracks 3 and 2 pixels wide, light that grades from dark to bright across the image (0.7 to 1.2 times), and one wide wet stain. Compare (1) Otsu on the whole image, (2) black-hat with an 11 × 11 elliptical kernel and a threshold of the median plus twice the robust spread, and (3) the same followed by keeping long thin pieces, against “a perfect answer shifted sideways by 1 and 2 pixels” to see how sensitive the strict metrics are.

import cv2
import numpy as np

h, w = 240, 320
truth = np.zeros((h, w), np.uint8)             # crack truth: two cracks, 3 and 2 px wide
cv2.polylines(truth, [np.array([(15, 50), (100, 80), (170, 120), (300, 150)], np.int32)], False, 1, 3)
cv2.polylines(truth, [np.array([(60, 200), (140, 175), (230, 215)], np.int32)], False, 1, 2)
img = concrete(h, w, 41, 0.3).astype(np.float32)
img = img - 70 * cv2.GaussianBlur(truth.astype(np.float32), (0, 0), 0.8)
yy, xx = np.mgrid[0:h, 0:w]
img = img * (0.7 + 0.5 * xx / w)               # light grading from dark to bright across the image
stain = cv2.GaussianBlur(cv2.ellipse(np.zeros((h, w), np.float32), (250, 70), (38, 22), 0, 0, 360, 1.0, -1), (0, 0), 6)
img = np.clip(img - 45 * stain + np.random.RandomState(3).normal(0, 3, img.shape), 0, 255).astype(np.uint8)   # a wide wet stain

def metrics(pred, name):
    pred, t = pred.astype(bool), truth.astype(bool)
    inter = (pred & t).sum()
    iou, dice = inter / max((pred | t).sum(), 1), 2 * inter / max(pred.sum() + t.sum(), 1)
    k = np.ones((5, 5), np.uint8)              # a tolerance of 2 px around the line
    prec = (pred & (cv2.dilate(truth, k) > 0)).sum() / max(pred.sum(), 1)
    rec = (t & (cv2.dilate(pred.astype(np.uint8), k) > 0)).sum() / t.sum()
    n = cv2.connectedComponents(pred.astype(np.uint8), connectivity=8)[0] - 1
    print(f"{name:28s} IoU {iou:4.2f}  Dice {dice:4.2f} | with 2 px tolerance: precision {prec:4.2f}  recall {rec:4.2f} | pieces {n:3d}")

otsu_t, otsu = cv2.threshold(img, 0, 1, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
metrics(otsu, f"1 global Otsu ({otsu_t:.0f})")

bh = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))).astype(np.float32)   # black-hat: closing minus image keeps dark lines narrower than the filter
sig = 1.4826 * np.median(np.abs(bh - np.median(bh)))
bh_mask = (cv2.GaussianBlur(bh, (0, 0), 0.8) > np.median(bh) + 2 * sig).astype(np.uint8)   # threshold = median + 2 robust spreads
metrics(bh_mask, "2 black-hat + threshold")

n, lab, st, _ = cv2.connectedComponentsWithStats(bh_mask, connectivity=8)
keep = np.zeros(n, bool)
for i in range(1, n):
    x, y, ww, hh, a = st[i]
    keep[i] = np.hypot(ww, hh) >= 40 and a < 0.35 * ww * hh      # long enough and line-like, not a blob
clean = keep[lab].astype(np.uint8)
metrics(clean, "3 + keep long thin pieces")

for px in (1, 2):                              # a perfect answer shifted sideways
    metrics(np.roll(truth, px, axis=1), f"perfect but {px} px to the side")
1 global Otsu (139)          IoU 0.05  Dice 0.09 | with 2 px tolerance: precision 0.09  recall 1.00 | pieces 392
2 black-hat + threshold      IoU 0.74  Dice 0.85 | with 2 px tolerance: precision 0.88  recall 1.00 | pieces  90
3 + keep long thin pieces    IoU 0.84  Dice 0.91 | with 2 px tolerance: precision 1.00  recall 1.00 | pieces   2
perfect but 1 px to the side IoU 0.84  Dice 0.91 | with 2 px tolerance: precision 1.00  recall 1.00 | pieces   2
perfect but 2 px to the side IoU 0.70  Dice 0.83 | with 2 px tolerance: precision 1.00  recall 1.00 | pieces   2

Otsu gets a Dice of only 0.09, because its threshold of 139 cuts along the light gradient, not along the crack, giving 392 small pieces across the image. Black-hat gets a Dice of 0.85 with a recall of 1.00, but still has 90 pieces and a tolerant precision of 0.88. Keeping only long thin pieces leaves exactly 2 pieces, matching the true cracks, with an IoU of 0.84 and a Dice of 0.91. The interesting part is the bottom lines. An answer that is perfect but shifted by only 1 pixel also gets an IoU of 0.84 and a Dice of 0.91, the same as method 3, and a 2 pixel shift drops the Dice to 0.83 while the tolerant metric stays at 1.00 in each case. A Dice of 0.91 for method 3 therefore means that the remaining error is at the one-pixel level, which is beyond the resolution of the image, and does not mean that the model is weak. Whether the segmentation is good enough must be judged by the width it yields (module 14), not by Dice alone.

Horizontal bar chart with five groups, each with a purple strict Dice bar and a green precision bar with a 2 pixel tolerance. Global Otsu 0.09 and 0.09, black-hat with a threshold 0.85 and 0.88, plus keeping long thin pieces 0.91 and 1.00, answer shifted by 1 pixel 0.91 and 1.00, answer shifted by 2 pixels 0.83 and 1.00.
Figure 3 Strict and tolerant metrics for a thin line

When to use a deep-learning model

The classical baseline loses when the appearance is more varied than hand-made rules can cover, for example cracks on several surfaces mixed with water stains and shadows. Deep models such as the YOLO detector (Redmon et al., 2016), which gives boxes, and U-Net (Ronneberger et al., 2015), which gives masks, can take over when three things are in place: enough labelled images that cover real conditions (at pixel level for segmentation, which costs far more), compute hardware that can run them (the subject of UAT 462), and evaluation criteria set in advance. The evaluation methods of this module apply to any deep model unchanged: IoU at 0.5, precision and recall at a threshold chosen on the validation set, a tolerant metric for thin lines, and conversion of the false-alarm rate into a count per unit of work. The rule is to build the classical baseline first, so that you know what level a deep model must beat to be worth it. Training and tuning models is covered in modules 1–5 of this course.

Module lab

Lab: build a baseline and evaluate it with the right metrics

  1. Cut real images of concrete or a wall into at least 200 patches of 128 × 128 pixels, label them in two classes (crack, no crack), and split them into training, validation and test sets by source image, so that patches from one image never land in different sets.
  2. Extract colour, extreme darkness, elongation and LBP features, train a logistic regression, and report the accuracy against always answering “sound”, with the confusion table.
  3. Choose the probability threshold on the validation set so that false alarms per concrete panel stay under a stated limit, then report the test result and explain why it differs from the validation figure.
  4. Detect a repeated object in the scene (for example a stud, a weep hole or a sign) by template matching, report precision and recall at an IoU of 0.5, and test the effect of light and scale.
  5. Label the crack masks by hand on 5 images, run black-hat and shape filtering, and report the strict Dice with the metric that tolerates 2 pixels.
  6. Write your group’s decision table of 5 methods against 5 criteria and test at which weight the result flips.

Common mistakes

Watch out

  • Using accuracy on imbalanced data. A classifier that always answers “sound” scores 96% or more.
  • Choosing the threshold on the test set, which makes the reported result better than it really is.
  • Not converting the false-alarm rate into a count per concrete panel or per kilometre, so the user does not know how many items must be checked.
  • Using SQDIFF or any non-normalised matching method where the light changes.
  • Using a one-scale template on images from changing flight heights.
  • Using Otsu on the whole image for cracks under a graded light.
  • Judging the segmentation of thin lines by strict Dice alone. An error of one pixel then looks like a weak model.

Summary

  • Choose the technique from the output the task needs first (a label per patch, a box or a mask), then score with weights and test the sensitivity to the weights.
  • With imbalanced data accuracy misleads. Look at precision and recall, choose the threshold on a validation set with real proportions, and convert to false alarms per concrete panel.
  • Normalised template matching tolerates changes of light but not of scale; search over several scales and set the threshold from the real objects.
  • Black-hat followed by shape filtering segments cracks better than Otsu under graded light, and thin lines must be evaluated with a tolerant metric.
  • Build the classical baseline before moving to a deep model, and use the same evaluation criteria for both.

Self-check questions

  1. A test set holds 4,000 normal patches and 80 patches with a crack. What accuracy does a classifier that always answers “normal” get, and what is its crack recall?
  2. A false-alarm rate of 0.15% per patch and 10,935 patches per concrete panel. How many false alarms per concrete panel?
  3. A detected box is x = 100, y = 50, width 17, height 17. The true box is x = 104, y = 50, width 17, height 17. Compute the IoU and say whether it counts as a TP at 0.5.
  4. Why does TM_CCOEFF_NORMED give the same score when the image is changed to , while TM_SQDIFF does not?
  5. A decision table has weights 0.3, 0.3, 0.2, 0.1, 0.1. Method A scores 4, 3, 5, 2, 4 and method B scores 2, 5, 3, 4, 2. Which wins, and with what total?
Answers
  1. The accuracy is and the crack recall is 0%, because it finds no cracks at all.
  2. , about 16 false alarms per concrete panel.
  3. The overlap is wide and 17 high, an area of . The union is , so the IoU is . That is not below 0.5, so it counts as a TP.
  4. The formula subtracts the mean and divides by the standard deviation of both the image patch and the template, so multiplying by 0.6 and adding 20 cancels out. SQDIFF sums the differences of brightness directly, so its value changes with the light.
  5. Method A . Method B . Method A wins.

Key formulas

IoU of two boxes
Precision and recall
Dice coefficient
Weighted score of a method

Key references

  1. Szeliski, R. (2022). Computer vision: Algorithms and applications (2nd ed.). Springer. link
  2. OpenCV. OpenCV documentation. link
  3. OpenCV. Template matching. OpenCV 4.x Python tutorials. link
  4. OpenCV. Morphological transformations. OpenCV 4.x Python tutorials. link
  5. Ojala, T., Pietikäinen, M., & Mäenpää, T. (2002). Multiresolution gray-scale and rotation invariant texture classification with local binary patterns. IEEE Transactions on Pattern Analysis and Machine Intelligence, 24(7), 971–987. link
  6. Pedregosa, F., et al. (2011). Scikit-learn: Machine learning in Python. Journal of Machine Learning Research, 12, 2825–2830. link
  7. scikit-learn developers. Metrics and scoring: Quantifying the quality of predictions (scikit-learn 1.9). link
  8. Saito, T., & Rehmsmeier, M. (2015). The precision-recall plot is more informative than the ROC plot when evaluating binary classifiers on imbalanced datasets. PLOS ONE, 10(3), e0118432. link
  9. Dorafshan, S., Thomas, R. J., & Maguire, M. (2018). SDNET2018: An annotated image dataset for non-contact concrete crack detection using deep convolutional neural networks. Data in Brief, 21, 1664–1668. link
  10. Dorafshan, S., Thomas, R. J., & Maguire, M. (2018). Comparison of deep convolutional neural networks and edge detectors for image-based crack detection in concrete. Construction and Building Materials, 186, 1031–1045. link
  11. Lee, S. B., Lee, D. H., & Kim, J. (2026). An exploratory study on imaging resolution, operational parameters, and measurement uncertainty in UAV-based crack inspection. Sensors, 26(3), 1031. link
  12. Redmon, J., Divvala, S., Girshick, R., & Farhadi, A. (2016). You only look once: Unified, real-time object detection. In Proceedings of CVPR 2016 (pp. 779–788). link
  13. Ronneberger, O., Fischer, P., & Brox, T. (2015). U-Net: Convolutional networks for biomedical image segmentation. In Medical Image Computing and Computer-Assisted Intervention (MICCAI 2015) (Lecture Notes in Computer Science, pp. 234-241). Springer. https://doi.org/10.1007/978-3-319-24574-4_28 link

Further reading

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

In class / field

Lab or field practice from worksheets with a safety checklist

Learning evidence: Checked worksheets and quiz results

Module quiz

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

Knowledge domain: Artificial intelligence and computer vision