Lably
Skip to content

Marching squares

  • 4 min read
  • 4 chapters

Related on Lably

Through Algorithm, Contour line and Topographic map

The contours can be of two kinds:

  • Isolines – lines following a single data level, or isovalue.
  • Isobands – filled areas between isolines.

Typical applications include the contour lines on topographic maps or the generation of isobars for weather maps.

Marching squares takes a similar approach to the 3D marching cubes algorithm:

  • Process each cell in the grid independently.
  • Calculate a cell index using comparisons of the contour level(s) with the data values at the cell corners.
  • Use a pre-built lookup table, keyed on the cell index, to describe the output geometry for the cell.
  • Apply linear interpolation along the boundaries of the cell to calculate the exact contour position.

Basic algorithm

Here are the steps of the algorithm:

Apply a threshold to the 2D field to make a binary image containing:

  • 1 where the data value is above the isovalue
  • 0 where the data value is below the isovalue

Note: Data equal to the isovalue has to be treated as above or below in a consistent way.

Every 2x2 block of pixels in the binary image forms a contouring cell, so the whole image is represented by a grid of such cells (shown in green in the picture below). Note that this contouring grid is one cell smaller in each direction than the original 2D field.

For each cell in the contouring grid:

  1. Compose the 4 bits at the corners of the cell to build a binary index: walk around the cell in a clockwise direction appending the bit to the index, using bitwise OR and left-shift, from most significant bit at the top left, to least significant bit at the bottom left. The resulting 4-bit index can have 16 possible values in the range 0–15.
  2. Use the cell index to access a pre-built lookup table with 16 entries listing the edges needed to represent the cell (shown in the lower right part of the picture below).
  3. Apply linear interpolation between the original field data values to find the exact position of the contour line along the edges of the cell.

Disambiguation of saddle points

The contour is ambiguous at saddle points. It is possible to resolve the ambiguity by using the average data value for the center of the cell to choose between different connections of the interpolated points (four images in bottom-right corner):

Isobands

A similar algorithm can be created for filled contour bands within upper and lower threshold values:

Sign in to keep reading

3 more chapters are free with a Lably account.

More in Computing and communication