GDAL raster calculator

28.04.2011 17:30 ·  GIS  ·  gdal

Having a raster calculator in QGIS is cool, but if you need to process a lot of rasters, it won’t be much help. There is no batch mode in the calculator (neither in the my plugin nor in the QGIS core). Well, there is an entry about it in my TODO. But knowing that won’t help if you have hundreds of images for which you need to calculate, e.g., NDVI, or perform pixel replacement by a tricky condition.

This is where GDAL and Python come to the rescue. It literally takes 10 minutes to write a script, as there is nice and detailed documentation. But again, writing almost identical scripts for every task is not very practical.

Let me tell you a little secret. GDAL 1.8.0 has a wonderful tool, modestly named gdal_calc.py. This small (about 300 lines) Python script works with rasters of the same size (no check for mismatching CRS is performed) and supports basic arithmetic and logical operations. It is easy to use:

# sum of two rasters
gdal_calc.py -A input1.tif -B input2.tif --outfile=result.tif --calc="A+B"
# average of two rasters
gdal_calc.py -A input1.tif -B input2.tif --outfile=result.tif --calc="(A+B)/2"
# difference of raster bands
gdal_calc.py -A input.tif --A_band=1 -B input.tif --B_band=2 --outfile=result.tif --calc="A-B"

It accepts up to 26 images as input, which should be sufficient for most use cases. As you can see from the examples, there is support for parentheses, you can access individual bands, and the console nature makes it easy to use the script for batch processing. It still lacks some features, but even in its current state, it is a great console calculator.

⮜ Prev
Next ⮞