12.3.10.2.1. Numpy FFT, PyFFTW#

This example shows how to use the FFT or IFFT from Numpy. If possible the package PyFFTW is searched. If it is available, the fast implementation of FFT and IFFT is used from this package (GPL license!!!).

In order to have the fast version of the fourier transform in pyfftw, align your input data using getAlignNdArray. This is an idle operation if PyFFTW is not available. Either np.fft.fft2 or pyfftw.interfaces.numpy_fft.fft2 are mapped to myfft2, such the overall call can be done by using myfft2(...). The same holds for myifft2(...).

import numpy as np

myfft2 = np.fft.fft2  # default: fft2 from numpy
myifft2 = np.fft.ifft2  # default: ifft2 from numpy

Define function and overwrite it when pyfftw is available.

def getAlignNdArray(image):
    return np.array(image)


try:
    import pyfftw

    myfft2 = pyfftw.interfaces.numpy_fft.fft2  # if PyFFTW: use fft2 from this package
    myifft2 = pyfftw.interfaces.numpy_fft.ifft2
    alignSize = pyfftw.simd_alignment

    def getAlignNdArray(image):
        return pyfftw.n_byte_align(np.array(image), alignSize)

except ModuleNotFoundError:
    print("pyfftw could not be found. Numpy fft is used instead")


image = np.random.randn(1024, 512)
I = getAlignNdArray(image)
I1 = myfft2(I)
I2 = myifft2(I)
I2
pyfftw could not be found. Numpy fft is used instead

array([[-4.41454107e-04+0.00000000e+00j, -2.51629340e-04-6.22621070e-04j,
        -5.24166091e-04-8.69670371e-04j, ...,
        -9.68750785e-04-1.40335374e-03j, -5.24166091e-04+8.69670371e-04j,
        -2.51629340e-04+6.22621070e-04j],
       [-1.37564520e-03-5.02280564e-04j, -3.16131226e-04-3.83928675e-04j,
        -2.64524355e-03+1.21308171e-03j, ...,
         6.43585986e-04+4.19576266e-04j, -5.99395508e-04+3.66520961e-04j,
         6.92728343e-04+4.41714402e-04j],
       [-1.00728360e-03+6.71349255e-04j, -2.00100703e-03-3.09363704e-04j,
        -8.92034028e-04-9.69901790e-05j, ...,
         8.30072838e-05+8.28516470e-04j, -3.14040628e-04-9.99640259e-04j,
         3.96885141e-04+1.28553377e-04j],
       ...,
       [-1.39918521e-03+1.49365727e-03j,  1.28884982e-03-2.33037098e-04j,
         7.99750333e-04+1.03343398e-03j, ...,
         1.55898393e-03+2.42627676e-03j, -4.51848616e-04+3.83616458e-04j,
         4.70787993e-04-9.90595756e-05j],
       [-1.00728360e-03-6.71349255e-04j,  3.96885141e-04-1.28553377e-04j,
        -3.14040628e-04+9.99640259e-04j, ...,
         3.99798804e-04-6.90250285e-04j, -8.92034028e-04+9.69901790e-05j,
        -2.00100703e-03+3.09363704e-04j],
       [-1.37564520e-03+5.02280564e-04j,  6.92728343e-04-4.41714402e-04j,
        -5.99395508e-04-3.66520961e-04j, ...,
        -8.33580524e-05+1.38016544e-03j, -2.64524355e-03-1.21308171e-03j,
        -3.16131226e-04+3.83928675e-04j]])

Total running time of the script: (0 minutes 0.032 seconds)