Lecture

Signal and Image Processing Modules

SciPy provides powerful tools for signal processing and image processing.

You can filter time-series or spatial data, analyze frequencies, and apply transformations or basic image operations.

The two main modules are:

  • scipy.signal: Works with 1D and 2D signals like audio, time-series, and images.
  • scipy.ndimage: Provides advanced image processing functions.

Example 1: Low-Pass Filtering

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

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 is useful for analyzing audio, vibrations, or any time-varying frequency patterns.


Example 3: Image Blurring

Use signal.convolve2d() to blur an image with a Gaussian kernel.

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

  • Use scipy.signal for working with 1D and 2D signals, including filtering and frequency analysis.
  • Use scipy.ndimage for advanced image processing tasks.
Quiz
0 / 1

SciPy's signal processing module can be used to design and apply a Butterworth low-pass filter to a time-series signal without introducing a phase shift.

True
False

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help