Signal-to-Noise Ratio

Imagine developing a song recognition application. The software’s goal is to recognize a song even when it’s played in a noisy environment, similar to Shazam. To achieve this, you want to enhance the audio quality by reducing the noise and evaluating the improvement using the Signal-to-Noise Ratio (SNR).

In this example, we will demonstrate how to generate a clean signal, add varying levels of noise to simulate the noisy recording, use FFT for noise reduction, and then evaluate the quality of the reconstructed audio using SNR.

Import necessary libraries

11 from typing import Tuple
12
13 import matplotlib.animation as animation
14 import matplotlib.pyplot as plt
15 import numpy as np
16 import torch
17 from torchmetrics.audio import SignalNoiseRatio

Generate a clean signal (simulating a high-quality recording)

23 def generate_clean_signal(length: int = 1000) -> Tuple[np.ndarray, np.ndarray]:
24     """Generate a clean signal (sine wave)"""
25     t = np.linspace(0, 1, length)
26     signal = np.sin(2 * np.pi * 10 * t)  # 10 Hz sine wave, representing the clean recording
27     return t, signal

Add Gaussian noise to the signal to simulate the noisy environment

34 def add_noise(signal: np.ndarray, noise_level: float = 0.5) -> np.ndarray:
35     """Add Gaussian noise to the signal."""
36     noise = noise_level * np.random.randn(signal.shape[0])
37     return signal + noise

Apply FFT to filter out the noise

44 def fft_denoise(noisy_signal: np.ndarray, threshold: float) -> np.ndarray:
45     """Denoise the signal using FFT."""
46     freq_domain = np.fft.fft(noisy_signal)  # Filter frequencies using FFT
47     magnitude = np.abs(freq_domain)
48     filtered_freq_domain = freq_domain * (magnitude > threshold)
49     return np.fft.ifft(filtered_freq_domain).real  # Perform inverse FFT to reconstruct the signal

Generate and plot clean, noisy, and denoised signals to visualize the reconstruction

55 length = 1000
56 t, clean_signal = generate_clean_signal(length)
57 noisy_signal = add_noise(clean_signal, noise_level=0.5)
58 denoised_signal = fft_denoise(noisy_signal, threshold=10)
59
60 plt.figure(figsize=(12, 4))
61 plt.plot(t, noisy_signal, label="Noisy environment", color="blue", alpha=0.7)
62 plt.plot(t, denoised_signal, label="Denoised signal", color="green", alpha=0.7)
63 plt.plot(t, clean_signal, label="Clean song", color="red", linewidth=3)
64 plt.xlabel("Time")
65 plt.ylabel("Amplitude")
66 plt.title("Clean Song vs. Noisy Environment vs. Denoised Signal")
67 plt.legend()
68 plt.show()
Clean Song vs. Noisy Environment vs. Denoised Signal

Convert the signals to PyTorch tensors and calculate the SNR

72 clean_signal_tensor = torch.tensor(clean_signal).float()
73 noisy_signal_tensor = torch.tensor(noisy_signal).float()
74 denoised_signal_tensor = torch.tensor(denoised_signal).float()
75
76 snr = SignalNoiseRatio()
77 initial_snr = snr(preds=noisy_signal_tensor, target=clean_signal_tensor)
78 reconstructed_snr = snr(preds=denoised_signal_tensor, target=clean_signal_tensor)
79 print(f"Initial SNR: {initial_snr:.2f}")
80 print(f"Reconstructed SNR: {reconstructed_snr:.2f}")
Initial SNR: 3.12
Reconstructed SNR: 3.39

To show the effect of different noise levels on the SNR, we create an animation that iterates over different noise levels and updates the plot accordingly:

 84 fig, ax = plt.subplots(figsize=(12, 4))
 85 noise_levels = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
 86
 87
 88 def update(num: int) -> tuple:
 89     """Update the plot for each frame."""
 90     t, clean_signal = generate_clean_signal(length)
 91     noisy_signal = add_noise(clean_signal, noise_level=noise_levels[num])
 92     denoised_signal = fft_denoise(noisy_signal, threshold=10)
 93
 94     clean_signal_tensor = torch.tensor(clean_signal).float()
 95     noisy_signal_tensor = torch.tensor(noisy_signal).float()
 96     denoised_signal_tensor = torch.tensor(denoised_signal).float()
 97     initial_snr = snr(preds=noisy_signal_tensor, target=clean_signal_tensor)
 98     reconstructed_snr = snr(preds=denoised_signal_tensor, target=clean_signal_tensor)
 99
100     ax.clear()
101     (noisy,) = plt.plot(t, noisy_signal, label="Noisy Environment", color="blue", alpha=0.7)
102     (denoised,) = plt.plot(t, denoised_signal, label="Denoised Signal", color="green", alpha=0.7)
103     (clean,) = plt.plot(t, clean_signal, label="Clean Song", color="red", linewidth=3)
104     ax.set_xlabel("Time")
105     ax.set_ylabel("Amplitude")
106     ax.set_title(
107         f"Initial SNR: {initial_snr:.2f} - Reconstructed SNR: {reconstructed_snr:.2f} - Noise level: {noise_levels[num]}"
108     )
109     ax.legend(loc="upper right")
110     ax.set_ylim(-3, 3)
111     return noisy, denoised, clean
112
113
114 ani = animation.FuncAnimation(fig, update, frames=len(noise_levels), interval=1000)

Total running time of the script: (0 minutes 3.153 seconds)

Gallery generated by Sphinx-Gallery