I would like to know if there is any way that I can extract images from a GeoTIFF file using an ESRI shapefile which contains shapely polygon data for specific locations in the image in Python.

I would like to extract an image per polygon in the shapefile. The closest I have gotten to this until now is using gdal_rasterize to mask out all the areas outside the Polygons and creating windows using rasterio.

  • The rasterstats package will do this for you also.
    – Jon
    Nov 19, 2019 at 15:27

2 Answers 2


You can use rioxarray. Here is an example: https://corteva.github.io/rioxarray/stable/examples/clip_geom.html

Fiona example:

import rioxarray
import fiona

xds = rioxarray.open_rasterio(...)
with fiona.open(...) as fds:
    for row in fds:
        clipped = xds.rio.clip([row["geometry"]], fds.crs_wkt)

geopandas example:

import rioxarray
import geopandas
from shapely.geometry import mapping

xds = rioxarray.open_rasterio(...)
gpd = geopandas.read_file(...)

for _, geom in gpd.geometry.apply(mapping).iteritems():
    clipped = xds.rio.clip([geom], gpd.crs)

The mask and rasterize code is good but you need to do it for each feature in the shapefile.

Open the shapefile using fiona and loop through individual features.

features = fiona.open("myshapefile.shp")

for polys in features: masking and clip code here.

This will give you a separate image for each polygon in the shapefile

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.