File size: 9,223 Bytes
ede2c89 | 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 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""wuwa_playable_character(鸣潮可操控角色识别)ONNX 最简推理示例。
纯 CPU、单文件、无训练仓库依赖;预处理与判定逻辑与训练仓库
(src/preprocess.py + src/infer.py)逐位一致:
原图 -> EXIF 转正 / 透明合成白底 -> letterbox 512x512(保宽高比、
居中、四边用边缘像素均值色填充)-> resize 到模型输入尺寸(双三次)
-> ImageNet mean/std 归一化 -> NCHW float32
模型输出: embedding(256 维, 图内已 L2 归一化) + logits(58 类, 含负类 "_negative")。
判定(三道闸,任一命中判为未知):
unknown = (top1_cos < tau) or (max softmax(logits) < p_min)
or (argmax(logits) == "_negative")
tau / p_min 存放在模型配套的 prototypes*.npz 中,必须与模型同精度成对使用。
用法:
python examples/predict.py 图片.jpg [图片2.png ...]
python examples/predict.py 图片.jpg --model latest/mnv4s_384/wuwa_playable_character_latest_mnv4s_384.onnx
python examples/predict.py 图片.jpg --json
依赖: pip install -r requirements.txt
"""
from __future__ import annotations
import argparse
import json
import time
from pathlib import Path
import numpy as np
import onnxruntime as ort
from PIL import Image, ImageOps
RELEASE_ROOT = Path(__file__).resolve().parents[1]
DEFAULT_MODEL = RELEASE_ROOT / "latest/mnv4l_448/wuwa_playable_character_latest_mnv4l_448_int8.onnx"
IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)
LETTERBOX_SIZE = 512 # 训练缓存边长:先 letterbox 到 512,再缩到模型输入尺寸
NEGATIVE_CLASSES = {"_negative"} # 背景负类:分类头 top-1 落在它上面 => 不是任何已知角色
VARIANT_MARKERS = ("_int8", "_fp16", "_fp32") # 模型文件名精度后缀 -> 配套原型库
def normalize_pil(img: Image.Image) -> Image.Image:
"""EXIF 转正、调色板转 RGBA、透明像素合成白底、统一 RGB。"""
img = ImageOps.exif_transpose(img)
if img.mode == "P":
img = img.convert("RGBA")
if img.mode in ("RGBA", "LA"):
bg = Image.new("RGB", img.size, (255, 255, 255))
bg.paste(img, mask=img.convert("RGBA").split()[-1])
return bg
if img.mode != "RGB":
return img.convert("RGB")
return img
def letterbox_square(img: Image.Image, size: int = LETTERBOX_SIZE) -> Image.Image:
"""长边缩放到 size(双三次),保宽高比,居中填充成 size x size。"""
w, h = img.size
scale = size / max(w, h)
nw, nh = max(1, round(w * scale)), max(1, round(h * scale))
small = img.resize((nw, nh), Image.BICUBIC)
if (nw, nh) == (size, size):
return small
arr = np.asarray(small, dtype=np.uint8)
border = np.concatenate([arr[0, :], arr[-1, :], arr[:, 0], arr[:, -1]], axis=0)
fill = np.clip(border.astype(np.float32).mean(axis=0).round(), 0, 255).astype(np.uint8)
out = np.empty((size, size, 3), dtype=np.uint8)
out[:] = fill
oy, ox = (size - nh) // 2, (size - nw) // 2
out[oy:oy + nh, ox:ox + nw] = arr
return Image.fromarray(out, "RGB")
def preprocess(img: Image.Image, size: int) -> np.ndarray:
"""与训练/部署完全一致的确定性预处理,返回 (1, 3, size, size) float32。"""
img = normalize_pil(img)
sq = letterbox_square(img, LETTERBOX_SIZE)
if sq.size != (size, size):
sq = sq.resize((size, size), Image.BICUBIC)
x = np.asarray(sq, dtype=np.float32) / 255.0
x = (x - IMAGENET_MEAN) / IMAGENET_STD
return np.ascontiguousarray(x.transpose(2, 0, 1)[None])
def proto_path_for(model_path: Path) -> Path:
"""模型文件 -> 配套原型库(*_int8.onnx -> prototypes_int8.npz,其余 -> prototypes.npz)。"""
stem = model_path.stem
for mk in VARIANT_MARKERS:
if stem.endswith(mk):
p = model_path.parent / f"prototypes{mk}.npz"
if p.exists():
return p
raise FileNotFoundError(f"找不到与 {model_path.name} 配套的原型库: {p.name}")
return model_path.parent / "prototypes.npz"
def softmax(x: np.ndarray) -> np.ndarray:
p = np.exp(x - x.max())
return p / p.sum()
class Predictor:
"""加载 ONNX + 原型库,predict() 返回与训练仓库 src.infer 相同结构的 dict。"""
def __init__(self, model_path: str | Path, proto_path: str | Path | None = None,
threads: int = 2, size: int | None = None):
self.model_path = Path(model_path)
self.proto_path = Path(proto_path) if proto_path else proto_path_for(self.model_path)
so = ort.SessionOptions()
so.intra_op_num_threads = threads
so.inter_op_num_threads = 1
so.enable_cpu_mem_arena = False
so.enable_mem_pattern = False
self.sess = ort.InferenceSession(str(self.model_path), so,
providers=["CPUExecutionProvider"])
self.input_name = self.sess.get_inputs()[0].name
if size:
self.size = int(size)
else:
try:
self.size = int(self.sess.get_inputs()[0].shape[2])
except (TypeError, ValueError, IndexError):
raise SystemExit("无法从模型读取输入尺寸,请用 --size 指定(448 或 384)")
with np.load(self.proto_path, allow_pickle=False) as z:
self.protos = z["protos"] # (57, 256) 归一化原型
self.class_names = [str(c) for c in z["class_names"]] # 58 类, 含 "_negative"
self.proto_class_idx = z["proto_class_idx"] # 原型行 -> class_names 下标
self.tau = float(z["tau"]) # 余弦拒识阈值(该模型/精度专用)
self.p_min = float(z["p_min"]) # 分类头置信度下限
self.version = int(z["version"])
def predict(self, img: Image.Image) -> dict:
t0 = time.perf_counter()
x = preprocess(img, self.size)
outs = self.sess.run(None, {self.input_name: x})
emb, logits = outs[0], (outs[1] if len(outs) > 1 else None)
fused = emb[0] / (np.linalg.norm(emb[0]) + 1e-9)
sims = self.protos @ fused # 与每个角色原型的余弦
top1_cos = float(sims.max()) # 拒识分数:top-1 原型余弦
best: dict[str, float] = {} # top5 按类去重(同类取最佳原型)
for i in np.argsort(-sims):
name = self.class_names[int(self.proto_class_idx[int(i)])]
if name not in best:
best[name] = float(sims[i])
if len(best) >= 5:
break
top5 = sorted(best.items(), key=lambda kv: -kv[1])
head_conf = float(np.max(softmax(logits[0]))) if logits is not None else 1.0
head_top = self.class_names[int(np.argmax(logits[0]))] if logits is not None else None
unknown = bool(top1_cos < self.tau or head_conf < self.p_min
or (head_top in NEGATIVE_CLASSES))
pred = head_top if (not unknown and head_top is not None) else None
return {
"pred": pred,
"unknown": unknown,
"top5": [{"name": n, "score": round(s, 4)} for n, s in top5],
"head_conf": round(head_conf, 4),
"top1_cos": round(top1_cos, 4),
"tau": self.tau,
"p_min": self.p_min,
"model": self.model_path.name,
"protos": self.proto_path.name,
"version": self.version,
"latency_ms": round((time.perf_counter() - t0) * 1000, 1),
}
def main() -> None:
ap = argparse.ArgumentParser(description="wuwa_playable_character ONNX 最简推理")
ap.add_argument("images", nargs="+", help="输入图片(jpg/png/webp 等)")
ap.add_argument("--model", default=str(DEFAULT_MODEL),
help="ONNX 模型路径(默认 latest/mnv4l_448 INT8)")
ap.add_argument("--protos", default=None,
help="原型库 npz 路径(默认按模型文件名自动配对)")
ap.add_argument("--size", type=int, default=None, help="覆盖输入尺寸(默认从模型读取)")
ap.add_argument("--threads", type=int, default=2, help="ORT intra-op 线程数")
ap.add_argument("--json", action="store_true", help="只输出 JSON")
args = ap.parse_args()
predictor = Predictor(args.model, args.protos, threads=args.threads, size=args.size)
for path in args.images:
with Image.open(path) as img:
result = predictor.predict(img)
if args.json:
print(json.dumps({"image": path, **result}, ensure_ascii=False))
else:
tag = "未识别(低于阈值)" if result["unknown"] else result["pred"]
print(f"{path}: {tag} ({result['latency_ms']} ms, "
f"top1_cos={result['top1_cos']:.4f} head_conf={result['head_conf']:.4f})")
for t in result["top5"]:
print(f" {t['score']:.4f} {t['name']}")
if __name__ == "__main__":
main()
|