The Problem: Manual Inspection Does Not Scale
Every year, tens of thousands of bridges, retaining walls, tunnel linings, and building facades must be inspected for surface defects. The most common defect — and often the first visible sign of structural distress — is cracking. Hairline cracks in concrete may indicate shrinkage, thermal cycling, or the early stages of reinforcement corrosion. Wider cracks may signal overloading, settlement, or seismic damage.
Traditional inspection relies on trained engineers physically examining every surface, photographing defects, and manually logging their location, width, and severity. This process is slow, expensive, subjective, and dangerous when it involves rope access, scaffolding, or under-bridge inspection vehicles.
The goal of this case study is to build an automated crack detection system powered by a convolutional neural network. Given a photograph of a concrete surface, the model will classify it as either Crack or No Crack with high confidence. This is a binary image classification task — the simplest and most well-understood form of computer vision, yet one with enormous practical impact.
Why Automate Crack Detection?
- Scale — A single drone survey of a highway bridge can produce thousands of high-resolution images. No inspector can manually review every patch of every image at pixel-level detail. A CNN can process hundreds of images per second.
- Consistency — Human inspectors disagree on crack classification approximately 15–30% of the time, depending on crack width and lighting conditions. A trained CNN applies the same criteria to every image, eliminating inter-observer variability.
- Speed — What takes a team of engineers days can be processed by a CNN in minutes, enabling rapid post-disaster assessment when time is critical.
- Safety — Reducing the need for inspectors to access dangerous locations (bridge undersides, dam faces, high-rise facades) by processing drone-captured imagery remotely.
- Record keeping — Automated systems generate structured, time-stamped defect databases that enable longitudinal tracking of crack propagation across inspection cycles.
Automated crack detection is to structural inspection what GPS total stations are to surveying. Both technologies replace a slow, manual, skill-dependent process with a faster, more consistent, and more scalable digital workflow — not eliminating the engineer, but freeing them from tedious repetitive tasks so they can focus on interpretation and decision-making.
Project Pipeline Overview
This case study walks through the complete machine learning pipeline for building a crack detection system. The table below summarises each stage:
| Stage | Task | Key Decisions |
|---|---|---|
| 1. Data | Acquire and explore dataset | Source, class balance, image quality |
| 2. Preparation | Resize, augment, split | Input size, augmentation strategy |
| 3. Architecture | Select and configure CNN | Transfer learning vs custom |
| 4. Training | Fit model to training data | LR schedule, early stopping, epochs |
| 5. Evaluation | Measure performance | Confusion matrix, precision, recall, AUC |
| 6. Interpretation | Validate model reasoning | Grad-CAM heatmaps |
| 7. Deployment | Run on inspection hardware | Edge device, inference speed, ONNX |
The Dataset: Concrete Crack Images
The foundation of any supervised learning project is a high-quality labelled dataset. For crack detection, two publicly available benchmarks are widely used in the civil engineering AI literature:
SDNET2018 — Structural Defects Network Dataset
Created by Utah State University, SDNET2018 contains over 56,000 images (256 × 256 pixels) of cracked and uncracked concrete surfaces from bridges, pavements, and walls. Each image is labelled as either Crack or No Crack. The dataset is challenging because it includes images with stains, rough textures, joints, and surface variations that can confuse a model into false positive detections.
Concrete Crack Images for Classification (CCIC)
This dataset comprises 40,000 images (227 × 227 pixels) equally split into 20,000 cracked and 20,000 uncracked samples. The images were collected from various concrete structures and manually verified. Its balanced class distribution makes it an excellent starting point for binary classification.
For this case study, we will use the Concrete Crack Images for Classification (CCIC) dataset due to its clean labelling, perfect class balance, and widespread adoption in benchmarking studies. The dataset requires no additional cleaning — a luxury rarely found in real-world projects.
Sample Images: What the Model Sees
The Crack class contains images with visible surface cracks of varying widths — from hairline cracks barely visible to the naked eye to wide structural cracks several millimetres across. Cracks appear as dark, roughly linear features against the lighter concrete background.
The No Crack class includes images of intact concrete surfaces. Critically, many of these contain challenging features that could be confused with cracks: expansion joints, surface scratches, staining patterns, form lines from construction, aggregate shadows, and water marks. These “hard negatives” force the model to learn the true visual signature of structural cracking rather than simply detecting any dark linear feature.
A balanced dataset is like a well-designed experiment. In geotechnical testing, you would not run 100 tests on clay and only 2 on sand and then claim your model applies to all soils. Similarly, a crack detector trained on 95% uncracked images and 5% cracked images would learn to always predict “no crack” and still achieve 95% accuracy — a useless model. Balanced datasets ensure the model learns both classes equally.
Class Balance Matters
The CCIC dataset is perfectly balanced (50/50). In real-world deployments, however, the vast majority of concrete surface patches will not contain cracks — typical ratios might be 98% no-crack to 2% crack. This imbalance requires careful handling during training:
- Weighted loss function — assign higher penalty to misclassifying the minority (crack) class.
- Oversampling — duplicate or augment crack images to balance the training batches.
- Undersampling — reduce the no-crack images to match the crack count (risks losing useful variation).
- Focal loss — a modified loss function that down-weights easy examples and focuses training on hard, misclassified samples.
Data Preparation
Raw images rarely go directly into a neural network. A series of preprocessing steps transforms the data into a form suitable for training. Each decision affects model performance, training speed, and generalisation.
Step 1: Resizing
The original images are 227 × 227 pixels. For transfer learning with ResNet-18, the standard input size is 224 × 224. We resize all images to this dimension. The 3-pixel difference is negligible and avoids any architecture mismatch.
Step 2: Data Augmentation
Data augmentation artificially expands the training set by applying random transformations to each image during training. This forces the model to learn features that are invariant to orientation, lighting, and scale — all of which vary enormously in real inspection imagery.
Augmentation Pipeline
- Random horizontal flip — cracks have no preferred left-right orientation. Probability: 50%.
- Random vertical flip — drone images can be captured from any angle. Probability: 50%.
- Random rotation (0–30 degrees) — cracks can run at any angle across the surface.
- Colour jitter — randomly adjust brightness (±20%), contrast (±20%), and saturation (±10%) to simulate varying lighting conditions.
- Random resized crop — crop a random 80–100% region and resize back to 224 × 224, simulating scale variation.
Notice that the validation transform does not include random augmentations. We only resize and normalise, because we want evaluation to be deterministic and reproducible.
Step 3: Train / Validation / Test Split
We partition the 40,000 images into three disjoint subsets:
| Subset | Size | Percentage | Purpose |
|---|---|---|---|
| Training | 28,000 | 70% | Learn weights via backpropagation |
| Validation | 6,000 | 15% | Tune hyperparameters, monitor overfitting |
| Test | 6,000 | 15% | Final, unbiased performance estimate |
The split is stratified — each subset maintains the 50/50 class ratio. The test set is never used during training or hyperparameter tuning. It is opened only once, at the very end, to report final performance. This discipline prevents optimistic bias.
Data Leakage Warning
If the same concrete surface appears in both training and test sets (e.g., overlapping drone image crops from the same wall), the model may memorise specific textures rather than learning general crack features. Always split by structure or inspection session, not by individual image, when working with real-world data.
Architecture: Transfer Learning vs Custom CNN
The most critical design decision is whether to train a CNN from scratch or leverage transfer learning — using a model pre-trained on millions of images from ImageNet and fine-tuning it on our crack dataset. Both approaches have trade-offs.
ResNet-18 (Transfer Learning)
- Pre-trained on 1.2M ImageNet images
- Already knows edges, textures, shapes
- Only need to retrain the final FC layer
- Fast convergence (5–15 epochs)
- 11.7M parameters total, 512 retrained
- Strong performance even with small datasets
Custom Lightweight CNN
- Designed from scratch for this task
- Smaller model (fewer parameters)
- Needs more data and longer training
- Full control over architecture
- May underperform without sufficient data
- Better for highly specialised domains
We choose ResNet-18 with transfer learning. The reasoning is straightforward: ImageNet pre-training teaches the early convolutional layers to detect edges, gradients, and textures — exactly the low-level features that distinguish cracks from intact concrete. We freeze these early layers and only retrain the final fully connected layer to output two classes (crack / no crack).
ResNet-18 Architecture Summary
ResNet-18 consists of an initial 7×7 convolution, followed by 4 residual blocks (each containing two 3×3 convolutions with skip connections), a global average pooling layer, and a final fully connected layer. The skip connections solve the vanishing gradient problem, enabling deeper networks to train effectively.
For our binary classification task, we replace the original 1000-class output layer with a single fully connected layer mapping 512 features to 2 output neurons (or 1 neuron with sigmoid activation).
By unfreezing layer4 (the deepest residual block), we allow
the model to adapt its high-level feature representations to crack-specific
patterns while keeping the lower layers (edge detectors, texture detectors)
frozen at their ImageNet-learned weights.
Training the Model
Training a CNN involves feeding batches of images through the network, computing the loss (how wrong the predictions are), and updating the weights via backpropagation. The hyperparameters governing this process significantly affect final performance.
Hyperparameter Configuration
| Hyperparameter | Value | Rationale |
|---|---|---|
| Optimiser | Adam | Adaptive learning rate, fast convergence |
| Initial learning rate | 1e-4 | Small LR for fine-tuning (avoid destroying pre-trained weights) |
| Batch size | 32 | Good balance of speed and gradient stability |
| Loss function | CrossEntropyLoss | Standard for multi-class (2-class) classification |
| Epochs | 25 (max) | With early stopping, typically converges in 8–12 |
| Weight decay | 1e-4 | L2 regularisation to prevent overfitting |
| Dropout | 0.3 | Applied before the final FC layer |
Learning Rate Scheduling
A constant learning rate rarely produces optimal results. We use ReduceLROnPlateau, which monitors the validation loss and reduces the learning rate by a factor of 0.1 when improvement stalls for 3 consecutive epochs. This allows the model to make large initial progress and then fine-tune with smaller updates as it approaches the optimum.
Early Stopping
Early stopping prevents overfitting by monitoring the validation loss and halting training when it stops improving. We use a patience of 5 epochs — if validation loss does not decrease for 5 consecutive epochs, training stops and the model weights from the best epoch are restored.
Why Early Stopping Matters for Safety-Critical Systems
An overfit crack detector memorises specific crack patterns from the training set rather than learning generalised features. It may achieve 99.5% accuracy on training data but drop to 85% on new images from a different bridge. In safety-critical applications, this gap between training and real-world performance can lead to missed cracks — a potentially catastrophic failure mode. Early stopping is your primary defence against this.
Training Loop Summary
- For each epoch, iterate over all training batches. For each batch: forward pass, compute loss, backward pass, update weights.
-
After each epoch, evaluate on the validation set.
Record validation loss and accuracy. No gradient computation during
validation (use
torch.no_grad()). - Update the learning rate scheduler with the validation loss. If the loss has plateaued, the learning rate is reduced.
- Check early stopping. If validation loss has improved, save the model checkpoint. If not improved for 5 epochs, stop training.
- After training, load the best checkpoint and evaluate on the held-out test set exactly once.
Evaluation: Measuring What Matters
Accuracy alone is insufficient for evaluating a crack detection system. In safety-critical applications, we care deeply about which errors the model makes. Missing a crack (false negative) is far more dangerous than flagging intact concrete as cracked (false positive). This asymmetry demands a nuanced evaluation framework.
The Confusion Matrix
A confusion matrix breaks down the model's predictions into four categories:
| Predicted: Crack | Predicted: No Crack | |
|---|---|---|
| Actual: Crack | True Positive (TP) | False Negative (FN) — DANGEROUS |
| Actual: No Crack | False Positive (FP) — costly | True Negative (TN) |
In structural inspection, a false negative (missed crack) could lead to an undetected defect progressing to structural failure. A false positive (false alarm) wastes inspection time but poses no safety risk. Therefore, we prioritise recall (sensitivity) for the crack class.
Key Metrics
Of all images predicted as “crack,” what fraction truly contain cracks?
Of all images that truly contain cracks, what fraction does the model detect? A recall of 0.99 means only 1 in 100 cracks is missed.
Harmonic mean of precision and recall. Balanced single-number summary.
ROC Curve and AUC
The Receiver Operating Characteristic (ROC) curve plots the True Positive Rate (recall) against the False Positive Rate at various classification thresholds. The Area Under the Curve (AUC) summarises performance across all thresholds in a single number between 0 and 1.
- AUC = 1.0 — perfect classifier
- AUC = 0.5 — random guessing (the diagonal line)
- AUC > 0.95 — typical target for crack detection
Typical Results for ResNet-18 on CCIC
Published studies using ResNet-18 with transfer learning on the Concrete Crack Images dataset report the following approximate performance on held-out test sets:
- Accuracy: 98.5–99.5%
- Precision (crack): 98.0–99.2%
- Recall (crack): 98.8–99.6%
- F1 Score: 98.5–99.4%
- AUC: 0.998–0.999
These numbers are achievable because the CCIC dataset is clean and well-separated. Real-world performance on novel structures will be lower, making robust evaluation even more important.
Threshold Tuning for Safety
The default classification threshold is 0.5: if the model outputs a crack probability above 0.5, it predicts “crack.” But for safety-critical applications, we can lower this threshold — say to 0.3 — to increase recall at the cost of more false positives. This is a deliberate engineering trade-off: better to inspect 10 extra patches of intact concrete than to miss one real crack.
Demo 1: Crack Detector Simulator
This interactive demo simulates an AI crack detection system. The canvas displays a grid of concrete surface patches. Click Inspect All to run the simulated CNN over each patch. The model assigns a crack probability and labels each patch as Crack or No Crack with a confidence score. Click New Surface to generate a fresh set of patches with different crack patterns.
Deployment: From Lab to Field
A model that achieves 99% accuracy on a test set is worthless if it cannot run in the field. Deployment is where engineering meets machine learning — the model must work within the constraints of real hardware, real power budgets, and real-time requirements.
Edge Deployment on Inspection Drones
The target deployment platform for this crack detector is an edge computing device mounted on an inspection drone. The device processes images from the drone's camera in real-time during flight, flagging cracked regions for the pilot to investigate or automatically geotagging defect locations for later review.
Drone-Mounted Processing
NVIDIA Jetson Nano or Xavier NX mounted on the drone payload. Processes frames at 10–30 FPS depending on model size. Results available during flight, enabling adaptive survey paths.
Edge Computing Box
Ruggedised edge device at the inspection site. Receives images via Wi-Fi from the drone. Runs inference on batches of images as they are captured. Results displayed on a field tablet.
Cloud Processing
Images uploaded post-flight to a cloud GPU server for batch inference. Highest throughput but requires internet connectivity and introduces latency. Best for non-time-critical inspections.
Mobile App
Lightweight model (MobileNetV2 or quantised ResNet) running directly on an engineer's smartphone. Point the camera at a surface and get instant crack classification. Useful for walkthrough inspections.
Inference Speed Considerations
| Platform | Model | Inference Time | FPS |
|---|---|---|---|
| NVIDIA Jetson Nano | ResNet-18 (FP16) | ~15 ms | ~65 |
| Jetson Xavier NX | ResNet-18 (FP16) | ~5 ms | ~200 |
| Raspberry Pi 4 | MobileNetV2 (INT8) | ~80 ms | ~12 |
| Smartphone (mid-range) | MobileNetV2 (FP16) | ~30 ms | ~33 |
| Cloud GPU (V100) | ResNet-18 (FP32) | ~2 ms | ~500 |
Model Optimisation for Edge
To achieve acceptable inference speed on edge devices, several optimisation techniques are applied:
- ONNX Export — Convert the PyTorch model to ONNX (Open Neural Network Exchange) format for cross-platform compatibility and runtime optimisation.
- TensorRT Optimisation — NVIDIA's TensorRT compiler fuses layers, optimises memory access, and applies kernel auto-tuning for the specific GPU architecture.
- Quantisation — Reduce weight precision from FP32 (32-bit floating point) to FP16 or INT8. This halves or quarters the model size and speeds up computation with minimal accuracy loss (typically less than 0.5% for crack detection).
- Pruning — Remove neurons and connections with near-zero weights. A pruned ResNet-18 can be 40–60% smaller with less than 1% accuracy loss.
Results Interpretation: Grad-CAM Validation
High accuracy numbers are necessary but not sufficient. We must verify that the model is making predictions for the right reasons. Grad-CAM (Gradient-weighted Class Activation Mapping) produces a heatmap showing which regions of the input image most influenced the model's prediction.
What Good Grad-CAM Results Look Like
For a correctly functioning crack detector, the Grad-CAM heatmap should show warm colours (red/orange) concentrated along the crack itself and cool colours (blue/transparent) on the surrounding intact concrete. This confirms that the model has learned to focus on the crack — not on irrelevant background features.
Red Flags in Grad-CAM Analysis
If Grad-CAM reveals any of the following patterns, the model has learned a spurious correlation rather than true crack features:
- Heatmap on image borders — the model may have learned that cracked images tend to have different border artifacts (e.g., from inconsistent cropping).
- Heatmap on shadows or stains — the model confuses dark shadow regions with cracks, a common failure when training data has correlated lighting conditions.
- Uniform heatmap — the model is not localising features at all; it may be relying on global statistics like average brightness.
- Heatmap on metadata text — some inspection images contain embedded timestamps or labels. The model may learn to read these instead of analysing the concrete surface.
Grad-CAM validation is like checking a structural model's deformed shape. A finite element analysis might report stress values that look reasonable, but if the deformed shape shows the building bending the wrong way, you know the boundary conditions are wrong. Similarly, a CNN might report 99% accuracy, but if Grad-CAM shows it looking at the wrong part of the image, you know the model has learned a shortcut rather than real structural features.
Demo 2: Live Confusion Matrix Builder
This demo simulates a model evaluating test images one at a time. Click Start Evaluation to watch simulated predictions accumulate in the confusion matrix. Observe how precision, recall, and F1 score update in real time as each prediction arrives. Use Adjust Threshold to see how lowering the classification threshold increases recall at the cost of more false positives.
Chapter 4 Recap: Computer Vision for Civil Engineers
This case study brings together every concept from Chapter 4 into a single, cohesive project. Let us trace the connections:
How It All Connects
- 4.1 Images as Data — Each concrete patch is a 224 × 224 × 3 tensor of normalised pixel values.
- 4.2 Convolution Operation — The convolutional layers in ResNet-18 slide learned filters across the image to detect edges, textures, and patterns.
- 4.3 Pooling & Stride — Max pooling in ResNet progressively reduces spatial dimensions while preserving dominant features like crack edges.
- 4.4 CNN Architecture — ResNet-18's four residual blocks form the backbone, with skip connections enabling gradient flow through 18 layers.
- 4.5 Transfer Learning — ImageNet pre-training gives us powerful feature extractors. We only retrain the classifier head for crack vs no-crack.
- 4.6 Data Augmentation — Flips, rotations, and colour jitter expand our effective dataset and improve generalisation to unseen structures.
- 4.7 Object Detection — Beyond classification, the next step would be localising cracks with bounding boxes using architectures like YOLO or Faster R-CNN.
- 4.8 Semantic Segmentation — For precise crack delineation, pixel-wise segmentation with U-Net can trace crack paths and measure their width.
- 4.9 Visualizing CNN Internals — Grad-CAM validates that our model focuses on the crack itself, not on spurious features.
Key Lessons from This Case Study
- Transfer learning is powerful — a pre-trained ResNet-18, fine-tuned with 28,000 crack images, achieves over 99% accuracy in as few as 10 epochs. Building this from scratch would require far more data and compute.
- Evaluation must match the application — for safety-critical crack detection, recall is more important than precision. A missed crack is more dangerous than a false alarm.
- Interpretability builds trust — Grad-CAM heatmaps allow engineers to verify that the model's reasoning aligns with physical reality. This is essential for gaining acceptance in a profession built on rigorous verification.
- Deployment is engineering, not just data science — converting a PyTorch model to ONNX, quantising weights, and optimising for edge hardware requires systems-level thinking that civil engineers are well-equipped to learn.
- The pipeline is the product — no single component (data, model, evaluation, deployment) works in isolation. The value lies in the complete, validated, deployed system.
What Comes Next
Chapter 4 has equipped you with the visual AI toolkit: from pixels to classification, from convolutions to deployment. In Chapter 5: LLMs & Transformers, we shift from image data to text data, exploring how the Transformer architecture powers large language models — and how these models are beginning to transform civil engineering through automated report generation, specification analysis, and conversational AI assistants for design and construction.
Advanced Application: End-to-End Crack Detection Pipeline
A production crack detection system combines everything from this chapter into a deployable pipeline:
Complete Pipeline
Each step uses concepts from different sub-chapters: images as data (4.1), convolution for edges (4.2), pooling for efficiency (4.3), architecture design (4.4), training strategy (4.5), and segmentation for area computation (4.8). This is why civil engineers who understand CNNs end-to-end are invaluable.
Test Your Knowledge
Four questions covering the end-to-end crack detection pipeline. Test your understanding of dataset preparation, evaluation metrics, model interpretation, and deployment considerations.
Q1: Why is recall more important than precision for a crack detection system deployed on highway bridges?
Q2: A Grad-CAM heatmap for a crack image shows warm colours concentrated on the image border rather than the crack itself. What does this indicate?
Q3: When using transfer learning with ResNet-18 for crack detection, which layers are typically frozen and which are retrained?
Q4: What is the primary purpose of quantising a crack detection model from FP32 to INT8 before edge deployment?
Key Takeaways
What You Should Remember
- Automated crack detection replaces slow, subjective manual inspection with a fast, consistent, scalable CNN-based system.
- A balanced, well-labelled dataset (like CCIC with 40,000 images) is the foundation. Data quality matters more than model complexity.
- Transfer learning with ResNet-18 achieves over 99% accuracy with minimal training time by leveraging ImageNet-learned features.
- Data augmentation (flips, rotations, colour jitter) is essential for generalisation to unseen structures and lighting conditions.
- In safety-critical systems, recall is king — missing a crack is far worse than a false alarm. Tune your threshold accordingly.
- Grad-CAM validation confirms the model focuses on actual cracks, not spurious features. Never deploy without interpretability checks.
- Edge deployment requires model optimisation (ONNX, TensorRT, quantisation) to achieve real-time inference on drone-mounted hardware.
- The complete pipeline — data, preparation, architecture, training, evaluation, interpretation, deployment — is the deliverable, not just the model.