Sunday, 1 December 2019

loop - Looping through raster layers in folder with PyQGIS?



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?




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

    MASK
    NO_DATA
    ALPHA_BAND
    KEEP_RESOLUTION
    EXTRA
    OUTPUT


  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!


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...