Applying mode filter using Python and Pillow

Mode filter replaces the pixel values in an image with the mode value of its neighbourhood pixel window.Mode filter is an edge preserving filter. The python example program applies mode filter several times to the image before displaying the output.

Pillow Updated 13 Jun 2019 1 min read

Overview

  • The mode filter replaces each pixel of a Digital image with the mode value of its neighborhood pixel window.
  • The class ImageFilter.ModeFilter implements the mode filter.
  • As per Pillow's implementation, to consider a pixel value as mode, the value should at least occur twice in the neighborhood. Else the original pixel value is retained in the image.
  • The Python example applies the mode filter 7x times to a digital image.
  • Similar to the median filter the mode filter as well is an edge preserving filter.

Example

python
# import the required PIL Modules

from PIL import Image

from PIL import ImageFilter

# Load an image

imageObject = Image.open("./nightsky.jpg");

# Show the original image

imageObject.show();

# Apply mode filter multiple times

modeFilterApplied = imageObject.filter(ImageFilter.ModeFilter);

for i in range (0, 6):

    modeFilterApplied = modeFilterApplied.filter(ImageFilter.ModeFilter);

# Show the image with mode filter applied

modeFilterApplied.show();

Output

Before applying the mode filter

Before applying mode filter using Pillow - the Python image processing library

After applying the mode filter 7x times

After applying mode filter using the python library - pillow