2

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()
1
  • 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. Nov 1, 2021 at 16:16

1 Answer 1

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.