How can I execute from the console an expression that should be used with the raster calculator?

I'm searching for something like this:

qgis.someRasterCalcClass.evaluate("boh@1 + boh@2", "outputfile.tif")

1 Answer 1


Starting from QGIS 2.0 (and current development version), the class QgsRasterCalculator is available in python. Unfortunately it is not very well documented.

The basic usage is, that you have to define an alias for each band used in the calculator expression in form of a QgsRasterCalculatorEntry

Your example can then be written as follows, given you have already assigned your rasterlayer to a variable bohLayer.

from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry

entries = []
# Define band1
boh1 = QgsRasterCalculatorEntry()
boh1.ref = 'boh@1'
boh1.raster = bohLayer
boh1.bandNumber = 1
entries.append( boh1 )

# Define band2
boh2 = QgsRasterCalculatorEntry()
boh2.ref = 'boh@2'
boh2.raster = bohLayer
boh2.bandNumber = 2
entries.append( boh2 )

# Process calculation with input extent and resolution
calc = QgsRasterCalculator( 'boh@1 + boh@2', '/home/user/outputfile.tif', 'GTiff', bohLayer.extent(), bohLayer.width(), bohLayer.height(), entries )

The return of processCalculation() will be

  • 0 in case of success
  • 1 in case the provider string (GTiff in the example) was wrong
  • 2 for other errors

The layer is not automatically added to the TOC, so either do this manually or with some python code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.