-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmain_diffuse.py
201 lines (158 loc) · 7.94 KB
/
main_diffuse.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
import os.path
import argparse
import cv2
import numpy as np
from styleGAN2_model.stylegan2_generator import StyleGAN2Generator
from classifier.src.feature_extractor.neck_mask_extractor import get_neck_mask, get_parsingNet
from classifier.classify import get_model, check_double_chin
#from interface.utils.myinverter import StyleGAN2Inverter
from CHINGER_inverter import StyleGAN2Inverter
import glob
import time
from utils import str2bool
'''
Data prepare:
For real images process, you should input `--data_dir PATH`,
put original real images in $PATH/origin, named `{name}.jpg`,
the corresponding wp latent code should be put in $PATH/code,
named `{name}_wp.npy`.
'''
def parse_args():
"""Parses arguments."""
parser = argparse.ArgumentParser(
description='Edit image synthesis with given semantic boundary.')
parser.add_argument('-i', '--data_dir', type=str, required=True,
help='If specified, will load latent codes from given ')
parser.add_argument('-b', '--boundary_path', type=str,
required=True,
help='Path to the semantic boundary. (required)')
parser.add_argument('--boundary_init_ratio', type=float, default=-4.0,
help='End point for manipulation in latent space. '
'(default: 3.0)')
parser.add_argument('--boundary_additional_ratio', type=float, default=-1.0,
help='End point for manipulation in latent space. '
'(default: 3.0)')
parser.add_argument('-s', '--latent_space_type', type=str, default='wp',
choices=['z', 'Z', 'w', 'W', 'wp', 'wP', 'Wp', 'WP'],
help='Latent space used in Style GAN. (default: `Z`)')
parser.add_argument('--learning_rate', type=float, default=0.01,
help='Learning rate for optimization. (default: 0.01)')
parser.add_argument('--num_iterations', type=int, default=100,
help='Number of optimization iterations. (default: 100)')
parser.add_argument('--loss_weight_feat', type=float, default=1e-4,
help='The perceptual loss scale for optimization. '
'(default: 5e-5)')
parser.add_argument('--gpu_id', type=str, default='0',
help='Which GPU(s) to use. (default: `0`)')
parser.add_argument("--cycle", type=str2bool, nargs='?',
const=False, default=False,
help="diffuse until no double chin.")
return parser.parse_args()
def mkdir(path):
if not os.path.exists(path):
os.mkdir(path)
def run():
model_name = 'stylegan2_ffhq'
args = parse_args()
latent_space_type = args.latent_space_type
assert os.path.exists(args.data_dir), f'data_dir {args.data_dir} dose not exist!'
origin_img_dir = os.path.join(args.data_dir, 'origin')
code_dir = os.path.join(args.data_dir, 'code')
diffuse_code_dir = os.path.join(args.data_dir, 'diffuse_code')
res_dir = os.path.join(args.data_dir, 'diffuse_res')
temp_dir = os.path.join(args.data_dir, 'temp')
assert os.path.exists(origin_img_dir), f'{origin_img_dir} dose not exist!'
assert os.path.exists(code_dir), f'data_dir {code_dir} dose not exist!'
mkdir(res_dir)
mkdir(temp_dir)
mkdir(diffuse_code_dir)
print(f'Initializing generator.')
model = StyleGAN2Generator(model_name, logger=None)
kwargs = {'latent_space_type': latent_space_type}
print(f'Initializing Inverter.')
inverter = StyleGAN2Inverter(
model_name,
learning_rate=args.learning_rate,
iteration=args.num_iterations,
reconstruction_loss_weight=1.0,
perceptual_loss_weight=args.loss_weight_feat,
logger=None,
stylegan2_model=model)
print(f'Preparing boundary.')
if not os.path.isfile(args.boundary_path):
raise ValueError(f'Boundary `{args.boundary_path}` does not exist!')
boundary = np.load(args.boundary_path)
print(f'Load latent codes and images from `{args.data_dir}`.')
latent_codes = []
origin_img_list = []
for img in glob.glob(os.path.join(origin_img_dir, '*.jpg'))[::-1]:
name = os.path.basename(img)[:6]
code_path = os.path.join(code_dir, f'{name}_wp.npy')
if os.path.exists(code_path):
latent_codes.append(code_path)
origin_img_list.append(img)
total_num = len(latent_codes)
print(f'Processing {total_num} samples.')
neckMaskNet = get_parsingNet()
double_chin_checker = get_model()
times = []
for img_index in range(total_num):
score = 1
image_name = os.path.splitext(os.path.basename(origin_img_list[img_index]))[0]
if os.path.exists(os.path.join(code_dir, f'{image_name}_inverted_wp.npy')):
continue
wps_latent = np.reshape(np.load(latent_codes[img_index]), (1, 18, 512))
origin_img = cv2.imread(origin_img_list[img_index])
neck_mask = get_neck_mask(img_path=origin_img, net=neckMaskNet)
neck_mask = (neck_mask > 0).astype(np.uint8) * 255
mask_dilate = cv2.dilate(neck_mask, kernel=np.ones((30, 30), np.uint8))
mask_dilate_blur = cv2.blur(mask_dilate, ksize=(35, 35))
mask_dilate_blur = neck_mask + (255 - neck_mask) // 255 * mask_dilate_blur
train_count = 0
diffuse_step = []
# invert_imgs=[]
ratio = args.boundary_init_ratio
while (score):
train_count += 1
edited_wps_latent = wps_latent + ratio * boundary
# wps_latents = np.concatenate([wps_latent,edited_wps_latent], axis=0)
edited_output = model.easy_style_mixing(latent_codes=edited_wps_latent,
style_range=range(7, 18),
style_codes=wps_latent,
mix_ratio=1.0, **kwargs)
edited_img = edited_output['image'][0][:, :, ::-1]
synthesis_image = origin_img * (1 - neck_mask // 255) + \
edited_img * (neck_mask // 255)
init_code = wps_latent
target_image = synthesis_image[:, :, ::-1]
start_diffuse = time.clock()
code, viz_result = inverter.easy_mask_diffuse(target=target_image,
init_code=init_code,
mask=mask_dilate_blur,
**kwargs)
time_diffuse = (time.clock() - start_diffuse)
times.append(time_diffuse)
viz_result = viz_result[:, :, ::-1]
# invert_imgs.append(viz_result)
res = origin_img * (1 - mask_dilate_blur / 255) + viz_result * (mask_dilate_blur / 255)
score = check_double_chin(img=res, model=double_chin_checker)
if score:
print('\n still exists double chin! continue....')
else:
print('\n double chin is removed')
wps_latent = code
ratio += args.boundary_additional_ratio
if not args.cycle or train_count >= 5:
break
#diffuse_step.append(np.concatenate([synthesis_image, res], axis=0))
print('train %d times.' % train_count)
np.save(os.path.join(diffuse_code_dir, f'{image_name}_inverted_wp.npy'), code)
#diffuse_step = np.concatenate(diffuse_step, axis=1)
# invert_imgs= np.concatenate(invert_imgs, axis=1)
cv2.imwrite(os.path.join(res_dir, f'{image_name}.jpg'), res)
# cv2.imwrite(os.path.join(res_dir, f'{image_name}_invert.jpg'), invert_imgs)
#cv2.imwrite(os.path.join(temp_dir, f'{image_name}_diffuse_step.jpg'), diffuse_step)
# print(times)
# print('train %d images using %f seconds, each image uses %f seconds'%(len(times),times,np.array(times)/len(times)))
if __name__ == '__main__':
run()