3

I have different raster in the same folder and I want to sum all of them and generate a new raster. I'm trying todo a script on Python, but it doesn't work or run the process but it doesn't generate an output.

Which is the most easy way to write an expression to sum different raster?

I have different examples of the scripts, but I can't find the right way to write the expression just to sum them. Finally, my problem is how to write the expression to sum rasters in the same folder and generate a new one.

EX 1.
import qgis
from qgis.analysis import QgsRasterCalculatorEntry, QgsRasterCalculator
# Get layer object
layer = processing.getObject(lyr)
lddLrs = qgis.utils.iface.legendInterface().layers()
for lyr in lddLrs:
 entries = [] 
 ras = QgsRasterCalculatorEntry()
 ras.ref = 'lyr@1'
 ras.raster = lyr
 ras.bandNumber = 1
 entries.append( ras ) 
 calc = QgsRasterCalculator( '("lyr@1" / "lyr@1") * "lyr@1"', +lyr.name() + "_suffix.tif", 'GTiff', lyr.extent(), lyr.width(), lyr.height(), entries )
 calc.processCalculation()
EX 2.
import os
import fnmatch
import os
import shutil
#import lib.config as config
import processing
from osgeo import gdal 
#from PyQt4.QtCore import QFileInfo
from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry
inputFolder = "C:/++ELABORAZIONI_NUOVE/entrevistas/+++HEATMAP/hm_ben"
outputfilename = '/calculos_raster/hotspot_ben.tif'
outputFolder="C:/++ELABORAZIONI_NUOVE/entrevistas/+++HEATMAP/calculos_raster"
def findRasters(path, filter):
 for root, dirs, files in os.walk(path, filter):
 for file in fnmatch.filter(files, filter):
 yield os.path.join(root, file)
entries = []
layers = []
for l in findRasters(inputFolder, '*.tif'):
 print (l)
 fileInfo = QFileInfo(l)
 baseName = fileInfo.baseName()
 rlayer = QgsRasterLayer(l,baseName)
 #QgsMapLayerRegistry.instance().addMapLayer(rlayer) 
 layer = QgsRasterCalculatorEntry()
 layer.ref = rlayer.name() + '@1'
 layer.raster = rlayer
 layers.append(rlayer)
 layer.bandNumber = 1
 print (layer)
 entries.append(layer) 
 reflist = " + ".join([ent.ref for ent in entries]) 
 expression = '(' + reflist + ')'
 outuput = outputFolder
 print (expression)
calc = QgsRasterCalculator(expression,outputfilename,
 'GTiff',
 layers[0].extent(),
 layers[0].width(),
 layers[0].height(),
 entries)
calc.processCalculation()
PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Feb 11, 2020 at 8:53
1

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.