-
Notifications
You must be signed in to change notification settings - Fork 57
/
dataset.py
285 lines (227 loc) · 10.4 KB
/
dataset.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
import os
import glob
import random
import numpy as np
from PIL import Image
from pathlib import Path
import torch
from torch.utils.data import Dataset
from torchvision import transforms
import PIL
from PIL import Image, ImageFile
PIL.ImageFile.LOAD_TRUNCATED_IMAGES = True
def same_or_not(percent):
return random.randrange(100) < percent
def color_masking(img, r, g, b):
return np.logical_and(np.logical_and(img[:, :, 0] == r, img[:, :, 1] == g), img[:, :, 2] == b)
def logical_or_masks(mask_list):
mask_all = np.zeros_like(mask_list[0], dtype=bool)
for mask in mask_list:
mask_all = np.logical_or(mask_all, mask)
return mask_all
def parsing2mask(paring):
img_numpy = np.array(paring)
mask_nose = color_masking(img_numpy, 76, 153, 0)
mask_left_eye = color_masking(img_numpy, 204, 0, 204)
mask_right_eye = color_masking(img_numpy, 51, 51, 255)
mask_skin = color_masking(img_numpy, 204, 0, 0)
mask_left_eyebrow = color_masking(img_numpy, 255, 204, 204)
mask_right_eyebrow = color_masking(img_numpy, 0, 255, 255)
mask_up_lip = color_masking(img_numpy, 255, 255, 0)
mask_mouth_inside = color_masking(img_numpy, 102, 204, 0)
mask_down_lip = color_masking(img_numpy, 0, 0, 153)
mask_left_ear = color_masking(img_numpy, 255, 0, 0)
mask_right_ear = color_masking(img_numpy, 102, 51, 0)
mask_face = logical_or_masks(
[mask_nose, mask_left_eye, mask_right_eye, mask_skin, mask_left_eyebrow, mask_right_eyebrow, mask_up_lip,
mask_mouth_inside, mask_down_lip, mask_left_ear, mask_right_ear, ])
mask_face = 1.0 * mask_face
mask_face = Image.fromarray(np.array(mask_face))
return mask_face
class HifiFaceParsingTrainDataset(Dataset):
def __init__(self, img_root, parsing_root, same_rate=50, transform=transforms.Compose([transforms.Resize((256, 256)),
transforms.CenterCrop((256, 256)),
transforms.ToTensor()])):
super(HifiFaceParsingTrainDataset, self).__init__()
ext_list = ['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'JPEG']
self.img_root = img_root
img_dir = Path(img_root)
img_files = []
for ext in ext_list:
file_generator = img_dir.glob(f"**/*.{ext}")
img_files.extend([file for file in file_generator])
img_files.sort()
self.img_files = img_files
self.parsing_root = parsing_root
parsing_dir = Path(parsing_root)
parsing_files = []
for ext in ext_list:
file_generator = parsing_dir.glob(f"**/*.{ext}")
parsing_files.extend([file for file in file_generator])
parsing_files.sort()
self.parsing_files = parsing_files
assert len(self.img_files) == len(self.parsing_files), f"number of image files and parsing files are different. ({len(self.img_files)} and {len(self.parsing_files)})"
for img_path, parsing_path in zip(self.img_files, self.parsing_files):
_, img_path_ = os.path.split(img_path)
_, parsing_path_ = os.path.split(parsing_path)
img_path_, ext = os.path.splitext(img_path_)
parsing_path_, ext = os.path.splitext(parsing_path_)
assert img_path_ == parsing_path_, f"image file and parsing file not matched, {img_path}, {parsing_path}"
self.same_rate = same_rate
self.transform = transform
def __getitem__(self, index):
l = self.__len__()
s_idx = index
if same_or_not(self.same_rate):
t_idx = s_idx
else:
t_idx = random.randrange(l)
if t_idx == s_idx:
same = torch.ones(1)
else:
same = torch.zeros(1)
f_img = Image.open(self.img_files[t_idx])
s_img = Image.open(self.img_files[s_idx])
f_img = f_img.convert('RGB')
s_img = s_img.convert('RGB')
f_parsing = Image.open(self.parsing_files[t_idx])
f_parsing = f_parsing.convert('RGB')
f_mask = parsing2mask(f_parsing)
if self.transform is not None:
f_img = self.transform(f_img)
s_img = self.transform(s_img)
f_mask = self.transform(f_mask)
return {'target_image': f_img,
'source_image': s_img,
'target_mask': f_mask,
'same': same,
}
def __len__(self):
return len(self.img_files)
class HifiFaceParsingTrainRecDataset(Dataset):
def __init__(self, img_root, parsing_root, same_rate=50, transform=transforms.Compose([transforms.Resize((256, 256)),
transforms.CenterCrop((256, 256)),
transforms.ToTensor()])):
super(HifiFaceParsingTrainRecDataset, self).__init__()
ext_list = ['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'JPEG']
self.img_root = img_root
img_dir = Path(img_root)
img_files = []
for ext in ext_list:
file_generator = img_dir.glob(f"**/*.{ext}")
img_files.extend([file for file in file_generator])
img_files.sort()
self.img_files = img_files
img_file_dict = {}
for idx, img_file in enumerate(img_files):
dir_name, file_name = os.path.split(img_file)
if not str(dir_name) in img_file_dict:
img_file_dict[str(dir_name)] = []
img_file_dict[str(dir_name)].append(idx)
self.img_file_dict = img_file_dict
self.parsing_root = parsing_root
parsing_dir = Path(parsing_root)
parsing_files = []
for ext in ext_list:
file_generator = parsing_dir.glob(f"**/*.{ext}")
parsing_files.extend([file for file in file_generator])
parsing_files.sort()
self.parsing_files = parsing_files
assert len(self.img_files) == len(
self.parsing_files), f"number of image files and parsing files are different. ({len(self.img_files)} and {len(self.parsing_files)})"
for img_path, parsing_path in zip(self.img_files, self.parsing_files):
_, img_path_ = os.path.split(img_path)
_, parsing_path_ = os.path.split(parsing_path)
img_path_, ext = os.path.splitext(img_path_)
parsing_path_, ext = os.path.splitext(parsing_path_)
assert img_path_ == parsing_path_, f"image file and parsing file not matched, {img_path}, {parsing_path}"
self.same_rate = same_rate
self.transform = transform
def __getitem__(self, index):
l = self.__len__()
s_idx = index
if same_or_not(self.same_rate):
file_path = self.img_files[s_idx]
dir_name, _ = os.path.split(file_path)
same_identity_idx = random.randrange(len(self.img_file_dict[str(dir_name)]))
t_idx = self.img_file_dict[str(dir_name)][same_identity_idx]
else:
t_idx = random.randrange(l)
if t_idx == s_idx:
same = torch.ones(1)
else:
same = torch.zeros(1)
f_img = Image.open(self.img_files[t_idx])
s_img = Image.open(self.img_files[s_idx])
f_img = f_img.convert('RGB')
s_img = s_img.convert('RGB')
f_parsing = Image.open(self.parsing_files[t_idx])
f_parsing = f_parsing.convert('RGB')
f_mask = parsing2mask(f_parsing)
if self.transform is not None:
f_img = self.transform(f_img)
s_img = self.transform(s_img)
f_mask = self.transform(f_mask)
return {'target_image': f_img,
'source_image': s_img,
'target_mask': f_mask,
'same': same,
}
def __len__(self):
return len(self.img_files)
class HifiFaceParsingValDataset(Dataset):
def __init__(self, img_root, parsing_root, transform=transforms.Compose([transforms.Resize((256, 256)),
transforms.CenterCrop((256, 256)),
transforms.ToTensor()])):
super(HifiFaceParsingValDataset, self).__init__()
ext_list = ['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'JPEG']
self.img_root = img_root
img_dir = Path(img_root)
img_files = []
for ext in ext_list:
file_generator = img_dir.glob(f"**/*.{ext}")
img_files.extend([file for file in file_generator])
img_files.sort()
self.img_files = img_files
self.parsing_root = parsing_root
parsing_dir = Path(parsing_root)
parsing_files = []
for ext in ext_list:
file_generator = parsing_dir.glob(f"**/*.{ext}")
parsing_files.extend([file for file in file_generator])
parsing_files.sort()
self.parsing_files = parsing_files
assert len(self.img_files) == len(self.parsing_files), f"number of image files and parsing files are different. ({len(self.img_files)} and {len(self.parsing_files)})"
for img_path, parsing_path in zip(self.img_files, self.parsing_files):
_, img_path_ = os.path.split(img_path)
_, parsing_path_ = os.path.split(parsing_path)
img_path_, ext = os.path.splitext(img_path_)
parsing_path_, ext = os.path.splitext(parsing_path_)
assert img_path_ == parsing_path_, f"image file and parsing file not matched, {img_path}, {parsing_path}"
self.transform = transform
def __getitem__(self, index):
l = len(self.img_files)
t_idx = index // l
s_idx = index % l
if t_idx == s_idx:
same = torch.ones(1)
else:
same = torch.zeros(1)
f_img = Image.open(self.img_files[t_idx])
s_img = Image.open(self.img_files[s_idx])
f_img = f_img.convert('RGB')
s_img = s_img.convert('RGB')
f_parsing = Image.open(self.parsing_files[t_idx])
f_parsing = f_parsing.convert('RGB')
f_mask = parsing2mask(f_parsing)
if self.transform is not None:
f_img = self.transform(f_img)
s_img = self.transform(s_img)
f_mask = self.transform(f_mask)
return {'target_image': f_img,
'source_image': s_img,
'target_mask': f_mask,
'same': same,
}
def __len__(self):
return len(self.img_files) * len(self.img_files)