在Python中, 用shp文件边界裁剪tif文件
from osgeo import gdal
import os
gdal.PushErrorHandler("CPLQuietErrorHandler")
def subset_by_shp(shape_fn, raster_fn, raster_out):
"""
根据 shapefile 对栅格文件进行裁剪并输出结果
:param shape_fn: shapefile 文件路径
:param raster_fn: 栅格数据文件路径
:param raster_out: 输出结果文件路径
"""
if not os.path.exists(shape_fn):
print(f"Shapefile 文件不存在: {shape_fn}")
return
if not os.path.exists(raster_fn):
print(f"栅格文件不存在: {raster_fn}")
return
try:
result = gdal.Warp(
raster_out,
raster_fn,
format='GTiff',
cutlineDSName=shape_fn,
cropToCutline=True
)
if result is None:
raise RuntimeError(gdal.GetLastErrorMsg())
else:
print(f'裁剪完成: {raster_out}')
except Exception as e:
print(f"裁剪失败: {e}")
finally:
result = None
if __name__ == "__main__":
# 待裁剪的栅格文件路径
raster = r'C:\Users\xxx\Desktop\todo-tif\k.tif'
# shapefile 文件路径
shp = r'C:\Users\xxx\Desktop\shp\1000.shp'
# 输出裁剪后的栅格文件路径
raster_out = r'C:\Users\xxx\Desktop\ok-tif\k.tif'
subset_by_shp(shp, raster, raster_out)