基于shapefile或多边形将栅格剪辑为numpy数组

时间:2018-04-26 05:41:06

标签: python raster gdal

我有一个很大的光栅文件,我想基于多边形或shapefile剪辑到6个numpy数组。我有shapefile和多边形作为geopandas数据帧。谁能帮助我如何使用python(没有arcpy)

来帮助我

1 个答案:

答案 0 :(得分:5)

我创造了一个小型发电机,可以满足您的需求。我选择了生成器,而不是直接迭代这些功能,因为如果您想检查数组,它会更方便。如果需要,您仍然可以迭代生成器。

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