Last modified: Jan 05, 2025 By Alexander Williams

SciPy Signal Processing Example for Beginners

Signal processing is a key part of many scientific and engineering applications. SciPy, a Python library, provides powerful tools for signal processing. This article will guide you through a practical example.

What is SciPy?

SciPy is a Python library used for scientific and technical computing. It builds on NumPy and provides additional functionality. One of its modules, scipy.signal, is dedicated to signal processing.

Installing SciPy

Before starting, ensure SciPy is installed. If not, install it using pip. For installation help, check our guide on How to Install SciPy in Python.

Basic Signal Processing with SciPy

Let's start with a simple example. We'll create a signal, apply a filter, and analyze the result. This will demonstrate basic signal processing techniques.

Creating a Signal

First, we create a signal. We'll use a sine wave for this example. The signal will have a frequency of 5 Hz and a sampling rate of 100 Hz.


import numpy as np
import matplotlib.pyplot as plt

# Create a time vector
t = np.linspace(0, 1, 100, endpoint=False)

# Create a sine wave signal
signal = np.sin(2 * np.pi * 5 * t)

# Plot the signal
plt.plot(t, signal)
plt.title('Original Signal')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.show()
    

Applying a Filter

Next, we apply a low-pass filter to the signal. This will remove high-frequency components. We'll use a Butterworth filter for this purpose.


from scipy import signal

# Design a Butterworth low-pass filter
b, a = signal.butter(4, 0.1, 'low')

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

# Plot the filtered signal
plt.plot(t, filtered_signal)
plt.title('Filtered Signal')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.show()
    

Analyzing the Signal

Finally, we analyze the filtered signal. We'll use the Fourier transform to see its frequency components. This helps in understanding the effect of the filter.


# Compute the Fourier Transform of the filtered signal
fourier_transform = np.fft.fft(filtered_signal)

# Compute the frequencies
frequencies = np.fft.fftfreq(len(filtered_signal), d=1/100)

# Plot the frequency spectrum
plt.plot(frequencies, np.abs(fourier_transform))
plt.title('Frequency Spectrum of Filtered Signal')
plt.xlabel('Frequency [Hz]')
plt.ylabel('Magnitude')
plt.show()
    

Conclusion

This example demonstrates basic signal processing using SciPy. We created a signal, applied a filter, and analyzed the result. SciPy's scipy.signal module is powerful and versatile. For more advanced techniques, explore our guide on Perform Discrete Fourier Transform with SciPy.

Signal processing is essential in many fields. With SciPy, you can easily perform complex operations. Start experimenting with your own signals today!