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.
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.
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
These values are calculated using the following Gaussian function:
Here,
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
This will be calculated as follows:
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.requestfrom PIL import Image, ImageFilterurl = "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.requestto 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 theradiusargument. It defaults to2.
Free Resources