|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Metrics, labeled previews, image grids and convergence plots for renderer evaluations. |
| 3 | +
|
| 4 | + plots.py <eval_dir> <out_dir> |
| 5 | +
|
| 6 | +Expects <eval_dir>/<scene>/{ref,cold_bsdf,cold_old,cold_new,pre_bsdf,pre_old,pre_new}/<iter>.pfm. |
| 7 | +""" |
| 8 | + |
| 9 | +import json |
| 10 | +import sys |
| 11 | +from pathlib import Path |
| 12 | + |
| 13 | +import matplotlib |
| 14 | + |
| 15 | +matplotlib.use("Agg") |
| 16 | +import matplotlib.pyplot as plt |
| 17 | +import numpy as np |
| 18 | +from PIL import Image, ImageDraw, ImageFont |
| 19 | + |
| 20 | +TECHNIQUES = [ |
| 21 | + ("bsdf", "BSDF sampling", "#2a78d6"), |
| 22 | + ("old", "MCPG (single chain)", "#eb6834"), |
| 23 | + ("new", "MCPG (dual chain)", "#1baf7a"), |
| 24 | +] |
| 25 | +PROTOCOLS = [ |
| 26 | + ("cold", "cold start (guiding trains while accumulating)"), |
| 27 | + ("pre", "after 1024 training frames"), |
| 28 | +] |
| 29 | + |
| 30 | +LUM = np.array([0.2126, 0.7152, 0.0722], np.float32) |
| 31 | +FONT = Path(matplotlib.get_data_path()) / "fonts" / "ttf" / "DejaVuSans.ttf" |
| 32 | + |
| 33 | + |
| 34 | +def read_pfm(path): |
| 35 | + with open(path, "rb") as f: |
| 36 | + header = f.readline().rstrip() |
| 37 | + if header not in (b"PF", b"Pf"): |
| 38 | + raise ValueError(f"{path}: not a PFM file ({header!r})") |
| 39 | + channels = 3 if header == b"PF" else 1 |
| 40 | + while True: |
| 41 | + line = f.readline() |
| 42 | + if not line.startswith(b"#"): |
| 43 | + break |
| 44 | + width, height = (int(v) for v in line.split()) |
| 45 | + scale = float(f.readline().rstrip()) |
| 46 | + data = np.fromfile(f, "<f4" if scale < 0 else ">f4", width * height * channels) |
| 47 | + return np.flipud(data.reshape(height, width, channels)).astype(np.float32) |
| 48 | + |
| 49 | + |
| 50 | +def finite(image): |
| 51 | + return np.nan_to_num(image, nan=0.0, posinf=0.0, neginf=0.0) |
| 52 | + |
| 53 | + |
| 54 | +def tonemap(image, exposure): |
| 55 | + x = np.clip(image * exposure, 0.0, None) |
| 56 | + x = x / (1.0 + x) |
| 57 | + return np.where(x <= 0.0031308, x * 12.92, 1.055 * np.power(x, 1 / 2.4) - 0.055) |
| 58 | + |
| 59 | + |
| 60 | +def to_u8(image, exposure): |
| 61 | + return (np.clip(tonemap(image, exposure), 0, 1) * 255).astype(np.uint8) |
| 62 | + |
| 63 | + |
| 64 | +def label(image_u8, text): |
| 65 | + img = Image.fromarray(image_u8) |
| 66 | + draw = ImageDraw.Draw(img, "RGBA") |
| 67 | + size = max(16, img.height // 40) |
| 68 | + font = ImageFont.truetype(str(FONT), size) |
| 69 | + pad = size // 2 |
| 70 | + box = draw.textbbox((pad, pad), text, font=font) |
| 71 | + draw.rectangle((0, 0, box[2] + pad, box[3] + pad), fill=(0, 0, 0, 180)) |
| 72 | + draw.text((pad, pad), text, fill=(255, 255, 255, 255), font=font) |
| 73 | + return np.asarray(img) |
| 74 | + |
| 75 | + |
| 76 | +def save_labeled(image, exposure, text, path): |
| 77 | + Image.fromarray(label(to_u8(image, exposure), text)).save(path) |
| 78 | + |
| 79 | + |
| 80 | +def metrics(ref, test, scale): |
| 81 | + r, t = ref * scale, test * scale |
| 82 | + d = t - r |
| 83 | + return { |
| 84 | + "rmse": float(np.sqrt(np.mean(d * d))), |
| 85 | + # Rousselle-style relative MSE on brightness-normalized images |
| 86 | + "rel_mse": float(np.mean(d * d / (r * r + 1e-2))), |
| 87 | + } |
| 88 | + |
| 89 | + |
| 90 | +def style_axis(ax): |
| 91 | + ax.grid(True, which="major", color="#e8e7e4", linewidth=0.7) |
| 92 | + ax.grid(True, which="minor", color="#f3f2f0", linewidth=0.5) |
| 93 | + for spine in ("top", "right"): |
| 94 | + ax.spines[spine].set_visible(False) |
| 95 | + for spine in ("left", "bottom"): |
| 96 | + ax.spines[spine].set_color("#c9c8c4") |
| 97 | + ax.tick_params(colors="#52514e", labelsize=9) |
| 98 | + ax.set_xticks([1, 4, 16, 64, 256, 1024, 4096]) |
| 99 | + ax.set_xticklabels(["1", "4", "16", "64", "256", "1024", "4096"]) |
| 100 | + |
| 101 | + |
| 102 | +def plot_protocol(ax, runs, protocol, metric): |
| 103 | + for key, name, color in TECHNIQUES: |
| 104 | + curve = runs[f"{protocol}_{key}"] |
| 105 | + spp = np.array(sorted(curve)) |
| 106 | + err = np.array([curve[s][metric] for s in spp]) |
| 107 | + ax.loglog(spp, err, color=color, linewidth=1.8, marker="o", markersize=4, label=name) |
| 108 | + |
| 109 | + |
| 110 | +def eval_scene(scene_dir, out_dir, results): |
| 111 | + scene = scene_dir.name |
| 112 | + ref_pfm = next(iter(sorted((scene_dir / "ref").glob("*.pfm")))) |
| 113 | + ref = finite(read_pfm(ref_pfm)) |
| 114 | + lum = ref @ LUM |
| 115 | + scale = 1.0 / float(np.mean(lum)) |
| 116 | + # photographic log-average key, so a bright window does not underexpose the interior |
| 117 | + exposure = 0.18 / float(np.exp(np.mean(np.log(lum + 1e-4)))) |
| 118 | + ref_spp = 16 * int(ref_pfm.stem) |
| 119 | + save_labeled(ref, exposure, f"{scene} — reference, BSDF {ref_spp} spp", |
| 120 | + out_dir / f"{scene}_reference.png") |
| 121 | + |
| 122 | + runs = {} |
| 123 | + for protocol, _ in PROTOCOLS: |
| 124 | + for key, name, _ in TECHNIQUES: |
| 125 | + run = f"{protocol}_{key}" |
| 126 | + curve = {} |
| 127 | + for pfm in sorted((scene_dir / run).glob("*.pfm")): |
| 128 | + curve[int(pfm.stem)] = metrics(ref, finite(read_pfm(pfm)), scale) |
| 129 | + runs[run] = curve |
| 130 | + print(scene, run, {s: round(v["rmse"], 4) for s, v in sorted(curve.items())}) |
| 131 | + for spp in (1, 4): |
| 132 | + pfm = scene_dir / run / f"{spp:05}.pfm" |
| 133 | + if pfm.exists(): |
| 134 | + save_labeled(finite(read_pfm(pfm)), exposure, |
| 135 | + f"{scene} — {name}, {spp} spp ({protocol})", |
| 136 | + out_dir / f"{scene}_{run}_{spp}spp.png") |
| 137 | + results[scene] = {"exposure": exposure, "runs": runs} |
| 138 | + |
| 139 | + for protocol, subtitle in PROTOCOLS: |
| 140 | + fig, ax = plt.subplots(figsize=(7.5, 5.2), dpi=160) |
| 141 | + fig.patch.set_facecolor("#fcfcfb") |
| 142 | + ax.set_facecolor("#fcfcfb") |
| 143 | + plot_protocol(ax, runs, protocol, "rmse") |
| 144 | + ax.set_xlabel("samples per pixel", color="#0b0b0b") |
| 145 | + ax.set_ylabel("RMSE", color="#0b0b0b") |
| 146 | + ax.set_title(f"{scene} — {subtitle}", color="#0b0b0b", fontsize=11, loc="left") |
| 147 | + style_axis(ax) |
| 148 | + ax.legend(frameon=False, fontsize=9, loc="lower left") |
| 149 | + fig.tight_layout() |
| 150 | + fig.savefig(out_dir / f"{scene}_convergence_{protocol}.png", |
| 151 | + facecolor=fig.get_facecolor(), bbox_inches="tight") |
| 152 | + plt.close(fig) |
| 153 | + |
| 154 | + # comparison sheet: rows 1/4 spp, columns reference | BSDF | single chain | dual chain |
| 155 | + ref_tile = label(to_u8(ref, exposure), f"reference — {ref_spp} spp") |
| 156 | + for protocol, _ in PROTOCOLS: |
| 157 | + rows = [] |
| 158 | + for spp in (1, 4): |
| 159 | + row = [ref_tile] + [ |
| 160 | + label(to_u8(finite(read_pfm(scene_dir / f"{protocol}_{key}" / f"{spp:05}.pfm")), |
| 161 | + exposure), f"{name} — {spp} spp") |
| 162 | + for key, name, _ in TECHNIQUES |
| 163 | + ] |
| 164 | + rows.append(np.concatenate(row, axis=1)) |
| 165 | + Image.fromarray(np.concatenate(rows, axis=0)).save( |
| 166 | + out_dir / f"{scene}_sheet_{protocol}.png") |
| 167 | + |
| 168 | + |
| 169 | +def evaluate(eval_dir, out_dir): |
| 170 | + out_dir.mkdir(parents=True, exist_ok=True) |
| 171 | + |
| 172 | + results = {} |
| 173 | + scenes = [d for d in sorted(eval_dir.iterdir()) if any((d / "ref").glob("*.pfm"))] |
| 174 | + for scene_dir in scenes: |
| 175 | + eval_scene(scene_dir, out_dir, results) |
| 176 | + (out_dir / "metrics.json").write_text(json.dumps(results, indent=1)) |
| 177 | + |
| 178 | + # combined small-multiples figure, one panel per scene |
| 179 | + for protocol, subtitle in PROTOCOLS: |
| 180 | + fig, axes = plt.subplots(1, len(scenes), figsize=(4.6 * len(scenes), 4.2), dpi=160) |
| 181 | + fig.patch.set_facecolor("#fcfcfb") |
| 182 | + for ax, scene_dir in zip(np.atleast_1d(axes), scenes): |
| 183 | + ax.set_facecolor("#fcfcfb") |
| 184 | + plot_protocol(ax, results[scene_dir.name]["runs"], protocol, "rmse") |
| 185 | + ax.set_title(scene_dir.name, color="#0b0b0b", fontsize=10, loc="left") |
| 186 | + ax.set_xlabel("spp", color="#52514e", fontsize=9) |
| 187 | + style_axis(ax) |
| 188 | + np.atleast_1d(axes)[0].set_ylabel("RMSE", color="#0b0b0b") |
| 189 | + np.atleast_1d(axes)[0].legend(frameon=False, fontsize=8.5, loc="lower left") |
| 190 | + fig.suptitle(f"Convergence, {subtitle}", color="#0b0b0b", fontsize=11, x=0.02, ha="left") |
| 191 | + fig.tight_layout(rect=(0, 0, 1, 0.95)) |
| 192 | + fig.savefig(out_dir / f"convergence_all_{protocol}.png", |
| 193 | + facecolor=fig.get_facecolor(), bbox_inches="tight") |
| 194 | + plt.close(fig) |
| 195 | + |
| 196 | + print("wrote", out_dir) |
| 197 | + |
| 198 | + |
| 199 | +if __name__ == "__main__": |
| 200 | + evaluate(Path(sys.argv[1]), Path(sys.argv[2])) |
0 commit comments