From Raw Numbers to Meaningful Features
In Sub-chapter 4.1 you learned that every digital image is a rectangular grid of numbers. A 640×480 grayscale photo of a concrete surface is 307,200 numbers. A crack running across that surface is not labelled anywhere in those numbers — it is just a narrow band of darker values surrounded by lighter ones.
How does a neural network find that crack? It cannot examine the entire image at once the way you do. Instead, it uses a brilliantly simple trick: a tiny sliding window — called a kernel or filter — that scans across the image, one small patch at a time, performing the same arithmetic at every position. This operation is called convolution, and it is the single most important building block of convolutional neural networks.
Convolution is not unique to deep learning. Signal processing engineers have used convolution for decades to blur, sharpen, and detect edges in images. What CNNs added was the ability to learn the optimal kernel values from data, rather than requiring a human to hand-craft them. But the underlying mathematics is exactly the same.
In this sub-chapter we will build the convolution operation from first principles. We will walk through the sliding-window mechanics step by step, understand padding and stride, explore classic hand-crafted kernels (edge detection, blur, sharpen), and see how CNNs learn their own kernels. Along the way, two interactive demos will let you watch convolution happen in real time and experiment with different filters on simulated structural images.
This sub-chapter builds directly on Sub-chapter 4.1: Images as Data. You should be comfortable with the idea of pixel grids, grayscale values (0–255), and the concept of an image as a 2D array of numbers. No calculus or linear algebra beyond basic multiplication and addition is needed.
What Is Convolution?
At its core, convolution is a mathematical operation that combines two arrays of numbers to produce a third. In the context of image processing, those two arrays are:
- The input image — a 2D grid of pixel values (e.g. a 5×5 grayscale patch).
- The kernel (filter) — a much smaller 2D grid of weights (typically 3×3 or 5×5).
The output is called a feature map (or activation map). Every value in the feature map is produced by placing the kernel on top of a region of the input, multiplying each overlapping pair of values, and summing the results. The kernel then slides one position to the right, and the process repeats. When it reaches the right edge, it drops down one row and starts again from the left.
Convolution is like a site inspector with a magnifying glass. Imagine you are inspecting a large concrete wall for hairline cracks. You hold a small magnifying glass (the kernel) and examine a small patch of the wall at a time. At each position you assess whether the pattern of light and dark under your magnifying glass matches a "crack-like" pattern. You then move the glass a small step to the right and repeat. When you reach the edge of the wall, you drop down one row and start again.
The result of your inspection is a map of the wall showing where crack- like patterns were detected — exactly analogous to the feature map produced by convolution. The magnifying glass never changes; it applies the same assessment criteria everywhere. This is called weight sharing, and it is one of the key reasons CNNs are so efficient.
The Step-by-Step Mechanics
Let us work through a concrete example. Suppose we have a 5×5 input image and a 3×3 kernel. Here is the procedure:
Convolution in Four Steps
- Place the kernel on the top-left corner of the input image so the 3×3 kernel overlaps the top-left 3×3 region of the image.
- Element-wise multiply: multiply each kernel weight by the corresponding pixel value beneath it. This gives 9 products (for a 3×3 kernel).
- Sum all products: add the 9 products together to get a single number. This number is written into the corresponding position of the output feature map.
- Slide the kernel one position to the right and repeat steps 1–3. When you reach the right edge, move down one row and start from the left again. Continue until every valid position has been processed.
With a 5×5 input and a 3×3 kernel (no padding, stride 1), the kernel can be placed in 3 horizontal positions and 3 vertical positions, producing a 3×3 output feature map. The general formula for the output size is:
Output Size Formula
output_size = (input_size − kernel_size) / stride + 1
For our example: (5 − 3) / 1 + 1 = 3. So a 5×5 input with a 3×3 kernel at stride 1 produces a 3×3 output.
A Worked Numerical Example
Consider the following 5×5 grayscale patch (perhaps from a concrete surface photograph) and a 3×3 edge-detection kernel:
Numerical Walkthrough
Input patch (5×5):
120 130 125 128 132 122 135 140 138 130 118 20 15 22 128 125 18 12 20 135 130 128 132 130 128
The low values (12–22) in the centre-left represent a dark crack against a lighter concrete background (120–140).
Kernel (3×3, horizontal edge):
-1 -1 -1 0 0 0 1 1 1
Top-left position calculation:
(-1×120) + (-1×130) + (-1×125)
+ (0×122) + (0×135) + (0×140)
+ (1×118) + (1×20) + (1×15)
= -375 + 0 + 153 = −222
A large negative value indicates a strong horizontal edge (transition from bright above to dark below). The kernel has detected the top edge of the crack region.
This same multiply-and-sum operation is repeated at every position the kernel can occupy. Regions with no edge produce values near zero; regions with strong edges produce large positive or negative values. The resulting feature map is essentially a "crack presence" map — exactly the kind of signal a CNN needs to begin classifying structural damage.
Padding and Stride
Two parameters control how the kernel slides across the input and what size the output feature map will be: padding and stride.
Padding: Preserving Spatial Dimensions
You may have noticed that with a 3×3 kernel and no padding, a 5×5 input shrinks to 3×3. Each convolution layer loses pixels around the border. In a deep network with many layers, this cumulative shrinkage would quickly reduce the feature map to a tiny remnant.
Padding solves this by adding extra rows and columns of zeros (or other values) around the border of the input before convolution. The two most common padding modes are:
Valid vs Same Padding
- Valid padding (no padding) — the kernel is only placed where it fully overlaps the input. Output is smaller than the input. Output size: (n − k) / s + 1.
- Same padding — enough zeros are added around the border so that the output has the same spatial dimensions as the input (when stride = 1). For a 3×3 kernel, this means adding 1 row/column of zeros on each side.
Padding is like extending a survey grid beyond the site boundary. When your geotechnical survey grid reaches the edge of the site, you cannot sample points beyond the boundary. But if you assume the ground conditions at the boundary are similar to the surrounding area (or assign a default value of zero), you can extend your analysis grid outward so that your boundary measurements still get a full neighbourhood of data. The result is a complete map that covers the same area as your original site — no edge data is lost.
Stride: Controlling the Step Size
By default the kernel slides one pixel at a time (stride = 1). But we can choose to skip positions by using a larger stride. A stride of 2 means the kernel jumps two pixels at a time, both horizontally and vertically, reducing the output size by roughly half in each dimension.
Stride Effects
- Stride 1: fine-grained output, captures every position. Most common in early layers.
- Stride 2: halves the output dimensions. Used as a downsampling mechanism, sometimes replacing pooling layers.
- Stride 3+: aggressive downsampling. Rarely used except in specialised architectures.
The generalised output size formula with padding p and stride s is:
output = floor((n + 2p − k) / s) + 1
For most practical CNN architectures, the early convolution layers use stride 1 with same padding (to preserve spatial resolution), while later layers may use stride 2 or pooling to progressively reduce the feature map size. We will explore pooling in detail in Sub-chapter 4.3.
Classic Hand-Crafted Kernels
Before the rise of deep learning, engineers and computer scientists manually designed convolution kernels for specific purposes. Understanding these classic kernels builds valuable intuition for what CNN-learned kernels do.
Edge Detection Kernels
Edge detection is arguably the most important low-level operation in image analysis. Edges mark boundaries between objects, transitions in texture, and — critically for civil engineers — cracks, spalling boundaries, and joint lines in structural surfaces.
Sobel Operators
The Sobel operator uses two 3×3 kernels to detect horizontal and vertical edges separately:
Sobel Horizontal (Gx):
-1 0 1 -2 0 2 -1 0 1
Sobel Vertical (Gy):
-1 -2 -1 0 0 0 1 2 1
The horizontal Sobel kernel responds to vertical edges (intensity changes from left to right), while the vertical Sobel responds to horizontal edges (changes from top to bottom). The total edge strength at any point is often computed as sqrt(Gx2 + Gy2).
Prewitt Operators
Prewitt kernels are similar to Sobel but use uniform weights instead of emphasising the centre row/column:
Prewitt Horizontal:
-1 0 1 -1 0 1 -1 0 1
Prewitt Vertical:
-1 -1 -1 0 0 0 1 1 1
Prewitt is slightly less noise-sensitive than Sobel because it does not weight the centre pixel more heavily. In practice, Sobel is more widely used, but Prewitt remains a useful reference.
Blur Kernels
Blurring smooths out noise and fine detail. The simplest blur kernel is a box blur (also called an averaging filter) — every weight is equal, and the kernel sums the neighbourhood and divides by the number of elements:
Box Blur (3×3)
1/9 1/9 1/9 1/9 1/9 1/9 1/9 1/9 1/9
Each output pixel is the average of its 3×3 neighbourhood. This reduces noise but also blurs edges. The Gaussian blur uses a bell-curve distribution of weights to prioritise nearby pixels:
1/16 2/16 1/16 2/16 4/16 2/16 1/16 2/16 1/16
Gaussian blur preserves edges slightly better than box blur while still reducing high-frequency noise.
Sharpen Kernel
Sharpening enhances edges and fine detail by amplifying the difference between a pixel and its neighbours:
Sharpen (3×3)
0 -1 0 -1 5 -1 0 -1 0
The centre weight (5) is much larger than the negative neighbours. This means the output amplifies differences between a pixel and its neighbours, enhancing edges and fine textures. In crack detection, a sharpen filter applied before edge detection can improve visibility of very faint hairline cracks.
Emboss Kernel
Embossing creates a 3D relief effect by detecting gradients in one direction:
Emboss (3×3)
-2 -1 0 -1 1 1 0 1 2
The emboss kernel highlights directional texture by emphasising the gradient from the top-left to the bottom-right. It can be rotated to detect gradients in other directions. In structural inspection, emboss filters can reveal surface texture variations and subtle deformation patterns that are difficult to see in the original image.
Understanding hand-crafted kernels is not just academic. When you visualise the kernels a CNN has learned, you will often find that the first convolutional layer has learned filters remarkably similar to Sobel, Gabor, and other classic operators. Knowing what these classical filters do helps you interpret what your neural network has discovered on its own.
How CNNs Learn Their Own Kernels
The breakthrough of convolutional neural networks is that they do not require a human to design the kernels. Instead, the kernel weights are treated as learnable parameters that are adjusted during training using backpropagation and gradient descent — the same optimisation process covered in Chapter 2.
During training, the network sees thousands of labelled images (e.g. "cracked" vs "intact" concrete). It starts with random kernel weights and makes terrible predictions. The loss function measures how wrong the predictions are. The gradients of the loss with respect to each kernel weight tell the optimiser which direction to adjust each weight. Over many iterations, the kernels converge to patterns that extract the most useful features for the task.
What Different Layers Learn
- Layer 1 (early): simple edge and texture detectors — remarkably similar to Sobel and Gabor filters.
- Layers 2–3 (middle): combinations of edges forming corners, curves, and simple shapes.
- Layers 4+ (deep): complex, abstract patterns specific to the task — crack-like textures, spalling patterns, reinforcement outlines.
A CNN learning kernels is like a junior inspector developing expertise. A new graduate inspecting bridges for the first time might look at everything randomly. Over time, they learn to focus on certain telltale signs: dark lines against lighter backgrounds (cracks), colour changes (corrosion), texture differences (spalling). They develop a set of mental "filters" tuned to the defects they need to find. A CNN does the same thing mathematically — it develops kernels (filters) tuned to the features that best distinguish the classes in its training data.
Multiple Kernels Per Layer
A single kernel can only detect one type of pattern (e.g. horizontal edges). To capture the full richness of an image, each convolutional layer applies many kernels in parallel. A typical first layer might have 32 or 64 different 3×3 kernels, each producing its own feature map. The collection of feature maps stacks together to form a multi-channel output, which becomes the input to the next layer.
This is why deep CNNs have millions of parameters — each layer has dozens to hundreds of kernels, and each kernel has its own set of learnable weights. But because each kernel is small (3×3 = 9 weights), the total parameter count is far smaller than what a fully connected network would require for the same input size.
- Weight sharing: the same kernel is applied at every spatial position, so a crack detector works regardless of where the crack appears in the image.
- Translation invariance: the feature map records where a feature was found, not at a fixed location.
- Parameter efficiency: a 3×3 kernel has only 9 weights, no matter how large the input image is.
Civil Engineering Focus: Edge Detection for Crack Finding
Let us bring the theory home with a concrete civil engineering application. Detecting cracks in concrete surfaces is one of the most active areas of AI-assisted structural inspection. Understanding convolution is essential because it is the mechanism by which a CNN processes the raw image and begins to isolate crack-like features.
Why Edges Matter for Crack Detection
A crack in a concrete surface is, fundamentally, an edge — a sharp transition from the lighter concrete background to the darker crack interior. When a Sobel or similar edge-detection kernel is convolved over an image of a cracked surface, the output feature map lights up along the crack path while suppressing the uniform concrete background.
In a CNN trained for crack detection, the first convolutional layer learns kernels very similar to Sobel operators. Deeper layers then combine these edge signals to distinguish genuine cracks from benign features like construction joints, surface staining, or casting marks.
The Processing Pipeline
A simplified pipeline for CNN-based crack detection looks like this:
From Photo to Crack Map
- Capture: photograph the concrete surface with a camera or drone.
- Preprocessing: convert to grayscale, resize to a standard dimension, normalise pixel values to 0–1.
- Convolution layers: the CNN applies learned kernels to extract edge and texture features at multiple scales.
- Classification/Segmentation: deeper layers and a final classifier decide whether each region is "cracked" or "intact" (classification) or label every pixel (segmentation).
- Output: a crack map or probability heatmap highlighting detected cracks, which the engineer can review.
The convolution operation is the workhorse of steps 3 and 4. Without it, the network would have no mechanism to detect the local spatial patterns that distinguish cracks from background. This is why convolution is not just a mathematical curiosity — it is the operational core of every vision- based AI system used in structural engineering today.
Production crack-detection systems typically use pre-trained networks (like ResNet or EfficientNet) that have been fine-tuned on domain-specific datasets of concrete images. These networks have dozens of convolutional layers, each with hundreds of learned kernels. But the fundamental operation in every one of those layers is the same slide-multiply-sum process described in this sub-chapter.
Interactive Demo 1: Convolution Visualiser
Watch the convolution operation step by step. A 3×3 kernel slides across a small input grid, performing the element-wise multiplication and summation at each position. The output feature map builds up in real time as the kernel moves. Use the controls to step through manually or let the animation play.
Press Play to watch the kernel slide across the input grid, or Step to advance one position at a time.
Interactive Demo 2: Kernel Gallery
Select different kernels from the gallery and see their effect on a simulated concrete surface image. The original image (left) is processed in real time to produce the filtered output (right). Notice how edge-detection kernels highlight crack-like features while blur kernels suppress them.
Click a kernel button above to see how different filters transform the simulated concrete image. The left panel shows the original; the right panel shows the convolution result.
Putting It All Together
Let us summarise the key ideas from this sub-chapter before moving on:
Key Takeaways
- Convolution is a slide-multiply-sum operation that transforms a raw image into a feature map highlighting specific patterns.
- The kernel (filter) is a small grid of weights that determines what pattern the convolution detects.
- Padding (same vs valid) controls whether the output preserves the input dimensions or shrinks.
- Stride controls the step size and therefore the output resolution.
- Classic kernels (Sobel, Prewitt, blur, sharpen, emboss) demonstrate what different patterns of weights detect.
- CNNs learn their kernel weights from data, often rediscovering classical edge detectors in early layers.
- For civil engineers, convolution is the mechanism that enables a network to detect cracks, edges, and texture patterns in structural images.
In the next sub-chapter we will explore pooling and stride — the operations that reduce the spatial dimensions of feature maps and build progressively more abstract representations. Together with convolution, pooling completes the core building blocks of every CNN architecture.
Civil Engineering Application: Convolution for Crack Detection
Convolution is the foundation of automated crack detection. Here's exactly how it works on real infrastructure:
Edge Kernels Find Cracks
A Sobel kernel [[-1,0,1],[-2,0,2],[-1,0,1]] produces high responses at crack boundaries. The CNN's first conv layer learns kernels almost identical to Sobel — but optimized for concrete textures specifically.
Pavement Distress Analysis
FHWA classifies pavement distress into 19 types (LTPP protocol). Convolution filters detect linear cracks (longitudinal/transverse), area distress (alligator cracking), and surface defects (raveling) — each activating different learned kernels.
Filter Size Selection
3×3 kernels catch fine cracks (0.1-0.5mm). 5×5 kernels detect wider spalling. 7×7 kernels identify large-scale deformations. CNNs stack these at multiple scales — deeper layers combine edge info into structural damage patterns.
Knowledge Check
Test your understanding of the convolution operation with these four questions.
A 7×7 input image is convolved with a 3×3 kernel using stride 1 and no padding (valid). What is the output size?
In a convolution step, after overlaying the 3×3 kernel on a 3×3 image patch, what operation produces the single output value?
What is the purpose of "same" padding in convolution?
A Sobel edge-detection kernel applied to a concrete surface image would most strongly respond to which feature?