initial commit

This commit is contained in:
Sen Liang committed 2022-01-21 17:42:41 +08:00
commit c7175dd7ff
127 files changed
+13949

No files matched your search

+102
View File
@@ -0,0 +1,102 @@
import os
import cv2
from pathlib import Path
import shutil
# UNZIP_FILES = False
MV_VIDEO_FILES = False
# RESAMPLE_FPS = True
# RESAMPLE_RATE = False
if __name__ == '__main__':
path_root = Path("/mnt/data2/DATA/LRW/")
if MV_VIDEO_FILES:
path_data = path_root.joinpath("lipread_mp4")
v_ids = sorted(path_data.glob("*"))
print(f"Have {len(v_ids)} dir files, \n {v_ids[:10]}")
# for each word
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_root.joinpath("lipread_mp4", id_name)
v_dir_videos = sorted(dir_video.glob("**/*.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
# for each video
for ipath_videos in v_dir_videos:
ivideo_name = ipath_videos.stem
itrain_test = ipath_videos.parent.name
# copy video
ipath_video_target = path_root.joinpath("processing", id_name, itrain_test, ivideo_name, "video/video_orignal.mp4")
if not ipath_video_target.exists():
ipath_video_target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(src=str(ipath_videos), dst=str(ipath_video_target))
#print(f"copy {ipath_videos} --> {ipath_video_target}")
# copy audio
ipath_audio_source = path_root.joinpath("lipread_wav", id_name, itrain_test, ivideo_name+".wav")
ipath_audio_target = path_root.joinpath("processing", id_name, itrain_test, ivideo_name, "audio/audio_orignal.wav")
if not ipath_audio_target.exists():
ipath_audio_target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(src=str(ipath_audio_source), dst=str(ipath_audio_target))
#print(f"copy {ipath_audio_source} --> {ipath_audio_target}")
# if RESAMPLE_FPS:
# path_data = path_root.joinpath("processing")
# v_ids = sorted(path_data.glob("*"))
# print(f"Have {len(v_ids)} dir files, \n {v_ids[:10]}")
# # for each word
# for i, ipath_id in enumerate(v_ids):
# id_name = ipath_id.stem
# dir_video = path_data.joinpath(id_name)
# v_dir_videos = sorted(dir_video.glob("**/*.mp4"))
# print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
# # for each video
# for ipath_videos in v_dir_videos:
# ivideo_name = ipath_videos.stem
# itrain_test = ipath_videos.parent.name
# # copy video
# ipath_video_target = ipath_videos.parent.joinpath("video_25fps.mp4")
# cap = cv2.VideoCapture(str(ipath_videos))
# nframe = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# nfps = int(cap.get(cv2.CAP_PROP_FPS))
# w, h = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# print(f"FPS = {nfps}, length = {nframe}, (w,h)=({w}, {h})")
# if not ipath_video_target.exists():
# #ipath_video_target.parent.mkdir(parents=True, exist_ok=True)
# #shutil.copy(src=str(ipath_videos), dst=str(ipath_video_target))
# pass
# #print(f"convert {ipath_videos} --> {ipath_video_target}")
+66
View File
@@ -0,0 +1,66 @@
import cv2
import os, sys
import glob
import numpy as np
import time
import pdb
import argparse
from pathlib2 import Path
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/processing")
v_ids = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_ids)} dir files, \n {v_ids[:10]}")
# for each word
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("**/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
# for each video
for iv, ipath_video in enumerate(v_dir_videos):
ivideo_name = ipath_video.stem
itrain_test = ipath_video.parent.name
# create data path
path_save_frames = ipath_video.parent.parent.joinpath("frames")
# if already exists frames
if path_save_frames.exists():
if len(list(path_save_frames.glob("*.jpg"))) > 20:
continue
path_save_frames.mkdir(parents=True, exist_ok=True)
#print("save frames dir = ", {path_save_frames})
# STEP1: extract frames
count = 0
cap = cv2.VideoCapture(str(ipath_video))
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
while True:
success, image = cap.read()
if not success:
break
ipath_frame = path_save_frames.joinpath(f"frame-{count:04d}.jpg")
if not ipath_frame.exists():
cv2.imwrite(str(ipath_frame), image)
count += 1
if iv % 50 == 0:
print(f"--> Extract {iv}-th video, have {length} frames, {ipath_video}")
#print(f"extract and save the {count}/{length}-th frame --> {ipath_frame}")
#break
#break
+83
View File
@@ -0,0 +1,83 @@
import numpy as np
from PIL import Image
from pathlib2 import Path
from face_alignment import FaceAlignment, LandmarksType
def select_ldmk(ladmks):
ladmks = np.array(ladmks)
area = []
for i in range(ladmks.shape[0]):
lands = ladmks[i, ...]
xmin, xmax = np.min(lands[:, 0]), np.max(lands[:, 0])
ymin, ymax = np.min(lands[:, 1]), np.max(lands[:, 1])
area.append((xmax - xmin) * (ymax-ymin))
print("area = ", area, "select = ", np.argmax(area))
return ladmks[np.argmax(area), :, :]
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/processing")
model = FaceAlignment(LandmarksType._2D, flip_input=False)
v_ids = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each word
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
# if id_name not in ["ABUSE", "ACCESS", "ACCORDING", "ACCUSED", "ACROSS"]:
# continue
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("**/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for iv, ipath_video in enumerate(v_dir_videos):
ipath_data = ipath_video.parent.parent
#print(f"ipath_data = {ipath_data}")
ipath_frames = ipath_data.joinpath("frames")
ipath_landmk = ipath_data.joinpath("landmk")
ipath_landmk.mkdir(parents=True, exist_ok=True)
# STEP1: get frames
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
if iv % 50 == 0:
print(f"--> Extract {iv}-th video landmark: have {len(v_path_frames)} frames in {ipath_frames}")
# STEP2: extract landmarks
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
if not ipath_landmk_frame.exists():
# detect image
image = Image.open(str(kpath_frame)).convert('RGB') # (h, w, 3)
ldmk_pred = model.get_landmarks(np.array(image))
if ldmk_pred is None:
continue
# select the first one or the bigger one face
if len(ldmk_pred) > 1:
ldmk_pred = select_ldmk(ldmk_pred)
else:
ldmk_pred = ldmk_pred[0]
np.savetxt(str(ipath_landmk_frame), ldmk_pred, fmt=" %3d")
# break
# break
+125
View File
@@ -0,0 +1,125 @@
import os
import glob
import pdb
import numpy as np
from pathlib import Path
from scipy.io import loadmat,savemat
COMBINE_COEFF_RBGFACE = True
COMBINE_LAMDK_RBGFACE = False
if __name__ == "__main__":
path_data = Path("/mnt/data/DATA/LRW/processing")
#num_train_file = 3000
#num_train_count = 0
# for each word
v_ids = sorted(path_data.glob("*"))
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for j, jpath_videos in enumerate(v_dir_videos):
if (j+1) % 100 == 100: print(f"processing {j+1}/{len(v_dir_videos)}")
jpath_data = jpath_videos.parent.parent
#print(f"jpath_data = {jpath_data}")
jpath_frames = jpath_data.joinpath("frames")
v_frames = sorted(jpath_frames.glob("*.jpg"), key=lambda x: int(x.stem[-4:]))
#print(f"contain {len(v_frames)} frames in {str(jpath_data)}")
#
if COMBINE_COEFF_RBGFACE:
jpath_coeff = jpath_data.joinpath("rgbface/coeff")
jpath_coeff_save = jpath_data.joinpath("video/coeff_rgbface2.npy")
jpath_coeff_save.parent.mkdir(parents=True, exist_ok=True)
v_coeff = sorted(jpath_coeff.glob("*.txt"))
#print(f"contain {len(v_coeff)} reconstruction/tans in {str(jpath_data)}")
if len(v_coeff) != len(v_frames):
print(f"\t ERROR && Continue: This video missing coeff{len(v_coeff)}/{len(v_frames)}, {str(jpath_coeff)} ")
continue
# elif jpath_coeff_save.exists():
# continue
else:
coeff_all = np.zeros((len(v_frames), 61), np.float32) # 55 + 3 + 3
for k, iframe in enumerate(v_frames):
fid = int(iframe.stem[-4:])
# load data
kpath_coeff = jpath_coeff.joinpath(f"frame-{fid:04d}.txt")
kk_coeff = np.loadtxt(str(kpath_coeff)).reshape(-1)
kk_coeff_expr = kk_coeff[100:155] # (55, ) , identity-100, expression-55 ==> (55, )
kk_coeff_rts = kk_coeff[155:161] # (6) , rotation-3, translation-3, scale-1 ==> (6, )
coeff_all[k, :] = np.r_[kk_coeff_expr, kk_coeff_rts] # (61, ) expression-55 + rotation-3 + trans-3
# save combine data
np.save(str(jpath_coeff_save), coeff_all)
#print(f"combine the coeff: {str(jpath_coeff)} --> {str(jpath_coeff_save)}")
# combine landmark of RGBFaceNet
if COMBINE_LAMDK_RBGFACE:
jpath_ladmk_proj = jpath_data.joinpath("rgbface/landmark_proj")
jpath_ladmk_crop = jpath_data.joinpath("rgbface/landmark_crop")
jpath_proj_save = jpath_data.joinpath("video/landmark_rgbface_proj.npy")
jpath_crop_save = jpath_data.joinpath("video/landmark_rgbface_crop.npy")
jpath_crop_save.parent.mkdir(parents=True, exist_ok=True)
v_ladmk_proj = sorted(jpath_ladmk_proj.glob("*.txt"))
v_ladmk_crop = sorted(jpath_ladmk_crop.glob("*.txt"))
#print(f"contain {len(v_ladmk_proj)} / {len(v_ladmk_crop)} landmark proj/crop in {str(jpath_data)}")
if len(v_ladmk_proj) != len(v_frames) or len(v_ladmk_crop) != len(v_frames):
print(f"\t ERROR && Continue: This video missing landmark, {str(jpath_ladmk_proj)} ")
continue
elif jpath_proj_save.exists() and jpath_crop_save.exists():
continue
else:
ladmk_proj_all = np.zeros((len(v_frames), 68, 2), np.float32)
ladmk_crop_all = np.zeros((len(v_frames), 68, 2), np.float32)
for k, iframe in enumerate(v_frames):
fid = int(iframe.stem[-4:])
# load data
kpath_proj = jpath_ladmk_proj.joinpath(f"frame-{fid:04d}.txt")
kpath_crop = jpath_ladmk_crop.joinpath(f"frame-{fid:04d}.txt")
ladmk_proj_all[k, :, :] = np.loadtxt(str(kpath_proj)) # (68, 2)
ladmk_crop_all[k, :, :] = np.loadtxt(str(kpath_crop)) # (68, 2)
# save combine data
np.save(str(jpath_proj_save), ladmk_proj_all)
np.save(str(jpath_crop_save), ladmk_crop_all)
#print(f"combine the coeff: {str(jpath_ladmk_proj)} --> {str(jpath_proj_save)}")
#break
#break
# combine 3dmm
#
@@ -0,0 +1,77 @@
import os
import numpy as np
from pathlib import Path
from scipy.io import loadmat,savemat
COMBINE_COEFF_RBGFACE = True
COMBINE_LAMDK_RBGFACE = True
if __name__ == "__main__":
path_data = Path("/mnt/data/DATA/LRW/processing")
#num_train_file = 3000
#num_train_count = 0
# for each word
v_ids = sorted(path_data.glob("*"))
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for j, jpath_videos in enumerate(v_dir_videos):
jpath_data = jpath_videos.parent.parent
#print(f"jpath_data = {jpath_data}")
jpath_frames = jpath_data.joinpath("frames")
v_frames = sorted(jpath_frames.glob("*.jpg"), key=lambda x: int(x.stem[-4:]))
n_frames = len(v_frames)
#print(f"contain {len(v_frames)} frames in {str(jpath_data)}")
jpath_coeff = jpath_data.joinpath("reconstruction/coeff")
jpath_coeff_save = jpath_data.joinpath("video/coeff_reconstruction.npy")
jpath_coeff_save.parent.mkdir(parents=True, exist_ok=True)
n_coeff = len(list(jpath_coeff.glob("*.txt")))
#print(f"contain {len(v_coeff)} reconstruction/tans in {str(jpath_data)}")
if n_frames != n_coeff:
print(f"\t ERROR && Continue: This video missing coeff {n_coeff}/{n_frames}, {str(jpath_coeff)}")
continue
# elif jpath_coeff_save.exists():
# continue
else:
coeff_all = np.zeros((n_frames, 70), np.float32) # 80 identity + 64 expression + 80 texture + 3 rot + 27 light + 3 trans
for k, iframe in enumerate(v_frames):
fid = int(iframe.stem[-4:])
# load data
kpath_coeff = jpath_coeff.joinpath(f"frame-{fid:04d}.txt")
kk_coeff = np.loadtxt(str(kpath_coeff)).reshape(-1)
kk_coeff_exp = kk_coeff[ 80:144] # (64, ) , expression-64 ==> (55, )
kk_coeff_rot = kk_coeff[224:227] # (3, ), rotation-3,
kk_coeff_tra = kk_coeff[254:257] # (3, ), translation - 3
coeff_all[k, :] = np.r_[kk_coeff_exp, kk_coeff_rot, kk_coeff_tra] # (70, ) expression-55 + rotation-3 + trans-3
#print(f"coef shape={coeff_all.shape}, path = {kpath_coeff}")
# save combine data
np.save(str(jpath_coeff_save), coeff_all)
if j % 100 == 99:
print(f"processing {j+1}/{len(v_dir_videos)}, shape={coeff_all.shape} --> {str(jpath_coeff_save)}")
+85
View File
@@ -0,0 +1,85 @@
import os
import pickle
import numpy as np
from pathlib import Path
from collections import OrderedDict
import sys
sys.path.insert(0, "/mnt/data/CODE/FaceDisentangleNetwork")
from common.landmark import landmark_normalize
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/LRW/processing")
path_anno = Path("data/LRW/anno_LRW_test_full.pickle")
annodb = OrderedDict()
nvideo = 0
# nvideo_target = 5000
# if not existing
vpath_words = sorted(path_data.glob("*"))
print(f"Have {len(vpath_words)} words folders, {vpath_words[0]}")
for i, ipath_wd in enumerate(vpath_words):
pid = ipath_wd.stem
# if nvideo > nvideo_target: break
# video
vpath_videos = sorted(ipath_wd.glob("test/*/video/video_orignal.mp4"))
print(f"\nid= {pid}, Have {len(vpath_videos)} video files")
for iv, ipath_video in enumerate(vpath_videos):
# if nvideo > nvideo_target: break
ipath_data = ipath_video.parent.parent
vid = ipath_data.stem
ipath_frames = ipath_data.joinpath("frames")
ipath_landmk = ipath_data.joinpath("landmk")
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
v_path_ladmks = sorted(ipath_landmk.glob("*.txt"))
nframes = len(v_path_frames)
if not (nframes > 20 and nframes== len(v_path_ladmks)):
print(f"have {nframes} frames, and {len(v_path_ladmks)} landmarks")
continue
if iv % 50 == 0:
print(f"--> picking the {iv}-th video landmark: vid({vid}) have {len(v_path_frames)} frames in {ipath_frames}")
# frames --> read landmarks
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
ldmk = np.loadtxt(ipath_landmk_frame) # shape = (68, 2)
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
v_ldmk[k, :, :] = ldmk
v_ldmk_norm[k, :, :] = ldmk_norm
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
dict_anno = {
"pid": pid,
"vid":vid,
# "ldmk": v_ldmk,
"ldmk_norm": v_ldmk_norm,
# "ldmk_auxs":v_ldmk_auxs
}
# count video numbers
nvideo += 1
annodb[vid] = dict_anno
# pickle and save
with open(str(path_anno), "wb") as f:
pickle.dump(annodb, f)
print(f"Total have {len(annodb)}/{nvideo} items anno, save to --> {path_anno}")
+86
View File
@@ -0,0 +1,86 @@
import os
import pickle
import numpy as np
from pathlib import Path
import sys
sys.path.insert(0, "/mnt/data/CODE/FaceDisentangleNetwork")
from common.landmark import landmark_normalize
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/LRW/processing")
path_anno = Path("data/LRW/anno_train_full.pickle")
annodb = []
nvideo = 0
nvideo_target = 5000
# if not existing
vpath_words = sorted(path_data.glob("*"))
print(f"Have {len(vpath_words)} words folders, {vpath_words[0]}")
for i, ipath_wd in enumerate(vpath_words):
pid = ipath_wd.stem
# if nvideo > nvideo_target: break
# video
vpath_videos = sorted(ipath_wd.glob("train/*/video/video_orignal.mp4"))
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, \n {vpath_videos[0]}")
for iv, ipath_video in enumerate(vpath_videos):
# if nvideo > nvideo_target: break
ipath_data = ipath_video.parent.parent
vid = ipath_data.stem
ipath_frames = ipath_data.joinpath("frames")
ipath_landmk = ipath_data.joinpath("landmk")
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
v_path_ladmks = sorted(ipath_landmk.glob("*.txt"))
nframes = len(v_path_frames)
if not (nframes > 20 and nframes== len(v_path_ladmks)):
print(f"have {nframes} frames, and {len(v_path_ladmks)} landmarks")
continue
if iv % 50 == 0:
print(f"--> pickling the {iv}-th video landmark: pid({vid}) have {len(v_path_frames)} frames in {ipath_frames}")
# frames --> read landmarks
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
ldmk = np.loadtxt(ipath_landmk_frame) # shape = (68, 2)
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
v_ldmk[k, :, :] = ldmk
v_ldmk_norm[k, :, :] = ldmk_norm
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
dict_anno = {
"pid": pid,
"vid":vid,
# "ldmk": v_ldmk,
"ldmk_norm": v_ldmk_norm,
# "ldmk_auxs":v_ldmk_auxs
}
# count video numbers
nvideo += 1
annodb.append(dict_anno)
# pickle and save
with open(str(path_anno), "wb") as f:
pickle.dump(annodb, f)
print(f"Total have {len(annodb)}/{nvideo} items anno, save to --> {path_anno}")
+89
View File
@@ -0,0 +1,89 @@
import os
import pickle
import numpy as np
from pathlib import Path
import sys
sys.path.insert(0, "/mnt/data/CODE/FaceDisentangleNetwork")
from common.landmark import landmark_normalize
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/LRW/processing")
path_anno = Path("data/LRW/anno_valid_full.pickle")
annodb = []
nvideo = 0
nvideo_target = 50000000
# if not existing
vpath_words = sorted(path_data.glob("*"))
print(f"Have {len(vpath_words)} words folders, {vpath_words[0]}")
for i, ipath_wd in enumerate(vpath_words):
pid = ipath_wd.stem
# if nvideo > nvideo_target: break
# video
vpath_videos = sorted(ipath_wd.glob("val/*/video/video_orignal.mp4"))
if len(vpath_videos) <= 0: continue
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, \n {vpath_videos[0]}")
for iv, ipath_video in enumerate(vpath_videos):
# if nvideo > nvideo_target: break
ipath_data = ipath_video.parent.parent
vid = ipath_data.stem
ipath_frames = ipath_data.joinpath("frames")
ipath_landmk = ipath_data.joinpath("landmk")
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
v_path_ladmks = sorted(ipath_landmk.glob("*.txt"))
nframes = len(v_path_frames)
if not (nframes > 20 and nframes== len(v_path_ladmks)):
print(f"have {nframes} frames, and {len(v_path_ladmks)} landmarks")
continue
if iv % 50 == 0:
print(f"--> pickling the {iv}-th video landmark: pid({vid}) have {len(v_path_frames)} frames in {ipath_frames}")
# frames --> read landmarks
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
ldmk = np.loadtxt(ipath_landmk_frame) # shape = (68, 2)
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
v_ldmk[k, :, :] = ldmk
v_ldmk_norm[k, :, :] = ldmk_norm
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
dict_anno = {
"pid": pid,
"vid":vid,
# "ldmk": v_ldmk,
"ldmk_norm": v_ldmk_norm,
# "ldmk_auxs":v_ldmk_auxs
}
# count video numbers
nvideo += 1
annodb.append(dict_anno)
# pickle and save
with open(str(path_anno), "wb") as f:
pickle.dump(annodb, f)
print(f"Total have {len(annodb)}/{nvideo} items anno, save to --> {path_anno}")
@@ -0,0 +1,95 @@
import os
import pickle
import numpy as np
from pathlib import Path
import sys
sys.path.insert(0, "/mnt/data/CODE/FaceDisentangleNetwork")
from common.landmark import landmark_normalize
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/LRW/processing")
path_save = Path('data/LRW') # processing
path_save.mkdir(parents=True, exist_ok=True)
nvideo = 0
nvideo_target = 1000
# if not existing
vpath_words = sorted(path_data.glob("*"))
print(f"Have {len(vpath_words)} words folders, {vpath_words[0]}")
motion_test = []
speech_test = []
for i, ipath_wd in enumerate(vpath_words):
pid = ipath_wd.stem
if nvideo >= nvideo_target: break
# video
vpath_videos = sorted(ipath_wd.glob("test/*/video/video_orignal.mp4"))
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, \n {vpath_videos[0]}")
if len(vpath_videos) <= 0: continue
for iv, ipath_video in enumerate(vpath_videos):
if nvideo >= nvideo_target: break
ipath_data = ipath_video.parent.parent
vid = ipath_data.stem
ipath_frames = ipath_data.joinpath("frames")
ipath_landmk = ipath_data.joinpath("landmk")
ipath_mfcc = ipath_data.joinpath("audio/feat_mfcc_align.npy")
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
v_path_ladmks = sorted(ipath_landmk.glob("*.txt"))
if not ipath_mfcc.exists(): continue
# load speech
mfcc = np.load(ipath_mfcc) # 29 x 27
nframes = len(v_path_frames)
if not (nframes == 29 and len(v_path_ladmks) ==29 and mfcc.shape[0] == 29):
print(f"have {nframes} frames, and {len(v_path_ladmks)} landmarks, {mfcc.shape[0]} mfcc")
continue
if iv % 50 == 0:
print(f"--> pickling the {iv}-th video landmark: pid({vid}) have {len(v_path_frames)} frames in {ipath_frames}")
# frames --> read landmarks
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
ldmk = np.loadtxt(ipath_landmk_frame) # shape = (68, 2)
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
v_ldmk[k, :, :] = ldmk
v_ldmk_norm[k, :, :] = ldmk_norm
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
motion_test.append(v_ldmk_norm) # (29, 68, 2)
speech_test.append(mfcc) # (29, 27)
# count video numbers
nvideo += 1
motion_test = np.array(motion_test) # (N, 29, 68, 2)
speech_test = np.array(speech_test) # (N, 29, 27)
np.savez(path_save.joinpath("motion_test.npz"), data=motion_test)
np.savez(path_save.joinpath("speech_test.npz"), data=speech_test)
print(f"save train data motion({motion_test.shape}), speech({speech_test.shape}) -> {path_save}")
@@ -0,0 +1,95 @@
import os
import pickle
import numpy as np
from pathlib import Path
import sys
sys.path.insert(0, "/mnt/data/CODE/FaceDisentangleNetwork")
from common.landmark import landmark_normalize
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/LRW/processing")
path_save = Path('data/LRW') # processing
path_save.mkdir(parents=True, exist_ok=True)
nvideo = 0
nvideo_target = 100000
# if not existing
vpath_words = sorted(path_data.glob("*"))
print(f"Have {len(vpath_words)} words folders, {vpath_words[0]}")
motion_train, motion_valid, motion_test = [], [], []
speech_train, speech_valid, speech_test = [], [], []
for i, ipath_wd in enumerate(vpath_words):
pid = ipath_wd.stem
if nvideo >= nvideo_target: break
# video
vpath_videos = sorted(ipath_wd.glob("train/*/video/video_orignal.mp4"))
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, \n {vpath_videos[0]}")
if len(vpath_videos) <= 0: continue
for iv, ipath_video in enumerate(vpath_videos):
if nvideo >= nvideo_target: break
ipath_data = ipath_video.parent.parent
vid = ipath_data.stem
ipath_frames = ipath_data.joinpath("frames")
ipath_landmk = ipath_data.joinpath("landmk")
ipath_mfcc = ipath_data.joinpath("audio/feat_mfcc_align.npy")
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
v_path_ladmks = sorted(ipath_landmk.glob("*.txt"))
if not ipath_mfcc.exists(): continue
# load speech
mfcc = np.load(ipath_mfcc) # 29 x 27
nframes = len(v_path_frames)
if not (nframes == 29 and len(v_path_ladmks) ==29 and mfcc.shape[0] == 29):
print(f"have {nframes} frames, and {len(v_path_ladmks)} landmarks, {mfcc.shape[0]} mfcc")
continue
if iv % 50 == 0:
print(f"--> pickling the {iv}-th video landmark: pid({vid}) have {len(v_path_frames)} frames in {ipath_frames}")
# frames --> read landmarks
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
ldmk = np.loadtxt(ipath_landmk_frame) # shape = (68, 2)
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
v_ldmk[k, :, :] = ldmk
v_ldmk_norm[k, :, :] = ldmk_norm
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
motion_train.append(v_ldmk_norm) # (29, 68, 2)
speech_train.append(mfcc) # (29, 27)
# count video numbers
nvideo += 1
motion_train = np.array(motion_train) # (N, 29, 68, 2)
speech_train = np.array(speech_train) # (N, 29, 27)
np.savez(path_save.joinpath("motion_train.npz"), data=motion_train)
np.savez(path_save.joinpath("speech_train.npz"), data=speech_train)
print(f"save train data motion({motion_train.shape}), speech({speech_train.shape}) -> {path_save}")
+101
View File
@@ -0,0 +1,101 @@
import os
import numpy as np
import librosa
import python_speech_features
from pathlib import Path
import multiprocessing
def splited_by_windows(data, wind_stride, wind_length, padding=True):
"""
data: seq_len1 x dim1
return: seq_len2 x wind_length x dim1
where seq_len2 = (L + 2p - k) // wind_stride + 1
"""
seq_len1, dim1 = data.shape
seq_len2 = seq_len1 // wind_stride + 1
#print("DATA befor shape=", data.shape) # DATA befor shape= (121, 13)
data = np.pad(data, pad_width=((wind_length//2,wind_length//2), (0,0)), mode="reflect")
#print("DATA after shape=", data.shape) # DATA after shape= (149, 13)
data_output = np.zeros((seq_len2, wind_length, dim1-1), dtype=float)
for i in range(seq_len2):
ibeg = i * wind_stride
iend = i * wind_stride + wind_length
data_output[i, :, :] = data[ibeg : iend, 1:] # TODO: why form 1:
return data_output
# def func_processing(path_audio):
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/LRW/processing")
# for each word
v_ids = sorted(path_data.glob("*"))
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for j, jpath_videos in enumerate(v_dir_videos):
if (j+1) % 100 == 0: print(f"processing {j+1}/{len(v_dir_videos)}")
jpath_data = jpath_videos.parent.parent
jpath_frame = jpath_data.joinpath("frames")
nframes = len(sorted(jpath_frame.glob("*.jpg")))
#print(f"jpath_data = {jpath_data}, nframe = {nframes}")
ipath_audio = jpath_data.joinpath("audio/audio_orignal.wav")
ipath_feat_save = jpath_data.joinpath("audio/mfcc_feat.npy")
ipath_feat_orignal_save = jpath_data.joinpath("audio/mfcc_feat_orignal.npy")
# for some data not have .wav files
if not ipath_audio.exists():
print(f"NOT EXISTING: {ipath_audio}")
continue
if ipath_feat_orignal_save.exists():
print(f"EXSTING, {ipath_feat_orignal_save}")
continue
# extarct mfcc feature
audio, sr = librosa.load(str(ipath_audio), sr=16000) # (69760, )
mfcc_orig = python_speech_features.mfcc(audio, 16000, winstep=0.01)
#duration = len(audio) / sr
#print(f"audio shape={audio.shape}, mfcc shape={mfcc_orig.shape}, duration={duration}")
# splited by windows (to fit video frame with fps 25)
wind_stride = 4 # 4 x 10ms = 40 ms, video(25fps) frame = 1/25s = 40ms
wind_length = 28 # 28 x 10ms = 280 ms, = 7 frames * 40 ms
# seq_len2 = (seq_len1 + 2*pad - wind_length) // wind_stride + 1
mfcc = splited_by_windows(mfcc_orig, wind_stride, wind_length, padding=True) # seq_len2 x 28 x 12,
#print(f"MFCC input size (splited by windows) ={mfcc.shape}")
# save files
np.save(str(ipath_feat_orignal_save), mfcc_orig)
# np.save(str(ipath_feat_save), mfcc)
# print(f"SAVE: mfcc size={mfcc.shape} --> {str(ipath_feat_save)}") # mfcc size=(31, 28, 12)
# print(f"SAVE: mfcc size={mfcc_orig.shape} --> {str(ipath_feat_orignal_save)}") # mfcc size=(31, 28, 12)
#break
#break
+113
View File
@@ -0,0 +1,113 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
import moviepy
from moviepy.editor import VideoFileClip, AudioFileClip
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/LRW/processing")
# for each word
v_ids = sorted(path_data.glob("*"))
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for j, jpath_videos in enumerate(v_dir_videos):
if (j+1) % 100 == 0: print(f"processing {j+1}/{len(v_dir_videos)}")
jpath_data = jpath_videos.parent.parent
jpath_frame = jpath_data.joinpath("frames")
nframes = len(sorted(jpath_frame.glob("*.jpg")))
#print(f"jpath_data = {jpath_data}, nframe = {nframes}")
ipath_video = jpath_data.joinpath("video/video_orignal.mp4")
ipath_audio = jpath_data.joinpath("audio/audio_orignal.wav")
ipath_save_feat = jpath_data.joinpath("audio/feat_mfcc_align.npy")
video = VideoFileClip(str(ipath_video))
# print(f"\nvideo duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
audio = AudioFileClip(str(ipath_audio))
# print(f"audio duration = {audio.duration}, fps = {audio.fps}, (start, end)=({audio.start},{audio.end}), nframes={int(audio.duration * audio.fps)}")
# for some data not have .wav files
if not ipath_audio.exists():
print(f"NOT EXISTING: {ipath_audio}")
continue
if ipath_save_feat.exists():
print(f"EXSTING, {ipath_save_feat}")
continue
fps = video.fps
data, sr = librosa.load(str(ipath_audio), sr=16000) # 16000 = fps * 550 让这个sr是fps的整数,
hop_len = int(sr / fps) # 640
n_fft = int(sr * 0.1) # default 2048
# print(f"data={data.shape}, sr={sr}, fps={fps}, hop_len={sr/fps}, frames = {(len(data) / sr) * fps}, minmax = {np.min(data)},{np.max(data)}")
mfcc = librosa.feature.mfcc(y=data, sr=sr,
n_fft=n_fft, # FFT窗口的长度
hop_length=hop_len, # 帧移
win_length=n_fft, # 窗口长度,默认=n_fft
window="hann", # 加hanming窗
n_mfcc=27,
fmin=0.0, fmax=8000)
# mfcc = np.log(mfcc+1).T
mfcc = mfcc.T
# print(f"sr={sr}, data ={data.shape}, mfcc = {mfcc.shape}, (min,max)=({np.min(mfcc), np.max(mfcc)}")
if mfcc.shape[0] < nframes:
print(f"\nERROR:")
print(f"video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
print(f"audio duration = {audio.duration}, fps = {audio.fps}, (start, end)=({audio.start},{audio.end}), nframes={int(audio.duration * audio.fps)}")
print(f"sr={sr}, data ={data.shape}, mfcc = {mfcc.shape}, (min,max)=({np.min(mfcc), np.max(mfcc)}")
print(f"mfcc length(={mfcc.shape[0]}) can not < nframe {nframes} ")
continue
else:
# save
mfcc_align = mfcc[:nframes, :]
np.save(str(ipath_save_feat), mfcc_align)
# # extarct mfcc feature
# audio, sr = librosa.load(str(ipath_audio), sr=16000) # (69760, )
# mfcc_orig = python_speech_features.mfcc(audio, 16000, winstep=0.01)
# #duration = len(audio) / sr
# #print(f"audio shape={audio.shape}, mfcc shape={mfcc_orig.shape}, duration={duration}")
# # splited by windows (to fit video frame with fps 25)
# wind_stride = 4 # 4 x 10ms = 40 ms, video(25fps) frame = 1/25s = 40ms
# wind_length = 28 # 28 x 10ms = 280 ms, = 7 frames * 40 ms
# # seq_len2 = (seq_len1 + 2*pad - wind_length) // wind_stride + 1
# mfcc = splited_by_windows(mfcc_orig, wind_stride, wind_length, padding=True) # seq_len2 x 28 x 12,
# #print(f"MFCC input size (splited by windows) ={mfcc.shape}")
# save files
# np.save(str(ipath_feat_orignal_save), mfcc_orig)
# np.save(str(ipath_feat_save), mfcc)
# print(f"SAVE: mfcc size={mfcc.shape} --> {str(ipath_feat_save)}") # mfcc size=(31, 28, 12)
# print(f"SAVE: mfcc size={mfcc_orig.shape} --> {str(ipath_feat_orignal_save)}") # mfcc size=(31, 28, 12)
#break
#break
+86
View File
@@ -0,0 +1,86 @@
import os
import pickle
import numpy as np
from pathlib import Path
import sys
sys.path.insert(0, "/mnt/data/CODE/Audio2Expression")
from common.landmark import landmark_normalize
from common.animation import save_animation, save_animation_with_gt
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/LRW/processing")
path_save = Path('data/LRW') # processing
path_save.mkdir(parents=True, exist_ok=True)
nvideo = 0
nvideo_target = 100000
# if not existing
vpath_words = sorted(path_data.glob("*"))
print(f"Have {len(vpath_words)} words folders, {vpath_words[0]}")
for i, ipath_wd in enumerate(vpath_words):
pid = ipath_wd.stem
if nvideo >= nvideo_target: break
# video
vpath_videos = sorted(ipath_wd.glob("train/*/video/video_orignal.mp4"))
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, \n {vpath_videos[0]}")
if len(vpath_videos) <= 0: continue
for iv, ipath_video in enumerate(vpath_videos):
if nvideo >= nvideo_target: break
ipath_data = ipath_video.parent.parent
vid = ipath_data.stem
ipath_frames = ipath_data.joinpath("frames")
ipath_landmk_dlib = ipath_data.joinpath("landmk")
ipath_landmk_pfld = ipath_data.joinpath("landmk-PFLD")
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
v_path_ladmks_dlib = sorted(ipath_landmk_dlib.glob("*.txt"))
v_path_ladmks_pfld = sorted(ipath_landmk_pfld.glob("*.txt"))
nframes = len(v_path_frames)
if not (nframes == 29 and len(v_path_ladmks_dlib) ==29 and len(v_path_ladmks_pfld) ==29):
print(f"have {nframes} frames, and {len(v_path_ladmks_dlib)} / {len(v_path_ladmks_pfld)} landmarks, ")
continue
if iv % 50 == 0:
print(f"--> pickling the {iv}-th video landmark: pid({vid}) have {len(v_path_frames)} frames in {ipath_frames}")
# frames --> read landmarks
vldmk_dlib = np.zeros((1, nframes, 68, 2), dtype=float)
vldmk_pfld = np.zeros((1, nframes, 68, 2), dtype=float)
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
kpath_landmk_dlib = ipath_landmk_dlib.joinpath(f"frame-{frame_id:04d}.txt")
kpath_landmk_pfld = ipath_landmk_pfld.joinpath(f"frame-{frame_id:04d}.txt")
ldmk_dlib = np.loadtxt(kpath_landmk_dlib) # shape = (68, 2)
ldmk_dlib, _, _ = landmark_normalize(ldmk_dlib)
vldmk_dlib[0, k, :, :] = ldmk_dlib
ldmk_pfld = np.loadtxt(kpath_landmk_pfld) # shape = (68, 2)
ldmk_pfld, _, _ = landmark_normalize(ldmk_pfld)
vldmk_pfld[0, k, :, :] = ldmk_pfld
# show annotation
save_animation_with_gt(vldmk_dlib, vldmk_pfld,
path_save=Path(ipath_data),
suffix=f'DLIB_PLDF',
w=256, h=256, dpi=100)