For looping folder to batch clip rasters by polygon using python and QGIS?
I'm agree with Nathan. You need to pythonize your whole script. So substitute your for
loop with something like the following:
import os, fnmatch
def findRasters (path, filter):
for root, dirs, files in os.walk(path):
for file in fnmatch.filter(files, filter):
yield file
for raster in findRasters(INPUT_FOLDER, '*.tif'):
inRaster = INPUT_FOLDER + '/' + raster
outRaster = OUTPUT_FOLDER + '/clip_' + raster
cmd = 'gdalwarp -q -cutline %s -crop_to_cutline %s %s' % (CLIP, inRaster, outRaster)
os.system(cmd)
Note 1: I'm supposing that your raster files are GeoTIFF (*.tif
).
Note 2: -of GTiff
is not needed in cmd
, because it's the default output format in gdalwarp
.
I finally managed with this very simple and clean script, which calls GDAL from Python without importing it (as suggested, but using "Call ()" method instead of "os.system ()". I hope this could help!
import os, fnmatch
from subprocess import call
call(["ls", "-l"])
inFolder= 'C:/Users/unimi/Documents/Umberto/Universita/PhD/Guglielmin/Permafrost/Alta_Valtellina/Landsat_ita/LE71930282000259EDC00/DNs2Reflectance_LE71930282000259EDC00/'
outFolder= 'C:/Users/unimi/Documents/Umberto/Universita/PhD/Guglielmin/Permafrost/Alta_Valtellina/Landsat_ita/Cloud_mask_AltaValtellina/clip_2_foscagno/'
os.chdir (inFolder)
def findRasters (path, filter):
for root, dirs, files in os.walk(path, filter):
for file in fnmatch.filter(files, filter):
yield os.path.join (root, file)
for raster in findRasters (inFolder, '*.tif'):
(infilepath, infilename)= os.path.split (raster)
print infilename
outRaster= outFolder+ 'clip_'+ infilename
print outRaster
warp= 'gdalwarp -dstnodata 0 -q -cutline %s -crop_to_cutline -of GTiff %s %s' % ('study_area_foscagno.shp', raster, outRaster)
call (warp)
Modified version of umbe1987`s solution for Linux users:
import os, fnmatch
from subprocess import call
call(["ls", "-l"])
inFolder= '/run/media/user/SOFT/LANDSAT/Bulk Order 595257/L8 OLI_TIRS/LC81840262015165LGN00/'
outFolder= '/run/media/user/SOFT/LANDSAT/Bulk Order 595257/summer_clipped/'
shp = '/run/media/user/SOFT/LANDSAT/Bulk Order 595257/vector/mask.shp'
os.chdir (inFolder)
def findRasters (path, filter):
for root, dirs, files in os.walk(path, filter):
for file in fnmatch.filter(files, filter):
yield os.path.join (root, file)
for raster in findRasters (inFolder, '*.TIF'):
(infilepath, infilename)= os.path.split (raster)
print infilename
outRaster= outFolder+ 'clip_'+ infilename
print outRaster
warp= 'gdalwarp -cutline \'%s\' -crop_to_cutline -dstalpha \'%s\' \'%s\'' % (shp, raster, outRaster)
os.system(warp)