Skip to content

Instantly share code, notes, and snippets.

@robbibt
Last active July 22, 2022 12:39
Show Gist options
  • Save robbibt/216d01b92aab9b5f92bd4473e374b270 to your computer and use it in GitHub Desktop.
Save robbibt/216d01b92aab9b5f92bd4473e374b270 to your computer and use it in GitHub Desktop.
Rasterio geometry mask example for Stack Exchange
import xarray as xr
import geopandas as gpd
import rasterio
# Open your shapefile and xarray object
ds = raster_mask
gdf = vector_mask
# Select shapefile feature you want to analyse
# and reproject to same CRS as xarray
gdf = gdf.iloc[[0]].to_crs(ds.crs)
# create polygon mask
mask = rasterio.features.geometry_mask(
gdf.geometry,
out_shape=ds.geobox.shape,
transform=ds.geobox.affine,
all_touched=False,
invert=False)
mask = xr.DataArray(mask, dims=("y", "x"))
# mask ds with rasterized gdf
ds = ds.where(~mask)
@e5k
Copy link

e5k commented Jul 22, 2022

Thanks for the answer @robbibt. Unfortunately, using odc.geo.xr does not add the geobox function onto my xarray dataset. Is it ok to simply open it like this or do I have to link it to old somehow?

EVI_post = xr.open_dataset('~/myfile.nc')

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