Convolutional Neural Networks: Computer Vision Applications
How convolutional neural networks read images: filters, feature maps, pooling, the architectures that matter, and how CNNs power real computer vision systems.
A 224 by 224 color photo is 150,528 numbers. Feed it to a feedforward network and a single dense layer of 1,000 units needs more than 150 million weights, each one tied to a single pixel position. That network has no idea that a pixel and its neighbor are related, and a cat in the top-left corner looks to it like a completely different input from the same cat in the bottom-right.
Convolutional neural networks (CNNs) fix both problems with one idea: instead of connecting every input to every unit, slide a small set of weights across the image and reuse them everywhere. That change cuts the parameter count by orders of magnitude and builds in the assumption that what matters in an image is local patterns, wherever they appear.
This article explains how a convolution works, with a filter you can check by hand, then builds a small CNN in PyTorch and trains it against a plain network on the same data. It closes with the architectures worth knowing, the vision tasks CNNs handle, and how the cloud providers package them.
Why dense layers struggle with images
- Locality. The pixels that matter for recognizing an edge, a corner or an eye are close together. A dense unit looks at every pixel at once, so it has to learn from data that distant pixels mostly don’t matter.
- Translation. An object can appear anywhere in the frame. A dense layer learns separate weights for each position, so a pattern learned in one place has to be learned again everywhere else.
- Size. Weight count grows with pixels times units, and more weights need more data to avoid overfitting.
A convolutional layer addresses all three. Each unit looks at a small patch (locality), the same weights are applied at every position (translation), and the weight count depends on the filter size rather than the image size.
How a convolution works
A filter sliding across an image
A convolutional filter (or kernel) is a small grid of weights, typically 3 by 3. To apply it, you place it over the top-left patch of the image, multiply each weight by the pixel under it, add the results, and write that sum into the output. Then you slide one step to the right and repeat, row by row, until you have covered the image. The output grid is called a feature map.
Here is that operation in plain NumPy, on a 6 by 6 image with a bright left half and a dark right half:
import numpy as np
image = np.zeros((6, 6))
image[:, :3] = 10 # bright left half, dark right half
kernel = np.array([[1, 0, -1],
[1, 0, -1],
[1, 0, -1]]) # responds to vertical edges
def conv2d(x, k):
kh, kw = k.shape
out = np.zeros((x.shape[0] - kh + 1, x.shape[1] - kw + 1))
for i in range(out.shape[0]):
for j in range(out.shape[1]):
out[i, j] = np.sum(x[i:i + kh, j:j + kw] * k)
return out
print(conv2d(image, kernel))
[[ 0. 30. 30. 0.]
[ 0. 30. 30. 0.]
[ 0. 30. 30. 0.]
[ 0. 30. 30. 0.]]
Check one value. At the top-left position the filter covers three columns of 10s, so the left column contributes 30, the right column contributes -30, and the sum is 0. One step to the right, the filter’s left column still sits on 10s but its right column sits on 0s, so the sum is 30. The feature map lights up exactly where the brightness changes, and stays at zero over flat regions. Run the same filter on the image rotated 90 degrees, so the edge is horizontal, and every output is zero: this filter only detects vertical edges.
That is the whole idea. A filter is a pattern detector, and the feature map records where in the image the pattern occurs. In a CNN, nobody designs the filters by hand. They start as random numbers and training adjusts them, the same way it adjusts the weights of a dense layer, until they detect whatever patterns help reduce the loss.
Strictly speaking, deep learning frameworks compute cross-correlation, not the flipped-kernel convolution from signal processing. Since the filter weights are learned, the distinction makes no practical difference, and everyone calls it convolution.
Channels and multiple filters
Real images have channels: three for an RGB photo. A filter on a color image is therefore 3 by 3 by 3, spanning all input channels, and it produces one feature map by summing across all of them. A convolutional layer runs many filters in parallel, say 64, and stacks their outputs into a 64-channel feature map. The next layer’s filters then span those 64 channels.
The parameter count for a layer is kernel height x kernel width x input channels x output channels, plus one bias per output channel. A layer of 64 filters, each 3 by 3, on an RGB image has 3 x 3 x 3 x 64 + 64 = 1,792 parameters, whatever the image size. Compare that with the 150 million of the dense layer above.
Stride and padding
Two settings control the output size:
- Stride is how far the filter moves at each step. A stride of 2 skips every other position and roughly halves the height and width.
- Padding adds a border of zeros around the input so the filter can be centered on edge pixels. With a 3 by 3 filter, a padding of 1 keeps the output the same size as the input (“same” padding).
The output size along each dimension is:
output = floor((input - kernel + 2 * padding) / stride) + 1
In the NumPy example, (6 - 3 + 0) / 1 + 1 = 4, which is why a 6 by 6 image produced a 4 by 4 feature map. ResNet’s first layer uses a 7 by 7 filter with stride 2 and padding 3 on a 224 by 224 image: floor((224 - 7 + 6) / 2) + 1 = 112.
A convolutional layer applies 16 filters of size 3 by 3 to an 8-channel input. How many parameters does it have?
Correct! Each filter has 3 x 3 x 8 = 72 weights, so 16 filters have 1,152, plus 16 biases makes 1,168, regardless of image size.
Pooling
A pooling layer shrinks a feature map by summarizing small windows. Max pooling with a 2 by 2 window and stride 2 keeps the largest value in each window, halving the height and width. It has no weights. Pooling makes the network less sensitive to small shifts (an edge one pixel to the left still produces the same maximum) and reduces the computation for later layers.
Many modern architectures use strided convolutions instead of pooling, with the same purpose: trade spatial resolution for more channels as the network deepens.
Receptive field and the feature hierarchy
A unit in the first layer sees a 3 by 3 patch. A unit in the second layer sees a 3 by 3 patch of the first layer’s output, which covers 5 by 5 pixels of the original image. Each pooling layer doubles the reach of everything after it. By the last layers, each unit’s receptive field covers most of the image.
That growth gives a CNN its hierarchy. Early filters learn edges and color blobs, middle layers combine them into textures and simple shapes, and later layers respond to object parts and whole objects. Nobody designs this; it falls out of training.
The shape of a CNN
Most image classifiers follow the same outline: a stack of convolution blocks that shrink the image while adding channels, followed by a small classifier head.
flowchart LR
I["Image 3x224x224"] --> C1["Conv + ReLU"]
C1 --> P1["Pool"]
P1 --> C2["Conv + ReLU"]
C2 --> P2["Pool"]
P2 --> C3["More conv blocks"]
C3 --> G["Global average pool"]
G --> D["Dense layer"]
D --> S["Softmax over classes"]
The convolution blocks are the feature extractor. The head at the end is a small feedforward network that turns the final features into class scores. Older designs flattened the last feature map into a long vector before the dense layers; most modern ones use global average pooling, which averages each channel down to a single number and so produces one value per channel regardless of input size.
A small CNN in PyTorch
Here is a CNN for 28 by 28 grayscale images, with the output shape and parameter count printed after each layer:
import torch
import torch.nn as nn
model = nn.Sequential(
nn.Conv2d(1, 32, kernel_size=3, padding=1), # 1x28x28 -> 32x28x28
nn.ReLU(),
nn.MaxPool2d(2), # -> 32x14x14
nn.Conv2d(32, 64, kernel_size=3, padding=1), # -> 64x14x14
nn.ReLU(),
nn.MaxPool2d(2), # -> 64x7x7
nn.Flatten(), # -> 3136
nn.Linear(64 * 7 * 7, 128),
nn.ReLU(),
nn.Linear(128, 10), # one score per class
)
x = torch.randn(1, 1, 28, 28) # batch of one grayscale image
for layer in model:
x = layer(x)
params = sum(p.numel() for p in layer.parameters())
print(f"{layer.__class__.__name__:<10} {str(tuple(x.shape)):<18} {params:>8,}")
print(f"total parameters: {sum(p.numel() for p in model.parameters()):,}")
Conv2d (1, 32, 28, 28) 320
ReLU (1, 32, 28, 28) 0
MaxPool2d (1, 32, 14, 14) 0
Conv2d (1, 64, 14, 14) 18,496
ReLU (1, 64, 14, 14) 0
MaxPool2d (1, 64, 7, 7) 0
Flatten (1, 3136) 0
Linear (1, 128) 401,536
ReLU (1, 128) 0
Linear (1, 10) 1,290
total parameters: 421,642
PyTorch orders image tensors as batch, channels, height, width. Notice where the parameters are: the two convolutional layers together have under 19,000, while the first dense layer has over 400,000. That imbalance is why modern architectures replace Flatten with global average pooling. Swap in nn.AdaptiveAvgPool2d(1) followed by nn.Flatten() and nn.Linear(64, 10), and the head shrinks to 650 parameters.
CNN against a plain network
To see what the convolutions buy, train this CNN and a fully connected network on Fashion-MNIST, a dataset of 70,000 grayscale images of clothing in 10 classes (shirts, sneakers, bags and so on). Both use the Adam optimizer, a learning rate of 0.001 and five epochs:
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
torch.manual_seed(0)
tf = transforms.ToTensor() # pixels scaled to 0..1, shape 1x28x28
train = datasets.FashionMNIST("data", train=True, download=True, transform=tf)
test = datasets.FashionMNIST("data", train=False, download=True, transform=tf)
train_dl = DataLoader(train, batch_size=64, shuffle=True)
test_dl = DataLoader(test, batch_size=1000)
def make_cnn():
return nn.Sequential(
nn.Conv2d(1, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Flatten(), nn.Linear(64 * 7 * 7, 128), nn.ReLU(), nn.Linear(128, 10),
)
def make_mlp():
return nn.Sequential(
nn.Flatten(), nn.Linear(28 * 28, 512), nn.ReLU(),
nn.Linear(512, 512), nn.ReLU(), nn.Linear(512, 10),
)
def accuracy(model):
model.eval()
correct = 0
with torch.no_grad():
for X, y in test_dl:
correct += (model(X).argmax(1) == y).sum().item()
return correct / len(test)
for name, make in [("MLP", make_mlp), ("CNN", make_cnn)]:
model = make()
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
loss_fn = nn.CrossEntropyLoss()
for epoch in range(5):
model.train()
for X, y in train_dl:
opt.zero_grad()
loss_fn(model(X), y).backward()
opt.step()
n = sum(p.numel() for p in model.parameters())
print(f"{name}: {n:,} parameters, test accuracy {accuracy(model):.3f}")
On a four-core CPU this takes about three minutes. With PyTorch 2.15 it printed:
MLP: 669,706 parameters, test accuracy 0.873
CNN: 421,642 parameters, test accuracy 0.908
The CNN has about a third fewer parameters and is 3.5 points more accurate. Put another way, its error rate drops from 12.7 percent to 9.2 percent, so it makes roughly a quarter fewer mistakes. The plain network sees each image as 784 unrelated numbers; the CNN knows that nearby pixels belong together. Your exact figures will differ slightly with library versions and hardware, but the gap is consistent. Neither model is tuned: more epochs, batch normalization and data augmentation would raise both, and the CNN has more room to gain from them.
There is no softmax layer in either model. nn.CrossEntropyLoss applies it internally to the raw scores (logits), and argmax picks the same class whether or not you apply softmax first.
Why does a convolutional layer need far fewer parameters than a dense layer on the same image?
Correct! Weight sharing means the parameter count depends on filter size and channel counts, not on the number of pixels.
Architectures worth knowing
You will rarely design a CNN from scratch for a real project. You will pick one of a handful of proven architectures, usually with weights pretrained on ImageNet, a dataset of about 1.2 million training images in 1,000 classes that served as the field’s benchmark for a decade.
| Architecture | Year | Key idea | Why it matters |
|---|---|---|---|
| LeNet-5 | 1998 | Conv and pooling layers trained end to end | Read handwritten digits on bank checks; the template for everything after |
| AlexNet | 2012 | Deeper CNN, ReLU, dropout, trained on GPUs | Won ImageNet by a wide margin and started the deep learning wave |
| VGG | 2014 | Stacks of 3 by 3 convolutions only | Simple and uniform; still used as a feature extractor, but VGG-16 has about 138 million parameters |
| GoogLeNet (Inception) | 2014 | Parallel filters of different sizes in one block | High accuracy at far lower cost than VGG |
| ResNet | 2015 | Residual (skip) connections | Made networks with 50 to 150+ layers trainable; still a default baseline |
| MobileNet | 2017 | Depthwise separable convolutions | Built for phones and edge devices |
| EfficientNet | 2019 | Scales depth, width and resolution together | Strong accuracy per parameter |
| ConvNeXt | 2022 | Modernized ResNet borrowing transformer design choices | Showed CNNs can match vision transformers |
Residual connections
ResNet’s contribution deserves a closer look, because the idea now appears in almost every deep architecture, transformers included. Before ResNet, adding layers beyond a certain depth made training accuracy worse, not better: the gradients that backpropagation sends back to early layers shrink or become erratic as they pass through many layers.
A residual block adds its input to its output, so the layers inside only have to learn a correction to the identity:
flowchart TD
X["Input x"] --> A["Conv, batch norm, ReLU"]
A --> B["Conv, batch norm"]
B --> P["Add"]
X -->|"Skip connection"| P
P --> R["ReLU"]
R --> Y["Output"]
If the best thing a block can do is nothing, it can learn weights near zero and pass its input through unchanged. And the addition gives gradients a direct path back to early layers. Together these let a 152-layer ResNet train well, where a plain stack of that depth would not.
CNNs and vision transformers
In 2020 the Vision Transformer (ViT) showed that the transformer architecture from language models works on images too: cut the image into 16 by 16 patches, treat each patch as a token, and let attention relate every patch to every other. Given enough training data, ViTs match or beat CNNs.
CNNs remain the practical choice in many situations. Their built-in assumptions about locality mean they learn well from smaller datasets, they run efficiently on phones, cameras and other edge hardware, and the established detection and segmentation toolkits are built around them. For a new project with a modest dataset, a pretrained ResNet, EfficientNet or ConvNeXt is a sound first choice, and a pretrained ViT is worth comparing if you have the data and compute.
Computer vision tasks
Classification, one label per image, is the simplest vision task. The same convolutional backbone supports several others by changing what comes after it.
flowchart TD
B["Pretrained CNN backbone"] --> C["Classification: one label per image"]
B --> D["Object detection: boxes and labels"]
B --> S["Semantic segmentation: a class per pixel"]
B --> I["Instance segmentation: a mask per object"]
B --> E["Embeddings: a vector per image for search"]
| Task | Output | Common model families | Example use |
|---|---|---|---|
| Classification | A label and a confidence | ResNet, EfficientNet, ConvNeXt | Sorting product photos, flagging defective parts |
| Object detection | A box, a label and a score per object | Faster R-CNN, YOLO family, RetinaNet | Counting vehicles, finding people in a frame |
| Semantic segmentation | A class for every pixel | U-Net, DeepLab | Tumor boundaries in scans, road and lane areas |
| Instance segmentation | A separate mask for each object | Mask R-CNN | Separating touching cells or overlapping items |
| Image embeddings | A fixed-length vector | Any backbone with the head removed | Visual search, near-duplicate detection |
Where CNNs are used
- Manufacturing inspection. Cameras on a production line photograph every part, and a classifier or segmentation model flags scratches, cracks and missing components. Defects are rare, so these projects often deal with heavily imbalanced data.
- Medical imaging. Segmentation models outline organs and lesions in CT and MRI scans, and classifiers screen retinal photos and X-rays. U-Net was designed for biomedical images and remains a standard there. These systems assist clinicians and need regulatory clearance before clinical use.
- Documents. Optical character recognition finds and reads text regions in scans and photos, which feeds invoice processing and form extraction.
- Retail, agriculture and vehicles. Shelf monitoring, crop disease detection from drone imagery, and detecting pedestrians, lanes and signs alongside a vehicle’s other sensors.
The convolution layer also turns up outside classic vision. The generators and discriminators in GANs are mostly convolutional, image-to-image models like CycleGAN are built from convolution blocks, and one-dimensional convolutions work on audio and time series.
Transfer learning: the usual way to build a vision model
Training a CNN from scratch needs a large labeled dataset. Most projects instead start from a network pretrained on ImageNet and adapt it. The early layers, which detect edges and textures, transfer well to almost any image domain. Only the head is specific to the original 1,000 classes.
import torch.nn as nn
from torchvision import models
weights = models.ResNet18_Weights.DEFAULT
model = models.resnet18(weights=weights)
preprocess = weights.transforms() # the resizing and normalization it was trained with
for p in model.parameters(): # freeze the pretrained backbone
p.requires_grad = False
model.fc = nn.Linear(model.fc.in_features, 5) # new head for 5 classes, trainable
Train this for a few epochs on your own images, passing only model.fc.parameters() to the optimizer. If accuracy plateaus and you have a few thousand images or more, unfreeze the last block (model.layer4) and continue at a lower learning rate. Always apply the same preprocessing the pretrained weights expect; a model fed differently normalized inputs loses much of its accuracy without any error message. The general approach, and when to unfreeze more, is covered in fine-tuning pre-trained models for specific tasks.
Two habits matter more for vision than for tabular data:
- Augment the training images. Random crops, flips, small rotations and color changes make the model robust to variations it will see in production. Use only augmentations that preserve the label: flipping a photo of a shoe is fine, flipping a road sign with text or an arrow may not be.
- Check the validation set matches reality. A model trained on clean studio photos will struggle with blurry phone photos under warehouse lighting. Collect validation images the way production images will be collected, and use the evaluation practices from model training and evaluation.
You have 800 labeled photos across 4 product categories. What is the most sensible starting point?
Correct! The pretrained backbone already detects general visual features, so only the small new head has to be learned from your 800 images.
Computer vision in the cloud
You don’t always need to train anything. Each major provider offers vision APIs backed by pretrained models, a way to train custom models from labeled images without writing model code, and a general ML platform for running your own PyTorch or TensorFlow training.
| Need | AWS | Google Cloud | Azure |
|---|---|---|---|
| Pretrained labels, objects, text, faces | Amazon Rekognition | Cloud Vision API | Azure Vision (Image Analysis) |
| Custom classifier or detector, no model code | Rekognition Custom Labels | AutoML image training in Gemini Enterprise Agent Platform | Custom Vision; Azure Machine Learning AutoML for images |
| Your own training code on managed GPUs | Amazon SageMaker AI | Gemini Enterprise Agent Platform custom training | Azure Machine Learning |
A few points to check before choosing:
- Pretrained APIs cover common cases. If you need generic labels, text extraction or explicit-content detection, a single API call may be all you need. They will not recognize your company’s specific parts or defects; that is what the custom options are for.
- Azure is consolidating its vision services. Microsoft has announced that Custom Vision and the Image Analysis API both retire on September 25, 2028, and points customers toward Azure Machine Learning AutoML and models in Microsoft Foundry. New Azure projects should start on those rather than Custom Vision.
- Google’s platform was renamed. Vertex AI became Gemini Enterprise Agent Platform in April 2026, so older tutorials and console paths use the previous name.
- Pricing differs by model. Pretrained APIs typically bill per image, while custom models also bill for training time and for the hours an endpoint is running. An idle custom model endpoint keeps costing money; check each provider’s current pricing page.
For a comparison of the general ML platforms, see setting up a simple ML project.
Further reading:
- PyTorch: torch.nn.Conv2d
- torchvision: models and pretrained weights
- Keras: Conv2D layer
- Amazon Rekognition Custom Labels
- Azure Custom Vision migration options
Key takeaways
- Dense layers ignore image structure and need enormous numbers of weights. Convolutional layers slide small shared filters across the image, so their size depends on the filter and channel counts, not the pixel count.
- A filter is a learned pattern detector, and its feature map shows where the pattern appears. Stacking layers grows the receptive field, so early layers find edges and later ones find parts and objects.
- Output size is
floor((input - kernel + 2 * padding) / stride) + 1. Pooling and strided convolutions shrink the spatial size while the channel count grows. - Most image models are a convolutional feature extractor plus a small classifier head; global average pooling keeps that head small.
- Residual connections made very deep networks trainable and now appear in nearly every deep architecture.
- For real projects, start from a pretrained network and fine-tune it, use label-preserving augmentation, and validate on images that look like production data.
- Cloud vision APIs handle generic tasks without training; custom-label services and ML platforms cover the rest. Azure’s Custom Vision and Image Analysis retire in September 2028, so plan new Azure work on their successors.
Part 2 of 2 · Deep Learning and Neural Networks