簡體   English   中英

將多邊形的shapefile轉換為numpy數組

[英]Convert a shapefile of polygons to numpy array

我有一個多邊形的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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM