Files
BoucleduHainaut-ar/tools/extract_osm_buildings_pbf.py
mathieuandClaude Opus 5.5 3662fd4993 Boucle du Hainaut : application de réalité augmentée (v46)
PWA three.js + LocAR : pylônes et câbles de la ligne 380 kV sur le tracé
projeté, à l'échelle réelle, cachés par le relief (SPW 10 m), les obstacles
LiDAR (1/2/4 m) et les bâtiments OpenStreetMap. Photo avant/après, calage
de la vue, mini-carte, hors-ligne complet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 22:19:19 +01:00

54 lines
2.3 KiB
Python

#!/usr/bin/env python3
"""Extrait les bâtiments du couloir depuis un fichier OpenStreetMap .osm.pbf (ex. Geofabrik
belgium-latest.osm.pbf) — bien plus rapide que les requêtes Overpass de fetch_osm_buildings.py.
Écrit un JSON au format Overpass (`out geom tags`) lisible par build_building_tiles.py.
Usage : python3 tools/extract_osm_buildings_pbf.py belgium.osm.pbf www/data/trace.json corridor.json [buffer_m]
Nécessite pyosmium (pip install osmium). Données © contributeurs OpenStreetMap (ODbL).
"""
import json, math, os, sys
import osmium
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from fetch_osm_buildings import cells_for, DLAT, DLON # même couloir que la version Overpass
def main(pbf, trace_path, out, buf=3000):
line = json.load(open(trace_path))['line']
cells = set(cells_for(line, float(buf)))
print(f'{len(cells)} cellules', flush=True)
elements, n = [], 0
fp = (osmium.FileProcessor(pbf)
.with_filter(osmium.filter.KeyFilter('building'))
.with_areas()
.with_filter(osmium.filter.EntityFilter(osmium.osm.AREA)))
for a in fp:
n += 1
tags = dict(a.tags)
if tags.get('building') in (None, 'no'):
continue
rings = []
try:
for r in a.outer_rings():
rings.append([{'lat': p.lat, 'lon': p.lon} for p in r])
except osmium.InvalidLocationError:
continue
if not rings:
continue
p0 = rings[0][0]
if (math.floor(p0['lat'] / DLAT), math.floor(p0['lon'] / DLON)) not in cells:
continue
oid = a.orig_id()
if a.from_way():
elements.append({'type': 'way', 'id': oid, 'tags': tags, 'geometry': rings[0]})
else:
elements.append({'type': 'relation', 'id': oid, 'tags': tags,
'members': [{'type': 'way', 'role': 'outer', 'geometry': g} for g in rings]})
stamp = osmium.io.Reader(pbf, osmium.osm.osm_entity_bits.NOTHING).header().get('osmosis_replication_timestamp')
json.dump({'osm3s': {'timestamp_osm_base': stamp}, 'elements': elements}, open(out, 'w'))
print(f'{n} bâtiments lus, {len(elements)} dans le couloir → {out}', flush=True)
if __name__ == '__main__':
main(*sys.argv[1:])