e32 commited on
Commit
e95f494
·
verified ·
1 Parent(s): 2ce6d27

Initial release: reconstruction pipeline + metadata

Browse files
.gitignore ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ---------------------------------------------------------------------------
2
+ # SAFETY: never commit Google-derived imagery or source/third-party data.
3
+ # These patterns prevent accidental redistribution of content that this repo
4
+ # is deliberately NOT allowed to host (see docs/GOOGLE_MAPS_NOTICE.md).
5
+ # ---------------------------------------------------------------------------
6
+
7
+ # Google Maps Static API imagery and styled renders
8
+ *_sat.png
9
+ *_map.png
10
+
11
+ # Semantic masks parsed from Google map renders (Google-derived)
12
+ *_Building.png
13
+ *_RoadSurface.png
14
+ *_Railway.png
15
+ *_VegetationLand.png
16
+ *_UrbanLand.png
17
+ *_WaterSurface.png
18
+
19
+ # Source / reconstructed point clouds and rasters (link to source instead)
20
+ *.las
21
+ *.laz
22
+ *.fbx
23
+ *_dsm.tif
24
+ *_dsm.png
25
+ *_bev.png
26
+
27
+ # Assembled per-tile output directories
28
+ output/
29
+ output_*/
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Secrets — never commit API keys or signing secrets
33
+ # ---------------------------------------------------------------------------
34
+ .env
35
+ *.key
36
+ *secret*
37
+ credentials*.json
38
+
39
+ # ---------------------------------------------------------------------------
40
+ # Python
41
+ # ---------------------------------------------------------------------------
42
+ __pycache__/
43
+ *.pyc
44
+ .venv/
45
+ venv/
46
+ .DS_Store
LICENSE ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Xinyu Wang, Muhammad Ibrahim, Atif Mansoor, Ajmal Mian
4
+ (The University of Western Australia)
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+
24
+ -------------------------------------------------------------------------------
25
+ NOTE: This license covers ONLY the pipeline code and the tile-coordinate
26
+ metadata authored by the City3D-MultiGen authors. It does NOT cover:
27
+ - Google Maps Platform content (satellite/semantic imagery) — governed by the
28
+ Google Maps Platform Terms of Service; not redistributed here.
29
+ - The City of Melbourne 3D Point Cloud — governed by its own license.
30
+ - HoliCity data — governed by its own terms of use.
31
+ See README.md and docs/GOOGLE_MAPS_NOTICE.md.
README.md ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: City3D-MultiGen
3
+ license: other
4
+ license_name: mixed-code-and-third-party-data
5
+ license_link: LICENSE
6
+ language:
7
+ - en
8
+ size_categories:
9
+ - 100K<n<1M
10
+ task_categories:
11
+ - image-to-3d
12
+ tags:
13
+ - 3d-point-cloud
14
+ - point-cloud-generation
15
+ - city-scale
16
+ - remote-sensing
17
+ - satellite-imagery
18
+ - digital-surface-model
19
+ - eccv-2026
20
+ ---
21
+
22
+ # City3D-MultiGen
23
+
24
+ A benchmark of **~163K densely annotated city tiles** from **Melbourne (Australia)** and
25
+ **London (UK)**, each with aligned **point-cloud geometry**, **satellite imagery**,
26
+ **semantic segmentation maps**, and a **Digital Surface Model (DSM)**.
27
+
28
+ City3D-MultiGen is the benchmark introduced in our ECCV 2026 paper *"GridFlow: Structured
29
+ Latent Flow for Seamless City-Scale 3D Point Cloud Generation."*
30
+
31
+ ---
32
+
33
+ ## ⚠️ Important: this repository does **not** redistribute third-party data
34
+
35
+ To comply with the **Google Maps Platform Terms of Service** and the licenses of the source
36
+ 3D datasets, this repository **does not contain**:
37
+
38
+ - ❌ Satellite images (`*_sat.png`) — retrieved from the Google Maps Static API
39
+ - ❌ Styled map renders (`*_map.png`) — Google Maps content
40
+ - ❌ Semantic masks (`*_Building.png`, `*_RoadSurface.png`, …) — **derived from** the Google
41
+ map renders, and therefore also Google-derived content
42
+ - ❌ Source point clouds (City of Melbourne LiDAR, HoliCity meshes)
43
+
44
+ Instead, this repository provides everything you need to **reproduce the full dataset
45
+ yourself**:
46
+
47
+ - ✅ The complete processing **pipeline scripts**
48
+ - ✅ **Tile coordinate metadata** (the geographic grid that defines every tile)
49
+ - ✅ Train / validation / test **split lists**
50
+ - ✅ Step-by-step instructions below
51
+
52
+ You bring your own **Google Maps Platform API key** and download the source 3D data from its
53
+ official providers; the scripts then rebuild the aligned multi-modal tiles locally.
54
+
55
+ ---
56
+
57
+ ## What gets reconstructed (per-tile layout)
58
+
59
+ After running the pipeline, each tile `grid_<id>/` contains:
60
+
61
+ | File | Modality | Produced by |
62
+ |------|----------|-------------|
63
+ | `grid_<id>.las` | Point cloud (geometry + RGB) | tiling the source point cloud |
64
+ | `grid_<id>.json` | Tile metadata (geo-extent, grid index) | tiling |
65
+ | `grid_<id>_sat.png` | Satellite image | Google Maps Static API |
66
+ | `grid_<id>_map.png` | Styled semantic render | Google Maps Static API |
67
+ | `grid_<id>_<Class>.png` | Per-class binary masks | parsing `_map.png` |
68
+ | `grid_<id>_dsm.tif` / `_dsm.png` | Digital Surface Model | rasterized from the point cloud |
69
+ | `grid_<id>_bev.png` | Bird's-eye-view render | rendered from the point cloud |
70
+
71
+ Semantic classes (6): `Building`, `RoadSurface`, `Railway`, `VegetationLand`,
72
+ `UrbanLand`, `WaterSurface`.
73
+
74
+ ---
75
+
76
+ ## Prerequisites
77
+
78
+ ```bash
79
+ pip install -r requirements.txt
80
+ ```
81
+
82
+ **System dependency — PDAL.** The tiling scripts call [PDAL](https://pdal.io/) (`pdal
83
+ translate` and PDAL pipelines) to crop tiles and write LAS spatial-reference headers. PDAL is
84
+ not a pip package; install it via conda or your system package manager:
85
+
86
+ ```bash
87
+ conda install -c conda-forge pdal
88
+ # or (Debian/Ubuntu): sudo apt-get install pdal
89
+ ```
90
+
91
+ You will also need a **Google Maps Platform** account with the **Maps Static API** enabled:
92
+
93
+ - `GOOGLE_MAPS_API_KEY` — your API key
94
+ - `GOOGLE_MAPS_URL_SIGNING_SECRET` — your URL-signing secret
95
+ - `GOOGLE_MAPS_STYLE_MAP_ID` — the ID of **your own** Google Cloud map style used to render the
96
+ semantic maps (see note below)
97
+
98
+ Set them as environment variables (the scripts read them from the environment; **never commit
99
+ keys to this repo**):
100
+
101
+ ```bash
102
+ export GOOGLE_MAPS_API_KEY="your-key"
103
+ export GOOGLE_MAPS_URL_SIGNING_SECRET="your-signing-secret"
104
+ export GOOGLE_MAPS_STYLE_MAP_ID="your-map-style-id"
105
+ ```
106
+
107
+ > **Recreating the semantic map style.** The per-class semantic masks are parsed from a
108
+ > *custom-styled* Google map in which each land-cover class is rendered in a fixed colour. You
109
+ > must recreate this map style in your own Google Cloud account and set its map-style ID above.
110
+ > The exact class→colour mapping is defined in `CLASS_COLORS_HEX` at the top of
111
+ > `Obtain_corresponding_map_signed.py` — reproduce those colours in your style.
112
+
113
+ > By using these scripts you are making **live calls to the Google Maps Platform under your own
114
+ > account**, and you are responsible for complying with the
115
+ > [Google Maps Platform Terms of Service](https://cloud.google.com/maps-platform/terms).
116
+ > See [`docs/GOOGLE_MAPS_NOTICE.md`](docs/GOOGLE_MAPS_NOTICE.md).
117
+
118
+ ---
119
+
120
+ ## Reproducing the dataset
121
+
122
+ ### Step 1 — Download the source 3D data (link only, not hosted here)
123
+
124
+ | City | Source | Link |
125
+ |------|--------|------|
126
+ | Melbourne | City of Melbourne 3D Point Cloud 2018 (LAS; MGA Zone 55 / AHD) | https://data.melbourne.vic.gov.au/explore/dataset/city-of-melbourne-3d-point-cloud-2018/ |
127
+ | London | HoliCity (FBX CAD models) | https://holicity.io/ · https://github.com/zhou13/holicity |
128
+
129
+ > ⚠️ **HoliCity is for non-commercial (academic/research) use only.** You must accept the
130
+ > HoliCity Terms of Use before downloading. The underlying CAD models are owned by AccuCities
131
+ > Inc. and the panoramas by Google; commercial use requires their explicit permission. The
132
+ > London portion of City3D-MultiGen inherits these restrictions.
133
+
134
+ Place the downloaded files where the tiling scripts expect them (see
135
+ [`scripts/README.md`](scripts/README.md)).
136
+
137
+ ### Step 2 — Tile the point clouds
138
+
139
+ **HoliCity only — first sample a point cloud from the FBX meshes.** The London source is
140
+ distributed as FBX CAD meshes, not point clouds. Sample a dense point cloud from each mesh and
141
+ export it to LAS using [CloudCompare](https://www.cloudcompare.org/)
142
+ (*Edit ▸ Mesh ▸ Sample Points*). Then attach the geographic spatial reference to the tiles with
143
+ `holicity/convert_coord.py` and `holicity/add_coord_head.py` before tiling. (Melbourne is
144
+ already distributed as LAS, so it skips this step.)
145
+
146
+ Then partition the point clouds into 150 m × 150 m tiles:
147
+
148
+ ```bash
149
+ # Melbourne
150
+ python scripts/melbourne/export_las_blocks_noKML.py # see script header for arguments
151
+
152
+ # London / HoliCity
153
+ python scripts/holicity/export_las_blocks_noKML.py
154
+ ```
155
+
156
+ This also produces the per-tile DSM and BEV render.
157
+
158
+ ### Step 3 — Fetch satellite + semantic maps (your own Google key)
159
+
160
+ ```bash
161
+ python scripts/melbourne/Obtain_corresponding_map_signed.py # reads keys from env vars
162
+ ```
163
+
164
+ This retrieves the satellite image and the styled map for each tile and parses the per-class
165
+ semantic masks.
166
+
167
+ ### Step 4 — Generate the DSM (and BEV render)
168
+
169
+ The DSM is rasterized from the point-cloud elevation (no Google data involved); it is produced
170
+ by the export/tiling scripts (see the `DSM` variant) or the dedicated step in
171
+ `build_dataset.py`.
172
+
173
+ ### Step 5 — Assemble the final dataset
174
+
175
+ ```bash
176
+ python scripts/build_dataset.py # orchestrates steps 2–4 into the per-tile layout above
177
+ ```
178
+
179
+ ---
180
+
181
+ ## Splits
182
+
183
+ Train / validation / test tile IDs are listed in [`metadata/splits/`](metadata/splits/).
184
+ Splits are spatially separated (≥150 m between regions) to prevent geographic leakage.
185
+
186
+ ---
187
+
188
+ ## Licenses & attribution
189
+
190
+ - **Pipeline code & metadata in this repo:** MIT — see [`LICENSE`](LICENSE).
191
+ - **City of Melbourne 3D Point Cloud 2018:** distributed via the City of Melbourne Open Data
192
+ Portal. _Confirm the exact license on the portal (City of Melbourne open data is generally
193
+ Creative Commons Attribution 4.0) and provide the required attribution to the City of
194
+ Melbourne._
195
+ - **HoliCity:** **non-commercial / academic use only**, subject to the HoliCity Terms of Use.
196
+ CAD models © AccuCities Inc.; street-view panoramas © Google. Commercial use requires
197
+ permission from the respective owners.
198
+ - **Google Maps content:** governed by the Google Maps Platform ToS; **not** redistributed
199
+ here. See [`docs/GOOGLE_MAPS_NOTICE.md`](docs/GOOGLE_MAPS_NOTICE.md).
200
+
201
+ Because the London/HoliCity portion is non-commercial and the satellite/semantic imagery is
202
+ Google-derived, City3D-MultiGen as a whole **cannot be redistributed as a single open archive**
203
+ — which is exactly why this repository ships a reconstruction recipe rather than the assembled
204
+ data.
205
+
206
+ ---
207
+
208
+ ## Citation
209
+
210
+ ```bibtex
211
+ @inproceedings{wang2026gridflow,
212
+ title = {GridFlow: Structured Latent Flow for Seamless City-Scale 3D Point Cloud Generation},
213
+ author = {Wang, Xinyu and Ibrahim, Muhammad and Mansoor, Atif and Mian, Ajmal},
214
+ booktitle = {European Conference on Computer Vision (ECCV)},
215
+ year = {2026}
216
+ }
217
+ ```
docs/GOOGLE_MAPS_NOTICE.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Google Maps Platform — Usage Notice
2
+
3
+ City3D-MultiGen uses imagery retrieved from the **Google Maps Static API** as its satellite
4
+ and semantic-map conditions. Under the
5
+ [Google Maps Platform Terms of Service](https://cloud.google.com/maps-platform/terms), this
6
+ content **cannot be cached, stored, redistributed, or used to create derivative works** that
7
+ are distributed to third parties.
8
+
9
+ Accordingly:
10
+
11
+ - This repository **does not contain** any Google Maps imagery (`*_sat.png`, `*_map.png`) or
12
+ the semantic masks derived from it (`*_<Class>.png`).
13
+ - The provided scripts retrieve this content **at run time, through live API calls made under
14
+ your own Google Maps Platform account and API key**.
15
+ - **You** are solely responsible for complying with the Google Maps Platform Terms of Service,
16
+ including any restrictions on caching, storage, redistribution, and derivative works, and for
17
+ any usage costs incurred on your account.
18
+
19
+ If you intend to redistribute a fully assembled copy of the dataset (including the imagery),
20
+ you must first obtain the necessary rights from Google and from the source-data providers. The
21
+ authors of City3D-MultiGen do not grant any rights to Google Maps content.
metadata/README.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tile metadata
2
+
3
+ Per-tile geographic coordinates are **regenerated by the pipeline** rather than shipped as a
4
+ static file. (An earlier exported grid file did not match the released tile set, so it was
5
+ removed to avoid confusion.)
6
+
7
+ ## Files
8
+
9
+ | File | Description |
10
+ |------|-------------|
11
+ | `melbourne_tile_index.kml` | Tile index for Melbourne, viewable in any GIS tool; input to `scripts/melbourne/grid_from_kml.py`. |
12
+ | `splits/` | Train / validation / test tile-ID lists. Generate with `scripts/make_splits.py` (see `splits/README.md`). |
13
+
14
+ ## Regenerating the tile grid
15
+
16
+ The tiling scripts derive each tile's geographic extent directly from the source LAS, so no
17
+ pre-computed grid file is required. If you want an explicit grid as JSON, run:
18
+
19
+ ```bash
20
+ python scripts/melbourne/grid_from_kml.py # writes output_grids.json from the tile index KML
21
+ ```
22
+
23
+ Each entry provides the tile id, grid row/column, and geographic bounding box (UTM + WGS84).
metadata/melbourne_tile_index.kml ADDED
The diff for this file is too large to render. See raw diff
 
metadata/splits/README.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Train / validation / test splits
2
+
3
+ The split is **deterministic** (no shuffling, no random seed): tiles are globbed
4
+ recursively, sorted by path, and sliced sequentially into 80% train / 10% val /
5
+ 10% test. Regenerate the exact split used in the paper with:
6
+
7
+ python ../../scripts/make_splits.py --data_root /path/to/output \
8
+ --train_split 0.8 --val_split 0.1 --out_dir .
9
+
10
+ This writes `train.txt`, `val.txt`, `test.txt` (one `grid_<id>` per line).
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dependencies for the City3D-MultiGen reproduction pipeline.
2
+ # (Derived from the actual imports in scripts/.)
3
+ numpy
4
+ scipy
5
+ requests
6
+ Pillow
7
+ tqdm
8
+ pyproj
9
+ laspy # LAS/LAZ point-cloud I/O
10
+ # System dependencies (NOT pip — install separately; see README):
11
+ # - PDAL : tiling scripts call `pdal translate` / PDAL pipelines
12
+ # (conda install -c conda-forge pdal)
13
+ # - CloudCompare : HoliCity FBX -> point-cloud sampling (manual, GUI)
scripts/README.md ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pipeline scripts
2
+
3
+ These scripts reconstruct City3D-MultiGen from the source data, organized by city.
4
+ Only the canonical (non-duplicate) version of each stage is kept.
5
+
6
+ ## `melbourne/`
7
+ Processing for the City of Melbourne 3D Point Cloud.
8
+
9
+ | Script | Role |
10
+ |--------|------|
11
+ | `export_las_blocks_noKML.py` | The full tiler: partitions the source LAS into 150 m tiles and produces the per-tile point cloud, **DSM**, and BEV render. |
12
+ | `grid_from_kml.py` | Builds the tile grid (`metadata/*_grids.json`) from the KML tile index. |
13
+ | `Obtain_corresponding_map_signed.py` | Fetches satellite + styled map from the Google Maps Static API and parses the per-class semantic masks. **Reads `GOOGLE_MAPS_API_KEY` and `GOOGLE_MAPS_URL_SIGNING_SECRET` from environment variables.** |
14
+
15
+ ## `holicity/`
16
+ Processing for HoliCity (London) FBX meshes.
17
+
18
+ | Script | Role |
19
+ |--------|------|
20
+ | `export_las_blocks_noKML.py` | Samples point clouds from the meshes and tiles them (same full tiler as Melbourne). |
21
+ | `convert_coord.py` | Converts HoliCity local coordinates to geographic coordinates. |
22
+ | `add_coord_head.py` | Writes the geographic coordinate header onto each tile. |
23
+ | `check_coord.py` | Sanity-checks the coordinate alignment of generated tiles (optional utility). |
24
+ | `Obtain_corresponding_map_signed.py` | Fetches satellite + semantic maps (same Google API, your own key). |
25
+
26
+ ## `build_dataset.py`
27
+ Top-level orchestrator: tiling → map fetching → DSM/BEV, assembling the per-tile
28
+ layout described in the top-level README.
29
+
30
+ ---
31
+
32
+ ### ⚠️ Before running
33
+ - Set your Google credentials as environment variables (see top-level README).
34
+ - API keys/secrets have been removed from these scripts and are read from the
35
+ environment. **Do not re-introduce hardcoded credentials** — this repo is public.
36
+ - Edit the input/output paths at the top of each script to match your local layout.
scripts/build_dataset.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ City3D-MultiGen — pipeline runner.
4
+
5
+ This runs the reconstruction stages for one city in order. It does NOT host any
6
+ data: it drives the same scripts documented in the README to rebuild the aligned
7
+ multi-modal tiles locally from (1) source 3D data you downloaded yourself and
8
+ (2) live Google Maps Static API calls made under your own key.
9
+
10
+ Manual prerequisites (NOT automated here — see README.md):
11
+ 1. Download the source 3D data:
12
+ - Melbourne: City of Melbourne 3D Point Cloud 2018 (LAS).
13
+ - HoliCity (London): FBX meshes, then sample a point cloud to LAS with
14
+ CloudCompare, and georeference it with holicity/convert_coord.py and
15
+ holicity/add_coord_head.py.
16
+ 2. Install PDAL (conda install -c conda-forge pdal) — the tiler calls it.
17
+ 3. Export your Google credentials:
18
+ GOOGLE_MAPS_API_KEY, GOOGLE_MAPS_URL_SIGNING_SECRET, GOOGLE_MAPS_STYLE_MAP_ID
19
+ 4. Set the input/output paths at the top of each stage script (the tilers read
20
+ their LAS input dir and output dir from module-level constants).
21
+
22
+ Stages run by this script (per city):
23
+ A. <city>/export_las_blocks_noKML.py -> tiles + per-tile DSM + BEV
24
+ B. <city>/Obtain_corresponding_map_signed.py -> satellite + 6 semantic masks
25
+ C. make_splits.py -> train/val/test tile lists
26
+
27
+ Usage:
28
+ python scripts/build_dataset.py --city melbourne
29
+ python scripts/build_dataset.py --city holicity --data_root ./output --skip_splits
30
+ """
31
+ import argparse
32
+ import os
33
+ import shutil
34
+ import subprocess
35
+ import sys
36
+
37
+ HERE = os.path.dirname(os.path.abspath(__file__))
38
+ ENV_VARS = ("GOOGLE_MAPS_API_KEY", "GOOGLE_MAPS_URL_SIGNING_SECRET", "GOOGLE_MAPS_STYLE_MAP_ID")
39
+
40
+
41
+ def check_prereqs():
42
+ missing = [k for k in ENV_VARS if not os.environ.get(k)]
43
+ if missing:
44
+ sys.exit(f"[error] Missing environment variables: {', '.join(missing)}. See README.md.")
45
+ if shutil.which("pdal") is None:
46
+ sys.exit("[error] PDAL not found on PATH. Install it: conda install -c conda-forge pdal")
47
+
48
+
49
+ def run(script_rel, *cli_args):
50
+ path = os.path.join(HERE, script_rel)
51
+ cmd = [sys.executable, path, *cli_args]
52
+ print(f"\n>>> {' '.join(cmd)}", flush=True)
53
+ subprocess.run(cmd, check=True)
54
+
55
+
56
+ def main():
57
+ ap = argparse.ArgumentParser(description="Run the City3D-MultiGen reconstruction stages.")
58
+ ap.add_argument("--city", choices=["melbourne", "holicity"], required=True)
59
+ ap.add_argument("--data_root", default="./output",
60
+ help="Directory holding the assembled tiles (used for the split step).")
61
+ ap.add_argument("--skip_splits", action="store_true", help="Do not run make_splits.py.")
62
+ args = ap.parse_args()
63
+
64
+ check_prereqs()
65
+ print(f"[info] Running the {args.city} pipeline. Ensure the manual prerequisites in this "
66
+ f"script's docstring are done and paths are configured at the top of each stage script.")
67
+
68
+ # Stage A — tile the (already downloaded / sampled) source point clouds.
69
+ run(f"{args.city}/export_las_blocks_noKML.py")
70
+
71
+ # Stage B — fetch satellite + semantic maps for the tiles produced in Stage A.
72
+ if args.city == "melbourne":
73
+ run("melbourne/Obtain_corresponding_map_signed.py", "--folder", args.data_root)
74
+ else:
75
+ run("holicity/Obtain_corresponding_map_signed.py")
76
+
77
+ # Stage C — generate the train/val/test split lists.
78
+ if not args.skip_splits:
79
+ run("make_splits.py", "--data_root", args.data_root,
80
+ "--out_dir", os.path.join(HERE, "..", "metadata", "splits"))
81
+
82
+ print("\n[done] Reminder: Google Maps imagery is subject to the Google Maps Platform ToS; "
83
+ "do not redistribute the fetched *_sat.png / *_map.png / *_<Class>.png files.")
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
scripts/holicity/Obtain_corresponding_map_signed.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Fetch satellite and styled basemap imagery and derive per-class semantic masks
3
+ (HoliCity / London variant of the City3D-MultiGen reconstruction pipeline).
4
+
5
+ Pipeline role:
6
+ For each 150 m tile this script downloads a satellite image and a custom-styled
7
+ Google "roadmap" basemap from the Google Maps Static API (using URL signing),
8
+ crops both to the tile's WGS84 bounding box, and parses the styled basemap into
9
+ binary semantic masks by exact/tolerant color matching against CLASS_COLORS_HEX.
10
+
11
+ Inputs:
12
+ - A folder (default ``./output``) of per-tile JSON files, each providing the tile
13
+ corners ``wgs84_nw`` = [west_lon, north_lat] and ``wgs84_se`` = [east_lon, south_lat].
14
+
15
+ Outputs (written next to each ``<base>.json``, sharing its base name):
16
+ - ``<base>_sat.png`` : cropped satellite image of the tile.
17
+ - ``<base>_map.png`` : cropped custom-styled basemap of the tile.
18
+ - Six binary masks ``<base>_<Class>.png`` for Building, RoadSurface, Railway,
19
+ VegetationLand, UrbanLand and WaterSurface (255 = class pixel, 0 = background).
20
+
21
+ Key steps:
22
+ 1. Compute the tile center and download satellite + styled basemap tiles (zoom 18).
23
+ 2. Web-Mercator project the bounding box and crop both images to the tile extent.
24
+ 3. Match styled-map colors per class (exact match, tolerant + 1px dilation for Railway)
25
+ and save one mask per class. Already-processed tiles are skipped.
26
+
27
+ Required environment variables (no defaults; the script reads them as-is):
28
+ - GOOGLE_MAPS_API_KEY : Google Maps Static API key.
29
+ - GOOGLE_MAPS_URL_SIGNING_SECRET : URL signing secret used to sign each request.
30
+ - GOOGLE_MAPS_STYLE_MAP_ID : Cloud-based map style ID defining the semantic-class
31
+ colors. You must recreate the custom styled map in your own Google Cloud account.
32
+ """
33
+ import os
34
+ import json
35
+ import math
36
+ import io
37
+ import time
38
+ import requests
39
+ from requests.adapters import HTTPAdapter
40
+ from urllib3.util.retry import Retry
41
+ from PIL import Image
42
+ import numpy as np
43
+ from tqdm import tqdm
44
+ import hashlib
45
+ import hmac
46
+ import base64
47
+ import urllib.parse as urlparse
48
+
49
+ CLASS_COLORS_HEX = {
50
+ "RoadSurface": ["1e1e1e"],
51
+ "Building": ["ff0000"],
52
+ "Railway": ["0073ff"],
53
+ "VegetationLand": ["c3f1d5"],
54
+ "UrbanLand": ["f5f0e5", "d3f8e2"],
55
+ "WaterSurface": ["90daee"],
56
+ }
57
+
58
+ def hex_to_rgb(hex_str):
59
+ h = hex_str.strip().lower()
60
+ return (
61
+ int(h[0:2], 16),
62
+ int(h[2:4], 16),
63
+ int(h[4:6], 16),
64
+ )
65
+
66
+ CLASS_COLORS_RGB = {
67
+ class_name: [hex_to_rgb(code) for code in hex_list]
68
+ for class_name, hex_list in CLASS_COLORS_HEX.items()
69
+ }
70
+
71
+ def sign_url(input_url, secret):
72
+ if not input_url or not secret:
73
+ raise Exception("Both input_url and secret are required")
74
+
75
+ url = urlparse.urlparse(input_url)
76
+ url_to_sign = url.path + "?" + url.query
77
+ decoded_key = base64.urlsafe_b64decode(secret)
78
+ signature = hmac.new(decoded_key, str.encode(url_to_sign), hashlib.sha1)
79
+ encoded_signature = base64.urlsafe_b64encode(signature.digest())
80
+ original_url = url.scheme + "://" + url.netloc + url.path + "?" + url.query
81
+ return original_url + "&signature=" + encoded_signature.decode()
82
+
83
+ def dilate_mask_1px(mask_arr):
84
+ h, w = mask_arr.shape
85
+ out = np.zeros((h, w), dtype=np.uint8)
86
+ ys, xs = np.nonzero(mask_arr > 0)
87
+ for y, x in zip(ys, xs):
88
+ y0 = max(y - 1, 0)
89
+ y1 = min(y + 1, h - 1)
90
+ x0 = max(x - 1, 0)
91
+ x1 = min(x + 1, w - 1)
92
+ out[y0:y1+1, x0:x1+1] = 255
93
+ return out
94
+
95
+ def match_mask_exact(arr, rgb_triplet):
96
+ r, g, b = rgb_triplet
97
+ return (
98
+ (arr[:, :, 0] == r) &
99
+ (arr[:, :, 1] == g) &
100
+ (arr[:, :, 2] == b)
101
+ )
102
+
103
+ def channel_bounds_with_margin(channel_val, margin_ratio):
104
+ low = int(round(channel_val * (1.0 - margin_ratio)))
105
+ high = int(round(channel_val * (1.0 + margin_ratio)))
106
+ if low < 0:
107
+ low = 0
108
+ if high > 255:
109
+ high = 255
110
+ return low, high
111
+
112
+ def match_mask_tolerant(arr, rgb_triplet, margin_ratio):
113
+ r, g, b = rgb_triplet
114
+ rl, rh = channel_bounds_with_margin(r, margin_ratio)
115
+ gl, gh = channel_bounds_with_margin(g, margin_ratio)
116
+ bl, bh = channel_bounds_with_margin(b, margin_ratio)
117
+ return (
118
+ (arr[:, :, 0] >= rl) & (arr[:, :, 0] <= rh) &
119
+ (arr[:, :, 1] >= gl) & (arr[:, :, 1] <= gh) &
120
+ (arr[:, :, 2] >= bl) & (arr[:, :, 2] <= bh)
121
+ )
122
+
123
+ def generate_masks_from_roadmap(crop_road_img, base_output_path_no_ext):
124
+ rgb = crop_road_img.convert("RGB")
125
+ arr = np.array(rgb, dtype=np.uint8)
126
+
127
+ for class_name, rgb_list in CLASS_COLORS_RGB.items():
128
+ class_mask_total = np.zeros(arr.shape[:2], dtype=np.uint8)
129
+
130
+ for rgb_triplet in rgb_list:
131
+ if class_name == "Railway":
132
+ match = match_mask_tolerant(arr, rgb_triplet, margin_ratio=0.1)
133
+ else:
134
+ match = match_mask_exact(arr, rgb_triplet)
135
+ class_mask_total[match] = 255
136
+
137
+ if class_name == "Railway":
138
+ class_mask_total = dilate_mask_1px(class_mask_total)
139
+
140
+ out_path = f"{base_output_path_no_ext}_{class_name}.png"
141
+ img = Image.fromarray(class_mask_total)
142
+ img.save(out_path)
143
+
144
+ def save_bbox_satellite_and_roadmap(
145
+ north_lat,
146
+ west_lon,
147
+ south_lat,
148
+ east_lon,
149
+ out_path_sat,
150
+ out_path_road,
151
+ api_key,
152
+ url_signing_secret,
153
+ style_map_id
154
+ ):
155
+ def mercator_project(lon_deg, lat_deg, zoom):
156
+ scale = 256 * (2 ** zoom)
157
+ x = (lon_deg + 180.0) / 360.0 * scale
158
+ lat_rad = math.radians(lat_deg)
159
+ y = (1.0 - math.log(math.tan(lat_rad) + 1.0 / math.cos(lat_rad)) / math.pi) / 2.0 * scale
160
+ return x, y
161
+
162
+ def bbox_center(n_lat, s_lat, w_lon, e_lon):
163
+ return (
164
+ (n_lat + s_lat) / 2.0,
165
+ (w_lon + e_lon) / 2.0
166
+ )
167
+
168
+ def download_static(center_lat, center_lon, zoom, size_px, maptype, api_key, url_signing_secret, style_map_id=None):
169
+ session = requests.Session()
170
+ retry_strategy = Retry(
171
+ total=5,
172
+ backoff_factor=2,
173
+ status_forcelist=[429, 500, 502, 503, 504],
174
+ allowed_methods=["GET"]
175
+ )
176
+ adapter = HTTPAdapter(max_retries=retry_strategy)
177
+ session.mount("https://", adapter)
178
+ session.mount("http://", adapter)
179
+
180
+ base = "https://maps.googleapis.com/maps/api/staticmap"
181
+ params = {
182
+ "center": f"{center_lat},{center_lon}",
183
+ "zoom": str(18),
184
+ "size": f"{size_px}x{size_px}",
185
+ "format": "png",
186
+ "key": api_key,
187
+ }
188
+ if maptype == "satellite":
189
+ params["maptype"] = "satellite"
190
+ else:
191
+ params["map_id"] = style_map_id
192
+
193
+ query_string = "&".join([f"{k}={urlparse.quote(str(v), safe='')}" for k, v in params.items()])
194
+ unsigned_url = f"{base}?{query_string}"
195
+ signed_url = sign_url(unsigned_url, url_signing_secret)
196
+
197
+ max_retries = 3
198
+ for attempt in range(max_retries):
199
+ try:
200
+ resp = session.get(signed_url, timeout=30)
201
+ resp.raise_for_status()
202
+ time.sleep(0.5)
203
+ return Image.open(io.BytesIO(resp.content)).convert("RGBA")
204
+ except (requests.exceptions.ConnectionError,
205
+ requests.exceptions.Timeout,
206
+ requests.exceptions.RequestException) as e:
207
+ if attempt < max_retries - 1:
208
+ wait_time = (attempt + 1) * 5
209
+ print(f"\nRequest failed, retrying in {wait_time} seconds...")
210
+ time.sleep(wait_time)
211
+ else:
212
+ raise
213
+
214
+ def crop_bbox_from_image(img, zoom, img_px, center_lat, center_lon,
215
+ n_lat, s_lat, w_lon, e_lon):
216
+ center_x, center_y = mercator_project(center_lon, center_lat, zoom)
217
+ img_left_world = center_x - img_px / 2.0
218
+ img_top_world = center_y - img_px / 2.0
219
+
220
+ w_x, _ = mercator_project(w_lon, center_lat, zoom)
221
+ e_x, _ = mercator_project(e_lon, center_lat, zoom)
222
+ _, n_y = mercator_project(center_lon, n_lat, zoom)
223
+ _, s_y = mercator_project(center_lon, s_lat, zoom)
224
+
225
+ xmin = w_x - img_left_world
226
+ xmax = e_x - img_left_world
227
+ ymin = n_y - img_top_world
228
+ ymax = s_y - img_top_world
229
+
230
+ box = (
231
+ int(round(xmin)),
232
+ int(round(ymin)),
233
+ int(round(xmax)),
234
+ int(round(ymax)),
235
+ )
236
+
237
+ box = (
238
+ max(0, box[0]),
239
+ max(0, box[1]),
240
+ min(img_px, box[2]),
241
+ min(img_px, box[3]),
242
+ )
243
+
244
+ return img.crop(box)
245
+
246
+ zoom = 18
247
+ img_px = 600
248
+
249
+ center_lat, center_lon = bbox_center(north_lat, south_lat, west_lon, east_lon)
250
+
251
+ img_sat = download_static(center_lat, center_lon, zoom, img_px, "satellite", api_key, url_signing_secret, style_map_id=None)
252
+ img_road = download_static(center_lat, center_lon, zoom, img_px, "roadmap", api_key, url_signing_secret, style_map_id=style_map_id)
253
+
254
+ crop_sat = crop_bbox_from_image(
255
+ img_sat, zoom, img_px, center_lat, center_lon,
256
+ north_lat, south_lat, west_lon, east_lon
257
+ )
258
+ crop_road = crop_bbox_from_image(
259
+ img_road, zoom, img_px, center_lat, center_lon,
260
+ north_lat, south_lat, west_lon, east_lon
261
+ )
262
+
263
+ crop_sat.save(out_path_sat)
264
+ crop_road.save(out_path_road)
265
+
266
+ return crop_sat, crop_road
267
+
268
+ def process_folder(
269
+ folder_path,
270
+ api_key,
271
+ url_signing_secret,
272
+ style_map_id
273
+ ):
274
+ json_files = [f for f in os.listdir(folder_path) if f.lower().endswith(".json")]
275
+
276
+ skipped = 0
277
+ failed = 0
278
+ failed_files = []
279
+
280
+ for filename in tqdm(json_files, desc="Processing files", unit="file"):
281
+ try:
282
+ json_path = os.path.join(folder_path, filename)
283
+ base_name = os.path.splitext(filename)[0]
284
+
285
+ out_sat = os.path.join(folder_path, base_name + "_sat.png")
286
+ out_map = os.path.join(folder_path, base_name + "_map.png")
287
+
288
+ expected_files = [out_sat, out_map]
289
+ for class_name in CLASS_COLORS_RGB.keys():
290
+ expected_files.append(os.path.join(folder_path, f"{base_name}_{class_name}.png"))
291
+
292
+ if all(os.path.exists(f) for f in expected_files):
293
+ skipped += 1
294
+ continue
295
+
296
+ with open(json_path, "r", encoding="utf-8") as f:
297
+ data = json.load(f)
298
+
299
+ wgs84_nw = data["wgs84_nw"]
300
+ wgs84_se = data["wgs84_se"]
301
+
302
+ west_lon = float(wgs84_nw[0])
303
+ north_lat = float(wgs84_nw[1])
304
+ east_lon = float(wgs84_se[0])
305
+ south_lat = float(wgs84_se[1])
306
+
307
+ crop_sat, crop_road = save_bbox_satellite_and_roadmap(
308
+ north_lat = north_lat,
309
+ west_lon = west_lon,
310
+ south_lat = south_lat,
311
+ east_lon = east_lon,
312
+ out_path_sat = out_sat,
313
+ out_path_road = out_map,
314
+ api_key = api_key,
315
+ url_signing_secret = url_signing_secret,
316
+ style_map_id = style_map_id
317
+ )
318
+
319
+ base_mask_prefix = os.path.join(folder_path, base_name)
320
+ generate_masks_from_roadmap(crop_road, base_mask_prefix)
321
+
322
+ except Exception as e:
323
+ failed += 1
324
+ failed_files.append(filename)
325
+ print(f"\nFailed to process {filename}: {str(e)}")
326
+ continue
327
+
328
+ print(f"\nProcessing complete!")
329
+ if skipped > 0:
330
+ print(f"Skipped {skipped} already processed files")
331
+ if failed > 0:
332
+ print(f"Failed to process {failed} files:")
333
+ for f in failed_files:
334
+ print(f" - {f}")
335
+
336
+ if __name__ == "__main__":
337
+ folder = "./output"
338
+ api_key = os.environ.get("GOOGLE_MAPS_API_KEY")
339
+ url_signing_secret = os.environ.get("GOOGLE_MAPS_URL_SIGNING_SECRET")
340
+ # Your own Google Cloud map-style ID (defines the semantic-class colors).
341
+ # See README: you must recreate the styled map in your own account.
342
+ style_map_id = os.environ.get("GOOGLE_MAPS_STYLE_MAP_ID")
343
+ process_folder(folder, api_key, url_signing_secret, style_map_id)
scripts/holicity/add_coord_head.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Stamp a spatial reference (EPSG) into the headers of LAS/LAZ point clouds.
5
+
6
+ Role in the pipeline:
7
+ After HoliCity (London) tiles have been translated into real-world projected
8
+ coordinates, some files still lack a CRS recorded in their LAS header. This
9
+ utility writes the target EPSG into each file's header WITHOUT modifying any
10
+ point coordinates, so the tiles are correctly tagged for QGIS / satellite
11
+ imagery alignment before tiling.
12
+
13
+ Behavior:
14
+ - Recursively scans a directory for .las/.laz files (skipping macOS "._*"
15
+ AppleDouble sidecar files).
16
+ - For each file, first attempts to write the CRS with laspy
17
+ (header.add_crs, falling back to header.epsg).
18
+ - If laspy cannot write the SRS, falls back to the PDAL CLI
19
+ (`pdal translate ... --writers.las.a_srs=EPSG:<code>`), which embeds the
20
+ SRS into the LAS header while leaving coordinates unchanged.
21
+ - Verifies each result by reading back the header EPSG and reprojecting the
22
+ bbox center to WGS84 for a printed sanity check.
23
+
24
+ Inputs: directory of .las/.laz files (CLI: -d/--dir).
25
+ Outputs: either overwritten files (--overwrite) or copies with a suffix
26
+ (default *_srs.las, configurable via --suffix), each carrying TARGET_EPSG.
27
+ External tools: laspy, pyproj, and PDAL (`pdal translate`) as a fallback.
28
+ """
29
+
30
+ import os
31
+ import sys
32
+ import argparse
33
+ import subprocess
34
+ from pathlib import Path
35
+
36
+ import laspy
37
+ from pyproj import CRS, Transformer
38
+
39
+ TARGET_EPSG = 27700 # OSGB36 / British National Grid (commonly used for London)
40
+
41
+ def is_mac_dot_underscore(p: Path) -> bool:
42
+ return p.name.startswith("._")
43
+
44
+ def try_write_epsg_with_laspy(in_path: Path, out_path: Path, epsg: int) -> bool:
45
+ """Write the CRS using laspy first; return True on success."""
46
+ las = laspy.read(str(in_path))
47
+ ok = False
48
+ # Option A: add_crs (laspy 2.3+)
49
+ try:
50
+ las.header.add_crs(CRS.from_epsg(epsg))
51
+ ok = True
52
+ except Exception:
53
+ pass
54
+ # Option B: write header.epsg directly (works on some versions)
55
+ if not ok:
56
+ try:
57
+ las.header.epsg = int(epsg)
58
+ ok = True
59
+ except Exception:
60
+ ok = False
61
+ if ok:
62
+ las.write(str(out_path))
63
+ return ok
64
+
65
+ def try_write_epsg_with_pdal(in_path: Path, out_path: Path, epsg: int) -> bool:
66
+ """Fall back to PDAL to write the SRS into the LAS header; coordinates unchanged."""
67
+ try:
68
+ cmd = [
69
+ "pdal", "translate", str(in_path), str(out_path),
70
+ "-f", "writers.las",
71
+ f"--writers.las.a_srs=EPSG:{epsg}",
72
+ "--writers.las.compression=false"
73
+ ]
74
+ subprocess.check_call(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
75
+ return True
76
+ except Exception:
77
+ return False
78
+
79
+ def center_wgs84(path: Path, epsg: int):
80
+ """Read the bbox center and reproject to WGS84, for printed verification only."""
81
+ with laspy.open(str(path)) as f:
82
+ hdr = f.header
83
+ mins = getattr(hdr, "mins", getattr(hdr, "min", (0,0,0)))
84
+ maxs = getattr(hdr, "maxs", getattr(hdr, "max", (0,0,0)))
85
+ cx = (mins[0] + maxs[0]) * 0.5
86
+ cy = (mins[1] + maxs[1]) * 0.5
87
+ tr = Transformer.from_crs(f"EPSG:{epsg}", "EPSG:4326", always_xy=True)
88
+ lon, lat = tr.transform(cx, cy)
89
+ return (lon, lat), (cx, cy), getattr(hdr, "epsg", None)
90
+
91
+ def process_file(p: Path, overwrite: bool, keep_suffix: str):
92
+ out_path = p if overwrite else p.with_name(p.stem + keep_suffix)
93
+ # Try laspy first
94
+ ok = try_write_epsg_with_laspy(p, out_path, TARGET_EPSG)
95
+ method = "laspy"
96
+ # Then fall back to PDAL
97
+ if not ok:
98
+ ok = try_write_epsg_with_pdal(p, out_path, TARGET_EPSG)
99
+ method = "pdal"
100
+
101
+ if not ok:
102
+ print(f"[FAIL] {p.name}: failed to write EPSG (neither laspy nor pdal available)")
103
+ return
104
+
105
+ # Read back to verify
106
+ (lon, lat), (cx, cy), epsg_now = center_wgs84(out_path, TARGET_EPSG)
107
+ print(f"[OK] {p.name} -> {out_path.name} via {method} "
108
+ f"| EPSG: {epsg_now} | center_xy=({cx:.3f},{cy:.3f}) | WGS84=({lon:.6f},{lat:.6f})")
109
+
110
+ def main():
111
+ ap = argparse.ArgumentParser(description="Batch-write EPSG into LAS/LAZ headers (without changing coordinates) and print a center-point verification.")
112
+ ap.add_argument("-d", "--dir", default=".", help="Directory to scan (recursive)")
113
+ ap.add_argument("--overwrite", action="store_true", help="Overwrite the original files (default writes *_srs.las)")
114
+ ap.add_argument("--suffix", default="_srs.las", help="Output suffix when not overwriting (default _srs.las)")
115
+ args = ap.parse_args()
116
+
117
+ root = Path(args.dir).resolve()
118
+ if not root.exists():
119
+ print(f"Directory does not exist: {root}", file=sys.stderr); sys.exit(1)
120
+
121
+ files = [p for p in root.rglob("*")
122
+ if p.is_file()
123
+ and p.suffix.lower() in (".las", ".laz")
124
+ and not is_mac_dot_underscore(p)]
125
+
126
+ if not files:
127
+ print("No .las/.laz files found (._* filtered out)"); return
128
+
129
+ print(f"Target EPSG: {TARGET_EPSG} | Scan directory: {root}\n")
130
+ for p in sorted(files):
131
+ try:
132
+ process_file(p, overwrite=args.overwrite, keep_suffix=args.suffix)
133
+ except Exception as e:
134
+ print(f"[ERR] {p.name}: {e}")
135
+
136
+ if __name__ == "__main__":
137
+ main()
scripts/holicity/check_coord.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Sanity-check the coordinates and CRS of georeferenced LAS/LAZ point clouds.
5
+
6
+ Role in the pipeline:
7
+ A verification utility that confirms the HoliCity (London) tiles have been
8
+ georeferenced correctly before tiling. It inspects each LAS/LAZ file's header
9
+ and bounding box, reprojects the bbox center to WGS84, and checks whether that
10
+ center falls within an approximate London bounding box.
11
+
12
+ Behavior:
13
+ - Recursively scans a directory for .las/.laz files.
14
+ - Reads header stats (EPSG, bbox, point count, point format, scale, offset)
15
+ and detects degenerate "near (0,0)" coordinates.
16
+ - If the file has an EPSG, reprojects its center to WGS84 and flags whether it
17
+ lies in the London region.
18
+ - If no EPSG is present, tries a list of candidate CRSs (BNG / UTM 30N / Web
19
+ Mercator / WGS84) and reports the first one whose center lands in London.
20
+ - Emits a per-file status (OK / WARN / BAD / ERR) plus a hint, printed as a
21
+ table and optionally exported to CSV.
22
+
23
+ Inputs: directory of .las/.laz files (CLI: -d/--dir), optional CSV path (-o/--output).
24
+ Outputs: a console report table and an optional CSV file. No files are modified.
25
+ External tools: laspy, numpy, pyproj.
26
+ """
27
+
28
+ import os
29
+ import sys
30
+ import csv
31
+ import math
32
+ import argparse
33
+ from pathlib import Path
34
+
35
+ import laspy
36
+ import numpy as np
37
+ from pyproj import CRS, Transformer
38
+
39
+ # ----------- Tunable parameters -----------
40
+ # London region (WGS84)
41
+ LON_MIN, LON_MAX = -0.6, 0.4
42
+ LAT_MIN, LAT_MAX = 51.2, 51.8
43
+
44
+ # Common candidate CRSs (used to guess when no EPSG is present)
45
+ CANDIDATE_EPSGS = [
46
+ 27700, # OSGB36 / British National Grid
47
+ 32630, # WGS84 / UTM zone 30N
48
+ 3857, # Web Mercator
49
+ 4326, # WGS84 (lat/lon)
50
+ ]
51
+
52
+ # Rough "plausible ranges" for the UK / London (quick sanity check; approximate only)
53
+ RANGE_HINTS = {
54
+ 27700: {"E": (0, 700000), "N": (0, 1300000), "name": "OSGB36 / BNG"},
55
+ 32630: {"E": (160000, 840000), "N": (5550000, 5900000), "name": "UTM 30N"},
56
+ 3857: {"X": (-500000, 500000), "Y": (6200000, 7300000), "name": "WebMerc"},
57
+ 4326: {"Lon": (-10, 10), "Lat": (45, 60), "name": "WGS84 deg"},
58
+ }
59
+ # Approximate reference for the center of London (used only for printed hints)
60
+ LONDON_WGS84 = (-0.1, 51.51)
61
+
62
+ # --------------------------------
63
+
64
+ def in_london(lon, lat):
65
+ return (LON_MIN <= lon <= LON_MAX) and (LAT_MIN <= lat <= LAT_MAX)
66
+
67
+ def safe_epsg_str(epsg):
68
+ try:
69
+ return f"EPSG:{int(epsg)}"
70
+ except Exception:
71
+ return "None"
72
+
73
+ def read_stats(path: Path, sample_n: int = 200000):
74
+ """Read the bbox and center point; for large clouds only the header bbox is read; sample some points for QC if needed."""
75
+ with laspy.open(str(path)) as f:
76
+ hdr = f.header
77
+ mins = np.array(getattr(hdr, "mins", getattr(hdr, "min", (0, 0, 0))), dtype=float)
78
+ maxs = np.array(getattr(hdr, "maxs", getattr(hdr, "max", (0, 0, 0))), dtype=float)
79
+ epsg = None
80
+ try:
81
+ epsg = hdr.epsg
82
+ except Exception:
83
+ pass
84
+
85
+ # Center point (the bbox midpoint is sufficient)
86
+ cx = (mins[0] + maxs[0]) * 0.5
87
+ cy = (mins[1] + maxs[1]) * 0.5
88
+ cz = (mins[2] + maxs[2]) * 0.5
89
+
90
+ # Check whether everything sits near (0,0)
91
+ zeroish = (abs(cx) < 1e-6 and abs(cy) < 1e-6) or \
92
+ (abs(mins[0]) < 1e-6 and abs(maxs[0]) < 1e-6 and
93
+ abs(mins[1]) < 1e-6 and abs(maxs[1]) < 1e-6)
94
+
95
+ return {
96
+ "epsg": epsg,
97
+ "mins": mins, "maxs": maxs,
98
+ "center": (cx, cy, cz),
99
+ "zeroish": zeroish,
100
+ "point_count": int(getattr(hdr, "point_count", 0)),
101
+ "point_format": str(getattr(hdr.point_format, "id", hdr.point_format)),
102
+ "scale": tuple(hdr.scales),
103
+ "offset": tuple(hdr.offsets),
104
+ }
105
+
106
+ def transform_to_wgs84(x, y, epsg):
107
+ """Reproject (x,y) from the given EPSG to WGS84 lon/lat. Return None on failure."""
108
+ try:
109
+ src = CRS.from_epsg(int(epsg))
110
+ dst = CRS.from_epsg(4326)
111
+ tr = Transformer.from_crs(src, dst, always_xy=True)
112
+ lon, lat = tr.transform(x, y)
113
+ return lon, lat
114
+ except Exception:
115
+ return None
116
+
117
+ def guess_and_transform_to_wgs84(x, y, candidates=CANDIDATE_EPSGS):
118
+ """When no EPSG is set, try each candidate CRS in turn; return the first projection that falls within the London region, along with its epsg."""
119
+ tried = []
120
+ for epsg in candidates:
121
+ res = transform_to_wgs84(x, y, epsg)
122
+ if res is None:
123
+ tried.append((epsg, None))
124
+ continue
125
+ lon, lat = res
126
+ tried.append((epsg, (lon, lat)))
127
+ if in_london(lon, lat):
128
+ return (lon, lat), epsg, tried
129
+ return None, None, tried
130
+
131
+ def range_hint_text(epsg, mins, maxs):
132
+ h = RANGE_HINTS.get(int(epsg)) if epsg is not None else None
133
+ if not h:
134
+ return ""
135
+ if epsg in (27700, 32630):
136
+ E = (mins[0], maxs[0]); N = (mins[1], maxs[1])
137
+ return f"RangeHint {h['name']}: E∈{h['E']} vs {E}, N∈{h['N']} vs {N}"
138
+ elif epsg == 3857:
139
+ X = (mins[0], maxs[0]); Y = (mins[1], maxs[1])
140
+ return f"RangeHint {h['name']}: X∈{h['X']} vs {X}, Y∈{h['Y']} vs {Y}"
141
+ elif epsg == 4326:
142
+ Lon = (mins[0], maxs[0]); Lat = (mins[1], maxs[1])
143
+ return f"RangeHint {h['name']}: Lon∈{h['Lon']} vs {Lon}, Lat∈{h['Lat']} vs {Lat}"
144
+ return ""
145
+
146
+ def analyze_file(path: Path):
147
+ size_mb = path.stat().st_size / (1024 * 1024)
148
+ stats = read_stats(path)
149
+ epsg = stats["epsg"]
150
+ cx, cy, cz = stats["center"]
151
+ mins, maxs = stats["mins"], stats["maxs"]
152
+
153
+ result = {
154
+ "file": str(path.name),
155
+ "size_mb": f"{size_mb:.2f}",
156
+ "epsg": safe_epsg_str(epsg),
157
+ "pt_fmt": stats["point_format"],
158
+ "pts": stats["point_count"],
159
+ "scale": stats["scale"],
160
+ "offset": stats["offset"],
161
+ "center_xy": (cx, cy),
162
+ "center_wgs84": None,
163
+ "in_london": False,
164
+ "status": "",
165
+ "hint": "",
166
+ }
167
+
168
+ # 0) All-zero / near-zero
169
+ if stats["zeroish"]:
170
+ result["status"] = "BAD"
171
+ result["hint"] = "Coordinates near (0,0); likely unassigned or wrong projection. Check the coordinate transform and EPSG write."
172
+ return result
173
+
174
+ # 1) Has EPSG: project and check directly
175
+ if epsg is not None:
176
+ wgs = transform_to_wgs84(cx, cy, int(epsg))
177
+ if wgs is None:
178
+ result["status"] = "WARN"
179
+ result["hint"] = f"Could not project the center from {safe_epsg_str(epsg)} to WGS84; the EPSG may be invalid."
180
+ return result
181
+ lon, lat = wgs
182
+ result["center_wgs84"] = (round(lon, 6), round(lat, 6))
183
+ result["in_london"] = in_london(lon, lat)
184
+ if result["in_london"]:
185
+ result["status"] = "OK"
186
+ result["hint"] = f"Center is within the London region; {range_hint_text(int(epsg), mins, maxs)}"
187
+ else:
188
+ result["status"] = "WARN"
189
+ result["hint"] = f"Center is outside the London region ({lon:.5f},{lat:.5f}); if it should be in London, the EPSG or translation may be wrong. {range_hint_text(int(epsg), mins, maxs)}"
190
+ return result
191
+
192
+ # 2) No EPSG: try to guess and check whether it lands in London
193
+ guessed, gepsg, tried = guess_and_transform_to_wgs84(cx, cy)
194
+ if guessed is not None:
195
+ lon, lat = guessed
196
+ result["center_wgs84"] = (round(lon, 6), round(lat, 6))
197
+ result["in_london"] = True
198
+ result["status"] = "WARN"
199
+ result["hint"] = (f"No EPSG written, but {safe_epsg_str(gepsg)} is inferred to fall in the London region. "
200
+ f"Suggest writing {safe_epsg_str(gepsg)} and retrying.")
201
+ else:
202
+ result["status"] = "BAD"
203
+ tried_text = "; ".join(
204
+ f"EPSG:{e} -> {('None' if v is None else f'({v[0]:.5f},{v[1]:.5f})')}" for e, v in tried
205
+ )
206
+ result["hint"] = ("No EPSG written, and none of the common candidate CRSs project the center into the London region. "
207
+ "Check whether a wrong translation/rotation/unit was used, or whether a different EPSG is needed. "
208
+ f"Attempts: {tried_text}")
209
+ return result
210
+
211
+ def print_table(rows):
212
+ headers = ["file","size_mb","epsg","pt_fmt","pts","center_xy","center_wgs84","in_london","status","hint"]
213
+ colw = {h: max(len(h), max((len(str(r[h])) for r in rows), default=0)) for h in headers}
214
+ sep = " | "
215
+ print(sep.join(h.ljust(colw[h]) for h in headers))
216
+ print("-" * (sum(colw.values()) + len(sep)*(len(headers)-1)))
217
+ for r in rows:
218
+ print(sep.join(str(r[h]).ljust(colw[h]) for h in headers))
219
+
220
+ def main():
221
+ ap = argparse.ArgumentParser(description="Check whether LAS/LAZ files have correct coordinates and CRS, and whether they fall within the London region.")
222
+ ap.add_argument("-d","--dir", default=".", help="Directory to scan (default: current directory)")
223
+ ap.add_argument("-o","--output", default=None, help="CSV export path (optional)")
224
+ args = ap.parse_args()
225
+
226
+ root = Path(args.dir).resolve()
227
+ if not root.exists():
228
+ print(f"Directory does not exist: {root}", file=sys.stderr); sys.exit(1)
229
+
230
+ files = []
231
+ for p in root.rglob("*"):
232
+ if p.is_file() and p.suffix.lower() in (".las",".laz"):
233
+ files.append(p)
234
+
235
+ if not files:
236
+ print("No .las/.laz files found"); return
237
+
238
+ rows = []
239
+ for p in sorted(files):
240
+ try:
241
+ rows.append(analyze_file(p))
242
+ except Exception as e:
243
+ rows.append({
244
+ "file": p.name, "size_mb":"?", "epsg":"?", "pt_fmt":"?", "pts":"?",
245
+ "center_xy":"?", "center_wgs84":"?", "in_london":"?", "status":"ERR",
246
+ "hint": f"Parse failed: {e}"
247
+ })
248
+
249
+ print(f"Scan directory: {root}\n")
250
+ print_table(rows)
251
+
252
+ if args.output:
253
+ out = Path(args.output).resolve()
254
+ out.parent.mkdir(parents=True, exist_ok=True)
255
+ with out.open("w", newline="", encoding="utf-8") as f:
256
+ writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
257
+ writer.writeheader()
258
+ writer.writerows(rows)
259
+ print(f"\nCSV written: {out}")
260
+
261
+ if __name__ == "__main__":
262
+ main()
scripts/holicity/convert_coord.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Georeference HoliCity (London) LAS tiles into a real-world projected CRS.
5
+
6
+ Role in the pipeline:
7
+ HoliCity point clouds are sampled (via CloudCompare) from FBX meshes in a
8
+ local coordinate frame with no spatial reference. This script geo-registers
9
+ the four 500x500 m tiles (NW/NE/SW/SE) of a HoliCity block onto the London
10
+ map so they line up with satellite imagery before tiling.
11
+
12
+ Method:
13
+ - The WGS84 latitude/longitude of the NW tile's top-left (north-west) corner
14
+ is known and hard-coded below (NW_LAT/NW_LON; west longitude is negative).
15
+ - That anchor is projected from WGS84 (EPSG:4326) into the target projected
16
+ CRS (default EPSG:27700, OSGB36 / British National Grid).
17
+ - The remaining tiles are placed by a fixed 500 m east/south offset.
18
+ - For each tile, the local top-left corner (minX, maxY) is read from the LAS
19
+ header bounding box, and a planar XY translation is computed to move that
20
+ corner onto its target projected coordinate.
21
+
22
+ Inputs:
23
+ The four LAS files listed in INPUT_FILES, located in the current directory.
24
+ Outputs:
25
+ For each input, a translated copy named *_georef.las with the target EPSG
26
+ written into its header.
27
+
28
+ External tools: laspy (LAS I/O), pyproj (CRS transform), numpy.
29
+ """
30
+
31
+ import os
32
+ from pathlib import Path
33
+ import laspy
34
+ import numpy as np
35
+ from pyproj import Transformer
36
+
37
+ # ==== Parameters to confirm / adjust ====
38
+ # Known WGS84 lat/lon of the NW tile's top-left (north-west) corner
39
+ NW_LAT = 51.512499
40
+ NW_LON = -0.099173 # WGS84 longitude; west of Greenwich is negative
41
+
42
+ # Real-world size of a single tile (meters)
43
+ TILE_SIZE_M = 500.0
44
+
45
+ # Target projected CRS (British National Grid recommended for London)
46
+ TARGET_EPSG = 27700 # OSGB36 / British National Grid
47
+ SOURCE_CRS = "EPSG:4326" # NW_LAT/NW_LON are given in WGS84
48
+
49
+ # The 4 files to process (filenames must distinguish the direction)
50
+ INPUT_FILES = [
51
+ "TQ3280_NW.las",
52
+ "TQ3280NE.las",
53
+ "TQ3280SW.las",
54
+ "TQ3280SE.las",
55
+ ]
56
+ # Output filename suffix
57
+ OUT_SUFFIX = "_georef.las"
58
+
59
+ # =================================
60
+
61
+ def read_bbox(path: Path):
62
+ with laspy.open(str(path)) as f:
63
+ hdr = f.header
64
+ mins = np.array(getattr(hdr, "mins", getattr(hdr, "min", (0,0,0))), dtype=float)
65
+ maxs = np.array(getattr(hdr, "maxs", getattr(hdr, "max", (0,0,0))), dtype=float)
66
+ scales = np.array(hdr.scales)
67
+ offsets = np.array(hdr.offsets)
68
+ return mins, maxs, scales, offsets
69
+
70
+ def apply_translation(in_path: Path, out_path: Path, tx: float, ty: float, target_epsg: int):
71
+ las = laspy.read(str(in_path))
72
+ # Translate (X/Y only; if a Z datum correction is needed, add a Z offset here)
73
+ las.x = las.x + tx
74
+ las.y = las.y + ty
75
+
76
+ # Write the EPSG (laspy 2.x: header.epsg)
77
+ try:
78
+ las.header.epsg = int(target_epsg)
79
+ except Exception:
80
+ # Some versions may require writing via a VLR; keep the simplest setting here
81
+ pass
82
+
83
+ # Optional: tag generation metadata
84
+ try:
85
+ las.header.system_identifier = "GeorefByScript"
86
+ las.header.generating_software = "laspy_pyproj_georef"
87
+ except Exception:
88
+ pass
89
+
90
+ las.write(str(out_path))
91
+
92
+ def main():
93
+ root = Path(".").resolve()
94
+ # 1) Project the NW top-left corner (WGS84) into target CRS coords (easting, northing)
95
+ transformer = Transformer.from_crs(SOURCE_CRS, f"EPSG:{TARGET_EPSG}", always_xy=True)
96
+ # always_xy=True => input order is longitude, latitude (lon, lat)
97
+ nw_e, nw_n = transformer.transform(NW_LON, NW_LAT)
98
+
99
+ # 2) Build the target "top-left" coords for the four directions (top-left = north-west)
100
+ # NE: +500m east of NW
101
+ # SW: +500m south of NW
102
+ # SE: +500m east and +500m south of NW
103
+ targets = {
104
+ "NW": (nw_e, nw_n),
105
+ "NE": (nw_e + TILE_SIZE_M, nw_n),
106
+ "SW": (nw_e, nw_n - TILE_SIZE_M),
107
+ "SE": (nw_e + TILE_SIZE_M, nw_n - TILE_SIZE_M),
108
+ }
109
+
110
+ # 3) Per file: compute translation from local top-left (minX, maxY) to target top-left
111
+ for fname in INPUT_FILES:
112
+ in_path = root / fname
113
+ if not in_path.exists():
114
+ print(f"[SKIP] File not found: {in_path}")
115
+ continue
116
+
117
+ # Determine the direction from the filename
118
+ up = fname.upper()
119
+ if "NW" in up and "TQ3280NW" in up:
120
+ key = "NW"
121
+ elif "NE" in up:
122
+ key = "NE"
123
+ elif "SW" in up:
124
+ key = "SW"
125
+ elif "SE" in up:
126
+ key = "SE"
127
+ elif "NW" in up:
128
+ # Case where the name contains _NW
129
+ key = "NW"
130
+ else:
131
+ print(f"[WARN] Cannot infer direction from filename; treating as NW: {fname}")
132
+ key = "NW"
133
+
134
+ tgt_e, tgt_n = targets[key]
135
+
136
+ # Read the local bbox
137
+ mins, maxs, scales, offsets = read_bbox(in_path)
138
+ minX, minY = float(mins[0]), float(mins[1])
139
+ maxX, maxY = float(maxs[0]), float(maxs[1])
140
+
141
+ # Local top-left corner (north-west) = (minX, maxY)
142
+ local_left_top = np.array([minX, maxY], dtype=float)
143
+ target_left_top = np.array([tgt_e, tgt_n], dtype=float)
144
+
145
+ # Translation t = target - local
146
+ t = target_left_top - local_left_top
147
+ tx, ty = float(t[0]), float(t[1])
148
+
149
+ # Print diagnostic info
150
+ print(f"\n=== {fname} ===")
151
+ print(f"Local bbox X:[{minX:.3f}, {maxX:.3f}] Y:[{minY:.3f}, {maxY:.3f}]")
152
+ print(f"Local top-left (NW local) = ({local_left_top[0]:.3f}, {local_left_top[1]:.3f})")
153
+ print(f"Target top-left (NW target EPSG:{TARGET_EPSG}) = ({target_left_top[0]:.3f}, {target_left_top[1]:.3f})")
154
+ print(f"Translation (tx, ty) = ({tx:.3f}, {ty:.3f}) [units: meters, projected coords]")
155
+
156
+ out_path = in_path.with_name(in_path.stem + OUT_SUFFIX)
157
+ apply_translation(in_path, out_path, tx, ty, TARGET_EPSG)
158
+ print(f"Written: {out_path.name} (EPSG:{TARGET_EPSG} set)")
159
+
160
+ print("\nDone. Load *_georef.las into QGIS and set the project CRS to EPSG:%d (or enable on-the-fly reprojection)." % TARGET_EPSG)
161
+
162
+ if __name__ == "__main__":
163
+ main()
scripts/holicity/export_las_blocks_noKML.py ADDED
@@ -0,0 +1,1048 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ HoliCity (London) LAS tiler for the City3D-MultiGen reconstruction pipeline.
3
+
4
+ Pipeline role:
5
+ This script implements the per-block tiling stage of the City3D-MultiGen
6
+ dataset pipeline used in the ECCV 2026 "GridFlow" paper. For the HoliCity
7
+ (London) source, dense point clouds are first sampled from the original FBX
8
+ meshes using CloudCompare and saved as LAS/LAZ. This script then partitions
9
+ those point clouds into regular 150m x 150m ground blocks and renders the
10
+ per-tile products consumed by downstream training/evaluation.
11
+
12
+ Inputs:
13
+ - LAS/LAZ point clouds sampled from HoliCity FBX meshes via CloudCompare,
14
+ placed in TILE_DIR. Files are auto-scanned (or listed explicitly), and
15
+ their georeferencing/CRS is read from the LAS headers (London uses the
16
+ OSGB / EPSG:27700 family; UTM is auto-detected as a fallback).
17
+
18
+ Outputs (one set per grid cell, written to OUTPUT_DIR):
19
+ - Per-tile cropped point cloud (grid_NNNNNN.las / .laz)
20
+ - DSM as GeoTIFF + normalized PNG (grid_NNNNNN_dsm.tif / _dsm.png)
21
+ - BEV top-down RGBA render (grid_NNNNNN_bev.png)
22
+ - Per-tile JSON log plus a global processing_summary.json and an
23
+ output_grids.kml visualization of the generated grid layout.
24
+
25
+ Key steps:
26
+ 1. Read each input LAS boundary and build one WGS84 polygon per file.
27
+ 2. Generate a regular grid of cells (with configurable overlap/spacing)
28
+ restricted to cells whose center falls inside an input polygon.
29
+ 3. Optionally scan all tiles for a global elevation range (for DSM scaling).
30
+ 4. For each cell: find overlapping tiles, crop the points, optionally voxel
31
+ downsample, then render the BEV and DSM and write logs. Supports resume
32
+ mode to skip already-completed cells.
33
+
34
+ External tools:
35
+ - PDAL is invoked via subprocess (`pdal pipeline`) to crop/merge tiles.
36
+ - GDAL/OSR (osgeo) is used to write georeferenced DSM GeoTIFFs.
37
+ - laspy, numpy, Pillow, scipy, pyproj and tqdm provide IO and processing.
38
+ """
39
+
40
+ import json
41
+ import os
42
+ import subprocess
43
+ import tempfile
44
+ from pathlib import Path
45
+ from pyproj import Transformer
46
+ from typing import List, Tuple, Dict
47
+ import laspy
48
+ import numpy as np
49
+ from PIL import Image
50
+ from tqdm import tqdm
51
+ from scipy.ndimage import uniform_filter
52
+
53
+ GRID_SIZE = 150
54
+ GRID_SPACING = -145
55
+ INPUT_LAS_FILES = None
56
+ TILE_DIR = "./LAS"
57
+ OUTPUT_DIR = "./output"
58
+ VOXEL_SIZE = 0.05
59
+ TEST_MODE_LIMIT = None
60
+ DEBUG_MODE = False
61
+ USE_VOXEL_FILTER = False
62
+ PYTHON_VOXEL_DEDUP = False
63
+ OUTPUT_COMPRESSED = False
64
+
65
+ RESUME_MODE = True
66
+ FORCE_REPROCESS = False
67
+
68
+ BEV_POINT_SIZE = 8
69
+ BEV_TRANSPARENT_BG = True
70
+ BEV_USE_RGB = True
71
+ BEV_POINT_OPACITY = 1.0
72
+ BEV_OPACITY_MODE = "fixed"
73
+
74
+ BEV_ADAPTIVE_POINT_SIZE = True
75
+ BEV_POINT_SIZE_MIN = 1
76
+ BEV_POINT_SIZE_MAX = 15
77
+ BEV_DENSITY_WINDOW = 10
78
+
79
+ MEMORY_OPTIMIZATION = True
80
+ BEV_RESOLUTION = 1024
81
+ MAX_POINTS_IN_MEMORY = 10000000
82
+
83
+ GENERATE_DSM = True
84
+ DSM_RESOLUTION = 256
85
+ DSM_POINT_SIZE = 3
86
+ DSM_USE_GLOBAL_RANGE = True
87
+
88
+ def parse_las_boundaries(las_files: List[str], tile_dir: str) -> Tuple[List[List[Tuple[float, float]]], str]:
89
+ if las_files is None or len(las_files) == 0:
90
+ print(f"AUTO-SCAN MODE: Scanning all LAS files in {tile_dir}")
91
+ las_paths = list(Path(tile_dir).glob("*.las")) + list(Path(tile_dir).glob("*.laz"))
92
+ las_paths = [f for f in las_paths if not f.name.startswith("grid_")]
93
+ las_files = [f.name for f in las_paths]
94
+
95
+ if len(las_files) == 0:
96
+ raise ValueError(f"No LAS files found in {tile_dir}")
97
+
98
+ print(f"Found {len(las_files)} LAS files:")
99
+ for f in las_files:
100
+ print(f" - {f}")
101
+ else:
102
+ print(f"MANUAL MODE: Using {len(las_files)} specified files")
103
+
104
+ print(f"\nReading boundaries from {len(las_files)} LAS files")
105
+ print("Creating individual polygons for each input file to preserve neighboring relationships")
106
+
107
+ all_bounds = []
108
+ crs_list = []
109
+
110
+ for las_file in las_files:
111
+ las_path = os.path.join(tile_dir, las_file)
112
+ if not os.path.exists(las_path):
113
+ print(f"Warning: File not found: {las_path}")
114
+ continue
115
+
116
+ try:
117
+ with laspy.open(las_path) as f:
118
+ header = f.header
119
+ bounds = {
120
+ 'file': las_file,
121
+ 'min_x': header.x_min,
122
+ 'max_x': header.x_max,
123
+ 'min_y': header.y_min,
124
+ 'max_y': header.y_max
125
+ }
126
+ all_bounds.append(bounds)
127
+
128
+ if hasattr(header, 'parse_crs'):
129
+ crs = header.parse_crs()
130
+ if crs:
131
+ crs_list.append(str(crs))
132
+
133
+ print(f" {las_file}: X=[{bounds['min_x']:.2f}, {bounds['max_x']:.2f}], Y=[{bounds['min_y']:.2f}, {bounds['max_y']:.2f}]")
134
+ except Exception as e:
135
+ print(f"Error reading {las_file}: {e}")
136
+ continue
137
+
138
+ if not all_bounds:
139
+ raise ValueError("No valid LAS files found")
140
+
141
+ overall_min_x = min(b['min_x'] for b in all_bounds)
142
+ overall_max_x = max(b['max_x'] for b in all_bounds)
143
+ overall_min_y = min(b['min_y'] for b in all_bounds)
144
+ overall_max_y = max(b['max_y'] for b in all_bounds)
145
+
146
+ print(f"\nOverall boundary: X=[{overall_min_x:.2f}, {overall_max_x:.2f}], Y=[{overall_min_y:.2f}, {overall_max_y:.2f}]")
147
+
148
+ if crs_list:
149
+ detected_crs = crs_list[0]
150
+ print(f"Detected CRS: {detected_crs}")
151
+ if 'EPSG:' in detected_crs:
152
+ utm_crs = detected_crs.split('EPSG:')[1].split()[0]
153
+ utm_crs = f"EPSG:{utm_crs}"
154
+ else:
155
+ print("Warning: Could not parse EPSG code, using auto-detection")
156
+ center_x = (overall_min_x + overall_max_x) / 2
157
+ center_y = (overall_min_y + overall_max_y) / 2
158
+ utm_crs = auto_detect_utm_from_coords(center_x, center_y)
159
+ else:
160
+ print("Warning: No CRS found in LAS headers, using auto-detection")
161
+ center_x = (overall_min_x + overall_max_x) / 2
162
+ center_y = (overall_min_y + overall_max_y) / 2
163
+ utm_crs = auto_detect_utm_from_coords(center_x, center_y)
164
+
165
+ print(f"Using UTM CRS: {utm_crs}")
166
+
167
+ transformer_to_wgs = Transformer.from_crs(utm_crs, "EPSG:4326", always_xy=True)
168
+
169
+ polygons_wgs84 = []
170
+ for i, bounds in enumerate(all_bounds):
171
+ rectangle_utm = [
172
+ (bounds['min_x'], bounds['max_y']),
173
+ (bounds['max_x'], bounds['max_y']),
174
+ (bounds['max_x'], bounds['min_y']),
175
+ (bounds['min_x'], bounds['min_y'])
176
+ ]
177
+
178
+ rectangle_wgs84 = []
179
+ for x, y in rectangle_utm:
180
+ lon, lat = transformer_to_wgs.transform(x, y)
181
+ rectangle_wgs84.append((lon, lat))
182
+
183
+ polygons_wgs84.append(rectangle_wgs84)
184
+ print(f" Created polygon {i+1} for {bounds['file']}")
185
+
186
+ print(f"\nCreated {len(polygons_wgs84)} individual polygons (one per input file)")
187
+ print("Grids will only be generated where they overlap with these polygons")
188
+
189
+ return polygons_wgs84, utm_crs
190
+
191
+ def auto_detect_utm_from_coords(x: float, y: float) -> str:
192
+ if 100000 < x < 900000 and 1000000 < y < 10000000:
193
+ if y > 5000000:
194
+ zone = int((x + 500000) / 1000000) + 30
195
+ return f"EPSG:326{zone:02d}"
196
+ else:
197
+ zone = int((x + 500000) / 1000000) + 30
198
+ return f"EPSG:327{zone:02d}"
199
+ else:
200
+ print(f"Warning: Coordinates ({x}, {y}) do not match typical UTM range")
201
+ return "EPSG:32650"
202
+
203
+ def get_utm_zone(lon: float, lat: float) -> str:
204
+ zone = int((lon + 180) / 6) + 1
205
+ hemisphere = 'north' if lat >= 0 else 'south'
206
+ return f"EPSG:326{zone:02d}" if hemisphere == 'north' else f"EPSG:327{zone:02d}"
207
+
208
+ def point_in_polygon(point: Tuple[float, float], polygon: List[Tuple[float, float]]) -> bool:
209
+ x, y = point
210
+ n = len(polygon)
211
+ inside = False
212
+
213
+ p1x, p1y = polygon[0]
214
+ for i in range(1, n + 1):
215
+ p2x, p2y = polygon[i % n]
216
+ if y > min(p1y, p2y):
217
+ if y <= max(p1y, p2y):
218
+ if x <= max(p1x, p2x):
219
+ if p1y != p2y:
220
+ xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
221
+ if p1x == p2x or x <= xinters:
222
+ inside = not inside
223
+ p1x, p1y = p2x, p2y
224
+
225
+ return inside
226
+
227
+ def generate_grids(polygons_wgs84: List[List[Tuple[float, float]]],
228
+ grid_size: float,
229
+ spacing: float,
230
+ utm_crs: str,
231
+ transformer_to_utm,
232
+ transformer_to_wgs) -> List[Dict]:
233
+
234
+ polygons_utm = []
235
+ for poly_wgs in polygons_wgs84:
236
+ poly_utm = [transformer_to_utm.transform(lon, lat) for lon, lat in poly_wgs]
237
+ polygons_utm.append(poly_utm)
238
+
239
+ all_utm_points = [p for poly in polygons_utm for p in poly]
240
+ min_x = min(p[0] for p in all_utm_points)
241
+ max_x = max(p[0] for p in all_utm_points)
242
+ min_y = min(p[1] for p in all_utm_points)
243
+ max_y = max(p[1] for p in all_utm_points)
244
+
245
+ print(f"Grid generation boundary: X=[{min_x:.2f}, {max_x:.2f}], Y=[{min_y:.2f}, {max_y:.2f}]")
246
+ print(f"Area size: {max_x-min_x:.2f}m x {max_y-min_y:.2f}m")
247
+
248
+ grids = []
249
+ grid_id = 0
250
+
251
+ y = min_y
252
+ row = 0
253
+ while y < max_y:
254
+ x = min_x
255
+ col = 0
256
+ while x < max_x:
257
+ center_x = x + grid_size / 2
258
+ center_y = y + grid_size / 2
259
+ center_lon, center_lat = transformer_to_wgs.transform(center_x, center_y)
260
+
261
+ is_in_any_polygon = False
262
+ for poly_wgs in polygons_wgs84:
263
+ if point_in_polygon((center_lon, center_lat), poly_wgs):
264
+ is_in_any_polygon = True
265
+ break
266
+
267
+ if is_in_any_polygon:
268
+ nw_lon, nw_lat = transformer_to_wgs.transform(x, y + grid_size)
269
+ se_lon, se_lat = transformer_to_wgs.transform(x + grid_size, y)
270
+
271
+ grid = {
272
+ 'id': grid_id,
273
+ 'row': row,
274
+ 'col': col,
275
+ 'utm_nw': (x, y + grid_size),
276
+ 'utm_se': (x + grid_size, y),
277
+ 'wgs84_nw': (nw_lon, nw_lat),
278
+ 'wgs84_se': (se_lon, se_lat),
279
+ 'center_wgs84': (center_lon, center_lat)
280
+ }
281
+ grids.append(grid)
282
+ grid_id += 1
283
+
284
+ x += (grid_size + spacing)
285
+ col += 1
286
+
287
+ y += (grid_size + spacing)
288
+ row += 1
289
+
290
+ print(f"Generated {len(grids)} grids that overlap with input polygons")
291
+ return grids
292
+
293
+ def create_kml(grids: List[Dict], output_path: str):
294
+ kml_header = '''<?xml version="1.0" encoding="UTF-8"?>
295
+ <kml xmlns="http://www.opengis.net/kml/2.2">
296
+ <Document>
297
+ <name>Grid Boundaries</name>
298
+ <Style id="gridStyle">
299
+ <LineStyle>
300
+ <color>ff0000ff</color>
301
+ <width>2</width>
302
+ </LineStyle>
303
+ <PolyStyle>
304
+ <color>330000ff</color>
305
+ </PolyStyle>
306
+ </Style>
307
+ '''
308
+
309
+ kml_footer = ''' </Document>
310
+ </kml>'''
311
+
312
+ with open(output_path, 'w') as f:
313
+ f.write(kml_header)
314
+
315
+ for grid in grids:
316
+ nw_lon, nw_lat = grid['wgs84_nw']
317
+ se_lon, se_lat = grid['wgs84_se']
318
+
319
+ ne_lon, ne_lat = se_lon, nw_lat
320
+ sw_lon, sw_lat = nw_lon, se_lat
321
+
322
+ placemark = f''' <Placemark>
323
+ <name>Grid {grid['id']:06d}</name>
324
+ <description>Row: {grid['row']}, Col: {grid['col']}</description>
325
+ <styleUrl>#gridStyle</styleUrl>
326
+ <Polygon>
327
+ <outerBoundaryIs>
328
+ <LinearRing>
329
+ <coordinates>
330
+ {nw_lon},{nw_lat},0
331
+ {ne_lon},{ne_lat},0
332
+ {se_lon},{se_lat},0
333
+ {sw_lon},{sw_lat},0
334
+ {nw_lon},{nw_lat},0
335
+ </coordinates>
336
+ </LinearRing>
337
+ </outerBoundaryIs>
338
+ </Polygon>
339
+ </Placemark>
340
+ '''
341
+ f.write(placemark)
342
+
343
+ f.write(kml_footer)
344
+
345
+ print(f"KML file created: {output_path}")
346
+
347
+ def get_tile_bounds(tile_dir: str) -> Dict[str, Dict]:
348
+ tile_bounds = {}
349
+ las_files = list(Path(tile_dir).glob("*.las")) + list(Path(tile_dir).glob("*.laz"))
350
+ las_files = [f for f in las_files if not f.name.startswith("grid_")]
351
+
352
+ print(f"Scanning {len(las_files)} tiles for bounds...")
353
+
354
+ for las_file in las_files:
355
+ try:
356
+ with laspy.open(str(las_file)) as f:
357
+ header = f.header
358
+ tile_bounds[las_file.name] = {
359
+ 'min_x': header.x_min,
360
+ 'max_x': header.x_max,
361
+ 'min_y': header.y_min,
362
+ 'max_y': header.y_max
363
+ }
364
+ except Exception as e:
365
+ print(f"Error reading {las_file.name}: {e}")
366
+
367
+ print(f"Successfully scanned {len(tile_bounds)} tiles")
368
+ return tile_bounds
369
+
370
+ def scan_global_elevation_range(tile_dir: str, tile_bounds: Dict) -> Tuple[float, float]:
371
+ print("\n" + "="*60)
372
+ print("Scanning global elevation range from all tiles...")
373
+ print("="*60)
374
+
375
+ global_min_z = float('inf')
376
+ global_max_z = float('-inf')
377
+ tiles_processed = 0
378
+
379
+ for tile_file in tqdm(tile_bounds.keys(), desc="Scanning tiles", unit="tile"):
380
+ tile_path = os.path.join(tile_dir, tile_file)
381
+ try:
382
+ with laspy.open(tile_path) as f:
383
+ las = f.read()
384
+ if las.header.point_count > 0:
385
+ z = np.array(las.z)
386
+ tile_min = float(z.min())
387
+ tile_max = float(z.max())
388
+ global_min_z = min(global_min_z, tile_min)
389
+ global_max_z = max(global_max_z, tile_max)
390
+ tiles_processed += 1
391
+ except Exception as e:
392
+ print(f"Error reading {tile_file}: {e}")
393
+ continue
394
+
395
+ if global_min_z == float('inf') or global_max_z == float('-inf'):
396
+ print("Warning: Could not determine global elevation range, will use local ranges")
397
+ return None, None
398
+
399
+ print(f"\nGlobal elevation range from {tiles_processed} tiles:")
400
+ print(f" Min elevation: {global_min_z:.2f}m")
401
+ print(f" Max elevation: {global_max_z:.2f}m")
402
+ print(f" Range: {global_max_z - global_min_z:.2f}m")
403
+
404
+ return global_min_z, global_max_z
405
+
406
+ def find_overlapping_tiles(grid: Dict, tile_bounds: Dict) -> List[str]:
407
+ grid_min_x, grid_max_y = grid['utm_nw']
408
+ grid_max_x, grid_min_y = grid['utm_se']
409
+
410
+ overlapping = []
411
+ for tile_name, bounds in tile_bounds.items():
412
+ if not (bounds['max_x'] < grid_min_x or bounds['min_x'] > grid_max_x or
413
+ bounds['max_y'] < grid_min_y or bounds['min_y'] > grid_max_y):
414
+ overlapping.append(tile_name)
415
+
416
+ return overlapping
417
+
418
+ def crop_las_with_pdal(tile_files: List[str], grid: Dict, output_path: str, tile_dir: str) -> Dict:
419
+ try:
420
+ min_x, max_y = grid['utm_nw']
421
+ max_x, min_y = grid['utm_se']
422
+
423
+ input_files = [os.path.join(tile_dir, f) for f in tile_files]
424
+
425
+ pipeline = {
426
+ "pipeline": []
427
+ }
428
+
429
+ for input_file in input_files:
430
+ pipeline["pipeline"].append(input_file)
431
+
432
+ bounds_str = f"([{min_x}, {max_x}], [{min_y}, {max_y}])"
433
+
434
+ filters = [
435
+ {
436
+ "type": "filters.crop",
437
+ "bounds": bounds_str
438
+ }
439
+ ]
440
+
441
+ if USE_VOXEL_FILTER and len(tile_files) > 1:
442
+ filters.append({
443
+ "type": "filters.voxelcenternearestneighbor",
444
+ "cell": VOXEL_SIZE
445
+ })
446
+
447
+ filters.append({
448
+ "type": "writers.las",
449
+ "filename": output_path,
450
+ "compression": "laszip" if OUTPUT_COMPRESSED else "none"
451
+ })
452
+
453
+ pipeline["pipeline"].extend(filters)
454
+
455
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
456
+ json.dump(pipeline, f, indent=2)
457
+ pipeline_file = f.name
458
+
459
+ try:
460
+ result = subprocess.run(
461
+ ['pdal', 'pipeline', pipeline_file],
462
+ capture_output=True,
463
+ text=True,
464
+ timeout=300
465
+ )
466
+
467
+ if result.returncode != 0:
468
+ return {
469
+ 'success': False,
470
+ 'error': f"PDAL error: {result.stderr}",
471
+ 'point_count': 0
472
+ }
473
+
474
+ if not os.path.exists(output_path):
475
+ return {
476
+ 'success': False,
477
+ 'error': 'Output file not created',
478
+ 'point_count': 0
479
+ }
480
+
481
+ with laspy.open(output_path) as f:
482
+ point_count = f.header.point_count
483
+
484
+ return {
485
+ 'success': True,
486
+ 'point_count': point_count,
487
+ 'tiles_used': tile_files
488
+ }
489
+
490
+ finally:
491
+ if os.path.exists(pipeline_file):
492
+ os.remove(pipeline_file)
493
+
494
+ except subprocess.TimeoutExpired:
495
+ return {
496
+ 'success': False,
497
+ 'error': 'PDAL pipeline timeout',
498
+ 'point_count': 0
499
+ }
500
+ except Exception as e:
501
+ return {
502
+ 'success': False,
503
+ 'error': str(e),
504
+ 'point_count': 0
505
+ }
506
+
507
+ def voxel_downsample_python(input_las: str, output_las: str, voxel_size: float) -> int:
508
+ with laspy.open(input_las) as f:
509
+ las = f.read()
510
+
511
+ x = np.array(las.x)
512
+ y = np.array(las.y)
513
+ z = np.array(las.z)
514
+
515
+ voxel_x = np.floor(x / voxel_size).astype(np.int32)
516
+ voxel_y = np.floor(y / voxel_size).astype(np.int32)
517
+ voxel_z = np.floor(z / voxel_size).astype(np.int32)
518
+
519
+ voxel_keys = np.column_stack([voxel_x, voxel_y, voxel_z])
520
+ unique_voxels, unique_indices = np.unique(voxel_keys, axis=0, return_index=True)
521
+
522
+ las_filtered = laspy.LasData(las.header)
523
+ las_filtered.points = las.points[unique_indices]
524
+
525
+ las_filtered.write(output_las)
526
+
527
+ return len(unique_indices)
528
+
529
+ def generate_bev_png(las_path: str, output_path: str, grid: Dict):
530
+ try:
531
+ with laspy.open(las_path) as f:
532
+ las = f.read()
533
+
534
+ if las.header.point_count == 0:
535
+ if DEBUG_MODE:
536
+ print(f" BEV: Empty point cloud")
537
+ img = Image.new('RGBA', (BEV_RESOLUTION, BEV_RESOLUTION), (0, 0, 0, 0) if BEV_TRANSPARENT_BG else (255, 255, 255, 255))
538
+ img.save(output_path)
539
+ return
540
+
541
+ x = np.array(las.x)
542
+ y = np.array(las.y)
543
+
544
+ minx = grid['utm_nw'][0]
545
+ maxx = grid['utm_se'][0]
546
+ miny = grid['utm_se'][1]
547
+ maxy = grid['utm_nw'][1]
548
+
549
+ px = ((x - minx) / (maxx - minx) * (BEV_RESOLUTION - 1)).astype(np.int32)
550
+ py = ((maxy - y) / (maxy - miny) * (BEV_RESOLUTION - 1)).astype(np.int32)
551
+
552
+ valid = (px >= 0) & (px < BEV_RESOLUTION) & (py >= 0) & (py < BEV_RESOLUTION)
553
+ px = px[valid]
554
+ py = py[valid]
555
+
556
+ if len(px) == 0:
557
+ if DEBUG_MODE:
558
+ print(f" BEV: No valid points")
559
+ img = Image.new('RGBA', (BEV_RESOLUTION, BEV_RESOLUTION), (0, 0, 0, 0) if BEV_TRANSPARENT_BG else (255, 255, 255, 255))
560
+ img.save(output_path)
561
+ return
562
+
563
+ if BEV_USE_RGB and hasattr(las, 'red'):
564
+ r = np.array(las.red)[valid] // 256
565
+ g = np.array(las.green)[valid] // 256
566
+ b = np.array(las.blue)[valid] // 256
567
+ else:
568
+ r = g = b = None
569
+
570
+ img_array = np.zeros((BEV_RESOLUTION, BEV_RESOLUTION, 4), dtype=np.uint8)
571
+ if not BEV_TRANSPARENT_BG:
572
+ img_array[:, :, :3] = 255
573
+ img_array[:, :, 3] = 255
574
+
575
+ if BEV_ADAPTIVE_POINT_SIZE:
576
+ density_map = np.zeros((BEV_RESOLUTION, BEV_RESOLUTION), dtype=np.int32)
577
+ for i in range(len(px)):
578
+ density_map[py[i], px[i]] += 1
579
+
580
+ density_smoothed = uniform_filter(density_map.astype(np.float32), size=BEV_DENSITY_WINDOW)
581
+ max_density = density_smoothed.max()
582
+ if max_density > 0:
583
+ density_normalized = density_smoothed / max_density
584
+ else:
585
+ density_normalized = density_smoothed
586
+
587
+ for i in range(len(px)):
588
+ if BEV_ADAPTIVE_POINT_SIZE:
589
+ density_value = density_normalized[py[i], px[i]]
590
+ point_size = int(BEV_POINT_SIZE_MIN + (BEV_POINT_SIZE_MAX - BEV_POINT_SIZE_MIN) * (1 - density_value))
591
+ else:
592
+ point_size = BEV_POINT_SIZE
593
+
594
+ half_size = point_size // 2
595
+ x_start = max(0, px[i] - half_size)
596
+ x_end = min(BEV_RESOLUTION, px[i] + half_size + 1)
597
+ y_start = max(0, py[i] - half_size)
598
+ y_end = min(BEV_RESOLUTION, py[i] + half_size + 1)
599
+
600
+ if BEV_OPACITY_MODE == "fixed":
601
+ alpha = int(BEV_POINT_OPACITY * 255)
602
+ else:
603
+ alpha = 255
604
+
605
+ if r is not None:
606
+ color = [r[i], g[i], b[i]]
607
+ else:
608
+ color = [0, 0, 0]
609
+
610
+ img_array[y_start:y_end, x_start:x_end, :3] = color
611
+ img_array[y_start:y_end, x_start:x_end, 3] = alpha
612
+
613
+ img = Image.fromarray(img_array)
614
+ img.save(output_path)
615
+ if DEBUG_MODE:
616
+ print(f" BEV: Saved to {output_path}")
617
+
618
+ except Exception as e:
619
+ print(f" BEV: Error generating BEV: {e}")
620
+ if DEBUG_MODE:
621
+ import traceback
622
+ traceback.print_exc()
623
+ img = Image.new('RGBA', (BEV_RESOLUTION, BEV_RESOLUTION), (0, 0, 0, 0) if BEV_TRANSPARENT_BG else (255, 255, 255, 255))
624
+ img.save(output_path)
625
+
626
+ def generate_dsm(las_path: str, output_geotiff: str, output_png: str, grid: Dict,
627
+ resolution: int = 1024, global_min_z: float = None, global_max_z: float = None) -> Dict:
628
+ try:
629
+ from osgeo import gdal, osr
630
+
631
+ with laspy.open(las_path) as f:
632
+ las = f.read()
633
+
634
+ if las.header.point_count == 0:
635
+ if DEBUG_MODE:
636
+ print(f" DSM: Empty point cloud")
637
+ return None
638
+
639
+ x = np.array(las.x)
640
+ y = np.array(las.y)
641
+ z = np.array(las.z)
642
+
643
+ minx = grid['utm_nw'][0]
644
+ maxx = grid['utm_se'][0]
645
+ miny = grid['utm_se'][1]
646
+ maxy = grid['utm_nw'][1]
647
+
648
+ cell_size_x = (maxx - minx) / resolution
649
+ cell_size_y = (maxy - miny) / resolution
650
+
651
+ px = ((x - minx) / (maxx - minx) * (resolution - 1)).astype(np.int32)
652
+ py = ((maxy - y) / (maxy - miny) * (resolution - 1)).astype(np.int32)
653
+
654
+ valid = (px >= 0) & (px < resolution) & (py >= 0) & (py < resolution)
655
+ px = px[valid]
656
+ py = py[valid]
657
+ z = z[valid]
658
+
659
+ if len(px) == 0:
660
+ if DEBUG_MODE:
661
+ print(f" DSM: No valid points")
662
+ return None
663
+
664
+ dsm = np.full((resolution, resolution), -9999.0, dtype=np.float32)
665
+
666
+ half_size = DSM_POINT_SIZE // 2
667
+
668
+ for i in range(len(px)):
669
+ cy, cx = py[i], px[i]
670
+
671
+ for dy in range(-half_size, half_size + 1):
672
+ for dx in range(-half_size, half_size + 1):
673
+ ny = cy + dy
674
+ nx = cx + dx
675
+
676
+ if 0 <= ny < resolution and 0 <= nx < resolution:
677
+ current_z = dsm[ny, nx]
678
+ if current_z == -9999.0 or z[i] > current_z:
679
+ dsm[ny, nx] = z[i]
680
+
681
+ mask = dsm != -9999.0
682
+ if not mask.any():
683
+ if DEBUG_MODE:
684
+ print(f" DSM: All cells empty")
685
+ return None
686
+
687
+ local_min_elevation = float(dsm[mask].min())
688
+ local_max_elevation = float(dsm[mask].max())
689
+
690
+ if DSM_USE_GLOBAL_RANGE and global_min_z is not None and global_max_z is not None:
691
+ use_min = global_min_z
692
+ use_max = global_max_z
693
+ if DEBUG_MODE:
694
+ print(f" DSM: Using global range {use_min:.2f}-{use_max:.2f}m (local: {local_min_elevation:.2f}-{local_max_elevation:.2f}m)")
695
+ else:
696
+ use_min = local_min_elevation
697
+ use_max = local_max_elevation
698
+ if DEBUG_MODE:
699
+ print(f" DSM: Using local range {use_min:.2f}-{use_max:.2f}m")
700
+
701
+ driver = gdal.GetDriverByName('GTiff')
702
+ dataset = driver.Create(output_geotiff, resolution, resolution, 1, gdal.GDT_Float32)
703
+
704
+ geotransform = (minx, cell_size_x, 0, maxy, 0, -cell_size_y)
705
+ dataset.SetGeoTransform(geotransform)
706
+
707
+ srs = osr.SpatialReference()
708
+ epsg_code = int(grid.get('utm_crs', 'EPSG:27700').split(':')[1]) if 'utm_crs' in grid else 27700
709
+ srs.ImportFromEPSG(epsg_code)
710
+ dataset.SetProjection(srs.ExportToWkt())
711
+
712
+ band = dataset.GetRasterBand(1)
713
+ band.SetNoDataValue(-9999.0)
714
+ band.WriteArray(dsm)
715
+
716
+ dataset.FlushCache()
717
+ dataset = None
718
+
719
+ dsm_normalized = np.where(dsm == -9999.0, 0,
720
+ np.clip((dsm - use_min) / (use_max - use_min), 0, 1) * 65535)
721
+ dsm_img = dsm_normalized.astype(np.uint16)
722
+
723
+ img = Image.fromarray(dsm_img)
724
+ img.save(output_png)
725
+
726
+ if DEBUG_MODE:
727
+ print(f" DSM: GeoTIFF and PNG saved")
728
+
729
+ return {
730
+ 'min_elevation': local_min_elevation,
731
+ 'max_elevation': local_max_elevation,
732
+ 'global_min_used': use_min,
733
+ 'global_max_used': use_max,
734
+ 'resolution': resolution,
735
+ 'cell_size_x': cell_size_x,
736
+ 'cell_size_y': cell_size_y
737
+ }
738
+
739
+ except ImportError:
740
+ print(f" DSM: Error - GDAL not installed. Install with: pip install gdal")
741
+ return None
742
+ except Exception as e:
743
+ print(f" DSM: Error - {e}")
744
+ if DEBUG_MODE:
745
+ import traceback
746
+ traceback.print_exc()
747
+ return None
748
+
749
+ def check_grid_already_processed(grid_id: int, output_dir: str) -> Dict:
750
+ file_ext = ".laz" if OUTPUT_COMPRESSED else ".las"
751
+ output_las = os.path.join(output_dir, f"grid_{grid_id:06d}{file_ext}")
752
+ output_bev = os.path.join(output_dir, f"grid_{grid_id:06d}_bev.png")
753
+ output_log = os.path.join(output_dir, f"grid_{grid_id:06d}.json")
754
+
755
+ required_files = [output_las, output_bev, output_log]
756
+
757
+ if GENERATE_DSM:
758
+ output_dsm_tif = os.path.join(output_dir, f"grid_{grid_id:06d}_dsm.tif")
759
+ output_dsm_png = os.path.join(output_dir, f"grid_{grid_id:06d}_dsm.png")
760
+ required_files.extend([output_dsm_tif, output_dsm_png])
761
+
762
+ if all(os.path.exists(f) for f in required_files):
763
+ try:
764
+ with open(output_log, 'r') as f:
765
+ log_data = json.load(f)
766
+
767
+ if all(os.path.getsize(f) > 0 for f in required_files):
768
+ return {
769
+ 'grid_id': grid_id,
770
+ 'status': 'success',
771
+ 'point_count': log_data.get('point_count', 0),
772
+ 'tiles_used': len(log_data.get('tiles_used', [])),
773
+ 'resumed': True
774
+ }
775
+ except Exception as e:
776
+ if DEBUG_MODE:
777
+ tqdm.write(f" DEBUG: Failed to read log for grid {grid_id}: {e}")
778
+ return None
779
+
780
+ return None
781
+
782
+ def process_single_grid(grid: Dict, tile_bounds: Dict, tile_dir: str, output_dir: str,
783
+ utm_crs: str, global_min_z: float = None, global_max_z: float = None) -> Dict:
784
+ grid_id = grid['id']
785
+
786
+ if RESUME_MODE and not FORCE_REPROCESS:
787
+ existing_result = check_grid_already_processed(grid_id, output_dir)
788
+ if existing_result:
789
+ return existing_result
790
+
791
+ if DEBUG_MODE:
792
+ print(f"\n DEBUG: Grid bounds UTM: NW={grid['utm_nw']}, SE={grid['utm_se']}")
793
+
794
+ overlapping_tiles = find_overlapping_tiles(grid, tile_bounds)
795
+
796
+ if DEBUG_MODE:
797
+ print(f" DEBUG: Found {len(overlapping_tiles)} overlapping tiles: {overlapping_tiles[:3]}...")
798
+
799
+ if not overlapping_tiles:
800
+ return {
801
+ 'grid_id': grid_id,
802
+ 'status': 'no_tiles',
803
+ 'message': 'No overlapping tiles found'
804
+ }
805
+
806
+ file_ext = ".laz" if OUTPUT_COMPRESSED else ".las"
807
+ output_las = os.path.join(output_dir, f"grid_{grid_id:06d}{file_ext}")
808
+ output_bev = os.path.join(output_dir, f"grid_{grid_id:06d}_bev.png")
809
+ output_log = os.path.join(output_dir, f"grid_{grid_id:06d}.json")
810
+
811
+ crop_result = crop_las_with_pdal(overlapping_tiles, grid, output_las, tile_dir)
812
+
813
+ if not crop_result['success']:
814
+ error_msg = crop_result.get('error', 'Unknown error')
815
+ return {
816
+ 'grid_id': grid_id,
817
+ 'status': 'failed',
818
+ 'message': error_msg,
819
+ 'tiles_checked': overlapping_tiles
820
+ }
821
+
822
+ if crop_result['point_count'] == 0:
823
+ return {
824
+ 'grid_id': grid_id,
825
+ 'status': 'empty',
826
+ 'message': 'No points in cropped area',
827
+ 'tiles_used': overlapping_tiles
828
+ }
829
+
830
+ if PYTHON_VOXEL_DEDUP and len(overlapping_tiles) > 1:
831
+ temp_output = output_las + ".temp"
832
+ os.rename(output_las, temp_output)
833
+ final_count = voxel_downsample_python(temp_output, output_las, VOXEL_SIZE)
834
+ os.remove(temp_output)
835
+ crop_result['point_count'] = final_count
836
+ if DEBUG_MODE:
837
+ print(f" DEBUG: Python voxel downsampled to {final_count} points")
838
+
839
+ generate_bev_png(output_las, output_bev, grid)
840
+
841
+ dsm_info = None
842
+ if GENERATE_DSM:
843
+ output_dsm_tif = os.path.join(output_dir, f"grid_{grid_id:06d}_dsm.tif")
844
+ output_dsm_png = os.path.join(output_dir, f"grid_{grid_id:06d}_dsm.png")
845
+ grid_with_crs = grid.copy()
846
+ grid_with_crs['utm_crs'] = utm_crs
847
+ dsm_info = generate_dsm(output_las, output_dsm_tif, output_dsm_png, grid_with_crs,
848
+ DSM_RESOLUTION, global_min_z, global_max_z)
849
+
850
+ log_data = {
851
+ 'grid_id': grid_id,
852
+ 'row': grid['row'],
853
+ 'col': grid['col'],
854
+ 'utm_nw': grid['utm_nw'],
855
+ 'utm_se': grid['utm_se'],
856
+ 'wgs84_nw': grid['wgs84_nw'],
857
+ 'wgs84_se': grid['wgs84_se'],
858
+ 'point_count': crop_result['point_count'],
859
+ 'tiles_used': crop_result['tiles_used'],
860
+ 'output_files': {
861
+ 'las': os.path.basename(output_las),
862
+ 'bev': os.path.basename(output_bev)
863
+ }
864
+ }
865
+
866
+ if GENERATE_DSM and dsm_info:
867
+ log_data['elevation'] = {
868
+ 'local_min_elevation': dsm_info['min_elevation'],
869
+ 'local_max_elevation': dsm_info['max_elevation'],
870
+ 'global_min_used': dsm_info['global_min_used'],
871
+ 'global_max_used': dsm_info['global_max_used'],
872
+ 'elevation_range': dsm_info['max_elevation'] - dsm_info['min_elevation']
873
+ }
874
+ log_data['output_files']['dsm_geotiff'] = os.path.basename(output_dsm_tif)
875
+ log_data['output_files']['dsm_png'] = os.path.basename(output_dsm_png)
876
+
877
+ with open(output_log, 'w') as f:
878
+ json.dump(log_data, f, indent=2)
879
+
880
+ return {
881
+ 'grid_id': grid_id,
882
+ 'status': 'success',
883
+ 'point_count': crop_result['point_count'],
884
+ 'tiles_used': len(overlapping_tiles)
885
+ }
886
+
887
+ def main():
888
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
889
+
890
+ if os.path.abspath(OUTPUT_DIR) == os.path.abspath(TILE_DIR):
891
+ print("ERROR: OUTPUT_DIR and TILE_DIR must be different!")
892
+ print(f"OUTPUT_DIR: {os.path.abspath(OUTPUT_DIR)}")
893
+ print(f"TILE_DIR: {os.path.abspath(TILE_DIR)}")
894
+ print("Please set OUTPUT_DIR to a different directory to avoid confusion.")
895
+ return
896
+
897
+ print("="*60)
898
+ print("STEP 1: Reading LAS boundaries and generating grids")
899
+ print("="*60)
900
+
901
+ polygons, utm_crs = parse_las_boundaries(INPUT_LAS_FILES, TILE_DIR)
902
+
903
+ transformer_to_utm = Transformer.from_crs("EPSG:4326", utm_crs, always_xy=True)
904
+ transformer_to_wgs = Transformer.from_crs(utm_crs, "EPSG:4326", always_xy=True)
905
+
906
+ grids = generate_grids(polygons, GRID_SIZE, GRID_SPACING,
907
+ utm_crs, transformer_to_utm, transformer_to_wgs)
908
+
909
+ print("\n" + "="*60)
910
+ print("STEP 2: Generating KML visualization")
911
+ print("="*60)
912
+
913
+ kml_output = os.path.join(OUTPUT_DIR, "output_grids.kml")
914
+ create_kml(grids, kml_output)
915
+
916
+ print("\n" + "="*60)
917
+ print("STEP 3: Scanning all LAS tiles")
918
+ print("="*60)
919
+
920
+ tile_bounds = get_tile_bounds(TILE_DIR)
921
+
922
+ if not tile_bounds:
923
+ print("ERROR: No valid tiles found!")
924
+ return
925
+
926
+ global_min_z = None
927
+ global_max_z = None
928
+
929
+ if GENERATE_DSM and DSM_USE_GLOBAL_RANGE:
930
+ global_min_z, global_max_z = scan_global_elevation_range(TILE_DIR, tile_bounds)
931
+
932
+ print("\n" + "="*60)
933
+ print("STEP 4: Processing grids and generating outputs")
934
+ print("="*60)
935
+
936
+ grids_to_process = grids[:TEST_MODE_LIMIT] if TEST_MODE_LIMIT else grids
937
+
938
+ if TEST_MODE_LIMIT:
939
+ print(f"\n*** TEST MODE: Processing only first {len(grids_to_process)} grids ***\n")
940
+ else:
941
+ print(f"\nProcessing all {len(grids_to_process)} grids\n")
942
+
943
+ if RESUME_MODE and not FORCE_REPROCESS:
944
+ print(f"*** RESUME MODE: Skipping already processed grids ***\n")
945
+ elif FORCE_REPROCESS:
946
+ print(f"*** FORCE REPROCESS: Reprocessing all grids ***\n")
947
+
948
+ if GENERATE_DSM:
949
+ print(f"DSM Configuration:")
950
+ print(f" Resolution: {DSM_RESOLUTION}x{DSM_RESOLUTION}")
951
+ print(f" Point size: {DSM_POINT_SIZE}x{DSM_POINT_SIZE} pixels per point")
952
+ print(f" Use global range: {DSM_USE_GLOBAL_RANGE}")
953
+ if DSM_USE_GLOBAL_RANGE and global_min_z is not None:
954
+ print(f" Global range: {global_min_z:.2f}m - {global_max_z:.2f}m\n")
955
+
956
+ results = []
957
+ resumed_count = 0
958
+ processed_count = 0
959
+
960
+ with tqdm(total=len(grids_to_process), desc="Processing grids", unit="grid") as pbar:
961
+ for i, grid in enumerate(grids_to_process):
962
+ grid_id = grid['id']
963
+ pbar.set_description(f"Processing grid {grid_id:06d}")
964
+
965
+ result = process_single_grid(grid, tile_bounds, TILE_DIR, OUTPUT_DIR, utm_crs,
966
+ global_min_z, global_max_z)
967
+ results.append(result)
968
+
969
+ if result.get('resumed', False):
970
+ resumed_count += 1
971
+ tqdm.write(f"Grid {grid_id:06d}: RESUMED - {result.get('point_count', 0):,} points (skipped)")
972
+ else:
973
+ processed_count += 1
974
+ if result['status'] == 'failed':
975
+ tqdm.write(f"Grid {grid_id:06d}: FAILED - {result.get('message', 'Unknown error')}")
976
+ elif result['status'] == 'success':
977
+ tqdm.write(f"Grid {grid_id:06d}: SUCCESS - {result.get('point_count', 0):,} points from {result.get('tiles_used', 0)} tiles")
978
+ elif result['status'] == 'empty':
979
+ tqdm.write(f"Grid {grid_id:06d}: EMPTY - No points in area")
980
+ elif result['status'] == 'no_tiles':
981
+ tqdm.write(f"Grid {grid_id:06d}: NO TILES - No overlapping tiles found")
982
+
983
+ pbar.update(1)
984
+
985
+ print("\n" + "="*60)
986
+ print("STEP 5: Generating final summary")
987
+ print("="*60)
988
+
989
+ summary = {
990
+ 'config': {
991
+ 'grid_size_m': GRID_SIZE,
992
+ 'grid_spacing_m': GRID_SPACING,
993
+ 'voxel_size_m': VOXEL_SIZE,
994
+ 'use_voxel_filter': USE_VOXEL_FILTER,
995
+ 'python_voxel_dedup': PYTHON_VOXEL_DEDUP,
996
+ 'output_compressed': OUTPUT_COMPRESSED,
997
+ 'bev_point_size': BEV_POINT_SIZE,
998
+ 'bev_transparent_bg': BEV_TRANSPARENT_BG,
999
+ 'bev_use_rgb': BEV_USE_RGB,
1000
+ 'bev_point_opacity': BEV_POINT_OPACITY,
1001
+ 'bev_opacity_mode': BEV_OPACITY_MODE,
1002
+ 'bev_adaptive_point_size': BEV_ADAPTIVE_POINT_SIZE,
1003
+ 'bev_point_size_min': BEV_POINT_SIZE_MIN,
1004
+ 'bev_point_size_max': BEV_POINT_SIZE_MAX,
1005
+ 'bev_density_window': BEV_DENSITY_WINDOW,
1006
+ 'generate_dsm': GENERATE_DSM,
1007
+ 'dsm_resolution': DSM_RESOLUTION,
1008
+ 'dsm_point_size': DSM_POINT_SIZE,
1009
+ 'dsm_use_global_range': DSM_USE_GLOBAL_RANGE,
1010
+ 'global_elevation_range': {
1011
+ 'min': global_min_z,
1012
+ 'max': global_max_z
1013
+ } if global_min_z is not None else None,
1014
+ 'utm_crs': utm_crs,
1015
+ 'test_mode': TEST_MODE_LIMIT is not None,
1016
+ 'test_mode_limit': TEST_MODE_LIMIT,
1017
+ 'resume_mode': RESUME_MODE,
1018
+ 'force_reprocess': FORCE_REPROCESS
1019
+ },
1020
+ 'statistics': {
1021
+ 'total_grids_generated': len(grids),
1022
+ 'grids_processed': len(grids_to_process),
1023
+ 'newly_processed': processed_count,
1024
+ 'resumed_skipped': resumed_count,
1025
+ 'successful': sum(1 for r in results if r['status'] == 'success'),
1026
+ 'failed': sum(1 for r in results if r['status'] == 'failed'),
1027
+ 'empty': sum(1 for r in results if r['status'] == 'empty'),
1028
+ 'no_tiles': sum(1 for r in results if r['status'] == 'no_tiles')
1029
+ },
1030
+ 'results': results
1031
+ }
1032
+
1033
+ summary_path = os.path.join(OUTPUT_DIR, "processing_summary.json")
1034
+ with open(summary_path, 'w') as f:
1035
+ json.dump(summary, f, indent=2)
1036
+
1037
+ print(f"\nSummary saved to: {summary_path}")
1038
+ print(f"KML visualization: {kml_output}")
1039
+ if TEST_MODE_LIMIT:
1040
+ print(f"Test mode: Processed {len(grids_to_process)}/{len(grids)} grids")
1041
+ if RESUME_MODE and resumed_count > 0:
1042
+ print(f"Resumed: Skipped {resumed_count} already processed grids")
1043
+ print(f"Newly processed: {processed_count} grids")
1044
+ print(f"Success: {summary['statistics']['successful']}/{len(grids_to_process)}")
1045
+ print("\nProcessing complete!")
1046
+
1047
+ if __name__ == "__main__":
1048
+ main()
scripts/make_splits.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Generate the exact train / val / test split used by City3D-MultiGen.
4
+
5
+ This replicates the deterministic split from the training dataloader:
6
+
7
+ all_files = sorted(list(Path(data_root).glob('**/grid_*.las')))
8
+ n_train = int(n_total * train_split)
9
+ n_val = int(n_total * val_split)
10
+ train = all_files[:n_train]
11
+ val = all_files[n_train:n_train + n_val]
12
+ test = all_files[n_train + n_val:]
13
+
14
+ There is **no shuffling and no random seed** — the split is a sequential slice of
15
+ the path-sorted tile list. Running this on the same assembled `output/` directory
16
+ therefore reproduces exactly the split used to produce the paper's results.
17
+
18
+ Because tile filenames (`grid_<id>`) are ordered along the spatial grid, this
19
+ path-sorted sequential split yields spatially contiguous train/val/test regions.
20
+
21
+ Usage:
22
+ python scripts/make_splits.py \
23
+ --data_root /path/to/output \
24
+ --train_split 0.8 --val_split 0.1 \
25
+ --out_dir metadata/splits
26
+ """
27
+ import argparse
28
+ from pathlib import Path
29
+
30
+
31
+ def main():
32
+ ap = argparse.ArgumentParser(description="Reproduce the City3D-MultiGen tile split.")
33
+ ap.add_argument("--data_root", required=True,
34
+ help="Directory containing the assembled tiles (grid_*/grid_*.las).")
35
+ ap.add_argument("--train_split", type=float, default=0.8)
36
+ ap.add_argument("--val_split", type=float, default=0.1)
37
+ ap.add_argument("--out_dir", default="metadata/splits")
38
+ args = ap.parse_args()
39
+
40
+ # Identical to the training dataloader: recursive glob, sorted by path.
41
+ all_files = sorted(list(Path(args.data_root).glob("**/grid_*.las")))
42
+ n = len(all_files)
43
+ if n == 0:
44
+ raise SystemExit(f"No grid_*.las files found under {args.data_root}")
45
+
46
+ n_train = int(n * args.train_split)
47
+ n_val = int(n * args.val_split)
48
+ splits = {
49
+ "train": all_files[:n_train],
50
+ "val": all_files[n_train:n_train + n_val],
51
+ "test": all_files[n_train + n_val:],
52
+ }
53
+
54
+ out = Path(args.out_dir)
55
+ out.mkdir(parents=True, exist_ok=True)
56
+ for name, files in splits.items():
57
+ ids = [f.stem for f in files] # e.g. "grid_120256"
58
+ (out / f"{name}.txt").write_text("\n".join(ids) + "\n")
59
+ print(f"{name:5s}: {len(ids):6d} tiles -> {out / (name + '.txt')}")
60
+ print(f"total: {n} tiles "
61
+ f"(train={n_train}, val={n_val}, test={n - n_train - n_val})")
62
+
63
+
64
+ if __name__ == "__main__":
65
+ main()
scripts/melbourne/Obtain_corresponding_map_signed.py ADDED
@@ -0,0 +1,490 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fetch per-tile imagery and derive semantic masks for the City3D-MultiGen
2
+ reconstruction pipeline (GridFlow, ECCV 2026).
3
+
4
+ Pipeline role:
5
+ For each 150 m tile this script downloads two co-registered rasters from the
6
+ signed Google Maps Static API -- a satellite image and a custom-styled
7
+ "roadmap" image -- then parses the styled roadmap into per-class binary
8
+ semantic masks using fixed color thresholds.
9
+
10
+ Inputs:
11
+ Tile geo-extents read from per-tile JSON metadata files (``wgs84_nw`` /
12
+ ``wgs84_se`` lon/lat corners). These JSONs can optionally be generated first
13
+ from an area bounding box (``--nw`` / ``--se``).
14
+
15
+ Outputs (written next to each JSON, keyed by the tile base name):
16
+ ``<base>_sat.png`` satellite crop, ``<base>_map.png`` styled roadmap crop,
17
+ and six mask images ``<base>_<Class>.png`` for the classes Building,
18
+ RoadSurface, Railway, VegetationLand, UrbanLand and WaterSurface.
19
+
20
+ Key steps:
21
+ 1. Build the Static Maps URL, sign it with the URL-signing secret (HMAC-SHA1).
22
+ 2. Fetch satellite and styled-roadmap tiles, then crop to the exact extent.
23
+ 3. Parse the roadmap crop into masks via the CLASS_COLORS_HEX color thresholds
24
+ (exact match per class; tolerant match plus 1 px dilation for Railway).
25
+
26
+ Required environment variables (each may be overridden by a CLI flag):
27
+ GOOGLE_MAPS_API_KEY Static Maps API key.
28
+ GOOGLE_MAPS_URL_SIGNING_SECRET URL-signing secret for the signed requests.
29
+ GOOGLE_MAPS_STYLE_MAP_ID Map ID of the custom roadmap style.
30
+
31
+ Note: the custom Google map style referenced by GOOGLE_MAPS_STYLE_MAP_ID is not
32
+ distributed here; you must recreate it in the Google Cloud console so the styled
33
+ roadmap colors match the CLASS_COLORS_HEX values used for mask parsing.
34
+ """
35
+
36
+ import os
37
+ import json
38
+ import math
39
+ import io
40
+ import time
41
+ import argparse
42
+ import requests
43
+ from requests.adapters import HTTPAdapter
44
+ from urllib3.util.retry import Retry
45
+ from PIL import Image
46
+ import numpy as np
47
+ from tqdm import tqdm
48
+ import hashlib
49
+ import hmac
50
+ import base64
51
+ import urllib.parse as urlparse
52
+ from pyproj import Transformer
53
+
54
+ CLASS_COLORS_HEX = {
55
+ "RoadSurface": ["1e1e1e"],
56
+ "Building": ["ff0000"],
57
+ "Railway": ["0073ff"],
58
+ "VegetationLand": ["c3f1d5"],
59
+ "UrbanLand": ["f5f0e5", "d3f8e2"],
60
+ "WaterSurface": ["90daee"],
61
+ }
62
+
63
+ def hex_to_rgb(hex_str):
64
+ h = hex_str.strip().lower()
65
+ return (
66
+ int(h[0:2], 16),
67
+ int(h[2:4], 16),
68
+ int(h[4:6], 16),
69
+ )
70
+
71
+ CLASS_COLORS_RGB = {
72
+ class_name: [hex_to_rgb(code) for code in hex_list]
73
+ for class_name, hex_list in CLASS_COLORS_HEX.items()
74
+ }
75
+
76
+ def sign_url(input_url, secret):
77
+ if not input_url or not secret:
78
+ raise Exception("Both input_url and secret are required")
79
+
80
+ url = urlparse.urlparse(input_url)
81
+ url_to_sign = url.path + "?" + url.query
82
+ decoded_key = base64.urlsafe_b64decode(secret)
83
+ signature = hmac.new(decoded_key, str.encode(url_to_sign), hashlib.sha1)
84
+ encoded_signature = base64.urlsafe_b64encode(signature.digest())
85
+ original_url = url.scheme + "://" + url.netloc + url.path + "?" + url.query
86
+ return original_url + "&signature=" + encoded_signature.decode()
87
+
88
+ def dilate_mask_1px(mask_arr):
89
+ h, w = mask_arr.shape
90
+ out = np.zeros((h, w), dtype=np.uint8)
91
+ ys, xs = np.nonzero(mask_arr > 0)
92
+ for y, x in zip(ys, xs):
93
+ y0 = max(y - 1, 0)
94
+ y1 = min(y + 1, h - 1)
95
+ x0 = max(x - 1, 0)
96
+ x1 = min(x + 1, w - 1)
97
+ out[y0:y1+1, x0:x1+1] = 255
98
+ return out
99
+
100
+ def match_mask_exact(arr, rgb_triplet):
101
+ r, g, b = rgb_triplet
102
+ return (
103
+ (arr[:, :, 0] == r) &
104
+ (arr[:, :, 1] == g) &
105
+ (arr[:, :, 2] == b)
106
+ )
107
+
108
+ def channel_bounds_with_margin(channel_val, margin_ratio):
109
+ low = int(round(channel_val * (1.0 - margin_ratio)))
110
+ high = int(round(channel_val * (1.0 + margin_ratio)))
111
+ if low < 0:
112
+ low = 0
113
+ if high > 255:
114
+ high = 255
115
+ return low, high
116
+
117
+ def match_mask_tolerant(arr, rgb_triplet, margin_ratio):
118
+ r, g, b = rgb_triplet
119
+ rl, rh = channel_bounds_with_margin(r, margin_ratio)
120
+ gl, gh = channel_bounds_with_margin(g, margin_ratio)
121
+ bl, bh = channel_bounds_with_margin(b, margin_ratio)
122
+ return (
123
+ (arr[:, :, 0] >= rl) & (arr[:, :, 0] <= rh) &
124
+ (arr[:, :, 1] >= gl) & (arr[:, :, 1] <= gh) &
125
+ (arr[:, :, 2] >= bl) & (arr[:, :, 2] <= bh)
126
+ )
127
+
128
+ def generate_masks_from_roadmap(crop_road_img, base_output_path_no_ext):
129
+ rgb = crop_road_img.convert("RGB")
130
+ arr = np.array(rgb, dtype=np.uint8)
131
+
132
+ for class_name, rgb_list in CLASS_COLORS_RGB.items():
133
+ class_mask_total = np.zeros(arr.shape[:2], dtype=np.uint8)
134
+
135
+ for rgb_triplet in rgb_list:
136
+ if class_name == "Railway":
137
+ match = match_mask_tolerant(arr, rgb_triplet, margin_ratio=0.1)
138
+ else:
139
+ match = match_mask_exact(arr, rgb_triplet)
140
+ class_mask_total[match] = 255
141
+
142
+ if class_name == "Railway":
143
+ class_mask_total = dilate_mask_1px(class_mask_total)
144
+
145
+ out_path = f"{base_output_path_no_ext}_{class_name}.png"
146
+ img = Image.fromarray(class_mask_total)
147
+ img.save(out_path)
148
+
149
+ def save_bbox_satellite_and_roadmap(
150
+ north_lat,
151
+ west_lon,
152
+ south_lat,
153
+ east_lon,
154
+ out_path_sat,
155
+ out_path_road,
156
+ api_key,
157
+ url_signing_secret,
158
+ style_map_id
159
+ ):
160
+ def mercator_project(lon_deg, lat_deg, zoom):
161
+ scale = 256 * (2 ** zoom)
162
+ x = (lon_deg + 180.0) / 360.0 * scale
163
+ lat_rad = math.radians(lat_deg)
164
+ y = (1.0 - math.log(math.tan(lat_rad) + 1.0 / math.cos(lat_rad)) / math.pi) / 2.0 * scale
165
+ return x, y
166
+
167
+ def bbox_center(n_lat, s_lat, w_lon, e_lon):
168
+ return (
169
+ (n_lat + s_lat) / 2.0,
170
+ (w_lon + e_lon) / 2.0
171
+ )
172
+
173
+ def download_static(center_lat, center_lon, zoom, size_px, maptype, api_key, url_signing_secret, style_map_id=None):
174
+ session = requests.Session()
175
+ retry_strategy = Retry(
176
+ total=5,
177
+ backoff_factor=2,
178
+ status_forcelist=[429, 500, 502, 503, 504],
179
+ allowed_methods=["GET"]
180
+ )
181
+ adapter = HTTPAdapter(max_retries=retry_strategy)
182
+ session.mount("https://", adapter)
183
+ session.mount("http://", adapter)
184
+
185
+ base = "https://maps.googleapis.com/maps/api/staticmap"
186
+ params = {
187
+ "center": f"{center_lat},{center_lon}",
188
+ "zoom": str(18),
189
+ "size": f"{size_px}x{size_px}",
190
+ "format": "png",
191
+ "key": api_key,
192
+ }
193
+ if maptype == "satellite":
194
+ params["maptype"] = "satellite"
195
+ else:
196
+ params["map_id"] = style_map_id
197
+
198
+ query_string = "&".join([f"{k}={urlparse.quote(str(v), safe='')}" for k, v in params.items()])
199
+ unsigned_url = f"{base}?{query_string}"
200
+ signed_url = sign_url(unsigned_url, url_signing_secret)
201
+
202
+ max_retries = 3
203
+ for attempt in range(max_retries):
204
+ try:
205
+ resp = session.get(signed_url, timeout=30)
206
+ resp.raise_for_status()
207
+ time.sleep(0.5)
208
+ return Image.open(io.BytesIO(resp.content)).convert("RGBA")
209
+ except (requests.exceptions.ConnectionError,
210
+ requests.exceptions.Timeout,
211
+ requests.exceptions.RequestException) as e:
212
+ if attempt < max_retries - 1:
213
+ wait_time = (attempt + 1) * 5
214
+ print(f"\nRequest failed, retrying in {wait_time} seconds...")
215
+ time.sleep(wait_time)
216
+ else:
217
+ raise
218
+
219
+ def crop_bbox_from_image(img, zoom, img_px, center_lat, center_lon,
220
+ n_lat, s_lat, w_lon, e_lon):
221
+ center_x, center_y = mercator_project(center_lon, center_lat, zoom)
222
+ img_left_world = center_x - img_px / 2.0
223
+ img_top_world = center_y - img_px / 2.0
224
+
225
+ w_x, _ = mercator_project(w_lon, center_lat, zoom)
226
+ e_x, _ = mercator_project(e_lon, center_lat, zoom)
227
+ _, n_y = mercator_project(center_lon, n_lat, zoom)
228
+ _, s_y = mercator_project(center_lon, s_lat, zoom)
229
+
230
+ xmin = w_x - img_left_world
231
+ xmax = e_x - img_left_world
232
+ ymin = n_y - img_top_world
233
+ ymax = s_y - img_top_world
234
+
235
+ box = (
236
+ int(round(xmin)),
237
+ int(round(ymin)),
238
+ int(round(xmax)),
239
+ int(round(ymax)),
240
+ )
241
+
242
+ box = (
243
+ max(0, box[0]),
244
+ max(0, box[1]),
245
+ min(img_px, box[2]),
246
+ min(img_px, box[3]),
247
+ )
248
+
249
+ return img.crop(box)
250
+
251
+ zoom = 18
252
+ img_px = 600
253
+
254
+ center_lat, center_lon = bbox_center(north_lat, south_lat, west_lon, east_lon)
255
+
256
+ img_sat = download_static(center_lat, center_lon, zoom, img_px, "satellite", api_key, url_signing_secret, style_map_id=None)
257
+ img_road = download_static(center_lat, center_lon, zoom, img_px, "roadmap", api_key, url_signing_secret, style_map_id=style_map_id)
258
+
259
+ crop_sat = crop_bbox_from_image(
260
+ img_sat, zoom, img_px, center_lat, center_lon,
261
+ north_lat, south_lat, west_lon, east_lon
262
+ )
263
+ crop_road = crop_bbox_from_image(
264
+ img_road, zoom, img_px, center_lat, center_lon,
265
+ north_lat, south_lat, west_lon, east_lon
266
+ )
267
+
268
+ crop_sat.save(out_path_sat)
269
+ crop_road.save(out_path_road)
270
+
271
+ return crop_sat, crop_road
272
+
273
+ def process_folder(
274
+ folder_path,
275
+ api_key,
276
+ url_signing_secret,
277
+ style_map_id
278
+ ):
279
+ json_files = [f for f in os.listdir(folder_path) if f.lower().endswith(".json")]
280
+
281
+ skipped = 0
282
+ failed = 0
283
+ failed_files = []
284
+
285
+ for filename in tqdm(json_files, desc="Processing files", unit="file"):
286
+ try:
287
+ json_path = os.path.join(folder_path, filename)
288
+ base_name = os.path.splitext(filename)[0]
289
+
290
+ out_sat = os.path.join(folder_path, base_name + "_sat.png")
291
+ out_map = os.path.join(folder_path, base_name + "_map.png")
292
+
293
+ expected_files = [out_sat, out_map]
294
+ for class_name in CLASS_COLORS_RGB.keys():
295
+ expected_files.append(os.path.join(folder_path, f"{base_name}_{class_name}.png"))
296
+
297
+ if all(os.path.exists(f) for f in expected_files):
298
+ skipped += 1
299
+ continue
300
+
301
+ with open(json_path, "r", encoding="utf-8") as f:
302
+ data = json.load(f)
303
+
304
+ wgs84_nw = data["wgs84_nw"]
305
+ wgs84_se = data["wgs84_se"]
306
+
307
+ west_lon = float(wgs84_nw[0])
308
+ north_lat = float(wgs84_nw[1])
309
+ east_lon = float(wgs84_se[0])
310
+ south_lat = float(wgs84_se[1])
311
+
312
+ crop_sat, crop_road = save_bbox_satellite_and_roadmap(
313
+ north_lat = north_lat,
314
+ west_lon = west_lon,
315
+ south_lat = south_lat,
316
+ east_lon = east_lon,
317
+ out_path_sat = out_sat,
318
+ out_path_road = out_map,
319
+ api_key = api_key,
320
+ url_signing_secret = url_signing_secret,
321
+ style_map_id = style_map_id
322
+ )
323
+
324
+ base_mask_prefix = os.path.join(folder_path, base_name)
325
+ generate_masks_from_roadmap(crop_road, base_mask_prefix)
326
+
327
+ except Exception as e:
328
+ failed += 1
329
+ failed_files.append(filename)
330
+ print(f"\nFailed to process {filename}: {str(e)}")
331
+ continue
332
+
333
+ print(f"\nProcessing complete!")
334
+ if skipped > 0:
335
+ print(f"Skipped {skipped} already processed files")
336
+ if failed > 0:
337
+ print(f"Failed to process {failed} files:")
338
+ for f in failed_files:
339
+ print(f" - {f}")
340
+
341
+ def make_utm_transformers(center_lat, center_lon):
342
+ zone = int((center_lon + 180) / 6) + 1
343
+ epsg = (32600 if center_lat >= 0 else 32700) + zone
344
+ to_utm = Transformer.from_crs("EPSG:4326", f"EPSG:{epsg}", always_xy=True)
345
+ to_wgs = Transformer.from_crs(f"EPSG:{epsg}", "EPSG:4326", always_xy=True)
346
+ return to_utm, to_wgs, epsg
347
+
348
+
349
+ def generate_tile_metadata_for_area(
350
+ nw_lat,
351
+ nw_lon,
352
+ se_lat,
353
+ se_lon,
354
+ output_folder,
355
+ tile_size_m=150.0,
356
+ grid_step_m=20.0,
357
+ grid_id_start=0,
358
+ overwrite=False,
359
+ ):
360
+ """Tile a lat/lon bounding box into JSON metadata files compatible with
361
+ the Melbourne dataset format (utm_nw / utm_se / wgs84_nw / wgs84_se / row / col).
362
+
363
+ Args:
364
+ nw_lat, nw_lon: northwest corner of the area (degrees).
365
+ se_lat, se_lon: southeast corner of the area (degrees).
366
+ output_folder: where JSON files will be written.
367
+ tile_size_m: edge length of each tile in meters (default 150, matches dataset).
368
+ grid_step_m: spacing between adjacent tile centers (default 20, matches dataset).
369
+ grid_id_start: starting grid_id for filenames (grid_NNNNNN).
370
+ overwrite: if False, existing JSONs are kept.
371
+
372
+ Returns:
373
+ list of file paths to the generated JSON files.
374
+ """
375
+ os.makedirs(output_folder, exist_ok=True)
376
+
377
+ center_lat = (nw_lat + se_lat) / 2.0
378
+ center_lon = (nw_lon + se_lon) / 2.0
379
+ to_utm, to_wgs, epsg = make_utm_transformers(center_lat, center_lon)
380
+
381
+ nw_x, nw_y = to_utm.transform(nw_lon, nw_lat)
382
+ se_x, se_y = to_utm.transform(se_lon, se_lat)
383
+ x_min, x_max = min(nw_x, se_x), max(nw_x, se_x)
384
+ y_min, y_max = min(nw_y, se_y), max(nw_y, se_y)
385
+
386
+ half = tile_size_m / 2.0
387
+ n_cols = max(1, int(math.ceil((x_max - x_min) / grid_step_m)))
388
+ n_rows = max(1, int(math.ceil((y_max - y_min) / grid_step_m)))
389
+
390
+ print(f"Area UTM (EPSG:{epsg}): x=[{x_min:.1f},{x_max:.1f}] "
391
+ f"y=[{y_min:.1f},{y_max:.1f}]")
392
+ print(f"Extent: {x_max-x_min:.0f}m x {y_max-y_min:.0f}m "
393
+ f"-> grid {n_rows} rows x {n_cols} cols "
394
+ f"({n_rows*n_cols} tiles, step={grid_step_m}m, tile={tile_size_m}m)")
395
+
396
+ written = []
397
+ grid_id = grid_id_start
398
+ for row in range(n_rows):
399
+ cy = y_max - half - row * grid_step_m
400
+ for col in range(n_cols):
401
+ cx = x_min + half + col * grid_step_m
402
+
403
+ utm_nw = [cx - half, cy + half]
404
+ utm_se = [cx + half, cy - half]
405
+ nw_lon_wgs, nw_lat_wgs = to_wgs.transform(utm_nw[0], utm_nw[1])
406
+ se_lon_wgs, se_lat_wgs = to_wgs.transform(utm_se[0], utm_se[1])
407
+
408
+ base_name = f"grid_{grid_id:06d}"
409
+ out_path = os.path.join(output_folder, base_name + ".json")
410
+ if os.path.exists(out_path) and not overwrite:
411
+ grid_id += 1
412
+ written.append(out_path)
413
+ continue
414
+
415
+ meta = {
416
+ "grid_id": grid_id,
417
+ "row": row,
418
+ "col": col,
419
+ "utm_nw": utm_nw,
420
+ "utm_se": utm_se,
421
+ "wgs84_nw": [nw_lon_wgs, nw_lat_wgs],
422
+ "wgs84_se": [se_lon_wgs, se_lat_wgs],
423
+ "utm_epsg": epsg,
424
+ "elevation": {
425
+ "local_min_elevation": 0.0,
426
+ "local_max_elevation": 0.0,
427
+ "global_min_used": -20.0,
428
+ "global_max_used": 302.0,
429
+ "elevation_range": 0.0,
430
+ },
431
+ }
432
+ with open(out_path, "w", encoding="utf-8") as f:
433
+ json.dump(meta, f, indent=2)
434
+ written.append(out_path)
435
+ grid_id += 1
436
+
437
+ print(f"Wrote {len(written)} tile JSONs to {output_folder}")
438
+ return written
439
+
440
+
441
+ if __name__ == "__main__":
442
+ parser = argparse.ArgumentParser(
443
+ description="Fetch satellite + styled-roadmap tiles and class masks "
444
+ "for an area (DSM/point-cloud not generated)."
445
+ )
446
+ parser.add_argument("--folder", default="./output",
447
+ help="Output folder. If --nw/--se given, JSONs are "
448
+ "created here first; otherwise existing JSONs "
449
+ "in this folder are processed.")
450
+ parser.add_argument("--nw", default=None,
451
+ help="Northwest corner 'lat,lon' (e.g. -37.778,144.932).")
452
+ parser.add_argument("--se", default=None,
453
+ help="Southeast corner 'lat,lon' (e.g. -37.785,144.948).")
454
+ parser.add_argument("--tile_size", type=float, default=150.0,
455
+ help="Tile edge length in meters (default 150).")
456
+ parser.add_argument("--grid_step", type=float, default=20.0,
457
+ help="Spacing between tile centers in meters "
458
+ "(default 20 = dense dataset grid). Use a value "
459
+ "close to --tile_size for non-overlapping coverage "
460
+ "with far fewer API calls.")
461
+ parser.add_argument("--grid_id_start", type=int, default=0)
462
+ parser.add_argument("--api_key",
463
+ default=os.environ.get("GOOGLE_MAPS_API_KEY"))
464
+ parser.add_argument("--url_signing_secret",
465
+ default=os.environ.get("GOOGLE_MAPS_URL_SIGNING_SECRET"))
466
+ parser.add_argument("--style_map_id",
467
+ default=os.environ.get("GOOGLE_MAPS_STYLE_MAP_ID"))
468
+ args = parser.parse_args()
469
+
470
+ if (args.nw is None) ^ (args.se is None):
471
+ parser.error("--nw and --se must be provided together.")
472
+
473
+ if args.nw and args.se:
474
+ nw_lat, nw_lon = [float(v) for v in args.nw.split(",")]
475
+ se_lat, se_lon = [float(v) for v in args.se.split(",")]
476
+ generate_tile_metadata_for_area(
477
+ nw_lat=nw_lat, nw_lon=nw_lon,
478
+ se_lat=se_lat, se_lon=se_lon,
479
+ output_folder=args.folder,
480
+ tile_size_m=args.tile_size,
481
+ grid_step_m=args.grid_step,
482
+ grid_id_start=args.grid_id_start,
483
+ )
484
+
485
+ process_folder(
486
+ args.folder,
487
+ args.api_key,
488
+ args.url_signing_secret,
489
+ args.style_map_id,
490
+ )
scripts/melbourne/export_las_blocks_noKML.py ADDED
@@ -0,0 +1,1047 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Melbourne LAS tiler for the City3D-MultiGen reconstruction pipeline.
3
+
4
+ Role in pipeline:
5
+ This script partitions Melbourne's source airborne LiDAR (distributed as LAS/LAZ)
6
+ into regular ground-plane tiles and produces the per-tile point cloud, DSM, and BEV
7
+ products consumed by the downstream City3D-MultiGen dataset (the GridFlow training
8
+ corpus). It is the Melbourne counterpart of the per-city tilers.
9
+
10
+ Inputs:
11
+ - One or more source LAS/LAZ files in TILE_DIR (auto-scanned when INPUT_LAS_FILES
12
+ is None, otherwise the explicitly listed files). The CRS is read from the LAS
13
+ headers (falling back to UTM auto-detection from coordinates).
14
+
15
+ Processing steps:
16
+ 1. Read each input file's XY extent and build one WGS84 polygon per file.
17
+ 2. Generate a regular grid of GRID_SIZE (150 m) tiles, keeping only tiles whose
18
+ center falls inside an input polygon; spacing yields overlapping tiles.
19
+ 3. Emit a KML visualization of the grid.
20
+ 4. Scan all tiles for bounds and (optionally) a global elevation range so DSMs
21
+ share a consistent vertical scale.
22
+ 5. For each grid tile: crop the overlapping source files to the tile bounds,
23
+ optionally voxel-downsample, then rasterize a BEV PNG and a DSM (GeoTIFF + PNG),
24
+ writing a per-tile JSON log. RESUME_MODE skips tiles already fully produced.
25
+
26
+ Outputs (per tile, named grid_<id>):
27
+ - grid_<id>.las/.laz : cropped point cloud for the tile
28
+ - grid_<id>_bev.png : top-down BEV render (RGB, optional transparency)
29
+ - grid_<id>_dsm.tif/png: digital surface model raster (georeferenced + 16-bit PNG)
30
+ - grid_<id>.json : per-tile metadata (bounds, point count, elevations)
31
+ Plus output_grids.kml and processing_summary.json at the dataset level.
32
+
33
+ External tools:
34
+ - PDAL (invoked via subprocess as `pdal pipeline`) for cropping/voxel filtering.
35
+ - GDAL/OSR for writing georeferenced DSM GeoTIFFs.
36
+ - laspy, numpy, Pillow, scipy, pyproj for I/O and rasterization.
37
+ """
38
+
39
+ import json
40
+ import os
41
+ import subprocess
42
+ import tempfile
43
+ from pathlib import Path
44
+ from pyproj import Transformer
45
+ from typing import List, Tuple, Dict
46
+ import laspy
47
+ import numpy as np
48
+ from PIL import Image
49
+ from tqdm import tqdm
50
+ from scipy.ndimage import uniform_filter
51
+
52
+ GRID_SIZE = 150
53
+ GRID_SPACING = -130 # 150 m tile - 130 m overlap = 20 m center spacing (paper setting)
54
+ INPUT_LAS_FILES = None
55
+ TILE_DIR = "./LAS"
56
+ OUTPUT_DIR = "./output"
57
+ VOXEL_SIZE = 0.05
58
+ TEST_MODE_LIMIT = None
59
+ DEBUG_MODE = False
60
+ USE_VOXEL_FILTER = False
61
+ PYTHON_VOXEL_DEDUP = False
62
+ OUTPUT_COMPRESSED = False
63
+
64
+ RESUME_MODE = True
65
+ FORCE_REPROCESS = False
66
+
67
+ BEV_POINT_SIZE = 8
68
+ BEV_TRANSPARENT_BG = True
69
+ BEV_USE_RGB = True
70
+ BEV_POINT_OPACITY = 1.0
71
+ BEV_OPACITY_MODE = "fixed"
72
+
73
+ BEV_ADAPTIVE_POINT_SIZE = True
74
+ BEV_POINT_SIZE_MIN = 3
75
+ BEV_POINT_SIZE_MAX = 3
76
+ BEV_DENSITY_WINDOW = 10
77
+
78
+ MEMORY_OPTIMIZATION = True
79
+ BEV_RESOLUTION = 256
80
+ MAX_POINTS_IN_MEMORY = 10000000
81
+
82
+ GENERATE_DSM = True
83
+ DSM_RESOLUTION = 256
84
+ DSM_POINT_SIZE = 3
85
+ DSM_USE_GLOBAL_RANGE = True
86
+
87
+ def parse_las_boundaries(las_files: List[str], tile_dir: str) -> Tuple[List[List[Tuple[float, float]]], str]:
88
+ if las_files is None or len(las_files) == 0:
89
+ print(f"AUTO-SCAN MODE: Scanning all LAS files in {tile_dir}")
90
+ las_paths = list(Path(tile_dir).glob("*.las")) + list(Path(tile_dir).glob("*.laz"))
91
+ las_paths = [f for f in las_paths if not f.name.startswith("grid_")]
92
+ las_files = [f.name for f in las_paths]
93
+
94
+ if len(las_files) == 0:
95
+ raise ValueError(f"No LAS files found in {tile_dir}")
96
+
97
+ print(f"Found {len(las_files)} LAS files:")
98
+ for f in las_files:
99
+ print(f" - {f}")
100
+ else:
101
+ print(f"MANUAL MODE: Using {len(las_files)} specified files")
102
+
103
+ print(f"\nReading boundaries from {len(las_files)} LAS files")
104
+ print("Creating individual polygons for each input file to preserve neighboring relationships")
105
+
106
+ all_bounds = []
107
+ crs_list = []
108
+
109
+ for las_file in las_files:
110
+ las_path = os.path.join(tile_dir, las_file)
111
+ if not os.path.exists(las_path):
112
+ print(f"Warning: File not found: {las_path}")
113
+ continue
114
+
115
+ try:
116
+ with laspy.open(las_path) as f:
117
+ header = f.header
118
+ bounds = {
119
+ 'file': las_file,
120
+ 'min_x': header.x_min,
121
+ 'max_x': header.x_max,
122
+ 'min_y': header.y_min,
123
+ 'max_y': header.y_max
124
+ }
125
+ all_bounds.append(bounds)
126
+
127
+ if hasattr(header, 'parse_crs'):
128
+ crs = header.parse_crs()
129
+ if crs:
130
+ crs_list.append(str(crs))
131
+
132
+ print(f" {las_file}: X=[{bounds['min_x']:.2f}, {bounds['max_x']:.2f}], Y=[{bounds['min_y']:.2f}, {bounds['max_y']:.2f}]")
133
+ except Exception as e:
134
+ print(f"Error reading {las_file}: {e}")
135
+ continue
136
+
137
+ if not all_bounds:
138
+ raise ValueError("No valid LAS files found")
139
+
140
+ overall_min_x = min(b['min_x'] for b in all_bounds)
141
+ overall_max_x = max(b['max_x'] for b in all_bounds)
142
+ overall_min_y = min(b['min_y'] for b in all_bounds)
143
+ overall_max_y = max(b['max_y'] for b in all_bounds)
144
+
145
+ print(f"\nOverall boundary: X=[{overall_min_x:.2f}, {overall_max_x:.2f}], Y=[{overall_min_y:.2f}, {overall_max_y:.2f}]")
146
+
147
+ if crs_list:
148
+ detected_crs = crs_list[0]
149
+ print(f"Detected CRS: {detected_crs}")
150
+ if 'EPSG:' in detected_crs:
151
+ utm_crs = detected_crs.split('EPSG:')[1].split()[0]
152
+ utm_crs = f"EPSG:{utm_crs}"
153
+ else:
154
+ print("Warning: Could not parse EPSG code, using auto-detection")
155
+ center_x = (overall_min_x + overall_max_x) / 2
156
+ center_y = (overall_min_y + overall_max_y) / 2
157
+ utm_crs = auto_detect_utm_from_coords(center_x, center_y)
158
+ else:
159
+ print("Warning: No CRS found in LAS headers, using auto-detection")
160
+ center_x = (overall_min_x + overall_max_x) / 2
161
+ center_y = (overall_min_y + overall_max_y) / 2
162
+ utm_crs = auto_detect_utm_from_coords(center_x, center_y)
163
+
164
+ print(f"Using UTM CRS: {utm_crs}")
165
+
166
+ transformer_to_wgs = Transformer.from_crs(utm_crs, "EPSG:4326", always_xy=True)
167
+
168
+ polygons_wgs84 = []
169
+ for i, bounds in enumerate(all_bounds):
170
+ rectangle_utm = [
171
+ (bounds['min_x'], bounds['max_y']),
172
+ (bounds['max_x'], bounds['max_y']),
173
+ (bounds['max_x'], bounds['min_y']),
174
+ (bounds['min_x'], bounds['min_y'])
175
+ ]
176
+
177
+ rectangle_wgs84 = []
178
+ for x, y in rectangle_utm:
179
+ lon, lat = transformer_to_wgs.transform(x, y)
180
+ rectangle_wgs84.append((lon, lat))
181
+
182
+ polygons_wgs84.append(rectangle_wgs84)
183
+ print(f" Created polygon {i+1} for {bounds['file']}")
184
+
185
+ print(f"\nCreated {len(polygons_wgs84)} individual polygons (one per input file)")
186
+ print("Grids will only be generated where they overlap with these polygons")
187
+
188
+ return polygons_wgs84, utm_crs
189
+
190
+ def auto_detect_utm_from_coords(x: float, y: float) -> str:
191
+ if 100000 < x < 900000 and 1000000 < y < 10000000:
192
+ if y > 5000000:
193
+ zone = int((x + 500000) / 1000000) + 30
194
+ return f"EPSG:326{zone:02d}"
195
+ else:
196
+ zone = int((x + 500000) / 1000000) + 30
197
+ return f"EPSG:327{zone:02d}"
198
+ else:
199
+ print(f"Warning: Coordinates ({x}, {y}) do not match typical UTM range")
200
+ return "EPSG:32650"
201
+
202
+ def get_utm_zone(lon: float, lat: float) -> str:
203
+ zone = int((lon + 180) / 6) + 1
204
+ hemisphere = 'north' if lat >= 0 else 'south'
205
+ return f"EPSG:326{zone:02d}" if hemisphere == 'north' else f"EPSG:327{zone:02d}"
206
+
207
+ def point_in_polygon(point: Tuple[float, float], polygon: List[Tuple[float, float]]) -> bool:
208
+ x, y = point
209
+ n = len(polygon)
210
+ inside = False
211
+
212
+ p1x, p1y = polygon[0]
213
+ for i in range(1, n + 1):
214
+ p2x, p2y = polygon[i % n]
215
+ if y > min(p1y, p2y):
216
+ if y <= max(p1y, p2y):
217
+ if x <= max(p1x, p2x):
218
+ if p1y != p2y:
219
+ xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
220
+ if p1x == p2x or x <= xinters:
221
+ inside = not inside
222
+ p1x, p1y = p2x, p2y
223
+
224
+ return inside
225
+
226
+ def generate_grids(polygons_wgs84: List[List[Tuple[float, float]]],
227
+ grid_size: float,
228
+ spacing: float,
229
+ utm_crs: str,
230
+ transformer_to_utm,
231
+ transformer_to_wgs) -> List[Dict]:
232
+
233
+ polygons_utm = []
234
+ for poly_wgs in polygons_wgs84:
235
+ poly_utm = [transformer_to_utm.transform(lon, lat) for lon, lat in poly_wgs]
236
+ polygons_utm.append(poly_utm)
237
+
238
+ all_utm_points = [p for poly in polygons_utm for p in poly]
239
+ min_x = min(p[0] for p in all_utm_points)
240
+ max_x = max(p[0] for p in all_utm_points)
241
+ min_y = min(p[1] for p in all_utm_points)
242
+ max_y = max(p[1] for p in all_utm_points)
243
+
244
+ print(f"Grid generation boundary: X=[{min_x:.2f}, {max_x:.2f}], Y=[{min_y:.2f}, {max_y:.2f}]")
245
+ print(f"Area size: {max_x-min_x:.2f}m x {max_y-min_y:.2f}m")
246
+
247
+ grids = []
248
+ grid_id = 0
249
+
250
+ y = min_y
251
+ row = 0
252
+ while y < max_y:
253
+ x = min_x
254
+ col = 0
255
+ while x < max_x:
256
+ center_x = x + grid_size / 2
257
+ center_y = y + grid_size / 2
258
+ center_lon, center_lat = transformer_to_wgs.transform(center_x, center_y)
259
+
260
+ is_in_any_polygon = False
261
+ for poly_wgs in polygons_wgs84:
262
+ if point_in_polygon((center_lon, center_lat), poly_wgs):
263
+ is_in_any_polygon = True
264
+ break
265
+
266
+ if is_in_any_polygon:
267
+ nw_lon, nw_lat = transformer_to_wgs.transform(x, y + grid_size)
268
+ se_lon, se_lat = transformer_to_wgs.transform(x + grid_size, y)
269
+
270
+ grid = {
271
+ 'id': grid_id,
272
+ 'row': row,
273
+ 'col': col,
274
+ 'utm_nw': (x, y + grid_size),
275
+ 'utm_se': (x + grid_size, y),
276
+ 'wgs84_nw': (nw_lon, nw_lat),
277
+ 'wgs84_se': (se_lon, se_lat),
278
+ 'center_wgs84': (center_lon, center_lat)
279
+ }
280
+ grids.append(grid)
281
+ grid_id += 1
282
+
283
+ x += (grid_size + spacing)
284
+ col += 1
285
+
286
+ y += (grid_size + spacing)
287
+ row += 1
288
+
289
+ print(f"Generated {len(grids)} grids that overlap with input polygons")
290
+ return grids
291
+
292
+ def create_kml(grids: List[Dict], output_path: str):
293
+ kml_header = '''<?xml version="1.0" encoding="UTF-8"?>
294
+ <kml xmlns="http://www.opengis.net/kml/2.2">
295
+ <Document>
296
+ <name>Grid Boundaries</name>
297
+ <Style id="gridStyle">
298
+ <LineStyle>
299
+ <color>ff0000ff</color>
300
+ <width>2</width>
301
+ </LineStyle>
302
+ <PolyStyle>
303
+ <color>330000ff</color>
304
+ </PolyStyle>
305
+ </Style>
306
+ '''
307
+
308
+ kml_footer = ''' </Document>
309
+ </kml>'''
310
+
311
+ with open(output_path, 'w') as f:
312
+ f.write(kml_header)
313
+
314
+ for grid in grids:
315
+ nw_lon, nw_lat = grid['wgs84_nw']
316
+ se_lon, se_lat = grid['wgs84_se']
317
+
318
+ ne_lon, ne_lat = se_lon, nw_lat
319
+ sw_lon, sw_lat = nw_lon, se_lat
320
+
321
+ placemark = f''' <Placemark>
322
+ <name>Grid {grid['id']:06d}</name>
323
+ <description>Row: {grid['row']}, Col: {grid['col']}</description>
324
+ <styleUrl>#gridStyle</styleUrl>
325
+ <Polygon>
326
+ <outerBoundaryIs>
327
+ <LinearRing>
328
+ <coordinates>
329
+ {nw_lon},{nw_lat},0
330
+ {ne_lon},{ne_lat},0
331
+ {se_lon},{se_lat},0
332
+ {sw_lon},{sw_lat},0
333
+ {nw_lon},{nw_lat},0
334
+ </coordinates>
335
+ </LinearRing>
336
+ </outerBoundaryIs>
337
+ </Polygon>
338
+ </Placemark>
339
+ '''
340
+ f.write(placemark)
341
+
342
+ f.write(kml_footer)
343
+
344
+ print(f"KML file created: {output_path}")
345
+
346
+ def get_tile_bounds(tile_dir: str) -> Dict[str, Dict]:
347
+ tile_bounds = {}
348
+ las_files = list(Path(tile_dir).glob("*.las")) + list(Path(tile_dir).glob("*.laz"))
349
+ las_files = [f for f in las_files if not f.name.startswith("grid_")]
350
+
351
+ print(f"Scanning {len(las_files)} tiles for bounds...")
352
+
353
+ for las_file in las_files:
354
+ try:
355
+ with laspy.open(str(las_file)) as f:
356
+ header = f.header
357
+ tile_bounds[las_file.name] = {
358
+ 'min_x': header.x_min,
359
+ 'max_x': header.x_max,
360
+ 'min_y': header.y_min,
361
+ 'max_y': header.y_max
362
+ }
363
+ except Exception as e:
364
+ print(f"Error reading {las_file.name}: {e}")
365
+
366
+ print(f"Successfully scanned {len(tile_bounds)} tiles")
367
+ return tile_bounds
368
+
369
+ def scan_global_elevation_range(tile_dir: str, tile_bounds: Dict) -> Tuple[float, float]:
370
+ print("\n" + "="*60)
371
+ print("Scanning global elevation range from all tiles...")
372
+ print("="*60)
373
+
374
+ global_min_z = float('inf')
375
+ global_max_z = float('-inf')
376
+ tiles_processed = 0
377
+
378
+ for tile_file in tqdm(tile_bounds.keys(), desc="Scanning tiles", unit="tile"):
379
+ tile_path = os.path.join(tile_dir, tile_file)
380
+ try:
381
+ with laspy.open(tile_path) as f:
382
+ las = f.read()
383
+ if las.header.point_count > 0:
384
+ z = np.array(las.z)
385
+ tile_min = float(z.min())
386
+ tile_max = float(z.max())
387
+ global_min_z = min(global_min_z, tile_min)
388
+ global_max_z = max(global_max_z, tile_max)
389
+ tiles_processed += 1
390
+ except Exception as e:
391
+ print(f"Error reading {tile_file}: {e}")
392
+ continue
393
+
394
+ if global_min_z == float('inf') or global_max_z == float('-inf'):
395
+ print("Warning: Could not determine global elevation range, will use local ranges")
396
+ return None, None
397
+
398
+ print(f"\nGlobal elevation range from {tiles_processed} tiles:")
399
+ print(f" Min elevation: {global_min_z:.2f}m")
400
+ print(f" Max elevation: {global_max_z:.2f}m")
401
+ print(f" Range: {global_max_z - global_min_z:.2f}m")
402
+
403
+ return global_min_z, global_max_z
404
+
405
+ def find_overlapping_tiles(grid: Dict, tile_bounds: Dict) -> List[str]:
406
+ grid_min_x, grid_max_y = grid['utm_nw']
407
+ grid_max_x, grid_min_y = grid['utm_se']
408
+
409
+ overlapping = []
410
+ for tile_name, bounds in tile_bounds.items():
411
+ if not (bounds['max_x'] < grid_min_x or bounds['min_x'] > grid_max_x or
412
+ bounds['max_y'] < grid_min_y or bounds['min_y'] > grid_max_y):
413
+ overlapping.append(tile_name)
414
+
415
+ return overlapping
416
+
417
+ def crop_las_with_pdal(tile_files: List[str], grid: Dict, output_path: str, tile_dir: str) -> Dict:
418
+ try:
419
+ min_x, max_y = grid['utm_nw']
420
+ max_x, min_y = grid['utm_se']
421
+
422
+ input_files = [os.path.join(tile_dir, f) for f in tile_files]
423
+
424
+ pipeline = {
425
+ "pipeline": []
426
+ }
427
+
428
+ for input_file in input_files:
429
+ pipeline["pipeline"].append(input_file)
430
+
431
+ bounds_str = f"([{min_x}, {max_x}], [{min_y}, {max_y}])"
432
+
433
+ filters = [
434
+ {
435
+ "type": "filters.crop",
436
+ "bounds": bounds_str
437
+ }
438
+ ]
439
+
440
+ if USE_VOXEL_FILTER and len(tile_files) > 1:
441
+ filters.append({
442
+ "type": "filters.voxelcenternearestneighbor",
443
+ "cell": VOXEL_SIZE
444
+ })
445
+
446
+ filters.append({
447
+ "type": "writers.las",
448
+ "filename": output_path,
449
+ "compression": "laszip" if OUTPUT_COMPRESSED else "none"
450
+ })
451
+
452
+ pipeline["pipeline"].extend(filters)
453
+
454
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
455
+ json.dump(pipeline, f, indent=2)
456
+ pipeline_file = f.name
457
+
458
+ try:
459
+ result = subprocess.run(
460
+ ['pdal', 'pipeline', pipeline_file],
461
+ capture_output=True,
462
+ text=True,
463
+ timeout=300
464
+ )
465
+
466
+ if result.returncode != 0:
467
+ return {
468
+ 'success': False,
469
+ 'error': f"PDAL error: {result.stderr}",
470
+ 'point_count': 0
471
+ }
472
+
473
+ if not os.path.exists(output_path):
474
+ return {
475
+ 'success': False,
476
+ 'error': 'Output file not created',
477
+ 'point_count': 0
478
+ }
479
+
480
+ with laspy.open(output_path) as f:
481
+ point_count = f.header.point_count
482
+
483
+ return {
484
+ 'success': True,
485
+ 'point_count': point_count,
486
+ 'tiles_used': tile_files
487
+ }
488
+
489
+ finally:
490
+ if os.path.exists(pipeline_file):
491
+ os.remove(pipeline_file)
492
+
493
+ except subprocess.TimeoutExpired:
494
+ return {
495
+ 'success': False,
496
+ 'error': 'PDAL pipeline timeout',
497
+ 'point_count': 0
498
+ }
499
+ except Exception as e:
500
+ return {
501
+ 'success': False,
502
+ 'error': str(e),
503
+ 'point_count': 0
504
+ }
505
+
506
+ def voxel_downsample_python(input_las: str, output_las: str, voxel_size: float) -> int:
507
+ with laspy.open(input_las) as f:
508
+ las = f.read()
509
+
510
+ x = np.array(las.x)
511
+ y = np.array(las.y)
512
+ z = np.array(las.z)
513
+
514
+ voxel_x = np.floor(x / voxel_size).astype(np.int32)
515
+ voxel_y = np.floor(y / voxel_size).astype(np.int32)
516
+ voxel_z = np.floor(z / voxel_size).astype(np.int32)
517
+
518
+ voxel_keys = np.column_stack([voxel_x, voxel_y, voxel_z])
519
+ unique_voxels, unique_indices = np.unique(voxel_keys, axis=0, return_index=True)
520
+
521
+ las_filtered = laspy.LasData(las.header)
522
+ las_filtered.points = las.points[unique_indices]
523
+
524
+ las_filtered.write(output_las)
525
+
526
+ return len(unique_indices)
527
+
528
+ def generate_bev_png(las_path: str, output_path: str, grid: Dict):
529
+ try:
530
+ with laspy.open(las_path) as f:
531
+ las = f.read()
532
+
533
+ if las.header.point_count == 0:
534
+ if DEBUG_MODE:
535
+ print(f" BEV: Empty point cloud")
536
+ img = Image.new('RGBA', (BEV_RESOLUTION, BEV_RESOLUTION), (0, 0, 0, 0) if BEV_TRANSPARENT_BG else (255, 255, 255, 255))
537
+ img.save(output_path)
538
+ return
539
+
540
+ x = np.array(las.x)
541
+ y = np.array(las.y)
542
+
543
+ minx = grid['utm_nw'][0]
544
+ maxx = grid['utm_se'][0]
545
+ miny = grid['utm_se'][1]
546
+ maxy = grid['utm_nw'][1]
547
+
548
+ px = ((x - minx) / (maxx - minx) * (BEV_RESOLUTION - 1)).astype(np.int32)
549
+ py = ((maxy - y) / (maxy - miny) * (BEV_RESOLUTION - 1)).astype(np.int32)
550
+
551
+ valid = (px >= 0) & (px < BEV_RESOLUTION) & (py >= 0) & (py < BEV_RESOLUTION)
552
+ px = px[valid]
553
+ py = py[valid]
554
+
555
+ if len(px) == 0:
556
+ if DEBUG_MODE:
557
+ print(f" BEV: No valid points")
558
+ img = Image.new('RGBA', (BEV_RESOLUTION, BEV_RESOLUTION), (0, 0, 0, 0) if BEV_TRANSPARENT_BG else (255, 255, 255, 255))
559
+ img.save(output_path)
560
+ return
561
+
562
+ if BEV_USE_RGB and hasattr(las, 'red'):
563
+ r = np.array(las.red)[valid] // 256
564
+ g = np.array(las.green)[valid] // 256
565
+ b = np.array(las.blue)[valid] // 256
566
+ else:
567
+ r = g = b = None
568
+
569
+ img_array = np.zeros((BEV_RESOLUTION, BEV_RESOLUTION, 4), dtype=np.uint8)
570
+ if not BEV_TRANSPARENT_BG:
571
+ img_array[:, :, :3] = 255
572
+ img_array[:, :, 3] = 255
573
+
574
+ if BEV_ADAPTIVE_POINT_SIZE:
575
+ density_map = np.zeros((BEV_RESOLUTION, BEV_RESOLUTION), dtype=np.int32)
576
+ for i in range(len(px)):
577
+ density_map[py[i], px[i]] += 1
578
+
579
+ density_smoothed = uniform_filter(density_map.astype(np.float32), size=BEV_DENSITY_WINDOW)
580
+ max_density = density_smoothed.max()
581
+ if max_density > 0:
582
+ density_normalized = density_smoothed / max_density
583
+ else:
584
+ density_normalized = density_smoothed
585
+
586
+ for i in range(len(px)):
587
+ if BEV_ADAPTIVE_POINT_SIZE:
588
+ density_value = density_normalized[py[i], px[i]]
589
+ point_size = int(BEV_POINT_SIZE_MIN + (BEV_POINT_SIZE_MAX - BEV_POINT_SIZE_MIN) * (1 - density_value))
590
+ else:
591
+ point_size = BEV_POINT_SIZE
592
+
593
+ half_size = point_size // 2
594
+ x_start = max(0, px[i] - half_size)
595
+ x_end = min(BEV_RESOLUTION, px[i] + half_size + 1)
596
+ y_start = max(0, py[i] - half_size)
597
+ y_end = min(BEV_RESOLUTION, py[i] + half_size + 1)
598
+
599
+ if BEV_OPACITY_MODE == "fixed":
600
+ alpha = int(BEV_POINT_OPACITY * 255)
601
+ else:
602
+ alpha = 255
603
+
604
+ if r is not None:
605
+ color = [r[i], g[i], b[i]]
606
+ else:
607
+ color = [0, 0, 0]
608
+
609
+ img_array[y_start:y_end, x_start:x_end, :3] = color
610
+ img_array[y_start:y_end, x_start:x_end, 3] = alpha
611
+
612
+ img = Image.fromarray(img_array)
613
+ img.save(output_path)
614
+ if DEBUG_MODE:
615
+ print(f" BEV: Saved to {output_path}")
616
+
617
+ except Exception as e:
618
+ print(f" BEV: Error generating BEV: {e}")
619
+ if DEBUG_MODE:
620
+ import traceback
621
+ traceback.print_exc()
622
+ img = Image.new('RGBA', (BEV_RESOLUTION, BEV_RESOLUTION), (0, 0, 0, 0) if BEV_TRANSPARENT_BG else (255, 255, 255, 255))
623
+ img.save(output_path)
624
+
625
+ def generate_dsm(las_path: str, output_geotiff: str, output_png: str, grid: Dict,
626
+ resolution: int = 1024, global_min_z: float = None, global_max_z: float = None) -> Dict:
627
+ try:
628
+ from osgeo import gdal, osr
629
+
630
+ with laspy.open(las_path) as f:
631
+ las = f.read()
632
+
633
+ if las.header.point_count == 0:
634
+ if DEBUG_MODE:
635
+ print(f" DSM: Empty point cloud")
636
+ return None
637
+
638
+ x = np.array(las.x)
639
+ y = np.array(las.y)
640
+ z = np.array(las.z)
641
+
642
+ minx = grid['utm_nw'][0]
643
+ maxx = grid['utm_se'][0]
644
+ miny = grid['utm_se'][1]
645
+ maxy = grid['utm_nw'][1]
646
+
647
+ cell_size_x = (maxx - minx) / resolution
648
+ cell_size_y = (maxy - miny) / resolution
649
+
650
+ px = ((x - minx) / (maxx - minx) * (resolution - 1)).astype(np.int32)
651
+ py = ((maxy - y) / (maxy - miny) * (resolution - 1)).astype(np.int32)
652
+
653
+ valid = (px >= 0) & (px < resolution) & (py >= 0) & (py < resolution)
654
+ px = px[valid]
655
+ py = py[valid]
656
+ z = z[valid]
657
+
658
+ if len(px) == 0:
659
+ if DEBUG_MODE:
660
+ print(f" DSM: No valid points")
661
+ return None
662
+
663
+ dsm = np.full((resolution, resolution), -9999.0, dtype=np.float32)
664
+
665
+ half_size = DSM_POINT_SIZE // 2
666
+
667
+ for i in range(len(px)):
668
+ cy, cx = py[i], px[i]
669
+
670
+ for dy in range(-half_size, half_size + 1):
671
+ for dx in range(-half_size, half_size + 1):
672
+ ny = cy + dy
673
+ nx = cx + dx
674
+
675
+ if 0 <= ny < resolution and 0 <= nx < resolution:
676
+ current_z = dsm[ny, nx]
677
+ if current_z == -9999.0 or z[i] > current_z:
678
+ dsm[ny, nx] = z[i]
679
+
680
+ mask = dsm != -9999.0
681
+ if not mask.any():
682
+ if DEBUG_MODE:
683
+ print(f" DSM: All cells empty")
684
+ return None
685
+
686
+ local_min_elevation = float(dsm[mask].min())
687
+ local_max_elevation = float(dsm[mask].max())
688
+
689
+ if DSM_USE_GLOBAL_RANGE and global_min_z is not None and global_max_z is not None:
690
+ use_min = global_min_z
691
+ use_max = global_max_z
692
+ if DEBUG_MODE:
693
+ print(f" DSM: Using global range {use_min:.2f}-{use_max:.2f}m (local: {local_min_elevation:.2f}-{local_max_elevation:.2f}m)")
694
+ else:
695
+ use_min = local_min_elevation
696
+ use_max = local_max_elevation
697
+ if DEBUG_MODE:
698
+ print(f" DSM: Using local range {use_min:.2f}-{use_max:.2f}m")
699
+
700
+ driver = gdal.GetDriverByName('GTiff')
701
+ dataset = driver.Create(output_geotiff, resolution, resolution, 1, gdal.GDT_Float32)
702
+
703
+ geotransform = (minx, cell_size_x, 0, maxy, 0, -cell_size_y)
704
+ dataset.SetGeoTransform(geotransform)
705
+
706
+ srs = osr.SpatialReference()
707
+ epsg_code = int(grid.get('utm_crs', 'EPSG:27700').split(':')[1]) if 'utm_crs' in grid else 27700
708
+ srs.ImportFromEPSG(epsg_code)
709
+ dataset.SetProjection(srs.ExportToWkt())
710
+
711
+ band = dataset.GetRasterBand(1)
712
+ band.SetNoDataValue(-9999.0)
713
+ band.WriteArray(dsm)
714
+
715
+ dataset.FlushCache()
716
+ dataset = None
717
+
718
+ dsm_normalized = np.where(dsm == -9999.0, 0,
719
+ np.clip((dsm - use_min) / (use_max - use_min), 0, 1) * 65535)
720
+ dsm_img = dsm_normalized.astype(np.uint16)
721
+
722
+ img = Image.fromarray(dsm_img)
723
+ img.save(output_png)
724
+
725
+ if DEBUG_MODE:
726
+ print(f" DSM: GeoTIFF and PNG saved")
727
+
728
+ return {
729
+ 'min_elevation': local_min_elevation,
730
+ 'max_elevation': local_max_elevation,
731
+ 'global_min_used': use_min,
732
+ 'global_max_used': use_max,
733
+ 'resolution': resolution,
734
+ 'cell_size_x': cell_size_x,
735
+ 'cell_size_y': cell_size_y
736
+ }
737
+
738
+ except ImportError:
739
+ print(f" DSM: Error - GDAL not installed. Install with: pip install gdal")
740
+ return None
741
+ except Exception as e:
742
+ print(f" DSM: Error - {e}")
743
+ if DEBUG_MODE:
744
+ import traceback
745
+ traceback.print_exc()
746
+ return None
747
+
748
+ def check_grid_already_processed(grid_id: int, output_dir: str) -> Dict:
749
+ file_ext = ".laz" if OUTPUT_COMPRESSED else ".las"
750
+ output_las = os.path.join(output_dir, f"grid_{grid_id:06d}{file_ext}")
751
+ output_bev = os.path.join(output_dir, f"grid_{grid_id:06d}_bev.png")
752
+ output_log = os.path.join(output_dir, f"grid_{grid_id:06d}.json")
753
+
754
+ required_files = [output_las, output_bev, output_log]
755
+
756
+ if GENERATE_DSM:
757
+ output_dsm_tif = os.path.join(output_dir, f"grid_{grid_id:06d}_dsm.tif")
758
+ output_dsm_png = os.path.join(output_dir, f"grid_{grid_id:06d}_dsm.png")
759
+ required_files.extend([output_dsm_tif, output_dsm_png])
760
+
761
+ if all(os.path.exists(f) for f in required_files):
762
+ try:
763
+ with open(output_log, 'r') as f:
764
+ log_data = json.load(f)
765
+
766
+ if all(os.path.getsize(f) > 0 for f in required_files):
767
+ return {
768
+ 'grid_id': grid_id,
769
+ 'status': 'success',
770
+ 'point_count': log_data.get('point_count', 0),
771
+ 'tiles_used': len(log_data.get('tiles_used', [])),
772
+ 'resumed': True
773
+ }
774
+ except Exception as e:
775
+ if DEBUG_MODE:
776
+ tqdm.write(f" DEBUG: Failed to read log for grid {grid_id}: {e}")
777
+ return None
778
+
779
+ return None
780
+
781
+ def process_single_grid(grid: Dict, tile_bounds: Dict, tile_dir: str, output_dir: str,
782
+ utm_crs: str, global_min_z: float = None, global_max_z: float = None) -> Dict:
783
+ grid_id = grid['id']
784
+
785
+ if RESUME_MODE and not FORCE_REPROCESS:
786
+ existing_result = check_grid_already_processed(grid_id, output_dir)
787
+ if existing_result:
788
+ return existing_result
789
+
790
+ if DEBUG_MODE:
791
+ print(f"\n DEBUG: Grid bounds UTM: NW={grid['utm_nw']}, SE={grid['utm_se']}")
792
+
793
+ overlapping_tiles = find_overlapping_tiles(grid, tile_bounds)
794
+
795
+ if DEBUG_MODE:
796
+ print(f" DEBUG: Found {len(overlapping_tiles)} overlapping tiles: {overlapping_tiles[:3]}...")
797
+
798
+ if not overlapping_tiles:
799
+ return {
800
+ 'grid_id': grid_id,
801
+ 'status': 'no_tiles',
802
+ 'message': 'No overlapping tiles found'
803
+ }
804
+
805
+ file_ext = ".laz" if OUTPUT_COMPRESSED else ".las"
806
+ output_las = os.path.join(output_dir, f"grid_{grid_id:06d}{file_ext}")
807
+ output_bev = os.path.join(output_dir, f"grid_{grid_id:06d}_bev.png")
808
+ output_log = os.path.join(output_dir, f"grid_{grid_id:06d}.json")
809
+
810
+ crop_result = crop_las_with_pdal(overlapping_tiles, grid, output_las, tile_dir)
811
+
812
+ if not crop_result['success']:
813
+ error_msg = crop_result.get('error', 'Unknown error')
814
+ return {
815
+ 'grid_id': grid_id,
816
+ 'status': 'failed',
817
+ 'message': error_msg,
818
+ 'tiles_checked': overlapping_tiles
819
+ }
820
+
821
+ if crop_result['point_count'] == 0:
822
+ return {
823
+ 'grid_id': grid_id,
824
+ 'status': 'empty',
825
+ 'message': 'No points in cropped area',
826
+ 'tiles_used': overlapping_tiles
827
+ }
828
+
829
+ if PYTHON_VOXEL_DEDUP and len(overlapping_tiles) > 1:
830
+ temp_output = output_las + ".temp"
831
+ os.rename(output_las, temp_output)
832
+ final_count = voxel_downsample_python(temp_output, output_las, VOXEL_SIZE)
833
+ os.remove(temp_output)
834
+ crop_result['point_count'] = final_count
835
+ if DEBUG_MODE:
836
+ print(f" DEBUG: Python voxel downsampled to {final_count} points")
837
+
838
+ generate_bev_png(output_las, output_bev, grid)
839
+
840
+ dsm_info = None
841
+ if GENERATE_DSM:
842
+ output_dsm_tif = os.path.join(output_dir, f"grid_{grid_id:06d}_dsm.tif")
843
+ output_dsm_png = os.path.join(output_dir, f"grid_{grid_id:06d}_dsm.png")
844
+ grid_with_crs = grid.copy()
845
+ grid_with_crs['utm_crs'] = utm_crs
846
+ dsm_info = generate_dsm(output_las, output_dsm_tif, output_dsm_png, grid_with_crs,
847
+ DSM_RESOLUTION, global_min_z, global_max_z)
848
+
849
+ log_data = {
850
+ 'grid_id': grid_id,
851
+ 'row': grid['row'],
852
+ 'col': grid['col'],
853
+ 'utm_nw': grid['utm_nw'],
854
+ 'utm_se': grid['utm_se'],
855
+ 'wgs84_nw': grid['wgs84_nw'],
856
+ 'wgs84_se': grid['wgs84_se'],
857
+ 'point_count': crop_result['point_count'],
858
+ 'tiles_used': crop_result['tiles_used'],
859
+ 'output_files': {
860
+ 'las': os.path.basename(output_las),
861
+ 'bev': os.path.basename(output_bev)
862
+ }
863
+ }
864
+
865
+ if GENERATE_DSM and dsm_info:
866
+ log_data['elevation'] = {
867
+ 'local_min_elevation': dsm_info['min_elevation'],
868
+ 'local_max_elevation': dsm_info['max_elevation'],
869
+ 'global_min_used': dsm_info['global_min_used'],
870
+ 'global_max_used': dsm_info['global_max_used'],
871
+ 'elevation_range': dsm_info['max_elevation'] - dsm_info['min_elevation']
872
+ }
873
+ log_data['output_files']['dsm_geotiff'] = os.path.basename(output_dsm_tif)
874
+ log_data['output_files']['dsm_png'] = os.path.basename(output_dsm_png)
875
+
876
+ with open(output_log, 'w') as f:
877
+ json.dump(log_data, f, indent=2)
878
+
879
+ return {
880
+ 'grid_id': grid_id,
881
+ 'status': 'success',
882
+ 'point_count': crop_result['point_count'],
883
+ 'tiles_used': len(overlapping_tiles)
884
+ }
885
+
886
+ def main():
887
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
888
+
889
+ if os.path.abspath(OUTPUT_DIR) == os.path.abspath(TILE_DIR):
890
+ print("ERROR: OUTPUT_DIR and TILE_DIR must be different!")
891
+ print(f"OUTPUT_DIR: {os.path.abspath(OUTPUT_DIR)}")
892
+ print(f"TILE_DIR: {os.path.abspath(TILE_DIR)}")
893
+ print("Please set OUTPUT_DIR to a different directory to avoid confusion.")
894
+ return
895
+
896
+ print("="*60)
897
+ print("STEP 1: Reading LAS boundaries and generating grids")
898
+ print("="*60)
899
+
900
+ polygons, utm_crs = parse_las_boundaries(INPUT_LAS_FILES, TILE_DIR)
901
+
902
+ transformer_to_utm = Transformer.from_crs("EPSG:4326", utm_crs, always_xy=True)
903
+ transformer_to_wgs = Transformer.from_crs(utm_crs, "EPSG:4326", always_xy=True)
904
+
905
+ grids = generate_grids(polygons, GRID_SIZE, GRID_SPACING,
906
+ utm_crs, transformer_to_utm, transformer_to_wgs)
907
+
908
+ print("\n" + "="*60)
909
+ print("STEP 2: Generating KML visualization")
910
+ print("="*60)
911
+
912
+ kml_output = os.path.join(OUTPUT_DIR, "output_grids.kml")
913
+ create_kml(grids, kml_output)
914
+
915
+ print("\n" + "="*60)
916
+ print("STEP 3: Scanning all LAS tiles")
917
+ print("="*60)
918
+
919
+ tile_bounds = get_tile_bounds(TILE_DIR)
920
+
921
+ if not tile_bounds:
922
+ print("ERROR: No valid tiles found!")
923
+ return
924
+
925
+ global_min_z = None
926
+ global_max_z = None
927
+
928
+ if GENERATE_DSM and DSM_USE_GLOBAL_RANGE:
929
+ global_min_z, global_max_z = scan_global_elevation_range(TILE_DIR, tile_bounds)
930
+
931
+ print("\n" + "="*60)
932
+ print("STEP 4: Processing grids and generating outputs")
933
+ print("="*60)
934
+
935
+ grids_to_process = grids[:TEST_MODE_LIMIT] if TEST_MODE_LIMIT else grids
936
+
937
+ if TEST_MODE_LIMIT:
938
+ print(f"\n*** TEST MODE: Processing only first {len(grids_to_process)} grids ***\n")
939
+ else:
940
+ print(f"\nProcessing all {len(grids_to_process)} grids\n")
941
+
942
+ if RESUME_MODE and not FORCE_REPROCESS:
943
+ print(f"*** RESUME MODE: Skipping already processed grids ***\n")
944
+ elif FORCE_REPROCESS:
945
+ print(f"*** FORCE REPROCESS: Reprocessing all grids ***\n")
946
+
947
+ if GENERATE_DSM:
948
+ print(f"DSM Configuration:")
949
+ print(f" Resolution: {DSM_RESOLUTION}x{DSM_RESOLUTION}")
950
+ print(f" Point size: {DSM_POINT_SIZE}x{DSM_POINT_SIZE} pixels per point")
951
+ print(f" Use global range: {DSM_USE_GLOBAL_RANGE}")
952
+ if DSM_USE_GLOBAL_RANGE and global_min_z is not None:
953
+ print(f" Global range: {global_min_z:.2f}m - {global_max_z:.2f}m\n")
954
+
955
+ results = []
956
+ resumed_count = 0
957
+ processed_count = 0
958
+
959
+ with tqdm(total=len(grids_to_process), desc="Processing grids", unit="grid") as pbar:
960
+ for i, grid in enumerate(grids_to_process):
961
+ grid_id = grid['id']
962
+ pbar.set_description(f"Processing grid {grid_id:06d}")
963
+
964
+ result = process_single_grid(grid, tile_bounds, TILE_DIR, OUTPUT_DIR, utm_crs,
965
+ global_min_z, global_max_z)
966
+ results.append(result)
967
+
968
+ if result.get('resumed', False):
969
+ resumed_count += 1
970
+ tqdm.write(f"Grid {grid_id:06d}: RESUMED - {result.get('point_count', 0):,} points (skipped)")
971
+ else:
972
+ processed_count += 1
973
+ if result['status'] == 'failed':
974
+ tqdm.write(f"Grid {grid_id:06d}: FAILED - {result.get('message', 'Unknown error')}")
975
+ elif result['status'] == 'success':
976
+ tqdm.write(f"Grid {grid_id:06d}: SUCCESS - {result.get('point_count', 0):,} points from {result.get('tiles_used', 0)} tiles")
977
+ elif result['status'] == 'empty':
978
+ tqdm.write(f"Grid {grid_id:06d}: EMPTY - No points in area")
979
+ elif result['status'] == 'no_tiles':
980
+ tqdm.write(f"Grid {grid_id:06d}: NO TILES - No overlapping tiles found")
981
+
982
+ pbar.update(1)
983
+
984
+ print("\n" + "="*60)
985
+ print("STEP 5: Generating final summary")
986
+ print("="*60)
987
+
988
+ summary = {
989
+ 'config': {
990
+ 'grid_size_m': GRID_SIZE,
991
+ 'grid_spacing_m': GRID_SPACING,
992
+ 'voxel_size_m': VOXEL_SIZE,
993
+ 'use_voxel_filter': USE_VOXEL_FILTER,
994
+ 'python_voxel_dedup': PYTHON_VOXEL_DEDUP,
995
+ 'output_compressed': OUTPUT_COMPRESSED,
996
+ 'bev_point_size': BEV_POINT_SIZE,
997
+ 'bev_transparent_bg': BEV_TRANSPARENT_BG,
998
+ 'bev_use_rgb': BEV_USE_RGB,
999
+ 'bev_point_opacity': BEV_POINT_OPACITY,
1000
+ 'bev_opacity_mode': BEV_OPACITY_MODE,
1001
+ 'bev_adaptive_point_size': BEV_ADAPTIVE_POINT_SIZE,
1002
+ 'bev_point_size_min': BEV_POINT_SIZE_MIN,
1003
+ 'bev_point_size_max': BEV_POINT_SIZE_MAX,
1004
+ 'bev_density_window': BEV_DENSITY_WINDOW,
1005
+ 'generate_dsm': GENERATE_DSM,
1006
+ 'dsm_resolution': DSM_RESOLUTION,
1007
+ 'dsm_point_size': DSM_POINT_SIZE,
1008
+ 'dsm_use_global_range': DSM_USE_GLOBAL_RANGE,
1009
+ 'global_elevation_range': {
1010
+ 'min': global_min_z,
1011
+ 'max': global_max_z
1012
+ } if global_min_z is not None else None,
1013
+ 'utm_crs': utm_crs,
1014
+ 'test_mode': TEST_MODE_LIMIT is not None,
1015
+ 'test_mode_limit': TEST_MODE_LIMIT,
1016
+ 'resume_mode': RESUME_MODE,
1017
+ 'force_reprocess': FORCE_REPROCESS
1018
+ },
1019
+ 'statistics': {
1020
+ 'total_grids_generated': len(grids),
1021
+ 'grids_processed': len(grids_to_process),
1022
+ 'newly_processed': processed_count,
1023
+ 'resumed_skipped': resumed_count,
1024
+ 'successful': sum(1 for r in results if r['status'] == 'success'),
1025
+ 'failed': sum(1 for r in results if r['status'] == 'failed'),
1026
+ 'empty': sum(1 for r in results if r['status'] == 'empty'),
1027
+ 'no_tiles': sum(1 for r in results if r['status'] == 'no_tiles')
1028
+ },
1029
+ 'results': results
1030
+ }
1031
+
1032
+ summary_path = os.path.join(OUTPUT_DIR, "processing_summary.json")
1033
+ with open(summary_path, 'w') as f:
1034
+ json.dump(summary, f, indent=2)
1035
+
1036
+ print(f"\nSummary saved to: {summary_path}")
1037
+ print(f"KML visualization: {kml_output}")
1038
+ if TEST_MODE_LIMIT:
1039
+ print(f"Test mode: Processed {len(grids_to_process)}/{len(grids)} grids")
1040
+ if RESUME_MODE and resumed_count > 0:
1041
+ print(f"Resumed: Skipped {resumed_count} already processed grids")
1042
+ print(f"Newly processed: {processed_count} grids")
1043
+ print(f"Success: {summary['statistics']['successful']}/{len(grids_to_process)}")
1044
+ print("\nProcessing complete!")
1045
+
1046
+ if __name__ == "__main__":
1047
+ main()
scripts/melbourne/grid_from_kml.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Build the 150 m tile grid for the City3D-MultiGen reconstruction pipeline.
3
+
4
+ Role in the pipeline:
5
+ This script turns a coarse tile-index footprint into the fine, regularly
6
+ spaced grid of 150 m x 150 m tiles that drives the rest of the pipeline.
7
+ Each generated tile later defines the geographic extent used to crop the
8
+ source city point cloud and to fetch aligned satellite/semantic maps.
9
+
10
+ Input:
11
+ A KML tile-index file (default "Tile_Index.kml") whose polygons describe
12
+ the WGS84 (lon/lat) coverage area of the source city data.
13
+
14
+ Outputs:
15
+ - output_grids.kml: a colorized KML visualization of the generated tiles.
16
+ - output_grids.json: the machine-readable grid consumed downstream. It
17
+ stores grid_size_m, grid_spacing_m, input_polygons, total_grids, and a
18
+ "grids" list where each entry has id, row, col, and both UTM and WGS84
19
+ corner coordinates (utm_nw/utm_se, wgs84_nw/wgs84_se).
20
+
21
+ Key steps:
22
+ Parse the KML polygons, pick a UTM zone from the data centroid, project the
23
+ polygons into metric UTM coordinates, tile the bounding box on a fixed
24
+ pitch, keep tiles whose center falls inside a footprint polygon, then
25
+ project the tile corners back to WGS84 for output.
26
+
27
+ Coordinate-system handling:
28
+ All distances/sizes are computed in metric UTM (zone chosen automatically
29
+ from the centroid via EPSG:326xx/327xx). pyproj Transformers (always_xy)
30
+ convert between EPSG:4326 (WGS84 lon/lat) and the chosen UTM CRS.
31
+ """
32
+
33
+ import json
34
+ import math
35
+ from xml.etree import ElementTree as ET
36
+ from pyproj import Transformer, CRS
37
+ from typing import List, Tuple
38
+
39
+ GRID_SIZE = 150
40
+ GRID_SPACING = -130 # 150 m tile - 130 m overlap = 20 m center spacing (paper setting)
41
+
42
+ def parse_kml_polygons(kml_path: str) -> List[List[Tuple[float, float]]]:
43
+ tree = ET.parse(kml_path)
44
+ root = tree.getroot()
45
+
46
+ polygons = []
47
+
48
+ for elem in root.iter():
49
+ if elem.tag.endswith('coordinates'):
50
+ coords_text = elem.text
51
+ if coords_text:
52
+ coords = []
53
+ for line in coords_text.strip().split():
54
+ parts = line.split(',')
55
+ if len(parts) >= 2:
56
+ lon, lat = float(parts[0]), float(parts[1])
57
+ coords.append((lon, lat))
58
+ if coords:
59
+ polygons.append(coords)
60
+
61
+ print(f"Parsed {len(polygons)} polygons from KML")
62
+ return polygons
63
+
64
+ def get_utm_zone(lon: float, lat: float) -> str:
65
+ zone = int((lon + 180) / 6) + 1
66
+ hemisphere = 'north' if lat >= 0 else 'south'
67
+ return f"EPSG:326{zone:02d}" if hemisphere == 'north' else f"EPSG:327{zone:02d}"
68
+
69
+ def point_in_polygon(point: Tuple[float, float], polygon: List[Tuple[float, float]]) -> bool:
70
+ x, y = point
71
+ n = len(polygon)
72
+ inside = False
73
+
74
+ p1x, p1y = polygon[0]
75
+ for i in range(1, n + 1):
76
+ p2x, p2y = polygon[i % n]
77
+ if y > min(p1y, p2y):
78
+ if y <= max(p1y, p2y):
79
+ if x <= max(p1x, p2x):
80
+ if p1y != p2y:
81
+ xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
82
+ if p1x == p2x or x <= xinters:
83
+ inside = not inside
84
+ p1x, p1y = p2x, p2y
85
+
86
+ return inside
87
+
88
+ def generate_grid(polygons_wgs84: List[List[Tuple[float, float]]],
89
+ grid_size: float,
90
+ spacing: float) -> List[dict]:
91
+
92
+ all_points = [p for poly in polygons_wgs84 for p in poly]
93
+ center_lon = sum(p[0] for p in all_points) / len(all_points)
94
+ center_lat = sum(p[1] for p in all_points) / len(all_points)
95
+
96
+ utm_crs = get_utm_zone(center_lon, center_lat)
97
+ print(f"Using coordinate system: {utm_crs}")
98
+
99
+ transformer_to_utm = Transformer.from_crs("EPSG:4326", utm_crs, always_xy=True)
100
+ transformer_to_wgs = Transformer.from_crs(utm_crs, "EPSG:4326", always_xy=True)
101
+
102
+ polygons_utm = []
103
+ for poly_wgs in polygons_wgs84:
104
+ poly_utm = [transformer_to_utm.transform(lon, lat) for lon, lat in poly_wgs]
105
+ polygons_utm.append(poly_utm)
106
+
107
+ all_utm_points = [p for poly in polygons_utm for p in poly]
108
+ min_x = min(p[0] for p in all_utm_points)
109
+ max_x = max(p[0] for p in all_utm_points)
110
+ min_y = min(p[1] for p in all_utm_points)
111
+ max_y = max(p[1] for p in all_utm_points)
112
+
113
+ print(f"Overall boundary in UTM: X=[{min_x:.2f}, {max_x:.2f}], Y=[{min_y:.2f}, {max_y:.2f}]")
114
+ print(f"Area size: {max_x-min_x:.2f}m x {max_y-min_y:.2f}m")
115
+
116
+ grids = []
117
+ grid_id = 0
118
+ total_candidates = 0
119
+
120
+ y = min_y
121
+ row = 0
122
+ while y < max_y:
123
+ x = min_x
124
+ col = 0
125
+ while x < max_x:
126
+ total_candidates += 1
127
+
128
+ center_x = x + grid_size / 2
129
+ center_y = y + grid_size / 2
130
+ center_utm = (center_x, center_y)
131
+
132
+ is_inside = False
133
+ for poly_utm in polygons_utm:
134
+ if point_in_polygon(center_utm, poly_utm):
135
+ is_inside = True
136
+ break
137
+
138
+ if is_inside:
139
+ nw_utm = (x, y + grid_size)
140
+ ne_utm = (x + grid_size, y + grid_size)
141
+ se_utm = (x + grid_size, y)
142
+ sw_utm = (x, y)
143
+
144
+ nw_wgs = transformer_to_wgs.transform(*nw_utm)
145
+ ne_wgs = transformer_to_wgs.transform(*ne_utm)
146
+ se_wgs = transformer_to_wgs.transform(*se_utm)
147
+ sw_wgs = transformer_to_wgs.transform(*sw_utm)
148
+
149
+ color_index = (row + col) % 2
150
+
151
+ grids.append({
152
+ 'id': grid_id,
153
+ 'row': row,
154
+ 'col': col,
155
+ 'color_index': color_index,
156
+ 'utm': {
157
+ 'nw': nw_utm,
158
+ 'ne': ne_utm,
159
+ 'se': se_utm,
160
+ 'sw': sw_utm
161
+ },
162
+ 'wgs84': {
163
+ 'nw': nw_wgs,
164
+ 'ne': ne_wgs,
165
+ 'se': se_wgs,
166
+ 'sw': sw_wgs
167
+ }
168
+ })
169
+
170
+ grid_id += 1
171
+
172
+ x += grid_size + spacing
173
+ col += 1
174
+
175
+ y += grid_size + spacing
176
+ row += 1
177
+
178
+ print(f"Generated {len(grids)} grids from {total_candidates} candidates")
179
+ return grids
180
+
181
+ def create_kml(grids: List[dict], output_path: str):
182
+ kml_header = '''<?xml version="1.0" encoding="UTF-8"?>
183
+ <kml xmlns="http://www.opengis.net/kml/2.2">
184
+ <Document>
185
+ <name>Grid Output</name>
186
+ <Style id="color0">
187
+ <LineStyle><color>ff0000ff</color><width>2</width></LineStyle>
188
+ <PolyStyle><color>4d0000ff</color></PolyStyle>
189
+ </Style>
190
+ <Style id="color1">
191
+ <LineStyle><color>ff00ff00</color><width>2</width></LineStyle>
192
+ <PolyStyle><color>4d00ff00</color></PolyStyle>
193
+ </Style>
194
+ '''
195
+
196
+ kml_footer = '''</Document>
197
+ </kml>'''
198
+
199
+ with open(output_path, 'w', encoding='utf-8') as f:
200
+ f.write(kml_header)
201
+
202
+ for grid in grids:
203
+ wgs = grid['wgs84']
204
+ color_id = f"color{grid['color_index']}"
205
+
206
+ f.write(f'''<Placemark>
207
+ <name>Grid_{grid['id']}</name>
208
+ <styleUrl>#{color_id}</styleUrl>
209
+ <Polygon>
210
+ <outerBoundaryIs>
211
+ <LinearRing>
212
+ <coordinates>
213
+ {wgs['nw'][0]},{wgs['nw'][1]},0
214
+ {wgs['ne'][0]},{wgs['ne'][1]},0
215
+ {wgs['se'][0]},{wgs['se'][1]},0
216
+ {wgs['sw'][0]},{wgs['sw'][1]},0
217
+ {wgs['nw'][0]},{wgs['nw'][1]},0
218
+ </coordinates>
219
+ </LinearRing>
220
+ </outerBoundaryIs>
221
+ </Polygon>
222
+ </Placemark>
223
+ ''')
224
+
225
+ f.write(kml_footer)
226
+
227
+ print(f"KML file saved to: {output_path}")
228
+
229
+ def create_json(grids: List[dict], output_path: str, input_polygon_count: int = 1):
230
+ output_data = {
231
+ 'grid_size_m': GRID_SIZE,
232
+ 'grid_spacing_m': GRID_SPACING,
233
+ 'input_polygons': input_polygon_count,
234
+ 'total_grids': len(grids),
235
+ 'grids': [
236
+ {
237
+ 'id': g['id'],
238
+ 'row': g['row'],
239
+ 'col': g['col'],
240
+ 'utm_nw': g['utm']['nw'],
241
+ 'utm_se': g['utm']['se'],
242
+ 'wgs84_nw': g['wgs84']['nw'],
243
+ 'wgs84_se': g['wgs84']['se']
244
+ }
245
+ for g in grids
246
+ ]
247
+ }
248
+
249
+ with open(output_path, 'w', encoding='utf-8') as f:
250
+ json.dump(output_data, f, indent=2, ensure_ascii=False)
251
+
252
+ print(f"JSON file saved to: {output_path}")
253
+
254
+ def main(input_kml: str, output_kml: str, output_json: str):
255
+ print(f"Reading input KML: {input_kml}")
256
+ print(f"Grid size: {GRID_SIZE}m, Spacing: {GRID_SPACING}m")
257
+ print("-" * 60)
258
+
259
+ polygons = parse_kml_polygons(input_kml)
260
+
261
+ if not polygons:
262
+ raise ValueError("No polygons found in input KML")
263
+
264
+ grids = generate_grid(polygons, GRID_SIZE, GRID_SPACING)
265
+
266
+ create_kml(grids, output_kml)
267
+ create_json(grids, output_json, len(polygons))
268
+
269
+ print("-" * 60)
270
+ print("Grid generation completed successfully!")
271
+
272
+ if __name__ == "__main__":
273
+ INPUT_KML = "Tile_Index.kml"
274
+ OUTPUT_KML = "output_grids.kml"
275
+ OUTPUT_JSON = "output_grids.json"
276
+
277
+ main(INPUT_KML, OUTPUT_KML, OUTPUT_JSON)