Your function is trying to test two things at once: (1) FFT and inverse FFT an image, and (2) disassemble a complex number into real and imaginary parts, transform to amplitude and phase, and then put it back together again. Instead of trying the whole thing at once and wondering why it doesn't work, you should test each of these two functions separately.
To test whether ifft(fft(image))
gives back the original image, you can just remove or comment out all the complex number manipulations:
function y = forwardBackwardFFT(image)
F = fft2(image);
%# stuff removed
f = ifft2(F);
subplot(1,2,1);
imshow(image);
title('Original Image');
subplot(1,2,2);
imshow(f, []);
title('Image after forward and backward FFT');
y = f;
This works. So the problem is with your complex number manipulations. Consider what happens when phase=0 or phase=pi/2. The tangent of 0 is 0, leading to a division by zero; and tan(pi/2) is infinite.
Here is some code that works:
mag = sqrt(real(F).^2 + imag(F).^2);
phase = atan2(imag(F),real(F));
re = mag .* cos(phase);
im = mag .* sin(phase);
F = re + 1i*im;
You will have to do imagesc(abs(f))
in order to show the resulting inverse-transformed image, to get rid of a (nearly zero) imaginary component.
A more idiomatic way to get the magnitude and phase of a complex number is to simply do:
mag = abs(F);
phase = angle(F);
Hope this helps.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…