【问题标题】:Clip raster into numpy arrays based on shapefile or polygons基于 shapefile 或多边形将栅格裁剪为 numpy 数组
【发布时间】:2018-04-26 05:41:06
【问题描述】:

我有一个大的栅格文件,我想根据多边形或 shapefile 将其剪辑为 6 个 numpy 数组。我有 shapefile 和多边形作为 geopandas 数据框。任何人都可以帮我如何使用python(没有arcpy)

【问题讨论】:

  • 你看到py-gdal cookbook了吗?
  • 是的。我的 shapefile 中有 6 个不同的多边形,我想将我的栅格拆分为 6 个不同的 numpy 数组,每个数组对应于 shapefile 中的一个多边形。我该怎么走?
  • 假设你的多边形是独立的特征,你可以iterate over features然后依次使用每个特征裁剪文件。
  • 谢谢。多边形是独立的特征。我不知道如何迭代特征来剪辑大光栅文件。您能否详细说明如何剪辑?

标签: python raster gdal


【解决方案1】:

我创建了一个小生成器,它应该可以满足您的需求。我选择了生成器而不是直接迭代功能,因为如果您想检查数组,它会更方便。如果你愿意,你仍然可以迭代生成器。

import gdal
import ogr, osr

# converts coordinates to index

def bbox2ix(bbox,gt):
    xo = int(round((bbox[0] - gt[0])/gt[1]))
    yo = int(round((gt[3] - bbox[3])/gt[1]))
    xd = int(round((bbox[1] - bbox[0])/gt[1]))
    yd = int(round((bbox[3] - bbox[2])/gt[1]))
    return(xo,yo,xd,yd)

def rasclip(ras,shp):
    ds = gdal.Open(ras)
    gt = ds.GetGeoTransform()

    driver = ogr.GetDriverByName("ESRI Shapefile")
    dataSource = driver.Open(shp, 0)
    layer = dataSource.GetLayer()

    for feature in layer:

        xo,yo,xd,yd = bbox2ix(feature.GetGeometryRef().GetEnvelope(),gt)
        arr = ds.ReadAsArray(xo,yo,xd,yd)
        yield arr

    layer.ResetReading()
    ds = None
    dataSource = None

假设你的 shapefile 被称为 shapefile.shp 和你的光栅 big_raster.tif 你可以像这样使用它:

gen = rasclip('big_raster.tif','shapefile.shp')

# manually with next

clip = next(gen)

## some processing or inspection here

# clip with next feature

clip = next(gen)

# or with iteration

for clip in gen:

    ## apply stuff to clip
    pass # remove

【讨论】:

  • 很高兴它有帮助。如果它回答了您的问题,请考虑接受该解决方案。
  • 我做到了。再次感谢。最后一件事。创建单个数组时是否可以排除无数据像素?
  • 如何排除? arr = ds.ReadAsArray(xo,yo,xd,yd) 行将读取要素和栅格相交的数组。您可以在yield 之前对arr 添加任何修改
  • 如何获取图像中所有像素值的坐标。 gis.stackexchange.com/questions/260304/…我正在使用链接作为参考
  • 这是一个矩形多边形的shapefile,如果它们不规则呢?
猜你喜欢
  • 1970-01-01
  • 2018-09-15
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
  • 2014-05-29
  • 1970-01-01
  • 1970-01-01
  • 2022-09-24
相关资源
最近更新 更多