I want to calculate sum values of many rasters (from input folder) in QGIS Python using raster calculator. When I run script, QGIS crashes:
Windows fatal exception: access violation
import osfrom qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntryfrom qgis.core import QgsRasterLayerwork_folder = 'C:/QGIS/input_rasters'rasters = [file for file in os.listdir(work_folder) if file.endswith('.nc')]entries = []i = 0for raster in rasters: i = i + 1 raster_path = os.path.join(work_folder, raster) input_raster = QgsRasterLayer(raster_path, raster) entry = QgsRasterCalculatorEntry() entry.ref = f"'ras@{i}'" entry.raster = input_raster entry.bandNumber = 1 entries.append(entry)expression = " +".join(entry.ref for entry in entries)output = 'C:/QGIS/output.tif'calc = QgsRasterCalculator(expression, output, 'GTiff', input_raster.extent(), input_raster.width(), input_raster.height(), entries)calc.processCalculation()
When I rewrite to two rasters, code works, but I need to do it for many rasters.
import osfrom qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntryfrom qgis.core import QgsRasterLayerwork_folder = 'C:/QGIS/input_rasters'rasters = [file for file in os.listdir(work_folder) if file.endswith('.nc')]entries = []raster_path = os.path.join(work_folder, 'test1.nc')input_raster = QgsRasterLayer(raster_path, raster)entry = QgsRasterCalculatorEntry()entry.ref = 'ras@1'entry.raster = input_rasterentry.bandNumber = 1entries.append(entry)raster2_path = os.path.join(work_folder, 'test2.nc')input2_raster = QgsRasterLayer(raster2_path, raster)entry = QgsRasterCalculatorEntry()entry.ref = 'ras@2'entry.raster = input2_rasterentry.bandNumber = 1entries.append(entry)output = 'C:/QGIS/output/output.tif'calc = QgsRasterCalculator('ras@1 + ras@2', output, 'GTiff', input_raster.extent(), input_raster.width(), input_raster.height(), entries)calc.processCalculation()