根据shp图对遥感影像进行裁剪,shp图有多个面的话将每个面裁剪出来并根据属性命名
数据准备
假设我们有一张多光谱影像和一个shp图,shp是一些取样点或者小区的面信息
这个shp中的属性表信息如下:
这里面其实只需要name信息即可
具体代码
# coding=utf-8
"""
Author: Shuaijie
Blog: https://blog.csdn.net/weixin_45452300
公众号:AgbioIT
date: 2023/12/8 16:30
desc: 根据画的shp图把每个shp的影像裁剪出小图
"""
import geopandas as gpd
import rasterio
from rasterio.mask import mask
# 读取Shapefile文件
shp_file = 'path/to/image.tif'
shape_data = gpd.read_file(shp_file)
# 读取多光谱影像
image_file = 'path/to/shapefile.shp'
image_data = rasterio.open(image_file)
# 获取影像的元数据
meta = image_data.meta.copy()
# 遍历每个区域
for index, region in shape_data.iterrows():
# 获取区域的几何对象
geometry = region['geometry']
if geometry == None:
continue
name = region['name']
# 使用几何对象创建遮罩
mask_shape = geometry.__geo_interface__
masked_image, masked_transform = mask(image_data, [mask_shape], crop=True)
# 更新元数据的影像尺寸
# meta.update({'height': masked_image.shape[1],
# 'width': masked_image.shape[2]})
# 更新元数据的影像尺寸及投影坐标信息
meta.update({
'transform': masked_transform,
'crs': image_data.crs, 'height': masked_image.shape[1],
'width': masked_image.shape[2]})
# 创建输出影像文件
output_file = 'path/to/imageflod/%s.tif'%name
with rasterio.open(output_file, 'w', **meta) as dst:
dst.write(masked_image)
# 关闭影像文件
image_data.close()