傅里叶变换分离高频低频信息
2020-05-31 本文已影响0人
原上的小木屋
傅里叶变换高通滤波与低通滤波例子
img = cv2.imread(r'C:\Users\root\Desktop\1.jpg') #读取图像
plt.imshow(img, cmap=plt.cm.gray) #展示图像
plt.axis('off') #显示时不显示坐标轴
plt.show() #展示原图
img = img.mean(axis=-1) #把RGB分量均分叠加到一个通道
#plt.imsave('gray_raccoon.jpg', np.dstack((img.astype(np.uint8), img.astype(np.uint8), img.astype(np.uint8))))
img = np.fft.fft2(img)#对图像进行傅里叶变换
img = np.fft.fftshift(img)#将低频区域移向中心
fourier = np.abs(img)#取频谱图幅度
magnitude_spectrum = np.log(fourier)#对幅度取对数,映射到0-255之间方便作图
plt.imshow(magnitude_spectrum.astype(np.uint8), cmap=plt.cm.gray)#展示频谱图
plt.axis('off')
plt.show() # image after fourier transform
#plt.imsave('fourier_raccoon.jpg', 14*np.dstack((magnitude_spectrum.astype(np.uint8),magnitude_spectrum.astype(np.uint8),magnitude_spectrum.astype(np.uint8))))
x,y = img.shape #提取图像尺寸
lowF = np.zeros((x, y)) #进行低通滤波
lowF = lowF.astype(np.complex128) #将图像矩阵转复数
window_shape = (10, 10) #滤波空间大小设置
lowF[int(x / 2) - window_shape[0]:int(x / 2) + window_shape[0],int(y / 2) - window_shape[1]:int(y / 2) + window_shape[1]] = \
img[int(x / 2) - window_shape[0]:int(x / 2) + window_shape[0],int(y / 2) - window_shape[1]:int(y / 2) + window_shape[1]] #保留原图低频区域
lowF_im = np.fft.ifft2(lowF) #傅里叶反变换
lowF_im = np.abs(lowF_im) #取幅度大小
lowF_im[lowF_im > 255] = 255 #截断大于255的像素点
plt.imshow(lowF_im.astype(np.uint8), cmap='gray') #展示图像
plt.axis('off')
plt.show()
#plt.imsave('LowF_raccoon.jpg', np.dstack((lowF_im.astype(np.uint8), lowF_im.astype(np.uint8), lowF_im.astype(np.uint8))))
highF = np.zeros((x, y)) #进行高通滤波
highF = highF.astype(np.complex128)
window_shape = (10, 10) #高通滤波空间大小
highF[0:window_shape[0], :] = img[0:window_shape[0], :] #保留原图高频区域
highF[x - window_shape[0]:x, :] = img[x - window_shape[0]:x, :] #保留原图高频区域
highF[:, 0:window_shape[1]] = img[:, 0:window_shape[1]]#保留原图高频区域
highF[:, y - window_shape[1]:y] = img[:, y - window_shape[1]:y]#保留原图高频区域
highF_im = np.fft.ifft2(highF)#傅里叶反变换
highF_im = np.abs(highF_im)
highF_im[highF_im > 255] = 255
plt.imshow(highF_im.astype(np.uint8), cmap='gray')
plt.axis('off')
plt.show()