-
Notifications
You must be signed in to change notification settings - Fork 7
/
dataset.py
executable file
·453 lines (380 loc) · 13.9 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
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
446
447
448
449
450
451
452
453
import os
from io import BytesIO
from pathlib import Path
import lmdb
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
from torchvision.datasets import CIFAR10, LSUNClass
import torch
import pandas as pd
import random
import torchvision.transforms.functional as Ftrans
class ImageDataset(Dataset):
def __init__(
self,
folder,
image_size,
exts=['jpg'],
do_augment: bool = True,
do_transform: bool = True,
do_normalize: bool = True,
sort_names=False,
has_subdir: bool = True,
max_num = None,
):
super().__init__()
self.folder = folder
self.image_size = image_size
# relative paths (make it shorter, saves memory and faster to sort)
if has_subdir:
self.paths = [
p.relative_to(folder) for ext in exts
for p in Path(f'{folder}').glob(f'**/*.{ext}')
]
else:
self.paths = [
p.relative_to(folder) for ext in exts
for p in Path(f'{folder}').glob(f'*.{ext}')
]
if sort_names:
self.paths = sorted(self.paths)
if max_num != None:
self.paths = self.paths[:max_num]
transform = [
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
]
if do_augment:
transform.append(transforms.RandomHorizontalFlip())
if do_transform:
transform.append(transforms.ToTensor())
if do_normalize:
transform.append(
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
self.transform = transforms.Compose(transform)
def __len__(self):
return len(self.paths)
def __getitem__(self, index):
path = os.path.join(self.folder, self.paths[index])
img = Image.open(path)
# if the image is 'rgba'!
img = img.convert('RGB')
if self.transform is not None:
img = self.transform(img)
return {'img': img, 'index': index}
class SubsetDataset(Dataset):
def __init__(self, dataset, size):
assert len(dataset) >= size
self.dataset = dataset
self.size = size
def __len__(self):
return self.size
def __getitem__(self, index):
assert index < self.size
return self.dataset[index]
class BaseLMDB(Dataset):
def __init__(self, path, original_resolution, zfill: int = 5):
self.original_resolution = original_resolution
self.zfill = zfill
self.env = lmdb.open(
path,
max_readers=32,
readonly=True,
lock=False,
readahead=False,
meminit=False,
)
if not self.env:
raise IOError('Cannot open lmdb dataset', path)
with self.env.begin(write=False) as txn:
self.length = int(
txn.get('length'.encode('utf-8')).decode('utf-8'))
def __len__(self):
return self.length
def __getitem__(self, index):
with self.env.begin(write=False) as txn:
key = f'{self.original_resolution}-{str(index).zfill(self.zfill)}'.encode(
'utf-8')
img_bytes = txn.get(key)
buffer = BytesIO(img_bytes)
img = Image.open(buffer)
return img
def make_transform(
image_size,
flip_prob=0.5,
crop_d2c=False,
):
if crop_d2c:
transform = [
d2c_crop(),
transforms.Resize(image_size),
]
else:
transform = [
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
]
transform.append(transforms.RandomHorizontalFlip(p=flip_prob))
transform.append(transforms.ToTensor())
transform.append(transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
transform = transforms.Compose(transform)
return transform
class Voxceleb(Dataset):
def __init__(self,
folder=os.path.expanduser('/home/server03/voxceleb/result/stit_out_vox1'),
batch_size=None,
image_size=256,
split='train',
as_tensor: bool = True,
do_augment: bool = True,
do_normalize: bool = True,
):
super().__init__()
self.folder = folder
self.image_size = image_size
self.batch_size = batch_size
self.split = split
assert split in ['train', 'test'] and batch_size != None
self.paths = [p.relative_to(f'{folder}/{split}') for p in Path(f'{folder}/{split}').glob(f'*')]
transform = [
transforms.Resize(image_size),
]
if do_augment:
transform.append(transforms.RandomHorizontalFlip())
if as_tensor:
transform.append(transforms.ToTensor())
if do_normalize:
transform.append(
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
self.transform = transforms.Compose(transform)
def __len__(self):
return len(self.paths)
def __getitem__(self, index):
paths = [p for p in Path(os.path.join(self.folder, self.split, self.paths[index])).glob("*")]
batch_paths = random.sample(paths, self.batch_size)
imgs = []
for path in batch_paths:
img = Image.open(path)
img = img.convert('RGB')
if self.transform is not None:
img = self.transform(img)
imgs.append(img)
return {'img': imgs, 'index': index}
class Crop:
def __init__(self, x1, x2, y1, y2):
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
def __call__(self, img):
return Ftrans.crop(img, self.x1, self.y1, self.x2 - self.x1,
self.y2 - self.y1)
def __repr__(self):
return self.__class__.__name__ + "(x1={}, x2={}, y1={}, y2={})".format(
self.x1, self.x2, self.y1, self.y2)
def d2c_crop():
# from D2C paper for CelebA dataset.
cx = 89
cy = 121
x1 = cy - 64
x2 = cy + 64
y1 = cx - 64
y2 = cx + 64
return Crop(x1, x2, y1, y2)
class CelebAlmdb(Dataset):
"""
also supports for d2c crop.
"""
def __init__(self,
path,
image_size,
original_resolution=128,
split=None,
as_tensor: bool = True,
do_augment: bool = True,
do_normalize: bool = True,
crop_d2c: bool = False,
**kwargs):
self.original_resolution = original_resolution
self.data = BaseLMDB(path, original_resolution, zfill=7)
self.length = len(self.data)
self.crop_d2c = crop_d2c
if split is None:
self.offset = 0
else:
raise NotImplementedError()
if crop_d2c:
transform = [
d2c_crop(),
transforms.Resize(image_size),
]
else:
transform = [
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
]
if do_augment:
transform.append(transforms.RandomHorizontalFlip())
if as_tensor:
transform.append(transforms.ToTensor())
if do_normalize:
transform.append(
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
self.transform = transforms.Compose(transform)
def __len__(self):
return self.length
def __getitem__(self, index):
assert index < self.length
index = index + self.offset
img = self.data[index]
if self.transform is not None:
img = self.transform(img)
return {'img': img, 'index': index}
class CelebAttrDataset(Dataset):
id_to_cls = [
'5_o_Clock_Shadow', 'Arched_Eyebrows', 'Attractive', 'Bags_Under_Eyes',
'Bald', 'Bangs', 'Big_Lips', 'Big_Nose', 'Black_Hair', 'Blond_Hair',
'Blurry', 'Brown_Hair', 'Bushy_Eyebrows', 'Chubby', 'Double_Chin',
'Eyeglasses', 'Goatee', 'Gray_Hair', 'Heavy_Makeup', 'High_Cheekbones',
'Male', 'Mouth_Slightly_Open', 'Mustache', 'Narrow_Eyes', 'No_Beard',
'Oval_Face', 'Pale_Skin', 'Pointy_Nose', 'Receding_Hairline',
'Rosy_Cheeks', 'Sideburns', 'Smiling', 'Straight_Hair', 'Wavy_Hair',
'Wearing_Earrings', 'Wearing_Hat', 'Wearing_Lipstick',
'Wearing_Necklace', 'Wearing_Necktie', 'Young'
]
cls_to_id = {v: k for k, v in enumerate(id_to_cls)}
def __init__(self,
folder,
image_size=64,
attr_path=os.path.expanduser(
'datasets/celeba_anno/list_attr_celeba.txt'),
ext='png',
only_cls_name: str = None,
only_cls_value: int = None,
do_augment: bool = False,
do_transform: bool = True,
do_normalize: bool = True,
d2c: bool = False):
super().__init__()
self.folder = folder
self.image_size = image_size
self.ext = ext
# relative paths (make it shorter, saves memory and faster to sort)
paths = [
str(p.relative_to(folder))
for p in Path(f'{folder}').glob(f'**/*.{ext}')
]
paths = [str(each).split('.')[0] + '.jpg' for each in paths]
if d2c:
transform = [
d2c_crop(),
transforms.Resize(image_size),
]
else:
transform = [
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
]
if do_augment:
transform.append(transforms.RandomHorizontalFlip())
if do_transform:
transform.append(transforms.ToTensor())
if do_normalize:
transform.append(
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
self.transform = transforms.Compose(transform)
with open(attr_path) as f:
# discard the top line
f.readline()
self.df = pd.read_csv(f, delim_whitespace=True)
self.df = self.df[self.df.index.isin(paths)]
if only_cls_name is not None:
self.df = self.df[self.df[only_cls_name] == only_cls_value]
def pos_count(self, cls_name):
return (self.df[cls_name] == 1).sum()
def neg_count(self, cls_name):
return (self.df[cls_name] == -1).sum()
def __len__(self):
return len(self.df)
def __getitem__(self, index):
row = self.df.iloc[index]
name = row.name.split('.')[0]
name = f'{name}.{self.ext}'
path = os.path.join(self.folder, name)
img = Image.open(path)
labels = [0] * len(self.id_to_cls)
for k, v in row.items():
labels[self.cls_to_id[k]] = int(v)
if self.transform is not None:
img = self.transform(img)
return {'img': img, 'index': index, 'labels': torch.tensor(labels)}
class CelebHQAttrDataset(Dataset):
id_to_cls = [
'5_o_Clock_Shadow', 'Arched_Eyebrows', 'Attractive', 'Bags_Under_Eyes',
'Bald', 'Bangs', 'Big_Lips', 'Big_Nose', 'Black_Hair', 'Blond_Hair',
'Blurry', 'Brown_Hair', 'Bushy_Eyebrows', 'Chubby', 'Double_Chin',
'Eyeglasses', 'Goatee', 'Gray_Hair', 'Heavy_Makeup', 'High_Cheekbones',
'Male', 'Mouth_Slightly_Open', 'Mustache', 'Narrow_Eyes', 'No_Beard',
'Oval_Face', 'Pale_Skin', 'Pointy_Nose', 'Receding_Hairline',
'Rosy_Cheeks', 'Sideburns', 'Smiling', 'Straight_Hair', 'Wavy_Hair',
'Wearing_Earrings', 'Wearing_Hat', 'Wearing_Lipstick',
'Wearing_Necklace', 'Wearing_Necktie', 'Young'
]
cls_to_id = {v: k for k, v in enumerate(id_to_cls)}
def __init__(self,
path=os.path.expanduser('datasets/celebahq256.lmdb'),
image_size=None,
attr_path=os.path.expanduser(
'datasets/celeba_anno/CelebAMask-HQ-attribute-anno.txt'),
original_resolution=256,
do_augment: bool = False,
do_transform: bool = True,
do_normalize: bool = True):
super().__init__()
self.image_size = image_size
self.data = BaseLMDB(path, original_resolution, zfill=5)
transform = [
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
]
if do_augment:
transform.append(transforms.RandomHorizontalFlip())
if do_transform:
transform.append(transforms.ToTensor())
if do_normalize:
transform.append(
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
self.transform = transforms.Compose(transform)
with open(attr_path) as f:
# discard the top line
f.readline()
self.df = pd.read_csv(f, delim_whitespace=True)
def pos_count(self, cls_name):
return (self.df[cls_name] == 1).sum()
def neg_count(self, cls_name):
return (self.df[cls_name] == -1).sum()
def __len__(self):
return len(self.df)
def __getitem__(self, index):
row = self.df.iloc[index]
img_name = row.name
img_idx, ext = img_name.split('.')
img = self.data[img_idx]
labels = [0] * len(self.id_to_cls)
for k, v in row.items():
labels[self.cls_to_id[k]] = int(v)
if self.transform is not None:
img = self.transform(img)
return {'img': img, 'index': index, 'labels': torch.tensor(labels)}
class Repeat(Dataset):
def __init__(self, dataset, new_len) -> None:
super().__init__()
self.dataset = dataset
self.original_len = len(dataset)
self.new_len = new_len
def __len__(self):
return self.new_len
def __getitem__(self, index):
index = index % self.original_len
return self.dataset[index]