QuiddityML

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.

Computer VisionBy · 3 December 2026 · 12 min read

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.

A 7 by 7 patch of pixel values with a 3 by 3 window outlined, its nine values averaged to 515 over 9, about 57, giving one output pixel.

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 at columns 0, 1 and 2 of a 5 by 7 input, each position writing its window sum (40, 40, 36) into the 3 by 5 output.

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.

A 3 by 3 window of an image multiplied element by element with a plus-shaped pattern of 1s, giving the sum 12.

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.

The pattern 1, 0, 1 placed at offsets 0, 1 and 2 of the row 10, 90, 10, 90, 10, with the products and sums 20, 180 and 20.

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.

The input row, the pattern and the output row 90, 20, 180, 20, 90, with the middle three values marked as matching the hand trace.

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.

A symmetric blur kernel is the same after flipping both ways, and the edge kernel -1, 0, 1 becomes 1, 0, -1, which flips the sign of its output.

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.

Each of the nine pixels times 1/9, summed to 170/9, about 18.9, and a dark image with one bright pixel turning into a faint 3 by 3 square after the blur.

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.

The vertical edge kernel, the patch with 90 in the center, the column contributions -30, 0 and +30, and the output 0.

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.

The identity kernel, a 3 by 3 grid of zeros with a 1 in the center, which copies the input.

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.

Three cases: weights summing to 1 keep a flat patch of 50 at 50, weights summing to 0.8 turn it into 40, and an edge kernel summing to 0 gives about 0.

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.

The sharpen kernel with 5 in the center and -1 on its four neighbors, and the result 450 - 40 = 410, clipped to 255.

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.

The blur, edge and sharpen kernels side by side, labelled summing a patch, differencing two halves and boosting the center.

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.

The hand-chosen edge kernel -1, 0, 1 next to a network kernel that starts with small random values and, after training, ends up close to an edge kernel.

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.

A 3 by 3 grid of 1 to 9 padded with zeros, with reflected values and with replicated values, and the two modes valid (smaller output) and same (matches 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.

The row 5, 8, 20 padded with 0, 5 or 8 on the left, and the first three-value averages 4.3, 6.0 and 7.0.

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.

F.pad's constant, replicate and reflect modes on the row 5, 8, 20, giving 0 and 0, 5 and 20, and 8 and 8 at the ends.

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.

An 8 by 8 input with padding: stride 1 computes all 64 positions for an 8 by 8 output, and stride 2 computes 16 positions for a 4 by 4 output, 4 times fewer.

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.

A row of 8 elements with window starts 0 to 5 at stride 1 (6 outputs) and 0, 2, 4 at stride 2 (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

The formula floor((H + 2p - k) / s) + 1 worked step by step for k = 3, p = 1 at stride 1 (224) and stride 2 (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.

A 5 by 5 input with a 3 by 3 region outlined around the center: everything that can influence one output pixel of a single 3 by 3 filter.

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]

A 9 by 9 pixel grid with nested outlines of 3 by 3, 5 by 5, 7 by 7 and 9 by 9 after one to four layers, and two 3 by 3 kernels (18 weights) next to one 5 by 5 kernel (25 weights).

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.

Five stacked layers over the same grid, with the outlined region one output can see growing at each layer.

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.conv2d needs 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.

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).