如何将shoreline shapefile叠加到GeoTIFF文件生成二值匹配栅格层?
实现方案
前置准备
你可以直接使用rasterio内置的矢量栅格化接口实现需求,全程不需要手动处理坐标映射,接口会自动基于TIFF的空间参数完成坐标匹配。
具体实现代码
import geopandas as gpd import rasterio from rasterio import features import numpy as np # 读取GeoTIFF提取空间参数 with rasterio.open("你的安大略湖TIFF路径.tif") as src: tiff_crs = src.crs tiff_transform = src.transform tiff_width = src.width tiff_height = src.height # 若需要原TIFF数组可打开下行注释 # tiff_array = src.read(1) # 读取岸线矢量 shoreline = gpd.read_file("你的岸线Shapefile路径.shp") # 自动对齐坐标系,避免坐标错位 if shoreline.crs != tiff_crs: shoreline = shoreline.to_crs(tiff_crs) # 构造栅格化的要素序列,岸线位置赋值为1 shapes = ((geom, 1) for geom in shoreline.geometry) # 若需要加粗岸线显示,可将上行替换为(缓冲距离单位与坐标系单位一致): # shapes = ((geom.buffer(5), 1) for geom in shoreline.geometry) # 生成与原TIFF尺寸完全一致的二值栅格 shoreline_binary = features.rasterize( shapes=shapes, out_shape=(tiff_height, tiff_width), transform=tiff_transform, fill=0, # 非岸线区域赋值为0 dtype=np.uint8 )
可选:保存结果为GeoTIFF
# 复用原TIFF的元数据配置 out_meta = src.meta.copy() out_meta.update( dtype=rasterio.uint8, count=1, compress="lzw" # 开启压缩减少文件体积 ) # 写出二值岸线栅格 with rasterio.open("岸线二值栅格.tif", "w", **out_meta) as dst: dst.write(shoreline_binary, 1)
结果说明
得到的shoreline_binary就是符合要求的m×n单通道栅格,岸线匹配坐标位置值为1,其余位置值为0,尺寸与原TIFF单通道完全一致。
内容的提问来源于stack exchange,提问作者Chloe
相关产品推荐
相关产品推荐

