Created
September 22, 2020 04:44
-
-
Save cbur24/56dd1145985384207de8ee5d246a2668 to your computer and use it in GitHub Desktop.
Looping through geopandas df, loading datacube data, masking with geometry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import datacube | |
import xarray as xr | |
import geopandas as gpd | |
from datacube.utils import geometry | |
sys.path.append('../Scripts') | |
from deafrica_datahandling import load_ard | |
from deafrica_spatialtools import xr_rasterize | |
#Connect to datacube | |
dc = datacube.Datacube(app='masking') | |
for index, row in gdf.iterrows(): | |
# Get the geometry | |
geom = geometry.Geometry(row.geometry.__geo_interface__, | |
geometry.CRS(f'EPSG:{gdf.crs.to_epsg()}')) | |
# generate a datacube query object | |
query = { | |
'time': time, | |
'measurements': measurements, | |
'resolution': resolution, | |
'output_crs': output_crs, | |
'group_by' : 'solar_day', | |
} | |
# Update dc query with geometry | |
query.update({'geopolygon': geom}) | |
#load data from datacube | |
ds = load_ard(dc=dc, | |
products=products, | |
dask_chunks=dask_chunks, | |
**query) | |
# Mask dataset to set pixels outside the polygon to `NaN` | |
mask = xr_rasterize(gdf.iloc[[index]], ds) | |
ds = ds.where(mask) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment