1

I am trying to use QgsRasterCalculator to do some calculations. However, my script does not output anything. It also doesn't show any error codes, it just executes without writing the desired output raster.

I have tried printing all the inputs to the calculator, and they seem to be the correct values. I've also included print statements in various parts of the script, including the end, to see if it fully runs, and it does.

lyr = r'C:\my_path\input_raster.tif'
output = r'C:\my_path\output_raster.tif'

lyr = QgsRasterLayer(lyr) exp = "%s * 2" % (lyr) ras = QgsRasterCalculatorEntry() ras.ref = 'test' ras.raster = lyr entries = [ras]

calc = QgsRasterCalculator(exp, output, 'GTiff', lyr.extent(), lyr.width(), lyr.height(), entries) calc.processCalculation()

Taras
  • 32,823
  • 4
  • 66
  • 137
Maarten
  • 197
  • 1
  • 9

2 Answers2

1

There are several suggestions regarding your code:

  • work with os.path package and its methods: basename, exists, join, and normpath

  • TIFF is a raster dataset containing one or more layers called bands. Therefore, in the expression, there should be specified a band. One can refer to a certain band via @-symbol i.e. @1. It is also possible to test the expression using the Raster Calculator

  • set a name when creating the QgsRasterLayer

     lyr = QgsRasterLayer(input_file, basename(input_file).split('.')[0])
    
  • use the f-string to format the expression:

     exp = f"{lyr.name()}@1 * 2"
    

So, in the end, the code may look like this:

from os.path import basename, exists, join, normpath

project_folder = normpath('D:\dop20rgbi_33412_5654_2_sn_tiff') input_file = join(project_folder, 'dop20rgbi_33412_5654_2_sn.tif') output_file = join(project_folder, 'output_raster.tif')

if exists(input_file): lyr = QgsRasterLayer(input_file, basename(input_file).split('.')[0])

rast = QgsRasterCalculatorEntry() rast.raster = lyr rast.ref = 'test'

entries = [rast]

exp = f"{lyr.name()}@1 * 2"

calc = QgsRasterCalculator(exp, output_file, 'GTiff', lyr.extent(), lyr.width(), lyr.height(), entries) calc.processCalculation()


References:

Taras
  • 32,823
  • 4
  • 66
  • 137
0

I've found the solution, based on Taras' comment. The issue was indeed in not assigning the band number. I fixed it by removing exp and ras.ref, and replacing it with

ras.ref = 'test@1'
exp = "%s*2" % (ras.ref)

Taras, if you change your comment into an answer I can mark it as answered.

Maarten
  • 197
  • 1
  • 9