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:
- In your algorithm, you are using
rstr(the path of the rasters) as the input instead of the actual rasters which you have defined aslyr. This probably depends on the Processing plugin version but in v2.10.2, the algorithm
gdalogr:cliprasterbymasklayerrequires 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
OUTPUTLastly, you could use the following code to loop through rasters in a specified folder. I like to use the
globmodule to search for specific types of files alongside setting the current directory withos.chdirto 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