1

I have done raster processing in Step 1. Next, I want to do the second processing using the output raster from step 1. How do I load the output raster from step 1 and use it in Step 2?

My Code is as below:

   #STEP 1
   calc = processing.run("gdal:rastercalculator",
        {'INPUT_A':parameters[self.INPUT_RASTER],
         'BAND_A':1,
         'FORMULA': f'(A > {parameters[self.THRESHOLD]})',
         'OUTPUT':'memory:'
        },
        context=context, feedback=feedback, is_child_algorithm=True)
        index = calc['OUTPUT']
    
    #STEP 2 
    zonalhistogram = processing.run("native:zonalhistogram", 
        {'INPUT_RASTER':index,
         'RASTER_BAND':1,
         'INPUT_VECTOR':newcircle,
         'COLUMN_PREFIX':'HISTO_',
         'OUTPUT':'memory:'
        },context=context, feedback=feedback, is_child_algorithm=True)
         
    zonal_histo = zonalhistogram['OUTPUT']

It prompts this error:

GDAL command output:
ERROR 4: Attempt to create new tiff file `memory:' failed: No error
'NoneType' object has no attribute 'SetGeoTransform'
Process returned error code 1
Results: {'OUTPUT': 'memory:'}
Results: {'OUTPUT': 'output_64f8f0e4_c78f_4291_982d_5e19900c3325'}
Results: {'OUTPUT': 'output_dfc91a09_2b54_429d_9dd6_1af3a6fe1de8'}
Results: {'OUTPUT': 'output_ba93c7be_e7cc_4a6b_8ce3_62d154a50e02'}
Results: {'OUTPUT': 'output_28a99eb2_cb9c_4ef3_86c1_7b97057f13f7'}
Unable to execute algorithm
Could not load source layer for INPUT_RASTER: memory: not found
Unable to execute algorithm
Could not load source layer for INPUT_RASTER: memory: not found
Execution failed after 0.70 seconds
1
  • Please always provide error messages as formatted text rather than pictures.
    – PolyGeo
    Sep 13, 2022 at 8:22

1 Answer 1

1

Your problem is 'OUTPUT':'memory:'. To create a memory layer for the output of an intermediate processing step you should use either QgsProcessing.TEMPORARY_OUTPUT or just 'TEMPORARY_OUTPUT'. Both of these will work because the attribute QgsProcessing.TEMPORARY_OUTPUT just returns QStringLiteral("TEMPORARY_OUTPUT") as per docs.

You can have a look at this script for a complete example based on your previous question. You can also see here how to use multi-step feedback in a parent algorithm which implements multiple calls to child algorithms and save outputs into a results dictionary which is returned at the end of the ProcessAlgorithm() method.

from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
               QgsProcessingAlgorithm,
               QgsProcessingParameterFeatureSource,
               QgsProcessingParameterFeatureSink,
               QgsProcessingParameterRasterLayer,
               QgsProcessingParameterNumber,
               QgsRasterLayer,
               QgsProcessingMultiStepFeedback)
from qgis import processing

class ExampleProcessingAlgorithm(QgsProcessingAlgorithm):

    INPUT = 'INPUT'
    THRESHOLD = 'THRESHOLD'
    ZONES = 'ZONES'
    OUTPUT = 'OUTPUT'
    
    def __init__(self):
        super().__init__()
 
    def name(self):
        return "exalgo"
     
    def tr(self, text):
        return QCoreApplication.translate("exalgo", text)
         
    def displayName(self):
        return self.tr("Example script")
 
    def group(self):
        return self.tr("Examples")
 
    def groupId(self):
        return "examples"
 
    def shortHelpString(self):
        return self.tr("Example script with raster calc")
 
    def helpUrl(self):
        return "https://qgis.org"
         
    def createInstance(self):
        return type(self)()

    def initAlgorithm(self, config=None):

        self.addParameter(
            QgsProcessingParameterRasterLayer(
                self.INPUT,
                self.tr('NDVI Layer'),
                [QgsProcessing.TypeRaster]
            )
        )

        self.addParameter(
            QgsProcessingParameterNumber(
            self.THRESHOLD,
            self.tr('Minimum Index'),
            QgsProcessingParameterNumber.Double
            )
        )
        
        self.addParameter(
            QgsProcessingParameterFeatureSource(
                self.ZONES,
                self.tr('Vector Layer Containing Zones'),
                [QgsProcessing.TypeVectorPolygon]
            )
        )

        self.addParameter(
            QgsProcessingParameterFeatureSink(
                self.OUTPUT,
                self.tr('Output layer')
            )
        )

    def processAlgorithm(self, parameters, context, model_feedback):
        outputs = {}
        results = {}
        
        steps = 2 # Number of child algorithms
        feedback = QgsProcessingMultiStepFeedback(steps, model_feedback)
        step = 1
        
        # Set current step and increment step counter for each child alg
        feedback.setCurrentStep(step)
        step+=1
        
        outputs['calc'] = processing.run('gdal:rastercalculator',
            {'INPUT_A':parameters[self.INPUT],
            'BAND_A':1,
            'FORMULA': f'(A > {parameters[self.THRESHOLD]})',
            'OUTPUT':'TEMPORARY_OUTPUT'
            },
            context=context, feedback=feedback, is_child_algorithm=True)
        
        results['calc'] = outputs['calc']['OUTPUT']

        feedback.setCurrentStep(step)
        step+=1
        
        #STEP 2 
        outputs['zonalhisto'] = processing.run("native:zonalhistogram", 
            {'INPUT_RASTER':results['calc'],
             'RASTER_BAND':1,
             'INPUT_VECTOR':parameters[self.ZONES],
             'COLUMN_PREFIX':'HISTO_',
             'OUTPUT':parameters[self.OUTPUT]
            },context=context, feedback=feedback, is_child_algorithm=True)
         
        results['zonalhisto'] = outputs['zonalhisto']['OUTPUT']

        return results
2
  • Thank you so much! It solved my problem. May you live long and prosper :)
    – Siti
    Sep 14, 2022 at 1:16
  • "Your problem is 'OUTPUT':'memory:'" only a problem because this is a raster, right? Jan 29, 2023 at 18:21

Your Answer

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

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