For instance, I have created a simple graphical modeler which gives NDVI as an output when the NIR band and Red Band are provided:

Graphical Model

I exported the Python script using 'Export as script algorithm' in the graphical modeler and the script is attached below:

Model exported as python.
Name : model
Group : 
With QGIS : 32203

from qgis.core import QgsProcessing
from qgis.core import QgsProcessingAlgorithm
from qgis.core import QgsProcessingMultiStepFeedback
from qgis.core import QgsProcessingParameterRasterLayer
from qgis.core import QgsProcessingParameterRasterDestination
from qgis.core import QgsCoordinateReferenceSystem
import processing

class Model(QgsProcessingAlgorithm):

    def initAlgorithm(self, config=None):
        self.addParameter(QgsProcessingParameterRasterLayer('nirband', 'NIR Band', defaultValue=None))
        self.addParameter(QgsProcessingParameterRasterLayer('redband', 'Red Band', defaultValue=None))
        self.addParameter(QgsProcessingParameterRasterDestination('Ndvi', 'ndvi', createByDefault=True, defaultValue=None))

    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(1, model_feedback)
        results = {}
        outputs = {}

        # NDVI Calculation
        alg_params = {
            'CELLSIZE': 0,
            'CRS': QgsCoordinateReferenceSystem('EPSG:3857'),
            'EXPRESSION': '("NIR Band@1"  - "Red Band@1" )  /  ( "NIR Band@1" + "Red Band@1" ) ',
            'EXTENT': parameters['nirband'],
            'LAYERS': parameters['nirband'],
            'OUTPUT': parameters['Ndvi']
        outputs['NdviCalculation'] = processing.run('qgis:rastercalculator', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        results['Ndvi'] = outputs['NdviCalculation']['OUTPUT']
        return results

    def name(self):
        return 'model'

    def displayName(self):
        return 'model'

    def group(self):
        return ''

    def groupId(self):
        return ''

    def createInstance(self):
        return Model()

I saved this file as ndvi.py. Now I would like to run this Python file in terminal (not in QGIS python console). I created a new virtual environment and installed all the necessary packages.

Now I am not sure how can I use ndvi.py or simply how can I use the class or function above to obtain the output. Could anyone tell me about this?


Your Answer

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

Browse other questions tagged or ask your own question.