Currently, I'm considering taking an image and its spectrum. Now Parceval's theorem says that both should have equal energy. However when I try to test this on some images, this doesn't seem to be the case for the numpy real FFT function.
This is the code I'm using for my test:
import numpy as np
from PIL import Image
im = np.array(Image.open('/images/building.jpeg'))
spectral_im = np.fft.rfft2(im, axes = (0,1), norm = 'ortho')
def getNorm(im):
return np.sum(np.abs(im))
print('Norm of the image: %d' % getNorm(im))
print('Norm of the spectrum of the image: %f' % getNorm(spectral_im))
print('Difference between norms: %f' % (getNorm(im) - getNorm(spectral_im)))
I expected that the difference between the norms would be (approximately) 0 for every image, however it differs by an order of magnitude for every image I have tried. Can anyone see what I'm doing wrong?
With the help from the answers, here is the corrected code (note the extra cast to float64, otherwise they still aren't equal):
import numpy as np
from PIL import Image
im = np.array(Image.open('/images/building.jpeg')).astype('float64')
spectral_im = np.fft.fft2(im, axes = (0,1), norm = 'ortho')
def getNorm(im):
return np.sum(np.abs(im) ** 2)
print('Norm of the image: %d' % getNorm(im))
print('Norm of the spectrum of the image: %f' % getNorm(spectral_im))
print('Difference between norms: %f' % (getNorm(im) - getNorm(spectral_im)))