Numpy FFT (Fast Fourier Transformation) of 1-dimensional array

I have a simple one-dimensional array like [0,0,0,0,0,1,1,1,1,1,0,0,0,0,0] which describes a square impulse. I would like to transform this impulse to the frequency domain and plot its magnitude spectrum by using the code below (I got it from OpenCV Python Tutorials):

squareimpulse = np.array([0,0,0,0,0,1,1,1,1,1,0,0,0,0,0])

img = (squareimpulse)
f = np.fft.fft(img)
fshift = np.fft.fftshift(f)
magnitude_spectrum = 20*np.log(np.abs(fshift))

plt.subplot(121),plt.imshow(img, cmap = 'gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(magnitude_spectrum, cmap = 'gray')
plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
plt.show()

The script works fine for two-dimensional arrays with f = np.fft.fft2(img) but not for my case where I only got one dimension.

Hope we can figure this out.

Answer

I changed plt.imshow(.....) into plt.plot(.....) and the script is now working!

import cv2
import numpy as np
from matplotlib import pyplot as plt

    squareimpulse = np.array([0,0,0,0,0,1,1,1,1,1,0,0,0,0,0])

    img = (squareimpulse)
    f = np.fft.fft(img)
    fshift = np.fft.fftshift(f)
    magnitude_spectrum = (np.abs(fshift))

    plt.subplot(121)
    plt.plot(img)
    plt.title('Input Image')
    plt.xticks([]), plt.yticks([])

    plt.subplot(122)
    plt.plot(magnitude_spectrum)
    plt.title('Magnitude Spectrum')
    plt.xticks([]), plt.yticks([])

    plt.show()

Leave a Reply

Your email address will not be published. Required fields are marked *