使用像素值出现率最高的图像过滤器

时间:2019-01-30 11:14:20

标签: python-3.x image opencv imagefilter image-editing

我想使用图像滤镜,该滤镜应以发生率最高的邻居替换它处理的像素。 例如,如果像素的值为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个不同的灰度值没有逻辑联系。

1 个答案:

答案 0 :(得分:2)

您可以在 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