DEV Community

Gabriel Wu
Gabriel Wu

Posted on • Edited on

My GDAL CLI snippets

To crop a raster file according to a shapefile

gdalwarp -overwrite -s_srs EPSG:32649 -q -cutline shapefile.shp -of GTiff raw.tiff crop.tiff
Enter fullscreen mode Exit fullscreen mode

To merge several bands into a raster file

gdal_merge.py -o target.tiff -of GTiff -ps 10 10 -separate B1.tiff B2.tiff B3.tiff
Enter fullscreen mode Exit fullscreen mode

Here 10 10 means 10 meters in the x-axis and 10 meters in the y-axis. If -ps is not specified, the spatial resolution of the first raster file will be considered to be the target resolution.

To merge several files spatially

gdal_merge.py -o target.tiff -of GTiff TL.tiff BL.tiff TR.tiff BR.tiff
Enter fullscreen mode Exit fullscreen mode

To resample a raster file

gdal_translate -outsize 50 50 raw.jp2 target.jp2
Enter fullscreen mode Exit fullscreen mode

Here 50 50 means 50% in x-axis, and 50% in y-axis.


Appendix: Install GDAL for Python on Ubuntu

# Install gdal library
sudo apt-get install -y gdal-bin libgdal-dev
# gdal-bin is not necessary, but you will definitely need it to run the CLI commands above

# Export include path
export CPLUS_INCLUDE_PATH=/usr/include/gdal
export C_INCLUDE_PATH=/usr/include/gdal

# Install the exact version of Python package
gdal-config --version | xargs -0 -I {} pip install gdal=={}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)