Clip/crop raster by polygon geometry in Python using Rioxarray
Raster clipping is one of the common task in raster processing. In this tutorial, we will clip a raster by polygon geometry in python using Rioxarray. Rioxarray is open source gis package that extends the functionality of xarray by rasterio.
Before cropping/clipping the raster data, we will set up conda environment and install required python GIS packages for this task. Make sure conda is installed on your system. Use following commands to create a conda environment and to install python libraries.
When you install geocube library using conda, it will automatically install related dependencies that includes gdal, shapely, rasterio, geopandas, xarray, rioxarray etc.
And we will also install pygeos library which is used to speed up the vectorized operations in GeoPandas and Shapely.
(base) geoknight@pop-os:~$conda create -n spatial-dev.guru python=3.10
(base) geoknight@pop-os:~$conda activate spatial-dev.guru
(spatial-dev.guru) geoknight@pop-os:~$conda install -c conda-forge geocube
(spatial-dev.guru) geoknight@pop-os:~$conda install -c conda-forge pygeos
Once you have successfully installed required libraries, the we will use rioxarray to clip the raster.
Before clipping raster, make sure the raster and polygon are same projection system. In our given example, both raster and polygon are in 3857 projection system.
To clip the raster, follow below steps:
- First import rioxarray and the Polygon method from shapely
- Then read the raster dataset using rioxarray
- Then, create shapely geomtery object from polygon by which you want to clip the raster.
- Then we will use clip method from rioxarray and pass shapely geometry object as parameter. This method will give you the clipped raster based on shapely geometry.
That’s it. We have successfully cropped/clipped raster based on polygon geometry
# import rioxarray and shapley
import rioxarray as riox
from shapely.geometry import Polygon
# Read raster using rioxarray
raster = riox.open_rasterio('cal_census.tiff')
# Shapely Polygon to clip raster
geom = Polygon([[-13315253,3920415], [-13315821.7,4169010.0], [-13019053.84,4168177.65], [-13020302.1595,3921355.7391]])
# Use shapely polygon in clip method of rioxarray object to clip raster
clipped_raster = raster.rio.clip([geom])
# Save clipped raster
I hope this tutorial will create a good foundation for you. If you want tutorials on another GIS topic or you have any queries, please send an email at firstname.lastname@example.org.