[英]Undo np.fft.fft2 to get the original image
我剛剛開始學習圖像頻率域。
我有這個功能:
def fourier_transform(img):
f = np.fft.fft2(img)
fshift = np.fft.fftshift(f)
magnitude_spectrum = 20*np.log(np.abs(fshift))
return magnitude_spectrum
我想實現這個功能:
def inverse_fourier_transform(magnitude_spectrum):
return img
但我不知道怎么做。
我的想法是使用magnitude_spectrum
來獲取原始img
。
我該怎么做?
你在這里失去了階段: np.abs(fshift)
。
np.abs
只需要你的數據的真實部分。 您可以通過以下方式分離振幅和相位:
abs = fshift.real
ph = fshift.imag
從理論上講,您可以在 abs 上工作,然后通過np.fft.ifft2
將它們與相位和反向 FFT 結合在一起。
編輯:您可以嘗試這種方法:
import numpy as np
import matplotlib.pyplot as plt
# single chanel image
img = np.random.random((100, 100))
img = plt.imread(r'path/to/color/img.jpg')[:,:,0]
# should be only width and height
print(img.shape)
# do the 2D fourier transform
fft_img = np.fft.fft2(img)
# shift FFT to the center
fft_img_shift = np.fft.fftshift(fft_img)
# extract real and phases
real = fft_img_shift.real
phases = fft_img_shift.imag
# modify real part, put your modification here
real_mod = real/3
# create an empty complex array with the shape of the input image
fft_img_shift_mod = np.empty(real.shape, dtype=complex)
# insert real and phases to the new file
fft_img_shift_mod.real = real_mod
fft_img_shift_mod.imag = phases
# reverse shift
fft_img_mod = np.fft.ifftshift(fft_img_shift_mod)
# reverse the 2D fourier transform
img_mod = np.fft.ifft2(fft_img_mod)
# using np.abs gives the scalar value of the complex number
# with img_mod.real gives only real part. Not sure which is proper
img_mod = np.abs(img_mod)
# show differences
plt.subplot(121)
plt.imshow(img, cmap='gray')
plt.subplot(122)
plt.imshow(img_mod, cmap='gray')
plt.show()
如果沒有相位信息,您將無法恢復准確的原始圖像,因此您不能只使用 fft2 的幅度。 要使用 fft2 恢復圖像,您只需要調用 numpy.fft.ifft2。 請參閱下面的代碼:
import numpy as np
from numpy.fft import fft2, ifft2, fftshift, ifftshift
#do the 2D fourier transform
fft_img = fftshift(fft2(img))
# reverse the 2D fourier transform
freq_filt_img = ifft2(ifftshift(fft_img))
freq_filt_img = np.abs(freq_filt_img)
freq_filt_img = freq_filt_img.astype(np.uint8)
請注意,如果您只想直接恢復原始圖像,則不需要調用 fftshift 和 ifftshift,但我添加了它們,以防在中間進行一些繪圖或其他一些需要將零頻率居中的操作。
調用 numpy.abs() 或 freq_filt_img.real(假設每個像素為正值)恢復圖像的結果應該是相同的,因為 ifft2 的虛部應該非常小。 當然,numpy.abs() 的復雜度是 O(n) 而 freq_filt_img.real 的復雜度是 O(1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.