Clip raster by polygon geometry in Python using Rioxarray

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.

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:

  1. First import rioxarray and the Polygon method from shapely
  2. Then read the raster dataset using rioxarray
  3. Then, create shapely geomtery object from polygon by which you want to clip the raster.
  4. 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

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 contact@spatial-dev.guru.

We also offer freelancing services. Please email us at contact@spatial-dev.guru for any query.

Leave a Reply Cancel reply

%%footer%%