The Short-Time Fourier Transform helps us see how the frequencies in a signal change over time. It breaks a long signal into small pieces and finds the frequencies in each piece.
Short-Time Fourier Transform (STFT) in Signal Processing
STFT(signal, window, step_size, n_fft) # signal: the input signal array # window: the size of each small piece # step_size: how much to move the window each time # n_fft: number of points for the Fourier transform
The window size controls the time resolution and frequency resolution trade-off.
Step size controls how much the window moves forward each time, affecting overlap.
stft_result = STFT(signal, window=256, step_size=128, n_fft=256)
stft_result = STFT(signal, window=512, step_size=256, n_fft=512)
This code creates a signal with two different frequencies in two time halves. It then calculates the STFT and shows how frequency content changes over time in a color plot.
import numpy as np import matplotlib.pyplot as plt from scipy.signal import stft # Create a sample signal: 2 seconds, 1000 Hz sample rate fs = 1000 T = 2 t = np.linspace(0, T, T*fs, endpoint=False) # Signal with two frequencies changing over time signal = np.sin(2*np.pi*50*t) * (t < 1) + np.sin(2*np.pi*120*t) * (t >= 1) # Compute STFT f, time_segments, Zxx = stft(signal, fs=fs, window='hann', nperseg=256, noverlap=128) # Plot the magnitude of STFT plt.pcolormesh(time_segments, f, np.abs(Zxx), shading='gouraud') plt.title('STFT Magnitude') plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') plt.colorbar(label='Magnitude') plt.tight_layout() plt.show()
STFT gives a 2D view: time on one axis, frequency on the other.
Choosing window size is a balance: smaller windows show time changes better, larger windows show frequency details better.
STFT breaks a signal into small time pieces and finds frequencies in each piece.
It helps us see how frequencies change over time in signals like audio or sensor data.
Window size and step size affect the detail and smoothness of the analysis.