Spaces:
Sleeping

File size: 2,408 Bytes
22938ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Score the exported model on real sprite sets by hiding frames and comparing.

    python evaluate.py examples/alan --out eval_alan.png
"""

from __future__ import annotations

import argparse
from pathlib import Path

import numpy as np
from PIL import Image

from autosprite import POSES
from autosprite.inference import SpriteCompleter
from autosprite.preprocess import prepare_frames

SCENARIOS = {
    "idle only": ("idle",),
    "idle + walk_1": ("idle", "walk_1"),
    "idle + walk_1 + jump": ("idle", "walk_1", "jump"),
}


def pixel_scores(pred: np.ndarray, truth: np.ndarray) -> tuple[float, float]:
    """Exact-pixel accuracy over the union of both silhouettes, and silhouette IoU."""
    p, t = pred[..., 3] > 0, truth[..., 3] > 0
    union = p | t
    same = union & p & t & (pred[..., :3] == truth[..., :3]).all(-1)
    return same.sum() / max(1, union.sum()), (p & t).sum() / max(1, union.sum())


def render(rows: list[list[np.ndarray]], scale: int = 8) -> Image.Image:
    h, w = rows[0][0].shape[:2]
    pad = 4
    sheet = Image.new("RGBA", (len(rows[0]) * (w * scale + pad), len(rows) * (h * scale + pad)), (225, 225, 225, 255))
    for r, row in enumerate(rows):
        for c, frame in enumerate(row):
            img = Image.fromarray(frame, "RGBA").resize((w * scale, h * scale), Image.Resampling.NEAREST)
            sheet.alpha_composite(img, (c * (w * scale + pad), r * (h * scale + pad)))
    return sheet


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("folder", type=Path)
    parser.add_argument("--model", type=Path, default=Path("weights/autosprite.onnx"))
    parser.add_argument("--out", type=Path)
    args = parser.parse_args()

    truth = prepare_frames([Image.open(args.folder / f"{p}.png") for p in POSES])
    completer = SpriteCompleter(args.model)
    rows = [truth]
    for label, given in SCENARIOS.items():
        frames = [f if p in given else None for p, f in zip(POSES, truth)]
        pred = completer.complete(frames)
        scores = [pixel_scores(pr, tr) for p, pr, tr in zip(POSES, pred, truth) if p not in given]
        acc, iou = np.mean(scores, axis=0)
        print(f"{label:24s} pixel acc {acc:.3f}  silhouette IoU {iou:.3f}")
        rows.append(pred)
    if args.out:
        render(rows).save(args.out)
        print(f"saved {args.out} (top row = ground truth)")


if __name__ == "__main__":
    main()