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
2010-04-16 11:37:38
link: http://www.pythonware.com/products/pil/
Personman
2010-04-16 11:39:17
When I make an inverse fft, i dont get the real image back. Why?
kame
2010-04-16 11:57:04
@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
2010-04-16 12:05:54
@kame: I added code to show how you can do an inverse FFT. I'm guessing this is what you need.
interjay
2010-04-16 12:32:09
Thanks a lot. This wasn't obvious. :)
kame
2010-04-16 16:30:20