如何使用 rasterio/python 使用 shapefile 屏蔽栅格,将多边形内的栅格像素设置为零?

How do I use rasterio/python to mask a raster using a shapefile, to set the raster pixels inside the polygons to zero?

我正在尝试创建一个应用于卫星图像的土地遮罩,它将与土地质量相交的光栅中的像素设置为 0。

在尝试了 gdal、skimage、pyplot 等之后,我发现 rasterio cookbook 中给出的方法既快速又简单。但是,它将多边形 外部 的像素设置为 0,而我正在尝试执行相反的操作。

尽可能继续使用栅格 - 您不必计算地理空间坐标的像素位置或处理超出栅格变为负范围的裁剪功能。它也很快,这对我正在处理的原始图像的文件大小很重要。

从这里开始:https://mapbox.s3.amazonaws.com/playground/perrygeo/rasterio-docs/cookbook.html#masking-raster-with-a-polygon-feature

我的代码如下:

import fiona
import rasterio
from rasterio.tools.mask import mask

with fiona.open("/Users/Cate/UK_Mainland.shp", "r") as shapefile:
    geoms = [feature["geometry"] for feature in shapefile]

with rasterio.open("jan_clip.tif") as src:
    out_image, out_transform = mask(src, geoms, crop=True)
    out_meta = src.meta.copy()

out_meta.update({"driver": "GTiff",
                 "height": out_image.shape[1],
                 "width": out_image.shape[2],
                 "transform": out_transform})

with rasterio.open("masked2.tif", "w", **out_meta) as dest:
    dest.write(out_image)

如何屏蔽与多边形相交的区域而不是不相交的区域?

rasterio.tools.mask.mask(在较新的版本中,它是 rasterio.mask.mask)包含一个选项 invert。当 invert=True 时,遮罩将应用于与您的形状重叠的像素,而不是形状之外的区域。因此,您可以将上面的行更改为:

out_image, out_transform = mask(src, geoms, invert=True)