I'm trying to mask a raster with population data with my area of interest. I reprojected the original population raster according to the AOI's crs, but after masking and writing the new file, the crs is set back to the original's crs, even though both inputs have the right crs (which is 32644). Can anyone point me to my mistake? I know I could reproject again, but there has to be a simpler way, right?
raster_crs = CRS(AOI.crs).to_epsg()
open original raster
with rio.open(pop_path, mode='r+') as pop:
transform, width, height = calculate_default_transform(
pop.crs, raster_crs, pop.width, pop.height, *pop.bounds)
kwargs = pop.meta.copy()
kwargs.update({
'crs': raster_crs,
'transform': transform,
'width': width,
'height': height
})
CRS(pop.crs).to_epsg()
4326
reproject original raster to AOI's crs
with rio.open(pop_proj_tif, 'w', **kwargs) as pop_proj:
for i in range(1, pop.count + 1):
reproject(
source=rio.band(pop, i),
destination=rio.band(pop_proj, i),
pop_transform=pop.transform,
pop_crs=pop.crs,
pop_proj_transform=transform,
pop_proj_crs=raster_crs,
resampling=Resampling.nearest)
CRS(AOI.crs).to_epsg()
32644
CRS(pop_proj.crs).to_epsg()
32644
mask reprojected raster with AOI
with rio.open(pop_proj_tif) as pop_proj:
pop_out_image, out_transform = rio.mask.mask(pop_proj, AOI.geometry, crop=True)
pop_out_meta = pop.meta
pop_out_meta.update({"driver": "GTiff",
"height": pop_out_image.shape[1],
"width": pop_out_image.shape[2],
"transform": out_transform})
writing masked raster gives wrong CRS
with rio.open(pop_proj_clip_tif, "w", **pop_out_meta) as pop_dest:
pop_dest.write(pop_out_image)
CRS(pop_dest.crs).to_epsg()
4326
with rio.open(pop_proj_tif, 'w', **kwargs) as pop_proj:
statement does, then thereproject
writes directly to the output banddestination=rio.band(pop_proj, i)
.with rio.open(pop_proj_tif) as pop_proj:
at stage "mask reprojected raster with AOI"?import
s (so we can just substitute our data). Your code fails immediately as CRS, AOI, rio are not defined.