I want to use an image filter, which should replace the pixel it\'s dealing with with the highest occurence of the neighbors. For example if the pixel has the value 10, and
You can use the modal filter in skimage, example here, documentation here.
Or if your needs differ slightly, you could experiment with the generic_filter()
in scipy (documentation here) along these lines:
#!/usr/bin/env python3
import numpy as np
from PIL import Image
from scipy.ndimage import generic_filter
from scipy import stats
# Modal filter
def modal(P):
"""We receive P[0]..P[8] with the pixels in the 3x3 surrounding window"""
mode = stats.mode(P)
return mode.mode[0]
# Open image and make into Numpy array - or use OpenCV 'imread()'
im = Image.open('start.png').convert('L')
im = np.array(im)
# Run modal filter
result = generic_filter(im, modal, (3, 3))
# Save result or use OpenCV 'imwrite()'
Image.fromarray(result).save('result.png')
Note that OpenCV images are completely interchangeable with Numpy arrays, so you can use OpenCV image = imread()
and then call the functions I am suggesting above with that image.
Keywords: Python, PIL, Pillow, skimage, simple filter, generic filter, mean, median, mode, image, image processing, numpy