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

Interpolation on grids

ProblemInterpolate values given on a rectilinear grid in two, three or more dimensions: images, terrain, physical fields, lookup tables
Devised byTensor-product interpolation: classical; bicubic convolution: Robert Keys (1981); Lanczos resampling: after Cornelius Lanczos’s sigma factors (1956), popularised by Claude Duchon (1979); B-spline interpolation: Isaac Schoenberg, made fast by Michael Unser and colleagues (1991); all-phase interpolation: Hou Zhengxin and colleagues (2000s)
AccuracyNearest: . Bilinear and multilinear: . Bicubic, tricubic Lagrange and B-spline: up to . Fourier: exponential for smooth periodic data
CostPer evaluation: , , or grid values in dimensions; B-splines need a prefilter pass once
Read firstPolynomial interpolation, Piecewise and spline interpolation
API2D: Nearest2D, Bilinear, Bicubic, CubicBasis2D, Lanczos2D, AllPhase2D, FourierInterpolator2D. 3D: Trilinear, CubicLagrangian3D, BSpline3D, FourierInterpolator3D. N-D: GridData, NearestND, CubicBasisND

Overview

Data on a grid is everywhere: the pixels of an image, the cells of a terrain model, the nodes of a simulation, the entries of a multidimensional lookup table. Interpolating between grid values is easier than interpolating scattered points, because the regular structure lets each one-dimensional method extend to several dimensions as a tensor product: interpolate along one axis, then along the next, and so on.

The methods differ in how many neighbouring values they use and how they weight them, which decides their accuracy, their smoothness, and their behaviour in image processing, where the visual result matters more than the error in a norm. This entry covers the classical polynomial methods (nearest, multilinear, bicubic, tricubic, B-spline), the kernel methods of signal processing (Lanczos, all-phase), and Fourier interpolation for periodic fields.

Where it is used

Data on a regular grid are interpolated millions of times a second in practice.

  • Lookup tables. Engine maps, aerodynamic coefficients and sensor calibrations stored on grids are interpolated at the operating point by controllers and simulators.
  • Images. Resizing and rotating pictures uses bilinear or bicubic interpolation.
  • Earth science. Elevation, temperature and wind fields are sampled on latitude-longitude grids and queried at arbitrary locations.
  • Higher dimensions. Multilinear and spline interpolation in 3-D and 4-D for volumetric and time-dependent data.

History

Linear interpolation in two variables was used with tables of functions of two arguments long before computers. Image processing made grid interpolation a central problem in the 1970s and 1980s: Robert Keys (1981) derived the cubic convolution kernel used in most image software, and Claude Duchon (1979) proposed filters based on Lanczos’s “sigma factors” for reducing Gibbs oscillations, which became the Lanczos resampling kernel. Michael Unser, Akram Aldroubi and Murray Eden (1991) showed how to interpolate with B-splines by a fast recursive prefilter, making smooth high-quality spline interpolation of images practical. All-phase interpolation and filtering were developed by Hou Zhengxin and colleagues in the 2000s, from the idea of averaging over all window alignments.

The idea

Tensor products

Every one-dimensional interpolation method in the previous entries can be written as a weighted sum of the data, , where the weights depend on where lies but not on the data. For linear interpolation between and , for example, with the fraction of the way across, the weights are and .

On a two-dimensional grid with values at the points , apply the method in two stages. First interpolate along within each grid row , which gives a value for each row. Then interpolate these row values along :

The weight of each grid value is the product of a one-dimensional weight for each axis. This construction is called a tensor product, and it works the same way in any number of dimensions. The order of the axes does not matter, since the final formula is symmetric in them.

The simplest example is bilinear interpolation, which uses the two nearest values per axis with linear weights. In a grid cell with corner values and fractional position ,

Each corner is weighted by the area of the rectangle opposite to it. Despite the name, the result is not a plane: it contains the product term , so it is linear along each axis but curved along the diagonals. Multilinear interpolation is the same in dimensions and uses the corners of the enclosing cell. Both are exact for functions that are linear in each coordinate separately and have error , like linear interpolation in one dimension.

Cubic methods

Higher accuracy needs more neighbours. The cubic methods use four values per axis, so 16 values in two dimensions and 64 in three. The library has three, all tensor products of one-dimensional cubic methods.

  • Bicubic interpolation is the tensor product of cubic Hermite interpolation. In each cell it fits a patch that matches the values and the estimated derivatives , and at the four corners. When the derivatives are estimated by central differences it is the same method as the Catmull-Rom cubic basis, and the two give identical results in the table below.
  • Tricubic Lagrange interpolation passes a cubic polynomial through the four nearest values along each axis, the tensor product of polynomial interpolation at four points.
  • The B-spline method is the tensor product of the cubic spline. It writes the interpolant as a sum of shifted copies of one smooth bump, the cubic B-spline , one copy centred on each grid point: . The bump is wider than one cell, so neighbouring bumps overlap and the coefficients are not the data values. They must be found first, by solving a tridiagonal system along each axis (the prefilter), exactly as a spline’s coefficients are found in one dimension. The result is twice continuously differentiable and fourth-order accurate.

Interpolation as convolution

On a uniform grid there is a second way to look at all these methods. Measure position in units of the grid spacing, so that the samples sit at the integers . Every linear method can then be written as

for some function , called the kernel of the method. The formula says: place a copy of at each sample, scale it by the sample value, and add the copies up. This operation is a convolution. To find the kernel of a method, feed it data that are 1 at one grid point and 0 everywhere else; the function it returns is . The figure shows the library’s kernels, computed exactly that way:

Figure 3.11. Interpolation kernels.

Every kernel equals 1 at and 0 at the other integers, which is what makes the method interpolate. Linear interpolation has a triangular kernel; the cubic kernels are smoother and have small negative lobes.

Signal processing suggests an ideal. If the data are samples of a band-limited function (one containing no frequencies above half the sampling rate), the sampling theorem says the function is recovered exactly with the kernel . The sinc function decays slowly and extends to infinity, so it cannot be used as it stands. Two practical kernels shorten it.

  • Lanczos resampling multiplies the sinc by a wider copy of itself, which acts as a window and brings it smoothly to zero: for , and 0 beyond.
  • All-phase interpolation averages the sinc interpolations of all -sample windows containing the point. The effect is a sinc tapered by a triangle, .

Both kernels have negative lobes that sharpen edges in images, at the price of slight ringing (faint echoes beside sharp edges).

Accuracy

The library’s errors for interpolation from a grid over :

Table 3.9. Accuracy of two-dimensional grid interpolation methods.

methodperiodic , interiornon-periodic , interiornon-periodic, whole grid
nearest8.0e-24.1e-24.4e-2
bilinear1.3e-28.9e-49.4e-4
bicubic5.9e-45.8e-61.7e-4
cubic basis (Catmull-Rom)5.9e-45.8e-61.7e-4
Lanczos, a = 33.1e-32.1e-34.6e-3
all-phase, n = 41.2e-31.4e-53.8e-3
Fourier1.6e-162.2e-21.0e-1

Three lessons stand out. The cubic methods are the most accurate for smooth data, by a wide margin. The windowed-sinc kernels are designed for images, not accuracy: Lanczos reproduces constants but not straight lines, so its error on a smooth non-band-limited function falls only like . And Fourier interpolation is exact to rounding for smooth periodic data but useless for non-periodic data, whose implied jump at the boundary causes Gibbs oscillations. Near the edges, every method that needs values beyond the grid (here they are replicated from the edge) loses accuracy.

In three dimensions the same pattern holds; the B-spline overtakes the Lagrange interpolant as the grid is refined, thanks to its global smoothness:

Table 3.10. Accuracy of three-dimensional grid interpolation methods.

gridtrilineartricubic Lagrangetricubic B-spline
5³1.7e-28.2e-41.7e-3
9³4.3e-36.0e-51.1e-4
17³1.1e-33.0e-64.5e-7
33³2.7e-42.1e-72.4e-8

Algorithm

Set-up. Most methods need none: they read the grid values directly. The B-spline interpolant first replaces the data by coefficients, solving the tridiagonal system along every line of the grid in each direction in turn (the prefilter). The Fourier interpolants compute a multidimensional FFT of the data.

Evaluation at a point, for a method that uses values per axis in dimensions ( for multilinear, 4 for the cubic methods, for a kernel of half-width ):

  1. Locate the cell. For each axis, find the grid interval containing the coordinate: by binary search on a non-uniform axis, or by one division on a uniform one. This also gives the fractional position within the cell.
  2. Compute the weights. For each axis, evaluate the method’s one-dimensional weights at that fractional position.
  3. Sum. Add up the neighbouring grid values, each multiplied by the product of its weights along the axes. Neighbours beyond the edge of the grid are supplied by the method’s edge rule (see the implementation notes).

The cost per point is , so the cubic methods cost 16 values in two dimensions and 64 in three.

Implementation

        let mut idx = vec![0usize; dims];
        let mut sum = 0.0;
        for corner in 0..(1usize << dims) {
            let mut weight = 1.0;
            for d in 0..dims {
                let up = (corner >> d) & 1;
                idx[d] = cell[d] + up;
                weight *= if up == 1 { t[d] } else { 1.0 - t[d] };
            }
            if weight != 0.0 {
                sum += weight * self.values[&idx[..]];
            }
        }
  • All grid interpolators validate that the axes are strictly increasing; the kernel methods and the B-spline also require uniform spacing.
  • Outside the grid, the polynomial methods extend their edge cells; the kernel methods replicate edge values; the Fourier interpolants are periodic.

In practice

//! Interpolation on grids in two, three and N dimensions.
//!
//! Run with `cargo run --release -p lib_jsl_interpolation --example interpolation_grids`.

use lib_jsl_core::{R1D, R2D};
use lib_jsl_interpolation::nd::InterpolationND;
use lib_jsl_interpolation::nd::grid_data::GridData;
use lib_jsl_interpolation::three_d::Interpolation3D;
use lib_jsl_interpolation::three_d::b_spline::BSpline3D;
use lib_jsl_interpolation::two_d::Interpolation2D;
use lib_jsl_interpolation::two_d::{bicubic::Bicubic, bilinear::Bilinear, lanczos::Lanczos2D};
use ndarray::{Array3, ArrayD, Dimension, IxDyn};

fn main() {
    // A height map sampled every 10 m over 200 m × 150 m.
    let x = R1D::from_vec((0..=20).map(|i| 10.0 * i as f64).collect());
    let y = R1D::from_vec((0..=15).map(|j| 10.0 * j as f64).collect());
    let terrain = |x: f64, y: f64| 50.0 + 20.0 * (x / 60.0).sin() * (y / 45.0).cos() + 0.05 * x;
    let z = R2D::from_shape_fn((21, 16), |(i, j)| terrain(x[i], y[j]));
    let (bl, bc, lz) = (Bilinear::new(x.view(), y.view(), z.view()).unwrap(), Bicubic::new(x.view(), y.view(), z.view()).unwrap(), Lanczos2D::new(x.view(), y.view(), z.view(), 3).unwrap());
    let (px, py) = (123.4, 67.8);
    println!("height at ({px}, {py}): exact {:.4}", terrain(px, py));
    println!("  bilinear {:.4}, bicubic {:.4}, Lanczos-3 {:.4}", bl.interpolate_at(px, py).unwrap(), bc.interpolate_at(px, py).unwrap(), lz.interpolate_at(px, py).unwrap());

    // A temperature field on a 3D grid, with a smooth tricubic B-spline.
    let a = R1D::from_vec((0..11).map(|i| i as f64 / 10.0).collect());
    let field = |x: f64, y: f64, z: f64| (x * y).exp() + z.sin();
    let v = Array3::from_shape_fn((11, 11, 11), |(i, j, k)| field(a[i], a[j], a[k]));
    let spline = BSpline3D::new(a.view(), a.view(), a.view(), &v).unwrap();
    println!("3D B-spline at (0.33, 0.47, 0.71): {:.6} (exact {:.6})", spline.interpolate_at(0.33, 0.47, 0.71).unwrap(), field(0.33, 0.47, 0.71));

    // Multilinear interpolation in 4 dimensions (5 points per axis).
    let axis: Vec<f64> = (0..5).map(|i| i as f64 * 0.25).collect();
    let axes = [axis.as_slice(); 4];
    let values = ArrayD::from_shape_fn(IxDyn(&[5, 5, 5, 5]), |i| i.as_array_view().iter().map(|&k| k as f64 * 0.25).sum::<f64>());
    let g = GridData::new(&axes, &values).unwrap();
    println!("4D multilinear at (0.1, 0.2, 0.3, 0.4): {:.6} (exact 1.0 for this linear function)", g.interpolate_at(&[0.1, 0.2, 0.3, 0.4]).unwrap());
}

Strengths

  • Fast, local and simple, in any number of dimensions.
  • Cubic and B-spline methods are fourth-order accurate for smooth data; Fourier interpolation is spectrally accurate for periodic data.

Weaknesses

  • The cost grows as (cubic) or (linear) per evaluation in dimensions.
  • Windowed-sinc kernels trade accuracy for visual quality.
  • The data must lie on a full grid; for scattered data see the next entry.

Exercises

  1. Show that bilinear interpolation on a cell is exact for , and not for .
  2. Compute the Lanczos-2 weights for and check whether . What does the answer imply about linear functions?
  3. Show that the B-spline prefilter equations follow from requiring , using , .
  4. Downsample an image-like function such as a checkerboard with sharp edges by each method and compare the ringing near the edges.
  5. Implement linear interpolation of a 5-dimensional lookup table with GridData and estimate how its cost grows with the dimension.
Hints and answers
  1. Bilinear interpolation reproduces the span of because it is the unique function in that span with the four corner values. For on the corner values are and , the interpolant along the bottom edge is , and at it gives rather than .
  2. for . At the four weights are . They sum to , not 1, and . The raw kernel does not reproduce constants exactly, but after dividing by the weight sum the second sum is exactly (by symmetry), so a normalised kernel reproduces linear functions at this point.
  3. The spline is , so : a tridiagonal system for the coefficients .
  4. Expect linear interpolation to blur edges without overshoot and cubic or Lanczos kernels to sharpen them but ring (overshoot) on either side; compare the pixel values next to an edge.
  5. The number of cell corners is , so a lookup in a 5-dimensional table needs 32 values and the cost doubles with each added dimension. The table itself also grows as .

Further reading

  • R. G. Keys, “Cubic convolution interpolation for digital image processing”, IEEE Transactions on Acoustics, Speech, and Signal Processing 29 (1981) 1153–1160.
  • C. E. Duchon, “Lanczos filtering in one and two dimensions”, Journal of Applied Meteorology 18 (1979) 1016–1022.
  • M. Unser, A. Aldroubi and M. Eden, “Fast B-spline transforms for continuous image representation and interpolation”, IEEE Transactions on Pattern Analysis and Machine Intelligence 13 (1991) 277–285.
  • P. Thévenaz, T. Blu and M. Unser, “Interpolation revisited”, IEEE Transactions on Medical Imaging 19 (2000) 739–758. A thorough comparison of interpolation kernels.