From Classification to Detection
In the previous sub-chapters you built CNNs that accept an image and return a single label: "cracked" or "intact." That is image classification. But a bridge inspector does not just say "this photo has a crack" — she points to the exact region, circles it, and writes its dimensions. Object detection teaches a neural network to do the same: predict what objects are present and draw a tight bounding box around each one.
The jump from classification to detection is one of the most important leaps in applied computer vision. It transforms AI from a passive labelling tool into an active spatial reasoning engine — one that can count cracks, measure their extent, flag un-helmeted workers, and locate exposed rebar in a single forward pass of the network.
The Four Levels of Visual Understanding
Computer vision researchers organise visual tasks along a spectrum of spatial granularity. Each level builds on the one before it:
- Image Classification — assign one label to the entire image. "This image contains a crack." No spatial information.
- Object Localization — classify the image and draw a single bounding box around the primary object. One object per image.
- Object Detection — find all objects in the image, classify each, and draw a bounding box around each one. Multiple objects, multiple classes.
- Instance Segmentation — detection plus pixel-level masks. Instead of a rectangle, every pixel belonging to each object is labelled. Useful for measuring crack width or area of spalling with sub-pixel accuracy.
Think of a bridge inspection report. Classification is a summary sentence: "Defects found." Localization is a single arrow on a photo pointing to the worst defect. Detection is a marked-up photo with every defect circled, labelled, and numbered. Instance segmentation is a CAD overlay where every defect region is traced as a polygon with area measurements. Each level adds spatial precision but also computational cost.
This sub-chapter focuses squarely on Object Detection — level 3. We will touch on instance segmentation briefly at the end, and the next sub-chapter (4.8) covers semantic segmentation in full detail.
Bounding Boxes and Anchor Boxes
A bounding box is the simplest way to localise an object: an axis-aligned rectangle defined by four numbers. The two most common representations are:
Box Representations
(xmin, ymin, xmax,
ymax) — top-left and bottom-right
corners. Intuitive for computing overlaps.
(xc, yc, w, h) —
centre coordinates plus width and height. Preferred by YOLO and
many modern detectors because the network predicts offsets from
a reference point.
What Are Anchor Boxes?
Early detection approaches used a brute-force sliding window: evaluate the classifier at every position and scale across the image. This was enormously expensive. Modern detectors replace the sliding window with anchor boxes (also called prior boxes or default boxes): a predefined set of reference rectangles placed at regular grid positions on the feature map.
Each anchor has a fixed aspect ratio and scale. The network does not predict bounding boxes from scratch; instead, it predicts small offsets (deltas) from the nearest anchor. This makes the regression problem much easier because the network only needs to learn small corrections rather than absolute coordinates.
Faster R-CNN uses 9 anchors per grid cell (3 scales × 3 aspect ratios). YOLO v2 uses 5 anchors determined by k-means clustering on the training set bounding boxes. SSD uses 4–6 anchors per feature-map level. More anchors increase recall but also increase the number of proposals the network must evaluate.
For civil engineering data, anchor design matters. Cracks are long and thin (high aspect ratio), spalling regions are roughly square, and rebar exposure patches are often small and narrow. Tuning anchor ratios to match your defect geometry improves detection accuracy significantly.
Intersection over Union (IoU)
Intersection over Union (IoU), also called the Jaccard index, is the single most important metric in object detection. It measures how well a predicted bounding box aligns with the ground-truth box.
IoU ranges from 0 (no overlap) to 1 (perfect overlap). In practice:
- IoU ≥ 0.50 — considered a correct detection in the PASCAL VOC benchmark (the traditional threshold).
- IoU ≥ 0.75 — a "strict" match. The COCO benchmark averages over IoU thresholds from 0.50 to 0.95 in steps of 0.05.
- IoU < 0.50 — the prediction is considered a false positive.
Imagine you are verifying a surveyor's measurement of a defect area. You overlay the surveyor's polygon on the true defect outline. IoU is the ratio of the overlapping area to the total area covered by either outline. A value of 0.85 means the surveyor captured 85% of the defect with very little wasted area — excellent agreement.
Computing IoU Step by Step
-
Compute the coordinates of the intersection rectangle:
x1 = max(A.x_min, B.x_min),y1 = max(A.y_min, B.y_min),x2 = min(A.x_max, B.x_max),y2 = min(A.y_max, B.y_max). -
If
x2 < x1ory2 < y1, the boxes do not overlap and IoU = 0. -
Intersection area =
(x2 - x1) × (y2 - y1). - Union area = Area(A) + Area(B) − Intersection.
- IoU = Intersection / Union.
Interactive Demo: IoU Calculator
Drag the two bounding boxes below to see how IoU changes in real time. The teal box represents the ground truth and the amber box represents a model prediction. Try to maximise the IoU by aligning them, then pull them apart to see how quickly IoU drops.
Non-Maximum Suppression (NMS)
A detector with thousands of anchor boxes will produce many overlapping predictions for the same object. Non-Maximum Suppression (NMS) is the post-processing step that eliminates redundant boxes and keeps only the best one per object.
The NMS Algorithm
- Sort all predicted boxes by their confidence score in descending order.
- Select the box with the highest confidence. Add it to the final output list.
- Compare this box against every remaining box. Remove any box whose IoU with the selected box exceeds a threshold (commonly 0.45–0.50).
- Repeat steps 2–3 on the remaining boxes until none are left.
Tuning the IoU Threshold
A low threshold (e.g., 0.3) aggressively removes duplicates but risks suppressing detections of nearby objects (e.g., two cracks running close together). A high threshold (e.g., 0.7) keeps more boxes but may leave duplicates. For civil engineering inspection where defects can cluster, a moderate value around 0.45 works well, with class-wise tuning for crowded scenes.
Instead of hard-removing overlapping boxes, Soft-NMS decays the confidence score of overlapping boxes using a Gaussian or linear function of their IoU with the top box. This preserves detections of nearby objects that share substantial overlap — useful when detecting multiple closely-spaced cracks or spalling patches on a concrete surface.
Interactive Demo: NMS Visualizer
Below you see a set of overlapping detection boxes, each with a confidence score. Press Run NMS to watch the algorithm iteratively remove redundant boxes. Adjust the IoU threshold to see how it affects the final set of detections.
Two-Stage Detectors
Two-stage detectors split the detection problem into two sequential steps: first propose regions that might contain an object, then classify and refine each region. This family dominated the field from 2014 to 2016 and still delivers state-of-the-art accuracy on many benchmarks.
R-CNN (2014)
Region-Based CNN
The original R-CNN used Selective Search to extract ~2,000 region proposals from an image. Each proposal was warped to a fixed size, fed through a CNN (AlexNet) to extract features, and then classified by an SVM. Bounding-box regression refined the coordinates. R-CNN achieved a dramatic jump in accuracy on PASCAL VOC but was extremely slow: each image required ~2,000 forward passes through the CNN.
Fast R-CNN (2015)
Ross Girshick's Fast R-CNN eliminated the bottleneck by running the CNN only once on the entire image to produce a shared feature map. Region proposals (still from Selective Search) were then projected onto this feature map, and a small RoI (Region of Interest) pooling layer extracted fixed-size feature vectors for each proposal. A single network head performed both classification and box regression. Training was end-to-end and inference was ~10× faster than R-CNN.
Faster R-CNN (2015)
Region Proposal Network (RPN)
Faster R-CNN replaced the external Selective Search with a lightweight neural network — the Region Proposal Network — that shares convolutional features with the detection head. The RPN slides a small window over the feature map and, at each position, predicts whether each anchor box contains an object (objectness score) and refines the anchor coordinates. This made proposal generation nearly cost-free and enabled real-time two-stage detection (~5 FPS on a GPU).
| Detector | Proposals | CNN Passes | Speed | mAP (VOC 2007) |
|---|---|---|---|---|
| R-CNN | Selective Search | ~2,000 | ~49 s/img | 58.5 |
| Fast R-CNN | Selective Search | 1 | ~2.3 s/img | 70.0 |
| Faster R-CNN | RPN (learned) | 1 | ~0.2 s/img | 73.2 |
Notice how each iteration kept the same two-stage philosophy but eliminated a bottleneck, yielding enormous speed gains without sacrificing accuracy. Faster R-CNN remains a popular baseline for civil engineering inspection tasks where accuracy matters more than real-time speed.
One-Stage Detectors
One-stage (or single-shot) detectors eliminate the proposal step entirely. They divide the image into a grid and predict bounding boxes and class probabilities directly from each grid cell in a single forward pass. The result: dramatically faster inference at the cost of some accuracy (though the gap has narrowed considerably).
YOLO — You Only Look Once (2016)
The YOLO Philosophy
Joseph Redmon's YOLO reframed detection as a single regression problem. The image is divided into an S × S grid. Each cell predicts B bounding boxes (each with a confidence score) and C class probabilities. At test time, all predictions are generated in one pass, making YOLO extraordinarily fast — the original version ran at 45 FPS and the "Fast YOLO" variant at 155 FPS.
Subsequent versions — YOLOv2 (YOLO9000), YOLOv3, YOLOv4, YOLOv5, YOLOv7, YOLOv8 — progressively added anchor boxes, multi-scale feature pyramids, better backbones, and advanced augmentation. Today YOLOv8 (by Ultralytics) is one of the most widely deployed detectors in civil engineering research, powering drone-based crack detection, PPE compliance monitoring, and structural damage surveys.
SSD — Single Shot MultiBox Detector (2016)
Multi-Scale Feature Maps
SSD improved on YOLO by making predictions from multiple feature maps at different resolutions. Early (large) feature maps detect small objects; later (small) feature maps detect large objects. Default (anchor) boxes of various aspect ratios are tiled across each feature map. This multi-scale approach substantially improved small-object detection — critical for spotting hairline cracks or small spalling patches.
Two-Stage vs One-Stage: Summary
| Aspect | Two-Stage | One-Stage |
|---|---|---|
| Pipeline | Propose then classify | Detect in one pass |
| Speed | Moderate (~5–15 FPS) | Fast (~30–155+ FPS) |
| Accuracy | Generally higher mAP | Competitive, slightly lower |
| Small Objects | Strong (RoI pooling) | SSD/YOLOv3+ improved |
| Use Case | Lab analysis, archival | Real-time / edge / drone |
| Example | Faster R-CNN, Cascade R-CNN | YOLOv8, SSD, RetinaNet |
If you are inspecting high-resolution drone imagery offline and accuracy is paramount, Faster R-CNN (or its successor Cascade R-CNN) is an excellent choice. If you need real-time detection on a construction site — for example, monitoring PPE compliance via a CCTV feed — YOLOv8 running on an edge GPU provides the best speed-accuracy trade-off.
The mAP Metric
Mean Average Precision (mAP) is the standard metric for evaluating object detectors. Understanding it requires a quick review of precision, recall, and the precision-recall curve.
Precision and Recall
A detection is a True Positive (TP) if its IoU with a ground-truth box exceeds the threshold (e.g., 0.50). Otherwise it is a False Positive (FP). A ground-truth box that no prediction matches is a False Negative (FN).
From PR Curve to AP
For each class, sort all predictions by confidence, compute precision and recall at each rank, plot the precision-recall curve, and compute the area under it. This area is the Average Precision (AP) for that class. The mAP is the mean AP across all classes.
Common mAP Variants
[email protected] (PASCAL VOC style): IoU threshold = 0.50.
Lenient; reports higher numbers.
[email protected]: strict IoU threshold.
mAP@[.50:.95] (COCO style): average mAP across
IoU thresholds 0.50, 0.55, …, 0.95. The gold-standard
metric that rewards both detection and precise localisation.
Think of mAP as a comprehensive quality rating for a surveying instrument. Precision is like the instrument not reporting false measurements (every measurement it gives is real). Recall is like the instrument not missing any real features (it finds every crack that exists). mAP combines both into one number — a surveying instrument with [email protected] of 0.92 finds 92% of defects with very few false alarms.
Civil Engineering Applications
Object detection has rapidly moved from the research lab to the job site. Below are four high-impact applications where detectors trained on domain-specific data are transforming civil engineering practice.
Crack Detection
YOLOv8 models trained on annotated bridge-deck images can locate cracks as narrow as 0.1 mm from drone photographs. Detectors draw bounding boxes around each crack, enabling automatic severity classification and length estimation. Typical reported [email protected] values range from 0.82 to 0.94 on concrete surfaces.
Spalling Detection
Concrete spalling — where chunks of cover concrete break away — is detected using Faster R-CNN or SSD. Multi-scale anchors are critical because spalling regions vary from centimetre-scale chips to metre-scale delaminations. Instance segmentation (Mask R-CNN) can additionally estimate the area of each spall.
Rebar Exposure
When the protective concrete cover erodes, reinforcing steel becomes visible. Detecting exposed rebar is a high-priority structural safety task. Detectors are trained to distinguish rebar from similar linear features (conduit, shadow lines) using colour and texture cues in the CNN features.
Safety Equipment (PPE)
Real-time YOLO-based systems on construction sites detect hard hats, high-visibility vests, safety goggles, and harnesses on workers. Non-compliance triggers an alert. These systems run on edge GPUs attached to CCTV cameras and must sustain ≥ 25 FPS to track moving workers.
Civil engineering detection datasets are far smaller than ImageNet or COCO. A bridge inspection dataset may contain only 500–2,000 annotated images. To compensate, practitioners rely heavily on transfer learning (fine-tuning a COCO-pretrained backbone), data augmentation (random crops, flips, colour jitter), and synthetic data (rendering cracks on 3-D concrete models) to boost effective training set size.
A Glimpse at Instance Segmentation
Instance segmentation takes detection one step further: instead of a bounding box, the model predicts a pixel-level mask for each detected object. The landmark architecture here is Mask R-CNN, which extends Faster R-CNN by adding a small fully convolutional branch that outputs a binary mask for each Region of Interest.
Mask R-CNN in Brief
Mask R-CNN replaces RoI Pooling with RoI Align, which uses bilinear interpolation instead of quantisation to preserve spatial precision. A parallel mask head — a small FCN — predicts a 28 × 28 binary mask per RoI. The mask, classification, and box regression heads are trained jointly. This architecture achieves strong results on defect area estimation tasks where bounding boxes are too coarse.
Instance segmentation is especially valuable in civil engineering when you need to measure defects, not just locate them. Accurately tracing the outline of a spalling region lets you compute area, perimeter, and depth (if combined with depth imagery), feeding directly into structural assessment models. We will explore semantic segmentation architectures (U-Net, DeepLab) in the next sub-chapter.
Civil Engineering Application: Detecting Defects in Infrastructure
Object detection goes beyond classification — it tells you where each defect is and what type it is, enabling quantitative damage assessment:
Multi-Defect Detection
YOLO or Faster R-CNN trained on bridge inspection images can simultaneously detect: cracks (IoU≥0.5), spalling (IoU≥0.5), exposed rebar (IoU≥0.4), and efflorescence — all in a single forward pass. A human inspector takes 4 hours per bridge span; the CNN does it in seconds from drone footage.
Damage Localization for Repair
Bounding boxes give repair crews exact coordinates. Example: "Spalling detected at beam B3, span 4, coordinates (1240, 890) to (1450, 1100) in image reference frame." Combined with photogrammetry, this maps to physical locations within ±5cm accuracy.
Construction Site Safety
Object detection monitors PPE compliance: hard hats, safety vests, harnesses. YOLOv5 trained on construction datasets achieves 92% mAP for detecting workers without helmets. Real-time alerts reduce safety incidents by 35% on monitored sites.
Knowledge Check
What does IoU measure in the context of object detection?
What is the primary advantage of one-stage detectors like YOLO over two-stage detectors like Faster R-CNN?
In the context of Non-Maximum Suppression, what happens when the IoU threshold is set very low (e.g., 0.2)?
What key innovation did Faster R-CNN introduce compared to Fast R-CNN?
Chapter Summary
Key Takeaways
- Object detection adds spatial localisation to classification: the model predicts what and where for every object in the image.
- Anchor boxes provide reference rectangles that the network refines via small offsets, making regression easier.
- IoU (Intersection over Union) measures overlap between predicted and ground-truth boxes; it is the foundation of mAP evaluation and NMS.
- Non-Maximum Suppression filters redundant detections by iteratively keeping the highest-confidence box and removing highly-overlapping alternatives.
- Two-stage detectors (R-CNN, Fast R-CNN, Faster R-CNN) propose regions first, then classify — high accuracy, moderate speed.
- One-stage detectors (YOLO, SSD) predict boxes and classes in a single pass — real-time speed, competitive accuracy.
- mAP averages per-class precision-recall areas across IoU thresholds; mAP@[.50:.95] is the gold standard.
- Civil engineering applications include crack detection, spalling, rebar exposure, and PPE compliance — all benefit from transfer learning and domain-specific anchor tuning.