Geographic Information Systems Asked on April 7, 2021
I’m cutting out several polygons from different rasters using the IDs of a shapefile and I would like the images to be just those polygons that overlap the raster without saving the empty images. Rasterio already stops as soon as it encounters an ID outside the image, returning the message:
ValueError: Input shapes do not overlap raster.
How can I solve this?
My code:
for polygon in polygons:
with fiona.open(polygon,'r')as shp:
shape=[feature["geometry"] for feature in shp]
for raster_path in rasterfiles:
output_path = outputPath + 'ID_{}'.format(shp[0]) + '.tif'
with rasterio.open(raster_path) as tile:
out_image, out_transform = rasterio.mask.mask(tile, shape, crop=True)
out_meta = tile.meta
out_meta.update({"driver": "GTiff",
"height": out_image.shape[1],
"width": out_image.shape[2],
"transform": out_transform})
with rasterio.open(output_path, "w", **out_meta) as dest:
dest.write(out_image)
From the rasterio documentation:
If shapes do not overlap the raster and crop=True, a ValueError is raised
So one way to deal with it when there is no overlap, is to catch the exception and skip to next tile. Something like that:
...
with rasterio.open(raster_path) as tile:
try:
out_image, out_transform = rasterio.mask.mask(tile, shape, crop=True)
except ValueError:
print(f"No overlap found for {tile.files[0]}. Try the next one ..")
continue
else:
out_meta = tile.meta
# the rest of your code here
Correct answer by diegus on April 7, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP