Friday, 9 March 2018

qgis - How to evaluate raster calculator expressions from the console?


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")

Answer



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 )
calc.processCalculation()

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.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...