In this article, we will see how we can apply a rank filter on images in mahotas. The rank filter especially filters isolated pixels out, whose intensity differs greatly from that of its immediate neighborhood. Large areas with constant intensity values adjacent to these pixels, as well as edges, are retained after this filter has been used.
In this tutorial, we will use the “Lena” image, below is the command to load it.
mahotas.demos.load('lena')
Below is the Lena image

In order to do this we will use mahotas.rank_filter method
Syntax : mahotas.rank_filter(img, neighbour, rank)
Argument : It takes image object and two integer as argument
Return : It returns image object
Note: Input image should be filtered or should be loaded as grey
In order to filter the image we will take the image object which is numpy.ndarray and filter it with the help of indexing, below is the command to do this
image = image[:, :, 0]
Below is the implementation
# importing required libraries
import mahotas
import mahotas.demos
from pylab import gray, imshow, show
import numpy as np
import matplotlib.pyplot as plt
# loading image
img = mahotas.demos.load('lena')
# filtering image
img = img.max(2)
print("Image")
# showing image
imshow(img)
show()
# neighbour pixel
neighbour = 3
# rank
rank = 2
# applying rank filter
new_img = mahotas.rank_filter(img, neighbour, rank)
# showing image
print("Rank Filter")
imshow(new_img)
show()
Output :
Image

Rank Filter
Another example
# importing required libraries
import mahotas
import numpy as np
from pylab import gray, imshow, show
import os
import matplotlib.pyplot as plt
# loading image
img = mahotas.imread('dog_image.png')
# filtering image
img = img[:, :, 0]
print("Image")
# showing image
imshow(img)
show()
# neighbour pixel
neighbour = 3
# rank
rank = 2
# applying rank filter
new_img = mahotas.rank_filter(img, neighbour, rank)
# showing image
print("Rank Filter")
imshow(new_img)
show()
Output :
Image

Rank Filter