-
Notifications
You must be signed in to change notification settings - Fork 8
/
inference.py
215 lines (172 loc) · 9.96 KB
/
inference.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
from dataset.video_data import get_deca_tform
from PIL import Image
from models.cvthead import CVTHead
import face_alignment
from skimage.transform import estimate_transform, warp, resize, rescale
import torch
import torch.optim as optim
from torch.optim.lr_scheduler import MultiStepLR
import numpy as np
import os
import argparse
import yaml
import pickle
import logging
def preprocess_image(img_pth, fa, device="cuda"):
img = Image.open(img_pth)
img = img.resize((256, 256))
img_npy = np.array(img) # (H=256,W=256,3), val:0-255
img_npy = img_npy[:, :, :3]
landmark = fa.get_landmarks(img_npy)[0]
tform = get_deca_tform(landmark) # (3,3)
img_npy = img_npy / 255. # (H,W,3), val: 0-1
crop_image = warp(img_npy, tform.inverse, output_shape=(224, 224)) # (224, 224, 3), val:[0, 1]
img_tensor = torch.from_numpy(img_npy).float() # tensor, (H, W, 3), val: [0, 1]
img_tensor = img_tensor.permute(2, 0, 1) # (H, W, 3) --> (3, H, W)
img_tensor = (img_tensor - 0.5) / 0.5 # (3,H,W), [-1, 1]
crop_image = torch.tensor(np.asarray(crop_image)).float() # (224, 224, 3), val:0-1
crop_image = crop_image.permute(2, 0, 1) # (3, 224, 224), val:0-1
tform = torch.tensor(np.asarray(tform)).float() # (3,3)
img_tensor = img_tensor.unsqueeze(0).to(device) # (1,3,256,256)
crop_image = crop_image.unsqueeze(0).to(device) # (1,3,224,224)
tform = tform.unsqueeze(0).to(device) # (1,3,3)
return img_tensor, crop_image, tform
def driven_by_face(model, src_pth, drv_pth, out_pth, device, softmask=True):
# face landmark detector
fa = face_alignment.FaceAlignment(face_alignment.LandmarksType.TWO_D, device=device)
src_img, src_img_crop, src_tform = preprocess_image(src_pth, fa, device)
drv_img, drv_img_crop, drv_tform = preprocess_image(drv_pth, fa, device)
with torch.no_grad():
outputs = model(src_img_crop, drv_img_crop, src_img, drv_img, src_tform, drv_tform, is_train=False, is_cross_id=True)
predict_img = outputs["pred_drv_img"] # (1,3,256,256), tensor, val:[-1,1]
predict_mask = outputs["pred_drv_mask"] # (1,256,256), tensor, val:[0, 1], soft mask
# visualize
predict_img = 0.5 * (predict_img + 1)
predict_img = predict_img[0].permute(1,2,0).cpu().numpy() # (256,256,3), npy
predict_mask = predict_mask[0].permute(1,2,0).cpu().numpy() # (256,256,1), npy
if not softmask:
predict_mask = (predict_mask > 0.6).float() # (256,256,1), npy
# apply mask
predict_img = predict_img * predict_mask + (1 - predict_mask) # apply mask to predicted image, val:[0, 1], npy
predict_img = (predict_img * 255).astype(np.uint8)
predict_img = Image.fromarray(predict_img)
predict_img.save(out_pth)
def driven_by_flame_coefs(model, src_pth, out_pth, device, softmask=False):
# face landmark detector
fa = face_alignment.FaceAlignment(face_alignment.LandmarksType.TWO_D, device=device)
src_img, src_img_crop, src_tform = preprocess_image(src_pth, fa, device)
with torch.no_grad():
pose = torch.zeros(1, 6).to(src_img.device) # (1, 6) rotation (3) + jaw pose (3)
# ######################### shape ###############################
frames = []
for i in range(10):
shape = torch.zeros(1, 100).to(src_img.device) # (1, 100)
shape[0, 0] = 2 * i / 10
outputs = model.flame_coef_generation(src_img_crop, src_img, src_tform, shape=shape, pose=pose)
predict_img = outputs["pred_drv_img"] # (1,3,256,256), tensor, val:[-1,1]
predict_mask = outputs["pred_drv_mask"] # (1,256,256), tensor, val:[0, 1], soft mask
# visualize
predict_img = 0.5 * (predict_img + 1)
predict_img = predict_img[0].permute(1,2,0).cpu().numpy() # (256,256,3), npy
predict_mask = predict_mask[0].permute(1,2,0).cpu().numpy() # (256,256,1), npy
if not softmask:
predict_mask = (predict_mask > 0.6) + 0.0 # (256,256,1), npy
# apply mask
predict_img = predict_img * predict_mask + (1 - predict_mask) # apply mask to predicted image, val:[0, 1], npy
predict_img = (predict_img * 255).astype(np.uint8)
predict_img = Image.fromarray(predict_img)
frames.append(predict_img)
# predict_img.save("examples/shape_{}.png".format(i))
frame_one = frames[0]
out_name = os.path.join(out_pth, "shape.gif")
frame_one.save(out_name, format="GIF", append_images=frames, save_all=True, duration=200, loop=0)
# ######################### exp ###############################
frames = []
for i in range(10):
exp = torch.zeros(1, 100).to(src_img.device) # (1, 100)
exp[0, 0] = 2 * i / 10
outputs = model.flame_coef_generation(src_img_crop, src_img, src_tform, exp=exp, pose=pose)
predict_img = outputs["pred_drv_img"] # (1,3,256,256), tensor, val:[-1,1]
predict_mask = outputs["pred_drv_mask"] # (1,256,256), tensor, val:[0, 1], soft mask
# visualize
predict_img = 0.5 * (predict_img + 1)
predict_img = predict_img[0].permute(1,2,0).cpu().numpy() # (256,256,3), npy
predict_mask = predict_mask[0].permute(1,2,0).cpu().numpy() # (256,256,1), npy
if not softmask:
predict_mask = (predict_mask > 0.6) + 0.0 # (256,256,1), npy
# apply mask
predict_img = predict_img * predict_mask + (1 - predict_mask) # apply mask to predicted image, val:[0, 1], npy
predict_img = (predict_img * 255).astype(np.uint8)
predict_img = Image.fromarray(predict_img)
frames.append(predict_img)
# predict_img.save("examples/exp_{}.png".format(i))
frame_one = frames[0]
out_name = os.path.join(out_pth, "exp.gif")
frame_one.save(out_name, format="GIF", append_images=frames, save_all=True, duration=200, loop=0)
# ######################### view ###############################
frames = []
for i in range(12):
pose = torch.zeros(1, 6).to(src_img.device) # (1, 100)
pose[0, 1] = - np.pi / 4 + i * np.pi / 24
outputs = model.flame_coef_generation(src_img_crop, src_img, src_tform, pose=pose)
predict_img = outputs["pred_drv_img"] # (1,3,256,256), tensor, val:[-1,1]
predict_mask = outputs["pred_drv_mask"] # (1,256,256), tensor, val:[0, 1], soft mask
# visualize
predict_img = 0.5 * (predict_img + 1)
predict_img = predict_img[0].permute(1,2,0).cpu().numpy() # (256,256,3), npy
predict_mask = predict_mask[0].permute(1,2,0).cpu().numpy() # (256,256,1), npy
if not softmask:
predict_mask = (predict_mask > 0.6) + 0.0 # (256,256,1), npy
# apply mask
predict_img = predict_img * predict_mask + (1 - predict_mask) # apply mask to predicted image, val:[0, 1], npy
predict_img = (predict_img * 255).astype(np.uint8)
predict_img = Image.fromarray(predict_img)
frames.append(predict_img)
frame_one = frames[0]
out_name = os.path.join(out_pth, "pose.gif")
frame_one.save(out_name, format="GIF", append_images=frames, save_all=True, duration=200, loop=0)
# ######################### Jaw pose ###############################
frames = []
for i in range(12):
pose = torch.zeros(1, 6).to(src_img.device) # (1, 100)
pose[0, 3] = 0.5 * i / 12
outputs = model.flame_coef_generation(src_img_crop, src_img, src_tform, pose=pose)
predict_img = outputs["pred_drv_img"] # (1,3,256,256), tensor, val:[-1,1]
predict_mask = outputs["pred_drv_mask"] # (1,256,256), tensor, val:[0, 1], soft mask
# visualize
predict_img = 0.5 * (predict_img + 1)
predict_img = predict_img[0].permute(1,2,0).cpu().numpy() # (256,256,3), npy
predict_mask = predict_mask[0].permute(1,2,0).cpu().numpy() # (256,256,1), npy
if not softmask:
predict_mask = (predict_mask > 0.6) + 0.0 # (256,256,1), npy
# apply mask
predict_img = predict_img * predict_mask + (1 - predict_mask) # apply mask to predicted image, val:[0, 1], npy
predict_img = (predict_img * 255).astype(np.uint8)
predict_img = Image.fromarray(predict_img)
frames.append(predict_img)
frame_one = frames[0]
out_name = os.path.join(out_pth, "jaw.gif")
frame_one.save(out_name, format="GIF", append_images=frames, save_all=True, duration=200, loop=0)
def main(args):
device = "cuda"
# >>>>>>>>>>>>>>>>> Model >>>>>>>>>>>>>>>>>
model = CVTHead() # cpu model
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)
model = model.to(device) # gpu model
# load pre-trained weights
ckpt = torch.load(args.ckpt_pth, map_location="cpu")["model"]
model.load_state_dict(ckpt, strict=False)
print(f'-- Number of parameters (G): {sum(p.numel() for p in model.parameters())/1e6} M\n')
if args.flame:
driven_by_flame_coefs(model, args.src_pth, args.out_pth, device, softmask=True)
else:
driven_by_face(model, args.src_pth, args.drv_pth, args.out_pth, device, softmask=True)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='CVTHead Inference')
parser.add_argument('--src_pth', type=str, default="examples/1.png")
parser.add_argument('--drv_pth', type=str, default="examples/2.png")
parser.add_argument('--out_pth', type=str, default="examples/output.png")
parser.add_argument('--ckpt_pth', type=str, default="data/cvthead.pt")
parser.add_argument('--flame', action='store_true')
args = parser.parse_args()
main(args)