Skip to content

Instantly share code, notes, and snippets.

@JustinSDK
Created May 24, 2021 09:00
Show Gist options
  • Save JustinSDK/d53098bdf04defbdfa605652e47d1b66 to your computer and use it in GitHub Desktop.
Save JustinSDK/d53098bdf04defbdfa605652e47d1b66 to your computer and use it in GitHub Desktop.
傅立葉轉換尋找圖像邊緣
import cv2
import numpy as np
f_range = 15 # 低頻範圍
# 圖片來源:https://openhome.cc/Gossip/images/caterpillar.jpg
img = cv2.imread('caterpillar.jpg', cv2.IMREAD_GRAYSCALE)
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment