-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.py
192 lines (133 loc) · 5.77 KB
/
test.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
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '3'
devicess = [0]
import time
import argparse
import numpy as np
import torch
from torch.utils.data import DataLoader
from torch import nn
from torchvision import transforms
import torch.distributed as dist
import math
import warnings
from tqdm import tqdm
from torchvision import utils
from hparams import hparams as hp
from torch.autograd import Variable
from tqdm import tqdm
warnings.filterwarnings("ignore")
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
from data_function import RefineData
weight_path_pytorch = 'pretrained/network-snapshot-020180.pt'
if hp.kind == 'mask':
mask_path = 'templates/mask'
elif hp.kind == 'glasses':
if hp.is_normal == True:
mask_path = 'templates/frame_glasses'
else:
mask_path = 'templates/glasses'
def parse_testing_args(parser):
"""
Parse commandline arguments.
"""
parser.add_argument('-o', '--output_dir', type=str, default=hp.output_dir, required=False, help='Directory to save checkpoints')
parser.add_argument('--latest-checkpoint-file', type=str, default='checkpoint_latest.pt', help='Store the latest checkpoint in each epoch')
# training
training = parser.add_argument_group('training setup')
training.add_argument('--epochs', type=int, default=500000, help='Number of total epochs to run')
training.add_argument('--epochs-per-checkpoint', type=int, default=10, help='Number of epochs per checkpoint')
training.add_argument('--sample', type=int, default=4, help='number of samples during training')
parser.add_argument(
'-k',
"--ckpt",
type=str,
default=None,
help="path to the checkpoints to resume training",
)
parser.add_argument("--init-lr", type=float, default=0.002, help="learning rate")
parser.add_argument(
"--wandb", action="store_true", help="use weights and biases logging"
)
parser.add_argument(
"--local_rank", type=int, default=0, help="local rank for distributed training"
)
training.add_argument('--amp-run', action='store_true', help='Enable AMP')
training.add_argument('--cudnn-enabled', default=True, help='Enable cudnn')
training.add_argument('--cudnn-benchmark', default=True, help='Run cudnn benchmark')
training.add_argument('--disable-uniform-initialize-bn-weight', action='store_true', help='disable uniform initialization of batchnorm layer weight')
return parser
def test():
parser = argparse.ArgumentParser(description='PyTorch Testing')
parser = parse_testing_args(parser)
args, _ = parser.parse_known_args()
args = parser.parse_args()
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.enabled = args.cudnn_enabled
torch.backends.cudnn.benchmark = args.cudnn_benchmark
os.makedirs(args.output_dir, exist_ok=True)
pwd = os.getcwd()
from model import Semantic_Fusion_Network
model = Semantic_Fusion_Network()
model = torch.nn.DataParallel(model, device_ids=devicess)
print("load model:", args.ckpt)
print(os.path.join(pwd, args.output_dir, args.latest_checkpoint_file))
ckpt = torch.load(os.path.join(pwd, args.output_dir, args.latest_checkpoint_file), map_location=lambda storage, loc: storage)
model.load_state_dict(ckpt["model"])
# torch.save({"model": model.state_dict()},os.path.join("checkpoint_xxx.pt"))
model.cuda()
normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
std=[0.5, 0.5, 0.5])
transform=transforms.Compose([
transforms.ToTensor(),
normalize
])
from pytorch_stylegan2.stylegan2_infer_pytorch import infer_face
class_generate = infer_face(weight_path_pytorch)
test_dataset = RefineData(class_generate, mask_path, transform)
test_loader = DataLoader(test_dataset,
batch_size=1,
shuffle=False,
pin_memory=False,
)
model.eval()
for i, batch in tqdm(enumerate(test_loader)):
if batch == ['error']:
continue
latent, face_image, mask_image, gt_dirs, canonical = batch
canonical = canonical.cuda()
gt_dir_repeat = gt_dirs.float()
gt_dir_repeat = gt_dir_repeat.unsqueeze(1).to(device)
latent = latent.unsqueeze(1)
latent = latent.repeat(1,14,1)
origins = class_generate.generate_from_synthesis(latent,None)
interfacegan_origins = class_generate.generate_from_synthesis(latent,gt_dir_repeat)
outputs = model(face_image, mask_image, canonical)
predict_images = class_generate.generate_from_synthesis(latent,outputs+gt_dir_repeat)
os.makedirs(os.path.join(pwd,args.output_dir,'predict_images'), exist_ok=True)
os.makedirs(os.path.join(pwd,args.output_dir,'origins'), exist_ok=True)
os.makedirs(os.path.join(pwd,args.output_dir,'interfacegan_origins'), exist_ok=True)
with torch.no_grad():
utils.save_image(
predict_images,
os.path.join(pwd,args.output_dir,'predict_images',f"{i:04d}.png"),
nrow=hp.row,
normalize=hp.norm,
range=hp.rangee,
)
utils.save_image(
origins,
os.path.join(pwd,args.output_dir,'origins',f"{i:04d}.png"),
nrow=hp.row,
normalize=hp.norm,
range=hp.rangee,
)
utils.save_image(
interfacegan_origins,
os.path.join(pwd,args.output_dir,'interfacegan_origins',f"{i:04d}.png"),
nrow=hp.row,
normalize=hp.norm,
range=hp.rangee,
)
if __name__ == '__main__':
test()