0
0
Signal Processingdata~7 mins

Short-Time Fourier Transform (STFT) in Signal Processing

Choose your learning style9 modes available
Introduction

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.

Analyzing how the pitch of a song changes over time.
Detecting spoken words in an audio recording.
Finding patterns in heartbeats from medical signals.
Monitoring machine sounds to detect faults over time.
Syntax
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.

Examples
Compute STFT with window size 256, moving 128 samples each step, and 256 FFT points.
Signal Processing
stft_result = STFT(signal, window=256, step_size=128, n_fft=256)
Use a larger window for better frequency detail but less time detail.
Signal Processing
stft_result = STFT(signal, window=512, step_size=256, n_fft=512)
Sample Program

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.

Signal Processing
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()
OutputSuccess
Important Notes

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.

Summary

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.