File size: 8,167 Bytes
62c375a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#!/usr/bin/env python3
"""Build the small preview subset shipped with the SWR-Bench Explorer Space.

For every world (nvidia_hq excluded) a few TEST views are fetched from the public dataset
(ming0531/SWR-Bench), read with the official loader (tools/swr_bench.py) and reduced to:

  data/<world>/<stem>.npz     clean + noisy cube, area abundances  (every STRIDE-th pixel, float16)
                              material id map (full resolution, uint8, 0 = background)
  data/<world>/<stem>_rgb.jpg       released sRGB render (full resolution)
  data/<world>/<stem>_mat.png       material ground truth, coloured with the world palette
  data/<world>/<stem>_cir.jpg       colour-infrared composite (850/650/550 nm) of the clean cube
  data/meta.json                    worlds, classes, palettes, wavelengths, views

Cube and ground-truth spectra are point samples of the full-resolution pixel (STRIDE*i+o, STRIDE*j+o);
nothing is averaged, so the noisy and clean spectra and the abundances refer to exactly the same pixel.
Raw downloads go to _raw/ and the large cubes are deleted after use.

Usage:  .venv/bin/python build_preview.py [--views 3] [--stride 3] [--workers 4]
"""
from __future__ import annotations

import argparse
import json
import os
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

import numpy as np
from huggingface_hub import hf_hub_download
from PIL import Image

REPO = "ming0531/SWR-Bench"
HERE = Path(__file__).resolve().parent
RAW = HERE / "_raw"
OUT = HERE / "data"

WORLDS = [  # (key, display name, setting); nvidia_hq deliberately excluded (trademark notice on the card)
    ("forbidden_city", "Forbidden City", "outdoor 路 palace complex"),
    ("market", "Market", "outdoor 路 market square with stalls and pottery"),
    ("botanical", "Botanical", "outdoor 路 botanical garden"),
    ("karst", "Karst", "outdoor 路 karst river valley with clear water"),
    ("city", "City", "outdoor 路 campus block in a city"),
    ("study", "Study", "indoor 路 scholar's study, spectral path tracing"),
    ("office", "Office", "indoor 路 open-plan office, spectral path tracing"),
    ("city_metamer", "City 路 metamers", "City variant 路 RGB metamers for vegetation and car paint"),
    ("city_stress", "City 路 stress", "City variant 路 dry or senescent foliage on ~25% of trees"),
    ("city_morning", "City 路 morning", "City variant 路 morning sun position"),
    ("city_afternoon", "City 路 afternoon", "City variant 路 afternoon sun position"),
]

# fallback categorical order (validated reference palette) for worlds without a palette in their protocol
FALLBACK = ["#257de0", "#f47230", "#00b894", "#f2a600", "#ee7fac", "#008a17", "#6a4ce2", "#ec4647"]


def fetch(rel):
    return Path(hf_hub_download(REPO, rel, repo_type="dataset", local_dir=RAW))


def hexrgb(c):
    return "#%02x%02x%02x" % tuple(int(v) for v in c[:3])


def world_palette(sc, key, names, stem):
    if sc.family == "indoor":
        pal = json.load(open(sc.shared / "scene_protocol.json")).get("material_palette")
    else:
        proto = json.load(open(sc.dir / "material_class_protocol.json"))
        pal = proto.get("primary_palette") or proto.get("palette_rgb")
    if pal and len(pal) >= len(names):
        return [hexrgb(c) for c in pal[: len(names)]]
    # derive from the released merged material preview of one view (per-class median colour)
    try:
        prev = np.asarray(Image.open(fetch(f"{key}/material_gt_rgb_merged/{stem}.png")).convert("RGB"))
        mat = sc.load_gt(stem)["material"]
        out = []
        for c in range(len(names)):
            m = mat == c
            out.append(hexrgb(np.median(prev[m], 0)) if m.sum() > 20 else FALLBACK[c % len(FALLBACK)])
        return out
    except Exception as e:  # pragma: no cover
        print(f"[{key}] palette fallback: {e}", file=sys.stderr)
        return [FALLBACK[c % len(FALLBACK)] for c in range(len(names))]


def build_world(key, name, setting, n_views, stride, keep_raw):
    t0 = time.time()
    for s in ("train", "val", "test"):
        fetch(f"{key}/transforms_{s}.json")
    for rel in (f"{key}/noise_settings.json", f"{key}/gt/spectral_sample_bank.npz",
                f"{key}/material_class_protocol.json", f"{key}/scene_protocol.json",
                f"{key}/spectral_materials.npz"):
        try:
            fetch(rel)
        except Exception:
            pass
    sys.path.insert(0, str(RAW / "tools"))
    from swr_bench import SWRScene, false_colour  # official loader

    sc = SWRScene(RAW, key, "noisy")
    names = sc.class_names()
    wl = sc.wavelengths()
    n_test = len(sc.stems("test"))
    idx = sorted(set(np.linspace(0, n_test - 1, n_views).round().astype(int).tolist()))
    od = OUT / key
    od.mkdir(parents=True, exist_ok=True)
    views, palette = [], None
    o = stride // 2
    for i in idx:
        cam = sc.camera("test", i)
        stem = cam["stem"]
        rels = [f"{key}/hsi_clean/{stem}.npy", f"{key}/hsi_noisy/{stem}.npy", f"{key}/gt/{stem}.npz",
                f"{key}/images/{stem}.png"]
        for r in rels:
            fetch(r)
        gt = sc.load_gt(stem)
        if palette is None:
            palette = world_palette(sc, key, names, stem)
        clean = np.asarray(sc.load_cube(stem))
        noisy = np.asarray(sc.load_cube(stem, other=True))
        sl = (slice(o, None, stride), slice(o, None, stride))
        c_s, n_s = clean[sl].astype(np.float32), noisy[sl].astype(np.float32)
        scale = float(max(np.abs(c_s).max(), np.abs(n_s).max(), 1e-30))
        mat = gt["material"].astype(np.int16)
        ab = gt["abundance_area"][sl].astype(np.float16)
        np.savez_compressed(
            od / f"{stem}.npz",
            clean=(c_s / scale).astype(np.float16), noisy=(n_s / scale).astype(np.float16),
            scale=np.float32(scale), abundance=ab, material=(mat + 1).astype(np.uint8),
            stride=np.int32(stride), offset=np.int32(o))
        # images
        Image.fromarray(sc.load_rgb(stem)[..., :3]).save(od / f"{stem}_rgb.jpg", quality=90)
        lut = np.zeros((len(names) + 1, 3), np.uint8)
        lut[0] = (24, 24, 27)
        for c, h in enumerate(palette):
            lut[c + 1] = [int(h[k:k + 2], 16) for k in (1, 3, 5)]
        Image.fromarray(lut[mat + 1]).save(od / f"{stem}_mat.png", optimize=True)
        Image.fromarray(false_colour(clean, wl)).save(od / f"{stem}_cir.jpg", quality=90)
        present = sorted(int(c) for c in np.unique(mat) if c >= 0)
        views.append(dict(stem=stem, split="test", test_index=int(i), present_classes=present))
        del clean, noisy, c_s, n_s, gt
        if not keep_raw:
            for r in rels[:3]:
                try:
                    os.remove(RAW / r)
                except FileNotFoundError:
                    pass
        print(f"[{key}] {stem} done ({time.time() - t0:.0f}s)", flush=True)
    fam = sc.family
    return key, dict(name=name, setting=setting, family=fam, classes=names, palette=palette,
                     views=views, n_test=n_test, wavelengths=[float(x) for x in wl])


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--views", type=int, default=3)
    ap.add_argument("--stride", type=int, default=3)
    ap.add_argument("--workers", type=int, default=4)
    ap.add_argument("--worlds", nargs="*")
    ap.add_argument("--keep-raw", action="store_true")
    a = ap.parse_args()
    fetch("tools/swr_bench.py")
    OUT.mkdir(exist_ok=True)
    todo = [w for w in WORLDS if not a.worlds or w[0] in a.worlds]
    meta_p = OUT / "meta.json"
    meta = json.load(open(meta_p)) if meta_p.is_file() else {"worlds": {}}
    with ThreadPoolExecutor(a.workers) as ex:
        res = list(ex.map(lambda w: build_world(*w, a.views, a.stride, a.keep_raw), todo))
    for k, v in res:
        meta["worlds"][k] = v
    order = [w[0] for w in WORLDS]
    meta["worlds"] = {k: meta["worlds"][k] for k in order if k in meta["worlds"]}
    meta.update(repo=REPO, units="W m^-2 sr^-1 nm^-1", resolution=[540, 960], stride=a.stride)
    json.dump(meta, open(meta_p, "w"), indent=1)
    print("wrote", meta_p)


if __name__ == "__main__":
    main()