Linear Filters

A linear filter modifies an image by replacing each pixel with a weighted sum of pixel intensities in a local neighborhood. The weights form the kernel (or filter mask) , a array indexed by offsets . The same weights are used at every pixel. The operation is linear, meaning . It is also shift-invariant: shifting the input shifts the output by the same amount. Every linear, shift-invariant operation on images is a convolution with some kernel.

Let be the input image and the output. Cross-correlation, written , slides the kernel over the image without flipping it:

Convolution, written , flips the kernel in both directions (a rotation) before sliding it:

In both formulas is the row and the column of the output pixel. The two operations agree whenever , as for box and Gaussian kernels. Convolution is commutative and associative. Cross-correlation is neither.

The unit impulse has a at the center and elsewhere, and it leaves the image unchanged. A single away from the center shifts the image. The box filter replaces each pixel by the mean of its neighborhood. The Gaussian filter weights neighbors by their distance from the center:

Here is the offset from the center, and the standard deviation , in pixels, sets the amount of smoothing. A discrete Gaussian kernel uses a half-width of about and is renormalized to sum to . Smoothing kernels have nonnegative weights that sum to . Derivative kernels have positive and negative weights that sum to .

For an image and an kernel (), the output is in full mode, in same mode, and in valid mode. Full and same modes need values outside the image. These come from zero padding (clip filter, black), wrap-around (circular), copy edge, or reflect across edge. Median filtering, thresholding, absolute values and squaring are not linear filters.

Notation Across the Slides

The filtering slides write for the image, for the kernel and for the output. They use for cross-correlation and for convolution. The slides on sharpening and template matching switch to for the image, for the kernel or template, and for the output. The letter also names the Gaussian. Read each formula with its own legend.

Two Slide Typos

One Gaussian-filtering slide writes the exponent as . The normalized 2D Gaussian with standard deviation has in the denominator, as on the following slide. The output-size slide says the full output is the “sum” and the valid output the “difference” of the image and kernel sizes. The exact sizes are and .

Intuition

Many basic image edits are local. A blur replaces each pixel with an average of its neighbors. An edge detector compares each pixel with the pixel beside it. In both cases the rule is a weighted sum over a small window, and the rule is the same everywhere in the image. In 1D the simplest case is a moving average. The weights replace each sample by the mean of five samples. Bell-shaped weights such as give nearer samples more influence. The output at one pixel is the inner product of the kernel with the image patch under it. “Linear” means the output depends linearly on the input image. “Filter” comes from signal processing, where a filter passes some frequencies and blocks others.

Linearity and shift invariance mean the kernel describes the filter completely. A filter of this kind is an LTI system, and its impulse response is its kernel. Feeding a single bright pixel into a convolution returns a copy of . Feeding it into a cross-correlation returns rotated by . Cross-correlation is the natural “compare the kernel with this patch” operation, and template matching uses it in that sense. Convolution flips the kernel so that the impulse response is itself. The flip makes convolution commutative and associative, and it makes the convolution theorem of the Fourier transform hold. The diagram shows which kernel weight meets which pixel in each case.

\usepackage{tikz}
\begin{document}
\definecolor{kern}{HTML}{2F80ED}
\definecolor{flip}{HTML}{D9483B}
\definecolor{mid}{HTML}{8A8A8A}
\begin{tikzpicture}[x=1.6cm,y=1cm,>=latex,font=\small]
\foreach \i/\lab in {-1/{F[i-1]},0/{F[i]},1/{F[i+1]}} {
  \draw[mid,thick] (\i-0.4,0) rectangle (\i+0.4,0.7);
  \node at (\i,0.35) {$\lab$};
}
\node[mid,left] at (-1.5,0.35) {image row};
\foreach \i/\lab in {-1/{H[-1]},0/{H[0]},1/{H[1]}} {
  \draw[kern,thick] (\i-0.4,1.6) rectangle (\i+0.4,2.3);
  \node[kern] at (\i,1.95) {$\lab$};
  \draw[->,kern] (\i,1.6) -- (\i,0.75);
}
\node[kern,left] at (-1.5,1.95) {cross-correlation};
\node[kern,right] at (1.5,1.95) {$G[i] = \sum_u H[u]\,F[i+u]$};
\foreach \i/\lab in {-1/{H[1]},0/{H[0]},1/{H[-1]}} {
  \draw[flip,thick] (\i-0.4,-1.6) rectangle (\i+0.4,-0.9);
  \node[flip] at (\i,-1.25) {$\lab$};
  \draw[->,flip] (\i,-0.9) -- (\i,-0.05);
}
\node[flip,left] at (-1.5,-1.25) {convolution};
\node[flip,right] at (1.5,-1.25) {$G[i] = \sum_u H[u]\,F[i-u]$};
\end{tikzpicture}
\end{document}

Properties

(When the Flip Matters) The flip changes the output only for kernels that are not symmetric under a rotation.

Box and Gaussian kernels satisfy , so both operations give identical results. An antisymmetric kernel satisfies , and for it convolution returns the negative of cross-correlation. The derivative kernel is the standard case. A shift kernel changes direction. Cross-correlating with a at , right of center, moves the image one pixel left, and convolving with the same kernel moves it right. Library names follow the math: scipy.signal.convolve2d flips and scipy.signal.correlate2d does not. PyTorch’s conv2d, used in the convolutional layers of CNNs, computes cross-correlation. The flip does not matter there, because the network learns whichever weights it needs.

(Sum Rule) The sum of the kernel weights is the filter’s gain on a constant image.

If everywhere, then at every interior pixel. A blur kernel that sums to therefore leaves flat regions and overall brightness unchanged. A kernel that sums to more than brightens the image, and one that sums to less darkens it. A common bug is a box of ones without the factor . It multiplies the brightness by and saturates almost every pixel to white. Derivative kernels sum to , so they ignore a constant added to the whole image. They are not invariant to contrast, since multiplying the image by multiplies their output by .

(Separable Kernels) A 2D Gaussian is the outer product of two 1D Gaussians, so it can be applied as two 1D passes.

The 2D Gaussian factors as , where is the 1D Gaussian. By associativity, filtering with the 2D kernel equals filtering every row with and then every column with . An kernel costs multiplications per pixel, while two 1D passes cost about . One way to build the 2D kernel is to take a 1D Gaussian, for example from cv2.getGaussianKernel, and form its outer product with itself. The box filter is separable too. A disk-shaped kernel is not.

(Kernel Size) A Gaussian kernel needs a half-width of about , or it starts to behave like a box.

The Gaussian never reaches zero, so every discrete kernel truncates it. At distance from the center the weight is of the center weight. In 1D the interval holds of the Gaussian’s mass. A kernel cut much shorter has a visible jump at its border, and that jump brings back box-like artifacts. After truncation, divide by the sum of the weights so the kernel sums to . Changing without enlarging the kernel produces a different, truncated filter.

(Boundary Artifacts) Each way of inventing pixels beyond the border leaves its own artifact.

The table pads the row by two pixels on each side.

MethodPadded row
Zero padding (clip filter)
Wrap-around (circular)
Copy edge
Reflect across edge

Zero padding pulls blurred borders toward black and creates false edges for derivative filters. Wrap-around mixes the left border with the right one, and it is the boundary that the discrete Fourier transform assumes. Copy edge and reflect usually look the most natural. In scipy.signal.convolve2d the options are boundary='fill' (zeros by default), 'wrap' and 'symm', which reflects with the edge pixel repeated as in the table. np.pad offers mode='edge' for copy edge, and its mode='reflect' omits the edge pixel, giving . Valid mode avoids the choice by dropping every output pixel whose window leaves the image.

(Even-Length Kernels) An even-length kernel has no center pixel, so its same-mode output is offset by half a pixel.

The two-tap difference estimates a derivative halfway between two pixels. In same mode the library must store that value at one of the two neighbors. For the row , correlate2d with puts the response at index , and convolve2d puts at index . The odd kernel is centered on a pixel and has no such ambiguity. This is one reason to prefer it for gradients.

(What Is Not a Convolution) An operation is a convolution only if it is both linear and shift-invariant.

The median filter fails linearity. The medians of and of are both , but the median of their sum is . Gradient magnitude fails too, because it squares its inputs. A blur whose changes across the image is linear but not shift-invariant, so no single kernel describes it. Such operations have no frequency response, and the convolution theorem does not apply to them.

Examples

(Easy) Shifting a Photo by One Pixel

A kernel has a in the middle of its right column and elsewhere, so . It is applied to a image whose entries are in row-major order. The output uses same mode with zero padding.

(Medium) Where the Flip Changes the Answer

A row of a photo crosses from a dark wall to a bright window: , indexed to . The kernel is with , and .

(Hard) Budgeting a Gaussian Blur

A grayscale photo is blurred with a Gaussian of pixels.

See Also