我想使用一个图像过滤器,它应该用相邻像素中出现次数最多的像素替换它正在处理的像素。 例如,如果像素的值为 10,而 8 个邻居有 9、9、9、27、27、200、200、210,那么它应该选择 9,因为 9 在邻域中出现次数最多。它还应该考虑像素本身。因此,例如,如果像素的值为 27,而 8 个相邻像素的值为 27、27、30、30、34、70、120、120,那么它应该选择 27,因为 27 出现了 3 次,包括像素本身。 我也应该可以选择内核的大小。 我没有找到这样的过滤器。有吗?还是我必须自己创建它?我将 opencv 与 python 结合使用。
背景资料: 我不能只使用中值过滤器,因为我的图像不同。我有 3 到 6 个不同灰度值的灰度图像。因此我不能使用一些形态转换。我没有得到我想要的结果。中值滤波器会选择中值,因为其思想是这些值以正确的方式表示图像。但是我的图像是kmeans的结果,3-6个不同的灰度值没有逻辑联系。
最佳答案
您可以在 skimage 中使用模态过滤器,例如 here , 文档 here .
或者,如果您的需求略有不同,您可以按照以下几行在 scipy(文档 here)中试验 generic_filter()
:
#!/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')
请注意,OpenCV 图像可与 Numpy 数组完全互换,因此您可以使用 OpenCV image = imread()
然后调用函数我在上面建议使用该图片。
关键词:Python、PIL、Pillow、skimage、简单过滤器、通用过滤器、均值、中值、模式、图像、图像处理、numpy
关于python-3.x - 使用出现次数最多的像素值的图像过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54439298/