I have made a function in Python Editor in QGIS, which (among others) performs a raster calculation.
I want to use my function to loop through multiple rasters. However, I run into a memory issue when doing so.
I have found the sinner to be the raster calculator, where the memory is not cleared after processing the raster calculation (calc.processCalculation()
). I have tried various solutions including; loading and removing the resulting layer with removeMapLayer
, saving the output to a file (instead of using the memory) and using del
combined with gc.collect()
. But the memory is still not cleared, which ultimately causes the memory to fill up when running the function several times.
Does anybody know how to free the memory after running the raster calculator in PyQGIS?
I have tested the code using QGIS 3.24.4, 3.28.2, and 3.22.12. The relevant part of my code looks like this, where Rasterfile1 and 2 are inputs to the function (full paths to raster files):
lyr1 = QgsRasterLayer(Rasterfile1)
lyr2 = QgsRasterLayer(Rasterfile2)
entries = []
ras = QgsRasterCalculatorEntry()
ras.ref = 'ras@1'
ras.raster = lyr1
ras.bandNumber = 1
entries.append(ras)
ras = QgsRasterCalculatorEntry()
ras.ref = 'ras@2'
ras.raster = lyr2
ras.bandNumber = 1
entries.append(ras)
calc = QgsRasterCalculator('if(ras@1 - ras@2>0,ras@1 - ras@2,0)', "memory", 'GTiff', lyr2.extent(), lyr2.width(), lyr2.height(), entries)
calc.processCalculation()
result=iface.addRasterLayer("memory",'resultingRaster')
del
?"memory"
does not actually use the RAM to store the image but will write a file to your working directory. Are you sure that this is not the issue of growing memory, e.g. if your directory is a ramdisk? b) Does memory usage grow if you never add the result to your project (noiface.addRasterLayer()
)?