How it works
A polygon becomes a raster by deciding, cell by cell, how much of it is inside. There are two
common answers. Centre in asks only about the cell's centre: walk each row along the line
through its cell centres, find where the polygon's edges cross it, sort the crossings and fill
between pairs. That is GDAL's rasterize (gdal_rasterize, rasterio's rasterize) and the R package
fasterize. Each cell is in or out, so the count jumps as the grid shifts by less than a cell,
and a thin piece can fall between centres and vanish.
Exact coverage asks what fraction of the cell's area is inside, as exactextract does.
Only cells the boundary passes through need any geometry; every other cell is wholly in or
out. The fractions add up to the polygon's area in cells, however the grid is shifted. Here
they are worked out a row at a time from the boundary: each edge piece adds its part to the
cell it crosses and takes its height from every cell to its right, which is a running sum.
All touched (GDAL's ALL_TOUCHED) burns every cell the boundary meets, the cells with any
coverage. Warped rasterizes in longitude and latitude first and then resamples onto this
grid, nearest neighbour, as a warp would: compare it with rasterizing the polygon in the grid's
own CRS. A polygon's edges are straight in its own CRS, so they are densified to a quarter of a
degree before they are projected.
Storage. A raster is stored in tiles (or chunks), and a reader fetches whole tiles. The
tiles a polygon touches are what it costs to read or write it there. A dense mask spends a byte
on every cell; runs along rows (row, first, last) or a list of cell numbers spend bytes only on
the polygon; exactextract keeps a float for every cell of the polygon's bounding box. Exact
coverage is mostly ones, so runs of whole cells plus a list of edge fractions holds it in about
what the centre-in runs take. With a raster file, the tiles are the file's own at the level the
polygon is read from, and their byte ranges come from the TIFF's tile offsets, as on
Tiles and overviews.
The page's results are checked against GDAL's rasterize (cell for cell, centre in and
ALL_TOUCHED) and exactextract's coverage fractions (to 1e-7) on stars with holes, countries and
Antarctica in several CRSs, in test/check-rasterize.mjs.
- exactextract by Dan Baston (ISciences), exact coverage fractions and zonal statistics.
- fasterize by Noam Ross (EcoHealth Alliance), a scanline polygon fill for R.
- GDAL's rasterize, by Frank Warmerdam, Even Rouault and the GDAL contributors.
- Shapes from Natural Earth; grids projected with proj4js; the globe drawn with d3-geo.