Spaces:
Sleeping

AutoSprite / evaluate.py
neonforestmist's picture
AutoSprite: initial app (early checkpoint)
22938ed verified
Raw History Blame Contribute Delete
2.41 kB
"""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()