-
Notifications
You must be signed in to change notification settings - Fork 62
/
data.py
174 lines (150 loc) · 6.97 KB
/
data.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
# Copyright (C) 2018 Elvis Yu-Jing Lin <[email protected]>
#
# This work is licensed under the MIT License. To view a copy of this license,
# visit https://opensource.org/licenses/MIT.
"""Custom datasets for CelebA and CelebA-HQ."""
import numpy as np
import os
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from PIL import Image
class Custom(data.Dataset):
def __init__(self, data_path, attr_path, image_size, selected_attrs):
self.data_path = data_path
att_list = open(attr_path, 'r', encoding='utf-8').readlines()[1].split()
atts = [att_list.index(att) + 1 for att in selected_attrs]
self.images = np.loadtxt(attr_path, skiprows=2, usecols=[0], dtype=np.str)
self.labels = np.loadtxt(attr_path, skiprows=2, usecols=atts, dtype=np.int)
self.tf = transforms.Compose([
transforms.Resize(image_size),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
def __getitem__(self, index):
img = self.tf(Image.open(os.path.join(self.data_path, self.images[index])))
att = torch.tensor((self.labels[index] + 1) // 2)
return img, att
def __len__(self):
return len(self.images)
class CelebA(data.Dataset):
def __init__(self, data_path, attr_path, image_size, mode, selected_attrs):
super(CelebA, self).__init__()
self.data_path = data_path
att_list = open(attr_path, 'r', encoding='utf-8').readlines()[1].split()
atts = [att_list.index(att) + 1 for att in selected_attrs]
images = np.loadtxt(attr_path, skiprows=2, usecols=[0], dtype=np.str)
labels = np.loadtxt(attr_path, skiprows=2, usecols=atts, dtype=np.int)
if mode == 'train':
self.images = images[:182000]
self.labels = labels[:182000]
if mode == 'valid':
self.images = images[182000:182637]
self.labels = labels[182000:182637]
if mode == 'test':
self.images = images[182637:]
self.labels = labels[182637:]
self.tf = transforms.Compose([
transforms.CenterCrop(170),
transforms.Resize(image_size),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
self.length = len(self.images)
def __getitem__(self, index):
img = self.tf(Image.open(os.path.join(self.data_path, self.images[index])))
att = torch.tensor((self.labels[index] + 1) // 2)
return img, att
def __len__(self):
return self.length
class CelebA_HQ(data.Dataset):
def __init__(self, data_path, attr_path, image_list_path, image_size, mode, selected_attrs):
super(CelebA_HQ, self).__init__()
self.data_path = data_path
att_list = open(attr_path, 'r', encoding='utf-8').readlines()[1].split()
atts = [att_list.index(att) + 1 for att in selected_attrs]
orig_images = np.loadtxt(attr_path, skiprows=2, usecols=[0], dtype=np.str)
orig_labels = np.loadtxt(attr_path, skiprows=2, usecols=atts, dtype=np.int)
indices = np.loadtxt(image_list_path, skiprows=1, usecols=[1], dtype=np.int)
images = ['{:d}.jpg'.format(i) for i in range(30000)]
labels = orig_labels[indices]
if mode == 'train':
self.images = images[:28000]
self.labels = labels[:28000]
if mode == 'valid':
self.images = images[28000:28500]
self.labels = labels[28000:28500]
if mode == 'test':
self.images = images[28500:]
self.labels = labels[28500:]
self.tf = transforms.Compose([
transforms.Resize(image_size),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
self.length = len(self.images)
def __getitem__(self, index):
img = self.tf(Image.open(os.path.join(self.data_path, self.images[index])))
att = torch.tensor((self.labels[index] + 1) // 2)
return img, att
def __len__(self):
return self.length
def check_attribute_conflict(att_batch, att_name, att_names):
def _get(att, att_name):
if att_name in att_names:
return att[att_names.index(att_name)]
return None
def _set(att, value, att_name):
if att_name in att_names:
att[att_names.index(att_name)] = value
att_id = att_names.index(att_name)
for att in att_batch:
if att_name in ['Bald', 'Receding_Hairline'] and att[att_id] != 0:
if _get(att, 'Bangs') != 0:
_set(att, 1-att[att_id], 'Bangs')
elif att_name == 'Bangs' and att[att_id] != 0:
for n in ['Bald', 'Receding_Hairline']:
if _get(att, n) != 0:
_set(att, 1-att[att_id], n)
_set(att, 1-att[att_id], n)
elif att_name in ['Black_Hair', 'Blond_Hair', 'Brown_Hair', 'Gray_Hair'] and att[att_id] != 0:
for n in ['Black_Hair', 'Blond_Hair', 'Brown_Hair', 'Gray_Hair']:
if n != att_name and _get(att, n) != 0:
_set(att, 1-att[att_id], n)
elif att_name in ['Straight_Hair', 'Wavy_Hair'] and att[att_id] != 0:
for n in ['Straight_Hair', 'Wavy_Hair']:
if n != att_name and _get(att, n) != 0:
_set(att, 1-att[att_id], n)
elif att_name in ['Mustache', 'No_Beard'] and att[att_id] != 0:
for n in ['Mustache', 'No_Beard']:
if n != att_name and _get(att, n) != 0:
_set(att, 1-att[att_id], n)
return att_batch
if __name__ == '__main__':
import argparse
import matplotlib.pyplot as plt
import torchvision.utils as vutils
attrs_default = [
'Bald', 'Bangs', 'Black_Hair', 'Blond_Hair', 'Brown_Hair', 'Bushy_Eyebrows',
'Eyeglasses', 'Male', 'Mouth_Slightly_Open', 'Mustache', 'No_Beard', 'Pale_Skin', 'Young'
]
parser = argparse.ArgumentParser()
parser.add_argument('--attrs', dest='attrs', default=attrs_default, nargs='+', help='attributes to test')
parser.add_argument('--data_path', dest='data_path', type=str, required=True)
parser.add_argument('--attr_path', dest='attr_path', type=str, required=True)
args = parser.parse_args()
dataset = CelebA(args.data_path, args.attr_path, 128, 'valid', args.attrs)
dataloader = data.DataLoader(
dataset, batch_size=64, shuffle=False, drop_last=False
)
print('Attributes:')
print(args.attrs)
for x, y in dataloader:
vutils.save_image(x, 'test.png', nrow=8, normalize=True, value_range=(-1., 1.))
print(y)
break
del x, y
dataset = CelebA(args.data_path, args.attr_path, 128, 'valid', args.attrs)
dataloader = data.DataLoader(
dataset, batch_size=16, shuffle=False, drop_last=False
)