-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdataloader.py
243 lines (203 loc) · 7.99 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
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
import PIL
import numpy as np
import torch.utils.data as data
from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode
import os.path as osp
import torch
class ResizedCrop(torch.nn.Module):
def __init__(self, size=64, ratio=(1, 1.2), interpolation=InterpolationMode.BILINEAR):
super().__init__()
self.transform_ = transforms.Compose([
transforms.Resize((int(size*ratio[0]), int(size*ratio[1])), interpolation=interpolation),
transforms.CenterCrop((size, size))
])
def forward(self, img):
out = self.transform_(img)
return out
class CelebA(data.Dataset):
def __init__(self, split, img_path='~/CelebA/celeba/img_align_celeba/', identity_file='~/CelebA/celeba/identity_CelebA.txt', num_ids=1000, trans=False):
self.num_ids = num_ids
self.trans = trans
self.img_path = osp.expanduser(img_path)
with open(osp.expanduser(identity_file)) as f:
lines = f.readlines()
id2file = {}
for line in lines:
file, id = line.strip().split()
id = int(id)
if id in id2file.keys():
id2file[id].append(file)
else:
id2file[id] = [file]
thres = 25
id2file_cleaned = {}
for key in id2file.keys():
if len(id2file[key]) > thres:
id2file_cleaned[key] = id2file[key]
self.name_list = []
self.label_list = []
if split == 'pub':
i = 0
for key in sorted(id2file_cleaned.keys())[:2000]:
for file in id2file_cleaned[key][:20]:
self.name_list.append(file)
self.label_list.append(i)
i += 1
elif split == 'pub-dev':
i = 0
for key in sorted(id2file_cleaned.keys())[:2000]:
for file in id2file_cleaned[key][20:25]:
self.name_list.append(file)
self.label_list.append(i)
i += 1
elif split == 'pub1':
i = 0
for key in sorted(id2file_cleaned.keys())[:1000]:
for file in id2file_cleaned[key][:20]:
self.name_list.append(file)
self.label_list.append(i)
i += 1
elif split == 'pub1-dev':
i = 0
for key in sorted(id2file_cleaned.keys())[:1000]:
for file in id2file_cleaned[key][20:25]:
self.name_list.append(file)
self.label_list.append(i)
i += 1
elif split == 'pub2':
i = 0
for key in sorted(id2file_cleaned.keys())[1000:2000]:
for file in id2file_cleaned[key][:20]:
self.name_list.append(file)
self.label_list.append(i)
i += 1
elif split == 'pub2-dev':
i = 0
for key in sorted(id2file_cleaned.keys())[1000:2000]:
for file in id2file_cleaned[key][20:25]:
self.name_list.append(file)
self.label_list.append(i)
i += 1
elif split == 'pri':
i = 0
for key in sorted(id2file_cleaned.keys())[2000:3000]:
for file in id2file_cleaned[key][:20]:
self.name_list.append(file)
self.label_list.append(i)
i += 1
elif split == 'pri-dev':
i = 0
for key in sorted(id2file_cleaned.keys())[2000:3000]:
for file in id2file_cleaned[key][20:25]:
self.name_list.append(file)
self.label_list.append(i)
i += 1
elif split == 'pri-':
i = 0
for key in sorted(id2file_cleaned.keys())[2000:2000+num_ids]:
for file in id2file_cleaned[key][:20]:
self.name_list.append(file)
self.label_list.append(i)
i += 1
elif split == 'pri-debug':
i = 0
for key in sorted(id2file_cleaned.keys())[2000:3000]:
for file in id2file_cleaned[key][:1]:
self.name_list.append(file)
self.label_list.append(i)
i += 1
else:
raise NotImplementedError()
self.processor = self.get_processor()
def get_processor(self):
crop_size = 108
re_size = 64
offset_height = (218 - crop_size) // 2
offset_width = (178 - crop_size) // 2
crop = lambda x: x[:, offset_height:offset_height + crop_size, offset_width:offset_width + crop_size]
proc = []
proc.append(transforms.ToTensor())
proc.append(transforms.Lambda(crop))
proc.append(transforms.ToPILImage())
proc.append(transforms.Resize((re_size, re_size)))
proc.append(transforms.ToTensor())
if self.trans:
proc.append(transforms.RandomApply([ResizedCrop()], p=0.2))
proc.append(transforms.RandomHorizontalFlip(p=0.2))
# proc.append(transforms.RandomApply([transforms.ColorJitter()], p=0.2))
proc.append(transforms.RandomGrayscale(p=0.2))
return transforms.Compose(proc)
def __getitem__(self, index):
path = self.img_path + "/" + self.name_list[index]
img = PIL.Image.open(path).convert('RGB')
img = self.processor(img)
label = self.label_list[index]
one_hot = np.zeros(self.num_ids)
one_hot[label] = 1
return img, one_hot, label
def __len__(self):
return len(self.name_list)
class CelebAVirtual(data.Dataset):
def __init__(self, path, split='all', num_ids=1000):
self.path = path
self.num_ids = num_ids
identity_file = osp.join(path, 'identity.txt')
with open(osp.expanduser(identity_file)) as f:
lines = f.readlines()
id2file = {}
file2id = {}
for line in lines:
file, id = line.strip().split()
id = int(id)
file2id[file] = id
if id in id2file.keys():
id2file[id].append(file)
else:
id2file[id] = [file]
self.name_list = []
self.label_list = []
if split == 'train':
for key in sorted(id2file.keys()):
for file in id2file[key][:int(0.8*len(id2file[key]))]:
self.name_list.append(file)
self.label_list.append(file2id[file])
elif split == 'dev':
for key in sorted(id2file.keys()):
for file in id2file[key][int(0.8*len(id2file[key])):]:
self.name_list.append(file)
self.label_list.append(file2id[file])
elif split == 'all':
for key in sorted(id2file.keys()):
for file in id2file[key]:
self.name_list.append(file)
self.label_list.append(file2id[file])
self.processor = self.get_processor()
def get_processor(self):
proc = []
proc.append(transforms.ToTensor())
return transforms.Compose(proc)
def __getitem__(self, index):
path = self.name_list[index]
path = osp.join(self.path, path[path.index('img'):])
img = PIL.Image.open(path).convert('RGB')
img = self.processor(img)
label = self.label_list[index]
one_hot = np.zeros(self.num_ids)
one_hot[label] = 1
return img, one_hot, label
def __len__(self):
return len(self.name_list)
if __name__ == '__main__':
celeba = CelebA(split='pub')
print(len(celeba))
celeba = CelebA(split='pub1')
print(len(celeba))
celeba = CelebA(split='pub2')
print(len(celeba))
celeba = CelebA(split='pri')
print(len(celeba))
celeba = CelebA(split='pri-dev')
print(len(celeba))
loader = data.DataLoader(celeba, batch_size=32)
batch = next(iter(loader))