第5章 Python 數字圖像處理(DIP) - 圖像復原與重建12 - 空間濾波 - 使用頻率域濾波降低周期噪聲 - 陷波濾波、最優陷波濾波

標題

    • 使用頻率域濾波降低周期噪聲
      • 陷波濾波深入介紹
      • 最優陷波濾波

本章陷波濾波器有部分得出的結果不佳,如果有更好的解決方案,請賜教,不勝感激。

使用頻率域濾波降低周期噪聲

陷波濾波深入介紹

零相移濾波器必須關于原點(頻率矩形中心)對稱,中以為(u0,v0)(u_0, v_0)(u0?,v0?)的陷波濾波器傳遞函數在(?u0,?v0)(-u_0, -v_0)(?u0?,?v0?)位置必須有一個對應的陷波。陷波帶阻濾波器傳遞函數可用中心被平移到陷波濾波中心的高通濾波器函數的乘積來產生

HNR(u,v)=∏k=1QHk(u,v)H?k(u,v)(5.33)H_{NR}(u, v) = \prod_{k=1}^Q H_k(u, v) H_{-k}(u, v) \tag{5.33}HNR?(u,v)=k=1Q?Hk?(u,v)H?k?(u,v)(5.33)

每個濾波器的距離計算公式為
Dk(u,v)=[(u?M/2?uk)2+(v?N/2?vk)2]1/2(5.34)D_{k}(u, v) = \big[(u - M / 2 - u_{k})^2 + (v - N / 2 - v_{k})^2 \big]^{1/2} \tag{5.34}Dk?(u,v)=[(u?M/2?uk?)2+(v?N/2?vk?)2]1/2(5.34)
D?k(u,v)=[(u?M/2+uk)2+(v?N/2+vk)2]1/2(5.35)D_{-k}(u, v) = \big[(u - M / 2 + u_{k})^2 + (v - N / 2 + v_{k})^2 \big]^{1/2} \tag{5.35}D?k?(u,v)=[(u?M/2+uk?)2+(v?N/2+vk?)2]1/2(5.35)

3個nnn階巴特沃斯帶阻濾波器
HNR(u,v)=∏k=13[11+[D0k/Dk(u,v)]n][11+[D0k/D?k(u,v)]n](5.36)H_{NR}(u, v) = \prod_{k=1}^3\bigg[ \frac{1}{1 + [D_{0k}/D_{k}(u,v)]^n} \bigg] \bigg[ \frac{1}{1 + [D_{0k}/D_{-k}(u,v)]^n} \bigg] \tag{5.36}HNR?(u,v)=k=13?[1+[D0k?/Dk?(u,v)]n1?][1+[D0k?/D?k?(u,v)]n1?](5.36)

常數D0kD_{0k}D0k?對每對陷波是相同的,但對不同的陷波對,它可以不同。

陷波帶通濾波器傳遞函數可用陷波帶阻濾波器得到
HNP(u,v)=1?HNR(u,v)(5.37)H_{NP}(u, v) = 1 - H_{NR}(u, v) \tag{5.37}HNP?(u,v)=1?HNR?(u,v)(5.37)

def butterworth_notch_resistant_filter(img, uk, vk, radius=10, n=1):"""create butterworth notch resistant filter, equation 4.155param: img:    input, source imageparam: uk:     input, int, center of the heightparam: vk:     input, int, center of the widthparam: radius: input, int, the radius of circle of the band pass filter, default is 10param: w:      input, int, the width of the band of the filter, default is 5param: n:      input, int, order of the butter worth fuction, return a [0, 1] value butterworth band resistant filter"""   M, N = img.shape[1], img.shape[0]u = np.arange(M)v = np.arange(N)u, v = np.meshgrid(u, v)DK = np.sqrt((u - M//2 - uk)**2 + (v - N//2 - vk)**2)D_K = np.sqrt((u - M//2 + uk)**2 + (v - N//2 + vk)**2)D0 = radiuskernel = (1 / (1 + (D0 / (DK+1e-5))**n)) * (1 / (1 + (D0 / (D_K+1e-5))**n))return kernel
def idea_notch_resistant_filter(source, uk, vk, radius=5):"""create idea notch resistant filter param: source: input, source imageparam: uk:     input, int, center of the heightparam: vk:     input, int, center of the widthparam: radius: input, the radius of the lowest value, greater value, bigger blocker out range, if the radius is 0, then allvalue is 0return a [0, 1] value filter"""M, N = source.shape[1], source.shape[0]u = np.arange(M)v = np.arange(N)u, v = np.meshgrid(u, v)DK = np.sqrt((u - M//2 - uk)**2 + (v - N//2 - vk)**2)D_K = np.sqrt((u - M//2 + uk)**2 + (v - N//2 + vk)**2)D0 = radiusk_1 = DK.copy()k_2 = D_K.copy()k_1[DK > D0] = 1k_1[DK <= D0] = 0k_2[D_K > D0] = 1k_2[D_K <= D0] = 0kernel = k_1 * k_2return kernel
def gauss_notch_resistant_filter(source, uk, vk, radius=5):"""create gauss low pass filter param: source: input, source imageparam: uk:     input, int, center of the heightparam: vk:     input, int, center of the widthparam: radius: input, the radius of the lowest value, greater value, bigger blocker out range, if the radius is 0, then allvalue is 0return a [0, 1] value filter"""    M, N = source.shape[1], source.shape[0]u = np.arange(M)v = np.arange(N)u, v = np.meshgrid(u, v)DK = np.sqrt((u - M//2 - uk)**2 + (v - N//2 - vk)**2)D_K = np.sqrt((u - M//2 + uk)**2 + (v - N//2 + vk)**2)D0 = radiusk_1 = 1 - np.exp(- (DK**2)/(D0**2))   k_2 = 1 - np.exp(- (D_K**2)/(D0**2))   kernel = k_1 * k_2return kernel
def plot_3d(ax, x, y, z, cmap):ax.plot_surface(x, y, z, antialiased=True, shade=True, cmap=cmap)ax.view_init(20, -20), ax.grid(b=False), ax.set_xticks([]), ax.set_yticks([]), ax.set_zticks([])
# 理想、高斯、巴特沃斯陷波濾波器
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cmimg_temp = np.zeros([256, 256])INRF = idea_notch_resistant_filter(img_temp, radius=20, uk=30, vk=80)
GNRF = gauss_notch_resistant_filter(img_temp, radius=20, uk=30, vk=80)
BNRF = butterworth_notch_resistant_filter(img_temp, radius=20, uk=30, vk=80, n=5)# 用來繪制3D圖
M, N = img_temp.shape[1], img_temp.shape[0]
u = np.arange(M)
v = np.arange(N)
u, v = np.meshgrid(u, v)fig = plt.figure(figsize=(21, 7))
ax_1 = fig.add_subplot(1, 3, 1, projection='3d')
plot_3d(ax_1, u, v, INRF, cmap=cm.plasma)ax_1 = fig.add_subplot(1, 3, 2, projection='3d')
plot_3d(ax_1, u, v, GNRF, cmap=cm.PiYG)ax_1 = fig.add_subplot(1, 3, 3, projection='3d')
plot_3d(ax_1, u, v, BNRF, cmap=cm.PiYG)
plt.tight_layout()
plt.show()

在這里插入圖片描述

def centralized_2d(arr):"""centralized 2d array $f(x, y) (-1)^{x + y}$, about 4.5 times faster than index, 160 times faster than loop,"""def get_1_minus1(img):"""get 1 when image index is even, -1 while index is odd, same shape as input image, need this array to multiply with input imageto get centralized image for DFTParameter: img: input, here we only need img shape to create the arrayreturn such a [[1, -1, 1], [-1, 1, -1]] array, example is 3x3"""dst = np.ones(img.shape)dst[1::2, ::2] = -1dst[::2, 1::2] = -1return dst#==================中心化=============================mask = get_1_minus1(arr)dst = arr * maskreturn dst
def pad_image(img, mode='constant'):"""pad image into PxQ shape, orginal is in the top left corner.param: img: input imageparam: mode: input, str, is numpy pad parameter, default is 'constant'. for more detail please refere to Numpy padreturn PxQ shape image padded with zeros or other values"""dst = np.pad(img, ((0, img.shape[0]), (0, img.shape[1])), mode=mode)return dst    
def add_sin_noise(img, scale=1, angle=0):"""add sin noise for imageparam: img: input image, 1 channel, dtype=uint8param: scale: sin scaler, smaller than 1, will enlarge, bigger than 1 will shrinkparam: angle: angle of the rotationreturn: output_img: output image is [0, 1] image which you could use as mask or any you want to"""height, width = img.shape[:2]  # original image shape# convert all the angleif int(angle / 90) % 2 == 0:rotate_angle = angle % 90else:rotate_angle = 90 - (angle % 90)rotate_radian = np.radians(rotate_angle)    # convert angle to radian# get new image height and widthnew_height = int(np.ceil(height * np.cos(rotate_radian) + width * np.sin(rotate_radian)))new_width = int(np.ceil(width * np.cos(rotate_radian) + height * np.sin(rotate_radian))) # if new height or new width less than orginal height or width, the output image will be not the same shape as input, here set it rightif new_height < height:new_height = heightif new_width < width:new_width = width# meshgridu = np.arange(new_width)v = np.arange(new_height)u, v = np.meshgrid(u, v)# get sin noise image, you could use scale to make some difference, better you could add some shift
#     noise = abs(np.sin(u * scale))noise = 1 - np.sin(u * scale)# here use opencv to get rotation, better write yourself rotation functionC1 = cv2.getRotationMatrix2D((new_width/2.0, new_height/2.0), angle, 1)new_img = cv2.warpAffine(noise, C1, (int(new_width), int(new_height)), borderValue=0)# ouput image should be the same shape as input, so caculate the offset the output image and the new image# I make new image bigger so that it will cover all output imageoffset_height = abs(new_height - height) // 2offset_width = abs(new_width - width) // 2img_dst = new_img[offset_height:offset_height + height, offset_width:offset_width+width]output_img = normalize(img_dst)return output_img 
def spectrum_fft(fft):"""return FFT spectrum"""return np.sqrt(np.power(fft.real, 2) + np.power(fft.imag, 2))
# 陷波濾波器處理周期噪聲
img_ori = cv2.imread('DIP_Figures/DIP3E_Original_Images_CH05/Fig0507(a)(ckt-board-orig).tif', 0) #直接讀為灰度圖像# 正弦噪聲
noise = add_sin_noise(img_ori, scale=0.35, angle=-20)
img = np.array(img_ori / 255, np.float32)
img_noise = img + noise
img_noise = np.uint8(normalize(img_noise)*255)# 頻率域中的其他特性
# FFT
img_fft = np.fft.fft2(img_noise.astype(np.float32))
# 中心化
fshift = np.fft.fftshift(img_fft)            # 將變換的頻率圖像四角移動到中心
# 中心化后的頻譜
spectrum_fshift = spectrum_fft(fshift)
spectrum_fshift_n = np.uint8(normalize(spectrum_fshift) * 255)# 對頻譜做對數變換
spectrum_log = np.log(1 + spectrum_fshift)BNRF = butterworth_notch_resistant_filter(img_ori, radius=5, uk=25, vk=10, n=4)f1shift = fshift * (BNRF)
f2shift = np.fft.ifftshift(f1shift) #對新的進行逆變換
img_new = np.fft.ifft2(f2shift)
img_new = np.abs(img_new)plt.figure(figsize=(15, 15))
plt.subplot(221), plt.imshow(img_noise, 'gray'), plt.title('With Sine noise'), plt.xticks([]),plt.yticks([])
plt.subplot(222), plt.imshow(spectrum_log, 'gray'), plt.title('Spectrum'), plt.xticks([]),plt.yticks([])
# 在圖像上加上箭頭
plt.arrow(180, 180, 25, 30, width=5,length_includes_head=True, shape='full')
plt.arrow(285, 265, -25, -30, width=5,length_includes_head=True, shape='full')plt.subplot(223), plt.imshow(BNRF, 'gray'), plt.title('Spectrum'), plt.xticks([]),plt.yticks([])
# 在圖像上加上箭頭
plt.arrow(180, 180, 25, 30, width=5,length_includes_head=True, shape='full')
plt.arrow(285, 265, -25, -30, width=5,length_includes_head=True, shape='full')plt.subplot(224), plt.imshow(img_new, 'gray'), plt.title('Spectrum'), plt.xticks([]),plt.yticks([])plt.tight_layout()
plt.show()

在這里插入圖片描述

# 陷波濾波器提取周期噪聲
img_ori = cv2.imread('DIP_Figures/DIP3E_Original_Images_CH05/Fig0507(a)(ckt-board-orig).tif', 0) #直接讀為灰度圖像# 正弦噪聲
noise = add_sin_noise(img_ori, scale=0.35, angle=-20)
img = np.array(img_ori / 255, np.float32)
img_noise = img + noise
img_noise = np.uint8(normalize(img_noise)*255)# 頻率域中的其他特性
# FFT
img_fft = np.fft.fft2(img_noise.astype(np.float32))
# 中心化
fshift = np.fft.fftshift(img_fft)            # 將變換的頻率圖像四角移動到中心
# 中心化后的頻譜
spectrum_fshift = spectrum_fft(fshift)
spectrum_fshift_n = np.uint8(normalize(spectrum_fshift) * 255)# 對頻譜做對數變換
spectrum_log = np.log(1 + spectrum_fshift)BNRF = 1 - butterworth_notch_resistant_filter(img_ori, radius=5, uk=25, vk=10, n=4)f1shift = fshift * (BNRF)
f2shift = np.fft.ifftshift(f1shift) #對新的進行逆變換
img_new = np.fft.ifft2(f2shift)
img_new = np.abs(img_new)plt.figure(figsize=(15, 15))
# plt.subplot(221), plt.imshow(img_noise, 'gray'), plt.title('With Sine noise'), plt.xticks([]),plt.yticks([])
# plt.subplot(222), plt.imshow(spectrum_log, 'gray'), plt.title('Spectrum'), plt.xticks([]),plt.yticks([])
# # 在圖像上加上箭頭
# plt.arrow(180, 180, 25, 30, width=5,length_includes_head=True, shape='full')
# plt.arrow(285, 265, -25, -30, width=5,length_includes_head=True, shape='full')# plt.subplot(223), plt.imshow(BNRF, 'gray'), plt.title('Spectrum'), plt.xticks([]),plt.yticks([])
# # 在圖像上加上箭頭
# plt.arrow(180, 180, 25, 30, width=5,length_includes_head=True, shape='full')
# plt.arrow(285, 265, -25, -30, width=5,length_includes_head=True, shape='full')plt.subplot(224), plt.imshow(img_new, 'gray'), plt.title('Sine pattern'), plt.xticks([]),plt.yticks([])plt.tight_layout()
plt.show()

在這里插入圖片描述

def butterworth_band_resistant_filter(source, center, radius=10, w=5, n=1):"""create butterworth band resistant filter, equation 4.150param: source: input, source imageparam: center: input, the center of the filter, where is the lowest value, (0, 0) is top left corner, source.shape[:2] is center of the source imageparam: radius: input, int, the radius of circle of the band pass filter, default is 10param: w:      input, int, the width of the band of the filter, default is 5param: n:      input, int, order of the butter worth fuction, return a [0, 1] value butterworth band resistant filter"""    epsilon = 1e-8N, M = source.shape[:2]u = np.arange(M)v = np.arange(N)u, v = np.meshgrid(u, v)D = np.sqrt((u - center[1]//2)**2 + (v - center[0]//2)**2)C0 = radiustemp = (D * w) / ((D**2 - C0**2) + epsilon)kernel = 1 / (1 + temp ** (2*n)) return kerneldef butterworth_low_pass_filter(img, center, radius=5, n=1):"""create butterworth low pass filter param: source: input, source imageparam: center: input, the center of the filter, where is the lowest value, (0, 0) is top left corner, source.shape[:2] is center of the source imageparam: radius: input, the radius of the lowest value, greater value, bigger blocker out range, if the radius is 0, then allvalue is 0param: n: input, float, the order of the filter, if n is small, then the BLPF will be close to GLPF, and more smooth from lowfrequency to high freqency.if n is large, will close to ILPFreturn a [0, 1] value filter"""  epsilon = 1e-8M, N = img.shape[1], img.shape[0]u = np.arange(M)v = np.arange(N)u, v = np.meshgrid(u, v)D = np.sqrt((u - center[1]//2)**2 + (v - center[0]//2)**2)D0 = radiuskernel = (1 / (1 + (D / (D0 + epsilon))**(2*n)))return kernel
# 陷波濾波器處理周期噪聲,用巴特沃斯低通濾波器得到的效果比目前的陷波濾波器效果還要好
img_ori = cv2.imread('DIP_Figures/DIP3E_Original_Images_CH05/Fig0516(a)(applo17_boulder_noisy).tif', 0)
M, N = img_ori.shape[:2]fp = pad_image(img_ori, mode='reflect')
fp_cen = centralized_2d(fp)
fft = np.fft.fft2(fp_cen)# 中心化后的頻譜
spectrum_fshift = spectrum_fft(fft)
spectrum_log = np.log(1 + spectrum_fshift)# 濾波器
n = 15
r = 20
H = butterworth_low_pass_filter(fp, fp.shape, radius=100, n=4)
# BNRF_1 = butterworth_notch_resistant_filter(fp, radius=r, uk=355, vk=0, n=n)
# BNRF_2 = butterworth_notch_resistant_filter(fp, radius=r, uk=0, vk=355, n=n)
# BNRF_3 = butterworth_notch_resistant_filter(fp, radius=r, uk=250, vk=250, n=n)
# BNRF_4 = butterworth_notch_resistant_filter(fp, radius=r, uk=-250, vk=250, n=n)
# BNRF = BNRF_1 * BNRF_2 * BNRF_3 * BNRF_4  * H
BNRF = Hfft_filter = fft * BNRF# 濾波后的頻譜
spectrum_filter = spectrum_fft(fft_filter)
spectrum_filter_log = np.log(1 + spectrum_filter)# 傅里葉反變換
ifft = np.fft.ifft2(fft_filter)# 去中心化反變換的圖像,并取左上角的圖像
img_new = centralized_2d(ifft.real)[:M, :N]
img_new = np.clip(img_new, 0, img_new.max())
img_new = np.uint8(normalize(img_new) * 255)plt.figure(figsize=(15, 12))
plt.subplot(221), plt.imshow(img_ori, 'gray'), plt.title('With noise'), plt.xticks([]),plt.yticks([])
plt.subplot(222), plt.imshow(spectrum_log, 'gray'), plt.title('Spectrum'), plt.xticks([]),plt.yticks([])
plt.subplot(223), plt.imshow(spectrum_filter_log, 'gray'), plt.title('Spectrum With Filter'), plt.xticks([]),plt.yticks([])
plt.subplot(224), plt.imshow(img_new, 'gray'), plt.title('IDFT'), plt.xticks([]),plt.yticks([])
plt.tight_layout()
plt.show()

在這里插入圖片描述

# 陷波濾波器提取周期噪聲
img_ori = cv2.imread('DIP_Figures/DIP3E_Original_Images_CH05/Fig0516(a)(applo17_boulder_noisy).tif', 0)
M, N = img_ori.shape[:2]fp = pad_image(img_ori, mode='constant')
fp_cen = centralized_2d(fp)
fft = np.fft.fft2(fp_cen)# 中心化后的頻譜
spectrum_fshift = spectrum_fft(fft)
spectrum_log = np.log(1 + spectrum_fshift)# 濾波器
n = 15
r = 20
H = butterworth_low_pass_filter(fp, fp.shape, radius=100, n=3)
# BNRF_1 = butterworth_notch_resistant_filter(fp, radius=r, uk=355, vk=0, n=n)
# BNRF_2 = butterworth_notch_resistant_filter(fp, radius=r, uk=0, vk=355, n=n)
# BNRF_3 = butterworth_notch_resistant_filter(fp, radius=r, uk=250, vk=250, n=n)
# BNRF_4 = butterworth_notch_resistant_filter(fp, radius=r, uk=-250, vk=250, n=n)
# BNRF = BNRF_1 * BNRF_2 * BNRF_3 * BNRF_4 * H
BNRF = H
fft_filter = fft * (1 - BNRF)# 濾波后的頻譜
spectrum_filter = spectrum_fft(fft_filter)
spectrum_filter_log = np.log(1 + spectrum_filter)# 傅里葉反變換
ifft = np.fft.ifft2(fft_filter)# 去中心化反變換的圖像,并取左上角的圖像
img_new = centralized_2d(ifft.real)[:M, :N]
img_new = np.clip(img_new, 0, img_new.max())
img_new = np.uint8(normalize(img_new) * 255)plt.figure(figsize=(15, 12))
# plt.subplot(221), plt.imshow(img_ori, 'gray'), plt.title('With Sine noise'), plt.xticks([]),plt.yticks([])
# plt.subplot(222), plt.imshow(spectrum_log, 'gray'), plt.title('Spectrum'), plt.xticks([]),plt.yticks([])
# plt.subplot(223), plt.imshow(spectrum_filter_log, 'gray'), plt.title('Spectrum'), plt.xticks([]),plt.yticks([])
plt.subplot(224), plt.imshow(img_new, 'gray'), plt.title('Spectrum'), plt.xticks([]),plt.yticks([])
plt.tight_layout()
plt.show()

在這里插入圖片描述

def narrow_notch_filter(img, w=5, opening=10, vertical=True, horizontal=False):"""create narrow notch resistant filterparam: img:        input, source imageparam: w:          input, int, width of the resistant, value is 0, default is 5param: opening:    input, int, opening of the resistant, value is 1, default is 10param: vertical:   input, boolean, whether vertical or not, default is "True"param: horizontal: input, boolean, whether horizontal or not, default is "False"return a [0, 1] value butterworth band resistant filter"""       assert w > 0, "W must greater than 0"w_half = w//2opening_half = opening//2img_temp = np.ones(img.shape[:2])M, N = img_temp.shape[:]img_vertical = img_temp.copy()img_horizontal = img_temp.copy()if horizontal:img_horizontal[M//2 - w_half:M//2 + w - w_half, :] = 0img_horizontal[:, N//2 - opening_half:N//2 + opening - opening_half] = 1if vertical:img_vertical[:, N//2 - w_half:N//2 + w - w_half] = 0img_vertical[M//2 - opening_half:M//2 + opening - opening_half, :] = 1img_dst = img_horizontal * img_verticalreturn img_dst
# 陷波濾波器處理周期噪聲,用巴特沃斯低通濾波器得到的效果比目前的陷波濾波器效果還要好
img_ori = cv2.imread('DIP_Figures/DIP3E_Original_Images_CH05/Fig0519(a)(florida_satellite_original).tif', 0)
M, N = img_ori.shape[:2]fp = pad_image(img_ori, mode='reflect')
fp_cen = centralized_2d(fp)
fft = np.fft.fft2(fp_cen)# 中心化后的頻譜
spectrum_fshift = spectrum_fft(fft)
spectrum_log = np.log(1 + spectrum_fshift)# 濾波器
n = 15
r = 20
H = narrow_notch_filter(fp, w=10, opening=30, vertical=True, horizontal=False)
# BNRF_1 = butterworth_notch_resistant_filter(fp, radius=r, uk=355, vk=0, n=n)
# BNRF_2 = butterworth_notch_resistant_filter(fp, radius=r, uk=0, vk=355, n=n)
# BNRF_3 = butterworth_notch_resistant_filter(fp, radius=r, uk=250, vk=250, n=n)
# BNRF_4 = butterworth_notch_resistant_filter(fp, radius=r, uk=-250, vk=250, n=n)
# BNRF = BNRF_1 * BNRF_2 * BNRF_3 * BNRF_4  * H
BNRF = Hfft_filter = fft * BNRF# 濾波后的頻譜
spectrum_filter = spectrum_fft(fft_filter)
spectrum_filter_log = np.log(1 + spectrum_filter)# 傅里葉反變換
ifft = np.fft.ifft2(fft_filter)# 去中心化反變換的圖像,并取左上角的圖像
img_new = centralized_2d(ifft.real)[:M, :N]
img_new = np.clip(img_new, 0, img_new.max())
img_new = np.uint8(normalize(img_new) * 255)plt.figure(figsize=(15, 16))
plt.subplot(221), plt.imshow(img_ori, 'gray'), plt.title('With noise'), plt.xticks([]),plt.yticks([])
plt.subplot(222), plt.imshow(spectrum_log, 'gray'), plt.title('Spectrum'), plt.xticks([]),plt.yticks([])
plt.subplot(223), plt.imshow(spectrum_filter_log, 'gray'), plt.title('Spectrum With Filter'), plt.xticks([]),plt.yticks([])
plt.subplot(224), plt.imshow(img_new, 'gray'), plt.title('IDFT'), plt.xticks([]),plt.yticks([])
plt.tight_layout()
plt.show()

在這里插入圖片描述

# 陷波濾波器提取周期噪聲,用巴特沃斯低通濾波器得到的效果比目前的陷波濾波器效果還要好
img_ori = cv2.imread('DIP_Figures/DIP3E_Original_Images_CH05/Fig0519(a)(florida_satellite_original).tif', 0)
M, N = img_ori.shape[:2]fp = pad_image(img_ori, mode='reflect')
fp_cen = centralized_2d(fp)
fft = np.fft.fft2(fp_cen)# 中心化后的頻譜
spectrum_fshift = spectrum_fft(fft)
spectrum_log = np.log(1 + spectrum_fshift)# 濾波器
n = 15
r = 20
H = narrow_notch_filter(fp, w=10, opening=30, vertical=True, horizontal=False)
# BNRF_1 = butterworth_notch_resistant_filter(fp, radius=r, uk=355, vk=0, n=n)
# BNRF_2 = butterworth_notch_resistant_filter(fp, radius=r, uk=0, vk=355, n=n)
# BNRF_3 = butterworth_notch_resistant_filter(fp, radius=r, uk=250, vk=250, n=n)
# BNRF_4 = butterworth_notch_resistant_filter(fp, radius=r, uk=-250, vk=250, n=n)
# BNRF = BNRF_1 * BNRF_2 * BNRF_3 * BNRF_4  * H
BNRF = Hfft_filter = fft * (1 - BNRF)# 濾波后的頻譜
spectrum_filter = spectrum_fft(fft_filter)
spectrum_filter_log = np.log(1 + spectrum_filter)# 傅里葉反變換
ifft = np.fft.ifft2(fft_filter)# 去中心化反變換的圖像,并取左上角的圖像
img_new = centralized_2d(ifft.real)[:M, :N]
img_new = np.clip(img_new, 0, img_new.max())
img_new = np.uint8(normalize(img_new) * 255)plt.figure(figsize=(15, 16))
# plt.subplot(221), plt.imshow(img_ori, 'gray'), plt.title('With noise'), plt.xticks([]),plt.yticks([])
# plt.subplot(222), plt.imshow(spectrum_log, 'gray'), plt.title('Spectrum'), plt.xticks([]),plt.yticks([])
# plt.subplot(223), plt.imshow(spectrum_filter_log, 'gray'), plt.title('Spectrum With Filter'), plt.xticks([]),plt.yticks([])
plt.subplot(224), plt.imshow(img_new, 'gray'), plt.title('IDFT'), plt.xticks([]),plt.yticks([])
plt.tight_layout()
plt.show()

在這里插入圖片描述

# 使用陷波帶阻濾波器濾波
img_florida = cv2.imread("DIP_Figures/DIP3E_Original_Images_CH05/Fig0519(a)(florida_satellite_original).tif", -1)#--------------------------------
fft = np.fft.fft2(img_florida)
fft_shift = np.fft.fftshift(fft)
amp_img = np.abs(np.log(1 + np.abs(fft_shift)))#--------------------------------
BNF = narrow_notch_filter(img_florida, w=5, opening=20, vertical=True, horizontal=False)fft_NNF = np.fft.fft2(BNF*255)
fft_shift_NNF = np.fft.fftshift(fft_NNF)
amp_img_NNF = np.abs(np.log(1 + np.abs(fft_shift_NNF)))#--------------------------------
f1shift = fft_shift * (BNF)
f2shift = np.fft.ifftshift(f1shift) #對新的進行逆變換
img_new = np.fft.ifft2(f2shift)#出來的是復數,無法顯示
img_new = np.abs(img_new)#調整大小范圍便于顯示
img_new = (img_new-np.amin(img_new))/(np.amax(img_new)-np.amin(img_new))fft_mask = amp_img * BNFplt.figure(figsize=(15, 16))
plt.subplot(221),plt.imshow(img_florida,'gray'),plt.title('Image with noise')
plt.subplot(222),plt.imshow(amp_img,'gray'),plt.title('FFT')
plt.subplot(223),plt.imshow(fft_mask,'gray'),plt.title('FFT with mask')
plt.subplot(224),plt.imshow(img_new,'gray'),plt.title('Denoising')
plt.tight_layout()
plt.show()

在這里插入圖片描述

最優陷波濾波

這種濾波方法的過程如下:
首先分離干擾模式的各個主要貢獻,然后從被污染圖像中減去該模式的一個可變加權部分。

首先提取干模式的主頻率分量,提取方法是在每個尖峰位置放一個陷波帶通濾波器傳遞函數HNP(u,v)H_{NP}(u, v)HNP?(u,v),則干擾噪聲模式的傅里葉變換為:
N(u,v)=HNP(u,v)G(u,v)(5.38)N(u, v) = H_{NP}(u, v)G(u, v) \tag{5.38}N(u,v)=HNP?(u,v)G(u,v)(5.38)

則有噪聲模式:
η(x,y)=J?1{HNP(u,v)G(u,v)}(5.39)\eta(x, y) = \mathfrak{J}^-1 \{ H_{NP}(u, v)G(u, v) \} \tag{5.39}η(x,y)=J?1{HNP?(u,v)G(u,v)}(5.39)

如果我們知道了噪聲模式,我們假設噪聲是加性噪聲,只可以用污染的噪聲g(x,y)g(x, y)g(x,y)減去噪聲模式η(x,y)\eta(x, y)η(x,y)可得到f^(x,y)\hat{f}(x, y)f^?(x,y),但通常這只是一個近似值。
f^(x,y)=g(x,y)?w(x,y)η(x,y)(5.40)\hat{f}(x, y) = g(x, y) - w(x, y)\eta(x, y) \tag{5.40}f^?(x,y)=g(x,y)?w(x,y)η(x,y)(5.40)
w(x,y)w(x, y)w(x,y)是一個加權函數或調制函數,這個方法的目的就是選取w(x,y)w(x, y)w(x,y),以便以某種意義的方式來優化結果。一種方法是選擇w(x,y)w(x, y)w(x,y),使f^(x,y)\hat{f}(x, y)f^?(x,y)在每點(x,y)(x, y)(x,y)的規定鄰域上的方差最小。

m×nm\times{n}m×n(奇數)的鄰域SxyS_{xy}Sxy?f^(x,y)\hat{f}(x, y)f^?(x,y)的“局部”方差估計如下:
σ2(x,y)=1mn∑(r,c)∈Sxy[f^(r,c)?f^ˉ]2(5.41)\sigma^2(x, y) = \frac{1}{mn} \sum_{(r,c)\in S_{xy}} \Big[ \hat{f}(r, c) - \bar{\hat{f}} \Big]^2 \tag{5.41}σ2(x,y)=mn1?(r,c)Sxy??[f^?(r,c)?f^?ˉ?]2(5.41)

f^ˉ\bar{\hat{f}}f^?ˉ?是鄰域f^\hat{f}f^?的平均值,
f^ˉ=1mn∑(r,c)∈Sxyf^(r,c)(5.42)\bar{\hat{f}} = \frac{1}{mn} \sum_{(r,c)\in S_{xy}} \hat{f}(r, c) \tag{5.42}f^?ˉ?=mn1?(r,c)Sxy??f^?(r,c)(5.42)

將式(5.40)代入(5.41),得
σ2(x,y)=1mn∑(r,c)∈Sxy{[g(r,c)?w(r,c)η(r,c)]?[g ̄?wη ̄]}2(5.43)\sigma^2(x, y) = \frac{1}{mn} \sum_{(r,c)\in S_{xy}} \Big\{\big[g(r, c) - w(r, c) \eta(r, c)\big] - \big[\overline{g} - \overline{w\eta} \big ] \Big\}^2\tag{5.43}σ2(x,y)=mn1?(r,c)Sxy??{[g(r,c)?w(r,c)η(r,c)]?[g??wη?]}2(5.43)

g ̄\overline{g}g?wη ̄\overline{w\eta}wη?分別是gggwηw\etawη在鄰域SxyS_{xy}Sxy?的平均值

若假設wwwSxyS_{xy}Sxy?內近似為常數,則可用該鄰域中心的www值來代替w(r,c)w(r, c)w(r,c):

w(r,c)=w(x,y)(5.44)w(r, c) = w(x, y) \tag{5.44}w(r,c)=w(x,y)(5.44)

因為w(x,y)w(x, y)w(x,y)SxyS_{xy}Sxy?中被假設為常數,因此在SxyS_{xy}Sxy?中根據w ̄=w(x,y)\overline{w} = w(x, y)w=w(x,y)

wη ̄=w(x,y)η ̄(5.45)\overline{w\eta} = w(x, y) \overline{\eta} \tag{5.45}wη?=w(x,y)η?(5.45)

η ̄\overline{\eta}η?是鄰域SxyS_{xy}Sxy?中的平均值,所以式(5.43)變為:

σ2(x,y)=1mn∑(r,c)∈Sxy{[g(r,c)?w(x,y)η(r,c)]?[g ̄?w(x,y)η ̄]}2(5.44)\sigma^2(x, y) = \frac{1}{mn} \sum_{(r,c)\in S_{xy}} \Big\{\big[g(r, c) - w(x, y) \eta(r, c)\big] - \big[\overline{g} - {w(x, y)}\overline{\eta} \big ] \Big\}^2\tag{5.44}σ2(x,y)=mn1?(r,c)Sxy??{[g(r,c)?w(x,y)η(r,c)]?[g??w(x,y)η?]}2(5.44)

要使得σ2(x,y)\sigma^2(x, y)σ2(x,y)相對w(x,y)w(x, y)w(x,y)最小,我們可以對式(5.44)求關于w(x,y)w(x, y)w(x,y)的偏導數,并令為偏導數為0;

?σ2(x,y)?w(x,y)=0(5.47)\frac{\partial{\sigma^2(x, y)}}{\partial{w(x, y)}} = 0 \tag{5.47}?w(x,y)?σ2(x,y)?=0(5.47)

求得w(x,y)w(x, y)w(x,y):
w(x,y)=gη ̄?gˉηˉη2 ̄?ηˉ2(5.48)w(x, y) = \frac{\overline{g\eta} - \bar{g}\bar{\eta}}{\overline{\eta^2} - \bar{\eta}^2}\tag{5.48}w(x,y)=η2??ηˉ?2gη??gˉ?ηˉ??(5.48)

把式(5.48)代入式(5.40)并在噪聲圖像ggg中的每個點執行這一過程,可得到完全復原的圖像。

# 這里還沒有實現,遲點再弄吧
img_mariner = cv2.imread("DIP_Figures/DIP3E_Original_Images_CH05/Fig0520(a)(NASA_Mariner6_Mars).tif", 0)
M, N = img_mariner.shape[:2]fp = pad_image(img_mariner, mode='reflect')
fp_cen = centralized_2d(fp)
fft = np.fft.fft2(fp_cen)# 中心化后的頻譜
spectrum_fshift = spectrum_fft(fft)
spectrum_log = np.log(1 + spectrum_fshift)# 未中心化的頻譜
fft_fp = np.fft.fft2(fp)
spectrum_fp = spectrum_fft(fft_fp)
spectrum_fp_log = np.log(1 + spectrum_fp)# 濾波器
n = 15
r = 20
H = butterworth_band_resistant_filter(fp, fp.shape, radius=40, w=5, n=5)
# BNRF_1 = butterworth_notch_resistant_filter(fp, radius=r, uk=355, vk=0, n=n)
# BNRF_2 = butterworth_notch_resistant_filter(fp, radius=r, uk=0, vk=355, n=n)
# BNRF_3 = butterworth_notch_resistant_filter(fp, radius=r, uk=250, vk=250, n=n)
# BNRF_4 = butterworth_notch_resistant_filter(fp, radius=r, uk=-250, vk=250, n=n)
# BNRF = BNRF_1 * BNRF_2 * BNRF_3 * BNRF_4  * Hfft_filter = fft_fp * (1 - H)
ifft = np.fft.ifft2(fft_filter)
img_new = ifft.real[:M, :N]# # show = spectrum_fp_log * H
# fft_filter = fft * BNRF# # 濾波后的頻譜
# spectrum_filter = spectrum_fft(fft_filter)
# spectrum_filter_log = np.log(1 + spectrum_filter)# # 傅里葉反變換
# ifft = np.fft.ifft2(fft_filter)# 去中心化反變換的圖像,并取左上角的圖像
# img_new = centralized_2d(ifft.real)[:M, :N]
# img_new = np.clip(img_new, 0, img_new.max())
# img_new = np.uint8(normalize(img_new) * 255)plt.figure(figsize=(15, 15))
plt.subplot(221), plt.imshow(img_mariner, 'gray'), plt.title('With noise'), plt.xticks([]),plt.yticks([])
plt.subplot(222), plt.imshow(spectrum_log, 'gray'), plt.title('Spectrum Centralied'), plt.xticks([]),plt.yticks([])
plt.subplot(223), plt.imshow(spectrum_fp_log, 'gray'), plt.title('Spectrum Not Centralized'), plt.xticks([]),plt.yticks([])
plt.subplot(224), plt.imshow(img_new, 'gray'), plt.title('IDFT'), plt.xticks([]),plt.yticks([])
plt.tight_layout()
plt.show()

在這里插入圖片描述

# 巴特沃斯帶阻陷波濾波器 BNRF
img_dst = img_mariner - img_new
plt.figure(figsize=(16, 16))
plt.subplot(221), plt.imshow(img_dst, 'gray'), plt.title('BNF_1')
# plt.subplot(222), plt.imshow(BNF_2, 'gray'), plt.title('BNF_2')
# plt.subplot(223), plt.imshow(BNF_3, 'gray'), plt.title('BNF_3')
# plt.subplot(224), plt.imshow(BNF_dst, 'gray'), plt.title('BNF_dst')
plt.tight_layout()
plt.show()

在這里插入圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/260586.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/260586.shtml
英文地址,請注明出處:http://en.pswp.cn/news/260586.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Android之Menu動態改變文字

Menu創建&#xff1a; Override//這里遇到一個問題add的是MenuItem的idpublic boolean onCreateOptionsMenu(Menu menu) {// TODO Auto-generated method stubmenu.add(0,1023, 0, "一");menu.add(0,1022, 1, "開啟線程");Log.e("onCreateOptionsMenu…

iOS 開發周報:Apple 發布 iPhone 7 / 7 Plus 、Apple Watch 2 等新品

新聞\\Apple 發布 iPhone 7 / 7 Plus 、Apple Watch 2 等新品&#xff1a;Apple 正式發布了 iPhone 7 / 7 Plus、Apple Watch 2 新品&#xff0c;帶來 AirPods 無線耳機&#xff0c;并把馬里奧帶進了 iOS。iPhone 7 新增亮黑色&#xff0c;移除3.5mm 耳機孔&#xff0c;支持 IP…

python寫界面c這算法_插入算法分別從C,java,python三種語言進行書寫

真正學懂計算機的人&#xff08;不只是“編程匠”&#xff09;都對數學有相當的造詣&#xff0c;既能用科學家的嚴謹思維來求證&#xff0c;也能用工程師的務實手段來解決問題——而這種思維和手段的最佳演繹就是“算法”。 作為一個初級編程人員或者說是一個程序員&#xff0c…

去掉xcode中警告的一些經驗

1、編譯時&#xff0c;編譯警告忽略掉某些文件 只需在在文件的Compiler Flags 中加入 -w 參數&#xff0c;例如&#xff1a; 2、編譯時&#xff0c;編譯警告忽略掉某段代碼 #pragma clang diagnostic push#pragma clang diagnostic ignored "-Wmultichar"char b df;…

富士施樂3065掃描教程_全面支持IT國產化 富士施樂70款機型獲統信UOS兼容認證

最近&#xff0c;富士施樂&#xff08;中國&#xff09;有限公司宣布共70款機型獲得國產操作系統統信UOS的兼容認證&#xff0c;其中包括新一代ApeosPort旗艦智能型數碼多功能機、多功能一體機/打印機、生產型數字印刷系統。這是繼獲得中標麒麟、龍芯和兆芯兼容認證后&#xff…

Flash系統字體中的中文字體問題

在flash中使用as來改變textfield的中文字體 &#xff0c;遇到發布版本超過10.2的時候&#xff0c;會悲劇&#xff01;不支持使用中文名稱來改變字體。 解決辦法&#xff1a;1&#xff09;使用英文名稱。2&#xff09;發布的版本低于10.2 label:TextField new TextField(); for…

第5章 Python 數字圖像處理(DIP) - 圖像復原與重建13 - 空間濾波 - 線性位置不變退化 - 退化函數估計、運動模糊函數

標題線性位置不變退化估計退化函數采用觀察法估計退化函數采用試驗法估計退化函數采用建模法估計退化函數運動模糊函數OpenCV Motion Blur在這一節中&#xff0c;得到的結果&#xff0c;有些不是很好&#xff0c;我需要再努力多找資料&#xff0c;重新完成學習&#xff0c;如果…

視覺感受排序算法

1. 快速排序 介紹&#xff1a; 快速排序是由東尼霍爾所發展的一種排序算法。在平均狀況下&#xff0c;排序 n 個項目要Ο(n log n)次比較。在最壞狀況下則需要Ο(n2)次比較&#xff0c;但這種狀況并不常見。事實上&#xff0c;快速排序通常明顯比其他Ο(n log n) 算法更快&…

python如何自定義函數_python如何自定義函數_后端開發

c語言特點是什么_后端開發 c語言特點是&#xff1a;1、語言簡潔、緊湊&#xff0c;使用方便、靈活&#xff1b;2、運算符豐富&#xff1b;3、數據結構豐富&#xff0c;具有現代化語言的各種數據結構&#xff1b;4、具有結構化的控制語句&#xff1b;5、語法限制不太嚴度格&…

js/css 檢測移動設備方向的變化 判斷橫豎屏幕

js&#xff0f;css 檢測移動設備方向的變化 判斷橫豎屏幕 方法一&#xff1a;用觸發手機的橫屏和豎屏之間的切換的事件 window.addEventListener("orientationchange", function() { // 宣布新方向的數值 alert(window.orientation); }, false); // 方法二&#xff1…

第5章 Python 數字圖像處理(DIP) - 圖像復原與重建14 - 逆濾波

標題逆濾波逆濾波逆濾波 逆濾波 圖像的退化函數已知或者由前面的方法獲取退化函數&#xff0c;則可以直接逆濾波 F^(u,v)G(u,v)H(u,v)(5.78)\hat{F}(u,v) \frac{G(u,v)}{H(u,v)} \tag{5.78}F^(u,v)H(u,v)G(u,v)?(5.78) F^(u,v)F(u,v)N(u,v)H(u,v)(5.79)\hat{F}(u,v) F(u, …

SetFormFullScreen()窗體全屏顯示

{讓窗體全屏顯示} //SetFormFullScreen(Form1); procedure SetFormFullScreen(Form:TForm); begin Form.BorderStyle:bsNone; Form.WindowState:wsMaximized; Form.Color:clBlack; end; 通過 為知筆記 發布轉載于:https://www.cnblogs.com/xe2011/archive/2012/07/26/2609327.h…

表示自己從頭開始的句子_微信拍一拍后綴幽默回復有趣的句子 拍了拍唯美內容文案...

閱讀本文前&#xff0c;請您先點擊上面的“藍色字體”&#xff0c;再點擊“關注”&#xff0c;這樣您就可以繼續免費收到文章了。每天都會有分享&#xff0c;都是免費訂閱&#xff0c;請您放心關注。注圖文來源網絡&#xff0c;侵刪 …

HoloLens開發手記 - Unity之Tracking loss

當HoloLens設備不能識別到自己在世界中的位置時&#xff0c;應用就會發生tracking loss。默認情況下&#xff0c;Unity會暫停Update更新循環并顯示一張閃屏圖片給用戶。當設備重新能追蹤到位置時&#xff0c;閃屏圖片會消失&#xff0c;并且Update循環還會繼續。 此外&#xff…

運維學python用不上_不會Python開發的運維終將被淘汰?

簡介 Python 語言是一種面向對象、直譯式計算機程序設計語言&#xff0c;由 Guido van Rossum 于 1989 年底發明。Python 語法簡捷而清晰&#xff0c;具有豐富和強大的類庫&#xff0c;具有可擴展性和可嵌入性&#xff0c;是現代比較流行的語言。最流行的語言 IEEE Spectrum 的…

windows驅動開發詳解學習筆記

1. windows驅動分兩類&#xff0c;NT式驅動和WDM驅動&#xff0c;后者支持即插即用&#xff1b; 2. DriverEntry是入口函數&#xff0c;傳入參數&#xff1a;pDriverObject由IO管理器傳入&#xff1b; 3. WDM驅動中&#xff0c;AddDevice創建設備對象&#xff0c;由PnP管理器調…

第5章 Python 數字圖像處理(DIP) - 圖像復原與重建15 - 最小均方誤差(維納)濾波

標題最小均方誤差&#xff08;維納&#xff09;濾波最小均方誤差&#xff08;維納&#xff09;濾波 目標是求未污染圖像fff的一個估計f^\hat{f}f^?&#xff0c;使它們之間的均方誤差最小。 e2E{(f?f^)2}(5.80)e^2 E \big\{(f - \hat{f})^2 \big\} \tag{5.80}e2E{(f?f^?)2…

入網許可證_入網許可證怎么辦理,申請流程

移動通信系統及終端投資項目核準的若干規定》的出臺&#xff0c;打開了更多企業進入手機業的大門&#xff0c;然而一些企業在關心拿到手機牌照后&#xff0c;是不是就是意味了拿到入網許可證&#xff0c;就可以上市銷售。某些廠商認為:"手機牌照實行核準制&#xff0c;意味…

OpenGL編程低級錯誤范例手冊

看到一篇OpenGL編程的錯誤總結&#xff0c;對我初學來說應該比較有用&#xff0c;先保留&#xff0c;嘿嘿... 謝謝原文作者的貢獻&#xff1a;http://www.cnitblog.com/linghuye/archive/2005/08/13/1845.html 1.沒有glDisable(GL_TEXTURE_2D),導致基本幾何作圖全部失敗。 2.鏡…

C/C++ 中變量的聲明、定義、初始化的區別

今天突然思考到這樣的一個問題&#xff0c;發現已經在學習或者編寫程序的時候壓根就沒有注意到這些&#xff0c;經過比較這些還是有很大的區別的。 int i;//聲明 不分配地址空間 int j1&#xff1b;//轉載于:https://www.cnblogs.com/kuoyan/p/3687391.html