使用Python和OpenCV的中值滤波器

2024-05-16 10:38:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试用python程序来做中值滤波。我得到了这篇文章http://www.programming-techniques.com/2013/02/median-filter-using-c-and-opencv-image.html,所以我尝试将该代码转换为python代码。

这是python中的代码

from cv2 import * #Import functions from OpenCV
import cv2

if __name__ == '__main__':
    source = cv2.imread("Medianfilterp.png", CV_LOAD_IMAGE_GRAYSCALE)
    final = source[:]
    for y in range(len(source)):
        for x in range(y):
            final[y,x]=source[y,x]

    members=[source[0,0]]*9
    for y in range(1,len(source)-1):
        for x in range(1,y-1):
            members[0] = source[y-1,x-1]
            members[1] = source[y,x-1]
            members[2] = source[y+1,x-1]
            members[3] = source[y-1,x]
            members[4] = source[y,x]
            members[5] = source[y+1,x]
            members[6] = source[y-1,x+1]
            members[7] = source[y,x+1]
            members[8] = source[y+1,x+1]

            members.sort()
            final[y,x]=members[4]

    cv.NamedWindow('Source_Picture', cv.CV_WINDOW_AUTOSIZE)
    cv.NamedWindow('Final_Picture', cv.CV_WINDOW_AUTOSIZE)
    cv2.imshow('Source_Picture', source) #Show the image
    cv2.imshow('Final_Picture', final) #Show the image
    cv2.waitKey()

这是中值滤波前的图片: source picture

但是我得到了奇怪的结果,程序的结果: final picture


Tags: 代码infromimage程序sourceforrange
1条回答
网友
1楼 · 发布于 2024-05-16 10:38:43

首先,我建议你不要re-invent the wheel。OpenCV已经包含一个执行中值过滤的方法:

final = cv2.medianBlur(source, 3)

也就是说,实现的问题在于迭代边界。您的y范围正确。但是,for x in range(1,y-1):只迭代到当前的y值,而不是图像的整个x范围。这解释了为什么过滤器只应用于图像左下角的三角形区域。您可以使用图像的shape字段(实际上只是一个numpy数组)来获取图像维度,然后可以对其进行迭代:

for y in range(1,source.shape[0]-1):
    for x in range(1,source.shape[1]-1):

这将对整个图像应用筛选器:

Median filter result

相关问题 更多 >