File size: 6,706 Bytes
cb8518a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3


from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Any

import cv2
import numpy as np
from PIL import Image


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Evaluate rendered GT/model images")
    parser.add_argument("--manifest", required=True)
    parser.add_argument("--clip_model_path", required=True)
    parser.add_argument("--out_json", required=True)
    parser.add_argument("--models", default=None)
    parser.add_argument("--batch_size", type=int, default=32)
    return parser.parse_args()


def read_image_rgb(path: Path) -> np.ndarray:
    bgr = cv2.imread(str(path), cv2.IMREAD_COLOR)
    if bgr is None:
        raise ValueError(f"Unable to decode image: {path}")
    return cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)


def photometric_loss(gt_frame: np.ndarray, pred_frame: np.ndarray) -> float:
    if pred_frame.shape[:2] != gt_frame.shape[:2]:
        h, w = gt_frame.shape[:2]
        pred_frame = cv2.resize(pred_frame, (w, h), interpolation=cv2.INTER_AREA)
    gt = gt_frame[..., :3].astype(np.float32) / 255.0
    pred = pred_frame[..., :3].astype(np.float32) / 255.0
    return float(np.mean(np.square(gt - pred)))


def score_lower_is_better(raw: float, bad_value: float = 1.0) -> float:
    if bad_value <= 0:
        return 0.0
    return float(100.0 * max(0.0, min(1.0, 1.0 - raw / bad_value)))


def encode_image_features(
    paths: list[Path],
    model: Any,
    processor: Any,
    device: str,
    batch_size: int,
) -> Any:
    import torch

    feats: list[torch.Tensor] = []
    with torch.no_grad():
        for start in range(0, len(paths), batch_size):
            chunk_paths = paths[start : start + batch_size]
            images = [Image.fromarray(read_image_rgb(p)) for p in chunk_paths]
            inputs = processor(images=images, return_tensors="pt")
            inputs = {k: v.to(device) for k, v in inputs.items()}
            image_features = model.get_image_features(**inputs)
            image_features = image_features / image_features.norm(dim=-1, keepdim=True)
            feats.append(image_features)
    return torch.cat(feats, dim=0)


def main() -> None:
    args = parse_args()
    manifest_path = Path(args.manifest).resolve()
    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    requested = [x.strip() for x in args.models.split(",") if x.strip()] if args.models else None
    models = requested or [x for x in manifest["renders"] if x != "gt"]

    from transformers import CLIPModel, CLIPProcessor
    import torch

    device = "cuda" if torch.cuda.is_available() else "cpu"
    clip_model = CLIPModel.from_pretrained(args.clip_model_path, local_files_only=True).to(device)
    clip_processor = CLIPProcessor.from_pretrained(args.clip_model_path, local_files_only=True)
    clip_model.eval()

    gt_by_frame = {int(item["gt_frame"]): Path(item["path"]) for item in manifest["renders"]["gt"]}
    results: dict[str, Any] = {}
    summary: list[dict[str, Any]] = []
    for key in models:
        pairs: list[tuple[Path, Path, int, int]] = []
        for item in manifest["renders"].get(key, []):
            gt_frame = int(item["gt_frame"])
            pred_frame = int(item["pred_frame"])
            gt_path = gt_by_frame.get(gt_frame)
            if gt_path is None:
                raise KeyError(f"Missing rendered GT image for gt_frame={gt_frame}")
            pairs.append((gt_path, Path(item["path"]), gt_frame, pred_frame))

        losses = [photometric_loss(read_image_rgb(g), read_image_rgb(p)) for g, p, _, _ in pairs]
        gt_feats = encode_image_features([g for g, _, _, _ in pairs], clip_model, clip_processor, device, args.batch_size)
        pred_feats = encode_image_features([p for _, p, _, _ in pairs], clip_model, clip_processor, device, args.batch_size)
        sims = torch.nn.functional.cosine_similarity(pred_feats, gt_feats, dim=-1)
        sim_values = sims.detach().cpu().numpy().astype(float).tolist()
        nclip_values = [float(1.0 - x) for x in sim_values]
        pl_raw = float(np.mean(losses)) if losses else 0.0
        nclip_raw = float(np.mean(nclip_values)) if nclip_values else 0.0
        result = {
            "frame_count": len(pairs),
            "pairs": [
                {"gt": str(g), "pred": str(p), "gt_frame": gt_frame, "pred_frame": pred_frame}
                for g, p, gt_frame, pred_frame in pairs
            ],
            "pl": {
                "metric": "PhotometricLoss_RenderedAlignedGTCamera",
                "pl_raw": pl_raw,
                "score_100": score_lower_is_better(pl_raw, bad_value=1.0),
                "frame_losses": losses,
                "direction": "lower_is_better",
            },
            "n_clip": {
                "metric": "VIGA_N_CLIP_RenderedAlignedGTCamera",
                "n_clip_raw": nclip_raw,
                "clip_similarity_mean": float(np.mean(sim_values)) if sim_values else 0.0,
                "score_100": float(100.0 * max(0.0, min(1.0, 1.0 - nclip_raw))),
                "frame_clip_similarity": sim_values,
                "frame_n_clip": nclip_values,
                "formula": "mean_i(1 - CLIPSim(pred_render_i, gt_render_i))",
                "direction": "lower_is_better",
            },
        }
        results[key] = result
        summary.append(
            {
                "model": key,
                "pl_raw": pl_raw,
                "pl_score_100": result["pl"]["score_100"],
                "n_clip_raw": nclip_raw,
                "n_clip_score_100": result["n_clip"]["score_100"],
                "clip_similarity_mean": result["n_clip"]["clip_similarity_mean"],
                "frame_count": len(pairs),
            }
        )

    payload = {
        "manifest": str(manifest_path),
        "clip_model_path": args.clip_model_path,
        "clip_device": device,
        "definition": {
            "pl": "MSE between GT-camera renders after alignment",
            "n_clip": "VIGA-style mean(1 - CLIPSim(pred_render, gt_render)) after alignment",
        },
        "results": results,
        "summary": summary,
        "rankings": {
            "pl_score_desc": sorted(summary, key=lambda x: x["pl_score_100"], reverse=True),
            "nclip_score_desc": sorted(summary, key=lambda x: x["n_clip_score_100"], reverse=True),
        },
    }
    out_path = Path(args.out_json).resolve()
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(payload["summary"], indent=2))
    print(f"SAVED {out_path}")


if __name__ == "__main__":
    main()