"""Figure for difficulty 2: tile defect on the border, with vs without center-crop.""" import numpy as np, torch, matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from pathlib import Path from torch.utils.data import DataLoader from patchcore.data import MVTecItems, list_category, to_display from patchcore.model import PatchCore from patchcore.viz import draw_contours, heat_overlay def main(): torch.set_num_threads(12) train, calib, test = list_category("data/mvtec_ad", "tile") item = [t for t in test if str(t[0]).endswith("gray_stroke/012.png")] panels = [] for kw, name in [({}, "avec recadrage"), ({"resize": 224, "crop": None}, "sans recadrage")]: m = PatchCore() m.fit(DataLoader(MVTecItems(train, **kw), batch_size=16, num_workers=4)) cs = torch.cat([m.predict(b["image"])[0] for b in DataLoader(MVTecItems(calib, **kw), batch_size=16)]).numpy() cm = torch.cat([m.predict(b["image"])[1] for b in DataLoader(MVTecItems(calib, **kw), batch_size=16)]).numpy() thr, pthr = float(np.quantile(cs, 0.95)), float(cm.max()) b = MVTecItems(item, **kw)[0] s, a = m.predict(b["image"][None]) img = to_display(b["image"]); gt = b["mask"][0].numpy() > 0.5 ratio = float(s[0]) / thr panels.append((draw_contours(img, gt, (40, 220, 90)), f"{name} : vérité terrain")) panels.append((heat_overlay(img, a[0].numpy(), pthr), f"{name} : {'DÉFAUT' if ratio >= 1 else 'OK'} ({ratio:.2f})")) print(name, ratio) fig, ax = plt.subplots(1, 4, figsize=(12, 3.3)) for k, (im, t) in enumerate(panels): ax[k].imshow(im); ax[k].set_title(t, fontsize=10, color="#0B3C49"); ax[k].axis("off") fig.tight_layout(); fig.savefig("figures/d2_tile.png", dpi=170) if __name__ == "__main__": main()