Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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")
share|improve this question
    
Can you import from qgis.analysis import QgsRasterCalculator ? I cannot import this on QGIS 1.8 although it should already be available there... –  Matthias Kuhn Apr 26 '13 at 16:40
    
@MatthiasKuhn It works on 1.9 but not in 1.8. –  diegogb Apr 27 '13 at 13:28
add comment

1 Answer

up vote 6 down vote accepted

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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