使用 Python 和 OpenCV 的中值滤波器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18427031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Median Filter with Python and OpenCV
提问by mas_bejo
I try make python program for do median filter. I got this article http://www.programming-techniques.com/2013/02/median-filter-using-c-and-opencv-image.html, so I try to translate that code to python code.
我尝试为做中值滤波器制作 python 程序。我收到了这篇文章http://www.programming-techniques.com/2013/02/median-filter-using-c-and-opencv-image.html,所以我尝试将该代码转换为 python 代码。
this the code in 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()
This is a picture before the median filter:
这是中值滤波前的图:
but I got strange results, the results of the program :
但我得到了奇怪的结果,程序的结果:
采纳答案by Aurelius
First, I recommend that you not re-invent the wheel. OpenCV already contains a method to perform median filtering:
首先,我建议您不要重新发明轮子。OpenCV 已经包含了一种执行中值滤波的方法:
final = cv2.medianBlur(source, 3)
That said, the problem with your implementation lies in your iteration bounds. Your y
range is correct. However, for x in range(1,y-1):
only iterates up to the current y
value, and not the entire x
range of the image. This explains why the filter is only applied to a triangular region in the lower-left of the image. You can use the shape
field of the image (which is really just a numpy array) to get the image dimensions, which can then be iterated over:
也就是说,您的实现问题在于您的迭代范围。你的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):
This will apply the filter to the entire image:
这会将过滤器应用于整个图像: