-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdata_loader.py
346 lines (307 loc) · 10.9 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
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
from os.path import isfile, join
import pandas as pd
from torch.utils import data
from torchvision import transforms as T
from torchvision.datasets import ImageFolder
from PIL import Image
import torch
import os
import random
from shutil import copyfile, copy2
from helpers.AgeGender import get_gender
class CelebA(data.Dataset):
"""
Dataset class for the CelebA dataset.
"""
def __init__(self, image_dir, attr_path, selected_attrs, transform, mode):
"""Initialize and preprocess the CelebA dataset."""
self.image_dir = image_dir
self.attr_path = attr_path
self.selected_attrs = selected_attrs
self.transform = transform
self.mode = mode
self.train_dataset = []
self.test_dataset = []
self.attr2idx = {}
self.idx2attr = {}
self.preprocess()
if mode == 'train':
self.num_images = len(self.train_dataset)
else:
self.num_images = len(self.test_dataset)
def preprocess(self):
"""
Preprocess the CelebA attribute file.
"""
lines = [line.rstrip() for line in open(self.attr_path, 'r')]
all_attr_names = lines[1].split()
for i, attr_name in enumerate(all_attr_names):
self.attr2idx[attr_name] = i
self.idx2attr[i] = attr_name
lines = lines[2:]
random.seed(1234)
random.shuffle(lines)
for i, line in enumerate(lines):
split = line.split()
filename = split[0]
values = split[1:]
label = []
for attr_name in self.selected_attrs:
idx = self.attr2idx[attr_name]
label.append(values[idx] == '1')
if (i + 1) < 2000:
self.test_dataset.append([filename, label])
else:
self.train_dataset.append([filename, label])
print('Finished preprocessing the CelebA dataset...')
def __getitem__(self, index):
"""
Return one image and its corresponding attribute label.
"""
dataset = self.train_dataset if self.mode == 'train' else self.test_dataset
filename, label = dataset[index]
image = Image.open(os.path.join(self.image_dir, filename))
return self.transform(image), torch.FloatTensor(label)
def __len__(self):
"""
Return the number of images.
"""
return self.num_images
# class CelebAHQ(data.Dataset):
# """
# Dataset class for the CelebA dataset.
# """
#
# def __init__(self, image_dir, transform, mode):
# """Initialize and preprocess the CelebA dataset."""
# self.image_dir = image_dir
# self.transform = transform
# self.mode = mode
# self.train_dataset = []
# self.test_dataset = []
#
# self.preprocess()
#
# if mode == 'train':
# self.num_images = len(self.train_dataset)
# else:
# self.num_images = len(self.test_dataset)
#
# def preprocess(self):
# """
# Preprocess the CelebA attribute file.
# """
# lines = [f for f in os.listdir(self.image_dir)]
# random.seed(1234)
# random.shuffle(lines)
# for i, line in enumerate(lines):
# if (i + 1) < 2000:
# self.test_dataset.append([line, random.choice(lines)])
# else:
# self.train_dataset.append([line, random.choice(lines)])
#
# print('Finished preprocessing the CelebA dataset...')
#
# def __getitem__(self, index):
# """
# Return one image and its corresponding attribute label.
# """
# dataset = self.train_dataset if self.mode == 'train' else self.test_dataset
# source, reference = dataset[index]
# source_image = Image.open(os.path.join(self.image_dir, source))
# reference_image = Image.open(os.path.join(self.image_dir, reference))
# return self.transform(source_image), self.transform(reference_image)
#
# def __len__(self):
# """
# Return the number of images.
# """
# return self.num_images
# def get_loader(image_dir, attr_path, selected_attrs, crop_size=178, image_size=128,
# batch_size=16, dataset='CelebA', mode='train', num_workers=1):
# """
# Build and return a data loader.
# """
# transform = []
# if mode == 'train':
# transform.append(T.RandomHorizontalFlip())
# transform.append(T.CenterCrop(crop_size))
# transform.append(T.Resize(image_size))
# transform.append(T.ToTensor())
# transform.append(T.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)))
# transform = T.Compose(transform)
#
# if dataset == 'CelebA':
# # dataset = CelebAHQ(image_dir, transform, mode)
# dataset = CelebA(image_dir, attr_path, selected_attrs, transform, mode)
# elif dataset == 'RaFD':
# dataset = ImageFolder(image_dir, transform)
#
# data_loader = data.DataLoader(dataset=dataset,
# batch_size=batch_size,
# shuffle=(mode == 'train'),
# num_workers=num_workers)
# return data_loader
def get_loader(image_dir, crop_size=178, image_size=128,
batch_size=16, mode='train', num_workers=1):
"""
Build and return a data loader.
"""
transform = []
if mode == 'train':
transform.append(T.RandomHorizontalFlip())
# transform.append(T.CenterCrop(crop_size))
transform.append(T.Resize(image_size))
transform.append(T.ToTensor())
transform.append(T.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)))
transform = T.Compose(transform)
#
# if dataset == 'CelebA':
# # dataset = CelebAHQ(image_dir, transform, mode)
# dataset = CelebA(image_dir, attr_path, selected_attrs, transform, mode)
# else:
# dataset = ImageFolder(image_dir, transform)
dataset = ImageFolder(image_dir, transform)
data_loader = data.DataLoader(dataset=dataset,
batch_size=batch_size,
shuffle=(mode == 'train'),
num_workers=num_workers)
return data_loader
def process_celeba():
"""
split aligned celeba images into multiple domain folders
:return:
"""
csv_file = "/data/datasets/CelebA/Anno/list_attr_celeba.txt"
attrs_df = pd.read_csv(csv_file, delim_whitespace=True, skiprows=2)
# # print(attrs_df.loc[0, :])
# for index, row in attrs_df.iterrows():
# try:
# print(row[0])
# # print(row[20])
# except Exception as e:
# print(str(e))
total = len(attrs_df)
for i in range(total):
if i < int(0.7 * total):
target = "train"
else:
target = "test"
base_path = "/data/datasets/CelebA/Img/img_align_celeba"
male_path = "/data/datasets/celeba/{}/male".format(target)
female_path = "/data/datasets/celeba/{}/female".format(target)
if not os.path.exists(male_path):
os.mkdir(male_path)
if not os.path.exists(female_path):
os.mkdir(female_path)
src_file = os.path.join(base_path, attrs_df.iloc[i, 0])
male = attrs_df.iloc[i, 21]
if male == 1:
# male
# copy2('/src/file.ext', '/dst/dir')
copy2(src_file, male_path)
else:
# female
copy2(src_file, female_path)
print(attrs_df.iloc[i, 0])
print(type(male))
return
def process_celebahq():
"""
split aligned celeba images into multiple domain folders
:return:
"""
csv_file = "/data/datasets/CelebA/Anno/list_attr_celeba.txt"
attrs_df = pd.read_csv(csv_file, delim_whitespace=True, skiprows=2)
# # print(attrs_df.loc[0, :])
# for index, row in attrs_df.iterrows():
# try:
# print(row[0])
# # print(row[20])
# except Exception as e:
# print(str(e))
total = len(attrs_df)
for i in range(total):
if i < int(0.7 * total):
target = "train"
else:
target = "test"
base_path = "/data/datasets/CelebA-HQ/celeba-1024"
male_path = "/data/datasets/celeba-hq/{}/male".format(target)
female_path = "/data/datasets/celeba-hq/{}/female".format(target)
if not os.path.exists(male_path):
os.mkdir(male_path)
if not os.path.exists(female_path):
os.mkdir(female_path)
src_file = os.path.join(base_path, attrs_df.iloc[i, 0])
male = attrs_df.iloc[i, 21]
if os.path.isfile(src_file):
if male == 1:
# male
# copy2('/src/file.ext', '/dst/dir')
copy2(src_file, male_path)
else:
# female
copy2(src_file, female_path)
print(attrs_df.iloc[i, 0])
print(type(male))
return
#
# def process_celebahq(mypath="/data/datasets/CelebA-HQ/celeba-1024"):
# """
# split aligned celeba images into multiple domain folders
# :return:
# """
#
# for i, f in enumerate(os.listdir(mypath)):
# try:
# if i < 25000:
# target = "train"
# else:
# target = "test"
# male_path = "/data/datasets/celeba-hq/{}/male".format(target)
# female_path = "/data/datasets/celeba-hq/{}/female".format(target)
# image_file = join(mypath, f)
# print(image_file)
# gender, confidence = get_gender(image_file)
# if confidence < 0.8:
# continue
# if gender == "Male":
# copy2(image_file, male_path)
# else:
# copy2(image_file, female_path)
# # print(onlyfiles)
# print(i)
# except Exception as e:
# print(str(e))
# # total = len(attrs_df)
# # for i in range(total):
# # if i < int(0.7 * total):
# # target = "train"
# # else:
# # target = "test"
# # base_path = "/data/datasets/CelebA/Img/img_align_celeba"
# # male_path = "/data/datasets/celeba/{}/male".format(target)
# # female_path = "/data/datasets/celeba/{}/female".format(target)
# #
# # if not os.path.exists(male_path):
# # os.mkdir(male_path)
# #
# # if not os.path.exists(female_path):
# # os.mkdir(female_path)
# #
# # src_file = os.path.join(base_path, attrs_df.iloc[i, 0])
# # male = attrs_df.iloc[i, 21]
# # if male == 1:
# # # male
# # # copy2('/src/file.ext', '/dst/dir')
# # copy2(src_file, male_path)
# # else:
# # # female
# # copy2(src_file, female_path)
# # print(attrs_df.iloc[i, 0])
# # print(type(male))
#
# return
if __name__ == "__main__":
process_celebahq()