Skip to content

Instantly share code, notes, and snippets.

@Choumingzhao
Last active May 14, 2026 04:10
Show Gist options
  • Select an option

  • Save Choumingzhao/1e486f8e86ebf41ec92f97a9748e9ce7 to your computer and use it in GitHub Desktop.

Select an option

Save Choumingzhao/1e486f8e86ebf41ec92f97a9748e9ce7 to your computer and use it in GitHub Desktop.

Mask a raster by another raster(with NoData) using rasterio

An update-to-date solution to following questions:

Variables used:

  • RASTER1: the raster to be masked
  • RASTER2: the raster to act as mask, usually with NoData (around data)
  • MASK.geojson: the footprint of valid data from RASTER2
  • OUT_RASTER: the output file path

Steps:

  1. Convert RASTER2 to vector MASK.geojson
rio shapes raster.tif --mask --collection --crop > MASK.geojson
  1. Use vector MASK.geojson to mask RASTER1
rio mask RASTER1 OUT_RASTER --geojson-mask MASK.geojson
@Choumingzhao
Copy link
Copy Markdown
Author

  1. When masking(step 2), you may use --crop option to change the extent of the output raster to the mask extent. This is much faster when the mask area is small comparing to the raster extent.
  2. When masking, you may also use gdal cli tools. This can be much faster.
gdalwarp  -cutline mask.geojson -crop_to_cutline in.tif out.tif

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment