forked from ariesiitr/Lip-Sync-STS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinference.py
188 lines (144 loc) · 5.4 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
from os import listdir, path
import numpy as np
import scipy, cv2, os, sys, argparse, audio
import dlib, json, h5py, subprocess
from tqdm import tqdm
from keras.callbacks import ModelCheckpoint
from keras.models import Model
args = parser.parse_args()
args.img_size = 96
if args.face.split('.')[1] in ['jpg', 'png', 'jpeg']:
args.static = True
def rect_to_bb(d):
x = d.rect.left()
y = d.rect.top()
w = d.rect.right() - x
h = d.rect.bottom() - y
return (x, y, w, h)
def calcMaxArea(rects):
max_cords = (-1,-1,-1,-1)
max_area = 0
max_rect = None
for i in range(len(rects)):
cur_rect = rects[i]
(x,y,w,h) = rect_to_bb(cur_rect)
if w*h > max_area:
max_area = w*h
max_cords = (x,y,w,h)
max_rect = cur_rect
return max_cords, max_rect
def face_detect(images):
detector = dlib.cnn_face_detection_model_v1(args.face_det_checkpoint)
batch_size = args.face_det_batch_size
predictions = []
for i in tqdm(range(0, len(images), batch_size)):
predictions.extend(detector(images[i:i + batch_size]))
results = []
pady1, pady2, padx1, padx2 = args.pads
for rects, image in zip(predictions, images):
(x, y, w, h), max_rect = calcMaxArea(rects)
if x == -1:
results.append([None, (-1,-1,-1,-1), False])
continue
y1 = max(0, y + pady1)
y2 = min(image.shape[0], y + h + pady2)
x1 = max(0, x + padx1)
x2 = min(image.shape[1], x + w + padx2)
face = image[y1:y2, x1:x2, ::-1] # RGB ---> BGR
results.append([face, (y1, y2, x1, x2), True])
del detector
return results
def datagen(frames, mels):
img_batch, mel_batch, frame_batch, coords_batch = [], [], [], []
if not args.static:
face_det_results = face_detect([f[...,::-1] for f in frames]) # BGR2RGB for CNN face detection
else:
face_det_results = face_detect([frames[0][...,::-1]])
for i, m in enumerate(mels):
idx = 0 if args.static else i%len(frames)
frame_to_save = frames[idx].copy()
face, coords, valid_frame = face_det_results[idx].copy()
if not valid_frame:
print ("Face not detected, skipping frame {}".format(i))
continue
face = cv2.resize(face, (args.img_size, args.img_size))
img_batch.append(face)
mel_batch.append(m)
frame_batch.append(frame_to_save)
coords_batch.append(coords)
if len(img_batch) >= args.lipgan_batch_size:
img_batch, mel_batch = np.asarray(img_batch), np.asarray(mel_batch)
img_masked = img_batch.copy()
img_masked[:, args.img_size//2:] = 0
img_batch = np.concatenate((img_batch, img_masked), axis=3) / 255.
mel_batch = np.reshape(mel_batch, [len(mel_batch), mel_batch.shape[1], mel_batch.shape[2], 1])
yield img_batch, mel_batch, frame_batch, coords_batch
img_batch, mel_batch, frame_batch, coords_batch = [], [], [], []
if len(img_batch) > 0:
img_batch, mel_batch = np.asarray(img_batch), np.asarray(mel_batch)
img_masked = img_batch.copy()
img_masked[:, args.img_size//2:] = 0
img_batch = np.concatenate((img_batch, img_masked), axis=3) / 255.
mel_batch = np.reshape(mel_batch, [len(mel_batch), mel_batch.shape[1], mel_batch.shape[2], 1])
yield img_batch, mel_batch, frame_batch, coords_batch
fps = args.fps
mel_step_size = 27
mel_idx_multiplier = 80./fps
if args.model == 'residual':
from generator import create_model_residual as create_model
else:
from generator import create_model as create_model
def main():
if args.face.split('.')[1] in ['jpg', 'png', 'jpeg']:
full_frames = [cv2.imread(args.face)]
else:
video_stream = cv2.VideoCapture(args.face)
full_frames = []
while 1:
still_reading, frame = video_stream.read()
if not still_reading:
video_stream.release()
break
full_frames.append(frame)
if len(full_frames) % 2000 == 0: print(len(full_frames))
if len(full_frames) * (1./fps) >= args.max_sec: break
print ("Number of frames available for inference: "+str(len(full_frames)))
wav = audio.load_wav(args.audio, 16000)
mel = audio.melspectrogram(wav)
print(mel.shape)
if np.isnan(mel.reshape(-1)).sum() > 0:
raise ValueError('Mel contains nan!')
mel_chunks = []
i = 0
while 1:
start_idx = int(i * mel_idx_multiplier)
if start_idx + mel_step_size > len(mel[0]):
break
mel_chunks.append(mel[:, start_idx : start_idx + mel_step_size])
i += 1
print("Length of mel chunks: {}".format(len(mel_chunks)))
batch_size = args.lipgan_batch_size
gen = datagen(full_frames.copy(), mel_chunks)
for i, (img_batch, mel_batch, frames, coords) in enumerate(tqdm(gen,
total=int(np.ceil(float(len(mel_chunks))/batch_size)))):
if i == 0:
model = create_model(args, mel_step_size)
print ("Model Created")
model.load_weights(args.checkpoint_path)
print ("Model loaded")
frame_h, frame_w = full_frames[0].shape[:-1]
out = cv2.VideoWriter(path.join(args.results_dir, 'result.avi'),
cv2.VideoWriter_fourcc(*'DIVX'), fps, (frame_w, frame_h))
pred = model.predict([img_batch, mel_batch])
pred = pred * 255
for p, f, c in zip(pred, frames, coords):
y1, y2, x1, x2 = c
p = cv2.resize(p, (x2 - x1, y2 - y1))
f[y1:y2, x1:x2] = p
out.write(f)
out.release()
command = 'ffmpeg -i {} -i {} -strict -2 -q:v 1 {}'.format(args.audio, path.join(args.results_dir, 'result.avi'),
path.join(args.results_dir, 'result_voice.avi'))
subprocess.call(command, shell=True)
if __name__ == '__main__':
main()