关于深度学习:Python图像处理频域滤波降噪和图像增强

6次阅读

共计 8041 个字符,预计需要花费 21 分钟才能阅读完成。

图像处理曾经成为咱们日常生活中不可或缺的一部分,波及到社交媒体和医学成像等各个领域。通过数码相机或卫星照片和医学扫描等其余起源取得的图像可能须要预处理以打消或加强噪声。频域滤波是一种可行的解决方案,它能够在加强图像锐化的同时打消噪声。

疾速傅里叶变换 (FFT) 是一种将图像从空间域变换到频率域的数学技术,是图像处理中进行频率变换的要害工具。通过利用图像的频域示意,咱们能够依据图像的频率内容无效地剖析图像,从而简化滤波程序的利用以打消噪声。本文将探讨图像从 FFT 到逆 FFT 的频率变换所波及的各个阶段,并联合 FFT 位移和逆 FFT 位移的应用。

本文应用了三个 Python 库,即 openCV、Numpy 和 Matplotlib。

 importcv2
 importnumpyasnp
 frommatplotlibimportpyplotasplt
 img=cv2.imread('sample.png',0) # Using 0 to read image in grayscale mode
 plt.imshow(img, cmap='gray')  #cmap is used to specify imshow that the image is in greyscale
 plt.xticks([]), plt.yticks([])  # remove tick marks
 plt.show()

1、疾速傅里叶变换(FFT)

疾速傅里叶变换 (FFT) 是一种广泛应用的数学技术,它容许图像从空间域转换到频率域,是频率变换的根本组成部分。利用 FFT 剖析,能够失去图像的周期性,并将其划分为不同的频率重量,生成图像频谱,显示每个图像各自频率成分的振幅和相位。

 f=np.fft.fft2(img)  #the image 'img' is passed to np.fft.fft2() to compute its 2D Discrete Fourier transform f 
 mag=20*np.log(np.abs(f))
 plt.imshow(mag, cmap='gray') #cmap='gray' parameter to indicate that the image should be displayed in grayscale.
 plt.title('Magnitude Spectrum') 
 plt.xticks([]), plt.yticks([])
 plt.show()

下面代码应用 np.abs()计算傅里叶变换 f 的幅度,np.log()转换为对数刻度,而后乘以 20 失去以分贝为单位的幅度。这样做是为了使幅度谱更容易可视化和解释。

2、FFT 位移

为了使滤波算法利用于图像,利用 FFT 移位将图像的零频率重量被挪动到频谱的核心

 fshift = np.fft.fftshift(f)
 mag = 20*np.log(np.abs(fshift)) 
 plt.imshow(mag, cmap = 'gray')
 plt.title('Centered Spectrum'), plt.xticks([]), plt.yticks([])
 plt.show()

3、过滤

频率变换的的一个目标是应用各种滤波算法来升高噪声和进步图像品质。两种最罕用的图像锐化滤波器是 Ideal high-pass filter 和 Gaussian high-pass filter。这些滤波器都是应用的通过疾速傅里叶变换 (FFT) 办法取得的图像的频域示意。

Ideal high-pass filter(现实滤波器)是一种有限长的、具备有限频带宽和现实通带和阻带响应的滤波器。其通带内所有频率的信号都被齐全传递,而阻带内所有频率的信号则齐全被克制。

在频域上,现实滤波器的幅频响应为:

  • 在通带内,幅频响应为 1
  • 在阻带内,幅频响应为 0

在时域上,现实滤波器的冲激响应为:

  • 在通带内,冲激响应为一个有限长的单位冲激函数序列
  • 在阻带内,冲激响应为零

因为现实滤波器在频域上具备有限带宽,因而它无奈在理论利用中实现。理论中应用的数字滤波器通常是基于现实滤波器的迫近,所以才被成为只是一个 Ideal。

高斯高通滤波器(Gaussian high-pass filter)是一种在数字图像处理中罕用的滤波器。它的作用是在图像中保留高频细节信息,并克制低频信号。该滤波器基于高斯函数,具备润滑的频率响应,能够适应各种图像细节。

高斯高通滤波器的频率响应能够示意为:

H(u,v) = 1 – L(u,v)

其中,L(u,v)是一个低通滤波器,它能够用高斯函数示意。通过将低通滤波器的响应从 1 中减去,能够失去一个高通滤波器的响应。在理论中,通常应用不同的参数设置来调整高斯函数,以达到不同的滤波成果。

圆形掩膜(disk-shaped images)是用于定义在图像中进行傅里叶变换时要保留或克制的频率重量。在这种状况下,现实滤波器通常是指现实的低通或高通滤波器,能够在频域上抉择保留或克制特定频率范畴内的信号。将这个现实滤波器利用于图像的傅里叶变换后,再进行逆变换,能够失去通过滤波器解决后的图像。

具体的细节咱们就不介绍了,间接来看代码:

上面函数是生成现实高通和低通滤波器的圆形掩膜

 importmath
 defdistance(point1,point2):
     returnmath.sqrt((point1[0]-point2[0])**2+ (point1[1]-point2[1])**2)
 
 defidealFilterLP(D0,imgShape):
     base=np.zeros(imgShape[:2])
     rows, cols=imgShape[:2]
     center= (rows/2,cols/2)
     forxinrange(cols):
         foryinrange(rows):
             ifdistance((y,x),center) <D0:
                 base[y,x] =1
     returnbase
 
 defidealFilterHP(D0,imgShape):
     base=np.ones(imgShape[:2])
     rows, cols=imgShape[:2]
     center= (rows/2,cols/2)
     forxinrange(cols):
         foryinrange(rows):
             ifdistance((y,x),center) <D0:
                 base[y,x] =0
     returnbase

上面函数生成一个高斯高、低通滤波器与所需的圆形掩膜

 importmath
 defdistance(point1,point2):
     returnmath.sqrt((point1[0]-point2[0])**2+ (point1[1]-point2[1])**2)
 
 defgaussianLP(D0,imgShape):
     base=np.zeros(imgShape[:2])
     rows, cols=imgShape[:2]
     center= (rows/2,cols/2)
     forxinrange(cols):
         foryinrange(rows):
             base[y,x] =math.exp(((-distance((y,x),center)**2)/(2*(D0**2))))
     returnbase
 
 defgaussianHP(D0,imgShape):
     base=np.zeros(imgShape[:2])
     rows, cols=imgShape[:2]
     center= (rows/2,cols/2)
     forxinrange(cols):
         foryinrange(rows):
             base[y,x] =1-math.exp(((-distance((y,x),center)**2)/(2*(D0**2))))
     returnbase

过滤示例

 fig, ax=plt.subplots(2, 2) # create a 2x2 grid of subplots
 fig.suptitle('Filters') # set the title for the entire figure
 
 # plot the first image in the top-left subplot
 im1=ax[0, 0].imshow(np.abs(idealFilterLP(50, img.shape)), cmap='gray')
 ax[0, 0].set_title('Low Pass Filter of Diameter 50 px')
 ax[0, 0].set_xticks([])
 ax[0, 0].set_yticks([])
 
 # plot the second image in the top-right subplot
 im2=ax[0, 1].imshow(np.abs(idealFilterHP(50, img.shape)), cmap='gray')
 ax[0, 1].set_title('High Pass Filter of Diameter 50 px')
 ax[0, 1].set_xticks([])
 ax[0, 1].set_yticks([])
 
 # plot the third image in the bottom-left subplot
 im3=ax[1, 0].imshow(np.abs(gaussianLP(50 ,img.shape)), cmap='gray')
 ax[1, 0].set_title('Gaussian Filter of Diameter 50 px')
 ax[1, 0].set_xticks([])
 ax[1, 0].set_yticks([])
 
 # plot the fourth image in the bottom-right subplot
 im4=ax[1, 1].imshow(np.abs(gaussianHP(50 ,img.shape)), cmap='gray')
 ax[1, 1].set_title('Gaussian Filter of Diameter 50 px')
 ax[1, 1].set_xticks([])
 ax[1, 1].set_yticks([])
 
 # adjust the spacing between subplots
 fig.subplots_adjust(wspace=0.5, hspace=0.5)
 
 # save the figure to a file
 fig.savefig('filters.png', bbox_inches='tight')

相乘过滤器和移位的图像失去过滤图像

为了取得具备所需频率响应的最终滤波图像,要害是在频域中对移位后的图像与滤波器进行逐点乘法。

这个过程将两个图像元素的对应像素相乘。例如,当利用低通滤波器时,咱们将对移位的傅里叶变换图像与低通滤波器逐点相乘。

此操作克制高频并保留低频,对于高通滤波器反之亦然。这个乘法过程对于去除不须要的频率和加强所需的频率是必不可少的,从而产生更清晰和更清晰的图像。

它使咱们可能取得冀望的频率响应,并在频域取得最终滤波图像。

4、乘法滤波器(Multiplying Filter)和平移后的图像(Shifted Image)

乘法滤波器是一种以像素值为权重的滤波器,它通过将滤波器的权重与图像的像素值相乘,来取得滤波后的像素值。具体地,假如乘法滤波器的权重为 h(i,j),图像的像素值为 f(m,n),那么滤波后的像素值 g(x,y)能够示意为:

g(x,y) = ∑∑ f(m,n)h(x-m,y-n)

其中,∑∑示意对所有的 (m,n) 进行求和。

平移后的图像是指将图像进行平移操作后的后果。平移操作通常是指将图像的像素沿着 x 轴和 y 轴方向进行平移。平移后的图像与原始图像具备雷同的大小和分辨率,但它们的像素地位产生了变动。在滤波操作中,平移后的图像能够用于与滤波器进行卷积运算,以实现滤波操作。

此操作克制高频并保留低频,对于高通滤波器反之亦然。这个乘法过程对于去除不须要的频率和加强所需的频率是必不可少的,从而产生更清晰和更清晰的图像。

它使咱们可能取得冀望的频率响应,并在频域取得最终滤波图像。

 fig, ax=plt.subplots()
 im=ax.imshow(np.log(1+np.abs(fftshifted_image*idealFilterLP(50,img.shape))), cmap='gray')
 ax.set_title('Filtered Image in Frequency Domain')
 ax.set_xticks([])
 ax.set_yticks([])
 
 fig.savefig('filtered image in freq domain.png', bbox_inches='tight')

在可视化傅里叶频谱时,应用 np.log(1+np.abs(x))和 20*np.log(np.abs(x))之间的抉择是集体爱好的问题,能够取决于具体的应用程序。

个别状况下会应用 Np.log (1+np.abs(x)),因为它通过压缩数据的动静范畴来帮忙更清晰地可视化频谱。这是通过取数据绝对值的对数来实现的,并加上 1 以防止取零的对数。

而 20*np.log(np.abs(x))将数据按 20 倍缩放,并对数据的绝对值取对数,这能够更容易地看到不同频率之间较小的幅度差别。然而它不会像 np.log(1+np.abs(x))那样压缩数据的动静范畴。

这两种办法都有各自的长处和毛病,最终取决于具体的应用程序和集体偏好。

5、逆 FFT 位移

在频域滤波后,咱们须要将图像移回原始地位,而后利用逆 FFT。为了实现这一点,须要应用逆 FFT 移位,它反转了后面执行的移位过程。

 fig, ax=plt.subplots()
 im=ax.imshow(np.log(1+np.abs(np.fft.ifftshift(fftshifted_image*idealFilterLP(50,img.shape)))), cmap='gray')
 ax.set_title('Filtered Image inverse fft shifted')
 ax.set_xticks([])
 ax.set_yticks([])
 
 fig.savefig('filtered image inverse fft shifted.png', bbox_inches='tight')

6、疾速傅里叶逆变换(IFFT)

疾速傅里叶逆变换 (IFFT) 是图像频率变换的最初一步。它用于将图像从频域传输回空间域。这一步的后果是在空间域中与原始图像相比,图像缩小了噪声并进步了清晰度。

 fig, ax=plt.subplots()
 im=ax.imshow(np.log(1+np.abs(np.fft.ifft2(np.fft.ifftshift(fftshifted_image*idealFilterLP(50,img.shape))))), cmap='gray')
 ax.set_title('Final Filtered Image In Spatial Domain')
 ax.set_xticks([])
 ax.set_yticks([])
 
 fig.savefig('final filtered image.png', bbox_inches='tight')

总结

咱们再把所有的操作串在一起显示,

函数绘制所有图像

 defFreq_Trans(image, filter_used):
     img_in_freq_domain=np.fft.fft2(image)
 
     # Shift the zero-frequency component to the center of the frequency spectrum
     centered=np.fft.fftshift(img_in_freq_domain)
 
     # Multiply the filter with the centered spectrum
     filtered_image_in_freq_domain=centered*filter_used
 
     # Shift the zero-frequency component back to the top-left corner of the frequency spectrum
     inverse_fftshift_on_filtered_image=np.fft.ifftshift(filtered_image_in_freq_domain)
 
     # Apply the inverse Fourier transform to obtain the final filtered image
     final_filtered_image=np.fft.ifft2(inverse_fftshift_on_filtered_image)
 
     returnimg_in_freq_domain,centered,filter_used,filtered_image_in_freq_domain,inverse_fftshift_on_filtered_image,final_filtered_image

应用高通、低通现实滤波器和高斯滤波器的直径别离为 50、100 和 150 像素,展现它们对加强图像清晰度的影响。

 fig, axs=plt.subplots(12, 7, figsize=(30, 60))
 
 filters= [(f, d) forfin [idealFilterLP, idealFilterHP, gaussianLP, gaussianHP] fordin [50, 100, 150]]
 
 forrow, (filter_name, filter_diameter) inenumerate(filters):
     # Plot each filter output on a separate subplot
     result=Freq_Trans(img, filter_name(filter_diameter, img.shape))
 
     forcol, title, img_arrayinzip(range(7), 
     ["Original Image", "Spectrum", "Centered Spectrum", f"{filter_name.__name__} of Diameter {filter_diameter} px",
     f"Centered Spectrum multiplied by {filter_name.__name__}", "Decentralize", "Processed Image"],
     [img, np.log(1+np.abs(result[0])), np.log(1+np.abs(result[1])), np.abs(result[2]), np.log(1+np.abs(result[3])), 
      np.log(1+np.abs(result[4])), np.abs(result[5])]):
         
         axs[row, col].imshow(img_array, cmap='gray')
         axs[row, col].set_title(title)
 
 plt.tight_layout()
 plt.savefig('all_processess.png', bbox_inches='tight')
 plt.show()

能够看到,当扭转圆形掩膜的直径时,对图像清晰度的影响会有所不同。随着直径的减少,更多的频率被克制,从而产生更平滑的图像和更少的细节。减小直径容许更多的频率通过,从而产生更清晰的图像和更多的细节。为了达到现实的成果,抉择适合的直径是很重要的,因为应用太小的直径会导致过滤器不够无效,而应用太大的直径会导致失落太多的细节。

一般来说,高斯滤波器因为其平滑性和鲁棒性,更罕用于图像处理工作。在某些利用中,须要更尖利的截止,现实滤波器可能更适宜。

利用 FFT 批改图像频率是一种无效的升高噪声和进步图像锐度的办法。这包含应用 FFT 将图像转换到频域,应用适当的技术过滤噪声,并应用反 FFT 将批改后的图像转换回空间域。通过了解和实现这些技术,咱们能够进步各种应用程序的图像品质。

https://avoid.overfit.cn/post/8768ec2a60a0456eab327abc33146508

作者:Muhammad Ahmed

正文完
 0