python - 基于 shapefile 或多边形将栅格剪辑到 numpy 数组中

标签 python raster gdal

我有一个很大的光栅文件,我想根据多边形或 shapefile 将其剪裁成 6 个 numpy 数组。我有 shapefile 和多边形作为 geopandas 数据框。任何人都可以帮助我如何使用 python(没有 arcpy)来做到这一点

最佳答案

我已经创建了一个小型生成器,它应该可以满足您的需要。我选择了生成器而不是直接迭代特征,因为如果您想检查数组,它会更方便。如果需要,您仍然可以迭代生成器。

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

关于python - 基于 shapefile 或多边形将栅格剪辑到 numpy 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50035578/

相关文章:

python - 如何检测小部件的类型?

r - 试图识别 Landsat 图像中的断点 - 为什么 BFAST 会错过明显的断点?

r - 在没有色标的R中绘制栅格

r - 从 conda 安装 gdal 2.3 后,sf R 包 "is not compatible with GDAL versions below 2.0.0"

python - 调整不适合内存的大图像

c++ - 如何在 OpenCV 3.0 中使用 GDAL 打开 ECW 文件

python - 如果我不将文件分配给变量,文件会自动关闭吗?

python - 在 Python 中循环遍历文件对象时重新读取文件

python - Tensorflow 形状不匹配

r - 在 R 中将 2 个或更多栅格堆栈合并为 1 个栅格堆栈