How to retain the kth rank pixel of an image in Python

The PIL library

In Python, PIL (Pillow) or Python Imaging Library is an image processing library. This library supports a wide range of file formats. It is designed for an efficient internal representation of image data. Moreover, it provides powerful image processing capabilities.

The ImageFilter module

The ImageFilter module in PIL contains definitions for a pre-defined set of filters used for different purposes.

The RankFilter class

The RankFilter class is used to create a rank filter. A rank filter is a type of filter that sorts all pixels in a window of the given size and returns the given rank’s value.

Syntax

PIL.ImageFilter.RankFilter(size, rank)

Parameter

  • size: This is the kernel size.
  • rank: This is the pixel to return. With different values for rank, we get different filters. For example, with rank as 0 we get a min filter. Similarly, with rank as size * size / 2, we get a median filter, and so on.

Example

from PIL import Image, ImageFilter

img = Image.open("man.png")

size = 3
rank = size * size - 1

new_img = img.filter(ImageFilter.RankFilter(size = size, rank = rank))

new_img.save("new_man.png")

Explanation

  • Line 1: We import the ImageFilter and Image modules.
  • Line 3: We use open() in Image to read module man.png into memory .
  • Line 5: We define the size of the kernel, size.
  • Line 6: We define the rank of the pixel to be chosen, rank.
  • Line 8: We apply RankFilter on the image loaded in Line 3.
  • Line 10: We save the new image to disk.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved