Remembering the math we studied in college, there was a term called “Fourier transformation”. A few nerds might recall completely what the term means, while a few of us, like me, might have scratched our heads when we saw this term for the first time. Even I didn’t come across this term until a few weeks ago when I was working on filtering our signal noise. I thought, “Hey, why not write a blog on the topic? This way, I’ll resurrect those lost brain cells of mine that contained the information on Fourier transformation.”
So in today’s blog, we will implement what Fourier transformation in Python to understand its importance.
Table of Contents
Understanding the basics
Fourier Transformation lies at the heart of signal processing, serving as a powerful mathematical tool to dissect intricate signals such as images or sounds into their constituent frequencies. By unraveling these signals, we gain insights into their underlying components, facilitating analysis and comprehension. Mathematically, it is described as:
\(x(t) = \sum\limits_{n = 0 }^{N – 1 } {{x_n}{e^{-j2\pi \frac{k}{N} n}}}\)
Before you tangle the wires in your brain in an attempt to understand the above formula, it’s essential to grasp its fundamental concept: the partitioning of signals into various frequencies and amplitudes. While a detailed explanation of the mathematical derivation is beyond the scope of this blog, the interested ones can explore further through the provided link.
Do not worry if you do not understand the math behind the above equation. In this blog, we will implement the algorithm on some examples using Python.
The concept of decomposing a signal into its constituent parts holds immense importance across various domains. Consider music, for instance. Fourier Transformation allows us to deconstruct a musical piece into its individual notes and frequencies, unveiling the fundamental tones, harmonics, and subtleties that collectively shape our auditory experience. Similarly, in image processing, Fourier Transformation dissects an image into its spatial frequencies, thereby providing information on different signals that the image encompasses. Or considering a completely simple analogy, Fourier transformation allows us to determine the ingredients from the already-made food.
By using Fourier transformation, we figure out the ingredients and can remove the one ingredient we do not like, hence making our dish better and taste the way we want.
Why do you need Fourier Transformation?
Recently, I had a fascinating experience with my Google Pixel smartphone that perfectly illustrates the application of Fourier transformation. Amidst the bustling ambiance of a crowded pub, I found myself intrigued by the faint melody drifting through relatively loud chatters. Despite the noisy environment, my Pixel effortlessly identified the song playing in the background.
Initially, I was surprised by the accuracy of its recognition. How could it identify a specific tune in such a loud environment? Yet, upon listening attentively, I did realize that the song was indeed being played. In that moment, I couldn’t help but appreciate the remarkable capabilities of modern technology.
Of course, Google used some machine learning model that took the audio signal as input and provided the name of the song as output. But if the model took the signal as it was as input, i.e. with all the noise in the background, I could only imagine that the probability of the model delivering a false result could be high. To avoid that, the audio signal is preprocessed, in which the noise frequencies are separated from the main audio signal. Another such use-case of Fourier transformation is text-to-speech applications.
Such separation between frequencies of signal is only possible when the signal is perceived in frequency domain. Working with time domain can get challenging as it hides the information about the frequencies that the signal carries. So in the next section, we will distinguish between time domain and frequency domain.
Time Domain vs. Frequency Domain
Time domain and frequency domain are the two perspective or two ways to visualize a signal. As one can guess from the names, time domain allows us to visualize the signal over time while the latter provides us information about the involved frequencies. Below is an example of a sine wave with 50 hz frequency in time domain and frequency domain.
Implementation in Python
Enough with the theory! Let us now get our hands on programming and apply Fourier transformation on a particular signal.
from scipy.fft import fft, fftfreq
import numpy as np
import matplotlib.pyplot as plt
sampling_freq = 1000 # Sampling frequency in Hz
duration = 1 # Duration of the signal in seconds
frequency_of_interest = 50 # Frequency of the sine wave in Hz
# Time array
t = np.arange(0, duration, 1/sampling_freq)
# Generate sine wave in time domain
sine_wave_time = np.sin(2 * np.pi * frequency_of_interest * t)
# Plot
plt.figure(figsize=(12, 6))
plt.subplot(2, 1, 1)
plt.plot(t, sine_wave_time)
plt.title('Sine Wave in Time Domain')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
There are three significant terms in this code to understand:
sampling_freq
: Sampling frequency of the signal, i.e., how many samples are taken per second.duration
: Duration of the signal in seconds.frequency_of_interest
: Frequency of the sine wave we want to generate in Hz.
We create a sine wave using the formula sin(2 * pi * f * t) and this is seen in the code:sine_wave_time = np.sin(2 * np.pi * frequency_of_interest * t)
This calculates the values of the sine wave at each time point t
using the formula sin(2 * pi * f * t)
, where f
is the frequency of interest.
This code generates the sine wave in time domain.
For Fourier transformation, we use the fft
module from scipy
package in Python.
# Compute Fourier Transform
sine_wave_frequency = np.fft.fft(sine_wave_time)
frequencies = np.fft.fftfreq(len(sine_wave_frequency), 1/sampling_freq)
plt.subplot(2, 1, 2)
plt.plot(frequencies, np.abs(sine_wave_frequency))
plt.title('Sine Wave in Frequency Domain')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude')
plt.tight_layout()
plt.show()
The np.fft.fft(sine_wave_time)
function computes the Fast Fourier Transform (FFT) of the time domain signal, giving us the frequency domain representation of the signal. np.fft.fftfreq(len(sine_wave_frequency), 1/sampling_freq)
generates an array of frequencies corresponding to the FFT result. The second argument is the sampling interval (1/sampling_freq
).
As a result of this, we have the following graph of sine wave in frequency domain:
This illustration above makes sense as when you have a look at the variable frequency_of_interest
in code, we chose our signal to have frequency of 50 hz.
I would encourage you to go ahead and try this with different types of signals. The significant part is to use the fft
and fftfreq
functions of the scipy
module in Python.
Conclusion
In this article, we’ve delved into the significance of Fourier transform in signal processing. By comprehending signals in the frequency domain, we gain deeper insights into their characteristics, enabling more efficient signal processing techniques. In the next post, we’ll take a practical approach by importing an actual audio recording. We’ll then understand how to filter out unwanted noise frequencies, resulting in a cleaner signal, and finally, save the filtered audio for further analysis.
Join me on social media platforms to stay updated with the latest trends, discussions, and exclusive content in the fields of machine learning and programming. Let’s connect, share knowledge, and inspire each other to reach new heights in our learning and professional endeavors. Follow me today and embark on this exciting journey together!
To never miss a post, subscribe to my *FREE* monthly newsletter to receive updates on the newly published posts: