【问题标题】:How to create a filtered graph from an OSM-formatted XML file using OSMnx?如何使用 OSMnx 从 OSM 格式的 XML 文件创建过滤图?
【发布时间】:2020-08-21 02:26:22
【问题描述】:

在 Python 中,我们可以使用函数 osmnx.graph_from_place() 和过滤器 custom_filter='["waterway"="river"]' 来获得过滤后的图。

import osmnx as ox
G = ox.graph_from_place("isle of man", custom_filter='["waterway"="river"]') # download directly.
fig, ax = ox.plot_graph(G, node_color='r')

我想从我的磁盘上的 OSM 格式的 XML 文件中获取过滤图,但函数 osmnx.graph_from_xml() 不支持参数 custom_filter。如何从 *.osm 数据中获取过滤后的图?

这只会绘制整个 *.osm 数据集:

import osmnx as ox
G = ox.graph_from_xml("isle-of-man-latest.osm") # from disk.
fig, ax = ox.plot_graph(G, node_color='r')

【问题讨论】:

    标签: python openstreetmap osmnx


    【解决方案1】:

    OSMnx 的custom_filter 参数允许您使用 OverpassQL 过滤 Overpass 查询,以生成过滤后的原始数据以用于图形构建。如果您正在加载 .osm 文件,那么您将明确绕过 Overpass 查询步骤,而是直接导入本地原始数据文件以进行图形构建。 OSMnx 会根据您提供的任何原始数据构建图表。

    您有几个选择。首先,如果可能,您可以直接使用 OSMnx 的 graph_from_placegraph_from_polygon 函数来获取图形,而不是从 .osm 文件中加载。其次,如果你需要使用graph_from_xml,并且想对其进行过滤,你可以在构建之后进行过滤:

    import osmnx as ox
    ox.config(use_cache=True, log_console=True)
    
    # create a graph with more edges than you want
    G = ox.graph_from_place('Piedmont, CA, USA', network_type='drive', simplify=False)
    
    # filter graph to retain only certain edge types
    filtr = ['tertiary', 'tertiary_link', 'secondary', 'unclassified']
    e = [(u, v, k) for u, v, k, d in G.edges(keys=True, data=True) if d['highway'] not in filtr]
    G.remove_edges_from(e)
    
    # remove any now-disconnected nodes or subcomponents, then simplify toplogy
    G = ox.utils_graph.get_largest_component(G)
    G = ox.simplify_graph(G)
    

    【讨论】:

    • 这两个选项适用于小区域,大区域如何?我尝试将graph_from_xml 与从Geofabrik 下载的柏林区域(.osm.bz2,约90 MB)一起使用。在我的机器上创建一个非简化图需要相当长的时间。
    • 大图可能很慢。如果没有完整的最小可重现示例和代码时序,很难说更多。听起来像是一个单独的问题,所以我建议打开一个新问题。
    • 这会导致KeyError: 'highway',所以首先检查密钥是否存在,utils_graph 曾经是geo_utils,我正在使用osmnx==0.11.4,以防万一有人遇到我遇到的同样问题
    • v0.11.4 已经很老了。如果您遇到错误,我建议您升级到现代版本。
    猜你喜欢
    • 2020-06-16
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 2014-04-25
    • 1970-01-01
    • 2018-07-29
    相关资源
    最近更新 更多