# 傅立葉轉換（五）

``````import cv2
import numpy as np

f_range = 15 # 低頻範圍
rows, cols = img.shape
cy, cx = int(rows / 2), int(cols/2)

# 傅立葉轉換後並位移低頻
shifted = np.fft.fftshift(np.fft.fft2(img))

max_amp = np.max(np.abs(shifted))

# 低頻範圍內設為 0
shifted[cy - f_range:cy + f_range, cx - f_range:cx + f_range] = 0

# 顯示一下頻域目前的樣子
cv2.imshow('FFT 2D', np.abs(shifted) / max_amp * 255)

# 逆轉換
inversed = np.fft.ifft2(np.fft.ifftshift(shifted))
inversed_img = np.abs(inversed).astype('uint8')
cv2.imshow('INVERSE FFT 2D', inversed_img)

cv2.waitKey(0)
cv2.destroyAllWindows()
``````

``````import cv2
import numpy as np

f_range = 50 # 低頻範圍
rows, cols = img.shape
cy, cx = int(rows / 2), int(cols/2)

x = np.arange(-cx, cx)
X, Y = np.meshgrid(np.arange(-cx, cx), np.arange(-cy, cy))

# 位移後的頻域表示
shifted = np.fft.fftshift(np.fft.fft2(img))

max_amp = np.max(np.abs(shifted))

# 低頻範圍內設為 0
shifted[X ** 2 + Y ** 2 > f_range ** 2] = 0

cv2.imshow('FFT 2D', np.abs(shifted) / max_amp * 255)

# 轉回圖片
inversed = np.fft.ifft2(np.fft.ifftshift(shifted))
inversed_img = np.abs(inversed).astype('uint8')
cv2.imshow('INVERSE FFT 2D', inversed_img)

cv2.waitKey(0)
cv2.destroyAllWindows()
``````