views:

222

answers:

1

Hello! I want to make a fourier-transformation of an image. But how can I change the picture to an array? And after this I think I should use numpy.fft.rfft2 for the transformation. And how to change back from the array to the image? Thanks in advance.

+6  A: 

You can use the PIL library to load/save images and convert to/from numpy arrays.

import Image, numpy
i = Image.open('img.png')
a = numpy.asarray(i) # a is readonly

b = abs(numpy.fft.rfft2(a))

j = Image.fromarray(b)
j.save('img2.png')

I used abs above because the result of the FFT has complex values so it doesn't really make sense to convert it directly to an image.

Edit:

To also perform an inverse FFT and get back the original image, the following works for me:

import Image, numpy
i = Image.open('img.png')
i = i.convert('L')    #convert to grayscale
a = numpy.asarray(i)

b = numpy.fft.rfft2(a)
c = numpy.fft.irfft2(b)

j = Image.fromarray(c.astype(numpy.uint8))
j.save('img2.png')
interjay
link: http://www.pythonware.com/products/pil/
Personman
When I make an inverse fft, i dont get the real image back. Why?
kame
@kame Because the call to `abs` loses data. Also, the source image should be grayscale, otherwise you'll get a 3D array instead of 2D.
interjay
@kame: I added code to show how you can do an inverse FFT. I'm guessing this is what you need.
interjay
Thanks a lot. This wasn't obvious. :)
kame