作为一名编码爱好者,我目前正在创建自己的“地理空间”工具,就像我希望它的工作方式一样。然而,一开始我已经面临一个问题。我的工具应该使用 GeoPandas 来提取信息,然后使用 OGR/GDAL 进行数据编辑,因为我希望它能够快速工作。我喜欢分析很多大数据!
带有问题的代码片段应该光栅化单个 GeoPandas 多边形。我尝试使用这条路径来做到这一点。- 使用 geopandas WKT-polygon 从多边形中提取 - 使用 WKT-polygon 创建 OGR 特征 - 使用 GDAL 将其栅格化。
我面临的问题是我只检索一个由 0 组成的栅格,而不是 0 和 1 ......
代码如下所示:
import geopandas as gpd
import ogr, osr
import gdal
import uuid
tf = r'f:test2.shp'
def vector_to_raster(source_layer, output_path, x_size, y_size, options, data_type=gdal.GDT_Byte):
'''
This method should create a raster object by burning the values of a source layer to values.
'''
x_min, x_max, y_min, y_max = source_layer.GetExtent()
print(source_layer.GetExtent())
x_resolution = int((x_max - x_min) / x_size)
y_resolution = int((y_max - y_min) / -y_size)
print(x_resolution, y_resolution)
target_ds = gdal.GetDriverByName(str('GTiff')).Create(output_path, x_resolution, y_resolution, 1, data_type)
spatial_reference = source_layer.GetSpatialRef()
target_ds.SetProjection(spatial_reference.ExportToWkt())
target_ds.SetGeoTransform((x_min, x_size, 0, y_max, 0, -y_size))
gdal.RasterizeLayer(target_ds, [1], source_layer, options=options)
target_ds.FlushCache()
return target_ds
#create geopandas dataframe
gdf = gpd.read_file(tf)
#grab projection from the gdf
projection = gdf.crs['init']
#get geometry from 1 polygon (now just the 1st one)
polygon = gdf.loc[0].geometry
#grab epsg from projection
epsg = int(projection.split(':')[1])
#create geometry
geom = ogr.CreateGeometryFromWkt(polygon.wkt)
#create spatial reference
proj = osr.SpatialReference()
proj.ImportFromEPSG(epsg)
#get driver
rast_ogr_ds = ogr.GetDriverByName('Memory').CreateDataSource('wrk')
#create polylayer with projection
rast_mem_lyr = rast_ogr_ds.CreateLayer('poly', srs=proj)
#create feature
feat = ogr.Feature(rast_mem_lyr.GetLayerDefn())
#set geometry in feature
feat.SetGeometryDirectly(geom)
#add feature to memory layer
rast_mem_lyr.CreateFeature(feat)
#create memory location
tif_output = '/vsimem/' + uuid.uuid4().hex + '.vrt'
#rasterize
lel = vector_to_raster(rast_mem_lyr, tif_output, 0.001, -0.001,['ATTRIBUTE=Shape__Len', 'COMPRESS=LZW', 'TILED=YES', 'NBITS=4'])
# output should consist of 0's and 1's
print(np.unique(lel.ReadAsArray()))
非常感谢能给我提示正确方向的人:-)。
干杯!