2

I am trying to use the qgis:rastercalculator algorithm inside a processing script and not able to find the correct syntax for specifying layer/band inputs. Below is a simple script to reproduce the problem. I am simply taking the input raster layer and returning it as output.

The same works fine with gdal:rastercalculator but fails with an unhelpful error:

An error occurred while performing the calculation.

from qgis.core import (QgsProcessing,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterRasterLayer,
                       QgsProcessingParameterRasterDestination)
from qgis import processing


class RasterCalcProcessingAlgorithm(QgsProcessingAlgorithm):
    INPUT = 'INPUT'
    OUTPUT = 'OUTPUT'
   
    def createInstance(self):
        return RasterCalcProcessingAlgorithm()

    def name(self):
        return 'rastercalctest'

    def displayName(self):
        return 'rastercalctest'

    def initAlgorithm(self, config=None):
        self.addParameter(
            QgsProcessingParameterRasterLayer(
                self.INPUT, 'INPUT', defaultValue=None
                
            )
        )

        self.addParameter(
            QgsProcessingParameterRasterDestination(
                  self.OUTPUT, 'OUTPUT'
            )
        )

    def processAlgorithm(self, parameters, context, feedback):
        input = self.parameterAsString(parameters, self.INPUT, context)
        output = self.parameterAsFileOutput(parameters, self.OUTPUT, context)
        params = {
            'CELLSIZE': 0,
            'CRS': None,
            'EXPRESSION': '\"{}@1\"'.format(input),
            'EXTENT': None,
            'LAYERS': [input],
            'OUTPUT':  parameters['OUTPUT'],
        }
        result = processing.run('qgis:rastercalculator', params, context=context)
        return {self.OUTPUT: result['OUTPUT']}
3

You need to adjust your script so that it reads the INPUT parameter as a raster layer, instead of as a string. Accordingly, you'll need to call the name() method to access the layer name.

Inside processAlgorithm() method, replace:

input = self.parameterAsString(parameters, self.INPUT, context)

by:

input = self.parameterAsRasterLayer(parameters, self.INPUT, context)

Additionally, replace:

'EXPRESSION': '\"{}@1\"'.format(input),

by:

'EXPRESSION': '\"{}@1\"'.format(input.name()),

Rationale:

When you read the (layer) parameter as a string, you get the layer id (e.g., my_raster_0bf496de_d00c_48bb_bd9b_157a3d1b9164), but what you need for your expression is the layer name (e.g., my_raster).

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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