Download patchcore/data.py from salimamri9/patchcore-mvtec-cpu: direct link, hf CLI and curl.
- Browser
- Download file 3.41 kB
-
https://huggingface.co/salimamri9/patchcore-mvtec-cpu/resolve/main/patchcore/data.py
- Command line
-
hf download hf://salimamri9/patchcore-mvtec-cpu/patchcore/data.py
-
curl -L -o data.py https://huggingface.co/salimamri9/patchcore-mvtec-cpu/resolve/main/patchcore/data.py
3.41 kB
| """MVTec AD loading. Layout: <root>/<category>/{train/good, test/<defect>, ground_truth/<defect>/*_mask.png}""" | |
| from __future__ import annotations | |
| import random | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| from PIL import Image | |
| from torch.utils.data import Dataset | |
| from torchvision import transforms as T | |
| CATEGORIES = [ | |
| "bottle", "cable", "capsule", "carpet", "grid", "hazelnut", "leather", "metal_nut", | |
| "pill", "screw", "tile", "toothbrush", "transistor", "wood", "zipper", | |
| ] | |
| MEAN, STD = (0.485, 0.456, 0.406), (0.229, 0.224, 0.225) | |
| def image_transform(resize=256, crop=224): | |
| """crop=None -> resize the full image straight to `resize` (keeps defects on the borders).""" | |
| if crop is None: | |
| return T.Compose([T.Resize((resize, resize)), T.ToTensor(), T.Normalize(MEAN, STD)]) | |
| return T.Compose([T.Resize(resize), T.CenterCrop(crop), T.ToTensor(), T.Normalize(MEAN, STD)]) | |
| def mask_transform(resize=256, crop=224): | |
| if crop is None: | |
| return T.Compose([T.Resize((resize, resize), interpolation=T.InterpolationMode.NEAREST), T.ToTensor()]) | |
| return T.Compose([T.Resize(resize, interpolation=T.InterpolationMode.NEAREST), T.CenterCrop(crop), T.ToTensor()]) | |
| def load_rgb(path) -> Image.Image: | |
| # MVTec contains grayscale categories (grid, screw, zipper): force 3 channels | |
| return Image.open(path).convert("RGB") | |
| class MVTecItems(Dataset): | |
| def __init__(self, items, resize=256, crop=224): | |
| self.items = items # list of (img_path, label, mask_path|None, defect_type) | |
| self.tf, self.mtf = image_transform(resize, crop), mask_transform(resize, crop) | |
| self.crop = crop if crop is not None else resize | |
| def __len__(self): | |
| return len(self.items) | |
| def __getitem__(self, i): | |
| p, label, mp, dtype = self.items[i] | |
| img = self.tf(load_rgb(p)) | |
| if mp is not None: | |
| mask = (self.mtf(Image.open(mp).convert("L")) > 0.5).float() | |
| else: | |
| mask = torch.zeros(1, self.crop, self.crop) | |
| return {"image": img, "mask": mask, "label": label, "path": str(p), "defect": dtype} | |
| def list_category(root, category, calib_frac=0.1, seed=0): | |
| """Returns train / calibration (normal only) / test item lists. | |
| The calibration split is held out of the memory bank and used *only* to | |
| set the decision thresholds, so no anomalous image is ever used for tuning. | |
| """ | |
| root = Path(root) / category | |
| normals = sorted((root / "train" / "good").glob("*.png")) | |
| rng = random.Random(seed) | |
| shuffled = normals[:] | |
| rng.shuffle(shuffled) | |
| n_cal = max(8, int(len(normals) * calib_frac)) | |
| calib = [(p, 0, None, "good") for p in sorted(shuffled[:n_cal])] | |
| train = [(p, 0, None, "good") for p in sorted(shuffled[n_cal:])] | |
| test = [] | |
| for d in sorted((root / "test").iterdir()): | |
| for p in sorted(d.glob("*.png")): | |
| if d.name == "good": | |
| test.append((p, 0, None, "good")) | |
| else: | |
| mp = root / "ground_truth" / d.name / f"{p.stem}_mask.png" | |
| test.append((p, 1, mp, d.name)) | |
| return train, calib, test | |
| def to_display(img_t: torch.Tensor) -> np.ndarray: | |
| """Normalised CHW tensor -> HWC uint8 RGB.""" | |
| m = torch.tensor(MEAN).view(3, 1, 1) | |
| s = torch.tensor(STD).view(3, 1, 1) | |
| x = (img_t * s + m).clamp(0, 1).permute(1, 2, 0).numpy() | |
| return (x * 255).astype(np.uint8) | |