2

I want to sum 4 raster layers by QgsRasterCalculator. Below code creates a raster layer as result, but pixel values in raster result is wrong. what is the error in this code?

from qgis.core import *
from PyQt4.QtCore import *
from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry

entries = []
rst1 = "home/Data/lyr1.tif"
rst2 = "home/Data/lyr2.tif"
rst3 = "home/Data/lyr3.tif"
rst4 = "home/Data/lyr4.tif"
myList = [rst1, rst2, rst3, rst4]

try:
    for i in range(0, len(myList)):
         raster = myList[i]
         readRst = processing.getObject(raster)
         ras1 = QgsRasterCalculatorEntry()
         ras1.raster = readRst
         ras1.ref = "ext_lyr@" + str(i+1)
         ras1.bandNumber = 1
         entries.append(ras1)

    formula = '(' + entries[0].ref + ' + ' + entries[1].ref + ' + ' + entries[2].ref + ' + ' + entries[3].ref + ')'
    readRst = QgsRasterLayer(myList[0])
    output = "home/Data/result.tif"
    calc = QgsRasterCalculator(formula, output, 'GTiff', readRst.extent(), readRst.width(), readRst.height(), entries)
    calc.processCalculation()

except:
    self.userWarning("Error in Create map", "Can not create Create map, Exit")
3

I found solution. This line is wrong:

ras1.ref = "ext_lyr@" + str(i+1)

It must be:

ras1.ref = "ext_lyr" + str(i+1) +"@1"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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