File size: 4,909 Bytes
fe0f47c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import os
from enum import Enum
from pathlib import Path

import datasets
from pandas import DataFrame

_HOMEPAGE = "https://www.mvtec.com/company/research/datasets/mvtec-ad"
_LICENSE = "cc-by-nc-sa-4.0"
_CITATION = """\
@misc{
    the-mvtec-anomaly-detection-dataset,
    title = { The MVTec Anomaly Detection Dataset: A Comprehensive Real-World Dataset for Unsupervised Anomaly Detection },
    type = { Open Source Dataset },
    author = { Paul Bergmann, Kilian Batzner, Michael Fauser, David Sattlegger, Carsten Steger },
    howpublished = { \\url{ https://link.springer.com/article/10.1007%2Fs11263-020-01400-4 } },
    url = { https://link.springer.com/article/10.1007%2Fs11263-020-01400-4 },
}
"""


class LabelName(int, Enum):
    NORMAL = 0
    ABNORMAL = 1


class MVTECCapsule(datasets.GeneratorBasedBuilder):
    VERSION = datasets.Version("1.0.0")
    _URL = "https://huggingface.co/datasets/alexsu52/mvtec_capsule/resolve/main/capsule.tar.xz"

    def _info(self):
        features = datasets.Features(
            {
                "image": datasets.Image(),
                "mask": datasets.Image(),
                "label": datasets.ClassLabel(names=["normal", "abnormal"]),
            }
        )
        return datasets.DatasetInfo(
            features=features,
            homepage=_HOMEPAGE,
            citation=_CITATION,
            license=_LICENSE,
        )

    def _split_generators(self, dl_manager):
        folder_dir = dl_manager.download_and_extract(self._URL)
        category_dir = os.path.join(folder_dir, "capsule")
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "category_dir": category_dir,
                    "split": "train",
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "category_dir": category_dir,
                    "split": "test",
                },
            ),
        ]

    def _generate_examples(self, category_dir, split):
        extensions = (".png", ".PNG")

        root = Path(category_dir)
        samples_list = [(str(root),) + f.parts[-3:] for f in root.glob(r"**/*") if f.suffix in extensions]
        if not samples_list:
            raise RuntimeError(f"Found 0 images in {root}")

        samples = DataFrame(samples_list, columns=["path", "split", "label", "image_path"])

        # Modify image_path column by converting to absolute path
        samples["image_path"] = samples.path + "/" + samples.split + "/" + samples.label + "/" + samples.image_path

        # Create label index for normal (0) and anomalous (1) images.
        samples.loc[(samples.label == "good"), "label_index"] = LabelName.NORMAL
        samples.loc[(samples.label != "good"), "label_index"] = LabelName.ABNORMAL
        samples.label_index = samples.label_index.astype(int)

        # separate masks from samples
        mask_samples = samples.loc[samples.split == "ground_truth"].sort_values(by="image_path", ignore_index=True)
        samples = samples[samples.split != "ground_truth"].sort_values(by="image_path", ignore_index=True)

        # assign mask paths to anomalous test images
        samples["mask_path"] = ""
        samples.loc[
            (samples.split == "test") & (samples.label_index == LabelName.ABNORMAL), "mask_path"
        ] = mask_samples.image_path.values

        # assert that the right mask files are associated with the right test images
        if len(samples.loc[samples.label_index == LabelName.ABNORMAL]):
            assert (
                samples.loc[samples.label_index == LabelName.ABNORMAL]
                .apply(lambda x: Path(x.image_path).stem in Path(x.mask_path).stem, axis=1)
                .all()
            ), "Mismatch between anomalous images and ground truth masks. Make sure the mask files in 'ground_truth' \
                    folder follow the same naming convention as the anomalous images in the dataset (e.g. image: \
                    '000.png', mask: '000.png' or '000_mask.png')."

        if split:
            samples = samples[samples.split == split].reset_index(drop=True)

        for idx in range(len(samples)):
            image_path = samples.iloc[idx].image_path
            mask_path = samples.iloc[idx].mask_path
            label_index = samples.iloc[idx].label_index

            with open(image_path, "rb") as f:
                image_bytes = f.read()

            if mask_path:
                with open(mask_path, "rb") as f:
                    mask_bytes = f.read()
            else:
                mask_bytes = bytes(len(image_bytes))

            yield idx, {
                "image": {"path": image_path, "bytes": image_bytes},
                "mask": {"path": mask_path, "bytes": mask_bytes},
                "label": label_index,
            }