2D Convolutional Neural Networks Explained: How CNNs Power Visual Inspection

How a 2D CNN for visual inspection handles channels, padding, stride and pooling, and how the output head shapes defect detection on the line.

2D Convolutional Neural Networks Explained: How CNNs Power Visual Inspection
Written by TechnoLynx Published on 11 Jul 2026

A 2D convolutional neural network reads an image by sliding small learned filters across its height and width. Each filter always extends through the full depth of the input, so its depth follows the number of input channels. Padding, stride and pooling set the size of each feature map the layers produce, and the network ends in a head that turns those maps into an output. In 2D CNN visual inspection, the head produces the output: an OK or not-good label for the whole image, a bounding box around a defect, or a defect segmentation.

We would argue that the choice of head deserves as much thought as the convolutional layers, because manufacturing data is highly repetitive with few defect images.

How a 2D Convolution Handles RGB and Multi-Band Inspection Images

An RGB image enters the network as a three-dimensional tensor of shape 3×h×w, and the axis of size 3 is the channel dimension. A convolution kernel must have the same number of input channels as the data, or the cross-correlation cannot be computed. A typical first-layer filter on a colour image is therefore something like 5×5×3: five pixels wide and high, and three deep for the colour channels.

At each position, the filter takes a weighted sum over all three channels, adds a bias and passes the result through an activation function. That gives one number in the output activation map. Connectivity is local in width and height but full along depth, an asymmetry that is easy to forget when you read layer definitions.

Two numbers are design choices and one is not. The spatial size of the filter is yours to choose (3×3 is very common, sometimes 5×5). So is the number of filters, and it sets how many activation maps, or output channels, the layer produces. Filter depth is not a choice: it follows the input. LearnOpenCV’s worked count shows how this adds up: two 3×3 filters over a three-channel input hold 27 weights each, so 54 weights plus two biases, 56 trainable parameters in all.

Multispectral and Hyperspectral Inputs

Nothing in the operation is tied to three channels. A deep CNN for hyperspectral image classification applies filters of 1×1×B, 3×3×B and 5×5×B, where B is the number of spectral bands. The 3×3 and 5×5 filters capture local spatial correlations, and the 1×1 filters capture spectral ones. A 1×1 convolution computes only along the channel dimension. It acts like a fully connected layer applied at each pixel, needing c_o×c_i weights plus bias. That makes it a cheap way to learn how bands should be combined before any spatial reasoning happens.

The inspection case for extra bands is concrete. Chen et al. found that different solar cell surface defects showed distinguishable characteristics in different spectral bands. They built a multispectral CNN to separate defects from complex textured backgrounds, and report a defect-recognition accuracy of 94.30% under K-fold cross-validation. That figure belongs to that dataset and set of defect types, not to multispectral inspection in general. For how the camera produces these images, see our piece on how a machine vision camera works in industrial inspection.

Not every layer has to mix all channels. In PyTorch’s Conv2d, the groups parameter controls which inputs connect to which outputs, and in_channels and out_channels must both divide by it. With groups equal to in_channels, each input channel is convolved with its own set of filters, which is a depthwise convolution.

Padding, Stride and Pooling: What Each Does to the Feature Map

Stride is the number of pixels the filter moves from one position to the next. A stride of 1 moves it one pixel at a time. A stride of 2 jumps two pixels and gives a smaller output, and strides of 3 or more are rare in practice.

Padding adds extra pixels around the border of the input. Zero padding is the most widely used kind because it is simple and cheap to compute. Without padding, every layer trims the map. Dive into Deep Learning works through a case where ten layers of 5×5 convolutions shrink a 240×240 image to 200×200, slicing off 30% of the image along with any information at its boundaries. CS231n adds that unpadded “valid” convolutions wash border information away too quickly, and that padding to keep sizes constant improves performance. On an inspection frame, whatever sits at the border is lost with it, so dropping padding to save a little compute is a poor trade.

Odd kernel sizes (1, 3, 5, 7) are common because they allow the same padding on top and bottom, and on left and right. With stride 1, a padding of P = (F − 1)/2 preserves the input size: P = 1 for a 3×3 filter and P = 2 for a 5×5.

Pooling shrinks the map deliberately. A pooling layer works on each depth slice separately, usually with a MAX operation. The most common form, a 2×2 window with stride 2, halves width and height and discards 75% of the activations, leaving depth unchanged. Pooling has no trainable parameters: window size, stride and padding are hyperparameters. It cuts the parameters and computation in later layers, which also helps control overfitting. CS231n notes that average pooling has largely given way to max pooling, which works better in practice.

The Output-Size Formula

For a convolution, the output width is (W − F + 2P)/S + 1, where W is the input size, F the filter size, P the padding and S the stride, and the output depth equals the number of filters. Max pooling uses the same formula with zero padding and the pool size as F, but its output keeps the number of input channels.

If the result is not an integer, the settings do not fit. With W = 10, P = 0 and F = 3, a stride of 2 gives (10 − 3 + 0)/2 + 1 = 4.5. A library might then raise an error, pad or crop. Dumoulin and Visin’s guide to convolution arithmetic (2016) sets out the full relationships between input shape, kernel shape, padding, stride and output shape for convolutional, pooling and transposed convolutional layers.

Worked Example: Tracing Tensor Shapes Through Four Layers

The first row comes from AlexNet’s documented first layer.

Layer Input Settings Calculation Output
Conv-1 (AlexNet) 227×227×3 96 filters of 11×11×3, S = 4, P = 0 (227 − 11 + 0)/4 + 1 = 55 55×55×96
Conv, size-preserving 512×512×1 (assumed) 32 filters of 3×3×1, S = 1, P = 1 (512 − 3 + 2)/1 + 1 = 512 512×512×32
Max pool 512×512×32 F = 2, S = 2 (512 − 2)/2 + 1 = 256 256×256×32

Parameter sharing keeps the conv layer’s parameter count down. In AlexNet’s first layer, each of 55×55×96 = 290,400 neurons connects to 11×11×3 = 363 inputs, so separate weights for every neuron would mean 105,705,600 parameters. Because every neuron in a depth slice shares its weights and bias, the layer actually holds 96 × (363 + 1) = 34,944 parameters.

What You Set in PyTorch’s Conv2d

In PyTorch, stride takes a single number or a tuple. padding takes an integer, a tuple, or the strings 'valid' (no padding) and 'same' (output keeps the input’s shape). 'same' supports only a stride of 1. dilation spaces out the kernel points, also known as the à trous algorithm. For multi-band inspection data, a kernel needs as many input channels as the input has bands.

From Convolution Blocks to the Classification Head

A ConvNet is built from three layer types: convolutional, pooling and fully connected. CS231n gives the most common arrangement as INPUT → [[CONV → RELU]×N → POOL?]×M → [FC → RELU]×K → FC: conv-ReLU pairs stacked, pooled, repeated until the image is spatially small, then fully connected layers whose last one holds the class scores. ReLU is there because convolution is linear, and the network needs a non-linearity to be more expressive.

LearnOpenCV describes the same structure as two halves. A feature extractor of repeated convolutional blocks, each one or more conv layers followed by max pooling, feeds a classifier that turns features into class predictions. In VGG-16, the last block outputs 7×7×512 activation maps. These are flattened to a vector of 25,088 values before the first fully connected layer, and the output layer has one neuron per class, with softmax giving each class’s probability.

Cost and parameters sit in different places. CS231n notes that most memory and compute go to the early conv layers, while most parameters sit in the final fully connected layers. The first FC layer alone holds about 100M of 140M weights. Not every architecture keeps that head. ResNet drops the fully connected layers at the end, and a fully convolutional network with no pooling can accept input of any size. Replacing fully connected layers with 1×1 convolutions lets the network classify each pixel, as in semantic segmentation.

Choosing the Output Head for 2D CNN Visual Inspection

Defect classification predicts whether an image contains a defect and labels it. The labels can be binary (OK or not-good) or multi-class. That is the classifier head described above. Manufacturing data is a challenge for it, though. A study of manufacturing defect detection points out that inspection data is highly repetitive and has few defect images. Models trained on it can be sensitive to context and miss new defects absent from training. The same study reports that object detection models trained to predict a label plus a bounding box outperformed label-only classifiers on held-out test data typical of inspection tasks.

A detection head sits on a convolutional backbone. RetinaNet, for example, combines a ResNet-50 feature extractor, a feature pyramid network that builds a multi-scale feature pyramid, and two sub-networks for classification and box regression. The pyramid draws on the hierarchy of the deep network to represent objects at several scales. When parts arrive rotated or defects are long and diagonal, oriented bounding boxes and when rotated detection earns its cost becomes the next decision. For how detection runs on a working line, see object detection on a production inspection line.

Segmentation networks segment the defect at pixel level rather than boxing it. Tabernik et al. (2019) designed a segmentation-based architecture for surface-crack detection that learned from about 25-30 defective training samples, rather than the hundreds or thousands deep learning usually needs. A study on mixed supervision built an end-to-end architecture with two sub-networks, one for segmentation and one for classification. It explored labels ranging from image-level through mixed to full pixel-level annotation, because the cost of high-precision labels can make industrial problems hard to solve or much more expensive. Data volume is its own question. The point here is that the head and the labelling scheme are chosen together.

In one dendrite-core microscopy study, segmentation also beat bounding-box regression. In microscopy of directionally solidified Ni-base alloys, a U-Net-based detector framed dendrite-core detection as segmentation, on 1,461 images at 512×512. At a 10-pixel deviation tolerance, it reports relative gains over a bounding-box regression baseline of 5.77% in recall, 7.29% in precision and 6.53% in F-score.

Head What it outputs Labels it needs Where it fits
Image classifier (conv blocks, FC, softmax) OK/not-good or a defect class per image One label per image Presence is the whole question; brittle when defects are rare or new
Object detector (backbone, feature pyramid, class and box sub-networks) Label plus bounding box per defect Boxes Location matters, or held-out robustness beats a label-only classifier
Segmentation network (encoder-decoder or fully convolutional) Pixel mask, often with an image-level score Pixel masks, or a mix of image-level and pixel-level labels Point-like targets (one microscopy study), few defective samples

What High-Resolution, Low-Defect Data Does to These Choices

The cost of a convolutional layer grows with the output height and width, the square of the kernel size, and the input and output channel counts. A full-resolution inspection frame costs far more per layer than a downsampled one. Since early conv layers dominate memory and compute, it is tempting to stride or pool aggressively from the first layer. We would resist that until someone has checked how many pixels the smallest defect of interest covers after each downsampling step, because a feature that pooling has averaged or maxed away cannot be recovered by the head. Our computer vision R&D page describes how we design and validate inspection models where small defects must survive downsampling.

Augmentation addresses scarce training data. Common methods are rotation, flipping, mirroring, added noise and changes in illumination, often combined. Augmentation widens the training set, but it does not replace held-out data from the line’s real lighting and part variation. Whether a model still holds up under those conditions is a validation question, not an architecture one. The same logic applies when deciding whether a learned model belongs on the line at all: where AI adds value in visual inspection equipment and where rules still win takes that question head on, and the automated visual inspection system guide connects model selection to false-reject rates.

The shape arithmetic is the cheap part: every feature map size follows from a formula you can check before training. The costly mistakes come later, when a classifier has learned a repetitive dataset too well and the first new defect type goes undetected. Once a model is on the line, keeping it trustworthy depends on the artefacts that keep a line-side inspection model running more than on the layer stack.