0
0
SciPydata~5 mins

Windowing before FFT in SciPy

Choose your learning style9 modes available
Introduction

Windowing helps reduce unwanted effects when analyzing signals with FFT. It smooths the edges to get clearer frequency results.

When analyzing sound recordings to find different tones.
When studying vibrations in machines to detect faults.
When processing EEG brain signals to identify brain waves.
When working with any signal that is cut into pieces before frequency analysis.
Syntax
SciPy
from scipy.signal import windows
window = windows.hann(N)
windowed_signal = signal * window
fft_result = np.fft.fft(windowed_signal)

Use a window function like Hann to reduce edge effects.

Multiply your signal by the window before applying FFT.

Examples
Apply a Hann window of length 100 to the first 100 samples of your signal.
SciPy
from scipy.signal import windows
window = windows.hann(100)
windowed_signal = signal[:100] * window
Use a Hamming window matching the signal length for smoother edges.
SciPy
from scipy.signal import windows
window = windows.hamming(len(signal))
windowed_signal = signal * window
Blackman window gives stronger edge smoothing for better frequency resolution.
SciPy
from scipy.signal import windows
window = windows.blackman(len(signal))
windowed_signal = signal * window
Sample Program

This code creates a noisy 5 Hz sine wave, applies a Hann window, and compares the FFT magnitude of the original and windowed signals. The window reduces spectral leakage, making the 5 Hz peak clearer.

SciPy
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import windows

# Create a sample signal: 5 Hz sine wave + noise
fs = 100  # Sampling frequency
T = 1.0   # seconds
N = int(T * fs)  # Number of samples

t = np.linspace(0, T, N, endpoint=False)
signal = np.sin(2 * np.pi * 5 * t) + 0.5 * np.random.randn(N)

# Create a Hann window
window = windows.hann(N)

# Apply window to the signal
windowed_signal = signal * window

# Compute FFT of original and windowed signals
fft_orig = np.fft.fft(signal)
fft_win = np.fft.fft(windowed_signal)

# Frequency axis
freqs = np.fft.fftfreq(N, 1/fs)

# Plot magnitude spectra
plt.figure(figsize=(10,5))
plt.plot(freqs[:N//2], np.abs(fft_orig)[:N//2], label='Original Signal')
plt.plot(freqs[:N//2], np.abs(fft_win)[:N//2], label='Windowed Signal')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude')
plt.title('FFT Magnitude: Original vs Windowed Signal')
plt.legend()
plt.grid(True)
plt.show()
OutputSuccess
Important Notes

Windowing reduces spectral leakage, which is when energy spreads to nearby frequencies.

Choosing the right window depends on your signal and what you want to see.

Always multiply the signal by the window before FFT, not after.

Summary

Windowing smooths signal edges to improve FFT results.

Apply window functions like Hann or Hamming before FFT.

This helps see true frequencies more clearly by reducing leakage.