Image convolution explained: kernels, padding, stride, and output shape
How a small grid of weights slides over an image to blur it, sharpen it or find its edges, what padding and stride do at the borders and to the output size, and how far one output pixel can see.
Image convolution slides a small grid of weights across an image and, at each position, multiplies the weights by the pixels under them and adds up the products. The sum becomes one pixel of the output. With different weights, the same operation blurs an image, sharpens it or marks its edges. Convolutional neural networks are built from this operation, with weights learned from data instead of chosen by hand.
Neighborhood operators
A grayscale image is a grid of numbers, one per pixel, usually from 0 for black to 255 for white. Some image operations change each pixel using only its own value, as brightening does. A neighborhood operator computes each output pixel from a small window of input pixels centered on that position.
Reading a window lets it respond to structure as well as value. An edge is a change between neighboring pixels, so at least two pixels are needed to see one.

The window moves across the image one position at a time. At each position it reads the local patch, computes one value and writes it to the matching position of the output. The same calculation runs everywhere, and blurring, edge detection and shape cleanup are all built this way.

A 3 by 3 window fits at 3 positions down and 5 across a 5 by 7 input, so the output in the picture is 3 by 5. Padding, covered below, keeps the output the same size as the input.
Correlation
To find where a particular pattern sits in an image, you need a score for how well a small pattern lines up with each patch. Correlation gives that score. It slides the pattern over the image, multiplies it with the overlapping patch element by element and adds up the products. The sum is large where the patch looks like the pattern and small where it does not. The output is a similarity map, bright where the pattern matched.

Correlation on one row
Take the pattern $[1, 0, 1]$, which responds to two bright pixels with a gap between them. Slide it over the image row $[10, 90, 10, 90, 10]$, placing it only where it fits.
At position 0, over $[10, 90, 10]$:
$$1 \cdot 10 + 0 \cdot 90 + 1 \cdot 10 = 20$$
At position 1, over $[90, 10, 90]$:
$$1 \cdot 90 + 0 \cdot 10 + 1 \cdot 90 = 180$$
At position 2, over $[10, 90, 10]$:
$$1 \cdot 10 + 0 \cdot 90 + 1 \cdot 10 = 20$$
The output is $[20, 180, 20]$. The response peaks at position 1, where the two bright pixels line up with the pattern's two 1s.

Correlation in code
import torch
def correlate1d(row, pattern):
pad = pattern.numel() // 2
padded = torch.cat([row.new_zeros(pad), row, row.new_zeros(pad)])
out = torch.zeros_like(row)
for i in range(len(row)):
out[i] = (padded[i:i + len(pattern)] * pattern).sum()
return out
row = torch.tensor([10, 90, 10, 90, 10], dtype=torch.float32)
pattern = torch.tensor([1, 0, 1], dtype=torch.float32)
out = correlate1d(row, pattern)
print(out) # tensor([ 90., 20., 180., 20., 90.])correlate1d centers the 3-wide pattern on each position of the row. At the two ends the pattern hangs off the row, so the code adds a zero at each end first. Adding values past the ends so the pattern fits at the border is called padding. Here it keeps the output the same length as the row, and the three middle values $[20, 180, 20]$ match the hand calculation.

Convolution and kernels
Convolution slides a kernel, a small array of weights, over the image. At each position it multiplies the kernel with the local patch and adds up the products. The only difference from correlation is that convolution first flips the kernel left to right and top to bottom.
For a symmetric kernel, such as a blur, the flip changes no weight. Deep learning libraries skip the flip and still call the operation convolution.

One convolution step with a blur kernel
Take a patch with one bright pixel and a box-blur kernel where every weight is $1/9$:
$$P = \begin{bmatrix} 10 & 10 & 10 \\ 10 & 90 & 10 \\ 10 & 10 & 10 \end{bmatrix}, \quad K = \frac{1}{9}\begin{bmatrix} 1 & 1 & 1 \\ 1 & 1 & 1 \\ 1 & 1 & 1 \end{bmatrix}$$
Every product is $1/9$ times its pixel. Eight pixels are 10 and one is 90:
$$\frac{1}{9}(8 \cdot 10 + 90) = \frac{170}{9} \approx 18.9$$
The center output drops from 90 to about 19, so the bright spot fades into its neighbors.

The same patch through an edge kernel
Now run the same patch $P$ through a vertical-edge kernel:
$$K = \begin{bmatrix} -1 & 0 & 1 \\ -1 & 0 & 1 \\ -1 & 0 & 1 \end{bmatrix}$$
The left column contributes $-1 \cdot (10 + 10 + 10) = -30$. The center column contributes $0$, and the right column contributes $+1 \cdot (10 + 10 + 10) = 30$:
$$-30 + 0 + 30 = 0$$
The output is 0 because the left and right sides of the patch have the same total. The patch and the operation are the same as before, and only the weights changed. The answer went from a smoothed value to an edge score of zero.

Convolution in PyTorch
F.conv2d is PyTorch's 2D convolution function. It expects the input shaped (N, C, H, W): batch size, channels, height and width. It expects the weights shaped (out_ch, in_ch, kH, kW): output channels, input channels and the kernel's height and width.
import torch
import torch.nn.functional as F
x = torch.tensor(
[[10., 10, 10],
[10, 90, 10],
[10, 10, 10]]).view(1, 1, 3, 3)
k = (torch.ones(3, 3) / 9).view(1, 1, 3, 3)
out = F.conv2d(x, k) # no padding
# torch.Size([1, 1, 1, 1]) 18.888...
print(out.shape, out.item())
out_same = F.conv2d(x, k, padding=1) # keep 3x3
# torch.Size([1, 1, 3, 3])
print(out_same.shape)With a 3 by 3 input, a 3 by 3 kernel and no padding, the kernel fits in one position. The output is a single value of 18.89. That matches the hand calculation. A 3 by 3 box blur that keeps the image size, as a function:
def blur3x3(x):
k = torch.ones(3, 3) / 9
k = k.view(1, 1, 3, 3)
return F.conv2d(x, k, padding=1)What the nine weights decide
The operation is the same every time: slide, multiply and add. What makes one filter a blur and another an edge detector is the kernel. A 3 by 3 kernel's nine numbers fully define what the filter does.
The simplest kernel has 1 in the center and 0 everywhere else:
$$K = \begin{bmatrix} 0 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 0 \end{bmatrix}$$
It copies the input unchanged, since each output pixel equals its own input pixel. That makes it a useful reference point.

Why blur weights sum to 1
A blur kernel has equal positive weights that sum to 1:
$$K = \frac{1}{9}\begin{bmatrix} 1 & 1 & 1 \\ 1 & 1 & 1 \\ 1 & 1 & 1 \end{bmatrix}$$
Each output is the average of its 3 by 3 window, which smooths the image. The weights sum to 1 so that a flat region keeps its value: a patch of all 50s gives $(1/9)(50 \cdot 9) = 50$. If the weights summed to 0.8 instead, a flat region of 50 would come out at 40 and the whole image would darken.
An edge kernel's weights sum to 0. A flat region then comes out near zero, and only changes show up.

Sharpening a pixel
A sharpen kernel boosts the center against its four nearest neighbors:
$$K = \begin{bmatrix} 0 & -1 & 0 \\ -1 & 5 & -1 \\ 0 & -1 & 0 \end{bmatrix}$$
Its weights sum to $5 - 4 = 1$, so flat regions stay the same. On the patch with a center of 90 and four neighbors of 10:
$$5 \cdot 90 + 4 \cdot (-1) \cdot 10$$
$$= 450 - 40 = 410$$
The center jumps from 90 to 410 and then clips to 255, the largest value an 8-bit pixel can hold. Sharpening widens the gap between a pixel and its neighbors, which also makes noise stronger.

Weight signs
A kernel with positive weights on one side and negative weights on the other computes a difference across the patch. The edge kernel above subtracts the left column from the right, so its output is large where the image changes from left to right. Where the image is flat, the output is near zero.
Positive weights add a region's values, and negative weights subtract them. Summing a patch gives a blur. Taking the difference of two halves gives an edge, and boosting the center gives sharpening.

Hand-designed to learned
A classical filter designer picks the weights from knowing what pattern to find. A neural network for images starts with random weights and adjusts them during training until they pick out useful patterns. The calculation is the same, and only the source of the numbers differs.

Padding
A 3 by 3 kernel centered on a border pixel hangs one row or column off the image. Padding fills those missing slots, and the choice is which values to use. Take the row $[5, 8, 20]$ and add one value at each end:
$$\text{zeros: } [\,0,\ 5,\ 8,\ 20,\ 0\,]$$
$$\text{replicate: } [\,5,\ 5,\ 8,\ 20,\ 20\,]$$
$$\text{reflect: } [\,8,\ 5,\ 8,\ 20,\ 8\,]$$
Zero padding adds zeros. Replicate padding repeats the edge value, and reflect padding mirrors the values next to the edge. Valid filtering skips padding and returns a smaller output. Same filtering pads enough to keep the output the size of the input.

Padding modes and the dark fringe
Average three values at the first position of $[5, 8, 20]$, once for each way of filling the missing left slot:
- zeros: $(0 + 5 + 8) / 3 \approx 4.3$
- replicate: $(5 + 5 + 8) / 3 = 6.0$
- reflect: $(8 + 5 + 8) / 3 = 7.0$
Zero padding pulls border values down toward the made-up zero. On a flat row of all 100s, the first pixel of a 3-wide average drops to about 67 while the interior stays at 100. That darker band along the edge biases any measurement taken near the border.

Padding in code
import torch
import torch.nn.functional as F
row = torch.tensor([5, 8, 20], dtype=torch.float32)
# tensor([ 0., 5., 8., 20., 0.])
print(F.pad(row, (1, 1), mode='constant'))
# tensor([ 5., 5., 8., 20., 20.])
print(F.pad(row[None, None], (1, 1), mode='replicate')[0, 0])
# tensor([ 8., 5., 8., 20., 8.])
print(F.pad(row[None, None], (1, 1), mode='reflect')[0, 0])Replicate and reflect padding do not accept a bare 1D row, so those two calls pad row[None, None], which adds a batch and a channel dimension. Constant padding takes the bare row. In 2D, F.pad(img, (1, 1, 1, 1), mode='reflect') adds a one-pixel border on all four sides.

Stride
Stride is how far the kernel moves between positions. With stride 1 it visits every position, and with padding the output keeps the input size. With stride 2 it visits every other position, which gives an output about half the width and half the height. That cuts compute and memory by roughly the square of the stride.

For example, take a row of eight positions numbered 0 to 7, a kernel of size 3 and no padding. Stride 1 starts the kernel at positions 0 through 5, which gives 6 outputs. Stride 2 starts it at 0, 2 and 4, which gives 3 outputs.

The output-shape formula
The output size along one axis is:
$$\left\lfloor \frac{H + 2p - k}{s} \right\rfloor + 1$$
Here $H$ is the input size and $p$ is the padding added at each end. $k$ is the kernel size and $s$ is the stride. The brackets $\lfloor\ \rfloor$ round down to a whole number. The row of eight checks out: $\lfloor (8 - 3) / 2 \rfloor + 1 = \lfloor 2.5 \rfloor + 1 = 3$.
Take a 224 by 224 input with $k = 3$, $p = 1$ and $s = 1$:
$$\lfloor (224 + 2 - 3) / 1 \rfloor + 1 = 224$$
Use the same input with $k = 3$, $p = 1$ and $s = 2$:
$$\lfloor (224 + 2 - 3) / 2 \rfloor + 1$$
$$= \lfloor 111.5 \rfloor + 1 = 112$$
Stride 1 with $p = 1$ keeps the size, and stride 2 halves it. In code:
def conv_out_size(H, k, p, s):
padded = H + 2 * p
steps = (padded - k) // s
return steps + 1
print(conv_out_size(224, 3, 1, 1), conv_out_size(224, 3, 1, 2))
# 224 112
Support and receptive field
The support of a filter is how many input pixels one application reads directly. A 3 by 3 kernel has 3 by 3 support.
The receptive field of an output pixel is the whole region of the original image that can affect it. For a single filter it equals the support. For a stack of filters, where each one runs on the output of the one before, it grows.

Stacking 3 by 3 layers
Each 3 by 3 layer adds 2 to the width of the receptive field and 2 to its height. Starting from a single pixel:
- after layer 1: $1 + 2 = 3$, so 3 by 3
- after layer 2: $3 + 2 = 5$, so 5 by 5
- after layer 3: $5 + 2 = 7$, so 7 by 7
- after layer 4: $7 + 2 = 9$, so 9 by 9
Two 3 by 3 layers see the same 5 by 5 region as one 5 by 5 layer, with $2 \cdot 3 \cdot 3 = 18$ weights instead of $5 \cdot 5 = 25$. In code, for a stack of num_layers layers with kernel size k and stride 1:
def receptive_field(num_layers, k):
grow = k - 1
total = num_layers * grow
return 1 + total
print([receptive_field(n, 3) for n in (1, 2, 3, 4)])
# [3, 5, 7, 9]
One 7 by 7 filter reads a 7 by 7 region in a single step, at the cost of more weights and more compute. A stack of small filters reaches the same region step by step. No single small filter looks at the whole image, and a deep enough stack still gives its last layer a receptive field that covers most of it.

When to use what, and common mistakes
Use convolution whenever each output pixel should depend on a small neighborhood: blurring, sharpening and edge detection. Pick padding by what should happen at the border, with reflect or replicate when edge measurements need to stay unbiased. Use stride 2 when you want a smaller output and can give up detail.
- Leaving a blur kernel unnormalized. Weights that sum to 0.8 darken the whole image, and weights that sum to more than 1 brighten it.
- Zero padding before measuring near the border. The made-up zeros pull border values down. Reflect or replicate padding avoids the dark fringe.
- Forgetting the batch and channel dimensions.
F.conv2dneeds the input as(N, C, H, W)and the kernel as(out_ch, in_ch, kH, kW), so a plain 3 by 3 tensor needs.view(1, 1, 3, 3). - Getting the output size wrong. Run the formula before wiring layers together, and remember that it rounds down.
- Sharpening a noisy image. A sharpen kernel makes noise stronger along with the edges.
Related concepts
Convolution is a neighborhood operator. Classical image processing covers point operators, which read one pixel at a time. Image blurring and denoising uses box and Gaussian kernels to remove noise. It also covers the median filter, which cannot be written as a kernel.
QuiddityML teaches convolution and the output-shape formula in the classical image processing unit of its Computer Vision track, where the exercises include tracing a convolution by hand and writing the formula as code (QuiddityML).