将一个多边形的shapefile转换为numpy数组

3

我有一个面状文件,包含几何形状、时间和数值三个字段。数据如下:

  | 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()

有任何想法如何做到这一点吗?谢谢。
1个回答

3
最终,我弄明白了。
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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接