1

I'm working on a plugin for QGIS3, and trying to clip a raster layer using a vector mask layer. I've been able to successfully do this using "Clip raster by mask layer" through the processing toolbox, but when I use the following code in PyQGIS, it does not generate any output. I tried saving the output to 'memory:', to 'TEMPORARY_OUTPUT' and to a specific path in the disk, however, same result for all. Any tips?

from qgis.core import *
import processing

#load layers
project = QgsProject.instance()
mask = project.mapLayersByName('vector')[0]
input = project.mapLayersByName('raster')[0]

parameters = {
    'ALPHA_BAND': False,
    'CROP_TO_CUTLINE': True,
    'DATA_TYPE': 0,
    'INPUT': input,
    'KEEP_RESOLUTION': True,
    'MASK': mask,
    'MULTITHREADING': False,
    'OUTPUT': 'memory:',
    'SOURCE_CRS': dem.crs(),
    'TARGET_CRS': dem.crs(),
    'NO_DATA': -9999
}

clip_output = processing.run("gdal:cliprasterbymasklayer", parameters)

result = QgsRasterLayer(clip_output['OUTPUT'], "clipped", 'gdal')

project.addMapLayer(result)

1 Answer 1

2

You have to include 'OUTPUT' : 'TEMPORARY_OUTPUT' in parameters.

parameters = {
    'ALPHA_BAND': False,
    'CROP_TO_CUTLINE': True,
    'DATA_TYPE': 0,
    'INPUT': input,
    'KEEP_RESOLUTION': True,
    'MASK': mask,
    'MULTITHREADING': False,
    'OUTPUT': 'memory:',
    'SOURCE_CRS': mask.crs(),
    'TARGET_CRS': mask.crs(),
    'NO_DATA': -9999,
    'OUTPUT' : 'TEMPORARY_OUTPUT',
}

After that, it worked for me with my own example; as it can be observed in following image.

enter image description here

2
  • You are right, it only works with 'TEMPORARY OUTPUT' as the algorithm output. However, I had already tried and it didn't work. Consequently, your answer forced me to check why it was working in your example and not in mine. I found the problem, the extent of the vector was larger than the raster's extensions. I seems than gdal simply returns nothing when it happens, without a warning. So, thank you! Commented Jul 25, 2021 at 19:30
  • In addition, in your example, the 'OUTPUT' key in parameters is duplicated. It's better not have duplicated keys in a dictionary since it can lead to unexpected behaviour. The script works if you only left the 'OUTPUT' as 'TEMPORARY_OUTPUT' as you said. Commented Jul 25, 2021 at 19:35

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.