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, }