2

I want to clip a raster (GeoTIFF) using a polygon shapefile. Both are in the same reference system. The polygon is not a regular polygon but has many vertices.

I used this Python script below in QGIS 2.18.4

    import processing
    processing.runandload("gdalogr:cliprasterbymasklayer", \
    "/home/giacomo/Desktop/RSM/bordi.tif", \
    "/home/giacomo/Desktop/RSM/mask_vec.shp", \
    "none", \
    False, \
    True, \
    True, \
    "", \
    "", \
    0, \
    0, \
    0, \
    False, \
    "", \
    False, \
    "", \
    "/home/giacomo/Desktop/RSM/bordi_clip.tif")

But I get Error: Wrong parameter value:

The parameters required as input are

    INPUT <ParameterRaster>
    MASK <ParameterVector>
    NO_DATA <ParameterString>
    ALPHA_BAND <ParameterBoolean>
    CROP_TO_CUTLINE <ParameterBoolean>
    KEEP_RESOLUTION <ParameterBoolean>
    RTYPE <ParameterSelection>
    COMPRESS <ParameterSelection>
    JPEGCOMPRESSION <ParameterNumber>
    ZLEVEL <ParameterNumber>
    PREDICTOR <ParameterNumber>
    TILED <ParameterBoolean>
    BIGTIFF <ParameterSelection>
    TFW <ParameterBoolean>
    EXTRA <ParameterString>
    OUTPUT <OutputRaster>
4

There are several errors in your code.

Firstly, you need to specify your input layers as objects (and not as strings):

raster_filepath = "C:/Users/path_to_the_raster/bordi.tif"
mask_filepath = "C:/Users/path_to_the_shapefile/mask_vec.shp"

raster_layer = QgsRasterLayer(raster_filepath, 'raster')
mask_layer = QgsVectorLayer(mask_filepath, 'mask', 'ogr')

Then, you didn't specify the RTYPE parameter:

RTYPE(Output raster type)
    0 - Byte
    1 - Int16
    2 - UInt16
    3 - UInt32
    4 - Int32
    5 - Float32
    6 - Float64

You can't set "" as value (as you did), but a number is required.

The same with the COMPRESS parameter:

COMPRESS(GeoTIFF options. Compression type:)
    0 - NONE
    1 - JPEG
    2 - LZW
    3 - PACKBITS
    4 - DEFLATE

You can't set "" as value (as you did), but a number is required.

Therefore, you set 0 as value for JPEGCOMPRESSION, ZLEVEL and PREDICTOR parameters. They can't be equal to 0 so, if you don't know what they mean, leave the default values (i.e. 75, 6 and 1, respectively).

Then, you didn't specify the BIGTIFF parameter:

BIGTIFF(Control whether the created file is a BigTIFF or a classic TIFF)
    0 - 
    1 - YES
    2 - NO
    3 - IF_NEEDED
    4 - IF_SAFER

Finally, you can't set "" as value, but a number is required.

A working solution for you should be this:

import processing
from qgis.core import *

raster_filepath = "C:/Users/path_to_the_raster/bordi.tif"
mask_filepath = "C:/Users/path_to_the_shapefile/mask_vec.shp"

raster_layer = QgsRasterLayer(raster_filepath, 'raster')
mask_layer = QgsVectorLayer(mask_filepath, 'mask', 'ogr')

processing.runandload("gdalogr:cliprasterbymasklayer", \
raster_layer, \
mask_layer, \
"none", \
False, \
True, \
True, \
5, \
4, \
75, \
6, \
1, \
False, \
0, \
False, \
"", \
"C:/Users/path_to_the_result/output.tif")
  • I was using the QgsRasterLayer in the wrong way. Mgri's solution works. Thank you – ilFonta Mar 24 '17 at 11:07
  • @ilFonta You're welcome. I'm glad you found it helpful! =) – mgri Mar 24 '17 at 11:17
2

If you use backslash (\) in your code it won't work. On the other hand, you need to put as "False" both 'CROP_TO_CUTLINE' and 'KEEP_RESOLUTION' if you want to preserve alignment with original raster. In my case, with these layers loaded at Map View of QGIS:

enter image description here

next code:

import processing

mask = processing.getObjectFromName('polygon2')
input = processing.getObjectFromName('utah_demUTM2')

path = processing.runandload('gdalogr:cliprasterbymasklayer', 
                             input,    #INPUT <ParameterRaster>
                             mask,     #MASK <ParameterVector>
                             "-9999",  #NO_DATA <ParameterString>
                             False,    #ALPHA_BAND <ParameterBoolean>
                             False,    #CROP_TO_CUTLINE <ParameterBoolean>
                             False,    #KEEP_RESOLUTION <ParameterBoolean>
                             5,        #RTYPE <ParameterSelection>
                             4,        #COMPRESS <ParameterSelection>
                             1,        #JPEGCOMPRESSION <ParameterNumber>
                             6,        #ZLEVEL <ParameterNumber>
                             1,        #PREDICTOR <ParameterNumber>
                             False,    #TILED <ParameterBoolean>
                             0,        #BIGTIFF <ParameterSelection>
                             False,    #TFW <ParameterBoolean>
                             "",       #EXTRA <ParameterString>
                             None)     #OUTPUT <OutputRaster>

produces a mask perfectly aligned with base raster; as you can corroborate with Value Tool plugin of QGIS (see next image):

enter image description here

'None' option as output raster produces a temporary layer loaded from /tmp directory. To preserve this resulting layer it's necessary to save it (or you can use your initial path: "/home/giacomo/Desktop/RSM/bordi_clip.tif").

  • Hi, I tried several combination of parameters, but always get Error: Wrong parameter value: None. import processing mask = processing.getObjectFromName('mask_vec.shp') input = processing.getObjectFromName('bordi.tif') path = processing.runandload('gdalogr:cliprasterbymasklayer', input, mask, None, False, False, False, 0, 0, 0, 0, 0, False, 0, False, "", None) – ilFonta Mar 23 '17 at 19:32
  • @ilFonta you are setting 0 values when it's not possible doing it. Please, see the explanation in my answer and let me know if it works for you. – mgri Mar 23 '17 at 20:25
  • @ilFonta Load your raster and your mask in QGIS. Copy/paste my code as another script. Change 'polygon2' and 'utah_demUTM2' for your respective names. Run it. It should work. – xunilk Mar 23 '17 at 20:31
1

I want to add an updated solution for QGIS 3 as some things have changed. I referenced various other StackOverflow threads and the QGIS Documentation page to make it work.

First, I'd like to mention this command that was hugely helpful to me. From the console you can run:

processing.algorithmHelp('gdal:cliprasterbymasklayer')

This prints out step-by-step instructions for the parameters, what values are accepted, etc. I used this to populate my parameter values.

Here is a code example:

import processing
from qgis.core import *

raster_layer = QgsRasterLayer('path to your input raster', 'raster')
mask_layer = QgsVectorLayer('path to your vector mask layer', 'mask', 'ogr')

parameters = {'INPUT': raster_layer,
            'MASK': mask_layer,
            'NODATA': -9999,
            'ALPHA_BAND': False,
            'CROP_TO_CUTLINE': True,
            'KEEP_RESOLUTION': True,
            'OPTIONS': None,
            'DATA_TYPE': 0,
            'OUTPUT': 'path to where you want to save'}

processing.runAndLoadResults('gdal:cliprasterbymasklayer', parameters)

A nice way to build your parameters list is to make a dictionary with them before feeding them into the GDAL tool.

Also, notice the processing.runandload method from QGIS 2 has now become processing.runAndLoadResults in QGIS 3.

  • 1
    Thank you Erich, I think it's time to move QGIS3 as well – ilFonta Feb 14 at 9:06

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.