Skip to main content
Practice

Signal and Image Processing Modules

SciPy provides powerful tools for signal and image processing, making it ideal for analyzing real-world data like audio, sensor readings, and images.

With these modules, you can:

  • Filter or transform time-series and spatial data
  • Analyze frequency components
  • Perform basic or advanced image manipulations

The two main modules are:

  • scipy.signal — for 1D and 2D signal analysis (e.g., audio, time-series, sensor data)
  • scipy.ndimage — for advanced image transformations and filtering

Example 1: Low-Pass Filtering

Use signal.butter() to design a low-pass filter and signal.filtfilt() to apply it without phase distortion.

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 a low-pass filter (cutoff 10 Hz)
b, a = signal.butter(N=4, Wn=10/(fs/2), btype='low')

# Apply the filter
filtered = signal.filtfilt(b, a, sig)

# Plot the results
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()

Example 2: Spectrogram

Use signal.spectrogram() to visualize how the frequency content of a signal changes over time.

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 reveals how a signal’s frequency content evolves over time — useful for analyzing audio, vibrations, or any time-dependent frequency patterns.


Example 3: Image Blurring

Use signal.convolve2d() to apply a Gaussian blur — a common image processing technique that smooths noise and details.

Gaussian Blur with Convolution
# Load a sample image
face = misc.face(gray=True)

# Create a 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 the original and blurred images
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()

Key Takeaways

  • scipy.signal — for 1D and 2D signal analysis, filtering, and frequency transformations.
  • scipy.ndimage — for advanced image filtering, transformation, and measurement operations.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.