Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Discrete cosine and sine transforms

ProblemExpand real data in cosines or sines: the discrete cosine and sine transforms of types I to IV, their inverses and orthonormal forms
Devised byNasir Ahmed, T. Natarajan and K. R. Rao (1974), the DCT-II; Zhongde Wang and others (1984), the classification into types I–IV; the JPEG committee (1992), image compression; John Princen and Alan Bradley (1986), the modified DCT of audio coding
Accuracy, through complex FFTs
CostOne complex FFT of length about plus work
Read firstThe fast Fourier transform
APIdct, idct, dst, idst, TrigTransformType, TrigNormalization

Overview

The DFT implicitly treats data as one period of a periodic signal. For data that is not periodic, the jump between the last sample and the first produces large high-frequency coefficients, decaying only like . The discrete cosine transform instead treats the data as half of an even signal, its mirror image appended, which has no jump: for smooth data its coefficients decay like or faster, so a few of them capture most of the signal. That energy compaction made the DCT-II the transform of JPEG images and MPEG video, and its relative the modified DCT the transform of MP3 and AAC audio.

The cosine and sine transforms are also the eigenvector bases of the second-difference matrix with Neumann and Dirichlet boundary conditions, so they diagonalise Poisson’s equation on rectangles and appear in spectral methods (the Chebyshev transform is a DCT-I).

Where it is used

The cosine transform is the FFT’s cousin for real data, and it is everywhere in compression.

  • Images and video. JPEG, MPEG and H.264/H.265 split pictures into blocks and quantise their DCT coefficients, because most of the energy sits in a few low-frequency terms.
  • Audio. MP3 and AAC use the modified DCT to compress sound.
  • Numerical methods. The DCT and DST diagonalise the second-difference matrix with Neumann or Dirichlet boundaries, so they solve Poisson and heat equations fast (see spectral methods).

History

Nasir Ahmed proposed the cosine transform in 1972 as an approximation of the optimal Karhunen-Loève transform for correlated signals, and published it with T. Natarajan and K. R. Rao in 1974. Zhongde Wang (1984) classified the eight variants by the symmetry of the extension (types I to IV of cosines and sines). The JPEG image standard (1992) used the DCT-II, and John Princen and Alan Bradley’s modified DCT (1986), a lapped DCT-IV, underlies MP3, AAC and Vorbis audio.

The idea

Symmetric extensions

The DFT treats its samples as one period of a periodic signal. If the last sample differs from the first, the periodic signal has a jump at every period boundary, and a jump needs many high frequencies to represent. The cosine and sine transforms avoid this by a different assumption about what lies beyond the ends of the data.

Take the samples and reflect them, as in a mirror, before repeating. For the samples one such extension is

This sequence is continuous at the joins, whatever the data are. It is also even (symmetric), and the Fourier series of an even sequence contains only cosines. Its DFT, of length , is therefore real (after a phase factor accounting for the position of the mirror), and only of its values are independent. Those real numbers are a discrete cosine transform (DCT) of the original samples. Reflecting with a change of sign (an odd extension) gives sines instead, and a discrete sine transform (DST).

There are several types, because there are choices to make: the mirror at each end can sit exactly on a sample or halfway between two samples, and the extension at each end can be even or odd. The example above, with both mirrors between samples and both extensions even, is the DCT-II. With the unnormalised conventions of SciPy and FFTW, the four common types of each are:

typecosine transform sine transform
I
II
III
IV

In the DCT-II formula the argument places sample at the position , the midpoint of its cell, which is the “mirror between samples” of the extension.

Types II and III are inverses of each other (up to a factor ), and types I and IV are their own inverses (up to and ). The orthonormal normalisation rescales each transform to an orthogonal matrix, so that its inverse is its transpose and it preserves the sum of squares of the data. “The DCT” usually means the DCT-II, and “the inverse DCT” the DCT-III.

Energy compaction

The smoother a periodic function is, the faster its Fourier coefficients decay. A jump gives coefficients that decay like ; a continuous function with a jump in its slope gives .

Take a smooth function on that is not periodic, sampled at the midpoints of cells. Its periodic extension, which the DFT sees, has a jump, so the DFT coefficients decay like . Its even extension, which the DCT-II sees, is continuous with at worst a corner, so the DCT-II coefficients decay like :

Figure 8.4. Energy compaction of the DCT.

Most of the signal’s energy is therefore packed into the first few DCT coefficients, and discarding the rest changes the signal very little. This property is called energy compaction, and it is the reason the DCT is used for compression: JPEG quantises the high-frequency DCT coefficients of each block coarsely or discards them.

Computing through the FFT

Since each transform is the DFT of a symmetric extension, each can be computed with one complex FFT of length about applied to the extended sequence, followed by a correction for the position of the mirror:

  • the DCT-I from the even extension of length ;
  • the DCT-II from the even extension of length , followed by multiplication by the twiddle factor , which shifts the origin by the half sample between the mirror and the first sample;
  • the DCT-III by the inverse of that;
  • the DCT-IV by twiddled zero-padding to length ;
  • the DST-I from the odd extension of length ;
  • the DST-II and DST-III from the corresponding cosine transforms, by reversing the order of the data and alternating signs;
  • the DST-IV as the imaginary part of the same twiddled FFT as the DCT-IV.

All are and inherit the FFT’s accuracy: compared with a direct sum with exactly reduced angles, the DCT-II is accurate to at .

Algorithm

dct(x, kind, norm) computes any of the four types through one complex FFT.

  1. Validate the length (type I needs at least two samples).
  2. Build the FFT input for the type:
    • type I: the even extension of length , that is followed by ;
    • type II: the even extension of length , that is followed by ;
    • type III: the samples multiplied by the twiddle factors , arranged so that the transform that follows inverts type II;
    • type IV: the samples multiplied by a twiddle factor and zero-padded to length .
  3. Transform with a complex FFT.
  4. Extract. Take the first outputs. For type II multiply output by , and for type IV by its own twiddle factor; keep the real parts.
  5. Normalise. With norm = Ortho, scale the outputs (the first, and for type I the last, by a different factor from the rest) so that the transform is an orthogonal matrix.

idct applies the inverse type (III for II, II for III, the same type for I and IV) with the scaling that makes the round trip exact. The sine transforms follow the same five steps with odd extensions, or reduce to a cosine transform by reversing the order of the input and alternating the signs of the output. Every transform costs one FFT of length about .

Implementation

fn dct_raw(x: &[f64], kind: TrigTransformType) -> Result<Vec<f64>, ErrorsJSL> {
    let n = x.len();
    Ok(match kind {
        I => {
            let ext: Vec<f64> = x.iter().copied().chain(x[1..n - 1].iter().rev().copied()).collect();
            unscaled_fft(&real(&ext), FftDirection::Forward)?[..n].iter().map(|v| v.re).collect()
        }
        II => {
            let ext: Vec<f64> = x.iter().copied().chain(x.iter().rev().copied()).collect();
            let big = unscaled_fft(&real(&ext), FftDirection::Forward)?;
            (0..n).map(|k| (C64::from_polar(1.0, -PI * k as f64 / (2 * n) as f64) * big[k]).re).collect()
        }
        III => {
            let mut w = vec![C64::new(0.0, 0.0); 2 * n];
            for (k, &a) in x.iter().enumerate() {
                let c = if k == 0 { 0.5 } else { 1.0 };
                w[k] = C64::from_polar(c * a, PI * k as f64 / (2 * n) as f64);
            }
            unscaled_fft(&w, FftDirection::Inverse)?[..n].iter().map(|v| 2.0 * v.re).collect()
        }
        IV => type_four_core(x)?.iter().map(|v| v.re).collect(),
    })
}
  • TrigNormalization::Backward is the unnormalised forward transform with the scaling on the inverse (SciPy’s default); Ortho makes both orthogonal.
  • The extensions are transformed with the complex Fft, of any length.

In practice

//! Discrete cosine and sine transforms: compression by truncating DCT coefficients.
//!
//! Run with `cargo run -p lib_jsl_ffts --example fft_dct`.

use lib_jsl_ffts::{TrigNormalization, TrigTransformType, dct, dst, idct};

fn main() {
    // A smooth signal on [0, 1]: its DCT-II coefficients decay quickly.
    let n = 64;
    let x: Vec<f64> = (0..n).map(|k| { let t = (k as f64 + 0.5) / n as f64; (2.0 * t).exp() * (3.0 * t).cos() }).collect();
    let c = dct(&x, TrigTransformType::II, TrigNormalization::Ortho).unwrap();
    // Keep only the largest coefficients (orthonormal: the energy of the rest is the squared error).
    let mut order: Vec<usize> = (0..n).collect();
    order.sort_by(|&a, &b| c[b].abs().total_cmp(&c[a].abs()));
    let scale = x.iter().fold(0.0f64, |m, v| m.max(v.abs()));
    for keep in [4, 8, 16] {
        let mut kept = vec![0.0; n];
        for &k in &order[..keep] {
            kept[k] = c[k];
        }
        let approx = idct(&kept, TrigTransformType::II, TrigNormalization::Ortho).unwrap();
        let err = approx.iter().zip(&x).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max);
        println!("{keep:>2} of {n} DCT coefficients: largest error {:.1e} of the signal's size", err / scale);
    }

    // The DST-I diagonalises the second-difference matrix with zero boundary values.
    let s = dst(&[0.0, 1.0, 0.0, 0.0, 0.0], TrigTransformType::I, TrigNormalization::Backward).unwrap();
    println!("DST-I of e₁: {s:.4?}");
}

Strengths

  • All eight classical transforms, unnormalised or orthonormal, for any length, in .
  • Excellent energy compaction for smooth, non-periodic data.

Weaknesses

  • Computed through complex FFTs of twice the length, about four times the work of a dedicated real-to-real algorithm.
  • No modified (lapped) DCT and no multidimensional DCT (apply dct along each axis).

Exercises

  1. Show that the DCT-II of is, up to a twiddle, the DFT of its even extension of length .
  2. Verify numerically that the orthonormal DCT-II matrix is orthogonal for .
  3. Compress a sampled smooth function by keeping the largest DCT-II coefficients and plot the error against ; compare with the DFT.
  4. Show that the vectors are eigenvectors of the second-difference matrix with zero boundary values, and use the DST-I to solve on .
  5. Implement the two-dimensional DCT-II of an image block with dct along rows and columns.
Hints and answers
  1. The even extension of length is symmetric about . Its DFT sums times a phase : that phase is the twiddle, and the cosine sum is the DCT-II.
  2. Build the matrix with and check to rounding.
  3. A smooth function has rapidly decaying DCT coefficients because its even extension is also smooth, whereas the DFT’s periodic extension has a jump unless the function is periodic, so DFT coefficients decay slowly. Expect the DCT error to fall much faster with .
  4. The second-difference matrix (tridiagonal ) satisfies for . Transform with the DST-I, divide by and transform back.
  5. Apply the one-dimensional dct to each row, then to each column of the result.

Further reading

  • N. Ahmed, T. Natarajan and K. R. Rao, “Discrete cosine transform”, IEEE Transactions on Computers C-23 (1974) 90–93.
  • G. Strang, “The discrete cosine transform”, SIAM Review 41 (1999) 135–147.
  • K. R. Rao and P. Yip, Discrete Cosine Transform: Algorithms, Advantages, Applications, Academic Press, 1990.
  • S. A. Martucci, “Symmetric convolution and the discrete sine and cosine transforms”, IEEE Transactions on Signal Processing 42 (1994) 1038–1051.