1. 导包
import os
import numpy as np
import rasterio as rio
import geopandas as gpd
import PIL.Image as Image
from rasterio.mask import mask
2. 相关代码
rasterdata = rio.open('a.tif')
out_meta = rasterdata.meta.copy()
shpdata = gpd.read_file('grid.shp',encoding='utf-8')
shpdata = shpdata.to_crs(rasterdata.crs)
for j in range(0, len(shpdata)):
try:
geo = shpdata.geometry[j]
feature = [geo.__geo_interface__]
out_image, out_transform = mask(rasterdata, feature, all_touched=True, crop=True)
if out_image.shape[0]==3:
out_image=(np.transpose(out_image,(1,2,0))+1)/2.0*255.0
elif out_image.shape[0]==1:
out_image=(out_image[0]+1)/2.0*255.0
img_orig=Image.fromarray(np.uint8(out_image*255))
img_orig.save(f'clip_{j}.jpg')
except ValueError as value_err:
print(value_err)