I am a QGIS beginner and I want to combine two layers using the raster calculator via Python. For the beginning, I simply want to add the two layers but currently, I don't get an output file.
Code is the following:
lyr1 = QgsRasterLayer(r'C:\layer1.tif')
lyr2 = QgsRasterLayer(r'C:\layer2.tif')
output = r'C:\output.tif'
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('ras@1 + ras@2', output, 'GTiff', \
lyr1.extent(), lyr1.width(), lyr1.height(), entries)
calc.processCalculation()
-
Check the dimensions of the two rasters is the same. This catches me out all the time! If the dimensions are different you'll need to clip the rasters to the same extent or resample them to the same resolution.murrayjanemary– murrayjanemary2021年11月01日 16:16:31 +00:00Commented Nov 1, 2021 at 16:16
1 Answer 1
For visualizing an output file in QGIS Map Canvas, you need additional bottom lines in following code for retrieving new computed layer.
lyr1 = QgsRasterLayer(r'C:\layer1.tif')
lyr2 = QgsRasterLayer(r'C:\layer2.tif')
output = r'C:\output.tif'
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('ras@1 + ras@2', output, 'GTiff', \
lyr1.extent(), lyr1.width(), lyr1.height(), entries)
calc.processCalculation()
layer_sum = QgsRasterLayer(output,
'output')
QgsProject.instance().addMapLayer(layer_sum)
answered Nov 1, 2021 at 15:40
lang-py