Fourier Transform in Python giving blank images

一笑奈何 提交于 2020-03-03 11:42:04

问题


I am new to python and I am simply trying the 2d Fourier transform on an image and simply reconstruct it using ifft2 in numpy. However, the spectrum magnitude and the reconstructed are white images. This might indicate some scaling issue but I don't understand how to resolve it.

import matplotlib.image as mpimg
import matplotlib.pyplot as plt
imgloc="C:\\Users\\AnacondaCodes\\cameraman.png"
img=mpimg.imread(imgloc,0)
import numpy as np
f=np.fft.fft2(img)
fshift=np.fft.fftshift(f)
magnitude_spectrum=20*np.log(np.abs(fshift))
f_ishift=np.fft.ifftshift(magnitude_spectrum)
img_back=np.fft.ifft2(f_ishift)
img_back=np.abs(img_back)
plt.subplot(131),plt.imshow(img, cmap='gray')
plt.title('input image'), plt.xticks([]),plt.yticks([])
plt.subplot(132),plt.imshow(magnitude_spectrum, cmap='gray')
plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
plt.subplot(133), plt.imshow(img_back,cmap='gray')
plt.title('reconstructed'), plt.xticks([]), plt.yticks([])`

回答1:


You backtransformed the log of the absolute value of the spectrum. That changes the spectrum dramatically. Even the absolute portion would not be a good thing, since the FFT transforms the real image into a complex spectrum (apparently 2N datapoints now , 1/2 of them is redundant because of symmetry). Now the absolute part is necessary to look at the spectrum in the spatial frequency domain, but that's because it consists of a real and imaginary part. The log also help in visualization, since you have a substantial DC offset (average of all pixels is not zero), so w/o the log you'll see just a single white dot in a sea of black.

If you transform the spectrum itself back, all is fine.

import matplotlib.pyplot as p
import numpy as np

img = p.imread("c:/pddata/cameraman.png").astype(float)    
spectrum = np.fft.fftshift(np.fft.fft2(img))

img_back=np.fft.ifft2(np.fft.ifftshift(spectrum))


p.figure(figsize=(20,6))
p.subplot(131)
p.imshow(img, cmap='gray')
p.title('input image') 
p.colorbar()

p.subplot(132)
p.imshow( np.log(np.abs(spectrum)) , cmap='gray')
p.title('Magnitude Spectrum') 
p.colorbar()

p.subplot(133)
p.imshow( np.abs(img_back),cmap='gray')
p.title('reconstructed') 
p.colorbar();



来源:https://stackoverflow.com/questions/58936938/fourier-transform-in-python-giving-blank-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!