Datasets:
File size: 8,109 Bytes
532fb5c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | #!/usr/bin/env python3
"""
citygml_to_cityjson.py — Convert Lyon CityGML (LOD2) to CityJSON v1.1
Handles lod2MultiSurface and lod2Solid geometries.
Maps EPSG:3946 CRS. Creates stable building IDs.
"""
import json, os, sys, math, numpy as np
from lxml import etree
NSMAP = {
'gml': 'http://www.opengis.net/gml',
'bldg': 'http://www.opengis.net/citygml/building/2.0',
}
def _tag(elem):
return etree.QName(elem).localname
def _find_recursive(elem, local_name):
for child in elem.iter():
if _tag(child) == local_name:
return child
return None
def _parse_poslist(text):
parts = text.strip().split()
return [float(p) for p in parts]
def _parse_polygon_patches(geom_elem):
"""Parse lod2MultiSurface → list of surfaces (each a list of [x,y,z] vertices)."""
surfaces = []
for polygon_elem in geom_elem.iter():
if _tag(polygon_elem) == 'Polygon':
exterior = _find_recursive(polygon_elem, 'exterior')
if exterior is None:
continue
ring = _find_recursive(exterior, 'LinearRing')
if ring is None:
continue
poslist = _find_recursive(ring, 'posList')
if poslist is None:
continue
coords = _parse_poslist(poslist.text)
verts = [[coords[i], coords[i+1], coords[i+2]] for i in range(0, len(coords)-2, 3)]
if verts:
surfaces.append(verts)
return surfaces
def _parse_solid(geom_elem):
"""Parse lod2Solid → list of surfaces."""
surfaces = []
for shell_elem in geom_elem.iter():
if _tag(shell_elem) in ('exterior', 'Shell'):
for polygon_elem in shell_elem.iter():
if _tag(polygon_elem) == 'Polygon':
exterior = _find_recursive(polygon_elem, 'exterior')
if exterior is None:
continue
ring = _find_recursive(exterior, 'LinearRing')
if ring is None:
continue
poslist = _find_recursive(ring, 'posList')
if poslist is None:
continue
coords = _parse_poslist(poslist.text)
verts = [[coords[i], coords[i+1], coords[i+2]] for i in range(0, len(coords)-2, 3)]
if verts:
surfaces.append(verts)
return surfaces
def _deduplicate_vertices(buildings):
"""Build global vertex array, remap surfaces to indices."""
vert_to_idx = {}
vertices_list = []
for bid, bdata in buildings.items():
new_surfaces = []
for surface in bdata.get('surfaces', []):
new_surf = []
for v in surface:
key = (round(v[0], 6), round(v[1], 6), round(v[2], 6))
if key not in vert_to_idx:
vert_to_idx[key] = len(vertices_list)
vertices_list.append(v)
new_surf.append(vert_to_idx[key])
new_surfaces.append([new_surf])
bdata['boundaries'] = new_surfaces
del bdata['surfaces']
return vertices_list, buildings
def _get_bbox(buildings):
"""Compute global bounding box from building surfaces."""
all_verts = []
for b in buildings.values():
for surf_list in b.get('boundaries', []):
for surf in surf_list:
for vidx in surf:
pass # We'll compute from vertices directly later
return None
def convert_gml_to_cityjson(gml_path, year, arrondissement):
"""Convert one CityGML file to CityJSON dict."""
print(f" Parsing {os.path.basename(gml_path)}...")
buildings = {}
crs_uri = None
current_building = None
context = etree.iterparse(gml_path, events=('start', 'end'), huge_tree=True)
for event, elem in context:
tag = _tag(elem)
if event == 'start':
if tag == 'Building':
gml_id = elem.get('{http://www.opengis.net/gml}id', f'unknown_{len(buildings)}')
current_building = {'id': gml_id, 'surfaces': []}
if tag in ('boundedBy', 'Envelope') and crs_uri is None:
srs = elem.get('srsName', '')
if srs:
crs_uri = srs
if event == 'end':
if tag in ('lod2MultiSurface', 'lod2Solid') and current_building is not None:
surfaces = _parse_polygon_patches(elem) if tag == 'lod2MultiSurface' else _parse_solid(elem)
if surfaces:
current_building['surfaces'].extend(surfaces)
if tag == 'Building' and current_building is not None:
if current_building['surfaces']:
bid = f"{year}_{arrondissement}_{current_building['id']}"
buildings[bid] = current_building
current_building = None
if tag not in ('Building', 'lod2MultiSurface', 'lod2Solid'):
elem.clear()
if not buildings:
print(f" WARNING: No buildings extracted!")
return None
# Deduplicate vertices
vertices, buildings = _deduplicate_vertices(buildings)
# Compute global bounding box
all_v = np.array(vertices)
bbox = [float(all_v[:,0].min()), float(all_v[:,0].max()),
float(all_v[:,1].min()), float(all_v[:,1].max()),
float(all_v[:,2].min()), float(all_v[:,2].max())]
# Transform for integer compression
translate = [bbox[0], bbox[2], bbox[4]]
max_dim = max(bbox[1]-bbox[0], bbox[3]-bbox[2], bbox[5]-bbox[4])
scale_factor = max(max_dim / 1e6, 1e-6)
scale = [scale_factor, scale_factor, scale_factor]
# Build CityObjects
city_objects = {}
for bid, bdata in buildings.items():
city_objects[bid] = {
'type': 'Building',
'geometry': [{
'type': 'MultiSurface',
'lod': '2',
'boundaries': bdata['boundaries'],
}],
}
cityjson = {
'type': 'CityJSON',
'version': '1.1',
'metadata': {
'referenceSystem': crs_uri or 'EPSG:3946',
'geographicalExtent': bbox,
'datasetTitle': f'Lyon {arrondissement} {year}',
},
'transform': {'scale': scale, 'translate': translate},
'CityObjects': city_objects,
'vertices': vertices,
}
print(f" {len(city_objects)} buildings, {len(vertices)} vertices, CRS={crs_uri}")
return cityjson
def main():
base_dir = os.path.dirname(os.path.abspath(__file__))
lyon_data = os.path.join(base_dir, '..', 'data', 'lyon')
years = ['2009', '2012', '2015']
for year in years:
gml_dir = os.path.join(lyon_data, year)
cityjson_dir = os.path.join(lyon_data, year + '_cityjson')
os.makedirs(cityjson_dir, exist_ok=True)
gml_files = sorted([f for f in os.listdir(gml_dir) if f.endswith('.gml')])
if not gml_files:
print(f"No GML files found for {year}")
continue
print(f"\n{'='*60}")
print(f"YEAR {year}: {len(gml_files)} files")
for gml_file in gml_files:
arr = gml_file.replace(f'_BATI_{year}.gml', '').replace('LYON_', '')
gml_path = os.path.join(gml_dir, gml_file)
output_path = os.path.join(cityjson_dir, f'LYON_{arr}_{year}.json')
if os.path.exists(output_path):
print(f" Skipping {gml_file} (already converted)")
continue
cityjson = convert_gml_to_cityjson(gml_path, year, arr)
if cityjson:
with open(output_path, 'w') as f:
json.dump(cityjson, f)
size_mb = os.path.getsize(output_path) / 1024 / 1024
print(f" → Saved: {os.path.basename(output_path)} ({size_mb:.1f} MB)")
if __name__ == '__main__':
main()
|