Signal and Image Processing Modules
SciPy includes powerful modules for signal and image processing, enabling you to:
- Filter time-series or spatial data
- Perform frequency analysis
- Apply transformations and basic image manipulation
The two main modules are:
scipy.signal
– Works with 1D and 2D signals (e.g., audio, time series, images)scipy.ndimage
– Offers advanced image processing functions
These tools are widely used in engineering, data analysis, and scientific research.
Example 1: Low-Pass Filtering
Butterworth Low-Pass Filter
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal, misc
# Sampling parameters
fs = 500.0 # Hz
t = np.arange(0, 1.0, 1/fs)
# Create a noisy signal
sig = np.sin(2*np.pi*5*t) + 0.5*np.sin(2*np.pi*50*t)
# Design low-pass filter (cutoff 10 Hz)
b, a = signal.butter(N=4, Wn=10/(fs/2), btype='low')
# Apply filter
filtered = signal.filtfilt(b, a, sig)
# Plot
plt.plot(t, sig, label="Original", alpha=0.5)
plt.plot(t, filtered, label="Filtered", linewidth=2)
plt.xlabel("Time [s]")
plt.ylabel("Amplitude")
plt.title("Low-Pass Butterworth Filter")
plt.legend()
plt.show()
signal.butter()
designs the filter, andsignal.filtfilt()
applies it without introducing a phase shift.
Example 2: Spectrogram
Spectrogram
f, t_spec, Sxx = signal.spectrogram(sig, fs)
plt.pcolormesh(t_spec, f, Sxx, shading='gouraud')
plt.ylabel("Frequency [Hz]")
plt.xlabel("Time [s]")
plt.title("Spectrogram")
plt.show()
A spectrogram shows how the frequency content of a signal changes over time — useful for audio analysis and vibration monitoring.
Example 3: Image Blurring
Gaussian Blur with Convolution
# Load sample image
face = misc.face(gray=True)
# Create Gaussian blur kernel
kernel_size = 15
sigma = 3.0
x = np.linspace(-sigma, sigma, kernel_size)
gauss_kernel_1d = np.exp(-x**2 / (2 * sigma**2))
gauss_kernel_1d /= gauss_kernel_1d.sum()
gauss_kernel_2d = np.outer(gauss_kernel_1d, gauss_kernel_1d)
# Apply convolution
blurred_face = signal.convolve2d(face, gauss_kernel_2d, mode='same', boundary='symm')
# Plot
plt.subplot(1, 2, 1)
plt.imshow(face, cmap='gray')
plt.title("Original")
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(blurred_face, cmap='gray')
plt.title("Blurred")
plt.axis('off')
plt.show()
signal.convolve2d()
applies a 2D convolution — in this case, using a Gaussian kernel to smooth the image.
What’s Next?
In the next lesson, we’ll conclude Chapter 3 with the Final Quiz on SciPy Fundamentals to test your knowledge from all previous lessons.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.