1. 程式人生 > 其它 >理想濾波器、巴特沃斯濾波器、高斯濾波器(Python)

理想濾波器、巴特沃斯濾波器、高斯濾波器(Python)

 1 import numpy as np
 2 import cv2
 3 import matplotlib.pyplot as plt
 4 
 5 def G(img,str,s):
 6     # 設定截止頻率
 7     D0 = 8
 8     # #傅立葉變換
 9     f = np.fft.fft2(img)
10     f_shift = np.fft.fftshift(f)   # 將零頻點移到頻譜的中間,就是中間化處理
11     m = f_shift.shape[0]
12     n = f_shift.shape[1]
13     h1 = np.zeros((m, n))
14 x0 = np.floor(m/2) 15 y0 = np.floor(n/2) #頻譜中心 16 for i in range(m): 17 for j in range(n): 18 D = np.sqrt((i - x0)**2 + (j - y0)**2) #計算距離 19 if(str=='hp'): #高通 20 if s=='ideal': #理想濾波 21 if (D > D0): 22 h1[i, j] = 1 23
else: 24 h1[i, j] = 0 25 if s=='Gaussian': #高斯濾波 26 h1[i][j] = 1-np.exp((-1)*D**2/2/(D0**2)) 27 if s=='butterworth': #巴特沃斯濾波器 28 h1[i][j] = 1.0 / (1 + (D0 / D) ** (2 * 2)) 29 if
(str == 'lp'): #低通 30 if s=='ideal': 31 if (D > D0): 32 h1[i, j] = 0 33 else: 34 h1[i, j] = 1 35 if s == 'Gaussian': 36 h1[i][j] = np.exp((-1) * D ** 2 / 2 / (D0 ** 2)) 37 if s=='butterworth': 38 h1[i][j] = 1.0 / (1 + (D / D0) ** (2 * 2)) 39 G = np.multiply(f_shift, h1) 40 new_f1 = np.fft.ifftshift(G) # 傅立葉反變換(之前是正變換,現在該反變換變回去了) 41 result = np.uint8(np.abs(np.fft.ifft2(new_f1))) 42 return result 43 44 img =cv2.imread('E:\A29.jpg',0) #影象輸入 45 plt.subplot(331), plt.imshow(img, 'gray'), plt.title('Original Image') 46 plt.axis('off') 47 res = G(img,'lp','ideal') 48 plt.subplot(332), plt.imshow(res, 'gray'), plt.title('ideal_lp') 49 plt.axis('off') 50 res = G(img,'hp','ideal') 51 plt.subplot(333), plt.imshow(res, 'gray'), plt.title('ideal_hp') 52 plt.axis('off') 53 res = G(img,'lp','butterworth') 54 plt.subplot(334), plt.imshow(res, 'gray'), plt.title('butterworth_lp') 55 plt.axis('off') 56 res = G(img,'hp','butterworth') 57 plt.subplot(335), plt.imshow(res, 'gray'), plt.title('butterworth_hp') 58 plt.axis('off') 59 res = G(img,'lp','Gaussian') 60 plt.subplot(336), plt.imshow(res, 'gray'), plt.title('Gaussian_lp') 61 plt.axis('off') 62 res = G(img,'hp','Gaussian') 63 plt.subplot(337), plt.imshow(res, 'gray'), plt.title('Gaussian_hp') 64 plt.axis('off') 65 plt.show()