smjfas commited on
Commit
16a0f31
·
1 Parent(s): 2875bb8

initial commit

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.DS_Store ADDED
Binary file (6.15 kB). View file
 
Dockerfile ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -----------------------------------------------------------------------------
2
+ # A sample Dockerfile to help you replicate our test environment
3
+ # -----------------------------------------------------------------------------
4
+
5
+ FROM pytorch/pytorch:2.4.1-cuda12.4-cudnn9-runtime
6
+ WORKDIR /app
7
+ COPY . .
8
+
9
+ # Install your python and apt requirements
10
+ RUN pip install -r requirements.txt
11
+ RUN apt-get update && apt-get install $(cat apt_requirements.txt) -y
12
+ RUN chmod +x run.sh
13
+
14
+ CMD ["python3", "runner.py"]
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Yunkang Cao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AdaCLIP (Detecting Anomalies for Novel Categories)
2
+ [![HuggingFace Space](https://img.shields.io/badge/🤗-HuggingFace%20Space-cyan.svg)](https://huggingface.co/spaces/Caoyunkang/AdaCLIP)
3
+
4
+ > [**ECCV 24**] [**AdaCLIP: Adapting CLIP with Hybrid Learnable Prompts for Zero-Shot Anomaly Detection**](https://arxiv.org/abs/2407.15795).
5
+ >
6
+ > by [Yunkang Cao](https://caoyunkang.github.io/), [Jiangning Zhang](https://zhangzjn.github.io/), [Luca Frittoli](https://scholar.google.com/citations?user=cdML_XUAAAAJ),
7
+ > [Yuqi Cheng](https://scholar.google.com/citations?user=02BC-WgAAAAJ&hl=en), [Weiming Shen](https://scholar.google.com/citations?user=FuSHsx4AAAAJ&hl=en), [Giacomo Boracchi](https://boracchi.faculty.polimi.it/)
8
+ >
9
+
10
+ ## Introduction
11
+ Zero-shot anomaly detection (ZSAD) targets the identification of anomalies within images from arbitrary novel categories.
12
+ This study introduces AdaCLIP for the ZSAD task, leveraging a pre-trained vision-language model (VLM), CLIP.
13
+ AdaCLIP incorporates learnable prompts into CLIP and optimizes them through training on auxiliary annotated anomaly detection data.
14
+ Two types of learnable prompts are proposed: \textit{static} and \textit{dynamic}. Static prompts are shared across all images, serving to preliminarily adapt CLIP for ZSAD.
15
+ In contrast, dynamic prompts are generated for each test image, providing CLIP with dynamic adaptation capabilities.
16
+ The combination of static and dynamic prompts is referred to as hybrid prompts, and yields enhanced ZSAD performance.
17
+ Extensive experiments conducted across 14 real-world anomaly detection datasets from industrial and medical domains indicate that AdaCLIP outperforms other ZSAD methods and can generalize better to different categories and even domains.
18
+ Finally, our analysis highlights the importance of diverse auxiliary data and optimized prompts for enhanced generalization capacity.
19
+
20
+ ## Corrections
21
+ - The description to the utilized training set in our paper is not accurate. By default, we utilize MVTec AD & ColonDB for training,
22
+ and VisA & ClinicDB are utilized for evaluations on MVTec AD & ColonDB.
23
+
24
+ ## Overview of AdaCLIP
25
+ ![overview](asset/framework.png)
26
+
27
+ ## 🛠️ Getting Started
28
+
29
+ ### Installation
30
+ To set up the AdaCLIP environment, follow one of the methods below:
31
+
32
+ - Clone this repo:
33
+ ```shell
34
+ git clone https://github.com/caoyunkang/AdaCLIP.git && cd AdaCLIP
35
+ ```
36
+ - You can use our provided installation script for an automated setup::
37
+ ```shell
38
+ sh install.sh
39
+ ```
40
+ - If you prefer to construct the experimental environment manually, follow these steps:
41
+ ```shell
42
+ conda create -n AdaCLIP python=3.9.5 -y
43
+ conda activate AdaCLIP
44
+ pip install torch==1.10.1+cu111 torchvision==0.11.2+cu111 torchaudio==0.10.1 -f https://download.pytorch.org/whl/cu111/torch_stable.html
45
+ pip install tqdm tensorboard setuptools==58.0.4 opencv-python scikit-image scikit-learn matplotlib seaborn ftfy regex numpy==1.26.4
46
+ pip install gradio # Optional, for app
47
+ ```
48
+ - Remember to update the dataset root in config.py according to your preference:
49
+ ```python
50
+ DATA_ROOT = '../datasets' # Original setting
51
+ ```
52
+
53
+ ### Dataset Preparation
54
+ Please download our processed visual anomaly detection datasets to your `DATA_ROOT` as needed.
55
+
56
+ #### Industrial Visual Anomaly Detection Datasets
57
+ Note: some links are still in processing...
58
+
59
+ | Dataset | Google Drive | Baidu Drive | Task
60
+ |------------|------------------|------------------| ------------------|
61
+ | MVTec AD | [Google Drive](https://drive.google.com/file/d/12IukAqxOj497J4F0Mel-FvaONM030qwP/view?usp=drive_link) | [Baidu Drive](https://pan.baidu.com/s/1k36IMP4w32hY9BXOUM5ZmA?pwd=kxud) | Anomaly Detection & Localization |
62
+ | VisA | [Google Drive](https://drive.google.com/file/d/1U0MZVro5yGgaHNQ8kWb3U1a0Qlz4HiHI/view?usp=drive_link) | [Baidu Drive](https://pan.baidu.com/s/15CIsP-ulZ1AN0_3quA068w?pwd=lmgc) | Anomaly Detection & Localization |
63
+ | MPDD | [Google Drive](https://drive.google.com/file/d/1cLkZs8pN8onQzfyNskeU_836JLjrtJz1/view?usp=drive_link) | [Baidu Drive](https://pan.baidu.com/s/11T3mkloDCl7Hze5znkXOQA?pwd=4p7m) | Anomaly Detection & Localization |
64
+ | BTAD | [Google Drive](https://drive.google.com/file/d/19Kd8jJLxZExwiTc9__6_r_jPqkmTXt4h/view?usp=drive_link) | [Baidu Drive](https://pan.baidu.com/s/1f4Tq-EXRz6iAswygH2WbFg?pwd=a60n) | Anomaly Detection & Localization |
65
+ | KSDD | [Google Drive](https://drive.google.com/file/d/13UidsM1taqEAVV_JJTBiCV1D3KUBpmpj/view?usp=drive_link) | [Baidu Drive](https://pan.baidu.com/s/12EaOdkSbdK85WX5ajrfjQw?pwd=6n3z) | Anomaly Detection & Localization |
66
+ | DAGM | [Google Drive](https://drive.google.com/file/d/1f4sm8hpWQRzZMpvM-j7Q3xPG2vtdwvTy/view?usp=drive_link) | [Baidu Drive](https://pan.baidu.com/s/1JpDUJIksD99t003dNF1y9g?pwd=u3aq) | Anomaly Detection & Localization |
67
+ | DTD-Synthetic | [Google Drive](https://drive.google.com/file/d/1em51XXz5_aBNRJlJxxv3-Ed1dO9H3QgS/view?usp=drive_link) | [Baidu Drive](https://pan.baidu.com/s/16FlvIBWtjaDzWxlZfWjNeg?pwd=aq5c) | Anomaly Detection & Localization |
68
+
69
+
70
+
71
+
72
+ #### Medical Visual Anomaly Detection Datasets
73
+ | Dataset | Google Drive | Baidu Drive | Task
74
+ |------------|------------------|------------------| ------------------|
75
+ | HeadCT | [Google Drive](https://drive.google.com/file/d/1ore0yCV31oLwwC--YUuTQfij-f2V32O2/view?usp=drive_link) | [Baidu Drive](https://pan.baidu.com/s/16PfXWJlh6Y9vkecY9IownA?pwd=svsl) | Anomaly Detection |
76
+ | BrainMRI | [Google Drive](https://drive.google.com/file/d/1JLYyzcPG3ULY2J_aw1SY9esNujYm9GKd/view?usp=drive_link) | [Baidu Drive](https://pan.baidu.com/s/1UgGlTR-ABWAEiVUX-QSPhA?pwd=vh9e) | Anomaly Detection |
77
+ | Br35H | [Google Drive](https://drive.google.com/file/d/1qaZ6VJDRk3Ix3oVp3NpFyTsqXLJ_JjQy/view?usp=drive_link) | [Baidu Drive](https://pan.baidu.com/s/1yCS6t3ht6qwJgM06YsU3mg?pwd=ps1e) | Anomaly Detection |
78
+ | ISIC | [Google Drive](https://drive.google.com/file/d/1atZwmnFsz7mCsHWBZ8pkL_-Eul9bKFEx/view?usp=drive_link) | [Baidu Drive](https://pan.baidu.com/s/1Mf0w8RFY9ECZBEoNTyV3ZA?pwd=p954) | Anomaly Localization |
79
+ | ColonDB | [Google Drive](https://drive.google.com/file/d/1tjZ0o5dgzka3wf_p4ErSRJ9fcC-RJK8R/view?usp=drive_link) | [Baidu Drive](https://pan.baidu.com/s/1nJ4L65vfNFGpkK_OJjLoVg?pwd=v8q7) | Anomaly Localization |
80
+ | ClinicDB | [Google Drive](https://drive.google.com/file/d/1ciqZwMs1smSGDlwQ6tsr6YzylrqQBn9n/view?usp=drive_link) | [Baidu Drive](https://pan.baidu.com/s/1TPysfqhA_sXRPLGNwWBX6Q?pwd=3da6) | Anomaly Localization |
81
+ | TN3K | [Google Drive](https://drive.google.com/file/d/1LuKEMhrUGwFBlGCaej46WoooH89V3O8_/view?usp=drive_link) | [Baidu Drive](https://pan.baidu.com/s/1i5jMofCcRFcUdteq8VMEOQ?pwd=aoez) | Anomaly Localization |
82
+
83
+ #### Custom Datasets
84
+ To use your custom dataset, follow these steps:
85
+
86
+ 1. Refer to the instructions in `./data_preprocess` to generate the JSON file for your dataset.
87
+ 2. Use `./dataset/base_dataset.py` to construct your own dataset.
88
+
89
+
90
+ ### Weight Preparation
91
+
92
+ We offer various pre-trained weights on different auxiliary datasets.
93
+ Please download the pre-trained weights in `./weights`.
94
+
95
+ | Pre-trained Datasets | Google Drive | Baidu Drive
96
+ |------------|------------------|------------------|
97
+ | MVTec AD & ClinicDB | [Google Drive](https://drive.google.com/file/d/1xVXANHGuJBRx59rqPRir7iqbkYzq45W0/view?usp=drive_link) | [Baidu Drive](https://pan.baidu.com/s/1K9JhNAmmDt4n5Sqlq4-5hQ?pwd=fks1) |
98
+ | VisA & ColonDB | [Google Drive](https://drive.google.com/file/d/1QGmPB0ByPZQ7FucvGODMSz7r5Ke5wx9W/view?usp=drive_link) | [Baidu Drive](https://pan.baidu.com/s/1GmRCylpboPseT9lguCO9nw?pwd=fvvf) |
99
+ | All Datasets Mentioned Above | [Google Drive](https://drive.google.com/file/d/1Cgkfx3GAaSYnXPLolx-P7pFqYV0IVzZF/view?usp=drive_link) | [Baidu Drive](https://pan.baidu.com/s/1J4aFAOhUbeYOBfZFbkOixA?pwd=0ts3) |
100
+
101
+
102
+ ### Train
103
+
104
+ By default, we use MVTec AD & Colondb for training and VisA for validation:
105
+ ```shell
106
+ CUDA_VISIBLE_DEVICES=0 python train.py --save_fig True --training_data mvtec colondb --testing_data visa
107
+ ```
108
+
109
+
110
+ Alternatively, for evaluation on MVTec AD & Colondb, we use VisA & ClinicDB for training and MVTec AD for validation.
111
+ ```shell
112
+ CUDA_VISIBLE_DEVICES=0 python train.py --save_fig True --training_data visa clinicdb --testing_data mvtec
113
+ ```
114
+ Since we have utilized half-precision (FP16) for training, the training process can occasionally be unstable.
115
+ It is recommended to run the training process multiple times and choose the best model based on performance
116
+ on the validation set as the final model.
117
+
118
+
119
+ To construct a robust ZSAD model for demonstration, we also train our AdaCLIP on all AD datasets mentioned above:
120
+ ```shell
121
+ CUDA_VISIBLE_DEVICES=0 python train.py --save_fig True \
122
+ --training_data \
123
+ br35h brain_mri btad clinicdb colondb \
124
+ dagm dtd headct isic mpdd mvtec sdd tn3k visa \
125
+ --testing_data mvtec
126
+ ```
127
+
128
+ ### Test
129
+
130
+ Manually select the best models from the validation set and place them in the `weights/` directory. Then, run the following testing script:
131
+ ```shell
132
+ sh test.sh
133
+ ```
134
+
135
+ If you want to test on a single image, you can refer to `test_single_image.sh`:
136
+ ```shell
137
+ CUDA_VISIBLE_DEVICES=0 python test.py --testing_model image --ckt_path weights/pretrained_all.pth --save_fig True \
138
+ --image_path asset/img.png --class_name candle --save_name test.png
139
+ ```
140
+
141
+ ## Main Results
142
+
143
+ Due to differences in versions utilized, the reported performance may vary slightly compared to the detection performance
144
+ with the provided pre-trained weights. Some categories may show higher performance while others may show lower.
145
+
146
+ ![Table_industrial](./asset/Table_industrial.png)
147
+ ![Table_medical](./asset/Table_medical.png)
148
+ ![Fig_detection_results](./asset/Fig_detection_results.png)
149
+
150
+ ### :page_facing_up: Demo App
151
+
152
+ To run the demo application, use the following command:
153
+
154
+ ```bash
155
+ python app.py
156
+ ```
157
+
158
+ Or visit our [Online Demo](https://huggingface.co/spaces/Caoyunkang/AdaCLIP) for a quick start. The three pre-trained weights mentioned are available there. Feel free to test them with your own data!
159
+
160
+ Please note that we currently do not have a GPU environment for our Hugging Face Space, so inference for a single image may take approximately 50 seconds.
161
+
162
+ ![Demo](./asset/Fig_app.png)
163
+
164
+ ## 💘 Acknowledgements
165
+ Our work is largely inspired by the following projects. Thanks for their admiring contribution.
166
+
167
+ - [VAND-APRIL-GAN](https://github.com/ByChelsea/VAND-APRIL-GAN)
168
+ - [AnomalyCLIP](https://github.com/zqhang/AnomalyCLIP)
169
+ - [SAA](https://github.com/caoyunkang/Segment-Any-Anomaly)
170
+
171
+
172
+ ## Stargazers over time
173
+ [![Stargazers over time](https://starchart.cc/caoyunkang/AdaCLIP.svg?variant=adaptive)](https://starchart.cc/caoyunkang/AdaCLIP)
174
+
175
+
176
+ ## Citation
177
+
178
+ If you find this project helpful for your research, please consider citing the following BibTeX entry.
179
+
180
+ ```BibTex
181
+
182
+ @inproceedings{AdaCLIP,
183
+ title={AdaCLIP: Adapting CLIP with Hybrid Learnable Prompts for Zero-Shot Anomaly Detection},
184
+ author={Cao, Yunkang and Zhang, Jiangning and Frittoli, Luca and Cheng, Yuqi and Shen, Weiming and Boracchi, Giacomo},
185
+ booktitle={European Conference on Computer Vision},
186
+ year={2024}
187
+ }
188
+
189
+ ```
app.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image, ImageDraw, ImageFont
3
+ import warnings
4
+ import os
5
+ os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8'
6
+ import json
7
+ import os
8
+ import torch
9
+ from scipy.ndimage import gaussian_filter
10
+ import cv2
11
+ from method import AdaCLIP_Trainer
12
+ import numpy as np
13
+
14
+ ############ Init Model
15
+ ckt_path1 = 'weights/pretrained_mvtec_colondb.pth'
16
+ ckt_path2 = "weights/pretrained_visa_clinicdb.pth"
17
+ ckt_path3 = 'weights/pretrained_all.pth'
18
+
19
+ # Configurations
20
+ image_size = 518
21
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
22
+ # device = 'cpu'
23
+ model = "ViT-L-14-336"
24
+ prompting_depth = 4
25
+ prompting_length = 5
26
+ prompting_type = 'SD'
27
+ prompting_branch = 'VL'
28
+ use_hsf = True
29
+ k_clusters = 20
30
+
31
+ config_path = os.path.join('./model_configs', f'{model}.json')
32
+
33
+ # Prepare model
34
+ with open(config_path, 'r') as f:
35
+ model_configs = json.load(f)
36
+
37
+ # Set up the feature hierarchy
38
+ n_layers = model_configs['vision_cfg']['layers']
39
+ substage = n_layers // 4
40
+ features_list = [substage, substage * 2, substage * 3, substage * 4]
41
+
42
+ model = AdaCLIP_Trainer(
43
+ backbone=model,
44
+ feat_list=features_list,
45
+ input_dim=model_configs['vision_cfg']['width'],
46
+ output_dim=model_configs['embed_dim'],
47
+ learning_rate=0.,
48
+ device=device,
49
+ image_size=image_size,
50
+ prompting_depth=prompting_depth,
51
+ prompting_length=prompting_length,
52
+ prompting_branch=prompting_branch,
53
+ prompting_type=prompting_type,
54
+ use_hsf=use_hsf,
55
+ k_clusters=k_clusters
56
+ ).to(device)
57
+
58
+
59
+ def process_image(image, text, options):
60
+ # Load the model based on selected options
61
+ if 'MVTec AD+Colondb' in options:
62
+ model.load(ckt_path1)
63
+ elif 'VisA+Clinicdb' in options:
64
+ model.load(ckt_path2)
65
+ elif 'All' in options:
66
+ model.load(ckt_path3)
67
+ else:
68
+ # Default to 'All' if no valid option is provided
69
+ model.load(ckt_path3)
70
+ print('Invalid option. Defaulting to All.')
71
+
72
+ # Ensure image is in RGB mode
73
+ image = image.convert('RGB')
74
+
75
+ # Convert PIL image to NumPy array
76
+ np_image = np.array(image)
77
+
78
+ # Convert RGB to BGR for OpenCV
79
+ np_image = cv2.cvtColor(np_image, cv2.COLOR_RGB2BGR)
80
+ np_image = cv2.resize(np_image, (image_size, image_size))
81
+ # Preprocess the image and run the model
82
+ img_input = model.preprocess(image).unsqueeze(0)
83
+ img_input = img_input.to(model.device)
84
+
85
+ with torch.no_grad():
86
+ anomaly_map, anomaly_score = model.clip_model(img_input, [text], aggregation=True)
87
+
88
+ # Process anomaly map
89
+ anomaly_map = anomaly_map[0, :, :].cpu().numpy()
90
+ anomaly_score = anomaly_score[0].cpu().numpy()
91
+ anomaly_map = gaussian_filter(anomaly_map, sigma=4)
92
+ anomaly_map = (anomaly_map * 255).astype(np.uint8)
93
+
94
+ # Apply color map and blend with original image
95
+ heat_map = cv2.applyColorMap(anomaly_map, cv2.COLORMAP_JET)
96
+ vis_map = cv2.addWeighted(heat_map, 0.5, np_image, 0.5, 0)
97
+
98
+ # Convert OpenCV image back to PIL image for Gradio
99
+ vis_map_pil = Image.fromarray(cv2.cvtColor(vis_map, cv2.COLOR_BGR2RGB))
100
+
101
+ return vis_map_pil, f'{anomaly_score:.3f}'
102
+
103
+ # Define examples
104
+ examples = [
105
+ ["asset/img.png", "candle", "MVTec AD+Colondb"],
106
+ ["asset/img2.png", "bottle", "VisA+Clinicdb"],
107
+ ["asset/img3.png", "button", "All"],
108
+ ]
109
+
110
+ # Gradio interface layout
111
+ demo = gr.Interface(
112
+ fn=process_image,
113
+ inputs=[
114
+ gr.Image(type="pil", label="Upload Image"),
115
+ gr.Textbox(label="Class Name"),
116
+ gr.Radio(["MVTec AD+Colondb",
117
+ "VisA+Clinicdb",
118
+ "All"],
119
+ label="Pre-trained Datasets")
120
+ ],
121
+ outputs=[
122
+ gr.Image(type="pil", label="Output Image"),
123
+ gr.Textbox(label="Anomaly Score"),
124
+ ],
125
+ examples=examples,
126
+ title="AdaCLIP -- Zero-shot Anomaly Detection",
127
+ description="Upload an image, enter class name, and select pre-trained datasets to do zero-shot anomaly detection"
128
+ )
129
+
130
+ # Launch the demo
131
+ demo.launch()
132
+ # demo.launch(server_name="0.0.0.0", server_port=10002)
133
+
config.py ADDED
@@ -0,0 +1 @@
 
 
1
+ DATA_ROOT = 'data'
data_preprocess/br35h.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+ from config import DATA_ROOT
5
+
6
+ Br35h_ROOT = os.path.join(DATA_ROOT, 'Br35h_anomaly_detection')
7
+ class Br35hSolver(object):
8
+ CLSNAMES = [
9
+ 'br35h',
10
+ ]
11
+
12
+ def __init__(self, root=Br35h_ROOT, train_ratio=0.5):
13
+ self.root = root
14
+ self.meta_path = f'{root}/meta.json'
15
+ self.train_ratio = train_ratio
16
+
17
+ def run(self):
18
+ self.generate_meta_info()
19
+
20
+ def generate_meta_info(self):
21
+ info = dict(train={}, test={})
22
+ for cls_name in self.CLSNAMES:
23
+ cls_dir = f'{self.root}/{cls_name}'
24
+ for phase in ['train', 'test']:
25
+ cls_info = []
26
+ species = os.listdir(f'{cls_dir}/{phase}')
27
+ for specie in species:
28
+ is_abnormal = True if specie not in ['good'] else False
29
+ img_names = os.listdir(f'{cls_dir}/{phase}/{specie}')
30
+ img_names.sort()
31
+
32
+ for idx, img_name in enumerate(img_names):
33
+ info_img = dict(
34
+ img_path=f'{cls_name}/{phase}/{specie}/{img_name}',
35
+ mask_path=f'',
36
+ cls_name=cls_name,
37
+ specie_name=specie,
38
+ anomaly=1 if is_abnormal else 0,
39
+ )
40
+ cls_info.append(info_img)
41
+
42
+ info[phase][cls_name] = cls_info
43
+
44
+ with open(self.meta_path, 'w') as f:
45
+ f.write(json.dumps(info, indent=4) + "\n")
46
+
47
+
48
+ if __name__ == '__main__':
49
+ runner = Br35hSolver(root=Br35h_ROOT)
50
+ runner.run()
data_preprocess/brain_mri.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+ from config import DATA_ROOT
5
+
6
+ BrainMRI_ROOT = os.path.join(DATA_ROOT, 'BrainMRI')
7
+
8
+ class BrainMRISolver(object):
9
+ CLSNAMES = [
10
+ 'brain_mri',
11
+ ]
12
+
13
+ def __init__(self, root=BrainMRI_ROOT, train_ratio=0.5):
14
+ self.root = root
15
+ self.meta_path = f'{root}/meta.json'
16
+ self.train_ratio = train_ratio
17
+
18
+ def run(self):
19
+ self.generate_meta_info()
20
+
21
+ def generate_meta_info(self):
22
+ info = dict(train={}, test={})
23
+ for cls_name in self.CLSNAMES:
24
+ cls_dir = f'{self.root}/{cls_name}'
25
+ for phase in ['train', 'test']:
26
+ cls_info = []
27
+ species = os.listdir(f'{cls_dir}/{phase}')
28
+ for specie in species:
29
+ is_abnormal = True if specie not in ['good'] else False
30
+ img_names = os.listdir(f'{cls_dir}/{phase}/{specie}')
31
+ img_names.sort()
32
+
33
+ for idx, img_name in enumerate(img_names):
34
+ info_img = dict(
35
+ img_path=f'{cls_name}/{phase}/{specie}/{img_name}',
36
+ mask_path=f'',
37
+ cls_name=cls_name,
38
+ specie_name=specie,
39
+ anomaly=1 if is_abnormal else 0,
40
+ )
41
+ cls_info.append(info_img)
42
+
43
+ info[phase][cls_name] = cls_info
44
+
45
+ with open(self.meta_path, 'w') as f:
46
+ f.write(json.dumps(info, indent=4) + "\n")
47
+
48
+
49
+ if __name__ == '__main__':
50
+ runner = BrainMRISolver(root=BrainMRI_ROOT)
51
+ runner.run()
data_preprocess/btad.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+ from config import DATA_ROOT
5
+
6
+ BTAD_ROOT = os.path.join(DATA_ROOT, 'BTech_Dataset_transformed')
7
+
8
+ class BTADSolver(object):
9
+ CLSNAMES = [
10
+ '01', '02', '03',
11
+ ]
12
+
13
+ def __init__(self, root=BTAD_ROOT, train_ratio=0.5):
14
+ self.root = root
15
+ self.meta_path = f'{root}/meta.json'
16
+ self.train_ratio = train_ratio
17
+
18
+ def run(self):
19
+ self.generate_meta_info()
20
+
21
+ def generate_meta_info(self):
22
+ info = dict(train={}, test={})
23
+ for cls_name in self.CLSNAMES:
24
+ cls_dir = f'{self.root}/{cls_name}'
25
+ for phase in ['train', 'test']:
26
+ cls_info = []
27
+ species = os.listdir(f'{cls_dir}/{phase}')
28
+ for specie in species:
29
+ is_abnormal = True if specie not in ['ok'] else False
30
+ img_names = os.listdir(f'{cls_dir}/{phase}/{specie}')
31
+ mask_names = os.listdir(f'{cls_dir}/ground_truth/{specie}') if is_abnormal else None
32
+ img_names.sort()
33
+ mask_names.sort() if mask_names is not None else None
34
+ for idx, img_name in enumerate(img_names):
35
+ info_img = dict(
36
+ img_path=f'{cls_name}/{phase}/{specie}/{img_name}',
37
+ mask_path=f'{cls_name}/ground_truth/{specie}/{mask_names[idx]}' if is_abnormal else '',
38
+ cls_name=cls_name,
39
+ specie_name=specie,
40
+ anomaly=1 if is_abnormal else 0,
41
+ )
42
+ cls_info.append(info_img)
43
+
44
+ info[phase][cls_name] = cls_info
45
+
46
+ with open(self.meta_path, 'w') as f:
47
+ f.write(json.dumps(info, indent=4) + "\n")
48
+
49
+
50
+ if __name__ == '__main__':
51
+ runner = BTADSolver(root=BTAD_ROOT)
52
+ runner.run()
data_preprocess/clinicdb.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+ from config import DATA_ROOT
5
+
6
+ ClinicDB_ROOT = os.path.join(DATA_ROOT, 'CVC-ClinicDB')
7
+
8
+ class ClinicDBSolver(object):
9
+ CLSNAMES = [
10
+ 'ClinicDB',
11
+ ]
12
+
13
+ def __init__(self, root=ClinicDB_ROOT, train_ratio=0.5):
14
+ self.root = root
15
+ self.meta_path = f'{root}/meta.json'
16
+ self.train_ratio = train_ratio
17
+
18
+ def run(self):
19
+ self.generate_meta_info()
20
+
21
+ def generate_meta_info(self):
22
+ info = dict(train={}, test={})
23
+ for cls_name in self.CLSNAMES:
24
+ cls_dir = f'{self.root}/{cls_name}'
25
+ for phase in ['train', 'test']:
26
+ cls_info = []
27
+ species = os.listdir(f'{cls_dir}/{phase}')
28
+ for specie in species:
29
+ is_abnormal = True if specie not in ['good'] else False
30
+ img_names = os.listdir(f'{cls_dir}/{phase}/{specie}')
31
+ mask_names = os.listdir(f'{cls_dir}/ground_truth/{specie}') if is_abnormal else None
32
+ img_names.sort()
33
+ mask_names.sort() if mask_names is not None else None
34
+ for idx, img_name in enumerate(img_names):
35
+ info_img = dict(
36
+ img_path=f'{cls_name}/{phase}/{specie}/{img_name}',
37
+ mask_path=f'{cls_name}/ground_truth/{specie}/{mask_names[idx]}' if is_abnormal else '',
38
+ cls_name=cls_name,
39
+ specie_name=specie,
40
+ anomaly=1 if is_abnormal else 0,
41
+ )
42
+ cls_info.append(info_img)
43
+
44
+ info[phase][cls_name] = cls_info
45
+
46
+ with open(self.meta_path, 'w') as f:
47
+ f.write(json.dumps(info, indent=4) + "\n")
48
+
49
+
50
+ if __name__ == '__main__':
51
+ runner = ClinicDBSolver(root=ClinicDB_ROOT)
52
+ runner.run()
data_preprocess/colondb.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+ from config import DATA_ROOT
5
+
6
+ ColonDB_ROOT = os.path.join(DATA_ROOT, 'CVC-ColonDB')
7
+
8
+ class ColonDBSolver(object):
9
+ CLSNAMES = [
10
+ 'ColonDB',
11
+ ]
12
+
13
+ def __init__(self, root=ColonDB_ROOT, train_ratio=0.5):
14
+ self.root = root
15
+ self.meta_path = f'{root}/meta.json'
16
+ self.train_ratio = train_ratio
17
+
18
+ def run(self):
19
+ self.generate_meta_info()
20
+
21
+ def generate_meta_info(self):
22
+ info = dict(train={}, test={})
23
+ for cls_name in self.CLSNAMES:
24
+ cls_dir = f'{self.root}/{cls_name}'
25
+ for phase in ['train', 'test']:
26
+ cls_info = []
27
+ species = os.listdir(f'{cls_dir}/{phase}')
28
+ for specie in species:
29
+ is_abnormal = True if specie not in ['good'] else False
30
+ img_names = os.listdir(f'{cls_dir}/{phase}/{specie}')
31
+ mask_names = os.listdir(f'{cls_dir}/ground_truth/{specie}') if is_abnormal else None
32
+ img_names.sort()
33
+ mask_names.sort() if mask_names is not None else None
34
+ for idx, img_name in enumerate(img_names):
35
+ info_img = dict(
36
+ img_path=f'{cls_name}/{phase}/{specie}/{img_name}',
37
+ mask_path=f'{cls_name}/ground_truth/{specie}/{mask_names[idx]}' if is_abnormal else '',
38
+ cls_name=cls_name,
39
+ specie_name=specie,
40
+ anomaly=1 if is_abnormal else 0,
41
+ )
42
+ cls_info.append(info_img)
43
+
44
+ info[phase][cls_name] = cls_info
45
+
46
+ with open(self.meta_path, 'w') as f:
47
+ f.write(json.dumps(info, indent=4) + "\n")
48
+
49
+
50
+ if __name__ == '__main__':
51
+ runner = ColonDBSolver(root=ColonDB_ROOT)
52
+ runner.run()
data_preprocess/dagm-pre.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ from sklearn.model_selection import train_test_split
4
+ import cv2
5
+ import argparse
6
+ from config import DATA_ROOT
7
+
8
+ dataset_root = os.path.join(DATA_ROOT, 'DAGM2007')
9
+
10
+ class_names = os.listdir(dataset_root)
11
+
12
+
13
+ for class_name in class_names:
14
+ states = os.listdir(os.path.join(dataset_root, class_name))
15
+ for state in states:
16
+ images = list()
17
+ mask = list()
18
+ files = os.listdir(os.path.join(dataset_root, class_name,state))
19
+ for f in files:
20
+ if 'PNG' in f[-3:]:
21
+ images.append(f)
22
+ files = os.listdir(os.path.join(dataset_root, class_name, state,'Label'))
23
+ for f in files:
24
+ if 'PNG' in f[-3:]:
25
+ mask.append(f)
26
+ normal_image_path_train = list()
27
+ normal_image_path_test = list()
28
+ normal_image_path = list()
29
+ abnormal_image_path = list()
30
+ abnormal_image_label = list()
31
+ for f in images:
32
+ id = f[-8:-4]
33
+ flag = 0
34
+ for y in mask:
35
+ if id in y:
36
+ abnormal_image_path.append(f)
37
+ abnormal_image_label.append(y)
38
+ flag = 1
39
+ break
40
+ if flag == 0:
41
+ normal_image_path.append(f)
42
+
43
+ if len(abnormal_image_path) != len(abnormal_image_label):
44
+ raise ValueError
45
+ length = len(abnormal_image_path)
46
+
47
+ normal_image_path_test = normal_image_path[:length]
48
+ normal_image_path_train = normal_image_path[length:]
49
+
50
+ target_root = '../datasets/DAGM_anomaly_detection'
51
+
52
+ train_root = os.path.join(target_root, class_name, 'train','good')
53
+ if not os.path.exists(train_root):
54
+ os.makedirs(train_root)
55
+ for f in normal_image_path_train:
56
+ image_data = cv2.imread(os.path.join(dataset_root, class_name, state,f))
57
+ cv2.imwrite(os.path.join(train_root,f), image_data)
58
+
59
+ test_root = os.path.join(target_root, class_name, 'test','good')
60
+ if not os.path.exists(test_root):
61
+ os.makedirs(test_root)
62
+ for f in normal_image_path_test:
63
+ image_data = cv2.imread(os.path.join(dataset_root, class_name, state,f))
64
+ cv2.imwrite(os.path.join(test_root,f), image_data)
65
+
66
+ test_root = os.path.join(target_root, class_name, 'test','defect')
67
+ if not os.path.exists(test_root):
68
+ os.makedirs(test_root)
69
+ for f in abnormal_image_path:
70
+ image_data = cv2.imread(os.path.join(dataset_root, class_name, state,f))
71
+ cv2.imwrite(os.path.join(test_root,f), image_data)
72
+
73
+ test_root = os.path.join(target_root, class_name, 'ground_truth','defect')
74
+ if not os.path.exists(test_root):
75
+ os.makedirs(test_root)
76
+ for f in mask:
77
+ image_data = cv2.imread(os.path.join(dataset_root, class_name, state,'Label',f))
78
+ cv2.imwrite(os.path.join(test_root,f), image_data)
79
+
80
+
81
+
82
+ print("Done")
data_preprocess/dagm.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+ from config import DATA_ROOT
5
+
6
+ DAGM_ROOT = os.path.join(DATA_ROOT, 'DAGM_anomaly_detection')
7
+
8
+ class DAGMSolver(object):
9
+ CLSNAMES = [
10
+ 'Class1', 'Class2', 'Class3', 'Class4', 'Class5','Class6','Class7','Class8','Class9','Class10',
11
+ ]
12
+
13
+ def __init__(self, root=DAGM_ROOT, train_ratio=0.5):
14
+ self.root = root
15
+ self.meta_path = f'{root}/meta.json'
16
+ self.train_ratio = train_ratio
17
+
18
+ def run(self):
19
+ self.generate_meta_info()
20
+
21
+ def generate_meta_info(self):
22
+ info = dict(train={}, test={})
23
+ for cls_name in self.CLSNAMES:
24
+ cls_dir = f'{self.root}/{cls_name}'
25
+ for phase in ['train', 'test']:
26
+ cls_info = []
27
+ species = os.listdir(f'{cls_dir}/{phase}')
28
+ for specie in species:
29
+ is_abnormal = True if specie not in ['good'] else False
30
+ img_names = os.listdir(f'{cls_dir}/{phase}/{specie}')
31
+ mask_names = os.listdir(f'{cls_dir}/ground_truth/{specie}') if is_abnormal else None
32
+ img_names.sort()
33
+ mask_names.sort() if mask_names is not None else None
34
+ for idx, img_name in enumerate(img_names):
35
+ info_img = dict(
36
+ img_path=f'{cls_name}/{phase}/{specie}/{img_name}',
37
+ mask_path=f'{cls_name}/ground_truth/{specie}/{mask_names[idx]}' if is_abnormal else '',
38
+ cls_name=cls_name,
39
+ specie_name=specie,
40
+ anomaly=1 if is_abnormal else 0,
41
+ )
42
+ cls_info.append(info_img)
43
+
44
+ info[phase][cls_name] = cls_info
45
+
46
+ with open(self.meta_path, 'w') as f:
47
+ f.write(json.dumps(info, indent=4) + "\n")
48
+
49
+
50
+ if __name__ == '__main__':
51
+ runner = DAGMSolver(root=DAGM_ROOT)
52
+ runner.run()
data_preprocess/dtd.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+ from config import DATA_ROOT
5
+
6
+ DTD_ROOT = os.path.join(DATA_ROOT, 'DTD-Synthetic')
7
+
8
+ class DTDSolver(object):
9
+ CLSNAMES = [
10
+ 'Blotchy_099', 'Fibrous_183', 'Marbled_078', 'Matted_069', 'Mesh_114','Perforated_037','Stratified_154','Woven_001','Woven_068','Woven_104','Woven_125','Woven_127',
11
+ ]
12
+
13
+ def __init__(self, root=DTD_ROOT, train_ratio=0.5):
14
+ self.root = root
15
+ self.meta_path = f'{root}/meta.json'
16
+ self.train_ratio = train_ratio
17
+
18
+ def run(self):
19
+ self.generate_meta_info()
20
+
21
+ def generate_meta_info(self):
22
+ info = dict(train={}, test={})
23
+ for cls_name in self.CLSNAMES:
24
+ cls_dir = f'{self.root}/{cls_name}'
25
+ for phase in ['train', 'test']:
26
+ cls_info = []
27
+ species = os.listdir(f'{cls_dir}/{phase}')
28
+ for specie in species:
29
+ is_abnormal = True if specie not in ['good'] else False
30
+ img_names = os.listdir(f'{cls_dir}/{phase}/{specie}')
31
+ mask_names = os.listdir(f'{cls_dir}/ground_truth/{specie}') if is_abnormal else None
32
+ img_names.sort()
33
+ mask_names.sort() if mask_names is not None else None
34
+ for idx, img_name in enumerate(img_names):
35
+ info_img = dict(
36
+ img_path=f'{cls_name}/{phase}/{specie}/{img_name}',
37
+ mask_path=f'{cls_name}/ground_truth/{specie}/{mask_names[idx]}' if is_abnormal else '',
38
+ cls_name=cls_name,
39
+ specie_name=specie,
40
+ anomaly=1 if is_abnormal else 0,
41
+ )
42
+ cls_info.append(info_img)
43
+
44
+ info[phase][cls_name] = cls_info
45
+
46
+ with open(self.meta_path, 'w') as f:
47
+ f.write(json.dumps(info, indent=4) + "\n")
48
+
49
+
50
+ if __name__ == '__main__':
51
+ runner = DTDSolver(root=DTD_ROOT)
52
+ runner.run()
data_preprocess/endo.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+ from config import DATA_ROOT
5
+
6
+ ENDO_ROOT = os.path.join(DATA_ROOT, 'EndoTect')
7
+
8
+ class ENDOSolver(object):
9
+ CLSNAMES = [
10
+ 'endo',
11
+ ]
12
+
13
+ def __init__(self, root=ENDO_ROOT, train_ratio=0.5):
14
+ self.root = root
15
+ self.meta_path = f'{root}/meta.json'
16
+ self.train_ratio = train_ratio
17
+
18
+ def run(self):
19
+ self.generate_meta_info()
20
+
21
+ def generate_meta_info(self):
22
+ info = dict(train={}, test={})
23
+ for cls_name in self.CLSNAMES:
24
+ cls_dir = f'{self.root}/{cls_name}'
25
+ for phase in ['train', 'test']:
26
+ cls_info = []
27
+ species = os.listdir(f'{cls_dir}/{phase}')
28
+ for specie in species:
29
+ is_abnormal = True if specie not in ['good'] else False
30
+ img_names = os.listdir(f'{cls_dir}/{phase}/{specie}')
31
+ mask_names = os.listdir(f'{cls_dir}/ground_truth/{specie}') if is_abnormal else None
32
+ img_names.sort()
33
+ mask_names.sort() if mask_names is not None else None
34
+ for idx, img_name in enumerate(img_names):
35
+ info_img = dict(
36
+ img_path=f'{cls_name}/{phase}/{specie}/{img_name}',
37
+ mask_path=f'{cls_name}/ground_truth/{specie}/{mask_names[idx]}' if is_abnormal else '',
38
+ cls_name=cls_name,
39
+ specie_name=specie,
40
+ anomaly=1 if is_abnormal else 0,
41
+ )
42
+ cls_info.append(info_img)
43
+
44
+ info[phase][cls_name] = cls_info
45
+
46
+ with open(self.meta_path, 'w') as f:
47
+ f.write(json.dumps(info, indent=4) + "\n")
48
+
49
+
50
+ if __name__ == '__main__':
51
+ runner = ENDOSolver(root=ENDO_ROOT)
52
+ runner.run()
data_preprocess/headct-pre.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ from sklearn.model_selection import train_test_split
4
+ import shutil
5
+ import argparse
6
+
7
+ from config import DATA_ROOT
8
+
9
+ dataset_root = os.path.join(DATA_ROOT, 'head_ct')
10
+
11
+ label_file = os.path.join(dataset_root, 'labels.csv')
12
+
13
+ data = np.loadtxt(label_file, dtype=int, delimiter=',', skiprows=1)
14
+
15
+ fnames = data[:, 0]
16
+ label = data[:, 1]
17
+
18
+ normal_fnames = fnames[label==0]
19
+ outlier_fnames = fnames[label==1]
20
+
21
+
22
+ target_root = '../datasets/HeadCT_anomaly_detection/headct'
23
+ train_root = os.path.join(target_root, 'train/good')
24
+ if not os.path.exists(train_root):
25
+ os.makedirs(train_root)
26
+
27
+ test_normal_root = os.path.join(target_root, 'test/good')
28
+ if not os.path.exists(test_normal_root):
29
+ os.makedirs(test_normal_root)
30
+ for f in normal_fnames:
31
+ source = os.path.join(dataset_root, 'head_ct/', '{:0>3d}.png'.format(f))
32
+ shutil.copy(source, test_normal_root)
33
+
34
+ test_outlier_root = os.path.join(target_root, 'test/defect')
35
+ if not os.path.exists(test_outlier_root):
36
+ os.makedirs(test_outlier_root)
37
+ for f in outlier_fnames:
38
+ source = os.path.join(dataset_root, 'head_ct/', '{:0>3d}.png'.format(f))
39
+ shutil.copy(source, test_outlier_root)
40
+
41
+ print('Done')
data_preprocess/headct.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+ # from dataset import MPDD_ROOT
5
+ # from dataset.mpdd import MPDD_ROOT
6
+
7
+
8
+ HEADCT_ROOT = '../datasets/HeadCT_anomaly_detection'
9
+ class HEADCTSolver(object):
10
+ CLSNAMES = [
11
+ 'headct',
12
+ ]
13
+
14
+ def __init__(self, root=HEADCT_ROOT, train_ratio=0.5):
15
+ self.root = root
16
+ self.meta_path = f'{root}/meta.json'
17
+ self.train_ratio = train_ratio
18
+
19
+ def run(self):
20
+ self.generate_meta_info()
21
+
22
+ def generate_meta_info(self):
23
+ info = dict(train={}, test={})
24
+ for cls_name in self.CLSNAMES:
25
+ cls_dir = f'{self.root}/{cls_name}'
26
+ for phase in ['train', 'test']:
27
+ cls_info = []
28
+ species = os.listdir(f'{cls_dir}/{phase}')
29
+ for specie in species:
30
+ is_abnormal = True if specie not in ['good'] else False
31
+ img_names = os.listdir(f'{cls_dir}/{phase}/{specie}')
32
+ img_names.sort()
33
+
34
+ for idx, img_name in enumerate(img_names):
35
+ info_img = dict(
36
+ img_path=f'{cls_name}/{phase}/{specie}/{img_name}',
37
+ mask_path=f'',
38
+ cls_name=cls_name,
39
+ specie_name=specie,
40
+ anomaly=1 if is_abnormal else 0,
41
+ )
42
+ cls_info.append(info_img)
43
+
44
+ info[phase][cls_name] = cls_info
45
+
46
+ with open(self.meta_path, 'w') as f:
47
+ f.write(json.dumps(info, indent=4) + "\n")
48
+
49
+
50
+ if __name__ == '__main__':
51
+ runner = HEADCTSolver(root=HEADCT_ROOT)
52
+ runner.run()
data_preprocess/isic.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+ from config import DATA_ROOT
5
+
6
+ ISIC_ROOT = os.path.join(DATA_ROOT, 'ISIC')
7
+
8
+ class ISICSolver(object):
9
+ CLSNAMES = [
10
+ 'isic',
11
+ ]
12
+
13
+ def __init__(self, root=ISIC_ROOT, train_ratio=0.5):
14
+ self.root = root
15
+ self.meta_path = f'{root}/meta.json'
16
+ self.train_ratio = train_ratio
17
+
18
+ def run(self):
19
+ self.generate_meta_info()
20
+
21
+ def generate_meta_info(self):
22
+ info = dict(train={}, test={})
23
+ for cls_name in self.CLSNAMES:
24
+ cls_dir = f'{self.root}/{cls_name}'
25
+ for phase in ['train', 'test']:
26
+ cls_info = []
27
+ species = os.listdir(f'{cls_dir}/{phase}')
28
+ for specie in species:
29
+ is_abnormal = True if specie not in ['good'] else False
30
+ img_names = os.listdir(f'{cls_dir}/{phase}/{specie}')
31
+ mask_names = os.listdir(f'{cls_dir}/ground_truth/{specie}') if is_abnormal else None
32
+ img_names.sort()
33
+ mask_names.sort() if mask_names is not None else None
34
+ for idx, img_name in enumerate(img_names):
35
+ info_img = dict(
36
+ img_path=f'{cls_name}/{phase}/{specie}/{img_name}',
37
+ mask_path=f'{cls_name}/ground_truth/{specie}/{mask_names[idx]}' if is_abnormal else '',
38
+ cls_name=cls_name,
39
+ specie_name=specie,
40
+ anomaly=1 if is_abnormal else 0,
41
+ )
42
+ cls_info.append(info_img)
43
+
44
+ info[phase][cls_name] = cls_info
45
+
46
+ with open(self.meta_path, 'w') as f:
47
+ f.write(json.dumps(info, indent=4) + "\n")
48
+
49
+
50
+ if __name__ == '__main__':
51
+ runner = ISICSolver(root=ISIC_ROOT)
52
+ runner.run()
data_preprocess/mpdd.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+ from config import DATA_ROOT
5
+
6
+ MPDD_ROOT = os.path.join(DATA_ROOT, 'MPDD')
7
+
8
+ class MPDDSolver(object):
9
+ CLSNAMES = [
10
+ 'bracket_black', 'bracket_brown', 'bracket_white', 'connector', 'metal_plate','tubes',
11
+ ]
12
+
13
+ def __init__(self, root=MPDD_ROOT, train_ratio=0.5):
14
+ self.root = root
15
+ self.meta_path = f'{root}/meta.json'
16
+ self.train_ratio = train_ratio
17
+
18
+ def run(self):
19
+ self.generate_meta_info()
20
+
21
+ def generate_meta_info(self):
22
+ info = dict(train={}, test={})
23
+ for cls_name in self.CLSNAMES:
24
+ cls_dir = f'{self.root}/{cls_name}'
25
+ for phase in ['train', 'test']:
26
+ cls_info = []
27
+ species = os.listdir(f'{cls_dir}/{phase}')
28
+ for specie in species:
29
+ is_abnormal = True if specie not in ['good'] else False
30
+ img_names = os.listdir(f'{cls_dir}/{phase}/{specie}')
31
+ mask_names = os.listdir(f'{cls_dir}/ground_truth/{specie}') if is_abnormal else None
32
+ img_names.sort()
33
+ mask_names.sort() if mask_names is not None else None
34
+ for idx, img_name in enumerate(img_names):
35
+ info_img = dict(
36
+ img_path=f'{cls_name}/{phase}/{specie}/{img_name}',
37
+ mask_path=f'{cls_name}/ground_truth/{specie}/{mask_names[idx]}' if is_abnormal else '',
38
+ cls_name=cls_name,
39
+ specie_name=specie,
40
+ anomaly=1 if is_abnormal else 0,
41
+ )
42
+ cls_info.append(info_img)
43
+
44
+ info[phase][cls_name] = cls_info
45
+
46
+ with open(self.meta_path, 'w') as f:
47
+ f.write(json.dumps(info, indent=4) + "\n")
48
+
49
+
50
+ if __name__ == '__main__':
51
+ runner = MPDDSolver(root=MPDD_ROOT)
52
+ runner.run()
data_preprocess/mvtec.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+ from dataset import MVTEC_ROOT
5
+
6
+ class MVTecSolver(object):
7
+ CLSNAMES = [
8
+ 'bottle', 'cable', 'capsule', 'carpet', 'grid',
9
+ 'hazelnut', 'leather', 'metal_nut', 'pill', 'screw',
10
+ 'tile', 'toothbrush', 'transistor', 'wood', 'zipper',
11
+ ]
12
+
13
+ def __init__(self, root=MVTEC_ROOT, train_ratio=0.5):
14
+ self.root = root
15
+ self.meta_path = f'{root}/meta.json'
16
+ self.train_ratio = train_ratio
17
+
18
+ def run(self):
19
+ self.generate_meta_info()
20
+
21
+ def generate_meta_info(self):
22
+ info = dict(train={}, test={})
23
+ for cls_name in self.CLSNAMES:
24
+ cls_dir = f'{self.root}/{cls_name}'
25
+ for phase in ['train', 'test']:
26
+ cls_info = []
27
+ species = os.listdir(f'{cls_dir}/{phase}')
28
+ for specie in species:
29
+ is_abnormal = True if specie not in ['good'] else False
30
+ img_names = os.listdir(f'{cls_dir}/{phase}/{specie}')
31
+ mask_names = os.listdir(f'{cls_dir}/ground_truth/{specie}') if is_abnormal else None
32
+ img_names.sort()
33
+ mask_names.sort() if mask_names is not None else None
34
+ for idx, img_name in enumerate(img_names):
35
+ info_img = dict(
36
+ img_path=f'{cls_name}/{phase}/{specie}/{img_name}',
37
+ mask_path=f'{cls_name}/ground_truth/{specie}/{mask_names[idx]}' if is_abnormal else '',
38
+ cls_name=cls_name,
39
+ specie_name=specie,
40
+ anomaly=1 if is_abnormal else 0,
41
+ )
42
+ cls_info.append(info_img)
43
+
44
+ info[phase][cls_name] = cls_info
45
+
46
+ with open(self.meta_path, 'w') as f:
47
+ f.write(json.dumps(info, indent=4) + "\n")
48
+
49
+
50
+ if __name__ == '__main__':
51
+ runner = MVTecSolver(root=MVTEC_ROOT)
52
+ runner.run()
data_preprocess/sdd-pre.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ from sklearn.model_selection import train_test_split
4
+ import cv2
5
+ import argparse
6
+
7
+ from config import DATA_ROOT
8
+
9
+ dataset_root = os.path.join(DATA_ROOT, 'KolektorSDD')
10
+
11
+ dirs = os.listdir(dataset_root)
12
+ normal_images = list()
13
+ normal_labels = list()
14
+ normal_fname = list()
15
+ outlier_images = list()
16
+ outlier_labels = list()
17
+ outlier_fname = list()
18
+ for d in dirs:
19
+ files = os.listdir(os.path.join(dataset_root, d))
20
+ images = list()
21
+ for f in files:
22
+ if 'jpg' in f[-3:]:
23
+ images.append(f)
24
+
25
+ for image in images:
26
+ split_images = list()
27
+ split_labels = list()
28
+ image_name = image.split('.')[0]
29
+ image_data = cv2.imread(os.path.join(dataset_root, d, image))
30
+ label_data = cv2.imread(os.path.join(dataset_root, d, image_name + '_label.bmp'))
31
+ if image_data.shape != label_data.shape:
32
+ raise ValueError
33
+ image_length = image_data.shape[0]
34
+ split_images.append(image_data[:image_length // 3, :, :])
35
+ split_images.append(image_data[image_length // 3:image_length * 2 // 3, :, :])
36
+ split_images.append(image_data[image_length * 2 // 3:, :, :])
37
+ split_labels.append(label_data[:image_length // 3, :, :])
38
+ split_labels.append(label_data[image_length // 3:image_length * 2 // 3, :, :])
39
+ split_labels.append(label_data[image_length * 2 // 3:, :, :])
40
+ for i, (im, la) in enumerate(zip(split_images, split_labels)):
41
+ if np.max(la) != 0:
42
+ outlier_images.append(im)
43
+ outlier_labels.append(la)
44
+ outlier_fname.append(d + '_' + image_name + '_' + str(i))
45
+ else:
46
+ normal_images.append(im)
47
+ normal_labels.append(la)
48
+ normal_fname.append(d + '_' + image_name + '_' + str(i))
49
+
50
+ normal_train, normal_test, normal_name_train, normal_name_test = train_test_split(normal_images, normal_fname, test_size=0.25, random_state=42)
51
+
52
+ target_root = '../datasets/SDD_anomaly_detection/SDD'
53
+ train_root = os.path.join(target_root, 'train/good')
54
+ if not os.path.exists(train_root):
55
+ os.makedirs(train_root)
56
+ for image, name in zip(normal_train, normal_name_train):
57
+ cv2.imwrite(os.path.join(train_root, name + '.png'), image)
58
+
59
+ test_root = os.path.join(target_root, 'test/good')
60
+ if not os.path.exists(test_root):
61
+ os.makedirs(test_root)
62
+ for image, name in zip(normal_test, normal_name_test):
63
+ cv2.imwrite(os.path.join(test_root, name + '.png'), image)
64
+
65
+ defect_root = os.path.join(target_root, 'test/defect')
66
+ label_root = os.path.join(target_root, 'ground_truth/defect')
67
+ if not os.path.exists(defect_root):
68
+ os.makedirs(defect_root)
69
+ if not os.path.exists(label_root):
70
+ os.makedirs(label_root)
71
+ for image, label, name in zip(outlier_images, outlier_labels, outlier_fname):
72
+ cv2.imwrite(os.path.join(defect_root, name + '.png'), image)
73
+ cv2.imwrite(os.path.join(label_root, name + '_mask.png'), label)
74
+
75
+ print("Done")
data_preprocess/sdd.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+ from config import DATA_ROOT
5
+
6
+ SDD_ROOT = os.path.join(DATA_ROOT, 'SDD_anomaly_detection')
7
+
8
+ class SDDSolver(object):
9
+ CLSNAMES = [
10
+ 'SDD',
11
+ ]
12
+
13
+ def __init__(self, root=SDD_ROOT, train_ratio=0.5):
14
+ self.root = root
15
+ self.meta_path = f'{root}/meta.json'
16
+ self.train_ratio = train_ratio
17
+
18
+ def run(self):
19
+ self.generate_meta_info()
20
+
21
+ def generate_meta_info(self):
22
+ info = dict(train={}, test={})
23
+ for cls_name in self.CLSNAMES:
24
+ cls_dir = f'{self.root}/{cls_name}'
25
+ for phase in ['train', 'test']:
26
+ cls_info = []
27
+ species = os.listdir(f'{cls_dir}/{phase}')
28
+ for specie in species:
29
+ is_abnormal = True if specie not in ['good'] else False
30
+ img_names = os.listdir(f'{cls_dir}/{phase}/{specie}')
31
+ mask_names = os.listdir(f'{cls_dir}/ground_truth/{specie}') if is_abnormal else None
32
+ img_names.sort()
33
+ mask_names.sort() if mask_names is not None else None
34
+ for idx, img_name in enumerate(img_names):
35
+ info_img = dict(
36
+ img_path=f'{cls_name}/{phase}/{specie}/{img_name}',
37
+ mask_path=f'{cls_name}/ground_truth/{specie}/{mask_names[idx]}' if is_abnormal else '',
38
+ cls_name=cls_name,
39
+ specie_name=specie,
40
+ anomaly=1 if is_abnormal else 0,
41
+ )
42
+ cls_info.append(info_img)
43
+
44
+ info[phase][cls_name] = cls_info
45
+
46
+ with open(self.meta_path, 'w') as f:
47
+ f.write(json.dumps(info, indent=4) + "\n")
48
+
49
+
50
+ if __name__ == '__main__':
51
+ runner = SDDSolver(root=SDD_ROOT)
52
+ runner.run()
data_preprocess/tn3k.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+ from config import DATA_ROOT
5
+
6
+ TN3K_ROOT = os.path.join(DATA_ROOT, 'TN3K')
7
+
8
+ class TN3KSolver(object):
9
+ CLSNAMES = [
10
+ 'tn3k',
11
+ ]
12
+
13
+ def __init__(self, root=TN3K_ROOT, train_ratio=0.5):
14
+ self.root = root
15
+ self.meta_path = f'{root}/meta.json'
16
+ self.train_ratio = train_ratio
17
+
18
+ def run(self):
19
+ self.generate_meta_info()
20
+
21
+ def generate_meta_info(self):
22
+ info = dict(train={}, test={})
23
+ for cls_name in self.CLSNAMES:
24
+ cls_dir = f'{self.root}/{cls_name}'
25
+ for phase in ['train', 'test']:
26
+ cls_info = []
27
+ species = os.listdir(f'{cls_dir}/{phase}')
28
+ for specie in species:
29
+ is_abnormal = True if specie not in ['good'] else False
30
+ img_names = os.listdir(f'{cls_dir}/{phase}/{specie}')
31
+ mask_names = os.listdir(f'{cls_dir}/ground_truth/{specie}') if is_abnormal else None
32
+ img_names.sort()
33
+ mask_names.sort() if mask_names is not None else None
34
+ for idx, img_name in enumerate(img_names):
35
+ info_img = dict(
36
+ img_path=f'{cls_name}/{phase}/{specie}/{img_name}',
37
+ mask_path=f'{cls_name}/ground_truth/{specie}/{mask_names[idx]}' if is_abnormal else '',
38
+ cls_name=cls_name,
39
+ specie_name=specie,
40
+ anomaly=1 if is_abnormal else 0,
41
+ )
42
+ cls_info.append(info_img)
43
+
44
+ info[phase][cls_name] = cls_info
45
+
46
+ with open(self.meta_path, 'w') as f:
47
+ f.write(json.dumps(info, indent=4) + "\n")
48
+
49
+
50
+ if __name__ == '__main__':
51
+ runner = TN3KSolver(root=TN3K_ROOT)
52
+ runner.run()
data_preprocess/visa.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import pandas as pd
4
+ import random
5
+ from dataset import VISA_ROOT
6
+
7
+ class VisASolver(object):
8
+ CLSNAMES = [
9
+ 'candle', 'capsules', 'cashew', 'chewinggum', 'fryum',
10
+ 'macaroni1', 'macaroni2', 'pcb1', 'pcb2', 'pcb3',
11
+ 'pcb4', 'pipe_fryum',
12
+ ]
13
+
14
+ def __init__(self, root=VISA_ROOT, train_ratio=0.5):
15
+ self.root = root
16
+ self.meta_path = f'{root}/meta.json'
17
+ self.phases = ['train', 'test']
18
+ self.csv_data = pd.read_csv(f'{root}/split_csv/1cls.csv', header=0)
19
+ self.train_ratio = train_ratio
20
+
21
+ def run(self):
22
+ self.generate_meta_info()
23
+
24
+ def generate_meta_info(self):
25
+ columns = self.csv_data.columns # [object, split, label, image, mask]
26
+ info = {phase: {} for phase in self.phases}
27
+ for cls_name in self.CLSNAMES:
28
+ cls_data = self.csv_data[self.csv_data[columns[0]] == cls_name]
29
+ for phase in self.phases:
30
+ cls_info = []
31
+ cls_data_phase = cls_data[cls_data[columns[1]] == phase]
32
+ cls_data_phase.index = list(range(len(cls_data_phase)))
33
+ for idx in range(cls_data_phase.shape[0]):
34
+ data = cls_data_phase.loc[idx]
35
+ is_abnormal = True if data[2] == 'anomaly' else False
36
+ info_img = dict(
37
+ img_path=data[3],
38
+ mask_path=data[4] if is_abnormal else '',
39
+ cls_name=cls_name,
40
+ specie_name='',
41
+ anomaly=1 if is_abnormal else 0,
42
+ )
43
+ cls_info.append(info_img)
44
+ info[phase][cls_name] = cls_info
45
+ with open(self.meta_path, 'w') as f:
46
+ f.write(json.dumps(info, indent=4) + "\n")
47
+
48
+
49
+
50
+ if __name__ == '__main__':
51
+ runner = VisASolver(root=VISA_ROOT)
52
+ runner.run()
dataset/__init__.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .mvtec import MVTEC_CLS_NAMES, MVTecDataset, MVTEC_ROOT
2
+ from .visa import VISA_CLS_NAMES, VisaDataset, VISA_ROOT
3
+ from .mpdd import MPDD_CLS_NAMES, MPDDDataset, MPDD_ROOT
4
+ from .btad import BTAD_CLS_NAMES, BTADDataset, BTAD_ROOT
5
+ from .sdd import SDD_CLS_NAMES, SDDDataset, SDD_ROOT
6
+ from .dagm import DAGM_CLS_NAMES, DAGMDataset, DAGM_ROOT
7
+ from .dtd import DTD_CLS_NAMES,DTDDataset,DTD_ROOT
8
+ from .isic import ISIC_CLS_NAMES,ISICDataset,ISIC_ROOT
9
+ from .colondb import ColonDB_CLS_NAMES, ColonDBDataset, ColonDB_ROOT
10
+ from .clinicdb import ClinicDB_CLS_NAMES, ClinicDBDataset, ClinicDB_ROOT
11
+ from .tn3k import TN3K_CLS_NAMES, TN3KDataset, TN3K_ROOT
12
+ from .headct import HEADCT_CLS_NAMES,HEADCTDataset,HEADCT_ROOT
13
+ from .brain_mri import BrainMRI_CLS_NAMES,BrainMRIDataset,BrainMRI_ROOT
14
+ from .br35h import Br35h_CLS_NAMES,Br35hDataset,Br35h_ROOT
15
+ from torch.utils.data import ConcatDataset
16
+
17
+ dataset_dict = {
18
+ 'br35h': (Br35h_CLS_NAMES, Br35hDataset, Br35h_ROOT),
19
+ 'brain_mri': (BrainMRI_CLS_NAMES, BrainMRIDataset, BrainMRI_ROOT),
20
+ 'btad': (BTAD_CLS_NAMES, BTADDataset, BTAD_ROOT),
21
+ 'clinicdb': (ClinicDB_CLS_NAMES, ClinicDBDataset, ClinicDB_ROOT),
22
+ 'colondb': (ColonDB_CLS_NAMES, ColonDBDataset, ColonDB_ROOT),
23
+ 'dagm': (DAGM_CLS_NAMES, DAGMDataset, DAGM_ROOT),
24
+ 'dtd': (DTD_CLS_NAMES, DTDDataset, DTD_ROOT),
25
+ 'headct': (HEADCT_CLS_NAMES, HEADCTDataset, HEADCT_ROOT),
26
+ 'isic': (ISIC_CLS_NAMES, ISICDataset, ISIC_ROOT),
27
+ 'mpdd': (MPDD_CLS_NAMES, MPDDDataset, MPDD_ROOT),
28
+ 'mvtec': (MVTEC_CLS_NAMES, MVTecDataset, MVTEC_ROOT),
29
+ 'sdd': (SDD_CLS_NAMES, SDDDataset, SDD_ROOT),
30
+ 'tn3k': (TN3K_CLS_NAMES, TN3KDataset, TN3K_ROOT),
31
+ 'visa': (VISA_CLS_NAMES, VisaDataset, VISA_ROOT),
32
+ }
33
+
34
+ def get_data(dataset_type_list, transform, target_transform, training):
35
+ if not isinstance(dataset_type_list, list):
36
+ dataset_type_list = [dataset_type_list]
37
+
38
+ dataset_cls_names_list = []
39
+ dataset_instance_list = []
40
+ dataset_root_list = []
41
+ for dataset_type in dataset_type_list:
42
+ if dataset_dict.get(dataset_type, ''):
43
+ dataset_cls_names, dataset_instance, dataset_root = dataset_dict[dataset_type]
44
+ dataset_instance = dataset_instance(
45
+ clsnames=dataset_cls_names,
46
+ transform=transform,
47
+ target_transform=target_transform,
48
+ training=training
49
+ )
50
+
51
+ dataset_cls_names_list.append(dataset_cls_names)
52
+ dataset_instance_list.append(dataset_instance)
53
+ dataset_root_list.append(dataset_root)
54
+
55
+ else:
56
+ print(f'Only support {list(dataset_dict.keys())}, but entered {dataset_type}...')
57
+ raise NotImplementedError
58
+
59
+ if len(dataset_type_list) > 1:
60
+ dataset_instance = ConcatDataset(dataset_instance_list)
61
+ dataset_cls_names = dataset_cls_names_list
62
+ dataset_root = dataset_root_list
63
+ else:
64
+ dataset_instance = dataset_instance_list[0]
65
+ dataset_cls_names = dataset_cls_names_list[0]
66
+ dataset_root = dataset_root_list[0]
67
+
68
+ return dataset_cls_names, dataset_instance, dataset_root
dataset/base_dataset.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Base class for our zero-shot anomaly detection dataset
3
+ """
4
+ import json
5
+ import os
6
+ import random
7
+ import numpy as np
8
+ import torch.utils.data as data
9
+ from PIL import Image
10
+ import cv2
11
+ from config import DATA_ROOT
12
+
13
+
14
+ class DataSolver:
15
+ def __init__(self, root, clsnames):
16
+ self.root = root
17
+ self.clsnames = clsnames
18
+ self.path = os.path.join(root, 'meta.json')
19
+
20
+ def run(self):
21
+ with open(self.path, 'r') as f:
22
+ info = json.load(f)
23
+
24
+ info_required = dict(train={}, test={})
25
+ for cls in self.clsnames:
26
+ for k in info.keys():
27
+ info_required[k][cls] = info[k][cls]
28
+
29
+ return info_required
30
+
31
+
32
+ class BaseDataset(data.Dataset):
33
+ def __init__(self, clsnames, transform, target_transform, root, aug_rate=0., training=True):
34
+ self.root = root
35
+ self.transform = transform
36
+ self.target_transform = target_transform
37
+ self.aug_rate = aug_rate
38
+ self.training = training
39
+ self.data_all = []
40
+ self.cls_names = clsnames
41
+
42
+ solver = DataSolver(root, clsnames)
43
+ meta_info = solver.run()
44
+
45
+ self.meta_info = meta_info['test'] # Only utilize the test dataset for both training and testing
46
+ for cls_name in self.cls_names:
47
+ self.data_all.extend(self.meta_info[cls_name])
48
+
49
+ self.length = len(self.data_all)
50
+
51
+ def __len__(self):
52
+ return self.length
53
+
54
+ def combine_img(self, cls_name):
55
+ """
56
+ From April-GAN: https://github.com/ByChelsea/VAND-APRIL-GAN
57
+ Here we combine four images into a single image for data augmentation.
58
+ """
59
+ img_info = random.sample(self.meta_info[cls_name], 4)
60
+
61
+ img_ls = []
62
+ mask_ls = []
63
+
64
+ for data in img_info:
65
+ img_path = os.path.join(self.root, data['img_path'])
66
+ mask_path = os.path.join(self.root, data['mask_path'])
67
+
68
+ img = Image.open(img_path).convert('RGB')
69
+ img_ls.append(img)
70
+
71
+ if not data['anomaly']:
72
+ img_mask = Image.fromarray(np.zeros((img.size[0], img.size[1])), mode='L')
73
+ else:
74
+ img_mask = np.array(Image.open(mask_path).convert('L')) > 0
75
+ img_mask = Image.fromarray(img_mask.astype(np.uint8) * 255, mode='L')
76
+
77
+ mask_ls.append(img_mask)
78
+
79
+ # Image
80
+ image_width, image_height = img_ls[0].size
81
+ result_image = Image.new("RGB", (2 * image_width, 2 * image_height))
82
+ for i, img in enumerate(img_ls):
83
+ row = i // 2
84
+ col = i % 2
85
+ x = col * image_width
86
+ y = row * image_height
87
+ result_image.paste(img, (x, y))
88
+
89
+ # Mask
90
+ result_mask = Image.new("L", (2 * image_width, 2 * image_height))
91
+ for i, img in enumerate(mask_ls):
92
+ row = i // 2
93
+ col = i % 2
94
+ x = col * image_width
95
+ y = row * image_height
96
+ result_mask.paste(img, (x, y))
97
+
98
+ return result_image, result_mask
99
+
100
+ def __getitem__(self, index):
101
+ data = self.data_all[index]
102
+ img_path = os.path.join(self.root, data['img_path'])
103
+ mask_path = os.path.join(self.root, data['mask_path'])
104
+ cls_name = data['cls_name']
105
+ anomaly = data['anomaly']
106
+ random_number = random.random()
107
+
108
+ if self.training and random_number < self.aug_rate:
109
+ img, img_mask = self.combine_img(cls_name)
110
+ else:
111
+ if img_path.endswith('.tif'):
112
+ img = cv2.imread(img_path)
113
+ img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
114
+ else:
115
+ img = Image.open(img_path).convert('RGB')
116
+ if anomaly == 0:
117
+ img_mask = Image.fromarray(np.zeros((img.size[0], img.size[1])), mode='L')
118
+ else:
119
+ if data['mask_path']:
120
+ img_mask = np.array(Image.open(mask_path).convert('L')) > 0
121
+ img_mask = Image.fromarray(img_mask.astype(np.uint8) * 255, mode='L')
122
+ else:
123
+ img_mask = Image.fromarray(np.zeros((img.size[0], img.size[1])), mode='L')
124
+ # Transforms
125
+ if self.transform is not None:
126
+ img = self.transform(img)
127
+ if self.target_transform is not None and img_mask is not None:
128
+ img_mask = self.target_transform(img_mask)
129
+ if img_mask is None:
130
+ img_mask = []
131
+
132
+ return {
133
+ 'img': img,
134
+ 'img_mask': img_mask,
135
+ 'cls_name': cls_name,
136
+ 'anomaly': anomaly,
137
+ 'img_path': img_path
138
+ }
dataset/br35h.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_dataset import BaseDataset
3
+ from config import DATA_ROOT
4
+
5
+ '''dataset source: https://www.kaggle.com/datasets/ahmedhamada0/brain-tumor-detection'''
6
+
7
+ Br35h_CLS_NAMES = [
8
+ 'br35h',
9
+ ]
10
+ Br35h_ROOT = os.path.join(DATA_ROOT, 'Br35h_anomaly_detection')
11
+
12
+ class Br35hDataset(BaseDataset):
13
+ def __init__(self, transform, target_transform, clsnames=Br35h_CLS_NAMES, aug_rate=0.0, root=Br35h_ROOT, training=True):
14
+ super(Br35hDataset, self).__init__(
15
+ clsnames=clsnames, transform=transform, target_transform=target_transform,
16
+ root=root, aug_rate=aug_rate, training=training
17
+ )
18
+
dataset/brain_mri.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_dataset import BaseDataset
3
+ from config import DATA_ROOT
4
+
5
+ '''dataset source: https://www.kaggle.com/datasets/navoneel/brain-mri-images-for-brain-tumor-detection'''
6
+ BrainMRI_CLS_NAMES = [
7
+ 'brain_mri',
8
+ ]
9
+ BrainMRI_ROOT = os.path.join(DATA_ROOT, 'BrainMRI')
10
+
11
+ class BrainMRIDataset(BaseDataset):
12
+ def __init__(self, transform, target_transform, clsnames=BrainMRI_CLS_NAMES, aug_rate=0.0, root=BrainMRI_ROOT, training=True):
13
+ super(BrainMRIDataset, self).__init__(
14
+ clsnames=clsnames, transform=transform, target_transform=target_transform,
15
+ root=root, aug_rate=aug_rate, training=training
16
+ )
dataset/btad.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_dataset import BaseDataset
3
+ from config import DATA_ROOT
4
+
5
+ '''dataset source: https://avires.dimi.uniud.it/papers/btad/btad.zip'''
6
+ BTAD_CLS_NAMES = [
7
+ '01', '02', '03',
8
+ ]
9
+ BTAD_ROOT = os.path.join(DATA_ROOT, 'BTech_Dataset_transformed')
10
+
11
+ class BTADDataset(BaseDataset):
12
+ def __init__(self, transform, target_transform, clsnames=BTAD_CLS_NAMES, aug_rate=0.0, root=BTAD_ROOT, training=True):
13
+ super(BTADDataset, self).__init__(
14
+ clsnames=clsnames, transform=transform, target_transform=target_transform,
15
+ root=root, aug_rate=aug_rate, training=training
16
+ )
dataset/clinicdb.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_dataset import BaseDataset
3
+ from config import DATA_ROOT
4
+
5
+ '''dataset source: https://paperswithcode.com/dataset/cvc-clinicdb'''
6
+ ClinicDB_CLS_NAMES = [
7
+ 'ClinicDB',
8
+ ]
9
+ ClinicDB_ROOT = os.path.join(DATA_ROOT, 'CVC-ClinicDB')
10
+
11
+ class ClinicDBDataset(BaseDataset):
12
+ def __init__(self, transform, target_transform, clsnames=ClinicDB_CLS_NAMES, aug_rate=0.0, root=ClinicDB_ROOT, training=True):
13
+ super(ClinicDBDataset, self).__init__(
14
+ clsnames=clsnames, transform=transform, target_transform=target_transform,
15
+ root=root, aug_rate=aug_rate, training=training
16
+ )
dataset/colondb.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_dataset import BaseDataset
3
+ from config import DATA_ROOT
4
+
5
+ '''dataset source: http://mv.cvc.uab.es/projects/colon-qa/cvccolondb'''
6
+ ColonDB_CLS_NAMES = [
7
+ 'ColonDB',
8
+ ]
9
+ ColonDB_ROOT = os.path.join(DATA_ROOT, 'CVC-ColonDB')
10
+
11
+ class ColonDBDataset(BaseDataset):
12
+ def __init__(self, transform, target_transform, clsnames=ColonDB_CLS_NAMES, aug_rate=0.0, root=ColonDB_ROOT, training=True):
13
+ super(ColonDBDataset, self).__init__(
14
+ clsnames=clsnames, transform=transform, target_transform=target_transform,
15
+ root=root, aug_rate=aug_rate, training=training
16
+ )
17
+
18
+
dataset/dagm.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_dataset import BaseDataset
3
+ from config import DATA_ROOT
4
+
5
+ '''dataset source: https://hci.iwr.uni-heidelberg.de/content/weakly-supervised-learning-industrial-optical-inspection'''
6
+ DAGM_CLS_NAMES = [
7
+ 'Class1', 'Class2', 'Class3', 'Class4', 'Class5','Class6','Class7','Class8','Class9','Class10',
8
+ ]
9
+ DAGM_ROOT = os.path.join(DATA_ROOT, 'DAGM_anomaly_detection')
10
+
11
+ class DAGMDataset(BaseDataset):
12
+ def __init__(self, transform, target_transform, clsnames=DAGM_CLS_NAMES, aug_rate=0.0, root=DAGM_ROOT, training=True):
13
+ super(DAGMDataset, self).__init__(
14
+ clsnames=clsnames, transform=transform, target_transform=target_transform,
15
+ root=root, aug_rate=aug_rate, training=training
16
+ )
dataset/dtd.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_dataset import BaseDataset
3
+ from config import DATA_ROOT
4
+
5
+ '''dataset source: https://drive.google.com/drive/folders/10OyPzvI3H6llCZBxKxFlKWt1Pw1tkMK1'''
6
+ DTD_CLS_NAMES = [
7
+ 'Blotchy_099', 'Fibrous_183', 'Marbled_078', 'Matted_069', 'Mesh_114','Perforated_037','Stratified_154','Woven_001','Woven_068','Woven_104','Woven_125','Woven_127',
8
+ ]
9
+ DTD_ROOT = os.path.join(DATA_ROOT, 'DTD-Synthetic')
10
+
11
+ class DTDDataset(BaseDataset):
12
+ def __init__(self, transform, target_transform, clsnames=DTD_CLS_NAMES, aug_rate=0.0, root=DTD_ROOT, training=True):
13
+ super(DTDDataset, self).__init__(
14
+ clsnames=clsnames, transform=transform, target_transform=target_transform,
15
+ root=root, aug_rate=aug_rate, training=training
16
+ )
dataset/headct.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_dataset import BaseDataset
3
+ from config import DATA_ROOT
4
+
5
+ '''dataset source: https://www.kaggle.com/datasets/felipekitamura/head-ct-hemorrhage'''
6
+ HEADCT_CLS_NAMES = [
7
+ 'headct',
8
+ ]
9
+ HEADCT_ROOT = os.path.join(DATA_ROOT, 'HeadCT_anomaly_detection')
10
+
11
+ class HEADCTDataset(BaseDataset):
12
+ def __init__(self, transform, target_transform, clsnames=HEADCT_CLS_NAMES, aug_rate=0.0, root=HEADCT_ROOT, training=True):
13
+ super(HEADCTDataset, self).__init__(
14
+ clsnames=clsnames, transform=transform, target_transform=target_transform,
15
+ root=root, aug_rate=aug_rate, training=training
16
+ )
17
+
18
+
dataset/isic.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_dataset import BaseDataset
3
+ from config import DATA_ROOT
4
+
5
+ '''dataset source: https://challenge.isic-archive.com/data/'''
6
+ ISIC_CLS_NAMES = [
7
+ 'isic',
8
+ ]
9
+ ISIC_ROOT = os.path.join(DATA_ROOT, 'ISIC')
10
+
11
+ class ISICDataset(BaseDataset):
12
+ def __init__(self, transform, target_transform, clsnames=ISIC_CLS_NAMES, aug_rate=0.0, root=ISIC_ROOT, training=True):
13
+ super(ISICDataset, self).__init__(
14
+ clsnames=clsnames, transform=transform, target_transform=target_transform,
15
+ root=root, aug_rate=aug_rate, training=training
16
+ )
17
+
18
+
dataset/mpdd.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_dataset import BaseDataset
3
+ from config import DATA_ROOT
4
+
5
+ '''dataset source: https://github.com/stepanje/MPDD'''
6
+ MPDD_CLS_NAMES = [
7
+ 'bracket_black', 'bracket_brown', 'bracket_white', 'connector', 'metal_plate','tubes',
8
+ ]
9
+ MPDD_ROOT = os.path.join(DATA_ROOT, 'MPDD')
10
+
11
+ class MPDDDataset(BaseDataset):
12
+ def __init__(self, transform, target_transform, clsnames=MPDD_CLS_NAMES, aug_rate=0.0, root=MPDD_ROOT, training=True):
13
+ super(MPDDDataset, self).__init__(
14
+ clsnames=clsnames, transform=transform, target_transform=target_transform,
15
+ root=root, aug_rate=aug_rate, training=training
16
+ )
17
+
dataset/mvtec.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_dataset import BaseDataset
3
+ from config import DATA_ROOT
4
+
5
+ '''dataset source: https://paperswithcode.com/dataset/mvtecad'''
6
+
7
+ MVTEC_CLS_NAMES = [
8
+ 'bottle', 'cable', 'capsule', 'carpet', 'grid',
9
+ 'hazelnut', 'leather', 'metal_nut', 'pill', 'screw',
10
+ 'tile', 'toothbrush', 'transistor', 'wood', 'zipper',
11
+ ]
12
+ MVTEC_ROOT = os.path.join(DATA_ROOT, 'mvtec_anomaly_detection')
13
+
14
+ class MVTecDataset(BaseDataset):
15
+ def __init__(self, transform, target_transform, clsnames=MVTEC_CLS_NAMES, aug_rate=0.2, root=MVTEC_ROOT, training=True):
16
+ super(MVTecDataset, self).__init__(
17
+ clsnames=clsnames, transform=transform, target_transform=target_transform,
18
+ root=root, aug_rate=aug_rate, training=training
19
+ )
dataset/sdd.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_dataset import BaseDataset
3
+ from config import DATA_ROOT
4
+
5
+ '''dataset source: https://data.vicos.si/datasets/KSDD/KolektorSDD.zip'''
6
+ SDD_CLS_NAMES = [
7
+ 'SDD',
8
+ ]
9
+ SDD_ROOT = os.path.join(DATA_ROOT, 'SDD_anomaly_detection')
10
+
11
+
12
+ class SDDDataset(BaseDataset):
13
+ def __init__(self, transform, target_transform, clsnames=SDD_CLS_NAMES, aug_rate=0.0, root=SDD_ROOT, training=True):
14
+ super(SDDDataset, self).__init__(
15
+ clsnames=clsnames, transform=transform, target_transform=target_transform,
16
+ root=root, aug_rate=aug_rate, training=training
17
+ )
18
+
dataset/tn3k.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_dataset import BaseDataset
3
+ from config import DATA_ROOT
4
+
5
+ '''dataset source: https://ieeexplore.ieee.org/document/9434087/references#references'''
6
+ TN3K_CLS_NAMES = [
7
+ 'tn3k',
8
+ ]
9
+ TN3K_ROOT = os.path.join(DATA_ROOT, 'TN3K')
10
+
11
+ class TN3KDataset(BaseDataset):
12
+ def __init__(self, transform, target_transform, clsnames=TN3K_CLS_NAMES, aug_rate=0.0, root=TN3K_ROOT, training=True):
13
+ super(TN3KDataset, self).__init__(
14
+ clsnames=clsnames, transform=transform, target_transform=target_transform,
15
+ root=root, aug_rate=aug_rate, training=training
16
+ )
17
+
18
+
dataset/visa.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_dataset import BaseDataset
3
+ from config import DATA_ROOT
4
+
5
+ '''dataset source: https://amazon-visual-anomaly.s3.us-west-2.amazonaws.com/VisA_20220922.tar'''
6
+ VISA_CLS_NAMES = [
7
+ 'candle', 'capsules', 'cashew', 'chewinggum', 'fryum',
8
+ 'macaroni1', 'macaroni2', 'pcb1', 'pcb2', 'pcb3',
9
+ 'pcb4', 'pipe_fryum',
10
+ ]
11
+
12
+ VISA_ROOT = os.path.join(DATA_ROOT, 'VisA_20220922')
13
+
14
+ class VisaDataset(BaseDataset):
15
+ def __init__(self, transform, target_transform, clsnames=VISA_CLS_NAMES, aug_rate=0.0, root=VISA_ROOT, training=True):
16
+ super(VisaDataset, self).__init__(
17
+ clsnames=clsnames, transform=transform, target_transform=target_transform,
18
+ root=root, aug_rate=aug_rate, training=training
19
+ )
20
+
datasets/rayan_dataset.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -----------------------------------------------------------------------------
2
+ # Do Not Alter This File!
3
+ # -----------------------------------------------------------------------------
4
+ # The following code is part of the logic used for loading and evaluating your
5
+ # output scores. Please DO NOT modify this section, as upon your submission,
6
+ # the whole evaluation logic will be overwritten by the original code.
7
+ # -----------------------------------------------------------------------------
8
+ # If you'd like to make modifications, you can create a completely new Dataset
9
+ # class or a child class that inherits from this one and use that with your
10
+ # data loader.
11
+ # -----------------------------------------------------------------------------
12
+
13
+ import os
14
+ from enum import Enum
15
+
16
+ import PIL
17
+ import torch
18
+ from torchvision import transforms
19
+
20
+ IMAGENET_MEAN = [0.485, 0.456, 0.406]
21
+ IMAGENET_STD = [0.229, 0.224, 0.225]
22
+
23
+
24
+ class DatasetSplit(Enum):
25
+ TRAIN = "train"
26
+ VAL = "val"
27
+ TEST = "test"
28
+
29
+
30
+ class RayanDataset(torch.utils.data.Dataset):
31
+ def __init__(
32
+ self,
33
+ source,
34
+ classname,
35
+ input_size=518,
36
+ output_size=224,
37
+ split=DatasetSplit.TEST,
38
+ external_transform=None,
39
+ **kwargs,
40
+ ):
41
+ super().__init__()
42
+ self.source = source
43
+ self.split = split
44
+ self.classnames_to_use = [classname]
45
+ self.imgpaths_per_class, self.data_to_iterate = self.get_image_data()
46
+
47
+ if external_transform is None:
48
+ self.transform_img = [
49
+ transforms.Resize((input_size, input_size)),
50
+ transforms.CenterCrop(input_size),
51
+ transforms.ToTensor(),
52
+ transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD),
53
+ ]
54
+ self.transform_img = transforms.Compose(self.transform_img)
55
+ else:
56
+ self.transform_img = external_transform
57
+
58
+ # Output size of the mask has to be of shape: 1×224×224
59
+ self.transform_mask = [
60
+ transforms.Resize((output_size, output_size)),
61
+ transforms.CenterCrop(output_size),
62
+ transforms.ToTensor(),
63
+ ]
64
+ self.transform_mask = transforms.Compose(self.transform_mask)
65
+ self.output_shape = (1, output_size, output_size)
66
+
67
+ def __getitem__(self, idx):
68
+ classname, anomaly, image_path, mask_path = self.data_to_iterate[idx]
69
+ image = PIL.Image.open(image_path).convert("RGB")
70
+ image = self.transform_img(image)
71
+
72
+ if self.split == DatasetSplit.TEST and mask_path is not None:
73
+ mask = PIL.Image.open(mask_path).convert("L")
74
+ mask = self.transform_mask(mask) > 0
75
+ else:
76
+ mask = torch.zeros([*self.output_shape])
77
+
78
+ return {
79
+ "image": image,
80
+ "mask": mask,
81
+ "is_anomaly": int(anomaly != "good"),
82
+ "image_path": image_path,
83
+ }
84
+
85
+ def __len__(self):
86
+ return len(self.data_to_iterate)
87
+
88
+ def get_image_data(self):
89
+ imgpaths_per_class = {}
90
+ maskpaths_per_class = {}
91
+
92
+ for classname in self.classnames_to_use:
93
+ classpath = os.path.join(self.source, classname, self.split.value)
94
+ maskpath = os.path.join(self.source, classname, "ground_truth")
95
+ anomaly_types = os.listdir(classpath)
96
+
97
+ imgpaths_per_class[classname] = {}
98
+ maskpaths_per_class[classname] = {}
99
+
100
+ for anomaly in anomaly_types:
101
+ anomaly_path = os.path.join(classpath, anomaly)
102
+ anomaly_files = sorted(os.listdir(anomaly_path))
103
+ imgpaths_per_class[classname][anomaly] = [
104
+ os.path.join(anomaly_path, x) for x in anomaly_files
105
+ ]
106
+
107
+ if self.split == DatasetSplit.TEST and anomaly != "good":
108
+ anomaly_mask_path = os.path.join(maskpath, anomaly)
109
+ anomaly_mask_files = sorted(os.listdir(anomaly_mask_path))
110
+ maskpaths_per_class[classname][anomaly] = [
111
+ os.path.join(anomaly_mask_path, x) for x in anomaly_mask_files
112
+ ]
113
+ else:
114
+ maskpaths_per_class[classname]["good"] = None
115
+
116
+ data_to_iterate = []
117
+ for classname in sorted(imgpaths_per_class.keys()):
118
+ for anomaly in sorted(imgpaths_per_class[classname].keys()):
119
+ for i, image_path in enumerate(imgpaths_per_class[classname][anomaly]):
120
+ data_tuple = [classname, anomaly, image_path]
121
+ if self.split == DatasetSplit.TEST and anomaly != "good":
122
+ data_tuple.append(maskpaths_per_class[classname][anomaly][i])
123
+ else:
124
+ data_tuple.append(None)
125
+ data_to_iterate.append(data_tuple)
126
+
127
+ return imgpaths_per_class, data_to_iterate
docker-compose.yml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -----------------------------------------------------------------------------
2
+ # A sample Docker Compose file to help you replicate our test environment
3
+ # -----------------------------------------------------------------------------
4
+
5
+ services:
6
+ zsad-service:
7
+ image: zsad-image:1
8
+ build:
9
+ context: .
10
+ container_name: zsad-container
11
+ volumes:
12
+ - ./shared_folder:/app/output
13
+ deploy:
14
+ resources:
15
+ reservations:
16
+ devices:
17
+ - driver: nvidia
18
+ count: all
19
+ capabilities: [gpu]
20
+
21
+ command: [ "python3", "runner.py" ]
evaluation/base_eval.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -----------------------------------------------------------------------------
2
+ # Do Not Alter This File!
3
+ # -----------------------------------------------------------------------------
4
+ # The following code is part of the logic used for loading and evaluating your
5
+ # output scores. Please DO NOT modify this section, as upon your submission,
6
+ # the whole evaluation logic will be overwritten by the original code.
7
+ # -----------------------------------------------------------------------------
8
+
9
+ import warnings
10
+ import os
11
+ from pathlib import Path
12
+ import csv
13
+ import json
14
+ import torch
15
+
16
+ import datasets.rayan_dataset as rayan_dataset
17
+ from evaluation.utils.metrics import compute_metrics
18
+
19
+ warnings.filterwarnings("ignore")
20
+
21
+
22
+ class BaseEval:
23
+ def __init__(self, cfg):
24
+ self.cfg = cfg
25
+ self.device = torch.device(
26
+ "cuda:{}".format(cfg["device"]) if torch.cuda.is_available() else "cpu"
27
+ )
28
+
29
+ self.path = cfg["datasets"]["data_path"]
30
+ self.dataset = cfg["datasets"]["dataset_name"]
31
+ self.save_csv = cfg["testing"]["save_csv"]
32
+ self.save_json = cfg["testing"]["save_json"]
33
+ self.categories = cfg["datasets"]["class_name"]
34
+ if isinstance(self.categories, str):
35
+ if self.categories.lower() == "all":
36
+ if self.dataset == "rayan_dataset":
37
+ self.categories = self.get_available_class_names(self.path)
38
+ else:
39
+ self.categories = [self.categories]
40
+ self.output_dir = cfg["testing"]["output_dir"]
41
+ os.makedirs(self.output_dir, exist_ok=True)
42
+ self.scores_dir = cfg["testing"]["output_scores_dir"]
43
+ self.class_name_mapping_dir = cfg["testing"]["class_name_mapping_dir"]
44
+
45
+ self.leaderboard_metric_weights = {
46
+ "image_auroc": 1.2,
47
+ "image_ap": 1.1,
48
+ "image_f1": 1.1,
49
+ "pixel_auroc": 1.0,
50
+ "pixel_aupro": 1.4,
51
+ "pixel_ap": 1.3,
52
+ "pixel_f1": 1.3,
53
+ }
54
+
55
+ def get_available_class_names(self, root_data_path):
56
+ all_items = os.listdir(root_data_path)
57
+ folder_names = [
58
+ item
59
+ for item in all_items
60
+ if os.path.isdir(os.path.join(root_data_path, item))
61
+ ]
62
+
63
+ return folder_names
64
+
65
+ def load_datasets(self, category):
66
+ dataset_classes = {
67
+ "rayan_dataset": rayan_dataset.RayanDataset,
68
+ }
69
+
70
+ dataset_splits = {
71
+ "rayan_dataset": rayan_dataset.DatasetSplit.TEST,
72
+ }
73
+
74
+ test_dataset = dataset_classes[self.dataset](
75
+ source=self.path,
76
+ split=dataset_splits[self.dataset],
77
+ classname=category,
78
+ )
79
+ return test_dataset
80
+
81
+ def get_category_metrics(self, category):
82
+ print(f"Loading scores of '{category}'")
83
+ gt_sp, pr_sp, gt_px, pr_px, _ = self.load_category_scores(category)
84
+
85
+ print(f"Computing metrics for '{category}'")
86
+ image_metric, pixel_metric = compute_metrics(gt_sp, pr_sp, gt_px, pr_px)
87
+
88
+ return image_metric, pixel_metric
89
+
90
+ def load_category_scores(self, category):
91
+ raise NotImplementedError()
92
+
93
+ def get_scores_path_for_image(self, image_path):
94
+ """example image_path: './data/photovoltaic_module/test/good/037.png'"""
95
+ path = Path(image_path)
96
+
97
+ category, split, anomaly_type = path.parts[-4:-1]
98
+ image_name = path.stem
99
+
100
+ return os.path.join(
101
+ self.scores_dir, category, split, anomaly_type, f"{image_name}_scores.json"
102
+ )
103
+
104
+ def calc_leaderboard_score(self, **metrics):
105
+ weighted_sum = 0
106
+ total_weight = 0
107
+ for key, weight in self.leaderboard_metric_weights.items():
108
+ metric = metrics.get(key)
109
+ weighted_sum += metric * weight
110
+ total_weight += weight
111
+
112
+ if total_weight == 0:
113
+ return 0
114
+
115
+ return weighted_sum / total_weight
116
+
117
+ def main(self):
118
+ image_auroc_list = []
119
+ image_f1_list = []
120
+ image_ap_list = []
121
+ pixel_auroc_list = []
122
+ pixel_f1_list = []
123
+ pixel_ap_list = []
124
+ pixel_aupro_list = []
125
+ leaderboard_score_list = []
126
+ for category in self.categories:
127
+ image_metric, pixel_metric = self.get_category_metrics(
128
+ category=category,
129
+ )
130
+ image_auroc, image_f1, image_ap = image_metric
131
+ pixel_auroc, pixel_f1, pixel_ap, pixel_aupro = pixel_metric
132
+ leaderboard_score = self.calc_leaderboard_score(
133
+ image_auroc=image_auroc,
134
+ image_f1=image_f1,
135
+ image_ap=image_ap,
136
+ pixel_auroc=pixel_auroc,
137
+ pixel_aupro=pixel_aupro,
138
+ pixel_f1=pixel_f1,
139
+ pixel_ap=pixel_ap,
140
+ )
141
+
142
+ image_auroc_list.append(image_auroc)
143
+ image_f1_list.append(image_f1)
144
+ image_ap_list.append(image_ap)
145
+ pixel_auroc_list.append(pixel_auroc)
146
+ pixel_f1_list.append(pixel_f1)
147
+ pixel_ap_list.append(pixel_ap)
148
+ pixel_aupro_list.append(pixel_aupro)
149
+ leaderboard_score_list.append(leaderboard_score)
150
+
151
+ print(category)
152
+ print(
153
+ "[image level] auroc:{}, f1:{}, ap:{}".format(
154
+ image_auroc * 100,
155
+ image_f1 * 100,
156
+ image_ap * 100,
157
+ )
158
+ )
159
+ print(
160
+ "[pixel level] auroc:{}, f1:{}, ap:{}, aupro:{}".format(
161
+ pixel_auroc * 100,
162
+ pixel_f1 * 100,
163
+ pixel_ap * 100,
164
+ pixel_aupro * 100,
165
+ )
166
+ )
167
+ print(
168
+ "leaderboard score:{}".format(
169
+ leaderboard_score * 100,
170
+ )
171
+ )
172
+
173
+ image_auroc_mean = sum(image_auroc_list) / len(image_auroc_list)
174
+ image_f1_mean = sum(image_f1_list) / len(image_f1_list)
175
+ image_ap_mean = sum(image_ap_list) / len(image_ap_list)
176
+ pixel_auroc_mean = sum(pixel_auroc_list) / len(pixel_auroc_list)
177
+ pixel_f1_mean = sum(pixel_f1_list) / len(pixel_f1_list)
178
+ pixel_ap_mean = sum(pixel_ap_list) / len(pixel_ap_list)
179
+ pixel_aupro_mean = sum(pixel_aupro_list) / len(pixel_aupro_list)
180
+ leaderboard_score_mean = sum(leaderboard_score_list) / len(
181
+ leaderboard_score_list
182
+ )
183
+
184
+ print("mean")
185
+ print(
186
+ "[image level] auroc:{}, f1:{}, ap:{}".format(
187
+ image_auroc_mean * 100, image_f1_mean * 100, image_ap_mean * 100
188
+ )
189
+ )
190
+ print(
191
+ "[pixel level] auroc:{}, f1:{}, ap:{}, aupro:{}".format(
192
+ pixel_auroc_mean * 100,
193
+ pixel_f1_mean * 100,
194
+ pixel_ap_mean * 100,
195
+ pixel_aupro_mean * 100,
196
+ )
197
+ )
198
+ print(
199
+ "leaderboard score:{}".format(
200
+ leaderboard_score_mean * 100,
201
+ )
202
+ )
203
+
204
+ # Save the final results as a csv file
205
+ if self.save_csv:
206
+ with open(self.class_name_mapping_dir, "r") as f:
207
+ class_name_mapping_dict = json.load(f)
208
+ csv_data = [
209
+ [
210
+ "Category",
211
+ "pixel_auroc",
212
+ "pixel_f1",
213
+ "pixel_ap",
214
+ "pixel_aupro",
215
+ "image_auroc",
216
+ "image_f1",
217
+ "image_ap",
218
+ "leaderboard_score",
219
+ ]
220
+ ]
221
+ for i, category in enumerate(self.categories):
222
+ csv_data.append(
223
+ [
224
+ class_name_mapping_dict[category],
225
+ pixel_auroc_list[i] * 100,
226
+ pixel_f1_list[i] * 100,
227
+ pixel_ap_list[i] * 100,
228
+ pixel_aupro_list[i] * 100,
229
+ image_auroc_list[i] * 100,
230
+ image_f1_list[i] * 100,
231
+ image_ap_list[i] * 100,
232
+ leaderboard_score_list[i] * 100,
233
+ ]
234
+ )
235
+ csv_data.append(
236
+ [
237
+ "mean",
238
+ pixel_auroc_mean * 100,
239
+ pixel_f1_mean * 100,
240
+ pixel_ap_mean * 100,
241
+ pixel_aupro_mean * 100,
242
+ image_auroc_mean * 100,
243
+ image_f1_mean * 100,
244
+ image_ap_mean * 100,
245
+ leaderboard_score_mean * 100,
246
+ ]
247
+ )
248
+
249
+ csv_file_path = os.path.join(self.output_dir, "results.csv")
250
+ with open(csv_file_path, mode="w", newline="") as file:
251
+ writer = csv.writer(file)
252
+ writer.writerows(csv_data)
253
+
254
+ # Save the final results as a json file
255
+ if self.save_json:
256
+ json_data = []
257
+ with open(self.class_name_mapping_dir, "r") as f:
258
+ class_name_mapping_dict = json.load(f)
259
+ for i, category in enumerate(self.categories):
260
+ json_data.append(
261
+ {
262
+ "Category": class_name_mapping_dict[category],
263
+ "pixel_auroc": pixel_auroc_list[i] * 100,
264
+ "pixel_f1": pixel_f1_list[i] * 100,
265
+ "pixel_ap": pixel_ap_list[i] * 100,
266
+ "pixel_aupro": pixel_aupro_list[i] * 100,
267
+ "image_auroc": image_auroc_list[i] * 100,
268
+ "image_f1": image_f1_list[i] * 100,
269
+ "image_ap": image_ap_list[i] * 100,
270
+ "leaderboard_score": leaderboard_score_list[i] * 100,
271
+ }
272
+ )
273
+ json_data.append(
274
+ {
275
+ "Category": "mean",
276
+ "pixel_auroc": pixel_auroc_mean * 100,
277
+ "pixel_f1": pixel_f1_mean * 100,
278
+ "pixel_ap": pixel_ap_mean * 100,
279
+ "pixel_aupro": pixel_aupro_mean * 100,
280
+ "image_auroc": image_auroc_mean * 100,
281
+ "image_f1": image_f1_mean * 100,
282
+ "image_ap": image_ap_mean * 100,
283
+ "leaderboard_score": leaderboard_score_mean * 100,
284
+ }
285
+ )
286
+
287
+ json_file_path = os.path.join(self.output_dir, "results.json")
288
+ with open(json_file_path, mode="w") as file:
289
+ final_json = {
290
+ "result": leaderboard_score_mean * 100,
291
+ "metadata": json_data,
292
+ }
293
+ json.dump(final_json, file, indent=4)
evaluation/class_name_mapping.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "pill": "industrial_01",
3
+ "photovoltaic_module": "industrial_02",
4
+ "capsules": "industrial_03"
5
+ }
evaluation/eval_main.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -----------------------------------------------------------------------------
2
+ # Do Not Alter This File!
3
+ # -----------------------------------------------------------------------------
4
+ # The following code is part of the logic used for loading and evaluating your
5
+ # output scores. Please DO NOT modify this section, as upon your submission,
6
+ # the whole evaluation logic will be overwritten by the original code.
7
+ # -----------------------------------------------------------------------------
8
+
9
+ import warnings
10
+ import argparse
11
+ import os
12
+ import sys
13
+
14
+ sys.path.append(os.getcwd())
15
+ from evaluation.json_score import JsonScoreEvaluator
16
+
17
+ warnings.filterwarnings("ignore")
18
+
19
+
20
+ def get_args():
21
+ parser = argparse.ArgumentParser(description="Rayan ZSAD Evaluation Code")
22
+ parser.add_argument("--data_path", type=str, default=None, help="dataset path")
23
+ parser.add_argument("--dataset_name", type=str, default=None, help="dataset name")
24
+ parser.add_argument("--class_name", type=str, default=None, help="category")
25
+ parser.add_argument("--device", type=int, default=None, help="gpu id")
26
+ parser.add_argument(
27
+ "--output_dir", type=str, default=None, help="save results path"
28
+ )
29
+ parser.add_argument(
30
+ "--output_scores_dir", type=str, default=None, help="save scores path"
31
+ )
32
+ parser.add_argument("--save_csv", type=str, default=None, help="save csv")
33
+ parser.add_argument("--save_json", type=str, default=None, help="save json")
34
+
35
+ parser.add_argument(
36
+ "--class_name_mapping_dir",
37
+ type=str,
38
+ default=None,
39
+ help="mapping from actual class names to class numbers",
40
+ )
41
+ args = parser.parse_args()
42
+ return args
43
+
44
+
45
+ def load_args(cfg, args):
46
+ cfg["datasets"]["data_path"] = args.data_path
47
+ assert os.path.exists(
48
+ cfg["datasets"]["data_path"]
49
+ ), f"The dataset path {cfg['datasets']['data_path']} does not exist."
50
+ cfg["datasets"]["dataset_name"] = args.dataset_name
51
+ cfg["datasets"]["class_name"] = args.class_name
52
+ cfg["device"] = args.device
53
+ if isinstance(cfg["device"], int):
54
+ cfg["device"] = str(cfg["device"])
55
+ cfg["testing"]["output_dir"] = args.output_dir
56
+ cfg["testing"]["output_scores_dir"] = args.output_scores_dir
57
+ os.makedirs(cfg["testing"]["output_scores_dir"], exist_ok=True)
58
+
59
+ cfg["testing"]["class_name_mapping_dir"] = args.class_name_mapping_dir
60
+ if args.save_csv.lower() == "true":
61
+ cfg["testing"]["save_csv"] = True
62
+ else:
63
+ cfg["testing"]["save_csv"] = False
64
+
65
+ if args.save_json.lower() == "true":
66
+ cfg["testing"]["save_json"] = True
67
+ else:
68
+ cfg["testing"]["save_json"] = False
69
+
70
+ return cfg
71
+
72
+
73
+ if __name__ == "__main__":
74
+ args = get_args()
75
+ cfg = load_args(cfg={"datasets": {}, "testing": {}, "models": {}}, args=args)
76
+ print(cfg)
77
+ model = JsonScoreEvaluator(cfg=cfg)
78
+ model.main()
evaluation/json_score.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -----------------------------------------------------------------------------
2
+ # Do Not Alter This File!
3
+ # -----------------------------------------------------------------------------
4
+ # The following code is part of the logic used for loading and evaluating your
5
+ # output scores. Please DO NOT modify this section, as upon your submission,
6
+ # the whole evaluation logic will be overwritten by the original code.
7
+ # -----------------------------------------------------------------------------
8
+
9
+ import warnings
10
+ import numpy as np
11
+ import torch
12
+ from tqdm import tqdm
13
+
14
+ from evaluation.base_eval import BaseEval
15
+ from evaluation.utils.json_helpers import json_to_dict
16
+
17
+ warnings.filterwarnings("ignore")
18
+
19
+
20
+ class JsonScoreEvaluator(BaseEval):
21
+ """
22
+ Evaluates anomaly detection performance based on pre-computed scores stored in JSON files.
23
+
24
+ This class extends the BaseEval class and specializes in reading scores from JSON files,
25
+ computing evaluation metrics, and optionally saving results to CSV or JSON format.
26
+
27
+ Notes:
28
+ - Score files are expected to follow the exact dataset structure.
29
+ `{category}/{split}/{anomaly_type}/{image_name}_scores.json`
30
+ e.g., `photovoltaic_module/test/good/037_scores.json`
31
+ - Score files are expected to be at `self.scores_dir`.
32
+
33
+ Example usage:
34
+ >>> evaluator = JsonScoreEvaluator(cfg)
35
+ >>> results = evaluator.main()
36
+ """
37
+
38
+ def __init__(self, cfg):
39
+ super().__init__(cfg)
40
+
41
+ def get_scores_for_image(self, image_path):
42
+ image_scores_path = self.get_scores_path_for_image(image_path)
43
+ image_scores = json_to_dict(image_scores_path)
44
+
45
+ return image_scores
46
+
47
+ def load_category_scores(self, category):
48
+ cls_scores_list = [] # image level prediction
49
+ anomaly_maps = [] # pixel level prediction
50
+ gt_list = [] # image level ground truth
51
+ img_masks = [] # pixel level ground truth
52
+
53
+ image_path_list = []
54
+ test_dataset = self.load_datasets(category)
55
+ test_dataloader = torch.utils.data.DataLoader(
56
+ test_dataset,
57
+ batch_size=1,
58
+ shuffle=False,
59
+ num_workers=0,
60
+ pin_memory=True,
61
+ )
62
+
63
+ for image_info in tqdm(test_dataloader):
64
+ if not isinstance(image_info, dict):
65
+ raise ValueError("Encountered non-dict image in dataloader")
66
+
67
+ del image_info["image"]
68
+
69
+ image_path = image_info["image_path"][0]
70
+ image_path_list.extend(image_path)
71
+
72
+ img_masks.append(image_info["mask"])
73
+ gt_list.extend(list(image_info["is_anomaly"].numpy()))
74
+
75
+ image_scores = self.get_scores_for_image(image_path)
76
+ cls_scores = image_scores["img_level_score"]
77
+ anomaly_maps_iter = image_scores["pix_level_score"]
78
+
79
+ cls_scores_list.append(cls_scores)
80
+ anomaly_maps.append(anomaly_maps_iter)
81
+
82
+ pr_sp = np.array(cls_scores_list)
83
+ gt_sp = np.array(gt_list)
84
+ pr_px = np.array(anomaly_maps)
85
+ gt_px = torch.cat(img_masks, dim=0).numpy().astype(np.int32)
86
+
87
+ assert pr_px.shape[1:] == (
88
+ 1,
89
+ 224,
90
+ 224,
91
+ ), "Predicted output scores do not meet the expected shape!"
92
+ assert gt_px.shape[1:] == (
93
+ 1,
94
+ 224,
95
+ 224,
96
+ ), "Loaded ground truth maps do not meet the expected shape!"
97
+
98
+ return gt_sp, pr_sp, gt_px, pr_px, image_path_list
evaluation/utils/json_helpers.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -----------------------------------------------------------------------------
2
+ # Do Not Alter This File!
3
+ # -----------------------------------------------------------------------------
4
+ # The following code is part of the logic used for loading and evaluating your
5
+ # output scores. Please DO NOT modify this section, as upon your submission,
6
+ # the whole evaluation logic will be overwritten by the original code.
7
+ # -----------------------------------------------------------------------------
8
+
9
+ import json
10
+ import numpy as np
11
+
12
+
13
+ class NumpyEncoder(json.JSONEncoder):
14
+ """Special json encoder for numpy types"""
15
+
16
+ def default(self, obj):
17
+ if isinstance(obj, np.integer):
18
+ return int(obj)
19
+ elif isinstance(obj, np.floating):
20
+ return float(obj)
21
+ elif isinstance(obj, np.ndarray):
22
+ return {
23
+ "__ndarray__": obj.tolist(),
24
+ "dtype": str(obj.dtype),
25
+ "shape": obj.shape,
26
+ }
27
+ else:
28
+ return super(NumpyEncoder, self).default(obj)
29
+
30
+
31
+ def dict_to_json(dct, filename):
32
+ """Save a dictionary to a JSON file"""
33
+ with open(filename, "w") as f:
34
+ json.dump(dct, f, cls=NumpyEncoder)
35
+
36
+
37
+ def json_to_dict(filename):
38
+ """Load a JSON file and convert it back to a dictionary of NumPy arrays"""
39
+ with open(filename, "r") as f:
40
+ dct = json.load(f)
41
+
42
+ for k, v in dct.items():
43
+ if isinstance(v, dict) and "__ndarray__" in v:
44
+ dct[k] = np.array(v["__ndarray__"], dtype=v["dtype"]).reshape(v["shape"])
45
+
46
+ return dct
evaluation/utils/metrics.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -----------------------------------------------------------------------------
2
+ # Do Not Alter This File!
3
+ # -----------------------------------------------------------------------------
4
+ # The following code is part of the logic used for loading and evaluating your
5
+ # output scores. Please DO NOT modify this section, as upon your submission,
6
+ # the whole evaluation logic will be overwritten by the original code.
7
+ # -----------------------------------------------------------------------------
8
+
9
+ import numpy as np
10
+ from sklearn.metrics import (
11
+ auc,
12
+ roc_auc_score,
13
+ average_precision_score,
14
+ precision_recall_curve,
15
+ )
16
+ from skimage import measure
17
+
18
+
19
+ # ref: https://github.com/gudovskiy/cflow-ad/blob/master/train.py
20
+ def cal_pro_score(masks, amaps, max_step=200, expect_fpr=0.3):
21
+ binary_amaps = np.zeros_like(amaps, dtype=bool)
22
+ min_th, max_th = amaps.min(), amaps.max()
23
+ delta = (max_th - min_th) / max_step
24
+ pros, fprs, ths = [], [], []
25
+ for th in np.arange(min_th, max_th, delta):
26
+ binary_amaps[amaps <= th], binary_amaps[amaps > th] = 0, 1
27
+ pro = []
28
+ for binary_amap, mask in zip(binary_amaps, masks):
29
+ for region in measure.regionprops(measure.label(mask)):
30
+ tp_pixels = binary_amap[region.coords[:, 0], region.coords[:, 1]].sum()
31
+ pro.append(tp_pixels / region.area)
32
+ inverse_masks = 1 - masks
33
+ fp_pixels = np.logical_and(inverse_masks, binary_amaps).sum()
34
+ fpr = fp_pixels / inverse_masks.sum()
35
+ pros.append(np.array(pro).mean())
36
+ fprs.append(fpr)
37
+ ths.append(th)
38
+ pros, fprs, ths = np.array(pros), np.array(fprs), np.array(ths)
39
+ idxes = fprs < expect_fpr
40
+ fprs = fprs[idxes]
41
+ fprs = (fprs - fprs.min()) / (fprs.max() - fprs.min())
42
+ pro_auc = auc(fprs, pros[idxes])
43
+ return pro_auc
44
+
45
+
46
+ def compute_metrics(gt_sp=None, pr_sp=None, gt_px=None, pr_px=None):
47
+ # classification
48
+ if (
49
+ gt_sp is None
50
+ or pr_sp is None
51
+ or gt_sp.sum() == 0
52
+ or gt_sp.sum() == gt_sp.shape[0]
53
+ ):
54
+ auroc_sp, f1_sp, ap_sp = 0, 0, 0
55
+ else:
56
+ auroc_sp = roc_auc_score(gt_sp, pr_sp)
57
+ ap_sp = average_precision_score(gt_sp, pr_sp)
58
+ precisions, recalls, thresholds = precision_recall_curve(gt_sp, pr_sp)
59
+ f1_scores = (2 * precisions * recalls) / (precisions + recalls)
60
+ f1_sp = np.max(f1_scores[np.isfinite(f1_scores)])
61
+
62
+ # segmentation
63
+ if gt_px is None or pr_px is None or gt_px.sum() == 0:
64
+ auroc_px, f1_px, ap_px, aupro = 0, 0, 0, 0
65
+ else:
66
+ auroc_px = roc_auc_score(gt_px.ravel(), pr_px.ravel())
67
+ ap_px = average_precision_score(gt_px.ravel(), pr_px.ravel())
68
+ precisions, recalls, thresholds = precision_recall_curve(
69
+ gt_px.ravel(), pr_px.ravel()
70
+ )
71
+ f1_scores = (2 * precisions * recalls) / (precisions + recalls)
72
+ f1_px = np.max(f1_scores[np.isfinite(f1_scores)])
73
+ aupro = cal_pro_score(gt_px.squeeze(), pr_px.squeeze())
74
+
75
+ image_metric = [auroc_sp, f1_sp, ap_sp]
76
+ pixel_metric = [auroc_px, f1_px, ap_px, aupro]
77
+
78
+ return image_metric, pixel_metric
install.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # add dependencies
2
+ # python395_cuda113_pytorch1101
3
+ # please change dataset root in ./config.py according to your specifications
4
+
5
+ conda create -n AdaCLIP python=3.9.5 -y
6
+ conda activate AdaCLIP
7
+ pip install torch==1.10.1+cu111 torchvision==0.11.2+cu111 torchaudio==0.10.1 -f https://download.pytorch.org/whl/cu111/torch_stable.html
8
+ pip install tqdm tensorboard setuptools==58.0.4 opencv-python scikit-image scikit-learn matplotlib seaborn ftfy regex numpy==1.26.4
9
+ pip install gradio
10
+
11
+
12
+
13
+
14
+
15
+
loss.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from math import exp
6
+
7
+ class FocalLoss(nn.Module):
8
+ """
9
+ copy from: https://github.com/Hsuxu/Loss_ToolBox-PyTorch/blob/master/FocalLoss/FocalLoss.py
10
+ This is a implementation of Focal Loss with smooth label cross entropy supported which is proposed in
11
+ 'Focal Loss for Dense Object Detection. (https://arxiv.org/abs/1708.02002)'
12
+ Focal_Loss= -1*alpha*(1-pt)*log(pt)
13
+ :param alpha: (tensor) 3D or 4D the scalar factor for this criterion
14
+ :param gamma: (float,double) gamma > 0 reduces the relative loss for well-classified examples (p>0.5) putting more
15
+ focus on hard misclassified example
16
+ :param smooth: (float,double) smooth value when cross entropy
17
+ :param balance_index: (int) balance class index, should be specific when alpha is float
18
+ :param size_average: (bool, optional) By default, the losses are averaged over each loss element in the batch.
19
+ """
20
+
21
+ def __init__(self, apply_nonlin=None, alpha=None, gamma=2, balance_index=0, smooth=1e-5, size_average=True):
22
+ super(FocalLoss, self).__init__()
23
+ self.apply_nonlin = apply_nonlin
24
+ self.alpha = alpha
25
+ self.gamma = gamma
26
+ self.balance_index = balance_index
27
+ self.smooth = smooth
28
+ self.size_average = size_average
29
+
30
+ if self.smooth is not None:
31
+ if self.smooth < 0 or self.smooth > 1.0:
32
+ raise ValueError('smooth value should be in [0,1]')
33
+
34
+ def forward(self, logit, target):
35
+ if self.apply_nonlin is not None:
36
+ logit = self.apply_nonlin(logit)
37
+ num_class = logit.shape[1]
38
+
39
+ if logit.dim() > 2:
40
+ # N,C,d1,d2 -> N,C,m (m=d1*d2*...)
41
+ logit = logit.view(logit.size(0), logit.size(1), -1)
42
+ logit = logit.permute(0, 2, 1).contiguous()
43
+ logit = logit.view(-1, logit.size(-1))
44
+ target = torch.squeeze(target, 1)
45
+ target = target.view(-1, 1)
46
+ alpha = self.alpha
47
+
48
+ if alpha is None:
49
+ alpha = torch.ones(num_class, 1)
50
+ elif isinstance(alpha, (list, np.ndarray)):
51
+ assert len(alpha) == num_class
52
+ alpha = torch.FloatTensor(alpha).view(num_class, 1)
53
+ alpha = alpha / alpha.sum()
54
+ elif isinstance(alpha, float):
55
+ alpha = torch.ones(num_class, 1)
56
+ alpha = alpha * (1 - self.alpha)
57
+ alpha[self.balance_index] = self.alpha
58
+
59
+ else:
60
+ raise TypeError('Not support alpha type')
61
+
62
+ if alpha.device != logit.device:
63
+ alpha = alpha.to(logit.device)
64
+
65
+ idx = target.cpu().long()
66
+
67
+ one_hot_key = torch.FloatTensor(target.size(0), num_class).zero_()
68
+ one_hot_key = one_hot_key.scatter_(1, idx, 1)
69
+ if one_hot_key.device != logit.device:
70
+ one_hot_key = one_hot_key.to(logit.device)
71
+
72
+ if self.smooth:
73
+ one_hot_key = torch.clamp(
74
+ one_hot_key, self.smooth / (num_class - 1), 1.0 - self.smooth)
75
+ pt = (one_hot_key * logit).sum(1) + self.smooth
76
+ logpt = pt.log()
77
+
78
+ gamma = self.gamma
79
+
80
+ alpha = alpha[idx]
81
+ alpha = torch.squeeze(alpha)
82
+ loss = -1 * alpha * torch.pow((1 - pt), gamma) * logpt
83
+
84
+ if self.size_average:
85
+ loss = loss.mean()
86
+ return loss
87
+
88
+
89
+ class BinaryDiceLoss(nn.Module):
90
+ def __init__(self):
91
+ super(BinaryDiceLoss, self).__init__()
92
+
93
+ def forward(self, input, targets):
94
+ # 获取每个批次的大小 N
95
+ N = targets.size()[0]
96
+ # 平滑变量
97
+ smooth = 1
98
+ # 将宽高 reshape 到同一纬度
99
+ input_flat = input.view(N, -1)
100
+ targets_flat = targets.view(N, -1)
101
+
102
+ # 计算交集
103
+ intersection = input_flat * targets_flat
104
+ N_dice_eff = (2 * intersection.sum(1) + smooth) / (input_flat.sum(1) + targets_flat.sum(1) + smooth)
105
+ # 计算一个批次中平均每张图的损失
106
+ loss = 1 - N_dice_eff.sum() / N
107
+ return loss
108
+
109
+
110
+
111
+
112
+ class ConADLoss(nn.Module):
113
+ """Supervised Contrastive Learning: https://arxiv.org/pdf/2004.11362.pdf.
114
+ It also supports the unsupervised contrastive loss in SimCLR"""
115
+ def __init__(self, contrast_mode='all',random_anchors=10):
116
+ super(ConADLoss, self).__init__()
117
+ assert contrast_mode in ['all', 'mean', 'random']
118
+ self.contrast_mode = contrast_mode
119
+ self.random_anchors = random_anchors
120
+ def forward(self, features, labels):
121
+ """Compute loss for model. If both `labels` and `mask` are None,
122
+ it degenerates to SimCLR unsupervised loss:
123
+ https://arxiv.org/pdf/2002.05709.pdf
124
+
125
+ Args:
126
+ features: hidden vector of shape [bsz, C, ...].
127
+ labels: ground truth of shape [bsz, 1, ...]., where 1 denotes to abnormal, and 0 denotes to normal
128
+ Returns:
129
+ A loss scalar.
130
+ """
131
+ device = (torch.device('cuda')
132
+ if features.is_cuda
133
+ else torch.device('cpu'))
134
+ if len(features.shape) != len(labels.shape):
135
+ raise ValueError('`features` needs to have the same dimensions with labels')
136
+
137
+ if len(features.shape) < 3:
138
+ raise ValueError('`features` needs to be [bsz, C, ...],'
139
+ 'at least 3 dimensions are required')
140
+
141
+ if len(features.shape) > 3:
142
+ features = features.view(features.shape[0], features.shape[1], -1)
143
+ labels = labels.view(labels.shape[0], labels.shape[1], -1)
144
+
145
+ labels = labels.squeeze()
146
+ batch_size = features.shape[0]
147
+
148
+ C = features.shape[1]
149
+ normal_feats = features[:, :, labels == 0]
150
+ abnormal_feats = features[:, :, labels == 1]
151
+
152
+ normal_feats = normal_feats.permute((1, 0, 2)).contiguous().view(C, -1)
153
+ abnormal_feats = abnormal_feats.permute((1, 0, 2)).contiguous().view(C, -1)
154
+
155
+ contrast_count = normal_feats.shape[1]
156
+ contrast_feature = normal_feats
157
+
158
+ if self.contrast_mode == 'mean':
159
+ anchor_feature = torch.mean(normal_feats, dim=1)
160
+ anchor_feature = F.normalize(anchor_feature, dim=0, p=2)
161
+ anchor_count = 1
162
+ elif self.contrast_mode == 'all':
163
+ anchor_feature = contrast_feature
164
+ anchor_count = contrast_count
165
+ elif self.contrast_mode == 'random':
166
+ dim_to_sample = 1
167
+ num_samples = min(self.random_anchors, contrast_count)
168
+ permuted_indices = torch.randperm(normal_feats.size(dim_to_sample)).to(normal_feats.device)
169
+ selected_indices = permuted_indices[:num_samples]
170
+ anchor_feature = normal_feats.index_select(dim_to_sample, selected_indices)
171
+ else:
172
+ raise ValueError('Unknown mode: {}'.format(self.contrast_mode))
173
+
174
+ # compute logits
175
+ # maximize similarity
176
+ anchor_dot_normal = torch.matmul(anchor_feature.T, normal_feats).mean()
177
+
178
+ # minimize similarity
179
+ anchor_dot_abnormal = torch.matmul(anchor_feature.T, abnormal_feats).mean()
180
+
181
+ loss = 0
182
+ if normal_feats.shape[1] > 0:
183
+ loss -= anchor_dot_normal
184
+ if abnormal_feats.shape[1] > 0:
185
+ loss += anchor_dot_abnormal
186
+
187
+ loss = torch.exp(loss)
188
+
189
+ return loss