Sunday 9 April 2017

qgis 3 - Adding layer from cliprasterbymask using PyQGIS


In my plugin I would like to use the gdal tool "cliprasterbymask" and add the new clipped raster to my project.


According to the Documentation the output has the type "raster". So it returns a raster object.


Thus, I have tried the following:



 clip = processing.run('gdal:cliprasterbymasklayer',{'INPUT': wasserstand,'MASK': gebeude,
'NODATA': -1, 'ALPHA_BAND': False, 'CROP_TO_CUTLINE': True, 'KEEP_RESOLUTION': True,
'OPTIONS': "", 'DATA_TYPE': 5, 'OUTPUT': outFile})

self.iface.addRasterLayer(clip)

Unfortunately, I get the following error message which I don't know what it means.



TypeError: QgisInterface.addRasterLayer(): arguments did not match any overloaded call: overload 1: argument 1 has unexpected type 'dict' overload 2: argument 1 has unexpected type 'dict'




How do I get the outputraster from cliprasterbymasklayer and what is actually output?


Apparently, its not just a simple raster layer.



Answer



The result of processing.run is always a Python dictionnary. From QGIS documentation (end of the paragraph):



The run method returns a dictionary with one or more output names (the ones shown in the algorithm description) as keys and the file paths of those outputs as values



For most processing algorithm, it contains only an 'OUTPUT' key.


When you call


clip = processing.run('gdal:cliprasterbymasklayer', {

'INPUT':my_layer,
'MASK': my_mask_layer,
'OUTPUT':'C:/Temp/my_output.tif'})

You get a dictionnary:


>>> clip
{'OUTPUT': 'C:/Temp/my_output.tif'}

So you in your case, you can either call


self.iface.addRasterLayer(clip['OUTPUT'])


or


self.iface.addRasterLayer(outFile)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...