-
Notifications
You must be signed in to change notification settings - Fork 40
/
step1_generate_data.py
159 lines (124 loc) · 5.74 KB
/
step1_generate_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
"""
Data Preparation.
Generate datasets for training
"""
import os.path
import argparse
from collections import defaultdict
import cv2
import numpy as np
from tqdm import tqdm
from styleGAN2_ada_model.stylegan2_ada_generator import StyleGAN2adaGenerator
from classifier.classify import get_model, check_hair, check_gender
def parse_args():
"""Parses arguments."""
parser = argparse.ArgumentParser(
description='Generate images using StyleGAN2-ada model.')
parser.add_argument('--dataset_name', type=str, required=True,
help='Dateset name. (required)')
parser.add_argument('--num', type=int, default=20000,
help='Number of images to generate.')
parser.add_argument('--truncation_psi', type=float, default='0.8')
parser.add_argument("--bald_only",
help="if set, Only generate bald images",
action="store_true")
parser.add_argument("--add_noise",
help="If set, add noise to wp latent code .",
action="store_true")
parser.add_argument("--save_StyleSpace",
help="If set, save latent code in StyleSpace.",
action="store_true")
return parser.parse_args()
def main():
"""Main function."""
args = parse_args()
model_name = 'stylegan2_ada'
dataset_path = './training_runs/dataset'
output_dir = os.path.join(dataset_path, args.dataset_name)
os.makedirs(output_dir, exist_ok=True)
print(f'============= Dataset will be saved to {output_dir} =============')
print(f'Initializing attribute classifier.')
hair_checker = get_model(attribuite='hair')
gender_checker = get_model(attribuite='gender')
print(f'Initializing generator.')
model = StyleGAN2adaGenerator(model_name, logger=None, truncation_psi=args.truncation_psi)
kwargs = {'latent_space_type': 'z'}
print(f'Sample latent codes randomly from Z latent space.')
latent_codes = model.easy_sample(args.num, **kwargs)
print(f'Generating {args.num} samples.')
results = defaultdict(list)
pbar = tqdm(total=args.num, leave=False)
hair_scores = []
gender_scores = []
for latent_codes_batch in model.get_batch_inputs(latent_codes):
outputs = model.easy_synthesize(latent_codes_batch,
**kwargs,
generate_style=False,
generate_image=True,
add_noise=args.add_noise)
if args.bald_only:
choose = []
key = 'image'
val = outputs[key]
for image in val:
hair_score = check_hair(img=image[:, :, ::-1], model=hair_checker)
gender_score = check_gender(img=image[:, :, ::-1], model=gender_checker)
if (hair_score == 0):
choose.append(True)
hair_scores.append(hair_score)
gender_scores.append(gender_score)
save_path = os.path.join(output_dir, f'{pbar.n:06d}.jpg')
cv2.imwrite(save_path, image[:, :, ::-1])
else:
choose.append(False)
pbar.update(1)
for key, val in outputs.items():
if not key == 'image':
if choose[0]:
results[key].append(val)
else:
for key, val in outputs.items():
if key == 'image':
for image in val:
save_path = os.path.join(output_dir, f'{pbar.n:06d}.jpg')
cv2.imwrite(save_path, image[:, :, ::-1])
hair_score = check_hair(img=image[:, :, ::-1], model=hair_checker)
gender_score = check_gender(img=image[:, :, ::-1], model=gender_checker)
gender_scores.append(gender_score)
hair_scores.append(hair_score)
else:
results[key].append(val)
pbar.update(1)
pbar.close()
print(f'Saving results.')
for key, val in results.items():
if key == 's' and args.save_StyleSpace:
'''
Save the StyleSpace latent codes
'''
for s_i in range(26):
save_path = os.path.join(output_dir, f'{key}_{s_i}.npy')
s_latent = np.concatenate([v[s_i] for v in val], axis=0)
np.save(save_path, s_latent)
s_mean = s_latent.mean(axis=0)
s_std = s_latent.std(axis=0)
mean_save_path = os.path.join(output_dir, f'{key}_{s_i}_mean.npy')
std_save_path = os.path.join(output_dir, f'{key}_{s_i}_std.npy')
np.save(mean_save_path, s_mean)
np.save(std_save_path, s_std)
if key != 's':
save_path = os.path.join(output_dir, f'{key}.npy')
np.save(save_path, np.concatenate(val, axis=0))
score_save_path = os.path.join(output_dir, 'hair_scores.npy')
hair_scores_array = np.array(hair_scores)[:, np.newaxis]
np.save(score_save_path, hair_scores_array)
score_save_path = os.path.join(output_dir, 'gender_scores.npy')
gender_scores_array = np.array(gender_scores)[:, np.newaxis]
np.save(score_save_path, gender_scores_array)
print(
f'============= {np.sum(hair_scores_array)} images with hair, {args.num - np.sum(hair_scores_array)} images without hair =============')
print(
f'============= {np.sum(gender_scores_array)} male images, {args.num - np.sum(gender_scores_array)} female images =============')
print(f'============= Done =============')
if __name__ == '__main__':
main()