Lis*_*hew 4 python raster gdal
我有一个很大的栅格文件,我想根据多边形或shapefile裁剪到6个numpy数组。我有shapefile,也有作为geopandas数据框的多边形。谁能帮我使用python(no 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
Run Code Online (Sandbox Code Playgroud)
假设您的shapefile被调用了,shapefile.shp并且您的栅格big_raster.tif可以这样使用:
gen = rasclip('big_raster.tif','shapefile.shp')
Run Code Online (Sandbox Code Playgroud)
# manually with next
clip = next(gen)
## some processing or inspection here
# clip with next feature
clip = next(gen)
Run Code Online (Sandbox Code Playgroud)
# or with iteration
for clip in gen:
## apply stuff to clip
pass # remove
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1906 次 |
| 最近记录: |