"""Precomputed results -> ready-to-load map samples for the GeoLibre plugin. python -m tiles.build_samples --out /samples `samples.json` lists already-processed scenes, paths relative to it: [{"id": "bhubaneswar-campus", "name": "Campus", "place": "Bhubaneswar, India", "dwproj": "path/to/scene.dwproj"}, # a saved DepthWizard project {"id": "kurnool-village", "name": "Village", "place": "Kurnool, India", "image": "input_optical.tif", "heights": "ndsm_m.tif", # or .npy on the image grid "objects": "objects.json"}] # optional Each sample becomes `/image.jpg` (the optical image, and a `thumb.jpg`), `/height.png` (turbo overlay, transparent nodata), `/ndsm_rgb.png` (Terrain-RGB heights for the 3D surface) and `/objects.geojson`, placed by the source GeoTIFF's own georeferencing; `index.json` lists them with their map corners. The plugin loads these straight onto the map — no model run. """ from __future__ import annotations import argparse import json import tempfile import zipfile from pathlib import Path import numpy as np from tiles import outputs as geo from tiles.build_catalog import detect_rgb_bands from tiles.mosaic import _stretch def _from_dwproj(path: Path, tmp: Path) -> dict: with zipfile.ZipFile(path) as z: names = z.namelist() tifs = [n for n in names if n.startswith("source/") and n.lower().endswith((".tif", ".tiff"))] if not tifs or "ndsm_m.npy" not in names: raise ValueError(f"{path.name}: needs source/.tif and ndsm_m.npy") wanted = [tifs[0], "ndsm_m.npy"] + (["objects.json"] if "objects.json" in names else []) z.extractall(tmp, members=wanted) return { "image": tmp / tifs[0], "heights": tmp / "ndsm_m.npy", "objects": tmp / "objects.json" if "objects.json" in wanted else None, } def _read_heights(path: Path, shape: tuple[int, int]) -> np.ndarray: if path.suffix == ".npy": h = np.load(path).astype(np.float32) else: import rasterio with rasterio.open(path) as src: h = src.read(1, masked=True).filled(np.nan).astype(np.float32) if h.shape != shape: raise ValueError(f"{path.name}: heights {h.shape} do not match image {shape}") return h def build_sample(entry: dict, base: Path, out: Path) -> dict: import rasterio from PIL import Image with tempfile.TemporaryDirectory() as tmpdir: if "dwproj" in entry: paths = _from_dwproj(base / entry["dwproj"], Path(tmpdir)) else: paths = {k: (base / entry[k]) if entry.get(k) else None for k in ("image", "heights", "objects")} with rasterio.open(paths["image"]) as src: if src.crs is None: raise ValueError(f"{entry['id']}: image has no CRS") bands = src.read(indexes=list(detect_rgb_bands(src))).astype(np.float32) valid = src.dataset_mask() > 0 transform, crs, shape = src.transform, src.crs, (src.height, src.width) is8 = src.dtypes[0] == "uint8" rgb = np.moveaxis(bands, 0, -1) if not is8: rgb[valid] = _stretch(rgb[valid]) heights = _read_heights(paths["heights"], shape) heights[~valid] = np.nan objects = (json.loads(Path(paths["objects"]).read_text(encoding="utf-8")) if paths.get("objects") and Path(paths["objects"]).is_file() else None) folder = out / entry["id"] folder.mkdir(parents=True, exist_ok=True) image = Image.fromarray(np.clip(rgb + 0.5, 0, 255).astype(np.uint8)) image.save(folder / "image.jpg", quality=85, optimize=True) thumb = image.copy() thumb.thumbnail((96, 96)) thumb.save(folder / "thumb.jpg", quality=80, optimize=True) finite = heights[np.isfinite(heights)] low, high = float(finite.min()), float(finite.max()) geo.write_overlay_png(folder / "height.png", heights, max(high, 1.0)) geo.write_heights_png(folder / "ndsm_rgb.png", heights) fc =geo.write_objects_geojson(folder / "objects.geojson", objects, transform, crs) corners = geo.corners_wgs84(transform, crs, shape[1], shape[0]) kinds = [f["properties"]["kind"] for f in fc["features"]] return { "id": entry["id"], "name": entry["name"], "place": entry.get("place", ""), "corners_wgs84": corners, "bounds_wgs84": geo.bounds_wgs84(corners), "height_min_m": round(low, 2), "height_max_m": round(high, 2), "height_mean_m": round(float(finite.mean()), 2), "counts": {"buildings": kinds.count("building"), "trees": kinds.count("tree")}, "image": f"{entry['id']}/image.jpg", "thumb": f"{entry['id']}/thumb.jpg", "height": f"{entry['id']}/height.png", "heights_rgb": f"{entry['id']}/ndsm_rgb.png", "objects":f"{entry['id']}/objects.geojson", } def main(argv: list[str] | None = None) -> None: ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("manifest", type=Path, help="samples.json") ap.add_argument("--out", required=True, type=Path, help="output folder") args = ap.parse_args(argv) entries = json.loads(args.manifest.read_text(encoding="utf-8")) args.out.mkdir(parents=True, exist_ok=True) index = [] for entry in entries: index.append(build_sample(entry, args.manifest.parent, args.out)) print(f"built {entry['id']}") (args.out / "index.json").write_text(json.dumps(index, indent=1), encoding="utf-8") print(f"{len(index)} samples -> {args.out}") if __name__ == "__main__": main()