City3D-MultiGen / scripts /holicity /add_coord_head.py
e32's picture
Initial release: reconstruction pipeline + metadata
e95f494 verified
Raw
History Blame Contribute Delete
5.38 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Stamp a spatial reference (EPSG) into the headers of LAS/LAZ point clouds.
Role in the pipeline:
After HoliCity (London) tiles have been translated into real-world projected
coordinates, some files still lack a CRS recorded in their LAS header. This
utility writes the target EPSG into each file's header WITHOUT modifying any
point coordinates, so the tiles are correctly tagged for QGIS / satellite
imagery alignment before tiling.
Behavior:
- Recursively scans a directory for .las/.laz files (skipping macOS "._*"
AppleDouble sidecar files).
- For each file, first attempts to write the CRS with laspy
(header.add_crs, falling back to header.epsg).
- If laspy cannot write the SRS, falls back to the PDAL CLI
(`pdal translate ... --writers.las.a_srs=EPSG:<code>`), which embeds the
SRS into the LAS header while leaving coordinates unchanged.
- Verifies each result by reading back the header EPSG and reprojecting the
bbox center to WGS84 for a printed sanity check.
Inputs: directory of .las/.laz files (CLI: -d/--dir).
Outputs: either overwritten files (--overwrite) or copies with a suffix
(default *_srs.las, configurable via --suffix), each carrying TARGET_EPSG.
External tools: laspy, pyproj, and PDAL (`pdal translate`) as a fallback.
"""
import os
import sys
import argparse
import subprocess
from pathlib import Path
import laspy
from pyproj import CRS, Transformer
TARGET_EPSG = 27700 # OSGB36 / British National Grid (commonly used for London)
def is_mac_dot_underscore(p: Path) -> bool:
return p.name.startswith("._")
def try_write_epsg_with_laspy(in_path: Path, out_path: Path, epsg: int) -> bool:
"""Write the CRS using laspy first; return True on success."""
las = laspy.read(str(in_path))
ok = False
# Option A: add_crs (laspy 2.3+)
try:
las.header.add_crs(CRS.from_epsg(epsg))
ok = True
except Exception:
pass
# Option B: write header.epsg directly (works on some versions)
if not ok:
try:
las.header.epsg = int(epsg)
ok = True
except Exception:
ok = False
if ok:
las.write(str(out_path))
return ok
def try_write_epsg_with_pdal(in_path: Path, out_path: Path, epsg: int) -> bool:
"""Fall back to PDAL to write the SRS into the LAS header; coordinates unchanged."""
try:
cmd = [
"pdal", "translate", str(in_path), str(out_path),
"-f", "writers.las",
f"--writers.las.a_srs=EPSG:{epsg}",
"--writers.las.compression=false"
]
subprocess.check_call(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
return True
except Exception:
return False
def center_wgs84(path: Path, epsg: int):
"""Read the bbox center and reproject to WGS84, for printed verification only."""
with laspy.open(str(path)) as f:
hdr = f.header
mins = getattr(hdr, "mins", getattr(hdr, "min", (0,0,0)))
maxs = getattr(hdr, "maxs", getattr(hdr, "max", (0,0,0)))
cx = (mins[0] + maxs[0]) * 0.5
cy = (mins[1] + maxs[1]) * 0.5
tr = Transformer.from_crs(f"EPSG:{epsg}", "EPSG:4326", always_xy=True)
lon, lat = tr.transform(cx, cy)
return (lon, lat), (cx, cy), getattr(hdr, "epsg", None)
def process_file(p: Path, overwrite: bool, keep_suffix: str):
out_path = p if overwrite else p.with_name(p.stem + keep_suffix)
# Try laspy first
ok = try_write_epsg_with_laspy(p, out_path, TARGET_EPSG)
method = "laspy"
# Then fall back to PDAL
if not ok:
ok = try_write_epsg_with_pdal(p, out_path, TARGET_EPSG)
method = "pdal"
if not ok:
print(f"[FAIL] {p.name}: failed to write EPSG (neither laspy nor pdal available)")
return
# Read back to verify
(lon, lat), (cx, cy), epsg_now = center_wgs84(out_path, TARGET_EPSG)
print(f"[OK] {p.name} -> {out_path.name} via {method} "
f"| EPSG: {epsg_now} | center_xy=({cx:.3f},{cy:.3f}) | WGS84=({lon:.6f},{lat:.6f})")
def main():
ap = argparse.ArgumentParser(description="Batch-write EPSG into LAS/LAZ headers (without changing coordinates) and print a center-point verification.")
ap.add_argument("-d", "--dir", default=".", help="Directory to scan (recursive)")
ap.add_argument("--overwrite", action="store_true", help="Overwrite the original files (default writes *_srs.las)")
ap.add_argument("--suffix", default="_srs.las", help="Output suffix when not overwriting (default _srs.las)")
args = ap.parse_args()
root = Path(args.dir).resolve()
if not root.exists():
print(f"Directory does not exist: {root}", file=sys.stderr); sys.exit(1)
files = [p for p in root.rglob("*")
if p.is_file()
and p.suffix.lower() in (".las", ".laz")
and not is_mac_dot_underscore(p)]
if not files:
print("No .las/.laz files found (._* filtered out)"); return
print(f"Target EPSG: {TARGET_EPSG} | Scan directory: {root}\n")
for p in sorted(files):
try:
process_file(p, overwrite=args.overwrite, keep_suffix=args.suffix)
except Exception as e:
print(f"[ERR] {p.name}: {e}")
if __name__ == "__main__":
main()