Spaces:
Running on Zero
Running on Zero
Commit Β·
b710eca
1
Parent(s): cd00edd
Add object detection and visualization features
Browse files- Implement object extraction from segmentation and height maps in `infer/objects.py`.
- Add class map previews and detected objects overlay in `viz/classes.py`.
- Update `app.py` to save segmentation and object data as artifacts.
- Enhance README with details on object classes and 3D objects.
- Create tests for object extraction in `tests/test_objects.py`.
- Update requirements and configuration files for new dependencies.
- README.md +14 -0
- app.py +58 -6
- config.py +9 -7
- infer/engine.py +11 -3
- infer/objects.py +292 -0
- pytest.ini +3 -0
- requirements.txt +2 -0
- tests/test_objects.py +156 -0
- viz/__init__.py +5 -2
- viz/classes.py +60 -0
README.md
CHANGED
|
@@ -47,6 +47,18 @@ on noisy input and roughly 4Γ slower.
|
|
| 47 |
affine), `terrain.glb` (a self-contained binary glTF with the optical image
|
| 48 |
as its base-colour texture β opens in any glTF viewer), `terrain.obj` +
|
| 49 |
`.mtl` + `texture.png` for MeshLab or Blender, and the two rasters.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
Heights are metres above local ground (nDSM). An input without georeferencing
|
| 52 |
yields a relative surface (`rDSM`); `meta.json` says which you got, and does not
|
|
@@ -58,6 +70,8 @@ publish an affine transform for a scene the demo resampled.
|
|
| 58 |
|---|---|
|
| 59 |
| `app.py` | the Space: inference, encodings, artefacts, and the viewer iframe |
|
| 60 |
| `infer/`, `dwdata/`, `models/` | the model and the preprocessing contract stored in the checkpoint |
|
|
|
|
|
|
|
| 61 |
| `viz/` | figure primitives, the mesh writers, and the standalone validation report |
|
| 62 |
| `viewer/` | the dual-pane DSM inspector β `index.html` + `app.js` + vendored three.js |
|
| 63 |
| `predict_image.py` | single-image CLI, writing the older `phase0_viewer.html` |
|
|
|
|
| 47 |
affine), `terrain.glb` (a self-contained binary glTF with the optical image
|
| 48 |
as its base-colour texture β opens in any glTF viewer), `terrain.obj` +
|
| 49 |
`.mtl` + `texture.png` for MeshLab or Blender, and the two rasters.
|
| 50 |
+
* **Object classes** β `seg.png`, the segmentation head's class per pixel on the
|
| 51 |
+
height grid (8-bit greyscale ids; the id β name legend is `meta.json`
|
| 52 |
+
`classes`: other, ground, low_veg, building, water, road, tree), plus a
|
| 53 |
+
colour preview in the gallery.
|
| 54 |
+
* **3D objects** β `objects.json` (`infer/objects.py`): trees as
|
| 55 |
+
`{x, y, h, r}` (crown centre, top height, crown radius), buildings as
|
| 56 |
+
footprint polygons with a median roof height, and water outlines. Positions
|
| 57 |
+
are pixels on the height grid; heights and radii are metres. Trees are split
|
| 58 |
+
into crowns by a watershed on the smoothed canopy seeded at its peaks, so
|
| 59 |
+
touching crowns come out as separate trees. The gallery's "Detected trees,
|
| 60 |
+
buildings and water" overlay is the check: every circle should sit on a tree.
|
| 61 |
+
A failure in this step is reported in the status and never costs the height map.
|
| 62 |
|
| 63 |
Heights are metres above local ground (nDSM). An input without georeferencing
|
| 64 |
yields a relative surface (`rDSM`); `meta.json` says which you got, and does not
|
|
|
|
| 70 |
|---|---|
|
| 71 |
| `app.py` | the Space: inference, encodings, artefacts, and the viewer iframe |
|
| 72 |
| `infer/`, `dwdata/`, `models/` | the model and the preprocessing contract stored in the checkpoint |
|
| 73 |
+
| `infer/objects.py` | class map + height map β trees / buildings / water (`objects.json`) |
|
| 74 |
+
| `tests/` | CPU-only unit tests for the object step (`pytest -q`; no torch needed) |
|
| 75 |
| `viz/` | figure primitives, the mesh writers, and the standalone validation report |
|
| 76 |
| `viewer/` | the dual-pane DSM inspector β `index.html` + `app.js` + vendored three.js |
|
| 77 |
| `predict_image.py` | single-image CLI, writing the older `phase0_viewer.html` |
|
app.py
CHANGED
|
@@ -37,6 +37,8 @@ import spaces
|
|
| 37 |
import torch
|
| 38 |
from PIL import Image
|
| 39 |
|
|
|
|
|
|
|
| 40 |
from viz import figures as viz_figures
|
| 41 |
from viz import mesh as viz_mesh
|
| 42 |
|
|
@@ -263,12 +265,26 @@ def _with_colorbar(colormap: np.ndarray, low: float, high: float) -> Image.Image
|
|
| 263 |
|
| 264 |
|
| 265 |
def _write_artifacts(
|
| 266 |
-
out_dir: Path, rgb: np.ndarray, height: np.ndarray, meta: dict, gsd_m: float
|
|
|
|
| 267 |
) -> list[str]:
|
| 268 |
"""Everything a user can take away, written by the same code as the CLI."""
|
| 269 |
out_dir.mkdir(parents=True, exist_ok=True)
|
| 270 |
files: list[str] = []
|
| 271 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
Image.fromarray(rgb).save(out_dir / "rgb.png")
|
| 273 |
np.save(out_dir / "ndsm_m.npy", height.astype(np.float32))
|
| 274 |
png16, affine = viz_mesh.encode_height_png16(height)
|
|
@@ -305,8 +321,10 @@ def _bundle(out_dir: Path, files: list[str], name_stem: str) -> list[str]:
|
|
| 305 |
archive = shutil.make_archive(
|
| 306 |
str(out_dir.parent / f"{name_stem}_result"), "zip", out_dir
|
| 307 |
)
|
|
|
|
|
|
|
| 308 |
keep = ["ndsm_m.npy", "meta.json", "terrain.glb", "height_colormap.png",
|
| 309 |
-
"hillshade.png"]
|
| 310 |
return [archive] + [str(out_dir / f) for f in keep if (out_dir / f).is_file()]
|
| 311 |
|
| 312 |
|
|
@@ -347,16 +365,19 @@ def _run_model(rgb, gsd_m, tta: bool):
|
|
| 347 |
else None
|
| 348 |
)
|
| 349 |
try:
|
| 350 |
-
|
|
|
|
|
|
|
| 351 |
model, rgb, gsd_m, spec, device,
|
| 352 |
tta=bool(tta), amp_dtype=amp_dtype, overlap=0.5, batch_tiles=4,
|
|
|
|
| 353 |
)
|
| 354 |
finally:
|
| 355 |
# hand the card back clean; the next reservation is a fresh attach
|
| 356 |
model.to("cpu")
|
| 357 |
if device.type == "cuda":
|
| 358 |
torch.cuda.empty_cache()
|
| 359 |
-
return height
|
| 360 |
|
| 361 |
|
| 362 |
_run_model_gpu = spaces.GPU(duration=_GPU_DURATION)(_run_model)
|
|
@@ -388,9 +409,20 @@ def predict(image_path: str | None, gsd: float, tta: bool = False):
|
|
| 388 |
)
|
| 389 |
|
| 390 |
runner = _run_model_gpu_tta if tta else _run_model_gpu
|
| 391 |
-
height = runner(rgb, scene_meta.gsd_m, bool(tta))
|
| 392 |
|
| 393 |
height = _sanitise(height)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 394 |
low, high = _height_bounds(height)
|
| 395 |
height16 = _encode_rg16(height, low, high)
|
| 396 |
|
|
@@ -412,11 +444,23 @@ def predict(image_path: str | None, gsd: float, tta: bool = False):
|
|
| 412 |
"transform_note": "omitted: the demo may resample the scene",
|
| 413 |
},
|
| 414 |
"preproc": spec.to_dict(),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
}
|
| 416 |
|
| 417 |
stem = _safe_stem(image_path)
|
| 418 |
out_dir = Path(tempfile.mkdtemp(prefix="dw_"))
|
| 419 |
-
files = _write_artifacts(
|
|
|
|
|
|
|
| 420 |
|
| 421 |
# --- the iframe payload, capped and re-stated in its own metres ------
|
| 422 |
rgb_small, _ = _fit(rgb, _VIEWER_MAX_SIDE, "bilinear")
|
|
@@ -437,6 +481,8 @@ def predict(image_path: str | None, gsd: float, tta: bool = False):
|
|
| 437 |
f"**scene** {height.shape[1]} Γ {height.shape[0]} px",
|
| 438 |
f"**{meta['frac_below_1m'] * 100:.1f} %** of pixels below 1 m "
|
| 439 |
"(a nadir urban scene is usually 40β70 %)",
|
|
|
|
|
|
|
| 440 |
f"Product `{meta['product']}` Β· {len(files)} artefacts written",
|
| 441 |
]
|
| 442 |
if max(orig_w, orig_h) != max(scene_meta.width, scene_meta.height):
|
|
@@ -456,7 +502,11 @@ def predict(image_path: str | None, gsd: float, tta: bool = False):
|
|
| 456 |
gallery = [
|
| 457 |
(str(out_dir / "height_colormap.png"), "Height (turbo, 0 β max, with scale)"),
|
| 458 |
(str(out_dir / "hillshade.png"), "Hillshade (315Β° / 45Β°)"),
|
|
|
|
| 459 |
]
|
|
|
|
|
|
|
|
|
|
| 460 |
return _result(
|
| 461 |
gallery, height16, viewer_html, _bundle(out_dir, files, stem),
|
| 462 |
"\n\n".join(info), warning,
|
|
@@ -491,6 +541,8 @@ surface to probe a height or slope; drag across it for an elevation profile.
|
|
| 491 |
_DOWNLOADS_LEGEND = (
|
| 492 |
"`.npy` = raw heights in metres (float32) Β· `.png` = colourised previews Β· "
|
| 493 |
"`.glb` = textured 3D mesh Β· `meta.json` = encoding + scene metadata Β· "
|
|
|
|
|
|
|
| 494 |
"the `.zip` bundles everything, named after your upload."
|
| 495 |
)
|
| 496 |
|
|
|
|
| 37 |
import torch
|
| 38 |
from PIL import Image
|
| 39 |
|
| 40 |
+
from config import CLASS_NAMES
|
| 41 |
+
from viz import classes as viz_classes
|
| 42 |
from viz import figures as viz_figures
|
| 43 |
from viz import mesh as viz_mesh
|
| 44 |
|
|
|
|
| 265 |
|
| 266 |
|
| 267 |
def _write_artifacts(
|
| 268 |
+
out_dir: Path, rgb: np.ndarray, height: np.ndarray, meta: dict, gsd_m: float,
|
| 269 |
+
seg: np.ndarray | None = None, objects: dict | None = None,
|
| 270 |
) -> list[str]:
|
| 271 |
"""Everything a user can take away, written by the same code as the CLI."""
|
| 272 |
out_dir.mkdir(parents=True, exist_ok=True)
|
| 273 |
files: list[str] = []
|
| 274 |
|
| 275 |
+
if seg is not None:
|
| 276 |
+
# class ids as an 8-bit greyscale PNG on the height grid; the legend is
|
| 277 |
+
# `meta.json` `classes`. Lossless, ~50x smaller than an .npy.
|
| 278 |
+
Image.fromarray(seg.astype(np.uint8), mode="L").save(out_dir / "seg.png")
|
| 279 |
+
viz_classes.class_preview(rgb, seg, CLASS_NAMES).save(out_dir / "classes_preview.png")
|
| 280 |
+
files += ["seg.png", "classes_preview.png"]
|
| 281 |
+
if objects is not None:
|
| 282 |
+
(out_dir / "objects.json").write_text(
|
| 283 |
+
json.dumps(objects, separators=(",", ":")), encoding="utf-8"
|
| 284 |
+
)
|
| 285 |
+
viz_classes.objects_overlay(rgb, objects).save(out_dir / "objects_overlay.png")
|
| 286 |
+
files += ["objects.json", "objects_overlay.png"]
|
| 287 |
+
|
| 288 |
Image.fromarray(rgb).save(out_dir / "rgb.png")
|
| 289 |
np.save(out_dir / "ndsm_m.npy", height.astype(np.float32))
|
| 290 |
png16, affine = viz_mesh.encode_height_png16(height)
|
|
|
|
| 321 |
archive = shutil.make_archive(
|
| 322 |
str(out_dir.parent / f"{name_stem}_result"), "zip", out_dir
|
| 323 |
)
|
| 324 |
+
# the frontend finds its inputs by name in this list, so a file it reads
|
| 325 |
+
# (seg.png, objects.json) must be here and not only inside the zip
|
| 326 |
keep = ["ndsm_m.npy", "meta.json", "terrain.glb", "height_colormap.png",
|
| 327 |
+
"hillshade.png", "seg.png", "objects.json"]
|
| 328 |
return [archive] + [str(out_dir / f) for f in keep if (out_dir / f).is_file()]
|
| 329 |
|
| 330 |
|
|
|
|
| 365 |
else None
|
| 366 |
)
|
| 367 |
try:
|
| 368 |
+
# the class map rides along on the same forward pass (one extra
|
| 369 |
+
# un-augmented pass per tile under TTA, which only augments height)
|
| 370 |
+
height, seg = predict_scene(
|
| 371 |
model, rgb, gsd_m, spec, device,
|
| 372 |
tta=bool(tta), amp_dtype=amp_dtype, overlap=0.5, batch_tiles=4,
|
| 373 |
+
want_seg=True,
|
| 374 |
)
|
| 375 |
finally:
|
| 376 |
# hand the card back clean; the next reservation is a fresh attach
|
| 377 |
model.to("cpu")
|
| 378 |
if device.type == "cuda":
|
| 379 |
torch.cuda.empty_cache()
|
| 380 |
+
return height, seg.astype(np.uint8)
|
| 381 |
|
| 382 |
|
| 383 |
_run_model_gpu = spaces.GPU(duration=_GPU_DURATION)(_run_model)
|
|
|
|
| 409 |
)
|
| 410 |
|
| 411 |
runner = _run_model_gpu_tta if tta else _run_model_gpu
|
| 412 |
+
height, seg = runner(rgb, scene_meta.gsd_m, bool(tta))
|
| 413 |
|
| 414 |
height = _sanitise(height)
|
| 415 |
+
# Objects are an extra, never a reason to lose the height map: a failure
|
| 416 |
+
# here is reported in the status and the run carries on without them.
|
| 417 |
+
objects, objects_error = None, None
|
| 418 |
+
try:
|
| 419 |
+
from infer.objects import extract_objects
|
| 420 |
+
from infer.objects import summarise as summarise_objects
|
| 421 |
+
|
| 422 |
+
objects = extract_objects(seg, height, scene_meta.gsd_m)
|
| 423 |
+
except Exception as exc: # noqa: BLE001
|
| 424 |
+
objects_error = str(exc) or type(exc).__name__
|
| 425 |
+
|
| 426 |
low, high = _height_bounds(height)
|
| 427 |
height16 = _encode_rg16(height, low, high)
|
| 428 |
|
|
|
|
| 444 |
"transform_note": "omitted: the demo may resample the scene",
|
| 445 |
},
|
| 446 |
"preproc": spec.to_dict(),
|
| 447 |
+
# `seg.png` legend: pixel value -> class name
|
| 448 |
+
"classes": {str(i): name for i, name in enumerate(CLASS_NAMES)},
|
| 449 |
+
"class_fractions": {
|
| 450 |
+
name: float((seg == i).mean()) for i, name in enumerate(CLASS_NAMES)
|
| 451 |
+
},
|
| 452 |
+
"objects": (
|
| 453 |
+
{"file": "objects.json", "version": objects["version"],
|
| 454 |
+
"counts": objects["counts"], "truncated": objects["truncated"]}
|
| 455 |
+
if objects is not None else {"error": objects_error}
|
| 456 |
+
),
|
| 457 |
}
|
| 458 |
|
| 459 |
stem = _safe_stem(image_path)
|
| 460 |
out_dir = Path(tempfile.mkdtemp(prefix="dw_"))
|
| 461 |
+
files = _write_artifacts(
|
| 462 |
+
out_dir, rgb, height, meta, scene_meta.gsd_m, seg=seg, objects=objects
|
| 463 |
+
)
|
| 464 |
|
| 465 |
# --- the iframe payload, capped and re-stated in its own metres ------
|
| 466 |
rgb_small, _ = _fit(rgb, _VIEWER_MAX_SIDE, "bilinear")
|
|
|
|
| 481 |
f"**scene** {height.shape[1]} Γ {height.shape[0]} px",
|
| 482 |
f"**{meta['frac_below_1m'] * 100:.1f} %** of pixels below 1 m "
|
| 483 |
"(a nadir urban scene is usually 40β70 %)",
|
| 484 |
+
(f"**Objects** {summarise_objects(objects)}" if objects is not None
|
| 485 |
+
else f"**Objects** not extracted: {objects_error}"),
|
| 486 |
f"Product `{meta['product']}` Β· {len(files)} artefacts written",
|
| 487 |
]
|
| 488 |
if max(orig_w, orig_h) != max(scene_meta.width, scene_meta.height):
|
|
|
|
| 502 |
gallery = [
|
| 503 |
(str(out_dir / "height_colormap.png"), "Height (turbo, 0 β max, with scale)"),
|
| 504 |
(str(out_dir / "hillshade.png"), "Hillshade (315Β° / 45Β°)"),
|
| 505 |
+
(str(out_dir / "classes_preview.png"), "Object classes (seg head)"),
|
| 506 |
]
|
| 507 |
+
if objects is not None:
|
| 508 |
+
gallery.append((str(out_dir / "objects_overlay.png"),
|
| 509 |
+
"Detected trees, buildings and water"))
|
| 510 |
return _result(
|
| 511 |
gallery, height16, viewer_html, _bundle(out_dir, files, stem),
|
| 512 |
"\n\n".join(info), warning,
|
|
|
|
| 541 |
_DOWNLOADS_LEGEND = (
|
| 542 |
"`.npy` = raw heights in metres (float32) Β· `.png` = colourised previews Β· "
|
| 543 |
"`.glb` = textured 3D mesh Β· `meta.json` = encoding + scene metadata Β· "
|
| 544 |
+
"`seg.png` = per-pixel class ids (legend in `meta.json`) Β· "
|
| 545 |
+
"`objects.json` = trees, buildings and water as 3D objects Β· "
|
| 546 |
"the `.zip` bundles everything, named after your upload."
|
| 547 |
)
|
| 548 |
|
config.py
CHANGED
|
@@ -24,14 +24,16 @@ _V3_DIR = Path(__file__).resolve().parent
|
|
| 24 |
_DEFAULT_OUTPUT_DIR = os.environ.get("DW_OUTPUT_DIR", str(_V3_DIR / "outputs" / "v3"))
|
| 25 |
_DEFAULT_DATA_ROOT = os.environ.get("DW_DATA_ROOT", str(_V3_DIR / "data"))
|
| 26 |
|
| 27 |
-
# GAMUS ships integer class ids in classes/<split>/<STEM>_CLS.h5.
|
| 28 |
-
#
|
| 29 |
-
#
|
| 30 |
-
#
|
| 31 |
-
#
|
| 32 |
-
#
|
|
|
|
| 33 |
CLASS_IDS: tuple[int, ...] = (0, 1, 2, 3, 4, 5, 6)
|
| 34 |
-
CLASS_NAMES: tuple[str, ...] =
|
|
|
|
| 35 |
N_SEG_CLASSES = 8 # 7 real ids + 7 == ignore
|
| 36 |
SEG_IGNORE_INDEX = 7
|
| 37 |
|
|
|
|
| 24 |
_DEFAULT_OUTPUT_DIR = os.environ.get("DW_OUTPUT_DIR", str(_V3_DIR / "outputs" / "v3"))
|
| 25 |
_DEFAULT_DATA_ROOT = os.environ.get("DW_DATA_ROOT", str(_V3_DIR / "data"))
|
| 26 |
|
| 27 |
+
# GAMUS ships integer class ids in classes/<split>/<STEM>_CLS.h5. v3/v4 used
|
| 28 |
+
# neutral names ("class0".."class6") until the ids were pinned from evidence;
|
| 29 |
+
# v5 pins them from the measured per-id heights (v5 config.py, 2861 GAMUS test
|
| 30 |
+
# tiles): building reads ~9.4 m, tree ~10.2 m, water is the flattest class. This
|
| 31 |
+
# is the published GAMUS order. The Space reports the class map and extracts 3D
|
| 32 |
+
# objects (`infer/objects.py`) under these names, so a checkpoint trained on a
|
| 33 |
+
# different id space must change them here.
|
| 34 |
CLASS_IDS: tuple[int, ...] = (0, 1, 2, 3, 4, 5, 6)
|
| 35 |
+
CLASS_NAMES: tuple[str, ...] = ("other", "ground", "low_veg", "building",
|
| 36 |
+
"water", "road", "tree")
|
| 37 |
N_SEG_CLASSES = 8 # 7 real ids + 7 == ignore
|
| 38 |
SEG_IGNORE_INDEX = 7
|
| 39 |
|
infer/engine.py
CHANGED
|
@@ -25,6 +25,7 @@ from __future__ import annotations
|
|
| 25 |
import numpy as np
|
| 26 |
import torch
|
| 27 |
|
|
|
|
| 28 |
from dwdata.preprocess import (
|
| 29 |
PreprocSpec, gsd_to_shape, hann2d, resize, stretch_scene, tile_origins,
|
| 30 |
)
|
|
@@ -53,7 +54,10 @@ def predict_canonical(
|
|
| 53 |
win = hann2d(S)
|
| 54 |
acc = np.zeros((Hp, Wp), np.float32)
|
| 55 |
wsum = np.zeros((Hp, Wp), np.float32)
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
| 57 |
coords = [(y, x) for y in ys for x in xs]
|
| 58 |
total = len(coords)
|
| 59 |
|
|
@@ -76,15 +80,19 @@ def predict_canonical(
|
|
| 76 |
pred, seg = out["fused"], (out["seg"] if want_seg else None)
|
| 77 |
pred = pred.float().cpu().numpy()[:, 0]
|
| 78 |
if seg is not None:
|
| 79 |
-
|
|
|
|
| 80 |
if seg_acc is None:
|
| 81 |
seg_acc = np.zeros((Hp, Wp), np.int16)
|
|
|
|
| 82 |
|
| 83 |
for i, (y, x) in enumerate(chunk):
|
| 84 |
acc[y:y + S, x:x + S] += pred[i] * win
|
| 85 |
wsum[y:y + S, x:x + S] += win
|
| 86 |
if seg is not None:
|
| 87 |
-
|
|
|
|
|
|
|
| 88 |
if progress:
|
| 89 |
progress(min(b0 + batch_tiles, total), total)
|
| 90 |
|
|
|
|
| 25 |
import numpy as np
|
| 26 |
import torch
|
| 27 |
|
| 28 |
+
from config import SEG_IGNORE_INDEX
|
| 29 |
from dwdata.preprocess import (
|
| 30 |
PreprocSpec, gsd_to_shape, hann2d, resize, stretch_scene, tile_origins,
|
| 31 |
)
|
|
|
|
| 54 |
win = hann2d(S)
|
| 55 |
acc = np.zeros((Hp, Wp), np.float32)
|
| 56 |
wsum = np.zeros((Hp, Wp), np.float32)
|
| 57 |
+
# Labels cannot be averaged, so each pixel keeps the label from the tile it
|
| 58 |
+
# sits most centrally in (largest Hann weight). Last-write-wins put a
|
| 59 |
+
# visible seam at every tile edge, where the head has the least context.
|
| 60 |
+
seg_acc = seg_best = None
|
| 61 |
coords = [(y, x) for y in ys for x in xs]
|
| 62 |
total = len(coords)
|
| 63 |
|
|
|
|
| 80 |
pred, seg = out["fused"], (out["seg"] if want_seg else None)
|
| 81 |
pred = pred.float().cpu().numpy()[:, 0]
|
| 82 |
if seg is not None:
|
| 83 |
+
# the ignore channel is a training target, never a prediction
|
| 84 |
+
seg = seg[:, :SEG_IGNORE_INDEX].float().argmax(1).cpu().numpy()
|
| 85 |
if seg_acc is None:
|
| 86 |
seg_acc = np.zeros((Hp, Wp), np.int16)
|
| 87 |
+
seg_best = np.zeros((Hp, Wp), np.float32)
|
| 88 |
|
| 89 |
for i, (y, x) in enumerate(chunk):
|
| 90 |
acc[y:y + S, x:x + S] += pred[i] * win
|
| 91 |
wsum[y:y + S, x:x + S] += win
|
| 92 |
if seg is not None:
|
| 93 |
+
better = win > seg_best[y:y + S, x:x + S]
|
| 94 |
+
seg_acc[y:y + S, x:x + S][better] = seg[i][better]
|
| 95 |
+
seg_best[y:y + S, x:x + S][better] = win[better]
|
| 96 |
if progress:
|
| 97 |
progress(min(b0 + batch_tiles, total), total)
|
| 98 |
|
infer/objects.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Class map + nDSM -> discrete 3D objects: trees, buildings, water.
|
| 2 |
+
|
| 3 |
+
The seg head says *what* each pixel is and the height heads say *how tall*. A
|
| 4 |
+
renderer wants neither: it wants "a 9 m tree here, a 12 m building with this
|
| 5 |
+
footprint there". This module is that step. It is pure numpy / scipy /
|
| 6 |
+
scikit-image and runs on the CPU after the GPU reservation has been handed back.
|
| 7 |
+
|
| 8 |
+
trees tree pixels >= `min_tree_height_m`, split into crowns by a
|
| 9 |
+
watershed on the smoothed canopy height, seeded at its peaks
|
| 10 |
+
buildings building components; height = median of the footprint's core
|
| 11 |
+
(edges eroded away, where the head blends roof into ground)
|
| 12 |
+
water water components, outline only
|
| 13 |
+
|
| 14 |
+
Output contract (`objects.json`, `version` 1)
|
| 15 |
+
---------------------------------------------
|
| 16 |
+
Positions are in **pixels of the height grid**, origin at the top-left *corner*
|
| 17 |
+
of the grid: pixel (row, col) covers x in [col, col + 1), y in [row, row + 1),
|
| 18 |
+
so its centre is (col + 0.5, row + 0.5). Multiply by `grid.gsd_m` for metres.
|
| 19 |
+
Heights, radii and areas are already metric.
|
| 20 |
+
|
| 21 |
+
trees[] {x, y, h, r} crown centroid, top height (m), crown radius (m)
|
| 22 |
+
buildings[] {poly, h, h_max, area_m2}
|
| 23 |
+
water[] {poly, area_m2}
|
| 24 |
+
|
| 25 |
+
`poly` is the outer ring only, as [[x, y], ...], first point not repeated,
|
| 26 |
+
clockwise on screen (x right, y down). Every list is sorted largest-first and
|
| 27 |
+
capped, and `truncated` says whether a cap was hit.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
from __future__ import annotations
|
| 31 |
+
|
| 32 |
+
from dataclasses import asdict, dataclass
|
| 33 |
+
|
| 34 |
+
import numpy as np
|
| 35 |
+
|
| 36 |
+
from config import CLASS_NAMES
|
| 37 |
+
|
| 38 |
+
SCHEMA_VERSION = 1
|
| 39 |
+
|
| 40 |
+
TREE_ID = CLASS_NAMES.index("tree")
|
| 41 |
+
BUILDING_ID = CLASS_NAMES.index("building")
|
| 42 |
+
WATER_ID = CLASS_NAMES.index("water")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@dataclass
|
| 46 |
+
class ObjectParams:
|
| 47 |
+
# trees
|
| 48 |
+
min_tree_height_m: float = 2.0 # below this it is shrub, drawn as ground
|
| 49 |
+
min_crown_sep_m: float = 2.5 # peaks closer than this are one crown
|
| 50 |
+
canopy_smooth_m: float = 0.75 # Gaussian sigma on the canopy before peak finding
|
| 51 |
+
min_tree_area_m2: float = 3.0 # watershed slivers smaller than this are dropped
|
| 52 |
+
max_trees: int = 20_000
|
| 53 |
+
# buildings
|
| 54 |
+
min_building_area_m2: float = 20.0
|
| 55 |
+
min_building_height_m: float = 2.0 # a "building" lower than this is a misread slab
|
| 56 |
+
building_edge_m: float = 1.0 # eroded off the footprint before taking the median
|
| 57 |
+
building_hole_m2: float = 25.0 # courtyards smaller than this are filled
|
| 58 |
+
max_buildings: int = 5_000
|
| 59 |
+
# water
|
| 60 |
+
min_water_area_m2: float = 50.0
|
| 61 |
+
max_water: int = 500
|
| 62 |
+
# shared
|
| 63 |
+
open_m: float = 1.0 # morphological opening: drops features thinner than this
|
| 64 |
+
outline_tolerance_m: float = 0.75 # Douglas-Peucker tolerance for footprints
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def extract_objects(seg: np.ndarray, height: np.ndarray, gsd_m: float,
|
| 68 |
+
params: ObjectParams | None = None) -> dict:
|
| 69 |
+
"""`seg` (H, W) class ids, `height` (H, W) metres, same grid -> objects dict."""
|
| 70 |
+
if seg.shape != height.shape:
|
| 71 |
+
raise ValueError(f"class map {seg.shape} and height map {height.shape} differ")
|
| 72 |
+
if not gsd_m or gsd_m <= 0:
|
| 73 |
+
raise ValueError(f"gsd_m must be positive, got {gsd_m}")
|
| 74 |
+
p = params or ObjectParams()
|
| 75 |
+
seg = np.asarray(seg)
|
| 76 |
+
height = np.where(np.isfinite(height), height, 0.0).astype(np.float32)
|
| 77 |
+
|
| 78 |
+
trees, trees_cut = _trees(seg == TREE_ID, height, gsd_m, p)
|
| 79 |
+
buildings, buildings_cut = _buildings(seg == BUILDING_ID, height, gsd_m, p)
|
| 80 |
+
water, water_cut = _water(seg == WATER_ID, gsd_m, p)
|
| 81 |
+
|
| 82 |
+
H, W = seg.shape
|
| 83 |
+
return {
|
| 84 |
+
"version": SCHEMA_VERSION,
|
| 85 |
+
"grid": {"width": int(W), "height": int(H), "gsd_m": float(gsd_m),
|
| 86 |
+
"origin": "top-left corner; pixel centre = (col + 0.5, row + 0.5)"},
|
| 87 |
+
"units": {"x": "px", "y": "px", "poly": "px", "h": "m", "h_max": "m",
|
| 88 |
+
"r": "m", "area_m2": "m^2"},
|
| 89 |
+
"trees": trees,
|
| 90 |
+
"buildings": buildings,
|
| 91 |
+
"water": water,
|
| 92 |
+
"counts": {"trees": len(trees), "buildings": len(buildings), "water": len(water)},
|
| 93 |
+
"truncated": {"trees": trees_cut, "buildings": buildings_cut, "water": water_cut},
|
| 94 |
+
"params": asdict(p),
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# ---------------------------------------------------------------------
|
| 99 |
+
# masks
|
| 100 |
+
# ---------------------------------------------------------------------
|
| 101 |
+
def _drop_small(mask: np.ndarray, min_px: int) -> np.ndarray:
|
| 102 |
+
from scipy import ndimage as ndi
|
| 103 |
+
|
| 104 |
+
if min_px <= 1 or not mask.any():
|
| 105 |
+
return mask
|
| 106 |
+
lab, _ = ndi.label(mask)
|
| 107 |
+
sizes = np.bincount(lab.ravel())
|
| 108 |
+
keep = sizes >= min_px
|
| 109 |
+
keep[0] = False
|
| 110 |
+
return keep[lab]
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _clean(mask: np.ndarray, gsd_m: float, min_area_m2: float, open_m: float,
|
| 114 |
+
hole_m2: float = 0.0) -> np.ndarray:
|
| 115 |
+
"""Opening, then small-blob removal, then (optionally) small-hole filling."""
|
| 116 |
+
from scipy import ndimage as ndi
|
| 117 |
+
|
| 118 |
+
radius = int(round(open_m / (2.0 * gsd_m)))
|
| 119 |
+
if radius > 0 and mask.any():
|
| 120 |
+
# a square, not a disk: a disk's opening clips every footprint corner
|
| 121 |
+
size = 2 * radius + 1
|
| 122 |
+
mask = ndi.binary_opening(mask, structure=np.ones((size, size), bool))
|
| 123 |
+
mask = _drop_small(mask, int(np.ceil(min_area_m2 / gsd_m**2)))
|
| 124 |
+
if hole_m2 > 0:
|
| 125 |
+
# a hole is a background component that is not the big outside one
|
| 126 |
+
mask = mask | ~_drop_small(~mask, int(np.ceil(hole_m2 / gsd_m**2)))
|
| 127 |
+
return mask
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
# ---------------------------------------------------------------------
|
| 131 |
+
# trees
|
| 132 |
+
# ---------------------------------------------------------------------
|
| 133 |
+
def _trees(mask: np.ndarray, height: np.ndarray, gsd_m: float,
|
| 134 |
+
p: ObjectParams) -> tuple[list[dict], bool]:
|
| 135 |
+
from scipy import ndimage as ndi
|
| 136 |
+
from skimage.feature import peak_local_max
|
| 137 |
+
from skimage.segmentation import watershed
|
| 138 |
+
|
| 139 |
+
mask = _clean(mask, gsd_m, p.min_tree_area_m2, p.open_m)
|
| 140 |
+
mask &= height >= p.min_tree_height_m
|
| 141 |
+
mask = _drop_small(mask, int(np.ceil(p.min_tree_area_m2 / gsd_m**2)))
|
| 142 |
+
if not mask.any():
|
| 143 |
+
return [], False
|
| 144 |
+
|
| 145 |
+
canopy = np.where(mask, height, 0.0).astype(np.float32)
|
| 146 |
+
sigma = p.canopy_smooth_m / gsd_m
|
| 147 |
+
smooth = ndi.gaussian_filter(canopy, sigma) if sigma >= 0.3 else canopy
|
| 148 |
+
# Tie-break plateaus towards the blob interior (1 mm per pixel from the
|
| 149 |
+
# edge): a flat-topped canopy otherwise yields a grid of equal "peaks",
|
| 150 |
+
# i.e. one tree becomes four. Far below any real crown relief.
|
| 151 |
+
smooth = smooth + 1e-3 * ndi.distance_transform_edt(mask).astype(np.float32)
|
| 152 |
+
|
| 153 |
+
comps, n_comps = ndi.label(mask)
|
| 154 |
+
min_dist = max(1, int(round(p.min_crown_sep_m / gsd_m)))
|
| 155 |
+
peaks = peak_local_max(smooth, min_distance=min_dist, labels=comps,
|
| 156 |
+
exclude_border=False)
|
| 157 |
+
markers = np.zeros(mask.shape, np.int32)
|
| 158 |
+
if len(peaks):
|
| 159 |
+
markers[peaks[:, 0], peaks[:, 1]] = np.arange(1, len(peaks) + 1)
|
| 160 |
+
|
| 161 |
+
# a flat-topped blob can yield no peak at all; it is still one tree
|
| 162 |
+
seeded = np.zeros(n_comps + 1, bool)
|
| 163 |
+
seeded[comps[markers > 0]] = True
|
| 164 |
+
missing = np.flatnonzero(~seeded[1:]) + 1
|
| 165 |
+
if len(missing):
|
| 166 |
+
pos = ndi.maximum_position(smooth, comps, missing)
|
| 167 |
+
start = int(markers.max()) + 1
|
| 168 |
+
for k, (r, c) in enumerate(pos):
|
| 169 |
+
markers[int(r), int(c)] = start + k
|
| 170 |
+
|
| 171 |
+
crowns = watershed(-smooth, markers, mask=mask)
|
| 172 |
+
|
| 173 |
+
# per-crown statistics, vectorised: tens of thousands of crowns is normal
|
| 174 |
+
rr, cc = np.nonzero(crowns)
|
| 175 |
+
lab = crowns[rr, cc]
|
| 176 |
+
n_lab = int(crowns.max()) + 1
|
| 177 |
+
count = np.bincount(lab, minlength=n_lab).astype(np.float64)
|
| 178 |
+
ok = count > 0
|
| 179 |
+
cy = np.bincount(lab, rr, n_lab)[ok] / count[ok]
|
| 180 |
+
cx = np.bincount(lab, cc, n_lab)[ok] / count[ok]
|
| 181 |
+
# raw maximum: the height head is already smooth at pixel scale (decoded at
|
| 182 |
+
# H/2 and resampled from the canonical GSD), and any filter here shaves the
|
| 183 |
+
# apex off a conical crown β a 3x3 median read an 18 m tree as 17.1 m
|
| 184 |
+
h = np.zeros(n_lab, np.float64)
|
| 185 |
+
np.maximum.at(h, lab, height[rr, cc])
|
| 186 |
+
h = h[ok]
|
| 187 |
+
area_m2 = count[ok] * gsd_m**2
|
| 188 |
+
|
| 189 |
+
keep = (area_m2 >= p.min_tree_area_m2) & (h >= p.min_tree_height_m)
|
| 190 |
+
cy, cx, h, area_m2 = cy[keep], cx[keep], h[keep], area_m2[keep]
|
| 191 |
+
order = np.argsort(-h, kind="stable")
|
| 192 |
+
truncated = len(order) > p.max_trees
|
| 193 |
+
order = order[:p.max_trees]
|
| 194 |
+
|
| 195 |
+
trees = [
|
| 196 |
+
{"x": round(float(cx[i]) + 0.5, 2), "y": round(float(cy[i]) + 0.5, 2),
|
| 197 |
+
"h": round(float(h[i]), 2),
|
| 198 |
+
"r": round(float(np.sqrt(area_m2[i] / np.pi)), 2)}
|
| 199 |
+
for i in order
|
| 200 |
+
]
|
| 201 |
+
return trees, truncated
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
# ---------------------------------------------------------------------
|
| 205 |
+
# footprints
|
| 206 |
+
# ---------------------------------------------------------------------
|
| 207 |
+
def _outline(component: np.ndarray, origin: tuple[int, int],
|
| 208 |
+
tolerance_px: float) -> list[list[float]] | None:
|
| 209 |
+
"""Outer ring of a single boolean component, in corner-origin pixels."""
|
| 210 |
+
from skimage.measure import approximate_polygon, find_contours
|
| 211 |
+
|
| 212 |
+
padded = np.pad(component, 1).astype(np.uint8)
|
| 213 |
+
contours = find_contours(padded, 0.5)
|
| 214 |
+
if not contours:
|
| 215 |
+
return None
|
| 216 |
+
ring = max(contours, key=len)
|
| 217 |
+
if tolerance_px > 0:
|
| 218 |
+
ring = approximate_polygon(ring, tolerance=tolerance_px)
|
| 219 |
+
if len(ring) > 1 and np.allclose(ring[0], ring[-1]):
|
| 220 |
+
ring = ring[:-1]
|
| 221 |
+
if len(ring) < 3:
|
| 222 |
+
return None
|
| 223 |
+
# (row, col) index space of the padded crop -> corner-origin (x, y) on the grid
|
| 224 |
+
y = ring[:, 0] - 1 + origin[0] + 0.5
|
| 225 |
+
x = ring[:, 1] - 1 + origin[1] + 0.5
|
| 226 |
+
# shoelace > 0 with y pointing down is clockwise on screen
|
| 227 |
+
if np.sum(x * np.roll(y, -1) - np.roll(x, -1) * y) < 0:
|
| 228 |
+
x, y = x[::-1], y[::-1]
|
| 229 |
+
return [[round(float(a), 2), round(float(b), 2)] for a, b in zip(x, y)]
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def _components(mask: np.ndarray):
|
| 233 |
+
from scipy import ndimage as ndi
|
| 234 |
+
|
| 235 |
+
lab, _ = ndi.label(mask)
|
| 236 |
+
for i, sl in enumerate(ndi.find_objects(lab), start=1):
|
| 237 |
+
if sl is not None:
|
| 238 |
+
yield sl, lab[sl] == i
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def _buildings(mask: np.ndarray, height: np.ndarray, gsd_m: float,
|
| 242 |
+
p: ObjectParams) -> tuple[list[dict], bool]:
|
| 243 |
+
from scipy import ndimage as ndi
|
| 244 |
+
|
| 245 |
+
mask = _clean(mask, gsd_m, p.min_building_area_m2, p.open_m, p.building_hole_m2)
|
| 246 |
+
erode = int(round(p.building_edge_m / gsd_m))
|
| 247 |
+
tol = p.outline_tolerance_m / gsd_m
|
| 248 |
+
out = []
|
| 249 |
+
for sl, comp in _components(mask):
|
| 250 |
+
core = ndi.binary_erosion(comp, iterations=erode) if erode else comp
|
| 251 |
+
# thin wings erode to nothing; fall back to the whole footprint
|
| 252 |
+
if core.sum() < max(4, 0.1 * comp.sum()):
|
| 253 |
+
core = comp
|
| 254 |
+
hv = height[sl][core]
|
| 255 |
+
h = float(np.median(hv))
|
| 256 |
+
if h < p.min_building_height_m:
|
| 257 |
+
continue
|
| 258 |
+
poly = _outline(comp, (sl[0].start, sl[1].start), tol)
|
| 259 |
+
if poly is None:
|
| 260 |
+
continue
|
| 261 |
+
out.append({"poly": poly, "h": round(h, 2),
|
| 262 |
+
"h_max": round(float(np.percentile(hv, 95)), 2),
|
| 263 |
+
"area_m2": round(float(comp.sum()) * gsd_m**2, 1)})
|
| 264 |
+
out.sort(key=lambda b: -b["area_m2"])
|
| 265 |
+
return out[:p.max_buildings], len(out) > p.max_buildings
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def _water(mask: np.ndarray, gsd_m: float, p: ObjectParams) -> tuple[list[dict], bool]:
|
| 269 |
+
mask = _clean(mask, gsd_m, p.min_water_area_m2, p.open_m, p.min_water_area_m2)
|
| 270 |
+
tol = p.outline_tolerance_m / gsd_m
|
| 271 |
+
out = []
|
| 272 |
+
for sl, comp in _components(mask):
|
| 273 |
+
poly = _outline(comp, (sl[0].start, sl[1].start), tol)
|
| 274 |
+
if poly is not None:
|
| 275 |
+
out.append({"poly": poly, "area_m2": round(float(comp.sum()) * gsd_m**2, 1)})
|
| 276 |
+
out.sort(key=lambda w: -w["area_m2"])
|
| 277 |
+
return out[:p.max_water], len(out) > p.max_water
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def summarise(objects: dict) -> str:
|
| 281 |
+
"""One status line: counts plus the mean tree / building height."""
|
| 282 |
+
t, b, w = objects["trees"], objects["buildings"], objects["water"]
|
| 283 |
+
parts = [f"{len(t)} trees"]
|
| 284 |
+
if t:
|
| 285 |
+
parts[-1] += f" (mean {np.mean([o['h'] for o in t]):.1f} m)"
|
| 286 |
+
parts.append(f"{len(b)} buildings")
|
| 287 |
+
if b:
|
| 288 |
+
parts[-1] += f" (median {np.median([o['h'] for o in b]):.1f} m)"
|
| 289 |
+
parts.append(f"{len(w)} water bodies")
|
| 290 |
+
if any(objects["truncated"].values()):
|
| 291 |
+
parts.append("capped β see objects.json `truncated`")
|
| 292 |
+
return " Β· ".join(parts)
|
pytest.ini
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[pytest]
|
| 2 |
+
testpaths = tests
|
| 3 |
+
pythonpath = .
|
requirements.txt
CHANGED
|
@@ -6,3 +6,5 @@ Pillow
|
|
| 6 |
torch
|
| 7 |
transformers
|
| 8 |
matplotlib
|
|
|
|
|
|
|
|
|
| 6 |
torch
|
| 7 |
transformers
|
| 8 |
matplotlib
|
| 9 |
+
scipy
|
| 10 |
+
scikit-image
|
tests/test_objects.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""`infer/objects.py` on synthetic class + height maps whose answer is known.
|
| 2 |
+
|
| 3 |
+
No torch, no checkpoint: `pip install numpy scipy scikit-image pillow pytest`
|
| 4 |
+
and run `pytest -q` from the repo root.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pytest
|
| 13 |
+
|
| 14 |
+
from config import CLASS_NAMES
|
| 15 |
+
from infer.objects import (
|
| 16 |
+
BUILDING_ID, TREE_ID, WATER_ID, ObjectParams, extract_objects, summarise,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
GSD = 0.5
|
| 20 |
+
GROUND_ID = CLASS_NAMES.index("ground")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def blank(h=120, w=160):
|
| 24 |
+
return np.full((h, w), GROUND_ID, np.uint8), np.zeros((h, w), np.float32)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def add_cone(seg, height, cy, cx, radius_px, top_m):
|
| 28 |
+
"""A conical crown: `top_m` at the centre, 0.5 * top at the rim."""
|
| 29 |
+
yy, xx = np.mgrid[:seg.shape[0], :seg.shape[1]]
|
| 30 |
+
d = np.hypot(yy - cy, xx - cx)
|
| 31 |
+
inside = d <= radius_px
|
| 32 |
+
seg[inside] = TREE_ID
|
| 33 |
+
cone = top_m * (1.0 - 0.5 * d / radius_px)
|
| 34 |
+
height[inside] = np.maximum(height[inside], cone[inside])
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_three_separate_trees():
|
| 38 |
+
seg, h = blank()
|
| 39 |
+
truth = [(30, 30, 8, 12.0), (30, 110, 6, 7.0), (90, 70, 10, 18.0)]
|
| 40 |
+
for cy, cx, r, top in truth:
|
| 41 |
+
add_cone(seg, h, cy, cx, r, top)
|
| 42 |
+
|
| 43 |
+
obj = extract_objects(seg, h, GSD)
|
| 44 |
+
trees = obj["trees"]
|
| 45 |
+
assert len(trees) == 3
|
| 46 |
+
# sorted tallest first
|
| 47 |
+
assert [t["h"] for t in trees] == sorted((t["h"] for t in trees), reverse=True)
|
| 48 |
+
for (cy, cx, r, top), t in zip(sorted(truth, key=lambda t: -t[3]), trees):
|
| 49 |
+
assert t["h"] == pytest.approx(top, abs=0.6)
|
| 50 |
+
# corner-origin pixels: the centre of pixel (cy, cx) is (cx + 0.5, cy + 0.5)
|
| 51 |
+
assert t["x"] == pytest.approx(cx + 0.5, abs=1.0)
|
| 52 |
+
assert t["y"] == pytest.approx(cy + 0.5, abs=1.0)
|
| 53 |
+
assert t["r"] == pytest.approx(r * GSD, rel=0.2)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_touching_crowns_are_split():
|
| 57 |
+
seg, h = blank()
|
| 58 |
+
add_cone(seg, h, 60, 60, 12, 10.0)
|
| 59 |
+
add_cone(seg, h, 60, 80, 12, 11.0) # overlaps the first
|
| 60 |
+
trees = extract_objects(seg, h, GSD)["trees"]
|
| 61 |
+
assert len(trees) == 2
|
| 62 |
+
xs = sorted(t["x"] for t in trees)
|
| 63 |
+
assert xs[0] < 70.5 < xs[1]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_flat_topped_blob_is_still_one_tree():
|
| 67 |
+
seg, h = blank()
|
| 68 |
+
seg[40:60, 40:60] = TREE_ID
|
| 69 |
+
h[40:60, 40:60] = 6.0
|
| 70 |
+
trees = extract_objects(seg, h, GSD)["trees"]
|
| 71 |
+
assert len(trees) == 1
|
| 72 |
+
assert trees[0]["h"] == pytest.approx(6.0, abs=0.01)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_shrubs_below_min_height_are_not_trees():
|
| 76 |
+
seg, h = blank()
|
| 77 |
+
add_cone(seg, h, 60, 60, 10, 1.5)
|
| 78 |
+
assert extract_objects(seg, h, GSD)["trees"] == []
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def test_building_footprint_and_height():
|
| 82 |
+
seg, h = blank()
|
| 83 |
+
seg[30:50, 10:40] = BUILDING_ID
|
| 84 |
+
h[30:50, 10:40] = 12.0
|
| 85 |
+
h[30, 10:40] = 3.0 # blurred roof edge, eroded away
|
| 86 |
+
obj = extract_objects(seg, h, GSD)
|
| 87 |
+
(b,) = obj["buildings"]
|
| 88 |
+
assert b["h"] == pytest.approx(12.0)
|
| 89 |
+
assert b["area_m2"] == pytest.approx(20 * 30 * GSD**2)
|
| 90 |
+
poly = np.array(b["poly"])
|
| 91 |
+
assert 4 <= len(poly) <= 8 # a rectangle, simplified
|
| 92 |
+
assert poly[:, 0].min() == pytest.approx(10, abs=0.6)
|
| 93 |
+
assert poly[:, 0].max() == pytest.approx(40, abs=0.6)
|
| 94 |
+
assert poly[:, 1].min() == pytest.approx(30, abs=0.6)
|
| 95 |
+
assert poly[:, 1].max() == pytest.approx(50, abs=0.6)
|
| 96 |
+
# clockwise on screen (y down) == positive shoelace
|
| 97 |
+
x, y = poly[:, 0], poly[:, 1]
|
| 98 |
+
assert np.sum(x * np.roll(y, -1) - np.roll(x, -1) * y) > 0
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def test_flat_building_is_rejected():
|
| 102 |
+
seg, h = blank()
|
| 103 |
+
seg[30:50, 10:40] = BUILDING_ID
|
| 104 |
+
h[30:50, 10:40] = 0.8
|
| 105 |
+
assert extract_objects(seg, h, GSD)["buildings"] == []
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_water_keeps_lakes_and_drops_puddles():
|
| 109 |
+
seg, h = blank()
|
| 110 |
+
seg[60:100, 60:120] = WATER_ID # 600 m^2
|
| 111 |
+
seg[10:14, 10:14] = WATER_ID # 4 m^2
|
| 112 |
+
water = extract_objects(seg, h, GSD)["water"]
|
| 113 |
+
assert len(water) == 1
|
| 114 |
+
assert water[0]["area_m2"] == pytest.approx(40 * 60 * GSD**2)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def test_caps_keep_the_tallest_and_flag_truncation():
|
| 118 |
+
seg, h = blank()
|
| 119 |
+
for cx, top in ((25, 5.0), (80, 9.0), (135, 7.0)):
|
| 120 |
+
add_cone(seg, h, 60, cx, 8, top)
|
| 121 |
+
obj = extract_objects(seg, h, GSD, ObjectParams(max_trees=2))
|
| 122 |
+
assert [round(t["h"]) for t in obj["trees"]] == [9, 7]
|
| 123 |
+
assert obj["truncated"]["trees"] is True
|
| 124 |
+
assert obj["counts"]["trees"] == 2
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def test_contract_is_json_and_self_describing():
|
| 128 |
+
seg, h = blank()
|
| 129 |
+
add_cone(seg, h, 60, 60, 8, 9.0)
|
| 130 |
+
seg[10:30, 100:140] = BUILDING_ID
|
| 131 |
+
h[10:30, 100:140] = 7.0
|
| 132 |
+
obj = json.loads(json.dumps(extract_objects(seg, h, GSD)))
|
| 133 |
+
assert obj["version"] == 1
|
| 134 |
+
assert obj["grid"] == {**obj["grid"], "width": 160, "height": 120, "gsd_m": GSD}
|
| 135 |
+
assert obj["counts"] == {"trees": 1, "buildings": 1, "water": 0}
|
| 136 |
+
assert "1 trees" in summarise(obj)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def test_empty_scene_and_bad_input():
|
| 140 |
+
seg, h = blank()
|
| 141 |
+
obj = extract_objects(seg, h, GSD)
|
| 142 |
+
assert obj["counts"] == {"trees": 0, "buildings": 0, "water": 0}
|
| 143 |
+
with pytest.raises(ValueError):
|
| 144 |
+
extract_objects(seg, h[:10], GSD)
|
| 145 |
+
with pytest.raises(ValueError):
|
| 146 |
+
extract_objects(seg, h, 0)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def test_previews_render():
|
| 150 |
+
from viz.classes import class_preview, objects_overlay
|
| 151 |
+
|
| 152 |
+
seg, h = blank()
|
| 153 |
+
add_cone(seg, h, 60, 60, 8, 9.0)
|
| 154 |
+
rgb = np.full(seg.shape + (3,), 128, np.uint8)
|
| 155 |
+
assert class_preview(rgb, seg, CLASS_NAMES).size == (160, 120)
|
| 156 |
+
assert objects_overlay(rgb, extract_objects(seg, h, GSD)).size == (160, 120)
|
viz/__init__.py
CHANGED
|
@@ -7,16 +7,19 @@ finished run's artefacts β or, in the Space, from a single in-memory predictio
|
|
| 7 |
(`colorize`, `hillshade`, `strip`).
|
| 8 |
* `mesh` β height grid -> `terrain.glb` / `terrain.obj`, and the 16-bit PNG
|
| 9 |
height encoding that carries its own decode affine.
|
|
|
|
| 10 |
* `report_html` β one self-contained validation report per run.
|
| 11 |
"""
|
| 12 |
|
| 13 |
from __future__ import annotations
|
| 14 |
|
| 15 |
-
from . import figures, mesh
|
|
|
|
| 16 |
from .figures import colorize, hillshade, strip
|
| 17 |
from .mesh import encode_height_png16, write_glb, write_mesh, write_obj
|
| 18 |
|
| 19 |
__all__ = [
|
| 20 |
-
"figures", "mesh", "colorize", "hillshade", "strip",
|
|
|
|
| 21 |
"encode_height_png16", "write_glb", "write_obj", "write_mesh",
|
| 22 |
]
|
|
|
|
| 7 |
(`colorize`, `hillshade`, `strip`).
|
| 8 |
* `mesh` β height grid -> `terrain.glb` / `terrain.obj`, and the 16-bit PNG
|
| 9 |
height encoding that carries its own decode affine.
|
| 10 |
+
* `classes` β the class-map preview and the detected-objects overlay.
|
| 11 |
* `report_html` β one self-contained validation report per run.
|
| 12 |
"""
|
| 13 |
|
| 14 |
from __future__ import annotations
|
| 15 |
|
| 16 |
+
from . import classes, figures, mesh
|
| 17 |
+
from .classes import class_preview, colorize_classes, objects_overlay
|
| 18 |
from .figures import colorize, hillshade, strip
|
| 19 |
from .mesh import encode_height_png16, write_glb, write_mesh, write_obj
|
| 20 |
|
| 21 |
__all__ = [
|
| 22 |
+
"classes", "figures", "mesh", "colorize", "hillshade", "strip",
|
| 23 |
+
"class_preview", "colorize_classes", "objects_overlay",
|
| 24 |
"encode_height_png16", "write_glb", "write_obj", "write_mesh",
|
| 25 |
]
|
viz/classes.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Class-map and object previews: the two PNGs a person reads to trust `objects.json`.
|
| 2 |
+
|
| 3 |
+
* `class_preview` β the seg head's class map blended over the optical image.
|
| 4 |
+
* `objects_overlay` β detected tree crowns, building footprints and water
|
| 5 |
+
outlines drawn on the optical image. This is the check for the object step:
|
| 6 |
+
a crown circle that does not sit on a tree is visible at a glance.
|
| 7 |
+
|
| 8 |
+
Pure numpy + Pillow, like `figures.colorize` / `figures.hillshade`. The palette
|
| 9 |
+
matches the frontend's "Object classes" layer so the two read the same.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
from PIL import Image, ImageDraw
|
| 16 |
+
|
| 17 |
+
CLASS_COLORS: dict[str, tuple[int, int, int]] = {
|
| 18 |
+
"other": (154, 160, 166),
|
| 19 |
+
"ground": (200, 181, 138),
|
| 20 |
+
"low_veg": (156, 204, 101),
|
| 21 |
+
"building": (224, 90, 71),
|
| 22 |
+
"water": (58, 143, 217),
|
| 23 |
+
"road": (95, 99, 104),
|
| 24 |
+
"tree": (46, 125, 50),
|
| 25 |
+
}
|
| 26 |
+
_UNKNOWN = (154, 160, 166)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def colorize_classes(seg: np.ndarray, names: tuple[str, ...]) -> np.ndarray:
|
| 30 |
+
"""(H, W) class ids -> (H, W, 3) uint8, by class *name* so ids can move."""
|
| 31 |
+
lut = np.array([CLASS_COLORS.get(n, _UNKNOWN) for n in names] + [_UNKNOWN] * 256,
|
| 32 |
+
np.uint8)[:256]
|
| 33 |
+
return lut[np.clip(seg, 0, 255).astype(np.uint8)]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def class_preview(rgb: np.ndarray, seg: np.ndarray, names: tuple[str, ...],
|
| 37 |
+
alpha: float = 0.6) -> Image.Image:
|
| 38 |
+
color = colorize_classes(seg, names).astype(np.float32)
|
| 39 |
+
out = alpha * color + (1.0 - alpha) * rgb.astype(np.float32)
|
| 40 |
+
return Image.fromarray(np.clip(out, 0, 255).astype(np.uint8))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def objects_overlay(rgb: np.ndarray, objects: dict) -> Image.Image:
|
| 44 |
+
"""Crowns as circles of their radius, footprints and water as outlines."""
|
| 45 |
+
gsd = float(objects["grid"]["gsd_m"])
|
| 46 |
+
base = Image.fromarray((rgb.astype(np.float32) * 0.7).astype(np.uint8))
|
| 47 |
+
draw = ImageDraw.Draw(base)
|
| 48 |
+
line = max(1, round(max(rgb.shape[:2]) / 800))
|
| 49 |
+
|
| 50 |
+
for w in objects["water"]:
|
| 51 |
+
draw.polygon([tuple(pt) for pt in w["poly"]], outline=CLASS_COLORS["water"], width=line)
|
| 52 |
+
for b in objects["buildings"]:
|
| 53 |
+
draw.polygon([tuple(pt) for pt in b["poly"]], outline=(255, 120, 90), width=line)
|
| 54 |
+
for t in objects["trees"]:
|
| 55 |
+
r = t["r"] / gsd
|
| 56 |
+
x, y = t["x"], t["y"]
|
| 57 |
+
draw.ellipse((x - r, y - r, x + r, y + r), outline=(120, 230, 120), width=line)
|
| 58 |
+
d = max(1.0, line)
|
| 59 |
+
draw.ellipse((x - d, y - d, x + d, y + d), fill=(255, 255, 255))
|
| 60 |
+
return base
|