【问题标题】:How do I use rasterio/python to mask a raster using a shapefile, to set the raster pixels inside the polygons to zero?如何使用 rasterio/python 使用 shapefile 屏蔽栅格,将多边形内的栅格像素设置为零?
【发布时间】:2017-05-18 16:41:43
【问题描述】:

我正在尝试创建一个陆地蒙版以应用于卫星图像,它将与陆地相交的栅格中的像素设置为 0。

在尝试了 gdal、skimage、pyplot 等之后,我发现 rasterio 食谱中给出的方法既快速又简单。但是,它将多边形 外部 的像素设置为 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)

如何掩盖与多边形相交的区域而不是不相交的区域?

【问题讨论】:

    标签: python mask raster clip rasterio


    【解决方案1】:

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

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

    【讨论】:

    • 裁剪和反转不能同时为真
    • @lorenzori 谢谢,没错,我已经更新以移除作物。
    猜你喜欢
    • 2022-07-01
    • 2021-08-15
    • 2019-12-06
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多