File size: 3,411 Bytes
142281f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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)