0
0
RosHow-ToBeginner · 4 min read

How to Use SciPy for Signal Processing: Simple Guide

Use scipy.signal module to perform signal processing tasks such as filtering, Fourier transforms, and peak detection. Import functions like butter for filters or find_peaks for peak detection, then apply them to your data arrays.
📐

Syntax

The scipy.signal module provides many functions for signal processing. Common functions include:

  • butter(N, Wn, btype='low'): Creates a Butterworth filter of order N with cutoff frequency Wn normalized to the Nyquist frequency.
  • lfilter(b, a, x): Applies a linear filter defined by coefficients b and a to signal x.
  • find_peaks(x): Finds peaks in the signal x.
  • fft(x): Computes the Fast Fourier Transform of x.

These functions work on arrays representing your signal data.

python
from scipy.signal import butter, lfilter, find_peaks
from scipy.fft import fft

# Butterworth filter design
b, a = butter(N=3, Wn=0.1, btype='low')

# Apply filter to data
filtered_signal = lfilter(b, a, [1, 2, 3, 4, 5])

# Find peaks
peaks, _ = find_peaks([0, 2, 1, 3, 0])

# Compute FFT
signal_fft = fft([1, 2, 3, 4])
💻

Example

This example shows how to create a low-pass Butterworth filter, apply it to a noisy signal, and detect peaks in the filtered signal.

python
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import butter, lfilter, find_peaks

# Create sample data: noisy sine wave
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)

# Design Butterworth low-pass filter
order = 4
cutoff = 10  # cutoff frequency in Hz
b, a = butter(order, cutoff / (0.5 * fs), btype='low')

# Apply filter
filtered_signal = lfilter(b, a, signal)

# Find peaks in filtered signal
peaks, _ = find_peaks(filtered_signal, height=0)

# Plot results
plt.figure(figsize=(10, 6))
plt.plot(t, signal, label='Noisy signal')
plt.plot(t, filtered_signal, label='Filtered signal', linewidth=2)
plt.plot(t[peaks], filtered_signal[peaks], 'ro', label='Peaks')
plt.xlabel('Time [seconds]')
plt.ylabel('Amplitude')
plt.legend()
plt.title('Signal Filtering and Peak Detection with SciPy')
plt.show()
Output
A plot window showing a noisy sine wave, its filtered version, and red dots marking detected peaks on the filtered signal.
⚠️

Common Pitfalls

Common mistakes when using SciPy for signal processing include:

  • Not normalizing the cutoff frequency by the Nyquist frequency (half the sampling rate) when designing filters.
  • Applying filters without considering signal edge effects, which can cause distortions.
  • Using find_peaks without setting parameters like height or distance, leading to false peak detections.
  • Confusing scipy.fft with numpy.fft; SciPy's FFT is recommended for newer code.

Example of wrong and right filter design:

python
# Wrong: cutoff frequency not normalized
from scipy.signal import butter

fs = 100
cutoff = 10
# Incorrect: cutoff not divided by Nyquist frequency
# b, a = butter(3, cutoff, btype='low')  # This will cause an error or wrong filter

# Right: normalize cutoff frequency
b, a = butter(3, cutoff / (0.5 * fs), btype='low')
📊

Quick Reference

Here is a quick summary of useful SciPy signal processing functions:

FunctionPurposeKey Parameters
butterDesign Butterworth filterN (order), Wn (cutoff freq), btype ('low', 'high')
lfilterApply linear filterb, a (filter coeffs), x (signal)
find_peaksDetect peaks in signalheight, distance, prominence
fftCompute Fast Fourier Transformx (signal array)
freqzFrequency response of filterb, a (filter coeffs)

Key Takeaways

Use scipy.signal module functions like butter and lfilter for filtering signals.
Always normalize cutoff frequencies by Nyquist frequency when designing filters.
Use find_peaks with parameters to accurately detect signal peaks.
Apply FFT with scipy.fft for frequency analysis of signals.
Visualize signals before and after processing to verify results.