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()
-
I recently answered a similar question in this link: gis.stackexchange.com/questions/475408/… . It works properly.xunilk– xunilk2024年06月24日 16:14:58 +00:00Commented Jun 24, 2024 at 16:14