python - 基于 shapefile 或多边形将栅格裁剪为 numpy 数组
问题描述
我有一个大光栅文件,我想根据多边形或 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
推荐阅读
- windows - Charles Proxy 突然停止检测本地主机
- python - aiohttp:未关闭的客户端会话 client_session
- c++ - 链接 Emscripten 编译的 Box2D 时未定义的符号
- php - PHP/XAMPP 使用 DirectoryIterator 类不显示图像
- azure-stream-analytics - Azure 流分析 - 从当前开始 x 分钟后首先
- javascript - 无法解构“未定义”或“空”的属性“obj1”
- jquery - 带有jquery ui可拖动的无限可拖动元素
- javascript - 带有特定灯光三个js的灯光网格
- python - Django ORM:使用 F、MAX 和 GROUP BY 的组合
- python - 将对象分配给 django 中的特定用户?