Clipping a Raster using a Shapefile

less than 1 minute read

Published:

A python script to clip raster data (.tiff file) using a Shapefile (.shp)

The python script below allows clipping a raster data or .tiff within the geographical domain specified by a .shp file. This type of clipping is highly useful if you have raster data of a large domain (say global data), but you want to clip it for a specific region, say for a specific country or state.

To achieve the clipping, certain geospatial libraries are required to be pre-installed such as fiona, rasterio, and good old numpy.


import fiona
import rasterio
import rasterio.mask
import numpy as np
# import affine
# import geopa



import sys
img = sys.argv[1]
shp = sys.argv[2]

# read shapefile
with fiona.open(str(shp), "r") as shapefile:
    shapes = [feature["geometry"] for feature in shapefile]

# read each imagery file
with rasterio.open(str(img)) as src:
    out_image, out_transform = rasterio.mask.mask(src, shapes, crop=True, filled=True, nodata=-1)
    out_meta = src.meta

# save clipped imagery
out_meta.update({"driver": "GTiff",
        "height": out_image.shape[1],
        "width": out_image.shape[2],
        "transform": out_transform})

with rasterio.open("./out_clipped.png", "w", **out_meta) as dest:
    dest.write(out_image)

USAGE - python clip.py [name_of_imagery_file_in_tif] [name_of_shapfile_in_shp]

Leave a Comment