如何用Python将Shapefile转换为匹配参考参数的栅格掩码图层?
用Python将Shapefile转为匹配参考栅格的掩码图层
可以用rasterio(处理栅格)和geopandas(处理矢量)实现需求,具体步骤和代码如下:
1. 安装依赖库
如果未安装相关库,先执行以下命令:
pip install rasterio geopandas numpy
2. 完整代码实现
import rasterio from rasterio.features import rasterize import geopandas as gpd import numpy as np # 读取参考栅格,提取匹配所需的元数据 ref_raster_path = "你的参考掩码路径.tif" with rasterio.open(ref_raster_path) as ref_src: ref_meta = ref_src.meta.copy() ref_transform = ref_src.transform ref_width, ref_height = ref_src.width, ref_src.height ref_crs = ref_src.crs # 读取Shapefile并对齐坐标系 shapefile_path = "你的Shapefile路径.shp" gdf = gpd.read_file(shapefile_path) if gdf.crs != ref_crs: gdf = gdf.to_crs(ref_crs) # 创建初始值为0的空栅格数组 mask_array = np.zeros((ref_height, ref_width), dtype=np.uint8) # 将矢量要素栅格化,覆盖区域设为1 shapes = [(geom, 1) for geom in gdf.geometry] mask_array = rasterize( shapes=shapes, out_shape=(ref_height, ref_width), transform=ref_transform, fill=0, dtype=np.uint8 ) # 写入结果栅格文件 output_raster_path = "输出掩码路径.tif" ref_meta.update({"dtype": "uint8", "count": 1}) with rasterio.open(output_raster_path, "w", **ref_meta) as dst: dst.write(mask_array, 1)
关键逻辑说明
- 元数据复用:直接读取参考栅格的
transform、crs、尺寸等参数,确保新栅格与参考栅格的范围、分辨率、坐标系完全一致。 - 坐标系对齐:通过
geopandas的to_crs方法将Shapefile转换为参考栅格的坐标系,避免矢量与栅格错位。 - 栅格化规则:
rasterize函数会逐个判断栅格单元格是否被矢量要素覆盖,覆盖则赋值为1,未覆盖保持初始值0。 - 数据类型优化:使用
uint8类型存储0/1值,最大化节省存储空间。
内容的提问来源于stack exchange,提问作者mn5hk
相关产品推荐
相关产品推荐

