patchcore-mvtec-cpu / make_figures.py
salimamri9's picture
PatchCore CPU: code, 15 models, results
142281f
Raw History Blame Contribute Delete
8.77 kB
"""Figures for the report / slides (French labels)."""
from __future__ import annotations
import json
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import torch
from PIL import Image
from patchcore.data import CATEGORIES, MVTecItems, list_category, to_display
from patchcore.model import FeatureExtractor, PatchCore
from patchcore.viz import draw_contours, heat_overlay
DATA = "data/mvtec_ad"
FIG = Path("figures")
FIG.mkdir(exist_ok=True)
NAVY, TEAL, ORANGE, RED, GREY = "#0B3C49", "#0F7B73", "#E8A33D", "#C8501E", "#8A9BA0"
plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 11, "axes.spines.top": False,
"axes.spines.right": False, "axes.edgecolor": GREY, "axes.labelcolor": NAVY,
"xtick.color": NAVY, "ytick.color": NAVY})
EXTRACTOR = FeatureExtractor("wide_resnet50_2")
FR = {"bottle": "bouteille", "cable": "câble", "capsule": "capsule", "carpet": "tapis", "grid": "grille",
"hazelnut": "noisette", "leather": "cuir", "metal_nut": "écrou", "pill": "comprimé", "screw": "vis",
"tile": "carrelage", "toothbrush": "brosse à dents", "transistor": "transistor", "wood": "bois",
"zipper": "fermeture éclair"}
def load_metrics(tag):
return json.loads((Path("results") / tag / "metrics.json").read_text())
def fig_per_category(tag="wrn50_c1"):
m = load_metrics(tag)
cats = [c for c in CATEGORIES if c in m]
x = np.arange(len(cats))
fig, ax = plt.subplots(figsize=(12, 4.2))
w = 0.27
for i, (k, lab, col) in enumerate([("image_auroc", "AUROC image", NAVY), ("pixel_auroc", "AUROC pixel", TEAL),
("au_pro", "AU-PRO", ORANGE)]):
v = [m[c][k] for c in cats]
ax.bar(x + (i - 1) * w, v, w, label=f"{lab} (moy. {np.mean(v):.3f})", color=col)
ax.set_xticks(x, [FR[c] for c in cats], rotation=35, ha="right")
ax.set_ylim(0.6, 1.005)
ax.set_ylabel("score")
ax.grid(axis="y", alpha=0.3)
ax.legend(loc="lower left", frameon=False, ncol=3)
fig.tight_layout()
fig.savefig(FIG / "per_category.png", dpi=200)
plt.close(fig)
def fig_ablation(tags):
rows = []
for tag, label in tags:
p = Path("results") / tag / "metrics.json"
if not p.exists():
continue
m = load_metrics(tag)
rows.append((label, np.mean([r["image_auroc"] for r in m.values()]),
np.mean([r["pixel_auroc"] for r in m.values()]),
np.mean([r["ms_per_image"] for r in m.values()]),
np.mean([r["bank_size"] for r in m.values()])))
fig, ax = plt.subplots(1, 2, figsize=(11, 3.8))
labels = [r[0] for r in rows]
y = np.arange(len(rows))
ax[0].barh(y - 0.2, [r[1] for r in rows], 0.4, color=NAVY, label="AUROC image")
ax[0].barh(y + 0.2, [r[2] for r in rows], 0.4, color=TEAL, label="AUROC pixel")
for i, r in enumerate(rows):
ax[0].text(r[1] + 0.002, i - 0.2, f"{r[1]:.3f}", va="center", fontsize=9, color=NAVY)
ax[0].text(r[2] + 0.002, i + 0.2, f"{r[2]:.3f}", va="center", fontsize=9, color=TEAL)
ax[0].set_yticks(y, labels)
ax[0].set_xlim(0.85, 1.02)
ax[0].invert_yaxis()
ax[0].legend(frameon=False, loc="lower right", fontsize=9)
ax[0].set_title("Performance (moyenne 15 catégories)", color=NAVY, fontsize=11)
ax[1].barh(y, [r[3] for r in rows], 0.5, color=ORANGE)
for i, r in enumerate(rows):
ax[1].text(r[3] + 2, i, f"{r[3]:.0f} ms (banque {r[4]:,.0f})".replace(",", " "), va="center",
fontsize=9, color=NAVY)
ax[1].set_yticks(y, [""] * len(rows))
ax[1].invert_yaxis()
ax[1].set_xlim(0, max(r[3] for r in rows) * 1.6)
ax[1].set_title("Temps d'inférence CPU par image", color=NAVY, fontsize=11)
fig.tight_layout()
fig.savefig(FIG / "ablation.png", dpi=200)
plt.close(fig)
return rows
def fig_hist(cat, tag="wrn50_c1"):
s = json.loads((Path("results") / tag / f"{cat}_scores.json").read_text())
m = load_metrics(tag)[cat]
sc, lab = np.array(s["scores"]), np.array(s["labels"])
fig, ax = plt.subplots(figsize=(6.4, 3.6))
bins = np.linspace(sc.min(), sc.max(), 35)
ax.hist(sc[lab == 0], bins, color=TEAL, alpha=0.8, label="test normal")
ax.hist(sc[lab == 1], bins, color=RED, alpha=0.7, label="test défectueux")
ax.hist(s["calib_scores"], bins, color=GREY, alpha=0.6, label="calibration (normal)")
ax.axvline(m["image_threshold"], color=NAVY, ls="-", lw=2, label="seuil calibré (normaux seuls)")
ax.axvline(m["oracle_threshold"], color=ORANGE, ls="--", lw=2, label="seuil oracle (F1 max)")
ax.set_xlabel("score d'anomalie de l'image")
ax.set_ylabel("nb d'images")
ax.set_title(f"{FR[cat]} — distribution des scores", color=NAVY, fontsize=11)
ax.legend(frameon=False, fontsize=8)
fig.tight_layout()
fig.savefig(FIG / f"hist_{cat}.png", dpi=200)
plt.close(fig)
def predict_items(cat, items):
model = PatchCore.load(Path("models") / cat, extractor=EXTRACTOR)
ds = MVTecItems(items, resize=model.config.get("resize", 256), crop=model.config.get("crop", 224))
out = []
for i in range(len(ds)):
b = ds[i]
s, a = model.predict(b["image"][None])
out.append((b, float(s[0]), a[0].numpy()))
return model, out
def qualitative(cases, name, title_suffix=""):
"""cases: list of (category, path, caption)"""
n = len(cases)
fig, axes = plt.subplots(n, 4, figsize=(10, 2.55 * n))
axes = np.atleast_2d(axes)
for r, (cat, path, cap) in enumerate(cases):
_, _, test = list_category(DATA, cat)
item = [t for t in test if str(t[0]).endswith(path)]
model, [(b, s, a)] = predict_items(cat, item)
img = to_display(b["image"])
gt = b["mask"][0].numpy() > 0.5
pred = a >= model.pixel_threshold
ratio = s / model.image_threshold
panels = [img, draw_contours(img, gt, (40, 220, 90)), heat_overlay(img, a, model.pixel_threshold),
draw_contours(img, pred) if ratio >= 1 else img]
titles = ["Entrée", "Vérité terrain", "Carte d'anomalie",
f"Prédiction: {'DÉFAUT' if ratio >= 1 else 'OK'} ({ratio:.2f})"]
for c in range(4):
ax = axes[r, c]
ax.imshow(panels[c])
ax.set_xticks([]), ax.set_yticks([])
for sp in ax.spines.values():
sp.set_visible(False)
if r == 0 or True:
ax.set_title(titles[c], fontsize=9, color=NAVY)
axes[r, 0].set_ylabel(cap, fontsize=9, color=NAVY)
fig.tight_layout()
fig.savefig(FIG / f"{name}.png", dpi=170)
plt.close(fig)
def single_panels(cat, path, prefix):
"""Separate input / output / ground-truth images for the 3-box slide."""
_, _, test = list_category(DATA, cat)
item = [t for t in test if str(t[0]).endswith(path)]
model, [(b, s, a)] = predict_items(cat, item)
img = to_display(b["image"])
gt = b["mask"][0].numpy() > 0.5
pred = a >= model.pixel_threshold
out = heat_overlay(img, a, model.pixel_threshold)
out = draw_contours(out, pred, (255, 255, 255))
Image.fromarray(img).resize((448, 448)).save(FIG / f"{prefix}_input.png")
Image.fromarray(out).resize((448, 448)).save(FIG / f"{prefix}_output.png")
Image.fromarray(draw_contours(img, gt, (40, 220, 90))).resize((448, 448)).save(FIG / f"{prefix}_gt.png")
return s / model.image_threshold
if __name__ == "__main__":
import sys
torch.set_num_threads(12)
what = sys.argv[1:] or ["all"]
if "all" in what or "summary" in what:
fig_per_category()
print(fig_ablation([("wrn50_c1", "WRN50 · coreset 1 %"), ("wrn50_c10", "WRN50 · coreset 10 %"),
("r18_c1", "ResNet18 · coreset 1 %"), ("r18_c10", "ResNet18 · coreset 10 %")]))
if "all" in what or "qual" in what:
qualitative([("bottle", "broken_large/000.png", "bouteille · cassure"),
("carpet", "color/000.png", "tapis · tache couleur"),
("transistor", "misplaced/000.png", "transistor · mal placé"),
("hazelnut", "crack/002.png", "noisette · fissure")], "success")
qualitative([("tile", "gray_stroke/012.png", "carrelage · trait gris (FN)"),
("pill", "crack/001.png", "comprimé · fissure (FN)"),
("capsule", "good/006.png", "capsule · normale (FP)"),
("wood", "good/016.png", "bois · normal (FP)")], "failure")
print("metal_nut ratio", single_panels("metal_nut", "scratch/000.png", "ex"))
for c in ("capsule", "carpet"):
fig_hist(c)