Last active
October 31, 2025 13:37
-
-
Save mhweber/1af47ef361c3b20184455060945ac61b to your computer and use it in GitHub Desktop.
Clipping rasters with GeoPandas and Rasterio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import geopandas as gpd | |
| import rasterio | |
| from rasterio.mask import mask | |
| from rasterio.plot import show | |
| from shapely.geometry import mapping | |
| import matplotlib.pyplot as plt | |
| df = gpd.read_file('myfile.shp') | |
| df = df.loc[df['Field']=='SomeValue'] | |
| inras = 'myraster.tif' | |
| src = rasterio.open(inras) | |
| def getFeatures(gdf): | |
| """Function to parse features from GeoDataFrame in such a manner that rasterio wants them""" | |
| import json | |
| return [json.loads(gdf.to_json())['features'][0]['geometry']] | |
| coords = getFeatures(df) | |
| clipped_array, clipped_transform = mask(dataset=src, shapes=coords, crop=True) | |
| df = df.to_crs(src.crs) | |
| out_meta = src.meta.copy() | |
| out_meta.update({"driver": "GTiff", | |
| "height": clipped_array.shape[1], | |
| "width": clipped_array.shape[2], | |
| "transform": clipped_transform}) | |
| out_tif= "clipped_example.tif" | |
| with rasterio.open(out_tif, "w", **out_meta) as dest: | |
| dest.write(clipped_array) | |
| clipped = rasterio.open(out_tif) | |
| fig, ax = plt.subplots(figsize=(8, 6)) | |
| p1 = df.plot(color=None,facecolor='none',edgecolor='red',linewidth = 2,ax=ax) | |
| show(clipped, ax=ax) | |
| ax.axis('off'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment