Python Blur Image Pillow

In this tutorial I will show you how to blur an image using Python pillow library. The pillow image library provides the ImageFilter module that contains definitions for a pre-defined set of filters, which can be be used with the Image.filter() method to apply blur on image.

I am going to show you three blur effects on an image – simple, box and gaussian blurs.

You can blur an image by reducing the level of noise in the image by applying a filter to that image. Blurring an image is one of the important aspects in image processing.

Prerequisites

Python 3.8.5

Blur Image

In the following example I am going to show you mainly three types of techniques to apply blur on image. There are several techniques which can be used using the filter() method and can be found here.

  • Simple Blur
  • Box Blur
  • Gaussian Blur

Original image is displayed below on which I am going to apply blur effect using above three techniques:

blur python image

Simple Blur

The simple blur effect on to the image is achieved through a convolution kernel. The current version only supports 3×3 and 5×5 integer and floating point kernels. In the current version, kernels can only be applied to “L” and “RGB” images.

from PIL import Image, ImageFilter
import os

img_dir = "/python/python-blur-image/"
img_name = 'original.jpg'
img = Image.open(img_dir + img_name)
f, e = os.path.splitext(img_dir + img_name)

blur_img = img.filter(ImageFilter.BLUR)
blur_img.save(f + '_blurred.jpg')

Output Image

python simple blur

Box Blur

Blurs the image by setting each pixel to the average value of the pixels in a square box extending radius pixels in each direction. Supports float radius of arbitrary size. Uses an optimized implementation which runs in linear time relative to the size of the image for any radius value.

Parameter, radius, indicates the size of the box in one direction. Radius with value 0 does not blur and returns an identical image. Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total.

from PIL import Image, ImageFilter
import os

img_dir = "C:/python/python-blur-image/"
img_name = 'original.jpg'
img = Image.open(img_dir + img_name)
f, e = os.path.splitext(img_dir + img_name)

box_blur_img = img.filter(ImageFilter.BoxBlur(7))
box_blur_img.save(f + '_box_blurred.jpg')

Output Image

python box blur

Gaussian Blur

This filter also takes the radius as a parameter but uses different algorithm – Gaussian blur filter.

from PIL import Image, ImageFilter
import os

img_dir = "C:/python/python-blur-image/"
img_name = 'original.jpg'
img = Image.open(img_dir + img_name)
f, e = os.path.splitext(img_dir + img_name)

gaus_blur_img = img.filter(ImageFilter.GaussianBlur(7))
gaus_blur_img.save(f + '_gaus_blurred.jpg')

Output Image

python gaussian blur

That’s all about blurring an image in Python with the help of Pillow library.

Source Code

Download

Thanks for reading.

Leave a Comment