[GIS] Mask rasterio raster with geopandas shapefile

geopandaspythonrasterrasterioshapefile

I am loading a shapefile using geopandas as follows:

import geopandas as gpd
StudyA = gpd.read_file('.../Study_Area_Polygon.shp')

Next, I am using folium to plot it interactively:

m = folium.Map([36.43, 43.06], zoom_start=12)
folium.GeoJson(StudyA).add_to(m)
m

My objective is now to use rasterio to mask a raster using the shapefile I have loaded before with the following code:

img, out_transform = rasterio.mask.mask(img, StudyA, crop=True, all_touched=True)

However, I am facing an issue as the information of the mask should be provided as a list of GeoJSON-like dicts according to rasterio documentation. How can I produce that GeoJSON-like dicts when reading the shapefile with geopandas.

Previously, I was reading the shp using the following code and it worked well. The issue is that I want/need to use geopandas for interactive plotting with folium

with fiona.open(".../Study_Area_Polygon.shp", "r") as StudyArea:
    shape = [feature["geometry"] for feature in StudyArea]

Best Answer

If your geodataframe has a column named "geometry" and geometry consists of Shapely Polygons, the following works for me

from rasterio.mask import mask

out, _ = mask(data, gdf.geometry, invert=False)