Convolution and Image Filtering
Introduction
Spatial filtering is one of the oldest ideas in signal processing and computer vision. In first-order filters, we shaped a one-dimensional signal over time by blending nearby samples. Here we extend that idea to discrete sliding-window filters—starting from 1D convolution and cross-correlation, extending both operations onto a 2D grid of pixels, and deriving the classic image kernels for smoothing noise, detecting edges, and sharpening local contrast. These operations also form the foundation of convolutional neural networks, though there we permit the optimization to learn custom filters by hand to pick up the features required for the task.
From 1D Filtering to 2D Convolution
In discrete time, a finite impulse response (FIR) filter slides a short window of weights along an input sequence , multiplying aligned samples and summing:
We call the weights the kernel. The kernel is the filter’s impulse response: if the input is a unit impulse, , then
because only the term with is not zero.
Why is there a minus sign in ? Because the kernel measures how much a spike still affects the output steps after it arrived (i.e. the impulse response). Suppose has three weights, . At step , today’s input gets the immediate weight , yesterday’s input gets , and from two steps ago gets :
Notice the order from left to right: on the axis, runs oldest to newest (), whereas is written newest to oldest ( steps ago). Pairing each input with its matching age puts underneath —which is why convolution flips the kernel horizontally before sliding it across .
If we drop that flip and slide directly as written, the operation is called 1D cross-correlation:
The cross-correlation tells us how similar two signals are when time-shifted by different values relative to each other - higher values mean higher overlap between two signals at a given shift.
Let’s explore a small visual of convolution and cross-correlation before proceeding:
- With impulse and asymmetric ramp
[1, 2, 4], dragmfrom0to12(or hit Play): under convolution (*) the window slides right-to-left across the impulse at and reproduces[1, 2, 4]along the output axis, whereas under cross-corr (⋆) it slides left-to-right and leaves[4, 2, 1]. - Switch Signal to 1D bright bar and Kernel to diff
[−1, 0, +1]: the output stays across both dark and bright interiors and spikes solely at the two boundaries.
Extending from a 1D Row to a 2D Grid
An image is simply a stack of those 1D rows indexed by two spatial coordinates: row (top to bottom) and column (left to right). Given a grayscale image and a small 2D kernel , two-dimensional discrete convolution flips the kernel along both axes before sliding it across the image:
Equivalently, if we define the -rotated kernel by reversing both row and column indices,
then simply slides across . Here is implicitly outside its grid, so only terms contribute. Near the image borders, we either evaluate only positions where the kernel fits entirely inside (valid convolution, turning the grid below into ) or treat out-of-bounds entries of as (zero-padding).
Omitting the flips gives 2D cross-correlation:
Every spatial output entry is just an inner product (Frobenius dot product) between the image patch anchored at and the kernel . Where the image patch resembles the pattern stored in , their signs align and the dot product is large and positive; where the patch has the opposite polarity, the dot product is strongly negative; where they are unrelated, terms cancel near zero.
When I first learned convolutional neural
networks, one terminology quirk
bothered me: PyTorch’s nn.Conv2d, TensorFlow, and virtually every deep learning paper actually
compute cross-correlation (), yet everyone calls it convolution. Why does signal
processing flip the kernel while deep learning uses cross-correlation instead?
In classical signal processing, is a fixed physical impulse response, and the minus sign is essential: it ensures , makes convolution commutative (), and turns spatial convolution into pointwise multiplication in the Fourier domain. In a neural network, none of those properties are needed because is a learned parameter tensor initialized at random—learning under cross-correlation represents the exact same family of filters as learning under convolution. Given that freedom, frameworks choose cross-correlation for two practical reasons:
- Contiguous memory indexing: both the image patch
X[i + u, j + v]and kernelK[u, v]step forward in memory (+u, +v), turning each patch evaluation into a direct dot product during forward passes or inference. - Intuitive template matching:
K[0, 0]multiplies the top-left of the image patch rather than the bottom-right, so the weights stored inconv.weightlook visually identical to the feature they detect instead of rotated.
Still, we cannot dodge the flip altogether: just as backpropagating through requires the transpose , transposing a sliding-window operator always reverses its window—so whichever operation runs forward, backpropagation runs the opposite one and flips the kernel anyway!
Play around with a small interactive 2D convolution example below:
Input (5×5)
Kernel (3×3)
Patch ⊙ K
Output Y (3×3)
Basic Kernels
Before letting an optimizer invent hundreds of filters, it pays to inspect a handful of classic kernels by hand. They give concrete intuition for what local spatial templates compute—smoothing noise, finding edges, or boosting local contrast—and the first layer of a CNN trained on natural photographs tends to discover related primitives, especially oriented wave-like edge templates (Gabor filters) and opposing color blobs (such as red-green or blue-yellow patches).
Smoothing and Low-Pass Kernels
Smoothing (low-passing) is a popular task in classical signal processing. For example, if camera pixels carry some independent zero-mean readout noise, we can smooth it to reduce the perceptible noise in the image. On a image, replacing each pixel by a weighted average of its neighborhood averages that noise down:
Notice two structural properties here:
- All weights are nonnegative and sum to (). On any flat patch where every pixel has intensity , the output is . Constant brightness passes through unchanged—in signal-processing terms, the filter has unit DC gain.
- Noise variance shrinks. For independent noise of variance , the output variance becomes , which drops to for the box filter and for the Gaussian.
First-Derivative and Sobel Edge Kernels
To locate boundaries or edges in images, we care about where intensity changes rather than the absolute level of the pixel; we are looking for where the derivative is greatest. Along a row, the symmetric finite-difference approximation to the horizontal derivative is
which corresponds to the 1D kernel under cross-correlation. Differentiating raw noisy pixels, however, amplifies high-frequency speckle. The Sobel operators pair finite differencing along one axis with Gaussian smoothing along the perpendicular axis:
Look at the sum of entries now: . On any patch of uniform brightness —whether pitch black () or sunlit concrete ()—the positive and negative halves cancel identically to zero. A zero-sum kernel is blind to DC brightness offsets and responds purely to local contrast:
- fires positively on dark-to-light left-to-right transitions (left edge of a bright bar) and negatively on light-to-dark transitions (right edge of that bar). Because the transition happens across columns, detects vertical edges.
- differentiates top-to-bottom across rows, detecting horizontal edges.
Together, estimate the spatial image gradient , from which classical vision computes edge strength and edge normal angle .
Second-Derivative and Sharpening Kernels
A second derivative measures how much the slope itself changes across pixel . Comparing the step to the right, , against the step from the left, , gives the 1D second difference :
Doing the same vertically gives , and summing the horizontal and vertical stencils (so their center weights add to ) produces the discrete Laplacian :
Notice what computes when rewritten as , where is the average of the four adjacent pixels: it is on flat regions, positive on the dark side of an edge (where neighbors are brighter than the center), and negative on the bright side of an edge (where neighbors are darker). Adding a small multiple of pulls every pixel toward its neighbors—which is literally blurring.
To sharpen an image, we do the exact opposite: we subtract the Laplacian from the original image, pushing pixels on the bright side of an edge brighter and pixels on the dark side darker while leaving flat regions unchanged. Writing out directly at pixel gives
Reading those weights straight off ( on the center pixel and on each of its four neighbors) gives the sharpening kernel:
whose entries sum to , meaning that the kernel preserves the original image brightness while amplifying local contrast across edges.
Try these kernels on a simulated downward landing-pad camera below:
- Keep
sobel xselected on thelanding padscene: the left wall of each vertical leg of theHglows purple () while the right wall glows coral (), and the horizontal crossbar vanishes almost completely. Switch tosobel yand the horizontal crossbar lights up instead. Recall that depending on the direction the filter is applied, it will pick up either horizontal or vertical features. - Drag Sensor noise up to
0.22and comparelaplacian(second derivatives dramatically amplify pixel noise) againstgaussian(smooths the tarmac while keeping theHintact). You can also edit any entry of the matrix directly.
Input image X
Output Y = X ⋆ K
1D intensity slice along dashed scanline
Hand-crafted kernels work cleanly when we know the exact behaviour we want such as averaging out noise, differentiating across edges, or boosting local contrast. Recognizing complex visual concepts like handwritten digits, faces, or vehicles, however, requires considerably more complex filters that are intractable to craft by hand. We explore this further in Convolutional Neural Networks.