-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataset_gender.py
445 lines (351 loc) · 14 KB
/
dataset_gender.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
import os
import random
from collections import defaultdict
from enum import Enum
from typing import Tuple, List
import numpy as np
import torch
from PIL import Image
from torch.utils.data import Dataset, Subset, random_split
from torchvision.transforms import (
Resize, ToTensor, Normalize, Compose, CenterCrop, ColorJitter, RandomHorizontalFlip, Grayscale, GaussianBlur)
IMG_EXTENSIONS = [
".jpg", ".JPG", ".jpeg", ".JPEG", ".png",
".PNG", ".ppm", ".PPM", ".bmp", ".BMP",
]
def is_image_file(filename):
return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
class BaseAugmentation:
def __init__(self, resize, mean, std, **args):
self.transform = Compose([
Resize(resize, Image.BILINEAR),
ToTensor(),
Normalize(mean=mean, std=std),
])
def __call__(self, image):
return self.transform(image)
class AddGaussianNoise(object):
"""
transform 에 없는 기능들은 이런식으로 __init__, __call__, __repr__ 부분을
직접 구현하여 사용할 수 있습니다.
"""
def __init__(self, mean=0., std=1.):
self.std = std
self.mean = mean
def __call__(self, tensor):
return tensor + torch.randn(tensor.size()) * self.std + self.mean
def __repr__(self):
return self.__class__.__name__ + '(mean={0}, std={1})'.format(self.mean, self.std)
class CustomAugmentation:
def __init__(self, resize, mean, std, **args):
self.transform = Compose([
CenterCrop((320, 256)),
Resize(resize, Image.BILINEAR),
ColorJitter(0.1, 0.1, 0.1, 0.1),
ToTensor(),
Normalize(mean=mean, std=std),
AddGaussianNoise()
])
def __call__(self, image):
return self.transform(image)
class MaskLabels(int, Enum):
MASK = 0
INCORRECT = 1
NORMAL = 2
class GenderLabels(int, Enum):
MALE = 0
FEMALE = 1
@classmethod
def from_str(cls, value: str) -> int:
value = value.lower()
if value == "male":
return cls.MALE
elif value == "female":
return cls.FEMALE
else:
raise ValueError(f"Gender value should be either 'male' or 'female', {value}")
class MaskBaseDataset(Dataset):
num_classes = 2
_file_names = {
"mask1": MaskLabels.MASK,
"mask2": MaskLabels.MASK,
"mask3": MaskLabels.MASK,
"mask4": MaskLabels.MASK,
"mask5": MaskLabels.MASK,
"incorrect_mask": MaskLabels.INCORRECT,
"normal": MaskLabels.NORMAL
}
image_paths = []
mask_labels = []
gender_labels = []
bandana_image_paths = []
bandana_gender_labels = []
def __init__(self, data_dir, mean=(0.548, 0.504, 0.479), std=(0.237, 0.247, 0.246), val_ratio=0.2):
self.data_dir = data_dir
self.mean = mean
self.std = std
self.val_ratio = val_ratio
self.transform = None
self.setup()
self.calc_statistics()
def setup(self):
profiles = os.listdir(self.data_dir)
for profile in profiles:
if profile.startswith("."): # "." 로 시작하는 파일은 무시합니다
continue
img_folder = os.path.join(self.data_dir, profile)
folder_num = int(profile[2:6])
for file_name in os.listdir(img_folder):
_file_name, ext = os.path.splitext(file_name)
if _file_name not in self._file_names: # "." 로 시작하는 파일 및 invalid 한 파일들은 무시합니다
continue
img_path = os.path.join(self.data_dir, profile, file_name) # (resized_data, 000004_male_Asian_54, mask1.jpg)
mask_label = self._file_names[_file_name]
id, gender, race, age = profile.split("_")
gender_label = GenderLabels.from_str(gender)
self.image_paths.append(img_path)
self.gender_labels.append(gender_label)
if folder_num>=5400 and folder_num<5600 and _file_name=='mask5':
self.bandana_image_paths.append(img_path)
self.bandana_gender_labels.append(gender_label)
def calc_statistics(self):
has_statistics = self.mean is not None and self.std is not None
if not has_statistics:
print("[Warning] Calculating statistics... It can take a long time depending on your CPU machine")
sums = []
squared = []
for image_path in self.image_paths[:3000]:
image = np.array(Image.open(image_path)).astype(np.int32)
sums.append(image.mean(axis=(0, 1)))
squared.append((image ** 2).mean(axis=(0, 1)))
self.mean = np.mean(sums, axis=0) / 255
self.std = (np.mean(squared, axis=0) - self.mean ** 2) ** 0.5 / 255
def set_transform(self, transform):
self.transform = transform
def __getitem__(self, index):
assert self.transform is not None, ".set_tranform 메소드를 이용하여 transform 을 주입해주세요"
image = self.read_image(index)
gender_label = self.get_gender_label(index)
image_transform = self.transform(image)
return image_transform, gender_label
def __len__(self):
return len(self.image_paths)
# def get_mask_label(self, index) -> MaskLabels:
# return self.mask_labels[index]
def get_gender_label(self, index) -> GenderLabels:
return self.gender_labels[index]
def read_image(self, index):
image_path = self.image_paths[index]
return Image.open(image_path)
@staticmethod
def denormalize_image(image, mean, std):
img_cp = image.copy()
img_cp *= std
img_cp += mean
img_cp *= 255.0
img_cp = np.clip(img_cp, 0, 255).astype(np.uint8)
return img_cp
def split_dataset(self) -> Tuple[Subset, Subset]:
"""
데이터셋을 train 과 val 로 나눕니다,
pytorch 내부의 torch.utils.data.random_split 함수를 사용하여
torch.utils.data.Subset 클래스 둘로 나눕니다.
구현이 어렵지 않으니 구글링 혹은 IDE (e.g. pycharm) 의 navigation 기능을 통해 코드를 한 번 읽어보는 것을 추천드립니다^^
"""
n_val = int(len(self) * self.val_ratio)
n_train = len(self) - n_val
train_set, val_set = random_split(self, [n_train, n_val])
return train_set, val_set
class MaskSplitByProfileDataset(MaskBaseDataset):
"""
train / val 나누는 기준을 이미지에 대해서 random 이 아닌
사람(profile)을 기준으로 나눕니다.
구현은 val_ratio 에 맞게 train / val 나누는 것을 이미지 전체가 아닌 사람(profile)에 대해서 진행하여 indexing 을 합니다
이후 `split_dataset` 에서 index 에 맞게 Subset 으로 dataset 을 분기합니다.
"""
def __init__(self, data_dir, mean=(0.548, 0.504, 0.479), std=(0.237, 0.247, 0.246), val_ratio=0.2):
self.indices = defaultdict(list)
super().__init__(data_dir, mean, std, val_ratio)
@staticmethod
def _split_profile(profiles, val_ratio):
length = len(profiles)
n_val = int(length * val_ratio)
val_indices = set(random.choices(range(length), k=n_val))
train_indices = set(range(length)) - val_indices
return {
"train": train_indices,
"val": val_indices
}
def setup(self):
profiles = os.listdir(self.data_dir)
profiles = [profile for profile in profiles if not profile.startswith(".")]
split_profiles = self._split_profile(profiles, self.val_ratio)
cnt = 0
for phase, indices in split_profiles.items():
for _idx in indices:
profile = profiles[_idx]
img_folder = os.path.join(self.data_dir, profile)
for file_name in os.listdir(img_folder):
_file_name, ext = os.path.splitext(file_name)
if _file_name not in self._file_names: # "." 로 시작하는 파일 및 invalid 한 파일들은 무시합니다
continue
img_path = os.path.join(self.data_dir, profile, file_name) # (resized_data, 000004_male_Asian_54, mask1.jpg)
mask_label = self._file_names[_file_name]
id, gender, race, age = profile.split("_")
gender_label = GenderLabels.from_str(gender)
self.image_paths.append(img_path)
self.gender_labels.append(gender_label)
self.indices[phase].append(cnt)
cnt += 1
def split_dataset(self) -> List[Subset]:
return [Subset(self, indices) for phase, indices in self.indices.items()]
class TestDataset(Dataset):
def __init__(self, img_paths, resize, mean=(0.548, 0.504, 0.479), std=(0.237, 0.247, 0.246)):
self.img_paths = img_paths
self.transform = Compose([
Resize(resize, Image.BILINEAR),
ToTensor(),
Normalize(mean=mean, std=std),
])
def __getitem__(self, index):
image = Image.open(self.img_paths[index])
if self.transform:
image = self.transform(image)
return image
def __len__(self):
return len(self.img_paths)
class CustomDataset(Dataset):
def __init__(self, img_paths, labels, transforms=None):
self.img_paths = img_paths
self.labels = labels
self.transforms = transforms
def __getitem__(self, index):
img_path = self.img_paths[index]
image = Image.open(img_path)
if self.transforms is not None:
image = self.transforms(image)
label = self.labels[index]
return image, label
def __len__(self):
return len(self.img_paths)
class train_transform_1:
def __init__(self, resize, mean, std, **args):
self.transform = Compose([
Resize(resize, Image.BILINEAR),
ToTensor(),
Normalize(mean=mean, std=std),
])
def __call__(self, image):
return self.transform(image)
class train_transform_2:
def __init__(self, resize, mean, std, **args):
self.transform = Compose([
Resize(resize, Image.BILINEAR),
ToTensor(),
RandomHorizontalFlip(),
ColorJitter(saturation=(1.2, 1.5), hue=(0.2, 0.5)),
Normalize(mean=mean, std=std),
])
def __call__(self, image):
return self.transform(image)
class train_transform_3:
def __init__(self, resize, mean, std, **args):
self.transform = Compose([
Resize(resize, Image.BILINEAR),
ToTensor(),
RandomHorizontalFlip(),
Grayscale(num_output_channels=3),
Normalize(mean=mean, std=std),
])
def __call__(self, image):
return self.transform(image)
class train_transform_4:
def __init__(self, resize, mean, std, **args):
self.transform = Compose([
Resize(resize, Image.BILINEAR),
ToTensor(),
RandomHorizontalFlip(),
GaussianBlur(kernel_size=5),
Normalize(mean=mean, std=std),
])
def __call__(self, image):
return self.transform(image)
class train_transform_5:
def __init__(self, resize, mean, std, **args):
self.transform = Compose([
Resize(resize, Image.BILINEAR),
ToTensor(),
RandomHorizontalFlip(),
GaussianBlur(kernel_size=5),
ColorJitter(0.5, 0.5, 0.5, 0.5),
Normalize(mean=mean, std=std),
])
def __call__(self, image):
return self.transform(image)
###################################
class train_transform_6:
def __init__(self, resize, mean, std, **args):
self.transform = Compose([
CenterCrop(resize),
ToTensor(),
RandomHorizontalFlip(),
GaussianBlur(kernel_size=5),
Normalize(mean=mean, std=std),
])
def __call__(self, image):
return self.transform(image)
class train_transform_7:
def __init__(self, resize, mean, std, **args):
self.transform = Compose([
CenterCrop(resize),
ToTensor(),
RandomHorizontalFlip(),
ColorJitter(0.5, 0.5, 0.5, 0.5),
Normalize(mean=mean, std=std),
])
def __call__(self, image):
return self.transform(image)
class train_transform_8:
def __init__(self, resize, mean, std, **args):
self.transform = Compose([
CenterCrop(resize),
ToTensor(),
RandomHorizontalFlip(),
GaussianBlur(kernel_size=5),
Grayscale(num_output_channels=3),
Normalize(mean=mean, std=std),
])
def __call__(self, image):
return self.transform(image)
class train_transform_9:
def __init__(self, resize, mean, std, **args):
self.transform = Compose([
CenterCrop(resize),
ToTensor(),
RandomHorizontalFlip(),
Grayscale(num_output_channels=3),
Normalize(mean=mean, std=std),
])
def __call__(self, image):
return self.transform(image)
class train_transform_10:
def __init__(self, resize, mean, std, **args):
self.transform = Compose([
CenterCrop(resize),
ToTensor(),
RandomHorizontalFlip(),
ColorJitter(0.5, 0.5, 0.5, 0.5),
GaussianBlur(kernel_size=5),
Normalize(mean=mean, std=std),
])
def __call__(self, image):
return self.transform(image)
class val_transform:
def __init__(self, resize, mean, std, **args):
self.transform = Compose([
Resize(resize, Image.BILINEAR),
ToTensor(),
Normalize(mean=mean, std=std),
])
def __call__(self, image):
return self.transform(image)