gpt4 book ai didi

python - 将多边形的 shapefile 转换为 numpy 数组

转载 作者:太空宇宙 更新时间:2023-11-03 15:44:14 25 4
gpt4 key购买 nike

我有一个多边形的 shapefile 及其几何形状、一列时间和一列值。数据如下所示:

  | TIME | AVG | geometry
---- ----+-----+--------------------------------
0 | NaN | NaN | POLYGON((-0.1599375 51.3977, ...

Nan 值表示这个特定的多边形没有值。我想将其转换为 3D numpy 数组(根据时间),其中每个单元格都将标有网格的值。我试过这个,但到处都是 0。

source_ds = ogr.Open("C:/Users/Nathan/Desktop/pl.shp")
source_layer = source_ds.GetLayer()
pixelWidth = pixelHeight = 0.001
x_min, x_max, y_min, y_max = source_layer.GetExtent()
cols = int((x_max - x_min) / pixelHeight)
rows = int((y_max - y_min) / pixelWidth)
target_ds = gdal.GetDriverByName('GTiff').Create('temp.tif', cols, rows, 1, gdal.GDT_Byte)
target_ds.SetGeoTransform((x_min, pixelWidth, 0, y_min, 0, pixelHeight))
band = target_ds.GetRasterBand(1)
NoData_value = 0
band.SetNoDataValue(NoData_value)
band.FlushCache()
gdal.RasterizeLayer(target_ds, [1], source_layer, options = ["ATTRIBUTE=VALUE"])
target_dsSRS = osr.SpatialReference()
target_dsSRS.ImportFromEPSG(4326)
target_ds.SetProjection(target_dsSRS.ExportToWkt())
k=gdal.Open('temp.tif').ReadAsArray()

知道怎么做吗?谢谢

最佳答案

我终于明白了。

source_ds = ogr.Open("C:/Users/Nathan/Desktop/pl.shp")
source_layer = source_ds.GetLayer()
pixelWidth = pixelHeight = 0.001
x_min, x_max, y_min, y_max = source_layer.GetExtent()
cols = int((x_max - x_min) / pixelHeight)
rows = int((y_max - y_min) / pixelWidth)
target_ds = gdal.GetDriverByName('GTiff').Create('temp.tif', cols, rows, 1, gdal.GDT_Byte)
target_ds.SetGeoTransform((x_min, pixelWidth, 0, y_min, 0, pixelHeight))
band = target_ds.GetRasterBand(1)
NoData_value = 0
band.SetNoDataValue(NoData_value)
band.FlushCache()
gdal.RasterizeLayer(target_ds, [1], source_layer, options = ["ATTRIBUTE=AVG"])
target_ds = None #this is the line that makes the difference
gdal.Open('temp.tif').ReadAsArray()

关于python - 将多边形的 shapefile 转换为 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51009185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com