原为url:https://www.cnblogs.com/my-love-is-python/p/10406038.html
效果图:
from turtle import shape
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 傅里叶变化--将图像从空间域转换为频率域
# 通常呈现中间亮,周围暗,是因为对于低频而言,波动较大,因此呈现亮,对于高频而言,波动较小,因此呈现暗
# 读取图片
img=cv2.imread('images/1.png',0)
# 进行float32形式转换
float32_img = np.float32(img)
# 进行傅里叶变化
dft=cv2.dft(float32_img,flags=cv2.DFT_COMPLEX_OUTPUT)
# 将图像中的低频部分移动到图像的中心
dftshift=np.fft.fftshift(dft)
# 使用cv2.magnitude将实部和虚部转换为实部,乘以20是为了使得结果更大
result=20*np.log(cv2.magnitude(dftshift[:,:,0],dftshift[:,:,1]))
plt.subplot(331), plt.imshow(img, cmap='gray')
plt.title('original'),plt.axis('off')
plt.subplot(332),plt.imshow(result,cmap='gray')
plt.title('fftImage'), plt.axis('off')
# 只保留低频,即进行低通滤波,因为高频表示是一些细节,即图像的轮廓和边缘,失去了高频部分,图像就容易变得模糊
# 求得图像的中心点位置
crow, ccol = int(img.shape[0] / 2), int(img.shape[1] / 2)
# 定义掩模:生成的掩模中间为1周围为0
mask_withlow = np.zeros((img.shape[0], img.shape[1], 2), np.uint8)
masklen = 50
mask_withlow[crow-masklen:crow+masklen, ccol-masklen:ccol+masklen] = 1
# 将掩模与傅里叶变化后图像相乘,保留掩膜为1的部分
mask_lowimg = dftshift * mask_withlow
result2=20*np.log(cv2.magnitude(mask_lowimg[:,:,0],mask_lowimg[:,:,1]))
# 使用np.fft.ifftshift 将低频移动到原来的位置
imglow_idf = np.fft.ifftshift(mask_lowimg)
# 使用cv2.idft进行傅里叶的反变化
imglow_idf = cv2.idft(imglow_idf)
# 使用cv2.magnitude转化为空间域内
imglow_idf = cv2.magnitude(imglow_idf[:, :, 0], imglow_idf[:, :, 1])
plt.subplot(334),plt.imshow(result2,cmap='gray')
plt.title('fftImageWithLow'), plt.axis('off')
plt.subplot(335),plt.imshow(imglow_idf,cmap='gray')
plt.title('rfftImageWithLow'), plt.axis('off')
# 保留图像的高频部分
mask_withHigh = np.ones((img.shape[0], img.shape[1], 2), np.uint8)
mask_withHigh[crow-masklen:crow+masklen, ccol-masklen:ccol+masklen] = 0
mask_highimg = dftshift * mask_withHigh
result3=20*np.log(cv2.magnitude(mask_highimg[:,:,0],mask_highimg[:,:,1]))
imghigh_idf = np.fft.ifftshift(mask_highimg)
imghigh_idf = cv2.idft(imghigh_idf)
imghigh_idf = cv2.magnitude(imghigh_idf[:, :, 0], imghigh_idf[:, :, 1])
plt.subplot(337),plt.imshow(result3,cmap='gray')
plt.title('fftImageWithHigh'), plt.axis('off')
plt.subplot(338),plt.imshow(imghigh_idf,cmap='gray')
plt.title('rfftImageWithHigh'), plt.axis('off')
plt.show()