QGIS Console Clip Raster – How to Call ‘Clip Raster by Mask Layer’ Tool Using QGIS Console

gdalpyqgisqgisqgis-3qgis-processing

I execute the followng code in QGIS 3.2.1 console, but Clip Raster by Mask Layer tool doesn't work – output file is not created.

Here is QGIS console output:

None # perhaps this None appears as a result of calling processing.run(...)
result = {'OUTPUT': 'W:\\MODIS\\tif_files\\MYD02QKM.A2018209.0820.006.2018209195116_tif_CLIPPED.tif'}

And here is the QGIS Log Messanges:

Prosessing tab:

2018-08-01T11:15:58     INFO    gdalwarp -ot Byte -of GTiff -tr 250.0 -250.0 -tap -cutline G:\!Download\!!MODIS\execute_files\cutter_ZERO.shp -crop_to_cutline -dstnodata 255.0 -co -of GTiff -co COMPRESS=LZW W:\MODIS\tif_files\MYD02QKM.A2018209.0820.006.2018209195116_tif.tif W:\MODIS\tif_files\MYD02QKM.A2018209.0820.006.2018209195116_tif_CLIPPED.tif
2018-08-01T11:15:58     INFO    GDAL command:
2018-08-01T11:15:58     INFO    gdalwarp -ot Byte -of GTiff -tr 250.0 -250.0 -tap -cutline G:\!Download\!!MODIS\execute_files\cutter_ZERO.shp -crop_to_cutline -dstnodata 255.0 -co -of GTiff -co COMPRESS=LZW W:\MODIS\tif_files\MYD02QKM.A2018209.0820.006.2018209195116_tif.tif W:\MODIS\tif_files\MYD02QKM.A2018209.0820.006.2018209195116_tif_CLIPPED.tif
2018-08-01T11:15:58     INFO    GDAL command output:
2018-08-01T11:15:58     INFO    ERROR 4: GTiff: No such file or directory

2018-08-01T11:15:58     INFO    GDAL execution console output
             ERROR 4: GTiff: No such file or directory

2018-08-01T11:15:58     INFO    Results: {'OUTPUT': 'W:\\MODIS\\tif_files\\MYD02QKM.A2018209.0820.006.2018209195116_tif_CLIPPED.tif'}

OGR tab:

2018-08-01T11:15:58     WARNING    Cannot open W:\MODIS\tif_files\MYD02QKM.A2018209.0820.006.2018209195116_tif.tif.()

Python warning tab:

2018-08-01T11:15:57     WARNING    warning:__console__:1: ResourceWarning:

             unclosed file 


             traceback: File "C:/OSGEO4~1/apps/qgis/./python\console\console.py", line 575, in runScriptEditor
              self.tabEditorWidget.currentWidget().newEditor.runScriptCode()
              File "C:/OSGEO4~1/apps/qgis/./python\console\console_editor.py", line 629, in runScriptCode
              .format(filename.replace("\\", "/"), sys.getfilesystemencoding()))
              File "C:/OSGEO4~1/apps/qgis/./python\console\console_sci.py", line 635, in runCommand
              more = self.runsource(src)
              File "C:/OSGEO4~1/apps/qgis/./python\console\console_sci.py", line 665, in runsource
              return super(ShellScintilla, self).runsource(source, filename, symbol)
              File "C:\OSGEO4~1\apps\Python36\lib\code.py", line 75, in runsource
              self.runcode(code)
              File "C:\OSGEO4~1\apps\Python36\lib\code.py", line 91, in runcode
              exec(code, self.locals)
              File "", line 1, in 

Calling the same tool from the QGIS interface with the same input files produces the expected results.

How to call 'gdal:cliprasterbymasklayer' using QGIS console?

Here is the code:

import os

def clip_raster_by_vector(input_raster, input_vector, output_raster, overwrite=False):
    if overwrite:
        if os.path.isfile(output_raster):
            os.remove(output_raster)

    if not os.path.isfile(input_raster):
        print ("File doesn't exists", input_raster)
        return None
    else:
        params = {'INPUT': input_raster,
                  'MASK': input_vector,
                  'NODATA': 255.0,
                  'ALPHA_BAND': False,
                  'CROP_TO_CUTLINE': True,
                  'KEEP_RESOLUTION': True,
                  'OPTIONS': '-of GTiff -co COMPRESS=LZW',
                  'DATA_TYPE': 0,  # Byte
                  'OUTPUT': output_raster,
                  }

        feedback = qgis.core.QgsProcessingFeedback()
        alg_name = 'gdal:cliprasterbymasklayer'
        print(processing.algorithmHelp(alg_name))
        result = processing.run(alg_name, params, feedback=feedback)
        return result


input_raster = r"W:\MODIS\tif_files\MYD02QKM.A2018209.0820.006.2018209195116_tif.tif"
output_raster = r"W:\MODIS\tif_files\MYD02QKM.A2018209.0820.006.2018209195116_tif_CLIPPED.tif"
input_vector = r"G:\!Download\!!MODIS\execute_files\cutter_ZERO.shp"
result = clip_raster_by_vector(input_raster, input_vector, output_raster, overwrite=True)
print('result =', result)

EDIT 1:

I have found a difference in calling gdalwarp with QGIS console and QGIS interface.

QGIS console

gdalwarp -ot Byte -of GTiff -tr 250.0 -250.0 -tap -cutline G:\!Download\!!MODIS\execute_files\cutter_ZERO.shp -crop_to_cutline -dstnodata 255.0 -co -of GTiff -co COMPRESS=LZW W:\MODIS\tif_files\MYD02QKM.A2018209.0820.006.2018209195116_tif.tif W:\MODIS\tif_files\MYD02QKM.A2018209.0820.006.2018209195116_tif_CLIPPED.tif

QGIS interface

gdalwarp -ot Byte -of GTiff -tr 250.0 -250.0 -tap -cutline path_to_data_file -crop_to_cutline -dstnodata 255.0 -co COMPRESS=LZW W:/MODIS/tif_files/MYD02QKM.A2018209.0820.006.2018209195116_tif.tif W:/MODIS/tif_files/MYD02QKM.A2018209.0820.006.2018209195116_tif_CLIPPED.tif

Best Answer

Problem were caused by incorrect options parameter. Changing that line:

'OPTIONS': '-of GTiff -co COMPRESS=LZW',

to

 'OPTIONS': 'COMPRESS=LZW',

solved the problem.