views:

81

answers:

2

I want to invert the Fourier transform of an image in MATLAB, but the result is not the original image (as it should be). There is obviously some implementation detail that I don't know about that's causing the issue. Here's the code:

img = imread('img.jpg');
fft = fft2(img);
inv = ifft2(fft);
imshow(inv);
+5  A: 

Since FFT2 and IFFT2 both only support inputs of type double and single, your image data (which is likely of type uint8) gets converted to type double first before being processed by FFT2. You will therefore have to convert your output image inv back to an unsigned 8-bit integer using the function UINT8 to recover the original image:

>> img = imread('peppers.png');  %# Load a sample image
>> fft = fft2(img);   %# Get the Fourier transform
>> inv = ifft2(fft);  %# Get the inverse Fourier transform
>> inv = uint8(inv);  %# Convert to uint8
>> imshow(inv);       %# Show the image
>> isequal(img,inv)   %# Test if inv matches the original image img

ans =

     1                %# It does!

NOTE: As an additional tip, I would avoid naming your variables fft and inv since functions with those names already exist in MATLAB.

gnovice
+1  A: 

Also if you are trying to do FFT on color (24-bit) image - note that imread() will return M x N x 3 array. So you should perform FFT on each R/G/B channel separately.

See this for detail.

0x69
Actually, it appears that FFT2 handles that for you. If you type `type fft2` into the Command Window, you can see that a 3-D input `x` results in the operation `fft(fft(x,[],2),[],1)`, which performs an FFT across the second then first dimension, while a 2-D input `x` (if you were passing each color plane separately) results in a call to [FFTN](http://www.mathworks.com/help/techdoc/ref/fftn.html). Comparing each method, the maximum absolute pixel-wise difference between the results is around 5.6e-10, likely due to differences in the order of operations. In short, the two are nearly equivalent.
gnovice
+1 for sharing this feature ...
0x69