Skip to content

Features | latest | spectral-centroid

Spectral centroid

The centroid frequency of a spectrum indicates where the center of mass of the spectrum is located. The spectral centroid is commonly associated as a measure of the brightness of a sound.

The spectral centroid is calculated from the power spectrum Xp=|X|2RM using the following formula:

fcentroid=fs2(M1)m=0M1Xp[m]mm=0M1Xp[m],

where:

  • Xp[m]: The power at frequency bin m,
  • M: The total number of frequency bins,
  • fs: The sampling rate of the signal.

The result lies within the range of 0 Hz to the Nyquist frequency, which is fs/2.

References

Code

INFO

The following snippet is written in a generic and unoptimized manner. The code aims to be comprehensible to programmers familiar with various programming languages and may not represent the most efficient or idiomatic Python practices. Please refer to implementations for optimized implementations in different programming languages.

py
import numpy as np


def spectral_centroid(spectrum: np.ndarray, samplerate: float):
    ps = np.abs(spectrum) ** 2
    ps_sum = 0.0
    ps_sum_weighted = 0.0
    for i, magnitude in enumerate(ps):
        ps_sum += magnitude
        ps_sum_weighted += magnitude * i
    return 0.5 * samplerate / (len(ps) - 1) * (ps_sum_weighted / ps_sum)
Run in playground