You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 09:05:23