[GIS] Using QgsRasterCalculator

pyqgisqgisraster-calculator

I'm trying to make a sum of n rasters and create a new one using QgsRasterClaculator. The problem is, every time the code reaches processCalculation, it makes QGIS close and create a dump file. I don't know if I'm doing it wrong, but I'd like to ask you for some help in how I can do it.

That's how I'm trying to do:

entries = []
rasters = os.listdir("C://test/Rasters/")
for i in range(0, len(rasters)):
        raster = "C://test/Rasters/"+rasters[i]

        resp = QgsRasterLayer(raster)
        rast1 = QgsRasterCalculatorEntry()
        rast1.raster = resp
        rast1.ref = "rast"+str(i+1)
        print(rast1.ref)
        rast1.bandNumber = 1
        entries.append(rast1)

        if(i == len(rasters)-1):
            var = var + 'rast'+str(i+1)  
        else:
            var = var + 'rast'+str(i+1)+' + '

calc = QgsRasterCalculator( var, 'C://test/Rasters/raster_somado.tif', 'GTiff', resp.extent(), resp.width(), resp.height(), entries )
print(calc.processCalculation())

I think the error might be happening because I'm using a variable (var), that contains the rasters alias. The base code I found and that works is

calc = QgsRasterCalculator( 'rast1 + rast2', 'C://test/Rasters/raster_somado.tif', 'GTiff', resp.extent(), resp.width(), resp.height(), entries )
print(calc.processCalculation())

Can anybody help me? I already tried some things but it's still not working, QGIS keeps creating the dump and closes.

Best Answer

thanks for the answers. The problem was that I had to set both 'resp' and 'rast1' variables to None after each iteration in the for loop, so my code end up like this

entries = []
rasters = os.listdir("C://test/Rasters/")
for i in range(0, len(rasters)):
    raster = "C://test/Rasters/"+rasters[i]

    resp = QgsRasterLayer(raster)
    rast1 = QgsRasterCalculatorEntry()
    rast1.raster = resp
    rast1.ref = "rast"+str(i+1)
    print(rast1.ref)
    rast1.bandNumber = 1
    entries.append(rast1)
    rast1 = None
    resp = None

    if(i == len(rasters)-1):
        var = var + 'rast'+str(i+1)  
    else:
        var = var + 'rast'+str(i+1)+' + '

calc = QgsRasterCalculator( var, 'C://test/Rasters/raster_somado.tif', 'GTiff', resp.extent(), resp.width(), resp.height(), entries )
print(calc.processCalculation())

And it worked

Related Question