Scipy Signal Processing

Data ScienceSciPyFree Lesson

Advertisement

Introduction

SciPy signal processing module provides tools for filtering, spectral analysis, and waveform generation.

Convolution

from scipy import signal
import numpy as np

# Convolve two signals
x = np.array([1, 2, 3])
h = np.array([1, 1])
y = signal.convolve(x, h, mode='full')
print(y)  # [1, 3, 5, 3]

# 2D convolution
img = np.array([[1, 2], [3, 4]])
kernel = np.array([[1, 0], [0, 1]])
result = signal.convolve2d(img, kernel, mode='same')

FFT and Spectral Analysis

from scipy import signal, fft
import numpy as np

# Generate signal
t = np.linspace(0, 1, 1000)
signal_data = np.sin(2*np.pi*5*t) + 0.5*np.sin(2*np.pi*10*t)

# FFT
N = len(signal_data)
fft_result = fft.fft(signal_data)
freq = fft.fftfreq(N, d=t[1]-t[0])

# Power spectrum
power = np.abs(fft_result)**2

Filters

from scipy import signal
import numpy as np

# Butterworth filter design
b, a = signal.butter(4, 0.2, btype='low')

# Apply filter
t = np.linspace(0, 1, 1000)
x = np.sin(2*np.pi*5*t) + 0.5*np.sin(2*np.pi*50*t)
y = signal.filtfilt(b, a, x)

# Bandpass filter
b, a = signal.butter(3, [0.1, 0.3], btype='band')
y_band = signal.filtfilt(b, a, x)

Filter Design

from scipy import signal

# Chebyshev Type I
b, a = signal.cheby1(4, 1, 0.2, btype='low')

# Elliptic filter
b, a = signal.ellip(4, 1, 40, 0.2, btype='low')

# FIR filter using window method
n = 51
b = signal.firwin(n, cutoff=0.2, window='hamming')

# Frequency response
w, h = signal.freqz(b, a)

Practice Problems

  1. Implement convolution of two discrete signals
  2. Analyze frequency content using FFT
  3. Design and apply lowpass Butterworth filter
  4. Compare filtfilt vs lfilter
  5. Generate spectrogram of audio signal

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement