-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_loader.py
183 lines (137 loc) · 6.06 KB
/
data_loader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import numpy as np
from torch.utils.data import Dataset
import torch
import glob
import torch
import random
from datasets import load_dataset as hf_load_dataset
from torchvision import transforms
import os
from PIL import Image
from models.segmentation.dataloader import get_padding_functions
def syn_shuffle(lst0,lst1,lst2,lst3):
lst = list(zip(lst0,lst1,lst2,lst3))
random.shuffle(lst)
lst0,lst1,lst2,lst3 = zip(*lst)
return lst0,lst1,lst2,lst3
def InfiniteDataloader(loader):
iterator = iter(loader)
while True:
try:
yield next(iterator)
except StopIteration:
iterator = iter(loader)
class MVTecLOCODataset(Dataset):
def __init__(self, root, image_size, phase,category,use_pad=True,to_gpu=True,config=None):
self.phase=phase
self.category = category
self.image_size = image_size
self.use_pad = use_pad
self.build_transform()
if phase=='train':
print(f"Loading MVTec LOCO {self.category} (train)")
self.img_path = os.path.join(root,category, 'train')
elif phase=='eval':
print(f"Loading MVTec LOCO {self.category} (validation)")
self.img_path = os.path.join(root,category, 'validation')
else:
print(f"Loading MVTec LOCO {self.category} (test)")
self.img_path = os.path.join(root,category, 'test')
self.gt_path = os.path.join(root,category, 'ground_truth')
assert os.path.isdir(os.path.join(root,category)), 'Error MVTecLOCODataset category:{}'.format(category)
self.img_paths, self.gt_paths, self.labels, self.types = self.load_paths() # self.labels => good : 0, anomaly : 1
# load dataset
self.load_images(to_gpu=to_gpu)
def build_transform(self):
self.norm_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
self.resize_norm_transform = transforms.Compose([
transforms.Resize((self.image_size,self.image_size),interpolation=Image.BILINEAR),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
self.aug_tranform = transforms.RandomChoice([
transforms.ColorJitter(brightness=0.2),
transforms.ColorJitter(contrast=0.2),
transforms.ColorJitter(saturation=0.2),
])
self.transform_gt = transforms.Compose([
transforms.ToTensor(),
])
def load_paths(self):
img_tot_paths = []
gt_tot_paths = []
tot_labels = []
tot_types = []
defect_types = os.listdir(self.img_path)
for defect_type in defect_types:
if defect_type == 'good':
img_paths = glob.glob(os.path.join(self.img_path, defect_type) + "/*.png")
img_tot_paths.extend(img_paths)
gt_tot_paths.extend([0]*len(img_paths))
tot_labels.extend([0]*len(img_paths))
tot_types.extend(['good']*len(img_paths))
else:
img_paths = glob.glob(os.path.join(self.img_path, defect_type) + "/*.png")
gt_paths = glob.glob(os.path.join(self.gt_path, defect_type) + "/*")
gt_paths = [g for g in gt_paths if os.path.isdir(g)]
img_paths.sort()
gt_paths.sort()
img_tot_paths.extend(img_paths)
if len(gt_paths)==0:
gt_paths = [0]*len(img_paths)
gt_tot_paths.extend(gt_paths)
tot_labels.extend([1]*len(img_paths))
tot_types.extend([defect_type]*len(img_paths))
assert len(img_tot_paths) == len(gt_tot_paths), "Something wrong with test and ground truth pair!"
return img_tot_paths, gt_tot_paths, tot_labels, tot_types
def __len__(self):
return len(self.img_paths)
def load_images(self,to_gpu=True):
self.pad_func, self.pad2resize = get_padding_functions(
Image.open(self.img_paths[0]).size,
target_size=self.image_size,
mode='bilinear')
self.samples = list()
self.images = list()
for i in range(len(self.img_paths)):
img_path, gt, label, img_type = self.img_paths[i], self.gt_paths[i], self.labels[i], self.types[i]
img = Image.open(img_path).convert('RGB')
self.images.append(img.copy())
resize_img = self.resize_norm_transform(img)
pad_img = self.norm_transform(self.pad_func(img))
if to_gpu:
resize_img = resize_img.cuda()
pad_img = pad_img.cuda()
self.samples.append({
'image': resize_img,
'pad_image': pad_img,
'label': label,
'name': os.path.basename(img_path[:-4]),
'type': img_type,
'path': img_path,
})
def __getitem__(self, idx):
if self.phase == 'train':
# augmentation
aug_image = self.aug_tranform(self.images[idx])
self.samples[idx]['aug_image'] = self.resize_norm_transform(aug_image).cuda()
self.samples[idx]['idx'] = torch.tensor([idx])
return self.samples[idx]
class ImageNetDataset(Dataset):
def __init__(self,transform=None,):
super().__init__()
print("Loading ImageNet")
self.dataset = hf_load_dataset('Maysee/tiny-imagenet', split='train')
# self.dataset = self.dataset['train']
# to tensor and apply transform
self.transform = transform if transform is not None else transforms.ToTensor()
def __len__(self):
return len(self.dataset)
def __getitem__(self, idx):
image = self.dataset[idx]["image"].convert("RGB")
image = self.transform(image).cuda()
# print(image.shape)
return image