Skip to content
Tactiverge

Convolution and filters

Slide a small grid of weights across an image to blur away noise or pick out edges, and work through both by hand and in Python.

Lesson 3 of 6 · 35 min · Self-paced · Free

Why look at neighbourhoods

Thresholding looks at one pixel at a time. But a single pixel tells you very little: is that bright dot a real feature or a speck of sensor noise? Is this pixel part of an edge? To answer, you need to look at a pixel together with its neighbours. The tool for that is convolution, and it is the most important operation in image processing. Blurring, sharpening, edge detection and even the first layers of modern neural networks for vision are all built from it.

The idea in one dimension

Start with a row of numbers, like one row of an image or a series of sensor readings:

signal = [10, 10, 10, 90, 10, 10, 50, 50, 50, 50]

The 90 looks like a spike of noise, and there is a genuine step up from 10 to 50 further along. A kernel is a short list of weights. To convolve, you place the kernel over each position, multiply each weight by the value beneath it, and add the results. With the kernel [1/3, 1/3, 1/3], each output is the average of a value and its two neighbours:

signal = [10, 10, 10, 90, 10, 10, 50, 50, 50, 50]
kernel = [1/3, 1/3, 1/3]

smoothed = []
for i in range(1, len(signal) - 1):
    total = 0
    for k in range(3):
        total += kernel[k] * signal[i - 1 + k]
    smoothed.append(round(total, 1))
print(smoothed)

Output:

[10.0, 36.7, 36.7, 36.7, 23.3, 36.7, 50.0, 50.0]

Work through the second output by hand: the kernel covers 10, 10 and 90, so (10 + 10 + 90) ÷ 3 = 36.7. Two things happened. The spike has been flattened from 90 to about 37, which is good. But it has also been spread out over three positions, and the clean step from 10 to 50 has become a ramp. That is the fundamental trade-off of smoothing: it reduces noise and blurs real detail at the same time.

Notice also that the output is two values shorter than the input. At the very ends, the kernel would hang off the edge of the data. Code must decide what to do there: skip those positions (as here), pad with zeros, or repeat the edge values. Every image library makes a choice about borders, and it is worth knowing which.

Two dimensions

For an image, the kernel becomes a small grid, usually 3 × 3. Place its centre over a pixel, multiply each of the nine weights by the pixel underneath, add the nine products, and write the total into the output image. Then slide one pixel along and repeat.

def convolve(img, kernel):
    """Apply a 3 x 3 kernel to every interior pixel (borders are skipped)."""
    out = []
    for r in range(1, len(img) - 1):
        row = []
        for c in range(1, len(img[0]) - 1):
            total = 0
            for kr in range(3):
                for kc in range(3):
                    total += kernel[kr][kc] * img[r - 1 + kr][c - 1 + kc]
            row.append(round(total))
        out.append(row)
    return out

The test image below has a dark region on the left, a bright region on the right, and one noisy speck of 90 in the dark region.

image = [
    [20, 20, 20, 200, 200, 200],
    [20, 20, 20, 200, 200, 200],
    [20, 90, 20, 200, 200, 200],
    [20, 20, 20, 200, 200, 200],
    [20, 20, 20, 200, 200, 200],
]

Blur: the box filter

A box filter gives all nine weights the value 1/9, so each output pixel is the average of its 3 × 3 neighbourhood:

box = [[1/9, 1/9, 1/9],
       [1/9, 1/9, 1/9],
       [1/9, 1/9, 1/9]]

for row in convolve(image, box):
    print(row)

Output:

[28, 88, 140, 200]
[28, 88, 140, 200]
[28, 88, 140, 200]

Check the first value by hand. The neighbourhood of row 1, column 1 holds eight 20s and the speck of 90: (8 × 20 + 90) ÷ 9 = 250 ÷ 9 ≈ 27.8, which rounds to 28. The speck has almost vanished. But look at the boundary: the sharp jump from 20 to 200 is now a gradual slope through 88 and 140. A Gaussian blur, which gives more weight to the centre than to the corners, is a popular gentler alternative that blurs edges a little less for the same noise reduction.

Edges: the Sobel kernel

An edge is a place where brightness changes quickly. To find one, use a kernel whose weights subtract the left side from the right side. The well-known Sobel kernel for horizontal changes is:

sobel_x = [[-1, 0, 1],
           [-2, 0, 2],
           [-1, 0, 1]]

for row in convolve(image, sobel_x):
    print(row)

Output:

[0, 650, 720, 0]
[0, 580, 720, 0]
[0, 650, 720, 0]

In flat regions, the left and right columns match, so the negative and positive weights cancel and the output is 0. Where the window straddles the boundary, the right column is bright and the left is dark. Over pure background either side of the edge, the response is (1 + 2 + 1) × (200 − 20) = 4 × 180 = 720. The weights sum to zero, which is why a uniform region gives exactly zero, however bright it is.

Now notice what the speck did. The second column should read 720 all the way down, like the third, but it reads 650, 580, 650. The speck of 90 sits in the left column of those windows and is subtracted, weakening the edge. Edge detectors amplify differences, and noise is made of differences, so edge kernels are very sensitive to noise. That is why practical edge detection usually blurs first, then differentiates.

A vertical version of the kernel (the same numbers, turned on its side) finds changes from top to bottom. Combining the two responses, gx and gy, as √(gx² + gy²) gives the edge strength in any direction.

Project

Paper and Python project: filters by hand

  1. On squared paper, draw a 6 × 6 greyscale image with a dark square in the middle of a bright background. Write a number in every cell.
  2. By hand, apply the 3 × 3 box filter to at least four interior pixels, including two that sit on the square's edge. Show your working.
  3. Apply the Sobel kernel to the same four pixels by hand.
  4. Type your image into Python and use the convolve function to check your answers. If any differ, find out why.
  5. Add one noisy pixel and compare the Sobel output with and without blurring first. Describe what you see in two or three sentences.

Deliverables

  • Hand calculations for four pixels with both kernels
  • Python output that confirms (or corrects) your hand results
  • A short comparison of edge detection with and without blurring first

Knowledge check

Check your understanding

  1. 1. A 3 × 3 box filter is applied to a neighbourhood of eight pixels at 50 and one at 140. What is the output?
  2. 2. What is the main cost of smoothing an image with a blur kernel?
  3. 3. Why does the Sobel kernel give exactly 0 on a perfectly uniform region of brightness 200?
  4. 4. Why do practical edge detectors usually blur an image before applying an edge kernel?

Go further