文章目录
- 傅里叶变换
-
- 得到图片傅里叶变换频谱
- 进行 shift 操作
- 进行低通滤波(只保留中间低频的部分)
- 高通滤波
import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as c
def cv_show(img):
cv2.imshow("img",img)
cv2.waitKey(0)
def cv_read(img_file,gray=True):
if gray == True:
return cv2.imread(img_file,0)
else:
return cv2.imread(img_file)
- 下文中使用的图片为 lena:
傅里叶变换
得到图片傅里叶变换频谱
img = cv_read("./img.png")
float32_img = np.float32(img)
dft = cv2.dft(float32_img, flags=cv2.DFT_COMPLEX_OUTPUT)
cv_show(img)
dft.shape
(200, 200, 2)
'''这个时候,四个角的亮的部分是低频信号,我们通常通过 shift 把他们转换到中间位置'''
magnitude_spectrum = 20 * np.log(cv2.magnitude(dft[:,:,0],dft[:,:,1]))
plt.imshow(magnitude_spectrum,cmap=c.jet)
进行 shift 操作
dft_shift = np.fft.fftshift(dft)
magnitude_spectrum = 20 * np.log(cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1]))
plt.imshow(magnitude_spectrum,c.jet)
进行低通滤波(只保留中间低频的部分)
lowpass_mask = np.zeros((*img.shape,2),np.uint8)
midpoint = (int(img.shape[0] / 2),int(img.shape[1] / 2))
midpointx = midpoint[0]
midpointy = midpoint[1]
'''人为指定矩形区域,中心点上下左右都30个像素'''
lowpass_mask[midpointx-30 : midpointx+30, midpointy-30:midpointy+30] = 1
dft_shift = dft_shift * lowpass_mask
magnitude_spectrum = 20 * np.log(cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1]))
plt.imshow(magnitude_spectrum,c.jet)
f_ishift = np.fft.ifftshift(dft_shift)
magnitude_spectrum = 20 * np.log(cv2.magnitude(f_ishift[:,:,0],f_ishift[:,:,1]))
plt.imshow(magnitude_spectrum)
img_ = cv2.idft(f_ishift)
img_.shape
(200, 200, 2)
show = np.hstack((img_[:,:,0],img_[:,:,1]))
plt.imshow(show,cmap=c.jet)
cv_show(show)
img_back = cv2.magnitude(img_[:,:,0],img_[:,:,1])
cv_show(img_back)
fig,(a,b) = plt.subplots(1,2)
a.imshow(img,cmap="gray")
b.imshow(img_back,cmap="gray")
plt.show()
高通滤波
img = cv_read("./img.png")
float32_img = np.float32(img)
dft = cv2.dft(float32_img, flags=cv2.DFT_COMPLEX_OUTPUT)
dft_shift = np.fft.fftshift(dft)
center_x,center_y = int(img.shape[0] / 2), int(img.shape[1] / 2)
highpass_mask = np.ones((*img.shape,2),np.uint8)
highpass_mask[center_x-30:center_x+30,center_y-30:center_y+30] = 0
f_shift = dft_shift * highpass_mask
f_ishift = np.fft.ifftshift(f_shift)
img_ = cv2.idft(f_ishift)
img_back = cv2.magnitude(img_[:,:,0],img_[:,:,1])
fig,(a,b) = plt.subplots(1,2)
a.imshow(img,cmap="gray")
b.imshow(img_back,cmap="gray")
plt.show()