AI Logic

Audio Features and Front-ends

Constant-Q Transform (CQT)

Updated:

Diagram of the constant-Q transform. The left side shows how time and frequency are divided, comparing the STFT with a constant window length (constant frequency width) and the CQT with a window length inversely proportional to frequency (long windows for low notes, short windows for high notes) on a logarithmic frequency axis. The right side shows the harmonics of G3 and G4: on a linear frequency axis the spacing changes, while on a logarithmic frequency axis the same pattern simply shifts.

Background and overview

The Constant-Q Transform (CQT) is a time-frequency transform that spaces frequency bins logarithmically and keeps the ratio QQ of center frequency to bandwidth the same for every bin. It resolves low frequencies finely with long windows and high frequencies coarsely with short windows.

The ordinary short-time Fourier transform (STFT) uses windows of the same length at every frequency, so its frequency bins are spaced at equal intervals in Hz. Musical scales, however, are geometric: each semitone raises the frequency by a factor of about 1.06. In the original paper's example, analyzing 32 kHz audio with a 1024-point window gives a frequency resolution of 31.3 Hz, which at the violin's lowest note G3 (196 Hz) is as much as 16% of the frequency, too coarse to distinguish adjacent semitones (about 6% apart). At the piano's highest note C8 (4186 Hz), on the other hand, it is 0.7%, so the computation is finer than necessary.

Judith Brown proposed the CQT in 1991 for analyzing musical sounds. Because its bins are aligned with the musical scale, it can distinguish neighboring notes even in the low register and does no wasted computation in the high register. It is used for music transcription, chord and key recognition, instrument identification, and more. If the mel scale divides frequency according to "how the human ear perceives it," the CQT divides it according to "the musical scale."

Computation steps

The original paper computes a CQT that divides each octave into 24 bins (quarter tones) in the following steps.

  1. Set center frequencies geometrically: Starting from the lowest frequency of interest fmin⁑f_{\min}, space the bins by factors of 21/242^{1/24} (Eq. 1).
  2. Set Q: To distinguish adjacent bins, set the bandwidth Ξ΄f\delta f to about 3% of the frequency (21/24βˆ’1β‰ˆ0.0292^{1/24} - 1 \approx 0.029). Every bin then has Q=f/Ξ΄fβ‰ˆ34Q = f / \delta f \approx 34 (Eq. 2).
  3. Set the window length for each bin: With sampling rate SS, the window for the bin at frequency fkf_k is N[k]=(S/fk) QN[k] = (S / f_k)\, Q samples long (Eq. 3). Each bin's window contains exactly QQ periods of the wave at that frequency.
  4. Apply the window and extract the component at that frequency: Apply a Hamming window of length N[k]N[k], take the inner product with a complex sinusoid as in the discrete Fourier transform, and divide by the window length N[k]N[k] (Eq. 5).
  5. Shift in time and repeat: Slide the window at a fixed interval; arranging the values for each time and bin gives the CQT spectrogram.

In equations:

fk=(21/24)kfmin⁑,Q=fkΞ΄fk=121/24βˆ’1β‰ˆ34,N[k]=Sfk Qf_k = \left(2^{1/24}\right)^{k} f_{\min}, \qquad Q = \frac{f_k}{\delta f_k} = \frac{1}{2^{1/24} - 1} \approx 34, \qquad N[k] = \frac{S}{f_k}\, Q X[k]=1N[k]βˆ‘n=0N[k]βˆ’1W[k,n] x[n] exp⁑ ⁣(βˆ’j2Ο€QnN[k])X[k] = \frac{1}{N[k]} \sum_{n=0}^{N[k]-1} W[k, n]\, x[n]\, \exp\!\left(\frac{-j 2\pi Q n}{N[k]}\right)

Here x[n]x[n] is the audio waveform, W[k,n]=Ξ±+(1βˆ’Ξ±)cos⁑(2Ο€n/N[k])W[k, n] = \alpha + (1 - \alpha)\cos(2\pi n / N[k]) (Ξ±=25/46\alpha = 25/46) is the Hamming window, and X[k]X[k] is the (complex) value of the kk-th bin. Whereas the kk-th component of the discrete Fourier transform looks at "kk periods in a fixed window," the CQT looks at "always QQ periods in a window whose length differs per bin."

In the general form with BB bins per octave, fk=fmin⁑ 2k/Bf_k = f_{\min}\, 2^{k/B} and Q=1/(21/Bβˆ’1)Q = 1 / (2^{1/B} - 1).

Why it suits music

There are two reasons the CQT suits music.

  • The harmonic pattern has the same shape regardless of pitch: An instrument's sound consists of a fundamental frequency ff and harmonics at its integer multiples 2f,3f,…2f, 3f, \dots. On a logarithmic frequency axis, the gap between the first and second harmonics is always log⁑2\log 2, and the gap between the second and third is always log⁑(3/2)\log(3/2). When the pitch changes, the same pattern simply shifts (right side of the figure at the top of the article). On a linear frequency axis, the gaps themselves change with pitch.
  • Time and frequency resolution can be allocated per frequency: Low notes have long periods and small frequency differences from their neighbors, so they need a long window to be examined carefully. High notes differ more in frequency, so a short window is enough, which in turn captures note onsets more precisely (left side of the figure at the top).

The shift property also makes the CQT a good match for CNNs. Because a convolution finds a shifted pattern with the same filter, a chord shape learned at one pitch can be reused as is at another pitch (a transposition).

The CQT is like a piano keyboard. A keyboard has 12 keys per octave, and the keys are the same width in the low and high registers, but the frequency range (in Hz) covered by one key widens for higher notes. CQT bins are arranged the same way.

Settings and results in the original paper

The original paper applied the CQT to violin, piano, and flute sounds recorded at 32 kHz and showed that the harmonic pattern keeps a constant shape on a logarithmic frequency axis. The settings were as follows.

ItemSetting in the original paper
Bin spacingQuarter tones (24 per octave)
Q34 (68 for bins at G6 = 1568 Hz and above, to separate high harmonics)
Number and range of bins156 bins, from 174.5 Hz to the Nyquist frequency
WindowHamming window (Ξ±=25/46\alpha = 25/46)
HopEvery 500 samples (about 15 ms)

The window length varies greatly with frequency (excerpted from Table II of the original paper).

Center frequencyWindow length (samples)Window length (ms)
175 Hz6231195
494 Hz220369
988 Hz110134
1978 Hz (Q = 68)110034
5608 Hz38812
13432 Hz1625

The lowest bin uses a window of nearly 0.2 seconds, while the highest uses only 5 ms. Applying the CQT to three notes, G3, G4, and G5 (synthetic tones with 20 harmonics each), confirmed that the harmonic pattern shifts sideways while keeping the same shape. The computational cost was reported to be about the same as a 512-point discrete Fourier transform.

Practical considerations

The CQT in the original paper cannot be inverted back to the original waveform. In the high-frequency bins, the window is shorter than the hop, so some samples are never analyzed. Later work (SchΓΆrkhuber and Klapuri, 2010) proposed a computation that is approximately invertible (a signal-to-noise ratio of about 55 dB), but it cannot be inverted perfectly as the STFT can. Care is needed for applications that convert back to a waveform after the transform, such as source separation.

Keep the following points in mind as well.

  • Heavy computation: Because the window length differs per bin, it cannot be computed with a single fast Fourier transform (FFT) as is. Practical libraries (such as librosa's cqt) speed it up with a method that uses the FFT and frequency-domain kernels (Brown and Puckette, 1992) or by downsampling the waveform octave by octave.
  • Low notes are blurred in time: Low bins have long windows (about 0.2 seconds at 175 Hz with the original paper's settings), so the onset time of low notes cannot be determined precisely.
  • Time resolution differs per bin: Unlike the STFT, "frames at the same time" do not line up neatly, which complicates data handling. Practical libraries output every bin at the same interval (hop_length) to arrange them as a matrix.
  • PyTorch's torchaudio has no built-in CQT: Preprocess with librosa, or compute it with convolutions as in the implementation example below.

Comparison with other time-frequency representations

Common ways of dividing sound into time and frequency are compared below from the same perspectives.

RepresentationFrequency bin spacingWindow lengthStrengthsWeaknessesMain uses
STFT (linear spectrogram)Equal steps in HzConstantFast with the FFT; perfectly invertible to the original waveformCoarse in frequency for low notes, overly fine for high notesSource separation, speech enhancement, waveform reconstruction
Mel spectrogramEqual steps on the mel scaleConstant (bands merged after the STFT)Close to human perception; low-dimensionalDiscards fine pitch informationSpeech recognition, speech synthesis, basis for MFCC
CQTLogarithmically equal steps (aligned with the musical scale)Inversely proportional to frequencyPitches are evenly spaced, and transposition becomes a shiftHeavy computation; not perfectly invertible; low notes blurred in timeMusic transcription, chord and key recognition, instrument identification
Learned filter banks (SincNet, LEAF)Learned from dataDetermined by trainingCan learn a division suited to the taskRequires training data and computationSpeaker recognition, sound classification

As a rough guide to choosing among them:

  • Music tasks where pitch, chords, and melody matter: Use the CQT, with 12 bins per octave (one per semitone), or 24 as in the original paper if slightly detuned pitches also matter.
  • Recognizing speech or general sounds: The mel spectrogram is the standard.
  • Needing to convert back to a waveform after the transform: Use the STFT.

PyTorch example

Show code
python
import math
import torch
import torch.nn.functional as F

'''
A small implementation that computes the constant-Q transform (CQT) with convolutions, following the original paper's equations.
torchaudio has no built-in CQT, so complex kernels of different lengths are built for each bin.
(If librosa is available, librosa.cqt(y, sr=sr, fmin=..., n_bins=..., bins_per_octave=...) computes it.)
'''

class ConstantQ(torch.nn.Module):
  def __init__(self, sample_rate, f_min=174.5, bins_per_octave=24, n_bins=96, hop_length=512):
    super().__init__()
    self.hop_length = hop_length
    self.q = 1.0 / (2.0 ** (1.0 / bins_per_octave) - 1.0)      # Eq. (2): about 34 when B = 24
    self.freqs = [f_min * 2.0 ** (k / bins_per_octave) for k in range(n_bins)]  # Eq. (1)
    assert self.freqs[-1] < sample_rate / 2, 'some bins exceed the Nyquist frequency'
    self.max_len = math.ceil(sample_rate / self.freqs[0] * self.q)  # the lowest bin has the longest window
    kernels = torch.zeros(n_bins, self.max_len, dtype=torch.cfloat)
    alpha = 25.0 / 46.0
    for k, fk in enumerate(self.freqs):
      n_k = math.ceil(sample_rate / fk * self.q)                 # Eq. (3): N[k] = (S / f_k) Q
      n = torch.arange(n_k, dtype=torch.float32)
      window = alpha + (1 - alpha) * torch.cos(2 * math.pi * n / n_k)  # window formula from the original paper
      atom = window * torch.exp(-2j * math.pi * self.q * n / n_k) / n_k  # weights of Eq. (5)
      start = (self.max_len - n_k) // 2                            # align the window centers
      kernels[k, start:start + n_k] = atom
    self.register_buffer('kernel_real', kernels.real.unsqueeze(1))
    self.register_buffer('kernel_imag', kernels.imag.unsqueeze(1))

  def forward(self, x):
    # x: [batch, samples]  ->  returns: [batch, bins, frames] (magnitude)
    x = F.pad(x.unsqueeze(1), (self.max_len // 2, self.max_len // 2))
    real = F.conv1d(x, self.kernel_real, stride=self.hop_length)
    imag = F.conv1d(x, self.kernel_imag, stride=self.hop_length)
    return torch.sqrt(real ** 2 + imag ** 2)


sample_rate = 32000
t = torch.arange(sample_rate) / sample_rate
# a tone made of harmonics 1-5 of G3 (196 Hz)
wave = sum(torch.sin(2 * math.pi * 196 * h * t) for h in range(1, 6)).unsqueeze(0)

cqt = ConstantQ(sample_rate, f_min=174.5, bins_per_octave=24, n_bins=96, hop_length=500)
spec = cqt(wave)
print(spec.shape)  # [1, 96, frames]
# the harmonics fall near bin index 24Β·log2(196Β·h / 174.5) (h = 1, 2, 3, ...).
# changing the fundamental frequency does not change the index differences (spacing between harmonics)
log_spec = torch.log(spec + 1e-6)

FAQ

Q. Should I use the CQT or a mel spectrogram?
A.

As a rule of thumb, use the CQT for music tasks where pitch, chords, and melody matter, and a mel spectrogram for speech or general sounds. The mel scale is nearly linear below 1000 Hz, so in the low register it distinguishes individual notes of the scale only coarsely. The CQT divides the whole range according to the musical scale, so it handles pitch accurately.

Q. How many bins per octave should be used?
A.

To distinguish each note of the scale, 12 (one per semitone) is the minimum. The original paper used 24 (one per quarter tone, Qβ‰ˆ34Q \approx 34) to also handle slightly detuned pitches. More bins mean a larger QQ and longer windows, which is a trade-off against time resolution.

Q. How does the CQT differ from the wavelet transform?
A.

Both use "windows whose length is inversely proportional to frequency," and the CQT can be regarded as a kind of wavelet transform. The difference is the size of QQ: for music, the CQT uses fine bins of 12 to 96 per octave (a large QQ). Conventional wavelet transform methods, which assume coarse bins of about one per octave, are considered hard to use as is.

References

  1. Brown, J. C. (1991). Calculation of a constant Q spectral transform. The Journal of the Acoustical Society of America, 89(1), 425–434.
  2. SchΓΆrkhuber, C., & Klapuri, A. (2010). Constant-Q transform toolbox for music processing. Proceedings of the 7th Sound and Music Computing Conference (SMC 2010), Barcelona.
  3. librosa.cqt (librosa 0.11.0 documentation).