You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中提取大型osm.pbf文件的指定区域?

解决大OSM文件内存错误并提取目标区域数据

当处理超过3GB的OSM文件时,直接加载全量数据会触发内存错误,核心解决方案是仅加载目标坐标及周边区域的子集数据,以下是两种实用实现方法:

方法一:用pyrosm直接加载指定边界框数据

pyrosm支持初始化时指定边界框,仅加载框内数据,无需提前裁剪文件,步骤如下:

  1. 计算目标区域的边界框
    假设你有一组经纬度坐标列表coords = [(lon1, lat1), (lon2, lat2), ...],先计算这些坐标的外接矩形,再扩展一定范围(示例中扩展0.01度,约1公里,可按需调整):
# 替换为你的实际坐标列表
coords = [(116.397, 39.908), (116.405, 39.912)]
# 计算基础外接矩形并扩展
min_lon = min(c[0] for c in coords) - 0.01
max_lon = max(c[0] for c in coords) + 0.01
min_lat = min(c[1] for c in coords) - 0.01
max_lat = max(c[1] for c in coords) + 0.01
# 组装边界框(格式:min_lon, min_lat, max_lon, max_lat)
bbox = (min_lon, min_lat, max_lon, max_lat)
  1. 加载边界框内的驾驶网络
from pyrosm import OSM

path = r"\*.osm.pbf"
# 仅加载指定边界框内的数据
osm = OSM(path, bounding_box=bbox)
# 提取驾驶网络
drive_net = osm.get_network(network_type="driving")
# 可视化验证
drive_net.plot()

方法二:用osmium先裁剪OSM文件(适合超大型文件)

osmium是流式处理OSM数据的高效库,内存占用极低,适合处理GB级文件,先裁剪出目标区域的小文件,再用pyrosm处理:

  1. 安装osmium
pip install osmium
  1. 裁剪OSM文件
import osmium as o

# 替换为你的边界框参数和文件路径
min_lon, min_lat, max_lon, max_lat = 116.387, 39.898, 116.415, 39.922
input_path = r"\*.osm.pbf"
output_path = "cropped_driving_area.osm.pbf"

# 定义裁剪处理器,仅保留边界框内及关联的元素
class BBoxCropper(o.SimpleHandler):
    def __init__(self, writer, bbox):
        super().__init__()
        self.writer = writer
        self.bbox = bbox

    def node(self, n):
        if self.bbox.contains(n.location):
            self.writer.add_node(n)

    def way(self, w):
        # 保留至少有一个节点在边界框内的道路
        if any(self.bbox.contains(n.location) for n in w.nodes):
            self.writer.add_way(w)

    def relation(self, r):
        # 保留关联的关系(如道路组)
        self.writer.add_relation(r)

# 初始化边界框和写入器
bbox_geom = o.Box(min_lon, min_lat, max_lon, max_lat)
writer = o.Writer(output_path, overwrite=True)

# 执行裁剪
handler = BBoxCropper(writer, bbox_geom)
handler.apply_file(input_path, locations=True)
writer.close()
  1. 加载裁剪后的文件提取驾驶网络
from pyrosm import OSM

osm = OSM(output_path)
drive_net = osm.get_network(network_type="driving")
drive_net.plot()

注意事项

  • 边界框的扩展幅度可根据实际需求调整,比如需要更大的周边区域可增大扩展值(如0.05度)。
  • 提取后的drive_net是GeoDataFrame,可直接用于后续路径规划(如转换为networkx图进行最短路径计算)。

内容的提问来源于stack exchange,提问作者anon.for

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 13:01:23