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:

1 Answer 1


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:
        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 ..")
        out_meta = tile.meta
        # the rest of your code here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.