PyQGIS – Looping Through Raster Layers in a Folder

looppyqgis

I'm looking to apply a mask to a number of rasters in PyQGIS.
(updated but still not working)

import processing
rstr = "/Users/rasterfilepath/"
shp = "/Users/shapefile.shp"
outputDir = "/Users/output/"

for lyr in rstr:
  processing.runandload("gdalogr:cliprasterbymasklayer", rstr, shp, "none", False, False, "", outputDir + lyr + ".tif")

What am I doing wrong?

Best Answer

There's a couple of things to notice:

  1. In your algorithm, you are using rstr (the path of the rasters) as the input instead of the actual rasters which you have defined as lyr.
  2. This probably depends on the Processing plugin version but in v2.10.2, the algorithm gdalogr:cliprasterbymasklayer requires 7 parameters (you mentioned 6). You can check this by using the Python console:

    import processing
    processing.alghelp("gdalogr:cliprasterbymasklayer")
    >>>ALGORITHM: Clip raster by mask layer
           INPUT <ParameterRaster>
           MASK <ParameterVector>
           NO_DATA <ParameterString>
           ALPHA_BAND <ParameterBoolean>
           KEEP_RESOLUTION <ParameterBoolean>
           EXTRA <ParameterString>
           OUTPUT <OutputRaster>
    
  3. Lastly, you could use the following code to loop through rasters in a specified folder. I like to use the glob module to search for specific types of files alongside setting the current directory with os.chdir to the path containing the files:

    import glob, os, processing
    rstr = "/Users/rasterfilepath//"
    shp = "/Users//shapefile.shp"
    outputDir = "/Users/output//"
    os.chdir(rstr)    # Sets the current directory to your rasterfilepath
    for lyr in glob.glob("*.tif"):
        processing.runandload("gdalogr:cliprasterbymasklayer", lyr, shp, 'none', False, False, '', outputDir + lyr)
    

Hope this helps!

Related Question