12.3.10.2.8. 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 avaible, 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([[-3.55202387e-04+0.00000000e+00j,  1.95369202e-03-8.83751122e-05j,
        -3.59279470e-04+4.21002312e-04j, ...,
        -1.80124856e-04-8.93321842e-04j, -3.59279470e-04-4.21002312e-04j,
         1.95369202e-03+8.83751122e-05j],
       [-2.05986089e-03+5.56528310e-04j, -2.08907601e-04-1.97809059e-03j,
        -3.00418534e-04-6.35550290e-04j, ...,
        -4.81585480e-04-2.49123098e-04j, -6.05407010e-04-1.00364005e-03j,
         1.13092943e-03+9.50158517e-04j],
       [-1.00728063e-03-6.25107360e-04j,  3.42311095e-05-6.61853805e-04j,
         1.45686745e-03-7.00583442e-04j, ...,
         3.49437711e-04-1.14649274e-03j, -4.47257219e-04+8.05294598e-04j,
         4.01986340e-04+1.37499214e-03j],
       ...,
       [-4.59561253e-04+1.69884542e-03j,  1.24844349e-03+1.56901498e-04j,
         4.50678848e-04+2.29446020e-04j, ...,
         1.12273701e-03-8.57928888e-04j, -1.49030703e-03-3.36220816e-04j,
        -1.06182221e-03-7.96829061e-04j],
       [-1.00728063e-03+6.25107360e-04j,  4.01986340e-04-1.37499214e-03j,
        -4.47257219e-04-8.05294598e-04j, ...,
         1.16845375e-03+6.71883933e-04j,  1.45686745e-03+7.00583442e-04j,
         3.42311095e-05+6.61853805e-04j],
       [-2.05986089e-03-5.56528310e-04j,  1.13092943e-03-9.50158517e-04j,
        -6.05407010e-04+1.00364005e-03j, ...,
        -2.09194733e-04-6.52091807e-04j, -3.00418534e-04+6.35550290e-04j,
        -2.08907601e-04+1.97809059e-03j]])

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