Notes / Signal Processing

Convolution and Image Filtering

Updated

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 3×33 \times 3 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 k[m]k[m] along an input sequence x[n]x[n], multiplying aligned samples and summing:

(x∗k)[n]=∑mx[n−m] k[m].(x * k)[n] = \sum_{m} x[n - m]\, k[m].

We call the weights k[m]k[m] the kernel. The kernel is the filter’s impulse response: if the input is a unit impulse, x[n]=δ[n]x[n] = \delta[n], then

(x∗k)[n]=∑mδ[n−m] k[m]=k[n],(x * k)[n] = \sum_m \delta[n - m]\, k[m] = k[n],

because only the term with m=nm = n is not zero.

Why is there a minus sign in x[n−m]x[n - m]? Because the kernel k[m]k[m] measures how much a spike still affects the output mm steps after it arrived (i.e. the impulse response). Suppose kk has three weights, [k[0], k[1], k[2]][k[0],\, k[1],\, k[2]]. At step nn, today’s input x[n]x[n] gets the immediate weight k[0]k[0], yesterday’s input x[n−1]x[n - 1] gets k[1]k[1], and x[n−2]x[n - 2] from two steps ago gets k[2]k[2]:

(x∗k)[n]=x[n−2] k[2]+x[n−1] k[1]+x[n] k[0].(x * k)[n] = x[n - 2]\,k[2] + x[n - 1]\,k[1] + x[n]\,k[0].

Notice the order from left to right: on the axis, xx runs oldest to newest (x[n−2], x[n−1], x[n]x[n - 2],\, x[n - 1],\, x[n]), whereas k=[k[0], k[1], k[2]]k = [k[0],\, k[1],\, k[2]] is written newest to oldest (0,1,20, 1, 2 steps ago). Pairing each input with its matching age puts [k[2], k[1], k[0]][k[2],\, k[1],\, k[0]] underneath [x[n−2], x[n−1], x[n]][x[n - 2],\, x[n - 1],\, x[n]]—which is why convolution flips the kernel horizontally before sliding it across xx.

If we drop that flip and slide kk directly as written, the operation is called 1D cross-correlation:

(x⋆k)[n]=∑mx[n+m] k[m](x \star k)[n] = \sum_m x[n + m]\,k[m]

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 δ\delta and asymmetric ramp [1, 2, 4], drag m from 0 to 12 (or hit Play): under convolution (*) the window slides right-to-left across the impulse at 55 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 00 across both dark and bright interiors and spikes solely at the two boundaries.
1D Sliding Filter: Convolution (*) vs. Cross-Correlation (⋆)(x * k)[n] = ∑ x[n − m] k[m]
Signal x
Kernel k
Operation

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 ii (top to bottom) and column jj (left to right). Given a grayscale image X∈RH×WX \in \mathbb{R}^{H \times W} and a small 2D kernel K∈Rkh×kwK \in \mathbb{R}^{k_h \times k_w}, two-dimensional discrete convolution flips the kernel along both axes before sliding it across the image:

(X∗K)[i,j]=∑u∑vX[i−u, j−v] K[u,v].(X * K)[i, j] = \sum_{u} \sum_{v} X[i - u,\, j - v]\, K[u, v].

Equivalently, if we define the 180∘180^\circ-rotated kernel K~∈Rkh×kw\tilde K \in \mathbb{R}^{k_h \times k_w} by reversing both row and column indices,

K~[u,v]=K[kh−1−u, kw−1−v],\tilde K[u, v] = K[k_h - 1 - u,\, k_w - 1 - v],

then X∗KX * K simply slides K~\tilde K across XX. Here K[u,v]K[u, v] is implicitly 00 outside its kh×kwk_h \times k_w grid, so only kh⋅kwk_h \cdot k_w terms contribute. Near the image borders, we either evaluate only positions where the kernel fits entirely inside XX (valid convolution, turning the 5×55 \times 5 grid below into 3×33 \times 3) or treat out-of-bounds entries of XX as 00 (zero-padding).

Omitting the flips gives 2D cross-correlation:

(X⋆K)[i,j]=∑u=0kh−1∑v=0kw−1X[i+u, j+v] K[u,v].(X \star K)[i, j] = \sum_{u=0}^{k_h - 1} \sum_{v=0}^{k_w - 1} X[i + u,\, j + v]\, K[u, v].

Every spatial output entry Y[i,j]Y[i, j] is just an inner product (Frobenius dot product) between the kh×kwk_h \times k_w image patch anchored at (i,j)(i, j) and the kernel KK. Where the image patch resembles the pattern stored in KK, 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 (X⋆K+bX \star K + b), yet everyone calls it convolution. Why does signal processing flip the kernel while deep learning uses cross-correlation instead?

In classical signal processing, KK is a fixed physical impulse response, and the minus sign is essential: it ensures (X∗δ)=X(X * \delta) = X, makes convolution commutative (X∗K=K∗XX * K = K * X), and turns spatial convolution into pointwise multiplication in the Fourier domain. In a neural network, none of those properties are needed because KK is a learned parameter tensor initialized at random—learning KK under cross-correlation represents the exact same family of filters as learning K~\tilde K under convolution. Given that freedom, frameworks choose cross-correlation for two practical reasons:

  1. Contiguous memory indexing: both the image patch X[i + u, j + v] and kernel K[u, v] step forward in memory (+u, +v), turning each patch evaluation into a direct dot product during forward passes or inference.
  2. Intuitive template matching: K[0, 0] multiplies the top-left of the image patch rather than the bottom-right, so the weights stored in conv.weight look visually identical to the feature they detect instead of 180∘180^\circ rotated.

Still, we cannot dodge the flip altogether: just as backpropagating through y=Mxy = M x requires the transpose M⊤M^\top, 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:

2D Cross-Correlation Playground5×5 ⋆ 3×3 → 3×3
Kernel
Padding
Stride

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 3×33\times 3 image, replacing each pixel by a weighted average of its 3×33 \times 3 neighborhood averages that noise down:

Kbox=19[111111111],Kgauss=116[121242121].K_{\text{box}} = \frac{1}{9} \begin{bmatrix} 1 & 1 & 1 \\ 1 & 1 & 1 \\ 1 & 1 & 1 \end{bmatrix}, \qquad K_{\text{gauss}} = \frac{1}{16} \begin{bmatrix} 1 & 2 & 1 \\ 2 & 4 & 2 \\ 1 & 2 & 1 \end{bmatrix}.

Notice two structural properties here:

  • All weights are nonnegative and sum to 11 (∑u,vK[u,v]=1\sum_{u,v} K[u, v] = 1). On any flat patch where every pixel has intensity cc, the output is c∑u,vK[u,v]=cc \sum_{u,v} K[u, v] = c. Constant brightness passes through unchanged—in signal-processing terms, the filter has unit DC gain.
  • Noise variance shrinks. For independent noise of variance σ2\sigma^2, the output variance becomes σ2∑u,vK[u,v]2\sigma^2 \sum_{u,v} K[u, v]^2, which drops to σ2/9\sigma^2 / 9 for the box filter and 36σ2/256≈0.14 σ236\sigma^2 / 256 \approx 0.14\,\sigma^2 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

∂X∂x[i,j]≈X[i,j+1]−X[i,j−1]2,\frac{\partial X}{\partial x}[i, j] \approx \frac{X[i, j+1] - X[i, j-1]}{2},

which corresponds to the 1D kernel 12[−1,0,+1]\frac{1}{2}[-1, 0, +1] under cross-correlation. Differentiating raw noisy pixels, however, amplifies high-frequency speckle. The Sobel operators pair finite differencing along one axis with [1,2,1][1, 2, 1] Gaussian smoothing along the perpendicular axis:

Kx=[−10+1−20+2−10+1],Ky=[−1−2−1+0+0+0+1+2+1].K_x = \begin{bmatrix} -1 & 0 & +1 \\ -2 & 0 & +2 \\ -1 & 0 & +1 \end{bmatrix}, \qquad K_y = \begin{bmatrix} -1 & -2 & -1 \\ \phantom{+}0 & \phantom{+}0 & \phantom{+}0 \\ +1 & +2 & +1 \end{bmatrix}.

Look at the sum of entries now: ∑u,vKx[u,v]=0\sum_{u,v} K_x[u, v] = 0. On any patch of uniform brightness cc—whether pitch black (c=0c = 0) or sunlit concrete (c=250c = 250)—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:

  • Gx=X⋆KxG_x = X \star K_x 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, KxK_x detects vertical edges.
  • Gy=X⋆KyG_y = X \star K_y differentiates top-to-bottom across rows, detecting horizontal edges.

Together, (Gx,Gy)(G_x, G_y) estimate the spatial image gradient ∇X\nabla X, from which classical vision computes edge strength ∥∇X∥=Gx2+Gy2\|\nabla X\| = \sqrt{G_x^2 + G_y^2} and edge normal angle atan2⁡(Gy,Gx)\operatorname{atan2}(G_y, G_x).

Second-Derivative and Sharpening Kernels

A second derivative measures how much the slope itself changes across pixel (i,j)(i, j). Comparing the step to the right, X[i,j+1]−X[i,j]X[i, j+1] - X[i, j], against the step from the left, X[i,j]−X[i,j−1]X[i, j] - X[i, j-1], gives the 1D second difference [1,−2,1][1, -2, 1]:

∂2X∂x2[i,j]≈(X[i,j+1]−X[i,j])⏟right slope−(X[i,j]−X[i,j−1])⏟left slope=X[i,j−1]−2X[i,j]+X[i,j+1].\frac{\partial^2 X}{\partial x^2}[i, j] \approx \underbrace{(X[i, j+1] - X[i, j])}_{\text{right slope}} - \underbrace{(X[i, j] - X[i, j-1])}_{\text{left slope}} = X[i, j-1] - 2X[i, j] + X[i, j+1].

Doing the same vertically gives X[i−1,j]−2X[i,j]+X[i+1,j]X[i-1, j] - 2X[i, j] + X[i+1, j], and summing the horizontal [1,−2,1][1, -2, 1] and vertical [1,−2,1]⊤[1, -2, 1]^\top stencils (so their center weights add to −2+(−2)=−4-2 + (-2) = -4) produces the discrete Laplacian ∇2X=∂2X∂x2+∂2X∂y2\nabla^2 X = \frac{\partial^2 X}{\partial x^2} + \frac{\partial^2 X}{\partial y^2}:

K∇2=[0−101−410−10].K_{\nabla^2} = \begin{bmatrix} 0 & \phantom{-}1 & 0 \\ 1 & -4 & 1 \\ 0 & \phantom{-}1 & 0 \end{bmatrix}.

Notice what (X⋆K∇2)[i,j](X \star K_{\nabla^2})[i, j] computes when rewritten as 4 (Xneighbors−X[i,j])4\,(X_{\text{neighbors}} - X[i, j]), where XneighborsX_{\text{neighbors}} is the average of the four adjacent pixels: it is 00 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 K∇2K_{\nabla^2} 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 X[i,j]−(X⋆K∇2)[i,j]X[i, j] - (X \star K_{\nabla^2})[i, j] directly at pixel (i,j)(i, j) gives

X[i,j]−(X[i−1,j]+X[i+1,j]+X[i,j−1]+X[i,j+1]−4 X[i,j])=5 X[i,j]−X[i−1,j]−X[i+1,j]−X[i,j−1]−X[i,j+1].X[i, j] - \big(X[i-1, j] + X[i+1, j] + X[i, j-1] + X[i, j+1] - 4\,X[i, j]\big) = 5\,X[i, j] - X[i-1, j] - X[i+1, j] - X[i, j-1] - X[i, j+1].

Reading those weights straight off (+5+5 on the center pixel and −1-1 on each of its four neighbors) gives the 3×33 \times 3 sharpening kernel:

Ksharpen=[−0−1−0−1−5−1−0−1−0],K_{\text{sharpen}} = \begin{bmatrix} \phantom{-}0 & -1 & \phantom{-}0 \\ -1 & \phantom{-}5 & -1 \\ \phantom{-}0 & -1 & \phantom{-}0 \end{bmatrix},

whose entries sum to 5−4=15 - 4 = 1, 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 x selected on the landing pad scene: the left wall of each vertical leg of the H glows purple (+1+1) while the right wall glows coral (−1-1), and the horizontal crossbar vanishes almost completely. Switch to sobel y and 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 σ\sigma up to 0.22 and compare laplacian (second derivatives dramatically amplify pixel noise) against gaussian (smooths the tarmac while keeping the H intact). You can also edit any entry of the 3×33 \times 3 matrix directly.
Spatial Filter Playground
Scene
Preset
Editable 3×3 weights

Input image X

Output Y = X ⋆ K

1D intensity slice along dashed scanline

Hand-crafted 3×33 \times 3 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.