Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions python-scipy-fft/README.md
Original file line number Diff line number Diff line change
@@ -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`.
17 changes: 17 additions & 0 deletions python-scipy-fft/fft_spectrum.py
Original file line number Diff line number Diff line change
@@ -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()
26 changes: 26 additions & 0 deletions python-scipy-fft/mix_tones.py
Original file line number Diff line number Diff line change
@@ -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)
33 changes: 33 additions & 0 deletions python-scipy-fft/remove_noise.py
Original file line number Diff line number Diff line change
@@ -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)
3 changes: 3 additions & 0 deletions python-scipy-fft/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
matplotlib==3.11.2
numpy==2.5.5
scipy==1.18.1
16 changes: 16 additions & 0 deletions python-scipy-fft/rfft_spectrum.py
Original file line number Diff line number Diff line change
@@ -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()
20 changes: 20 additions & 0 deletions python-scipy-fft/sine_wave.py
Original file line number Diff line number Diff line change
@@ -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()
Loading