diff --git a/python-scipy-fft/README.md b/python-scipy-fft/README.md new file mode 100644 index 0000000000..19272936c8 --- /dev/null +++ b/python-scipy-fft/README.md @@ -0,0 +1,31 @@ +# Fourier Transforms With scipy.fft: Python Signal Processing + +This folder contains the sample code for the Real Python tutorial [Fourier Transforms With scipy.fft: Python Signal Processing](https://realpython.com/python-scipy-fft/). + +## Setup + +You'll need Python 3.12 or later. Create and activate a virtual environment, then install the pinned dependencies: + +```console +$ python -m venv venv/ +$ source venv/bin/activate +(venv) $ python -m pip install -r requirements.txt +``` + +## Usage + +Each script covers one part of the tutorial's noise-removal example. Run them from this folder: + +```console +(venv) $ python sine_wave.py +(venv) $ python mix_tones.py +(venv) $ python fft_spectrum.py +(venv) $ python rfft_spectrum.py +(venv) $ python remove_noise.py +``` + +- `sine_wave.py` plots a 2 hertz sine wave. +- `mix_tones.py` mixes a 400 Hz tone with 4000 Hz noise, plots the result, and saves it as `mysinewave.wav`. +- `fft_spectrum.py` plots the frequency spectrum computed with `fft()`. +- `rfft_spectrum.py` plots the faster real-input spectrum computed with `rfft()`. +- `remove_noise.py` filters out the 4000 Hz noise, plots the cleaned signal, and saves it as `clean.wav`. diff --git a/python-scipy-fft/fft_spectrum.py b/python-scipy-fft/fft_spectrum.py new file mode 100644 index 0000000000..89f3b2ade3 --- /dev/null +++ b/python-scipy-fft/fft_spectrum.py @@ -0,0 +1,17 @@ +import numpy as np +from matplotlib import pyplot as plt +from scipy.fft import fft, fftfreq + +from mix_tones import generate_noisy_tone +from sine_wave import DURATION, SAMPLE_RATE + +normalized_tone = generate_noisy_tone() + +# Number of samples in normalized_tone +N = SAMPLE_RATE * DURATION + +yf = fft(normalized_tone) +xf = fftfreq(N, 1 / SAMPLE_RATE) + +plt.plot(xf, np.abs(yf)) +plt.show() diff --git a/python-scipy-fft/mix_tones.py b/python-scipy-fft/mix_tones.py new file mode 100644 index 0000000000..41aefce8b3 --- /dev/null +++ b/python-scipy-fft/mix_tones.py @@ -0,0 +1,26 @@ +import numpy as np +from matplotlib import pyplot as plt +from scipy.io.wavfile import write + +from sine_wave import DURATION, SAMPLE_RATE, generate_sine_wave + + +def generate_noisy_tone(): + _, nice_tone = generate_sine_wave(400, SAMPLE_RATE, DURATION) + _, noise_tone = generate_sine_wave(4000, SAMPLE_RATE, DURATION) + noise_tone = noise_tone * 0.3 + + mixed_tone = nice_tone + noise_tone + + normalized_tone = np.int16((mixed_tone / mixed_tone.max()) * 32767) + return normalized_tone + + +if __name__ == "__main__": + normalized_tone = generate_noisy_tone() + + plt.plot(normalized_tone[:1000]) + plt.show() + + # Remember SAMPLE_RATE = 44100 Hz is our playback rate + write("mysinewave.wav", SAMPLE_RATE, normalized_tone) diff --git a/python-scipy-fft/remove_noise.py b/python-scipy-fft/remove_noise.py new file mode 100644 index 0000000000..7e4e49de79 --- /dev/null +++ b/python-scipy-fft/remove_noise.py @@ -0,0 +1,33 @@ +import numpy as np +from matplotlib import pyplot as plt +from scipy.fft import irfft, rfft, rfftfreq +from scipy.io.wavfile import write + +from mix_tones import generate_noisy_tone +from sine_wave import DURATION, SAMPLE_RATE + +normalized_tone = generate_noisy_tone() +N = SAMPLE_RATE * DURATION + +yf = rfft(normalized_tone) +xf = rfftfreq(N, 1 / SAMPLE_RATE) + +# The maximum frequency is half the sample rate +points_per_freq = len(xf) / (SAMPLE_RATE / 2) + +# Our target frequency is 4000 Hz +target_idx = int(points_per_freq * 4000) + +yf[target_idx - 1 : target_idx + 2] = 0 + +plt.plot(xf, np.abs(yf)) +plt.show() + +new_sig = irfft(yf) + +plt.plot(new_sig[:1000]) +plt.show() + +norm_new_sig = np.int16(new_sig * (32767 / new_sig.max())) + +write("clean.wav", SAMPLE_RATE, norm_new_sig) diff --git a/python-scipy-fft/requirements.txt b/python-scipy-fft/requirements.txt new file mode 100644 index 0000000000..453ed0c16e --- /dev/null +++ b/python-scipy-fft/requirements.txt @@ -0,0 +1,3 @@ +matplotlib==3.11.2 +numpy==2.5.5 +scipy==1.18.1 diff --git a/python-scipy-fft/rfft_spectrum.py b/python-scipy-fft/rfft_spectrum.py new file mode 100644 index 0000000000..c66cff777a --- /dev/null +++ b/python-scipy-fft/rfft_spectrum.py @@ -0,0 +1,16 @@ +import numpy as np +from matplotlib import pyplot as plt +from scipy.fft import rfft, rfftfreq + +from mix_tones import generate_noisy_tone +from sine_wave import DURATION, SAMPLE_RATE + +normalized_tone = generate_noisy_tone() +N = SAMPLE_RATE * DURATION + +# Note the extra "r" at the front +yf = rfft(normalized_tone) +xf = rfftfreq(N, 1 / SAMPLE_RATE) + +plt.plot(xf, np.abs(yf)) +plt.show() diff --git a/python-scipy-fft/sine_wave.py b/python-scipy-fft/sine_wave.py new file mode 100644 index 0000000000..a638c0ee83 --- /dev/null +++ b/python-scipy-fft/sine_wave.py @@ -0,0 +1,20 @@ +import numpy as np +from matplotlib import pyplot as plt + +SAMPLE_RATE = 44100 # Hertz +DURATION = 5 # Seconds + + +def generate_sine_wave(freq, sample_rate, duration): + x = np.linspace(0, duration, sample_rate * duration, endpoint=False) + frequencies = x * freq + # 2pi because np.sin takes radians + y = np.sin((2 * np.pi) * frequencies) + return x, y + + +if __name__ == "__main__": + # Generate a 2 hertz sine wave that lasts for 5 seconds + x, y = generate_sine_wave(2, SAMPLE_RATE, DURATION) + plt.plot(x, y) + plt.show()