Grow your YouTube channel like a PRO with a free tool
Get Free YouTube Subscribers, Views and Likes

Reproject resample and clip raster data with GDAL in Python

Follow
Making Sense Remotely

In this tutorial, I explain how to use gdalwarp in Python to reproject raster data to a different coordinate reference system, change the resolution (resample) and clip it to a shapefile.

GDAL/OGR Python API: https://gdal.org/python/

Code:

from osgeo import gdal
import numpy as np
import matplotlib.pyplot as plt

ds = gdal.Open("dem.tif")

reproject
dsReprj = gdal.Warp("demReprj.tif", ds, dstSRS = "EPSG:4326")
resample
dsRes = gdal.Warp("demRes.tif", ds, xRes = 150, yRes = 150,
resampleAlg = "bilinear")
clip
make sure your raster data and shapefile have the same projection!
dsClip = gdal.Warp("demClip.tif", ds, cutlineDSName = "star.shp",
cropToCutline = True, dstNodata = np.nan)

visualize
array = dsClip.GetRasterBand(1).ReadAsArray()
plt.figure()
plt.imshow(array)
plt.colorbar()
plt.show()

close your datasets!
ds = dsClip = dsRes = dsReprj = None

posted by Wirtbergys