2016-02-16 43 views
3

我想使用python GDAL/OGR模块从OSM.PBF文件中提取数据。使用GDAL/OGR python模块解析osm.pbf数据

目前我的代码看起来是这样的:

import gdal, ogr 

osm = ogr.Open('file.osm.pbf') 

## Select multipolygon from the layer 
layer = osm.GetLayer(3) 
# Create list to store pubs 
pubs = [] 
for feat in layer: 
    if feat.GetField('amenity') == 'pub': 
     pubs.append(feat) 

虽然这个代码稍微正常工作与small.pbf文件(15MB)。然而,解析大于50MB的文件时,我收到以下错误:

ERROR 1: Too many features have accumulated in points layer. Use OGR_INTERLEAVED_READING=YES MODE 

当我把这个模式上:

gdal.SetConfigOption('OGR_INTERLEAVED_READING', 'YES') 

OGR根本不返回任何特征的全部了,解析即使小文件。

有人知道这里发生了什么吗?

+0

根据http://gdal.org/1.11/ogr/drv_osm.html交错也需要特殊的阅读模式。下面是这个特殊阅读模式的python示例:https://lists.osgeo.org/pipermail/gdal-dev/2014-April/038633.html 我从来没有使用GDAL/OGR,所以不知道细节。如果它可以随意发布更多有用的答案和示例代码。 – scai

回答

4

感谢scai的回答,我弄明白了。

在gdal.org/1.11/ogr/drv_osm.html中提到的交错阅读所需的特殊阅读模式被翻译成了一个可以在下面找到的工作python示例。

这是如何提取在.osm.pbf文件中有“市容=酒馆”标签

import gdal, ogr 

gdal.SetConfigOption('OGR_INTERLEAVED_READING', 'YES') 
osm = ogr.Open('file.osm.pbf') 

# Grab available layers in file 
nLayerCount = osm.GetLayerCount() 

thereIsDataInLayer = True 

pubs = [] 

while thereIsDataInLayer: 

    thereIsDataInLayer = False 

    # Cycle through available layers 
    for iLayer in xrange(nLayerCount): 

     lyr=osm.GetLayer(iLayer) 

     # Get first feature from layer 
     feat = lyr.GetNextFeature() 

     while (feat is not None): 

      thereIsDataInLayer = True 

      #Do something with feature, in this case store them in a list 
      if feat.GetField('amenity') == 'pub': 
       pubs.append(feat) 

      #The destroy method is necessary for interleaved reading 
      feat.Destroy() 

      feat = lyr.GetNextFeature() 

据我了解它的所有功能为例,需要一个while循环而不是一个for-loop,因为当使用交错读取方法时,不可能获得集合的特征计数。

更多关于这段代码为什么能起作用的原因将不胜感激。