-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocessing.py
288 lines (223 loc) · 9.05 KB
/
processing.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
from utils import *
np.seterr(divide='ignore', invalid='ignore')
EPSILON = 1e-8
parser = argparse.ArgumentParser()
parser.add_argument("-trim", "--trim", type=bool, default=False)
parser.add_argument("-extract_images", "--extract_images", type=bool, default=False)
parser.add_argument("-extract_audio", "--extract_audio", type=bool, default=False)
parser.add_argument("-extract_image_kp", "--extract_image_kp", type=bool, default=False)
parser.add_argument("-extract_pca", "--extract_pca", type=bool, default=False)
parser.add_argument("-extract_audio_kp", "--extract_audio_kp", type=bool, default=False)
if __name__ == '__main__':
args = parser.parse_args()
if (args.trim):
inputFolder = 'videos/'
outputFolder = 'trimmed_videos/'
video_width = 456
if not(os.path.exists(outputFolder)):
# Create directory
subprocess.call('mkdir -p ' + outputFolder, shell=True)
for i in range(2, 21):
num = str(i).rjust(5, '0')
captions_filename = 'captions/'+ num +'.en.vtt'
inputfilename = inputFolder + num + '.mp4 '
captions = WebVTT().read(captions_filename)
print('Total Length of captions is', len(captions))
for idx, caption in enumerate(captions):
outputfilename = outputFolder + num + '-' + str(idx).rjust(3, '0') + '.mp4'
ss = caption.start
end = caption.end
t = int(round(get_sec(end) - get_sec(ss)))
print('index: ', idx, 'Text: ', caption.text, 'Time: ', t)
cmd = 'ffmpeg -i ' + inputfilename + '-vf scale='+ str(video_width) + ':256 ' + '-ss ' + str(ss) + ' -t ' + str(t) + ' -acodec copy ' + outputfilename
subprocess.call(cmd, shell=True)
if (args.extract_images):
inputFolder = 'trimmed_videos/'
outputFolder = 'images/'
if not(os.path.exists(outputFolder)):
# Create directory
subprocess.call('mkdir -p ' + outputFolder, shell=True)
filelist = sorted(glob(inputFolder+'/*.mp4'))
print('Length of filelist: ', len(filelist))
for idx, filename in tqdm(enumerate(filelist)):
num = filename[len(inputFolder):-len('.mp4')]
print('Num: ', num)
# Create this directory if it doesn't exist
if not(os.path.exists(outputFolder+num)):
# Create directory
subprocess.call('mkdir -p ' + outputFolder+num, shell=True)
# Create the images
cmd = 'ffmpeg -i ' + filename + ' -vf scale=-1:256 '+ outputFolder + num + '/$filename%05d' + '.bmp'
subprocess.call(cmd, shell=True)
# Cropping
imglist = sorted(glob( outputFolder + num + '/*.bmp'))
for i in range(len(imglist)):
img = cv2.imread(imglist[i])
x = int(np.floor((img.shape[1]-256)/2))
crop_img = img[0:256, x:x+256]
cv2.imwrite( imglist[i][0:-len('.bmp')] + '.jpeg', crop_img)
subprocess.call('rm -rf '+ outputFolder + num + '/*.bmp', shell=True)
if (args.extract_audio):
inputFolder = 'trimmed_videos/'
outputFolder = 'audios/'
if not(os.path.exists(outputFolder)):
# Create directory
subprocess.call('mkdir -p ' + outputFolder, shell=True)
filelist = sorted(glob(inputFolder+'/*.mp4'))
for file in filelist:
cmd = 'ffmpeg -i ' + file + ' -ab 160k -ac 1 -ar 16000 -vn ' + outputFolder + file[len(inputFolder): -len('.mp4')] + '.wav'
subprocess.call(cmd, shell=True)
if (args.extract_image_kp):
inputFolder = 'images/'
outputFolder = 'image_kp_raw/'
resumeFrom = 0
if not(os.path.exists(outputFolder)):
# Create directory
subprocess.call('mkdir -p ' + outputFolder, shell=True)
directories = sorted(glob(inputFolder+'*/'))
d = {}
for idx, directory in tqdm(enumerate(directories[resumeFrom:])):
key = directory[len(inputFolder):-1]
imglist = sorted(glob(directory+'*.jpeg'))
big_list = []
for file in tqdm(imglist):
keypoints = get_facial_landmarks(file)
if not (keypoints.shape[0] == 1): # if there are some kp then
l = getKeypointFeatures(keypoints)
unit_kp, N, tilt, mean = l[0], l[1], l[2], l[3]
kp_mouth = unit_kp[48:68]
store_list = [kp_mouth, N, tilt, mean, unit_kp, keypoints]
prev_store_list = store_list
big_list.append(store_list)
else:
big_list.append(prev_store_list)
d[key] = big_list
saveFilename = outputFolder + 'kp' + str(idx+resumeFrom+1) + '.pickle'
oldSaveFilename = outputFolder + 'kp' + str(idx+resumeFrom-2) + '.pickle'
if not (os.path.exists(saveFilename)):
with open(saveFilename, "wb") as output_file:
pkl.dump(d, output_file)
print('Saved output for ', (idx+resumeFrom+1), ' file.')
else:
# Resume
with open(saveFilename, "rb") as output_file:
d = pkl.load(output_file)
print('Loaded output for ', (idx+resumeFrom+1), ' file.')
# Keep removing stale versions of the files
if (os.path.exists(oldSaveFilename)):
cmd = 'rm -rf ' + oldSaveFilename
subprocess.call(cmd, shell=True)
if (args.extract_audio_kp):
inputFolder = 'audios/'
outputFolder = 'audio_kp/'
resumeFrom = 0
frame_rate = 5
kp_type = 'mel'
if not(os.path.exists(outputFolder)):
# Create directory
subprocess.call('mkdir -p ' + outputFolder, shell=True)
filelist = sorted(glob(inputFolder+'*.wav'))
d = {}
for idx, file in enumerate(tqdm(filelist[resumeFrom:])):
key = file[len(inputFolder):-len('.wav')]
if(kp_type == 'world'):
x, fs = sf.read(file)
# 2-1 Without F0 refinement
f0, t = pw.dio(x, fs, f0_floor=50.0, f0_ceil=600.0,
channels_in_octave=2,
frame_period=frame_rate,
speed=1.0)
sp = pw.cheaptrick(x, f0, t, fs)
ap = pw.d4c(x, f0, t, fs)
features = np.hstack((f0.reshape((-1, 1)), np.hstack((sp, ap))))
elif (kp_type == 'mel'):
(rate, sig) = wav.read(file)
features = logfbank(sig,rate)
d[key] = features
saveFilename = outputFolder + 'audio_kp' + str(idx+resumeFrom+1) + '_' + kp_type + '.pickle'
oldSaveFilename = outputFolder + 'audio_kp' + str(idx+resumeFrom-2) + '_' + kp_type + '.pickle'
if not (os.path.exists(saveFilename)):
with open(saveFilename, "wb") as output_file:
pkl.dump(d, output_file)
# print('Saved output for', (idx+resumeFrom+1), 'file.')
else:
# Resume
with open(saveFilename, "rb") as output_file:
d = pkl.load(output_file)
print('Loaded output for ', (idx+resumeFrom+1), ' file.')
# Keep removing stale versions of the files
if (os.path.exists(oldSaveFilename)):
cmd = 'rm -rf ' + oldSaveFilename
subprocess.call(cmd, shell=True)
print('Saved Everything')
if (args.extract_pca):
inputFolder = 'image_kp_raw/'
outputFolder = 'pca/'
numOfFiles = 1414 # First 33 videos
new_list = []
filename = inputFolder + 'kp' + str(numOfFiles) + '.pickle'
if not(os.path.exists(outputFolder)):
# Create directory
subprocess.call('mkdir -p ' + outputFolder, shell=True)
if (os.path.exists(filename)):
with open(filename, 'rb') as file:
big_list = pkl.load(file)
print('Keypoints file loaded')
else:
print('Input keypoints not found')
sys.exit(0)
print('Unwrapping all items from the big list')
for key in tqdm(sorted(big_list.keys())):
for frame_kp in big_list[key]:
kp_mouth = frame_kp[0]
x = kp_mouth[:, 0].reshape((1, -1))
y = kp_mouth[:, 1].reshape((1, -1))
X = np.hstack((x, y)).reshape((-1)).tolist()
new_list.append(X)
X = np.array(new_list)
pca = PCA(n_components=8)
pca.fit(X)
with open(outputFolder + 'pca' + str(numOfFiles) + '.pickle', 'wb') as file:
pkl.dump(pca, file)
with open(outputFolder + 'explanation' + str(numOfFiles) + '.pickle', 'wb') as file:
pkl.dump(pca.explained_variance_ratio_, file)
print('Explanation for each dimension:', pca.explained_variance_ratio_)
print('Total variance explained:', 100*sum(pca.explained_variance_ratio_))
print('')
print('Upsampling...')
# Upsample the lip keypoints
upsampled_kp = {}
for key in tqdm(sorted(big_list.keys())):
# print('Key:', key)
nFrames = len(big_list[key])
factor = int(np.ceil(100/29.97))
# Create the matrix
new_unit_kp = np.zeros((int(factor*nFrames), big_list[key][0][0].shape[0], big_list[key][0][0].shape[1]))
new_kp = np.zeros((int(factor*nFrames), big_list[key][0][-1].shape[0], big_list[key][0][-1].shape[1]))
# print('Shape of new_unit_kp:', new_unit_kp.shape, 'new_kp:', new_kp.shape)
for idx, frame in enumerate(big_list[key]):
# Create two lists, one with original keypoints, other with unit keypoints
new_kp[(idx*(factor)), :, :] = frame[-1]
new_unit_kp[(idx*(factor)), :, :] = frame[0]
if (idx > 0):
start = (idx-1)*factor + 1
end = idx*factor
for j in range(start, end):
new_kp[j, :, :] = new_kp[start-1, :, :] + ((new_kp[end, :, :] - new_kp[start-1, :, :])*(np.float(j+1-start)/np.float(factor)))
# print('')
l = getKeypointFeatures(new_kp[j, :, :])
# print('')
new_unit_kp[j, :, :] = l[0][48:68, :]
upsampled_kp[key] = new_unit_kp
# Use PCA to de-correlate the points
d = {}
keys = sorted(upsampled_kp.keys())
for key in tqdm(keys):
x = upsampled_kp[key][:, :, 0]
y = upsampled_kp[key][:, :, 1]
X = np.hstack((x, y))
X_trans = pca.transform(X)
d[key] = X_trans
with open(outputFolder + 'pkp' + str(numOfFiles) + '.pickle', 'wb') as file:
pkl.dump(d, file)
print('Saved Everything')