How to blur an image using a Gaussian filter

Blurring is used as a pre-processing step in many computer vision applications as it can remove noise (high-frequency components). Photographers also blur some parts of the image so that the main object can be more prominent than the background.

Original Image
Blurred Image

Blurring an image is the process of applying a low-pass filter. A low pass filter allows low-frequency components and blocks the components with high-frequency.

In terms of images, the high-frequency components are those where we see an abrupt change in the pixel values. Similarly, low-frequency components show a gradual change in the pixel values.

Low-frequency components
High-frequency components

Note: Applying this low-pass filter smoothens the sharp edges in the image which gives it a blurred look.

Gaussian filter

When blurring an image, we take a filter and perform convolutionConvolution is a mathematical operation where a function is applied to another function to result in a mixture of the two functions. on the image. This filter is a symmetric matrix of usually odd dimensions so we can centralize pixels in the filter. A Gaussian filter uses the Gaussian functionNormal distribution function to calculate the values for the filter. A Gaussian filter of 3×33 \times 3 matrix is given below:

A 3x3 Gaussian filter

These values are calculated using the following Gaussian function:

Here, xx and yy are the coordinates and σ\sigma is the standard deviation. In the filter above, σ=1.0\sigma = 1.0.

Visualization

In this section, we'll visualize the process of applying a filter to an image. For simplicity, we assume that our image is of 3×33 \times 3 dimensions and the filter is the same as above. Usually, the image is padded with zeros as shown below:

Convolution operation

This will be calculated as follows:

1 of 9

Code example

In this section, we'll apply the mean filter to the un-blurred image above. We'll use the Pillow library to apply the mean filter to the image above:

import urllib.request
from PIL import Image, ImageFilter
url = "https://github.com/nabeelraza-7/images-for-articles/blob/main/educative.jpeg?raw=true"
filename = "image.jpeg"
urllib.request.urlretrieve(url, filename)
img = Image.open(filename)
blurred = img.filter(ImageFilter.GaussianBlur)
blurred.save("output/blurred.jpeg")

Explanation

  • Line 8: We use the in-built urllib.request to get the image from the web. This is stored in the local directory with the given name.

  • Line 9: We use the same file that we have downloaded from the web and opened it using Image.open().

  • Line 10: We use the filter method of the image object to apply the filter defined in ImageFilter.GaussianFilter(). We can increase the intensity of this filter by using the radius argument. It defaults to 2.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved