Python批量裁剪影像
接着前前前面,批量将hdf文件转换为TIFF格式后,问题又来了。。
该影像为全球的影像,而我只需要裁剪我研究区的影像,那么就需要用一个快速的方法来裁剪影像(手动裁剪影像,那是必不可能的!!!)
咋们看代码:
import os
import glob
import rasterio
from rasterio.mask import mask
import geopandas as gpd
def clip_raster_by_shp(input_raster, input_shp, output_raster):
with rasterio.open(input_raster) as src:
gdf = gpd.read_file(input_shp)
clipped, out_transform = mask(src, gdf.geometry, crop=True)
out_meta = src.meta.copy()
out_meta.update({
"driver": "GTiff",
"height": clipped.shape[1],
"width": clipped.shape[2],
"transform": out_transform
with rasterio.open(output_raster, "w", **out_meta) as dest:
dest.write(clipped)
input_folder = "输入路径"
output_folder = "输出路径"
input_shp = "SHP路径"
os.makedirs(output_folder, exist_ok=True)
# Get a list of TIFF files in the input folder
input_rasters = glob.glob(input_folder + "*.tif")