from osgeo import gdal
import os
import shapefile
#要裁剪的原图
input_raster = r’raw.tif’
input_raster=gdal.Open(input_raster)
#shp文件所在的文件夹
path=r’D:/shp_file/’
#裁剪结果保存的文件夹
savepath=r’D:/result/’
#读取shp文件所在的文件夹
files= os.listdir(path)
for f in files: # 循环读取路径下的文件并筛选输出
if os.path.splitext(f)[1] == “.shp”:
name=os.path.splitext(f)[0]
input_shape=path+f
r = shapefile.Reader(input_shape)
output_raster=savepath+name+’.tif’
ds=gdal.Warp(output_raster,
input_raster,
format = ‘GTiff’,
outputBounds=r.bbox,
cutlineDSName = input_shape,
cutlineWhere=“FIELD = ‘whatever’”,
dstNodata = -1000)
ds=None