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

求助:Python中提取Shapefile对应多边形的栅格像素值

问题修复方案

你的代码核心问题在于geometry_mask的参数设置错误,导致提取了多边形外部的像素,而非内部目标区域。以下是修复后的代码:

import geopandas as gpd
import rasterio
from rasterio.features import geometry_mask

polygons = gpd.read_file("poly_path.shp")
burn_attribute = "id"  # 确保多边形id唯一且不为0

with rasterio.open("raster_path.tif") as src:
    raster = src.read(1)
    transform = src.transform  # 提前获取transform,避免重复调用

pixel_values = []

for geom in polygons.geometry:
    # 生成多边形内部区域为True的掩膜
    mask = geometry_mask(
        [geom],
        out_shape=raster.shape,
        transform=transform,
        all_touched=True,
        invert=True  # 关键修改:反转掩膜,让多边形内部为True
    )
    # 提取掩膜覆盖的像素值
    polygon_values = raster[mask]
    pixel_values.append(polygon_values)

# 将提取的像素数组添加到GeoDataFrame
polygons['pixel_values'] = pixel_values

关键修改说明

  • 将invert=False改为invert=True:geometry_mask默认生成的掩膜中,多边形外部为True,内部为False,反转后才能正确选中多边形内部的像素。
  • 删除了无效的extracted_values = raster[polygons]行:GeoDataFrame无法直接作为NumPy数组的索引,这行代码无意义且会报错。
  • 优化了循环逻辑:直接遍历polygons.geometry,避免通过索引取值的冗余写法。

内容的提问来源于stack exchange,提问作者Naama

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:15:29