File size: 4,178 Bytes
6da4e64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import json
import math
from pathlib import Path

import numpy as np
from PIL import Image
from skimage.metrics import structural_similarity


def load_rgb(path: Path, size: tuple[int, int] | None = None) -> np.ndarray:
    with Image.open(path) as image:
        image = image.convert("RGB")
        if size and image.size != size:
            image = image.resize(size, Image.Resampling.LANCZOS)
        return np.asarray(image, dtype=np.float32) / 255.0


def evaluate(run_dir: Path, image_dir: Path) -> dict:
    evaluations = []
    for eval_dir in sorted(run_dir.glob("eval_*"), key=lambda path: int(path.name.split("_")[-1])):
        frame_scores = []
        for render_path in sorted(eval_dir.glob("*.png")):
            source_path = next(
                (
                    image_dir / f"{render_path.stem}{suffix}"
                    for suffix in (".jpg", ".jpeg", ".png", ".webp")
                    if (image_dir / f"{render_path.stem}{suffix}").is_file()
                ),
                None,
            )
            if source_path is None:
                raise FileNotFoundError(f"No source image found for {render_path.name} in {image_dir}")
            render = load_rgb(render_path)
            source = load_rgb(source_path, (render.shape[1], render.shape[0]))
            mse = float(np.mean((render - source) ** 2))
            psnr = float("inf") if mse == 0 else -10.0 * math.log10(mse)
            ssim = float(structural_similarity(source, render, channel_axis=2, data_range=1.0))
            provenance = render_path.stem.split("-", 1)[0] if "-" in render_path.stem else "unspecified"
            frame_scores.append(
                {"frame": render_path.name, "provenance": provenance, "psnr": psnr, "ssim": ssim}
            )
        by_provenance = {}
        for provenance in sorted({item["provenance"] for item in frame_scores}):
            subset = [item for item in frame_scores if item["provenance"] == provenance]
            by_provenance[provenance] = {
                "count": len(subset),
                "psnr": float(np.mean([item["psnr"] for item in subset])),
                "ssim": float(np.mean([item["ssim"] for item in subset])),
            }
        evaluations.append(
            {
                "step": int(eval_dir.name.split("_")[-1]),
                "count": len(frame_scores),
                "psnr": float(np.mean([item["psnr"] for item in frame_scores])),
                "ssim": float(np.mean([item["ssim"] for item in frame_scores])),
                "by_provenance": by_provenance,
                "frames": frame_scores,
            }
        )
    return {
        "schema": "kineworld.reconstruction-eval.v1",
        "method": {
            "psnr": "mean per-image RGB PSNR on [0,1]",
            "ssim": "skimage structural_similarity, RGB channel_axis=2, data_range=1.0",
            "resize": "reference input Lanczos-resized to rendered dimensions",
        },
        "limitations": ["Generated reference images are not ground truth",
                        "Optimizer holdouts may have influenced camera/depth initialization",
                        "Mixed-provenance averages are not real-world reconstruction accuracy"],
        "evaluations": evaluations,
    }


def main() -> None:
    parser = argparse.ArgumentParser(description="Independently evaluate Brush render folders")
    parser.add_argument("run_dir", type=Path)
    parser.add_argument("image_dir", type=Path)
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()
    result = evaluate(args.run_dir.resolve(), args.image_dir.resolve())
    output = args.output.resolve() if args.output else args.run_dir.resolve() / "evaluation.json"
    output.write_text(json.dumps(result, indent=2), encoding="utf-8")
    if not result["evaluations"]:
        raise RuntimeError(f"No evaluation renders found in {args.run_dir.resolve()}")
    latest = result["evaluations"][-1]
    print(f"step {latest['step']}: PSNR {latest['psnr']:.6f}, SSIM {latest['ssim']:.6f} ({latest['count']} frames)")
    print(output)


if __name__ == "__main__":
    main()