I have a polygon shapefile (containing 22 features) and raster files.

  • I wrote a code to clip the raster by shapefile and produce 22 separate raster files with polygon id. The problem is that within those 22 polygons, there are some which do not overlay with the raster file, so I have many outputs as black, empty raster images.
  • The question is how to determine polygons which overlay with a given raster file and remove those which don't. So the result would be only clipped raster images which overlay (the highlighted yellow ones)?

For example, in the picture, I have one large raster file and shapefile with 22 features where some of them overlay with a particular raster, and some of the don't. Then using python code I clip that raster using one single shapefile. As a result, I got clipped raster as separate files (the yellow ones which overlay) and also clipped files which do not overlay and create an empty file.

How can I not generate those clipped raster which does not overlay?

enter image description here

Here is the python code I used to clip rasters:

from osgeo import gdal
from osgeo import ogr

raster_fname = r'W:\large_raster.tif'
vector_fname = r'W:\polygon_shapes.shp'

gg = ogr.Open(vector_fname)

layer = gg.GetLayerByIndex(0)

# # Loop over all features
for ifeat in layer:
    id = ifeat.GetFieldAsInteger('id')
    fname_out = raster_fname.replace(".tif", f"_{int(id):01}.tif")
    OutTile = gdal.Warp(fname_out, raster_fname, format="GTiff",
                    dstNodata = 0)
    OutTile = None 

1 Answer 1


If you aren't set on using the gdal Python bindings, the rasterstats module provides this functionality out of the box, outputting "mini-rasters" as clipped and masked numpy arrays, which you can then write to disk. It uses rasterio as a dependency.

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.