Commit ·
142281f
0
Parent(s):
PatchCore CPU: code, 15 models, results
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributesAdded+55
- .gitignoreAdded+6
- README.mdAdded+115
- app.pyAdded+115
- demo_secours.mp4Added+3
- docs/difficulties.mdAdded+34
- examples/bottle_broken_large_000.pngAdded
- examples/capsule_crack_001.pngAdded
- examples/carpet_color_000.pngAdded
- examples/hazelnut_crack_002.pngAdded
- examples/leather_cut_000.pngAdded
- examples/metal_nut_scratch_000.pngAdded
- examples/pill_good_000.pngAdded
- examples/screw_good_000.pngAdded
- examples/tile_crack_000.pngAdded
- examples/transistor_misplaced_000.pngAdded
- examples/wood_good_000.pngAdded
- examples/zipper_broken_teeth_000.pngAdded
- fig_d2.pyAdded+37
- figures/d2_tile.pngAdded
- figures/demo_screenshot.pngAdded
- figures/ex_gt.pngAdded
- figures/ex_input.pngAdded
- figures/ex_output.pngAdded
- figures/failure.pngAdded
- figures/hist_capsule.pngAdded
- figures/hist_carpet.pngAdded
- figures/success.pngAdded
- logs/.logAdded+5
- logs/app.logAdded+45
- logs/r18_c1.logAdded+63
- logs/wrn50_c10.logAdded+3
- logs/wrn50_c10_subset.logAdded+23
- logs/wrn50_c1_nocrop.logAdded+23
- logs/wrn50_c1_part1.logAdded+19
- logs/wrn50_c1_part2.logAdded+19
- logs/wrn50_c1_part3.logAdded+26
- logs/wrn50_c1_part4.logAdded+30
- make_figures.pyAdded+194
- make_readme.pyAdded+128
- models/bottle/config.jsonAdded+34
- models/bottle/memory_bank.safetensorsAdded+3
- models/cable/config.jsonAdded+34
- models/cable/memory_bank.safetensorsAdded+3
- models/capsule/config.jsonAdded+34
- models/capsule/memory_bank.safetensorsAdded+3
- models/carpet/config.jsonAdded+34
- models/carpet/memory_bank.safetensorsAdded+3
- models/grid/config.jsonAdded+34
- models/grid/memory_bank.safetensorsAdded+3
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textdemo_secours.mp4 filter=lfs diff=lfs merge=lfs -textexamples/bottle_broken_large_000.png filter=lfs diff=lfs merge=lfs -textexamples/capsule_crack_001.png filter=lfs diff=lfs merge=lfs -textexamples/carpet_color_000.png filter=lfs diff=lfs merge=lfs -textexamples/hazelnut_crack_002.png filter=lfs diff=lfs merge=lfs -textexamples/leather_cut_000.png filter=lfs diff=lfs merge=lfs -textexamples/metal_nut_scratch_000.png filter=lfs diff=lfs merge=lfs -textexamples/pill_good_000.png filter=lfs diff=lfs merge=lfs -textexamples/screw_good_000.png filter=lfs diff=lfs merge=lfs -textexamples/tile_crack_000.png filter=lfs diff=lfs merge=lfs -textexamples/transistor_misplaced_000.png filter=lfs diff=lfs merge=lfs -textexamples/wood_good_000.png filter=lfs diff=lfs merge=lfs -textexamples/zipper_broken_teeth_000.png filter=lfs diff=lfs merge=lfs -textfigures/d2_tile.png filter=lfs diff=lfs merge=lfs -textfigures/demo_screenshot.png filter=lfs diff=lfs merge=lfs -textfigures/ex_gt.png filter=lfs diff=lfs merge=lfs -textfigures/ex_input.png filter=lfs diff=lfs merge=lfs -textfigures/ex_output.png filter=lfs diff=lfs merge=lfs -textfigures/failure.png filter=lfs diff=lfs merge=lfs -textfigures/success.png filter=lfs diff=lfs merge=lfs -text123456.venv/data/__pycache__/.playwright-mcp/presentation/node_modules/*.pyc123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115---license: cc-by-nc-sa-4.0library_name: pytorchpipeline_tag: image-segmentationtags: - anomaly-detection - industrial-inspection - patchcore - mvtec-ad - computer-visiondatasets: - foersben/mvtec-admetrics: - roc_auc - f1---
# PatchCore sur CPU — détection et localisation de défauts industriels (MVTec AD)
Projet de vision par ordinateur avancée (3e année cycle ingénieur en informatique).**Démo en ligne :** https://huggingface.co/spaces/salimamri9/patchcore-defect-detection
Le modèle n'apprend que sur des **pièces conformes**. Pour une nouvelle image, il renvoieun **score d'anomalie** (pièce OK / défectueuse) et une **carte d'anomalie** qui localise le défaut.

## Méthode
Réimplémentation *from scratch* de **PatchCore** (Roth et al., *Towards Total Recall in IndustrialAnomaly Detection*, CVPR 2022), sans anomalib, optimisée pour CPU :
1. Extracteur **Wide-ResNet-50-2** ImageNet gelé : `layer2` (512×28×28) et `layer3` (1024×14×14).2. Agrégation locale (avg-pool 3×3), `layer3` suréchantillonné à 28×28, concaténation (1536 canaux), réduction à 1024 canaux → **784 patchs × 1024** par image.3. « Apprentissage » = mémorisation des patchs des images normales puis **coreset glouton k-center (1 %)** calculé dans un espace de projection aléatoire de 128 dimensions.4. Inférence : distance de chaque patch à son plus proche voisin dans la banque → grille 28×28 → bilinéaire 224×224 → flou gaussien σ=4. Score image = max de la carte.5. **Apport du groupe — seuil automatique** : 10 % des images normales d'apprentissage sont mises de côté ; seuil = 95e centile de leurs scores (aucun défaut n'est utilisé). Voir `threshold_study.py`.
Pas de fonction de perte : aucune descente de gradient.
## Résultats (test MVTec AD, WRN-50, coreset 1 %, CPU Intel i7-1355U)
| catégorie | AUROC image | AUROC pixel | AU-PRO | F1 (seuil calibré) | ms / image | banque ||---|---|---|---|---|---|---|| bottle | 1.000 | 0.983 | 0.921 | 0.969 | 197 | 1,481 || cable | 0.994 | 0.984 | 0.923 | 0.978 | 160 | 1,583 || capsule | 0.957 | 0.987 | 0.907 | 0.958 | 173 | 1,552 || carpet | 0.990 | 0.988 | 0.912 | 0.931 | 184 | 1,975 || grid | 0.980 | 0.975 | 0.896 | 0.957 | 176 | 1,865 || hazelnut | 1.000 | 0.984 | 0.884 | 0.993 | 283 | 2,759 || leather | 1.000 | 0.990 | 0.957 | 0.911 | 294 | 1,732 || metal_nut | 0.998 | 0.984 | 0.904 | 0.984 | 247 | 1,552 || pill | 0.965 | 0.977 | 0.911 | 0.886 | 232 | 1,889 || screw | 0.944 | 0.979 | 0.874 | 0.892 | 263 | 2,257 || tile | 0.989 | 0.954 | 0.787 | 0.982 | 253 | 1,622 || toothbrush | 1.000 | 0.986 | 0.852 | 0.984 | 238 | 407 || transistor | 0.999 | 0.976 | 0.948 | 0.941 | 210 | 1,505 || wood | 0.996 | 0.938 | 0.834 | 0.909 | 211 | 1,748 || zipper | 0.994 | 0.982 | 0.928 | 0.975 | 207 | 1,693 || **moyenne** | **0.987** | **0.978** | **0.896** | **0.950** | **222** | |
Papier PatchCore-1 % (GPU) : AUROC image 0.990, AUROC pixel 0.980.
**Ablations** — ResNet-18 : AUROC image 0.982, pixel 0.972,66 ms/image (vs 222 ms pour WRN-50).
**Règles de seuil** (F1 moyen) : max 0.927 · moyenne+3σ 0.932 ·médiane+4·MAD 0.925 · **95e centile 0.950** · oracle 0.983.
## Utilisation
```bashpip install -r requirements.txthf download salimamri9/patchcore-mvtec-cpu --local-dir patchcore-mvtec-cpu && cd patchcore-mvtec-cpupython app.py # démo Gradio locale (modèles déjà dans models/)# reproduire les résultats (MVTec AD dans data/mvtec_ad) :hf download foersben/mvtec-ad --repo-type dataset --local-dir data/mvtec_ad --exclude "results/*"python run.py --tag wrn50_c1 --save-modelspython threshold_study.py wrn50_c1```
```pythonfrom PIL import Imagefrom patchcore.model import PatchCorefrom patchcore.data import image_transformm = PatchCore.load("models/bottle")score, amap = m.predict(image_transform()(Image.open("x.png").convert("RGB"))[None])print("défaut" if score.item() >= m.image_threshold else "ok")```
## Contenu du dépôt
| chemin | rôle ||---|---|| `patchcore/model.py` | extracteur, coreset, k-NN, carte d'anomalie, save/load || `patchcore/data.py` | chargement MVTec AD, split banque / calibration || `patchcore/metrics.py` | AUROC image/pixel, AU-PRO, F1 || `run.py` | fit + calibration + évaluation d'une configuration || `threshold_study.py` | comparaison des règles de seuil || `app.py` | démo Gradio || `models/<catégorie>/` | banque mémoire (safetensors fp16) + config (seuils, métriques) || `results/` | métriques et scores par image de chaque expérience || `logs/`, `docs/difficulties.md` | journaux d'exécution, difficultés rencontrées |
Environnement : voir `requirements-lock.txt` (Python 3.14.10, torch 2.15.0+cpu).
## Données et licence
MVTec AD — Bergmann et al., CVPR 2019 / IJCV 2021 — licence **CC BY-NC-SA 4.0** (usage non commercial).Les banques mémoire dérivent de ces images et sont donc publiées sous la même licence.Les images d'exemple de la démo proviennent du jeu de test MVTec AD.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115"""Gradio demo: industrial defect detection & localisation with PatchCore (CPU)."""from __future__ import annotations
import jsonimport osimport timefrom pathlib import Path
import gradio as grimport numpy as npimport torch
from patchcore.data import CATEGORIES, image_transform, load_rgb, to_displayfrom patchcore.model import FeatureExtractor, PatchCorefrom patchcore.viz import draw_contours, heat_overlay
torch.set_num_threads(max(1, os.cpu_count() or 1))MODEL_REPO = os.environ.get("MODEL_REPO", "")ROOT = Path(__file__).parent
def models_dir() -> Path: local = ROOT / "models" if local.exists() and any(local.iterdir()): return local from huggingface_hub import snapshot_download
return Path(snapshot_download(MODEL_REPO, allow_patterns=["models/*"])) / "models"
MODELS_DIR = models_dir()EXTRACTOR = FeatureExtractor("wide_resnet50_2")_cache: dict[str, PatchCore] = {}
def get_model(cat: str) -> PatchCore: if cat not in _cache: _cache[cat] = PatchCore.load(MODELS_DIR / cat, extractor=EXTRACTOR) return _cache[cat]
def analyse(image, category): if image is None: raise gr.Error("Chargez une image ou choisissez un exemple.") m = get_model(category) tf = image_transform(m.config.get("resize", 256), m.config.get("crop", 224)) x = tf(image.convert("RGB")).unsqueeze(0) t0 = time.time() score, amap = m.predict(x) dt = (time.time() - t0) * 1000 score, amap = float(score[0]), amap[0].numpy() img = to_display(x[0]) ratio = score / m.image_threshold mask = amap >= m.pixel_threshold heat = heat_overlay(img, amap, m.pixel_threshold) seg = draw_contours(img, mask) if ratio >= 1 else img bad = ratio >= 1 color = "#C8501E" if bad else "#0F7B73" verdict = "DÉFAUT DÉTECTÉ" if bad else "PIÈCE CONFORME" label = (f"<div style='background:{color};color:white;border-radius:10px;padding:14px 18px;" f"font-size:1.5em;font-weight:700;text-align:center'>{verdict} " f"<span style='font-weight:400;font-size:0.7em'>(score / seuil = {ratio:.2f})</span></div>") met = m.config.get("metrics", {}) info = ( f"**Score d'anomalie** : {score:.3f} (seuil calibré {m.image_threshold:.3f} → ratio **{ratio:.2f}**) \n" f"**Surface anormale** : {100 * mask.mean():.2f} % de l'image \n" f"**Temps d'inférence (CPU)** : {dt:.0f} ms \n" f"Modèle `{category}` : banque mémoire de {m.bank.shape[0]:,} patchs × {m.bank.shape[1]} — " f"AUROC image {met.get('image_auroc', float('nan')):.3f}, " f"AUROC pixel {met.get('pixel_auroc', float('nan')):.3f} sur le test MVTec AD" ) return label, heat, seg, info
def examples(): ex = [] d = ROOT / "examples" if d.exists(): for p in sorted(d.glob("*.png")): cat = next((c for c in sorted(CATEGORIES, key=len, reverse=True) if p.stem.startswith(c)), None) if cat: ex.append([str(p), cat]) return ex
with gr.Blocks(title="PatchCore – détection de défauts industriels") as demo: gr.Markdown( "# Détection et localisation de défauts industriels — PatchCore (CPU)\n" "Le modèle n'a vu **que des pièces conformes** pendant l'apprentissage. " "Chaque patch de l'image est comparé à une banque mémoire de patchs normaux ; " "les patchs trop éloignés sont signalés comme anomalies.\n\n" "Choisissez la catégorie de l'objet, puis chargez une image (ou cliquez sur un exemple)." ) with gr.Row(): with gr.Column(scale=1): inp = gr.Image(type="pil", label="Image d'entrée") cat = gr.Dropdown(CATEGORIES, value="bottle", label="Catégorie (modèle)") btn = gr.Button("Analyser", variant="primary") ex = examples() if ex: gr.Examples(ex, inputs=[inp, cat], examples_per_page=6, label="Exemples (MVTec AD, jeu de test)") with gr.Column(scale=2): out_label = gr.HTML() with gr.Row(): out_heat = gr.Image(label="Carte d'anomalie") out_seg = gr.Image(label="Défaut segmenté") out_info = gr.Markdown() btn.click(analyse, [inp, cat], [out_label, out_heat, out_seg, out_info]) gr.Markdown( "Données : MVTec AD (CC BY-NC-SA 4.0). Méthode : Roth et al., *Towards Total Recall in " "Industrial Anomaly Detection*, CVPR 2022 — réimplémentation et calibration du seuil par le groupe." )
if __name__ == "__main__": demo.launch()123version https://git-lfs.github.com/spec/v1oid sha256:2205943f480bcdf7ef00c45f71307e10193e0a0a18541727161c642ecb2dfdecsize 141567512345678910111213141516171819202122232425262728293031323334# Journal des difficultés rencontrées
## D1 — Seuil de décision instable : une image « normale » contient une poussière (capsule)
- **Constat** : avec la règle v1 « seuil = max des scores de calibration (images normales) », la catégorie *capsule* obtient F1 = 0.66 (rappel 0.495) alors que l'AUROC image vaut 0.957 et que le F1 oracle atteint 0.977.- **Log** (`logs/wrn50_c1_part1.log`) : `capsule image_auroc=0.9569 ... image_f1_max=0.9772 image_f1_calibrated=0.6585`- **Analyse** : top-5 des scores de calibration `[0.822 0.848 0.865 0.890 1.144]` → une seule image (`capsule/train/good/088.png`) est très au-dessus des autres. Inspection visuelle : une poussière noire sur le fond. Le modèle a raison de la signaler, mais la règle « max » propage cette erreur d'étiquetage au seuil de toute la catégorie.- **Pistes** : (a) nettoyer le jeu d'apprentissage à la main ; (b) règle mean + 3σ ; (c) règle robuste médiane + 4·1.4826·MAD ; (d) quantile 95 %. Voir `threshold_study.py`.
## D2 — Défauts situés au bord supprimés par le recadrage (carrelage)
- **Constat** : `tile/test/gray_stroke/012.png` est classée « OK » (score/seuil = 0.88) alors qu'elle est défectueuse ; la carte d'anomalie est vide et la vérité terrain n'apparaît plus qu'en bordure basse de l'image recadrée (`figures/failure.png`, ligne 1).- **Analyse** : le prétraitement standard (resize 256 → center-crop 224) supprime une bande de 16 px de chaque côté (≈ 23 % de la surface). Mesure sur tout le test : 7 images défectueuses sur 1 258 perdent plus de la moitié de leur défaut, 1 le perd entièrement (grid).- **Pistes** : (a) resize direct 224×224 sans recadrage (`run.py --no-crop`) ; (b) entrée plus grande ; (c) tuilage de l'image.- **Résultat (a)** sur 5 catégories : carrelage AUROC image 0.989 → 1.000, AU-PRO 0.787 → 0.828, l'image 012 est détectée (0.88 → 1.16) ; mais vis 0.944 → 0.925 et grille 0.980 → 0.970 (résolution effective plus faible sur les petits objets).- **Solution retenue** : prétraitement stocké par modèle (`config.json` : `resize`, `crop`) ; sans recadrage pour le carrelage uniquement. Choix fait au vu du test : à confirmer sur d'autres données.- **Résultat (d)** : capsule F1 0.659 → 0.958 ; F1 moyen 15 catégories 0.927 → 0.950 (rappel 0.910 → 0.965, fausses alarmes 9.6 % → 18.5 %).12345678910111213141516171819202122232425262728293031323334353637"""Figure for difficulty 2: tile defect on the border, with vs without center-crop."""import numpy as np, torch, matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltfrom pathlib import Pathfrom torch.utils.data import DataLoaderfrom patchcore.data import MVTecItems, list_category, to_displayfrom patchcore.model import PatchCorefrom 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()12345usage: run.py [-h] [--data DATA] [--categories [CATEGORIES ...]] [--backbone BACKBONE] [--coreset CORESET] [--tag TAG] [--batch BATCH] [--workers WORKERS] [--threads THREADS] [--save-models]run.py: error: argument --coreset: expected one argument123456789101112131415161718192021222324252627282930313233343536373839404142434445Traceback (most recent call last): File "/home/salimamri/computer-vision/.venv/lib/python3.14/site-packages/gradio/queueing.py", line 870, in process_events response = await route_utils.call_process_api( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...<6 lines>... ) ^ File "/home/salimamri/computer-vision/.venv/lib/python3.14/site-packages/gradio/route_utils.py", line 418, in call_process_api output = await app.get_blocks().process_api( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...<12 lines>... ) ^ File "/home/salimamri/computer-vision/.venv/lib/python3.14/site-packages/gradio/blocks.py", line 2698, in process_api result = await self.call_function( ^^^^^^^^^^^^^^^^^^^^^^^^^ ...<9 lines>... ) ^ File "/home/salimamri/computer-vision/.venv/lib/python3.14/site-packages/gradio/blocks.py", line 1963, in call_function prediction = await anyio.to_thread.run_sync( # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ fn, *processed_input, limiter=self.limiter ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ) ^ File "/home/salimamri/computer-vision/.venv/lib/python3.14/site-packages/anyio/to_thread.py", line 65, in run_sync return await get_async_backend().run_sync_in_worker_thread( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ func, args, abandon_on_cancel=abandon_on_cancel, limiter=limiter ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ) ^ File "/home/salimamri/computer-vision/.venv/lib/python3.14/site-packages/anyio/_backends/_asyncio.py", line 2779, in run_sync_in_worker_thread return await future ^^^^^^^^^^^^ File "/home/salimamri/computer-vision/.venv/lib/python3.14/site-packages/anyio/_backends/_asyncio.py", line 1124, in run result = context.run(func, *args) File "/home/salimamri/computer-vision/.venv/lib/python3.14/site-packages/gradio/utils.py", line 1116, in wrapper response = f(*args, **kwargs) File "/home/salimamri/computer-vision/app.py", line 44, in analyse raise gr.Error("Chargez une image ou choisissez un exemple.")gradio.exceptions.Error: 'Chargez une image ou choisissez un exemple.'/usr/lib/python3.14/multiprocessing/resource_tracker.py:475: UserWarning: resource_tracker: There appear to be 1 leaked semaphore objects to clean up at shutdown: {'/mp-wl69jc17'} warnings.warn(123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263=== bottle [r18_c1] memory bank: 148,176 patches -> coreset 1,481 (feat 17.6s, coreset 28.1s) image_auroc=1.0000 pixel_auroc=0.9777 au_pro=0.9151 image_f1_max=1.0000 image_f1_calibrated=0.9692 ms_per_image=65.1520=== cable [r18_c1] memory bank: 158,368 patches -> coreset 1,583 (feat 11.9s, coreset 22.0s) image_auroc=0.9863 pixel_auroc=0.9762 au_pro=0.9163 image_f1_max=0.9514 image_f1_calibrated=0.9468 ms_per_image=72.7497=== capsule [r18_c1] memory bank: 155,232 patches -> coreset 1,552 (feat 12.7s, coreset 24.7s) image_auroc=0.9469 pixel_auroc=0.9843 au_pro=0.8916 image_f1_max=0.9636 image_f1_calibrated=0.9589 ms_per_image=75.5483=== carpet [r18_c1] memory bank: 197,568 patches -> coreset 1,975 (feat 19.1s, coreset 32.5s) image_auroc=0.9795 pixel_auroc=0.9873 au_pro=0.9297 image_f1_max=0.9663 image_f1_calibrated=0.9263 ms_per_image=81.8062=== grid [r18_c1] memory bank: 186,592 patches -> coreset 1,865 (feat 12.5s, coreset 31.2s) image_auroc=0.9591 pixel_auroc=0.9621 au_pro=0.8717 image_f1_max=0.9412 image_f1_calibrated=0.9204 ms_per_image=70.0422=== hazelnut [r18_c1] memory bank: 275,968 patches -> coreset 2,759 (feat 22.3s, coreset 74.0s) image_auroc=1.0000 pixel_auroc=0.9822 au_pro=0.8446 image_f1_max=1.0000 image_f1_calibrated=1.0000 ms_per_image=87.7973=== leather [r18_c1] memory bank: 173,264 patches -> coreset 1,732 (feat 13.4s, coreset 24.2s) image_auroc=1.0000 pixel_auroc=0.9901 au_pro=0.9636 image_f1_max=1.0000 image_f1_calibrated=0.9340 ms_per_image=61.2192=== metal_nut [r18_c1] memory bank: 155,232 patches -> coreset 1,552 (feat 8.0s, coreset 20.3s) image_auroc=0.9971 pixel_auroc=0.9744 au_pro=0.9033 image_f1_max=0.9841 image_f1_calibrated=0.9785 ms_per_image=53.7824=== pill [r18_c1] memory bank: 188,944 patches -> coreset 1,889 (feat 11.7s, coreset 22.9s) image_auroc=0.9588 pixel_auroc=0.9658 au_pro=0.8965 image_f1_max=0.9617 image_f1_calibrated=0.8313 ms_per_image=72.1890=== screw [r18_c1] memory bank: 225,792 patches -> coreset 2,257 (feat 12.4s, coreset 30.2s) image_auroc=0.9414 pixel_auroc=0.9849 au_pro=0.9131 image_f1_max=0.9211 image_f1_calibrated=0.8502 ms_per_image=57.3492=== tile [r18_c1] memory bank: 162,288 patches -> coreset 1,622 (feat 9.5s, coreset 15.8s) image_auroc=0.9867 pixel_auroc=0.9330 au_pro=0.7575 image_f1_max=0.9820 image_f1_calibrated=0.9759 ms_per_image=54.8988=== toothbrush [r18_c1] memory bank: 40,768 patches -> coreset 407 (feat 3.2s, coreset 1.7s) image_auroc=1.0000 pixel_auroc=0.9862 au_pro=0.8820 image_f1_max=1.0000 image_f1_calibrated=0.9524 ms_per_image=60.9241=== transistor [r18_c1] memory bank: 150,528 patches -> coreset 1,505 (feat 9.6s, coreset 14.1s) image_auroc=1.0000 pixel_auroc=0.9691 au_pro=0.9389 image_f1_max=1.0000 image_f1_calibrated=0.8247 ms_per_image=61.4579=== wood [r18_c1] memory bank: 174,832 patches -> coreset 1,748 (feat 10.5s, coreset 20.4s) image_auroc=0.9877 pixel_auroc=0.9225 au_pro=0.8498 image_f1_max=0.9748 image_f1_calibrated=0.9440 ms_per_image=64.5355=== zipper [r18_c1] memory bank: 169,344 patches -> coreset 1,693 (feat 9.3s, coreset 19.7s) image_auroc=0.9798 pixel_auroc=0.9863 au_pro=0.9455 image_f1_max=0.9832 image_f1_calibrated=0.9752 ms_per_image=56.3834
category image_auroc pixel_auroc au_pro image_f1_calib image_f1_max ms_per_imagebottle 1.0000 0.9777 0.9151 0.9692 1.0000 65.1520cable 0.9863 0.9762 0.9163 0.9468 0.9514 72.7497capsule 0.9469 0.9843 0.8916 0.9589 0.9636 75.5483carpet 0.9795 0.9873 0.9297 0.9263 0.9663 81.8062grid 0.9591 0.9621 0.8717 0.9204 0.9412 70.0422hazelnut 1.0000 0.9822 0.8446 1.0000 1.0000 87.7973leather 1.0000 0.9901 0.9636 0.9340 1.0000 61.2192metal_nut 0.9971 0.9744 0.9033 0.9785 0.9841 53.7824pill 0.9588 0.9658 0.8965 0.8313 0.9617 72.1890screw 0.9414 0.9849 0.9131 0.8502 0.9211 57.3492tile 0.9867 0.9330 0.7575 0.9759 0.9820 54.8988toothbrush 1.0000 0.9862 0.8820 0.9524 1.0000 60.9241transistor 1.0000 0.9691 0.9389 0.8247 1.0000 61.4579wood 0.9877 0.9225 0.8498 0.9440 0.9748 64.5355zipper 0.9798 0.9863 0.9455 0.9752 0.9832 56.3834MEAN 0.9816 0.9721 0.8946 0.9325 0.9753 66.3890123=== bottle [wrn50_c10]/usr/lib/python3.14/multiprocessing/resource_tracker.py:475: UserWarning: resource_tracker: There appear to be 20 leaked semaphore objects to clean up at shutdown: {'/loky-1747833-_ui_p2qf', '/loky-1747833-o2mdypde', '/loky-1747833-kprw6wnj', '/loky-1747833-5810i00f', '/loky-1747833-zgq2k3hk', '/loky-1747833-10mb6up2', '/loky-1747833-myl5fx_n', '/loky-1747833-dibx8k75', '/loky-1747833-m5prho8h', '/loky-1747833-0a07lxxk', '/loky-1747833-ai1sr8av', '/loky-1747833-ha2lmbru', '/loky-1747833-53ivrapx', '/loky-1747833-t3ck_2iw', '/loky-1747833-3d049ogp', '/loky-1747833-43gpmfx7', '/loky-1747833-dau33mvc', '/loky-1747833-zgbdrt79', '/loky-1747833-_xaualbb', '/loky-1747833-_l1yh3cm'} warnings.warn(1234567891011121314151617181920212223=== bottle [wrn50_c10_subset] memory bank: 148,176 patches -> coreset 14,817 (feat 50.2s, coreset 147.3s) image_auroc=1.0000 pixel_auroc=0.9834 au_pro=0.9249 image_f1_max=1.0000 image_f1_calibrated=0.9921 ms_per_image=409.9214=== capsule [wrn50_c10_subset] memory bank: 155,232 patches -> coreset 15,523 (feat 41.2s, coreset 158.3s) image_auroc=0.9533 pixel_auroc=0.9869 au_pro=0.9126 image_f1_max=0.9817 image_f1_calibrated=0.9429 ms_per_image=399.1867=== carpet [wrn50_c10_subset] memory bank: 197,568 patches -> coreset 19,756 (feat 50.3s, coreset 234.0s) image_auroc=0.9912 pixel_auroc=0.9882 au_pro=0.9188 image_f1_max=0.9831 image_f1_calibrated=0.9418 ms_per_image=448.4120=== screw [wrn50_c10_subset] memory bank: 225,792 patches -> coreset 22,579 (feat 61.0s, coreset 305.1s) image_auroc=0.9522 pixel_auroc=0.9884 au_pro=0.9296 image_f1_max=0.9440 image_f1_calibrated=0.9256 ms_per_image=496.4151=== wood [wrn50_c10_subset] memory bank: 174,832 patches -> coreset 17,483 (feat 49.4s, coreset 217.8s) image_auroc=0.9912 pixel_auroc=0.9372 au_pro=0.8352 image_f1_max=0.9748 image_f1_calibrated=0.9160 ms_per_image=435.7724
category image_auroc pixel_auroc au_pro image_f1_calib image_f1_max ms_per_imagebottle 1.0000 0.9834 0.9249 0.9921 1.0000 409.9214capsule 0.9533 0.9869 0.9126 0.9429 0.9817 399.1867carpet 0.9912 0.9882 0.9188 0.9418 0.9831 448.4120screw 0.9522 0.9884 0.9296 0.9256 0.9440 496.4151wood 0.9912 0.9372 0.8352 0.9160 0.9748 435.7724MEAN 0.9776 0.9768 0.9042 0.9437 0.9767 437.94151234567891011121314151617181920212223=== carpet [wrn50_c1_nocrop] memory bank: 197,568 patches -> coreset 1,975 (feat 56.4s, coreset 26.5s) image_auroc=0.9876 pixel_auroc=0.9891 au_pro=0.9167 image_f1_max=0.9718 image_f1_calibrated=0.9462 ms_per_image=225.1071=== grid [wrn50_c1_nocrop] memory bank: 186,592 patches -> coreset 1,865 (feat 44.1s, coreset 22.6s) image_auroc=0.9699 pixel_auroc=0.9679 au_pro=0.8686 image_f1_max=0.9735 image_f1_calibrated=0.9735 ms_per_image=201.9464=== screw [wrn50_c1_nocrop] memory bank: 225,792 patches -> coreset 2,257 (feat 55.9s, coreset 31.9s) image_auroc=0.9250 pixel_auroc=0.9682 au_pro=0.8489 image_f1_max=0.9091 image_f1_calibrated=0.8020 ms_per_image=205.7428=== tile [wrn50_c1_nocrop] memory bank: 162,288 patches -> coreset 1,622 (feat 43.2s, coreset 17.3s) image_auroc=1.0000 pixel_auroc=0.9578 au_pro=0.8285 image_f1_max=1.0000 image_f1_calibrated=0.9882 ms_per_image=217.6040=== wood [wrn50_c1_nocrop] memory bank: 174,832 patches -> coreset 1,748 (feat 46.9s, coreset 20.1s) image_auroc=0.9886 pixel_auroc=0.9346 au_pro=0.8370 image_f1_max=0.9748 image_f1_calibrated=0.9160 ms_per_image=234.3610
category image_auroc pixel_auroc au_pro image_f1_calib image_f1_max ms_per_imagecarpet 0.9876 0.9891 0.9167 0.9462 0.9718 225.1071grid 0.9699 0.9679 0.8686 0.9735 0.9735 201.9464screw 0.9250 0.9682 0.8489 0.8020 0.9091 205.7428tile 1.0000 0.9578 0.8285 0.9882 1.0000 217.6040wood 0.9886 0.9346 0.8370 0.9160 0.9748 234.3610MEAN 0.9742 0.9635 0.8599 0.9252 0.9658 216.952312345678910111213141516171819=== bottle [wrn50_c1] memory bank: 148,176 patches -> coreset 1,481 (feat 36.6s, coreset 9.8s) image_auroc=1.0000 pixel_auroc=0.9829 au_pro=0.9211 image_f1_max=1.0000 image_f1_calibrated=0.9921 ms_per_image=197.3154=== cable [wrn50_c1] memory bank: 158,368 patches -> coreset 1,583 (feat 33.7s, coreset 15.1s) image_auroc=0.9942 pixel_auroc=0.9839 au_pro=0.9231 image_f1_max=0.9787 image_f1_calibrated=0.9674 ms_per_image=159.8239=== capsule [wrn50_c1] memory bank: 155,232 patches -> coreset 1,552 (feat 30.4s, coreset 10.1s) image_auroc=0.9569 pixel_auroc=0.9867 au_pro=0.9069 image_f1_max=0.9772 image_f1_calibrated=0.6585 ms_per_image=173.1044=== carpet [wrn50_c1] memory bank: 197,568 patches -> coreset 1,975 (feat 45.6s, coreset 19.1s) image_auroc=0.9900 pixel_auroc=0.9876 au_pro=0.9122 image_f1_max=0.9775 image_f1_calibrated=0.9462 ms_per_image=183.8275
category image_auroc pixel_auroc au_pro image_f1_calib image_f1_max ms_per_imagebottle 1.0000 0.9829 0.9211 0.9921 1.0000 197.3154cable 0.9942 0.9839 0.9231 0.9674 0.9787 159.8239capsule 0.9569 0.9867 0.9069 0.6585 0.9772 173.1044carpet 0.9900 0.9876 0.9122 0.9462 0.9775 183.8275MEAN 0.9853 0.9853 0.9158 0.8911 0.9834 178.517812345678910111213141516171819=== grid [wrn50_c1] memory bank: 186,592 patches -> coreset 1,865 (feat 43.2s, coreset 17.9s) image_auroc=0.9799 pixel_auroc=0.9747 au_pro=0.8963 image_f1_max=0.9825 image_f1_calibrated=0.9550 ms_per_image=175.9080=== hazelnut [wrn50_c1] memory bank: 275,968 patches -> coreset 2,759 (feat 71.5s, coreset 55.6s) image_auroc=0.9996 pixel_auroc=0.9840 au_pro=0.8845 image_f1_max=0.9929 image_f1_calibrated=0.9928 ms_per_image=282.8252=== leather [wrn50_c1] memory bank: 173,264 patches -> coreset 1,732 (feat 53.4s, coreset 23.4s) image_auroc=1.0000 pixel_auroc=0.9902 au_pro=0.9567 image_f1_max=1.0000 image_f1_calibrated=0.9840 ms_per_image=294.0620
category image_auroc pixel_auroc au_pro image_f1_calib image_f1_max ms_per_imagebottle 1.0000 0.9829 0.9211 0.9921 1.0000 197.3154cable 0.9942 0.9839 0.9231 0.9674 0.9787 159.8239capsule 0.9569 0.9867 0.9069 0.6585 0.9772 173.1044carpet 0.9900 0.9876 0.9122 0.9462 0.9775 183.8275grid 0.9799 0.9747 0.8963 0.9550 0.9825 175.9080hazelnut 0.9996 0.9840 0.8845 0.9928 0.9929 282.8252leather 1.0000 0.9902 0.9567 0.9840 1.0000 294.0620MEAN 0.9887 0.9843 0.9144 0.9280 0.9870 209.55231234567891011121314151617181920212223242526=== metal_nut [wrn50_c1] memory bank: 155,232 patches -> coreset 1,552 (feat 50.5s, coreset 18.1s) image_auroc=0.9976 pixel_auroc=0.9839 au_pro=0.9040 image_f1_max=0.9892 image_f1_calibrated=0.9840 ms_per_image=247.4747=== pill [wrn50_c1] memory bank: 188,944 patches -> coreset 1,889 (feat 58.0s, coreset 26.9s) image_auroc=0.9645 pixel_auroc=0.9773 au_pro=0.9105 image_f1_max=0.9640 image_f1_calibrated=0.8051 ms_per_image=231.5943=== screw [wrn50_c1] memory bank: 225,792 patches -> coreset 2,257 (feat 63.5s, coreset 40.3s) image_auroc=0.9440 pixel_auroc=0.9793 au_pro=0.8736 image_f1_max=0.9312 image_f1_calibrated=0.7919 ms_per_image=262.7361=== tile [wrn50_c1] memory bank: 162,288 patches -> coreset 1,622 (feat 48.5s, coreset 34.8s) image_auroc=0.9888 pixel_auroc=0.9544 au_pro=0.7866 image_f1_max=0.9820 image_f1_calibrated=0.9820 ms_per_image=253.4766
category image_auroc pixel_auroc au_pro image_f1_calib image_f1_max ms_per_imagebottle 1.0000 0.9829 0.9211 0.9921 1.0000 197.3154cable 0.9942 0.9839 0.9231 0.9674 0.9787 159.8239capsule 0.9569 0.9867 0.9069 0.6585 0.9772 173.1044carpet 0.9900 0.9876 0.9122 0.9462 0.9775 183.8275grid 0.9799 0.9747 0.8963 0.9550 0.9825 175.9080hazelnut 0.9996 0.9840 0.8845 0.9928 0.9929 282.8252leather 1.0000 0.9902 0.9567 0.9840 1.0000 294.0620metal_nut 0.9976 0.9839 0.9040 0.9840 0.9892 247.4747pill 0.9645 0.9773 0.9105 0.8051 0.9640 231.5943screw 0.9440 0.9793 0.8736 0.7919 0.9312 262.7361tile 0.9888 0.9544 0.7866 0.9820 0.9820 253.4766MEAN 0.9832 0.9804 0.8978 0.9145 0.9796 223.8316123456789101112131415161718192021222324252627282930=== toothbrush [wrn50_c1] memory bank: 40,768 patches -> coreset 407 (feat 16.1s, coreset 2.3s) image_auroc=1.0000 pixel_auroc=0.9855 au_pro=0.8516 image_f1_max=1.0000 image_f1_calibrated=0.9836 ms_per_image=238.0884=== transistor [wrn50_c1] memory bank: 150,528 patches -> coreset 1,505 (feat 40.8s, coreset 13.1s) image_auroc=0.9987 pixel_auroc=0.9764 au_pro=0.9480 image_f1_max=0.9873 image_f1_calibrated=0.9524 ms_per_image=210.3189=== wood [wrn50_c1] memory bank: 174,832 patches -> coreset 1,748 (feat 47.9s, coreset 20.4s) image_auroc=0.9965 pixel_auroc=0.9380 au_pro=0.8339 image_f1_max=0.9916 image_f1_calibrated=0.9231 ms_per_image=211.4498=== zipper [wrn50_c1] memory bank: 169,344 patches -> coreset 1,693 (feat 40.9s, coreset 20.8s) image_auroc=0.9945 pixel_auroc=0.9824 au_pro=0.9275 image_f1_max=0.9916 image_f1_calibrated=0.9916 ms_per_image=207.3998
category image_auroc pixel_auroc au_pro image_f1_calib image_f1_max ms_per_imagebottle 1.0000 0.9829 0.9211 0.9921 1.0000 197.3154cable 0.9942 0.9839 0.9231 0.9674 0.9787 159.8239capsule 0.9569 0.9867 0.9069 0.6585 0.9772 173.1044carpet 0.9900 0.9876 0.9122 0.9462 0.9775 183.8275grid 0.9799 0.9747 0.8963 0.9550 0.9825 175.9080hazelnut 0.9996 0.9840 0.8845 0.9928 0.9929 282.8252leather 1.0000 0.9902 0.9567 0.9840 1.0000 294.0620metal_nut 0.9976 0.9839 0.9040 0.9840 0.9892 247.4747pill 0.9645 0.9773 0.9105 0.8051 0.9640 231.5943screw 0.9440 0.9793 0.8736 0.7919 0.9312 262.7361tile 0.9888 0.9544 0.7866 0.9820 0.9820 253.4766toothbrush 1.0000 0.9855 0.8516 0.9836 1.0000 238.0884transistor 0.9987 0.9764 0.9480 0.9524 0.9873 210.3189wood 0.9965 0.9380 0.8339 0.9231 0.9916 211.4498zipper 0.9945 0.9824 0.9275 0.9916 0.9916 207.3998MEAN 0.9870 0.9778 0.8958 0.9273 0.9831 221.9603123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194"""Figures for the report / slides (French labels)."""from __future__ import annotations
import jsonfrom pathlib import Path
import matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as pltimport numpy as npimport torchfrom PIL import Image
from patchcore.data import CATEGORIES, MVTecItems, list_category, to_displayfrom patchcore.model import FeatureExtractor, PatchCorefrom 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128"""Generates README.md (Hugging Face model card) from results/*.json."""import jsonimport sysfrom pathlib import Path
import numpy as np
from patchcore.data import CATEGORIES
USER = sys.argv[1] if len(sys.argv) > 1 else "USER"MODEL = f"{USER}/patchcore-mvtec-cpu"SPACE = f"{USER}/patchcore-defect-detection"M = json.loads(Path("results/wrn50_c1/metrics.json").read_text())R18 = json.loads(Path("results/r18_c1/metrics.json").read_text())TS = json.loads(Path("results/wrn50_c1/threshold_study.json").read_text())mean = lambda m, k: float(np.mean([r[k] for r in m.values()]))
rows = "\n".join( f"| {c} | {M[c]['image_auroc']:.3f} | {M[c]['pixel_auroc']:.3f} | {M[c]['au_pro']:.3f} | " f"{M[c]['image_f1_calibrated']:.3f} | {M[c]['ms_per_image']:.0f} | {M[c]['bank_size']:,} |" for c in CATEGORIES)mrow = (f"| **moyenne** | **{mean(M, 'image_auroc'):.3f}** | **{mean(M, 'pixel_auroc'):.3f}** | **{mean(M, 'au_pro'):.3f}** | " f"**{mean(M, 'image_f1_calibrated'):.3f}** | **{mean(M, 'ms_per_image'):.0f}** | |")rule = lambda n, k="f1": np.mean([r[n][k] for r in TS.values()])
readme = f"""---license: cc-by-nc-sa-4.0library_name: pytorchpipeline_tag: image-segmentationtags: - anomaly-detection - industrial-inspection - patchcore - mvtec-ad - computer-visiondatasets: - foersben/mvtec-admetrics: - roc_auc - f1---
# PatchCore sur CPU — détection et localisation de défauts industriels (MVTec AD)
Projet de vision par ordinateur avancée (3e année cycle ingénieur en informatique).**Démo en ligne :** https://huggingface.co/spaces/{SPACE}
Le modèle n'apprend que sur des **pièces conformes**. Pour une nouvelle image, il renvoieun **score d'anomalie** (pièce OK / défectueuse) et une **carte d'anomalie** qui localise le défaut.

## Méthode
Réimplémentation *from scratch* de **PatchCore** (Roth et al., *Towards Total Recall in IndustrialAnomaly Detection*, CVPR 2022), sans anomalib, optimisée pour CPU :
1. Extracteur **Wide-ResNet-50-2** ImageNet gelé : `layer2` (512×28×28) et `layer3` (1024×14×14).2. Agrégation locale (avg-pool 3×3), `layer3` suréchantillonné à 28×28, concaténation (1536 canaux), réduction à 1024 canaux → **784 patchs × 1024** par image.3. « Apprentissage » = mémorisation des patchs des images normales puis **coreset glouton k-center (1 %)** calculé dans un espace de projection aléatoire de 128 dimensions.4. Inférence : distance de chaque patch à son plus proche voisin dans la banque → grille 28×28 → bilinéaire 224×224 → flou gaussien σ=4. Score image = max de la carte.5. **Apport du groupe — seuil automatique** : 10 % des images normales d'apprentissage sont mises de côté ; seuil = 95e centile de leurs scores (aucun défaut n'est utilisé). Voir `threshold_study.py`.
Pas de fonction de perte : aucune descente de gradient.
## Résultats (test MVTec AD, WRN-50, coreset 1 %, CPU Intel i7-1355U)
| catégorie | AUROC image | AUROC pixel | AU-PRO | F1 (seuil calibré) | ms / image | banque ||---|---|---|---|---|---|---|{rows}{mrow}
Papier PatchCore-1 % (GPU) : AUROC image 0.990, AUROC pixel 0.980.
**Ablations** — ResNet-18 : AUROC image {mean(R18, 'image_auroc'):.3f}, pixel {mean(R18, 'pixel_auroc'):.3f},{mean(R18, 'ms_per_image'):.0f} ms/image (vs {mean(M, 'ms_per_image'):.0f} ms pour WRN-50).
**Règles de seuil** (F1 moyen) : max {rule('max'):.3f} · moyenne+3σ {rule('mean+3sd'):.3f} ·médiane+4·MAD {rule('robust'):.3f} · **95e centile {rule('p95'):.3f}** · oracle {rule('oracle'):.3f}.
## Utilisation
```bashpip install -r requirements.txthf download {MODEL} --local-dir patchcore-mvtec-cpu && cd patchcore-mvtec-cpupython app.py # démo Gradio locale (modèles déjà dans models/)# reproduire les résultats (MVTec AD dans data/mvtec_ad) :hf download foersben/mvtec-ad --repo-type dataset --local-dir data/mvtec_ad --exclude "results/*"python run.py --tag wrn50_c1 --save-modelspython threshold_study.py wrn50_c1```
```pythonfrom PIL import Imagefrom patchcore.model import PatchCorefrom patchcore.data import image_transformm = PatchCore.load("models/bottle")score, amap = m.predict(image_transform()(Image.open("x.png").convert("RGB"))[None])print("défaut" if score.item() >= m.image_threshold else "ok")```
## Contenu du dépôt
| chemin | rôle ||---|---|| `patchcore/model.py` | extracteur, coreset, k-NN, carte d'anomalie, save/load || `patchcore/data.py` | chargement MVTec AD, split banque / calibration || `patchcore/metrics.py` | AUROC image/pixel, AU-PRO, F1 || `run.py` | fit + calibration + évaluation d'une configuration || `threshold_study.py` | comparaison des règles de seuil || `app.py` | démo Gradio || `models/<catégorie>/` | banque mémoire (safetensors fp16) + config (seuils, métriques) || `results/` | métriques et scores par image de chaque expérience || `logs/`, `docs/difficulties.md` | journaux d'exécution, difficultés rencontrées |
Environnement : voir `requirements-lock.txt` (Python 3.14.10, torch 2.15.0+cpu).
## Données et licence
MVTec AD — Bergmann et al., CVPR 2019 / IJCV 2021 — licence **CC BY-NC-SA 4.0** (usage non commercial).Les banques mémoire dérivent de ces images et sont donc publiées sous la même licence.Les images d'exemple de la démo proviennent du jeu de test MVTec AD."""Path("README.md").write_text(readme)print("README.md written for", MODEL)12345678910111213141516171819202122232425262728293031323334{ "backbone": "wide_resnet50_2", "target_dim": 1024, "coreset_ratio": 0.01, "proj_dim": 128, "image_size": 224, "blur_sigma": 4.0, "image_threshold": 0.9866601020097733, "pixel_threshold": 0.9986759424209595, "category": "bottle", "metrics": { "image_auroc": 1.0, "pixel_auroc": 0.9829091261157012, "au_pro": 0.9211403565651815, "image_f1_max": 1.0, "oracle_threshold": 1.223919153213501, "image_f1_calibrated": 0.9692307692307692, "recall_calibrated": 1.0, "fpr_calibrated": 0.2, "n_patches": 148176, "bank_size": 1481, "t_features": 36.59970450401306, "t_coreset": 9.769118547439575, "n_train": 189, "n_calib": 20, "n_test": 83, "n_anomalous": 63, "ms_per_image": 197.31543150292822, "image_threshold": 0.9866601020097733, "pixel_threshold": 0.9986759424209595, "image_f1_maxrule": 0.9921259842519685, "threshold_rule": "p95_calibration" }}123version https://git-lfs.github.com/spec/v1oid sha256:cc7fbe30611b398ddb09c681352a5daae478658b18edb11d215e49a0629805absize 303317612345678910111213141516171819202122232425262728293031323334{ "backbone": "wide_resnet50_2", "target_dim": 1024, "coreset_ratio": 0.01, "proj_dim": 128, "image_size": 224, "blur_sigma": 4.0, "image_threshold": 1.4948360323905945, "pixel_threshold": 1.461139440536499, "category": "cable", "metrics": { "image_auroc": 0.9941904047976011, "pixel_auroc": 0.9838819433411217, "au_pro": 0.9231395630137045, "image_f1_max": 0.9787234042553191, "oracle_threshold": 1.4879556894302368, "image_f1_calibrated": 0.978494623655914, "recall_calibrated": 0.9891304347826086, "fpr_calibrated": 0.05172413793103448, "n_patches": 158368, "bank_size": 1583, "t_features": 33.71747350692749, "t_coreset": 15.053833723068237, "n_train": 202, "n_calib": 22, "n_test": 150, "n_anomalous": 92, "ms_per_image": 159.8239247004191, "image_threshold": 1.4948360323905945, "pixel_threshold": 1.461139440536499, "image_f1_maxrule": 0.967391304347826, "threshold_rule": "p95_calibration" }}123version https://git-lfs.github.com/spec/v1oid sha256:f7c0e10b86173e919fcdc5bdc3dff18fcccb5b5023edddc4f53379ea0d9d4975size 324207212345678910111213141516171819202122232425262728293031323334{ "backbone": "wide_resnet50_2", "target_dim": 1024, "coreset_ratio": 0.01, "proj_dim": 128, "image_size": 224, "blur_sigma": 4.0, "image_threshold": 0.890324056148529, "pixel_threshold": 1.0936118364334106, "category": "capsule", "metrics": { "image_auroc": 0.9569206222576785, "pixel_auroc": 0.9866526581148318, "au_pro": 0.9068973600078228, "image_f1_max": 0.9771689497716896, "oracle_threshold": 0.8593783378601074, "image_f1_calibrated": 0.958139534883721, "recall_calibrated": 0.944954128440367, "fpr_calibrated": 0.13043478260869565, "n_patches": 155232, "bank_size": 1552, "t_features": 30.43201971054077, "t_coreset": 10.145739555358887, "n_train": 198, "n_calib": 21, "n_test": 132, "n_anomalous": 109, "ms_per_image": 173.10438011631823, "image_threshold": 0.890324056148529, "pixel_threshold": 1.0936118364334106, "image_f1_maxrule": 0.6585365853658537, "threshold_rule": "p95_calibration" }}123version https://git-lfs.github.com/spec/v1oid sha256:13158a3e1fb75ed6efff1436124374acab0ec1d876c1a2daabf3a6ef71eb2f75size 317858412345678910111213141516171819202122232425262728293031323334{ "backbone": "wide_resnet50_2", "target_dim": 1024, "coreset_ratio": 0.01, "proj_dim": 128, "image_size": 224, "blur_sigma": 4.0, "image_threshold": 0.9373959422111511, "pixel_threshold": 0.9511089324951172, "category": "carpet", "metrics": { "image_auroc": 0.989967897271268, "pixel_auroc": 0.9876293040021854, "au_pro": 0.9121812384515438, "image_f1_max": 0.9775280898876404, "oracle_threshold": 1.0981895923614502, "image_f1_calibrated": 0.9312169312169312, "recall_calibrated": 0.9887640449438202, "fpr_calibrated": 0.42857142857142855, "n_patches": 197568, "bank_size": 1975, "t_features": 45.648457288742065, "t_coreset": 19.06189751625061, "n_train": 252, "n_calib": 28, "n_test": 117, "n_anomalous": 89, "ms_per_image": 183.82751636016064, "image_threshold": 0.9373959422111511, "pixel_threshold": 0.9511089324951172, "image_f1_maxrule": 0.946236559139785, "threshold_rule": "p95_calibration" }}123version https://git-lfs.github.com/spec/v1oid sha256:c7cb1296d81dfbfd31a0c276b998f219eccbdb2f56a8cbf511e4cf0dfb727aeesize 404488812345678910111213141516171819202122232425262728293031323334{ "backbone": "wide_resnet50_2", "target_dim": 1024, "coreset_ratio": 0.01, "proj_dim": 128, "image_size": 224, "blur_sigma": 4.0, "image_threshold": 1.0662448108196259, "pixel_threshold": 1.1052676439285278, "category": "grid", "metrics": { "image_auroc": 0.9799498746867168, "pixel_auroc": 0.9746710352323249, "au_pro": 0.8963373472186169, "image_f1_max": 0.9824561403508771, "oracle_threshold": 1.0926036834716797, "image_f1_calibrated": 0.9572649572649573, "recall_calibrated": 0.9824561403508771, "fpr_calibrated": 0.19047619047619047, "n_patches": 186592, "bank_size": 1865, "t_features": 43.24864864349365, "t_coreset": 17.930366039276123, "n_train": 238, "n_calib": 26, "n_test": 78, "n_anomalous": 57, "ms_per_image": 175.90799392798007, "image_threshold": 1.0662448108196259, "pixel_threshold": 1.1052676439285278, "image_f1_maxrule": 0.954954954954955, "threshold_rule": "p95_calibration" }}123version https://git-lfs.github.com/spec/v1oid sha256:22417489fa3d5a448ee949505bbd7f9c967ea23e11673b33f4ed8c371b998fe4size 3819608.gitattributesAdded+55
.gitignoreAdded+6
README.mdAdded+115
app.pyAdded+115
demo_secours.mp4Added+3
docs/difficulties.mdAdded+34
examples/bottle_broken_large_000.pngAdded

Large File Pointer Details
- SHA256: 8bb6688c3523f54c0181609b6c8c2fd1c2943ca179ab23ec6364ae3675ed669c
- Pointer size: 131 Bytes
- Size of remote file: 288 kB
examples/capsule_crack_001.pngAdded

Large File Pointer Details
- SHA256: 6c0e539daaa7cdecb3f68645039b0983372ddebaba30427edd28a3690cfc961e
- Pointer size: 131 Bytes
- Size of remote file: 379 kB
examples/carpet_color_000.pngAdded

Large File Pointer Details
- SHA256: 206fe45aaca5aee303ec5e3b0da6e68c07a48f332b1ad8ab54328ecf787dce9b
- Pointer size: 131 Bytes
- Size of remote file: 515 kB
examples/hazelnut_crack_002.pngAdded

Large File Pointer Details
- SHA256: 9e01a904bc9878e3a9867b11c3f998f4ba7faec9893f29d78364cc681d020c9a
- Pointer size: 131 Bytes
- Size of remote file: 350 kB
examples/leather_cut_000.pngAdded

Large File Pointer Details
- SHA256: dea1855f7d17c8ba8982b9946e355192dca2ef772f96bcdb6b4ce5ddda6e1986
- Pointer size: 131 Bytes
- Size of remote file: 489 kB
examples/metal_nut_scratch_000.pngAdded

Large File Pointer Details
- SHA256: b0dbf701926865d5a8e14b8d2070095e038d7b2832736119ed0fa3b150399cf9
- Pointer size: 131 Bytes
- Size of remote file: 391 kB
examples/pill_good_000.pngAdded

Large File Pointer Details
- SHA256: ba9c50ab28267bd82c49b48f8fff6774dd40974f2493eb2b3ac923778741acdf
- Pointer size: 131 Bytes
- Size of remote file: 325 kB
examples/screw_good_000.pngAdded

Large File Pointer Details
- SHA256: 4b5d877854f114a2b988d7a44f5c3df933f57c4b6617f99801412f237ec021de
- Pointer size: 131 Bytes
- Size of remote file: 150 kB
examples/tile_crack_000.pngAdded

Large File Pointer Details
- SHA256: 1933c9e69f9ac02d63f72d8b0e694403204d59947146aee286032fd226ecaa4b
- Pointer size: 131 Bytes
- Size of remote file: 456 kB
examples/transistor_misplaced_000.pngAdded

Large File Pointer Details
- SHA256: 77dc15e4784f4d23ce3af9aa7a86dea4a60e1c120e0081bbca54f06cd121addf
- Pointer size: 131 Bytes
- Size of remote file: 327 kB
examples/wood_good_000.pngAdded

Large File Pointer Details
- SHA256: 7fe93888a713290775cec36fad32a4225b362d05a4e91407c4397aa14156561b
- Pointer size: 131 Bytes
- Size of remote file: 413 kB
examples/zipper_broken_teeth_000.pngAdded

Large File Pointer Details
- SHA256: ac5a945685c97eb761082dfcd171b3b72d9ae222563e2ea43ad85e09fff2d2fa
- Pointer size: 131 Bytes
- Size of remote file: 175 kB
fig_d2.pyAdded+37
figures/d2_tile.pngAdded

Large File Pointer Details
- SHA256: 42003cd838588a81d7f9aa7a7a54a0fd67e2eeb22547885f47b9439b03c95974
- Pointer size: 132 Bytes
- Size of remote file: 1.21 MB
figures/demo_screenshot.pngAdded

Large File Pointer Details
- SHA256: 935883b30062c03d203075572ef597d801d637503f76e3039116e5582ade77f2
- Pointer size: 131 Bytes
- Size of remote file: 399 kB
figures/ex_gt.pngAdded

Large File Pointer Details
- SHA256: ae9ce4910ed3f7f1d56505a3ed3b7af9cdb221c8994a1d4ccd10c07836a7f2fd
- Pointer size: 131 Bytes
- Size of remote file: 222 kB
figures/ex_input.pngAdded

Large File Pointer Details
- SHA256: 9f50c7bb93be83d9d3555ff6197cea68767c820de3f279d1a1b38468fbcd6b23
- Pointer size: 131 Bytes
- Size of remote file: 219 kB
figures/ex_output.pngAdded

Large File Pointer Details
- SHA256: c3dde217cbfcd5ab7ff6af03289e3e0c535e5c72f90e10545e7d7e69f88852bc
- Pointer size: 131 Bytes
- Size of remote file: 198 kB
figures/failure.pngAdded

Large File Pointer Details
- SHA256: 0fdff0110690cbef9688818fe7cf53916a3d26d373c98d91c4debf6c81eb8a84
- Pointer size: 132 Bytes
- Size of remote file: 2.3 MB
figures/hist_capsule.pngAdded

figures/hist_carpet.pngAdded

figures/success.pngAdded

Large File Pointer Details
- SHA256: e9f3df0d4e44a245b8b4ab2c6a4812b4e2fc5e49a929aed81e42867e3906c438
- Pointer size: 132 Bytes
- Size of remote file: 2.53 MB
logs/.logAdded+5
logs/app.logAdded+45
logs/r18_c1.logAdded+63
logs/wrn50_c10.logAdded+3
logs/wrn50_c10_subset.logAdded+23
logs/wrn50_c1_nocrop.logAdded+23
logs/wrn50_c1_part1.logAdded+19
logs/wrn50_c1_part2.logAdded+19
logs/wrn50_c1_part3.logAdded+26
logs/wrn50_c1_part4.logAdded+30
make_figures.pyAdded+194
make_readme.pyAdded+128
models/bottle/config.jsonAdded+34
models/bottle/memory_bank.safetensorsAdded+3
models/cable/config.jsonAdded+34
models/cable/memory_bank.safetensorsAdded+3
models/capsule/config.jsonAdded+34
models/capsule/memory_bank.safetensorsAdded+3
models/carpet/config.jsonAdded+34
models/carpet/memory_bank.safetensorsAdded+3
models/grid/config.jsonAdded+34
models/grid/memory_bank.safetensorsAdded+3