-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataLoader.py
191 lines (160 loc) · 6.83 KB
/
dataLoader.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
181
182
183
184
185
186
187
188
189
190
191
# encoding:utf-8
import os, sys, numpy as np, random, time, cv2
import torch
import jpeg4py as jpeg
from PIL import Image
import torch.utils.data as data
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import imgaug as ia
from imgaug import augmenters as iaa
from glob import glob
ia.seed(random.randint(1, 10000))
class ClassifyDataset(data.Dataset):
def __init__(self, base_data_path, train, transform, id_name_path, device, little_train=False, read_mode='jpeg4py', input_size=224, C=2048, test_mode=False):
print('data init')
self.train = train
self.base_data_path=base_data_path
self.transform=transform
self.fnames = []
self.resize = input_size
self.little_train = little_train
self.id_name_path = id_name_path
self.C = C
self.read_mode = read_mode
self.device = device
self._test = test_mode
self.fnames = self.get_data_list(base_data_path)
self.num_samples = len(self.fnames)
self.img_augsometimes = lambda aug: iaa.Sometimes(0.5, aug)
self.augmentation = iaa.Sequential(
[
# augment without change bboxes
self.img_augsometimes(
iaa.SomeOf((1, 4), [
iaa.Dropout([0.05, 0.2]), # drop 5% or 20% of all pixels
iaa.Sharpen((0.1, .8)), # sharpen the image
# iaa.GaussianBlur(sigma=(2., 3.5)),
iaa.OneOf([
iaa.GaussianBlur(sigma=(2., 3.5)),
iaa.AverageBlur(k=(2, 5)),
iaa.BilateralBlur(d=(7, 12), sigma_color=(10, 250), sigma_space=(10, 250)),
iaa.MedianBlur(k=(3, 7)),
]),
iaa.AddElementwise((-50, 50)),
iaa.AdditiveGaussianNoise(scale=(0, 0.1 * 255)),
iaa.JpegCompression(compression=(80, 95)),
iaa.Multiply((0.5, 1.5)),
iaa.MultiplyElementwise((0.5, 1.5)),
iaa.ReplaceElementwise(0.05, [0, 255]),
# iaa.WithColorspace(to_colorspace="HSV", from_colorspace="RGB",
# children=iaa.WithChannels(2, iaa.Add((-10, 50)))),
iaa.OneOf([
iaa.WithColorspace(to_colorspace="HSV", from_colorspace="RGB",
children=iaa.WithChannels(1, iaa.Add((-10, 50)))),
iaa.WithColorspace(to_colorspace="HSV", from_colorspace="RGB",
children=iaa.WithChannels(2, iaa.Add((-10, 50)))),
]),
iaa.Affine(
scale={"x": (0.8, 1.2), "y": (0.8, 1.2)},
translate_percent={"x": (-0.2, 0.2), "y": (-0.2, 0.2)},
rotate=(-25, 25),
shear=(-8, 8)
)
], random_order=True)
),
iaa.Fliplr(.5),
iaa.Flipud(.25),
],
random_order=True
)
self.get_id_map()
def get_id_list(self):
id_set = set()
if isinstance(self.base_data_path, list):
for i in self.base_data_path:
id_tl = os.listdir(i)
for j in id_tl:
id_set.add(j)
else:
id_tl = os.listdir(self.base_data_path)
for j in id_tl:
id_set.add(j)
return list(id_set)
def get_id_map(self):
self.id_name_map = {}
self.name_id_map = {}
if not os.path.exists(self.id_name_path):
id_list = self.get_id_list()
with open(self.id_name_path, 'w') as f:
for it, cls_name in enumerate(id_list):
self.name_id_map[cls_name] = it
self.id_name_map[it] = cls_name
f.write(cls_name+'\n')
else:
with open(self.id_name_path, 'r') as f:
itt = 0
for line in f:
self.name_id_map[line.strip()] = itt
self.id_name_map[itt] = line.strip()
itt += 1
def get_data_list(self, base_data_path):
cls_file_list = []
if isinstance(base_data_path, list):
for i in base_data_path:
cls_file_list = cls_file_list + glob(i + '/*/*.jpg')
else:
cls_file_list = glob(base_data_path + '/*/*.jpg')
if self.little_train:
return cls_file_list[:self.little_train]
return cls_file_list
def get_label_from_path(self, in_path):
t_str = in_path.split('/')[-2]
return self.name_id_map[t_str]
def get_img_from_path(self, in_path):
try:
if self.read_mode == 'cv2':
img = cv2.imread(in_path)
elif self.read_mode == 'jpeg4py':
img = jpeg.JPEG(in_path).decode()
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
except Exception as e:
print(in_path + ' img error!!!')
return img
def __getitem__(self,idx):
fname = self.fnames[idx]
if self._test:
print(fname)
img1 = self.get_img_from_path(fname)
assert img1 is not None, print(fname)
label1 = self.get_label_from_path(fname)
if self.train:
# add data augument
seq_det = self.augmentation.to_deterministic()
img1 = seq_det.augment_images([img1])[0]
img1 = self.transform(img1)
should_get_same_class = random.randint(0,1)
# print(should_get_same_class)
if should_get_same_class:
while True:
fname = self.fnames[random.randint(0, self.num_samples-1)]
label2 = self.get_label_from_path(fname)
if label1==label2:
break
else:
while True:
fname = self.fnames[random.randint(0, self.num_samples-1)]
label2 = self.get_label_from_path(fname)
if label1!=label2:
break
img2 = self.get_img_from_path(fname)
assert img2 is not None, print(fname)
if self.train:
# add data augument
seq_det = self.augmentation.to_deterministic()
img2 = seq_det.augment_images([img2])[0]
img2 = self.transform(img2)
label2 = self.get_label_from_path(fname)
return img1, img2, label1, label2, torch.from_numpy(np.array([int(label1 != label2)],dtype=np.float32))
def __len__(self):
return self.num_samples