What are median and mode filters in pillow in Python?

The Python Imaging Library, known as PIL or pillow is a Python image-processing library. This library has powerful image processing capabilities, supports many file types, and is built for an effective internal representation of picture data.

There are many modules in the PIL library for different purposes. One such module is the ImageFilter module. As the name suggests, the ImageFilter module in PIL contains a pre-defined set of filters used for different purposes.

The MedianFilter function

The median filter is used to pick the median value in a window of a given size. The MedianFilter() function creates a median filter.

Median is the middle term in a sorted array.

Syntax

PIL.ImageFilter.MedianFilter(size=3)

Parameter

  • size: This is the window size.

Coding example

from PIL import Image, ImageFilter
img = Image.open("/test.png").convert('RGB')
filter_size = 3
median_filter_img = img.filter(ImageFilter.MedianFilter(size=filter_size))
median_filter_img.save("output/median_filter_image.png")

Explanation

  • Line 1: We import the Image and ImageFilter modules from PIL.
  • Line 3: We load a test image into memory.
  • Line 5: We define the filter size (or window).
  • Line 7: We apply a median filter by invoking the filter() function on the image object. The median filter is passed as an argument to the filter() function.
  • Line 9: We save the resulting image after applying the median filter to the disk.

The ModeFilter function

The mode filter is used to pick the most occurring pixel value in a window of a given size. The ModeFilter function creates a mode filter. If no pixel value occurs more than twice, the original pixel value is preserved.

Syntax

PIL.ImageFilter.ModeFilter(size=3)

Parameter

  • size: This is the window size.

Code:

from PIL import Image, ImageFilter
img = Image.open("/test.png").convert('RGB')
filter_size = 3
mode_filter_img = img.filter(ImageFilter.ModeFilter(size=filter_size))
mode_filter_img.save("output/mode_filter_image.png")

Explanation

  • Line 1: We import the Image and ImageFilter modules from PIL.
  • Line 3: We load a test image into memory.
  • Line 5: We define the filter size (or window).
  • Line 7: We apply a mode filter by invoking the filter() function on the image object. The mode filter is passed as an argument to the filter() function.
  • Line 9: We save the resulting image after applying the mode filter to the disk.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved