2013-08-25 272 views
2

我嘗試使用python程序做中值濾波。我得到這篇文章http://www.programming-techniques.com/2013/02/median-filter-using-c-and-opencv-image.html,所以我嘗試將該代碼翻譯成python代碼。用Python和OpenCV進行中值濾波

這在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

回答

7

第一,我建議你不要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

+0

我只想學習如何做中值濾波,而不只是調用函數。謝謝..我沒有注意到這一點。 ha ..ha ..解決了我的問題,但是,我遇到了新問題,當我把圖片裁剪成一半時,它說的是outofbound。你知道爲什麼嗎? –

+0

@mas_bejo這可能是通過提出一個單獨問題最好解決的問題。你的新問題需要更多的解釋,評論並不是真正的地方。 – Aurelius

+0

好的,謝謝你的幫助。可能是我會發布有關後者的問題... –