Sign in

Windowing

Windowing and framing

Cuts a signal into overlapping frames and tapers each with a window such as Hann or Hamming, so that spectra are clean and frames can be added back.

Overview

To analyse a long signal piece by piece you cut it into short frames. A plain cut is abrupt: the frame starts and ends at arbitrary values, and a Fourier transform reads those sudden edges as extra frequencies that smear across the spectrum. This smearing is called leakage. A window is a smooth curve, high in the middle and low at the ends, that you multiply into each frame so it fades in and out. Leakage far from the true frequency drops sharply, and the price is a somewhat wider peak. Because tapering hides the frame's ends, frames are made to overlap so every sample is seen at full weight by some frame.

A short history

Cutting a record to finite length smears its spectrum, an effect called leakage. Tapering the ends reduces it. The Hann window is named after the meteorologist Julius von Hann, who used that smoothing on weather data, and the Hamming window after Richard Hamming. Ralph Blackman and John Tukey described both in their 1958 work on measuring power spectra. Fredric Harris published the standard comparison of windows in 1978.

How it works

  1. Choose a frame length and a hop. The hop is the distance between the starts of consecutive frames, and a hop smaller than the frame gives overlap.
  2. Cut the signal so that frame tt holds the samples from tHtH to tH+N−1tH + N - 1. Samples that do not fill a last frame are dropped unless pad_end is on.
  3. Build the window. Use the periodic form for overlapping frames and FFTs, and the symmetric form for filter design.
  4. Multiply every frame by the window.
  5. Process the frames, for example with an FFT.
  6. To rebuild a signal, add the frames back at their original positions and divide by the sum of the overlapping windows.
  7. Check the window's properties: its coherent gain to correct amplitudes, its equivalent noise bandwidth to correct noise levels, and whether shifted copies sum to a constant.

Watch out for

  • No window is best at everything. Rectangular has the narrowest peak and the worst leakage, and Blackman has very low leakage and the widest peak. Pick for the task.
  • A window scales the measured amplitude of a tone by its mean. Forgetting to divide by the coherent gain gives readings that are too low, by half for a Hann window.
  • The symmetric form used with overlapping frames breaks the constant-sum property, because its end points are counted twice. Use the periodic form there.
  • Not every hop sums to a constant. The default 400-sample Hann window with a hop of 160 does not, so overlap_add must divide by the summed windows.
  • With pad_end off, the samples after the last full frame are silently dropped, and a signal shorter than one frame raises an error.

Use cases

When to use it

Before any frame-based spectral analysis, and whenever a signal is processed in blocks and reassembled, as in spectrogram editing, denoising and time stretching.

In industry

Audio and speech coding
Codecs and speech recognisers cut audio into overlapping frames of a few tens of milliseconds and window each before transforming it.
Test and measurement
Spectrum analysers offer Hann, flat-top and other windows so users can trade frequency resolution against amplitude accuracy.
Radar and sonar
Processors taper each pulse or array snapshot with a window to push down sidelobes that could hide weak targets.

Choosing it: what must hold

  • A signal that will be analysed in finite frames, usually before a Fourier transform.
  • A frame length that matches how fast the signal changes.
  • A window and hop size that sum to a constant if frames will be added back together.
  • A choice between narrow main lobe and low sidelobes that fits the task.

When to choose something else

IfUse instead
The record holds an exact whole number of periodsA rectangular window, which is the same as no taper
You need accurate amplitude readings of single tonesA flat-top window
Features are short and at several scales, so no single frame length suitsWavelets

Math foundations

  1. Hann and Hamming windows

    wHann[n]=0.5−0.5cos⁡ ⁣(2πnD),wHamming[n]=0.54−0.46cos⁡ ⁣(2πnD)w_{\text{Hann}}[n] = 0.5 - 0.5\cos\!\left(\frac{2\pi n}{D}\right), \qquad w_{\text{Hamming}}[n] = 0.54 - 0.46\cos\!\left(\frac{2\pi n}{D}\right)

    Both are one raised cosine cycle over the frame, for nn from 0 to N−1N - 1. Hann falls to exactly zero at the ends. Hamming stops at 0.08, which lowers the nearest side lobe at the cost of slower decay further out. D=ND = N for the periodic form and N−1N - 1 for the symmetric one.

  2. Blackman window

    w[n]=0.42−0.5cos⁡ ⁣(2πnD)+0.08cos⁡ ⁣(4πnD)w[n] = 0.42 - 0.5\cos\!\left(\frac{2\pi n}{D}\right) + 0.08\cos\!\left(\frac{4\pi n}{D}\right)

    A second cosine term makes the taper gentler still. Leakage falls much further, and the main peak becomes about 50% wider than Hann's.

  3. Framing

    xt[n]=x[tH+n] w[n],T=1+⌊Nx−NH⌋x_t[n] = x[tH + n]\,w[n], \qquad T = 1 + \left\lfloor \frac{N_x - N}{H} \right\rfloor

    Frame tt is NN samples starting at tHtH, multiplied by the window. TT is the number of whole frames in a signal of NxN_x samples.

  4. Constant overlap-add

    ∑tw[n−tH]=Cfor every n\sum_{t} w[n - tH] = C \quad \text{for every } n

    If shifted copies of the window add up to the same constant everywhere, then simply adding the windowed frames gives back the signal times CC. A periodic Hann window has this property when N/HN / H is a whole number of at least 2. The method is_cola tests it.

  5. Coherent gain

    CG⁡=1N∑n=0N−1w[n]\operatorname{CG} = \frac{1}{N}\sum_{n=0}^{N-1} w[n]

    The mean of the window. A sine of amplitude AA appears in the spectrum with amplitude AA times this value, so divide by it to read true amplitudes. It is 1 for rectangular, 0.5 for Hann and 0.54 for Hamming.

  6. Equivalent noise bandwidth

    ENBW⁡=N∑nw[n]2(∑nw[n])2\operatorname{ENBW} = \frac{N \sum_{n} w[n]^{2}}{\left(\sum_{n} w[n]\right)^{2}}

    The width, in bins, of an ideal rectangular filter that would let through the same noise power as the window's main lobe. It is 1 for rectangular and 1.5 for Hann, so a Hann-windowed bin collects 50% more noise.

Symbols

w[n]w[n]
the window, for nn from 0 to N−1N - 1
NN
the frame length in samples (frame_length)
HH
the hop between frame starts in samples (hop_length)
DD
the denominator of the cosine: NN if periodic, N−1N - 1 if symmetric
x[n]x[n]
the signal
xt[n]x_t[n]
frame tt after windowing
NxN_x
the number of samples in the signal
TT
the number of frames
CC
the constant that overlapping windows sum to
CG⁡\operatorname{CG}
the coherent gain
ENBW⁡\operatorname{ENBW}
the equivalent noise bandwidth in bins

Worked by hand

Use the default config on one second of 16 kHz audio: a periodic Hann window with N=400N = 400 and H=160H = 160. Over one full period a cosine averages to 0 and a squared cosine to 0.5.

T=1+⌊16000−400160⌋=1+97=98T = 1 + \left\lfloor \frac{16000 - 400}{160} \right\rfloor = 1 + 97 = 98
CG⁡=0.5−0.5×0=0.5\operatorname{CG} = 0.5 - 0.5 \times 0 = 0.5
1N∑nw[n]2=0.52+0.52×0.5=0.375\frac{1}{N}\sum_{n} w[n]^{2} = 0.5^{2} + 0.5^{2} \times 0.5 = 0.375
ENBW⁡=0.3750.52=1.5 bins\operatorname{ENBW} = \frac{0.375}{0.5^{2}} = 1.5 \ \text{bins}

There are 98 frames, and the last 80 samples do not fill a frame and are dropped. A tone's spectral peak reads half its true amplitude, and each bin gathers the noise of one and a half bins.

Visual example

Loading the example.

Try this

  • With the Hann window and N = 64, compare a hop of 32 with a hop of 40: only the first adds up to a constant.
  • Switch between rectangular and Blackman and watch the skirt of the spectrum drop by tens of decibels while the peak gets wider.
  • Set the hop equal to N. The frames no longer overlap and the tapered ends leave gaps.

Code sample

import numpy as np
from impl import Windowing, get_window
from config import WindowingConfig

w = Windowing(WindowingConfig(window="hann", frame_length=400, hop_length=200))
x = np.random.default_rng(0).normal(size=16000)
frames = w.windowed_frames(x)            # (79, 400)
w.is_cola()                              # True: Hann at 50% overlap sums to 1
y = w.overlap_add(frames)                # equals x except at the very first sample, where the window is zero
get_window("hamming", 5, periodic=False) # [0.08, 0.54, 1.0, 0.54, 0.08]
Read the implementation (125 lines)
"""Window functions and framing.

`get_window` builds Hann, Hamming, Blackman, Bartlett and rectangular windows in periodic or symmetric form.
`Windowing` cuts a signal into overlapping frames, applies the window, puts frames back together by
overlap-add, and reports the properties that decide which window to use: coherent gain, equivalent noise
bandwidth and whether shifted copies add up to a constant.
"""
from __future__ import annotations

import math

import numpy as np

try:
    from .config import WindowingConfig
except ImportError:  # run from the template's own folder
    from config import WindowingConfig

WINDOW_NAMES = ("hann", "hamming", "blackman", "bartlett", "rectangular")


def get_window(name: str, length: int, periodic: bool = True) -> np.ndarray:
    """Window of `length` samples, array (length,).

    periodic=True divides the cosine argument by `length` (the window continues smoothly into the next frame);
    periodic=False divides by `length - 1`, so the window is symmetric and both ends match.
    """
    if name not in WINDOW_NAMES:
        raise ValueError(f"window must be one of {WINDOW_NAMES}, got {name!r}")
    if length < 1:
        raise ValueError("length must be at least 1")
    denominator = length if periodic else length - 1
    if name == "rectangular" or denominator == 0:
        return np.ones(length)
    phase = 2.0 * np.pi * np.arange(length) / denominator
    if name == "hann":
        return 0.5 - 0.5 * np.cos(phase)
    if name == "hamming":
        return 0.54 - 0.46 * np.cos(phase)
    if name == "blackman":
        return 0.42 - 0.5 * np.cos(phase) + 0.08 * np.cos(2.0 * phase)
    return 1.0 - np.abs(2.0 * np.arange(length) / denominator - 1.0)  # bartlett: a triangle


class Windowing:
    """Framing, windowing and overlap-add with one fixed window."""

    def __init__(self, config: WindowingConfig | None = None) -> None:
        self.config = config or WindowingConfig()
        self.window = get_window(self.config.window, self.config.frame_length, self.config.periodic)

    def n_frames(self, n_samples: int) -> int:
        """Number of frames a signal of n_samples gives."""
        length, hop = self.config.frame_length, self.config.hop_length
        if self.config.pad_end:
            return max(1, int(math.ceil(max(n_samples - length, 0) / hop)) + 1)
        if n_samples < length:
            raise ValueError(f"the signal ({n_samples} samples) is shorter than one frame ({length}); set pad_end")
        return 1 + (n_samples - length) // hop

    def frame(self, x) -> np.ndarray:
        """Cut x, array (n,), into overlapping frames without windowing. Returns array (n_frames, frame_length).

        Frame i holds x[i * hop_length : i * hop_length + frame_length].
        """
        x = np.asarray(x, dtype=float).ravel()
        length, hop = self.config.frame_length, self.config.hop_length
        count = self.n_frames(x.size)
        needed = (count - 1) * hop + length
        if needed > x.size:
            x = np.concatenate([x, np.zeros(needed - x.size)])
        index = np.arange(length)[None, :] + hop * np.arange(count)[:, None]
        return x[index]

    def windowed_frames(self, x) -> np.ndarray:
        """Frames of x, each multiplied by the window. Returns array (n_frames, frame_length)."""
        return self.frame(x) * self.window

    def overlap_sum(self, n_frames: int) -> np.ndarray:
        """Sum of the window placed at every frame position, array ((n_frames - 1) * hop_length + frame_length,)."""
        length, hop = self.config.frame_length, self.config.hop_length
        total = np.zeros((n_frames - 1) * hop + length)
        for i in range(n_frames):
            total[i * hop: i * hop + length] += self.window
        return total

    def overlap_add(self, frames, normalize: bool = True) -> np.ndarray:
        """Rebuild a signal from windowed frames, array (n_frames, frame_length), by adding them in place.

        normalize=True divides by the summed windows, which undoes the windowing wherever that sum is not zero.
        Returns array ((n_frames - 1) * hop_length + frame_length,).
        """
        frames = np.asarray(frames, dtype=float)
        length, hop = self.config.frame_length, self.config.hop_length
        if frames.ndim != 2 or frames.shape[1] != length:
            raise ValueError(f"frames must have shape (n_frames, {length})")
        out = np.zeros((frames.shape[0] - 1) * hop + length)
        for i, frame in enumerate(frames):
            out[i * hop: i * hop + length] += frame
        if normalize:
            weight = self.overlap_sum(frames.shape[0])
            out = np.divide(out, weight, out=np.zeros_like(out), where=weight > 1e-12)
        return out

    def is_cola(self, tolerance: float = 1e-10) -> bool:
        """Constant overlap-add: True when shifted copies of the window sum to the same value at every sample.

        When it holds, plain addition of windowed frames returns the signal times a constant.
        """
        length, hop = self.config.frame_length, self.config.hop_length
        if hop > length:
            return False
        folded = np.zeros(hop)
        for start in range(0, length, hop):
            piece = self.window[start: start + hop]
            folded[: piece.size] += piece
        return bool(folded.max() - folded.min() <= tolerance)

    def coherent_gain(self) -> float:
        """Mean of the window: the factor by which it scales the amplitude of a sine in a spectrum."""
        return float(self.window.mean())

    def equivalent_noise_bandwidth(self) -> float:
        """Width, in FFT bins, of the ideal filter passing the same noise power: N sum(w^2) / sum(w)^2."""
        return float(self.window.size * np.sum(self.window**2) / np.sum(self.window) ** 2)
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Create Windowing() and confirm n_frames(16000), coherent_gain and equivalent_noise_bandwidth against the worked example. Print is_cola for the default hop of 160, then for WindowingConfig(hop_length=200) and WindowingConfig(hop_length=100). Finally run windowed_frames on a random signal and check that overlap_add returns the original samples away from the two ends.

Check on learning

  1. A sine that completes exactly 10 cycles in a frame shows no leakage even with a rectangular window, but one with 10.5 cycles leaks badly. Why?
    A way to think about it

    The transform treats the frame as one period of a repeating signal. Look at what happens at the seam between repetitions in each case.

  2. You are looking for a weak tone close to a tone a thousand times stronger. Which window would you try, and what do you give up?
    A way to think about it

    The weak tone must stand above the strong tone's leakage. Low side lobes come with a wider main peak, so think about how close the two can be.

  3. Why does the periodic Hann window sum to a constant at a hop of half its length, while the symmetric form does not quite?
    A way to think about it

    Add a window to a copy shifted by half a frame and use cos⁡(θ+π)=−cos⁡θ\cos(\theta + \pi) = -\cos\theta. Then check whether that shift is exactly half a cosine cycle when the denominator is N−1N - 1.

  4. With the default hop the windows do not sum to a constant, yet overlap_add with normalize on still rebuilds the signal. How, and where does it fail?
    A way to think about it

    Dividing by the actual sum of windows at each sample undoes whatever weight was applied. Ask what happens where that sum is zero or nearly zero.

  5. A smaller hop gives more frames and more overlap. What does that buy, and what does it cost?
    A way to think about it

    More frames track changes more finely in time and make reconstruction safer. Count the computation and memory, and ask whether neighbouring frames carry independent information.