Convolution & correlation

A linear filter replaces every pixel by a weighted sum of its neighborhood. The weights form a small filter kernel that slides over the image. Pick a filter or type your own weights, see which pixels go into one output value, and find out what happens beyond the edge of the image.

Input with border dashed: the real image, click to select a pixel
Filtered

Correlation

The filter ff, also called the kernel, has its origin in the center, so its offsets kk and ll run from −r-r to rr for a (2r+1)×(2r+1)(2r + 1) \times (2r + 1) filter. Placing it over pixel [m,n][m, n] of the image II and adding up the products of weights and pixel values is called correlation:

h[m,n]=∑k,lf[k,l] I[m+k,n+l]h[m, n] = \sum_{k, l} f[k, l] \, I[m + k, n + l]

The same weights are used everywhere, so the filter is linear (filtering with f1+f2f_1 + f_2 gives the sum of the two results) and shift invariant (filtering a shifted image gives the shifted result). Every operation with these two properties can be written this way.

Convolution

Convolution uses the filter flipped horizontally and vertically, i.e. rotated by 180°:

h[m,n]=∑k,lf[k,l] I[m−k,n−l],h=I∗fh[m, n] = \sum_{k, l} f[k, l] \, I[m - k, n - l], \qquad h = I * f

For symmetric filters such as the box or the Gaussian both are identical. For asymmetric ones they are not: a filter with a single 1 at [k,l]=[2,1][k, l] = [2, 1] moves the image by 2 pixels left and 1 up under correlation, and right and down under convolution. The flip gives convolution its useful properties:

Convolving an image with a single bright pixel produces a copy of the filter, which is why ff is also called the impulse response.

Common filters

Filters that average have weights summing to 1, so the overall brightness of the image is preserved.

Boundary handling

Near the edge, part of the filter lies outside the image, and some rule has to supply those values. The left view shows the image extended by that rule:

Applying a filter nn times acts like a single, nn times wider filter (associativity), so the border effects creep further into the image with every pass.

Try this