Lesson 15 of 15
Spectral Analysis
Spectral Analysis
Spectral analysis extracts perceptual and statistical features from the frequency representation of a signal. Two fundamental descriptors are the spectral centroid and spectral flatness.
Spectral Centroid
The spectral centroid is the "center of mass" of the spectrum. It correlates with perceived brightness — a higher centroid sounds brighter.
where is the frequency (in Hz) of bin and is its magnitude.
Example: With magnitudes at frequencies Hz:
Spectral Flatness
Spectral flatness (also called Wiener entropy) measures how noise-like vs tonal a signal is:
- : white noise (flat spectrum, all bins equal)
- : pure tone (energy concentrated in one bin)
If any magnitude is zero or the arithmetic mean is zero, return .
Your Task
Implement:
spectral_centroid(magnitudes, freqs)— weighted average frequencyspectral_flatness(magnitudes)— geometric mean / arithmetic mean
import math
def spectral_centroid(magnitudes, freqs):
total = sum(magnitudes)
if total == 0:
return 0.0
return sum(f * m for f, m in zip(freqs, magnitudes)) / total
def spectral_flatness(magnitudes):
n = len(magnitudes)
arith = sum(magnitudes) / n
if arith == 0:
return 0.0
if any(m <= 0 for m in magnitudes):
return 0.0
geo = math.exp(sum(math.log(m) for m in magnitudes) / n)
return geo / arithPython runtime loading...
Loading...
Click "Run" to execute your code.