shpfile文件mask切割tif文件

shpfile文件mask切割tif文件

    • 1. 导包
    • 2. 相关代码

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') # 读取需切割的tif文件
out_meta = rasterdata.meta.copy()
shpdata = gpd.read_file('grid.shp',encoding='utf-8') # 读取shp文件掩码mask
shpdata = shpdata.to_crs(rasterdata.crs) # 获取tif投影编码,确保编码一致 
for j in range(0, len(shpdata)):
    try:
        geo = shpdata.geometry[j] # 读取几何数据
        feature = [geo.__geo_interface__] # 获取mask地理坐标数据范围
        out_image, out_transform = mask(rasterdata, feature, all_touched=True, crop=True) # 切割相应范围数据
        # tif文件转为jpg
        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)

你可能感兴趣的:(其他,tif,shpfile,mask掩码切割,tif文件转jpg)