add audio2mesh model support

This commit is contained in:
Sen Liang committed 2022-02-28 15:29:06 +08:00
1 parent 5eb304186a
commit 386df9a4ab
83 files changed
+9318 -1307

No files matched your search

+166
View File
@@ -0,0 +1,166 @@
import numpy as np
from pathlib import Path
if __name__ == "__main__":
# fid = "Bringing-Our-Workplace-Policies-into-the-21st-Century"
fid = "2021-P09"
path_root = Path("/yrfs/lsen/DATA/LuoXData/processing2/")
path_data = path_root.joinpath(fid)
path_coeff = path_data.joinpath("DECA_coeff")
vpath_coeff = sorted(path_coeff.glob("*.npy"), reverse=False)
print(f"Have {len(vpath_coeff)} frames")
feat_shape = []
feat_tex = []
feat_cam = []
feat_exp = []
feat_pos = []
feat_light = []
feat_detail = []
for ipath_coeff in vpath_coeff:
data_coeff = np.load(ipath_coeff, allow_pickle=True).item()
# print(data_coeff.keys())
feat_exp.append(data_coeff["exp"])
feat_pos.append(data_coeff["pose"])
feat_tex.append(data_coeff["tex"])
feat_cam.append(data_coeff["cam"])
feat_light.append(data_coeff["light"])
feat_detail.append(data_coeff["detail"])
feat_shape.append(data_coeff["shape"])
# save
feat_exp = np.array(feat_exp) # (nframe_trim, 50)
feat_pos = np.array(feat_pos) # (nframe_trim, 6)
feat_tex = np.array(feat_tex) # (nframe_trim, 50)
feat_cam = np.array(feat_cam) # (nframe_trim, 6)
feat_light = np.array(feat_light) # (nframe_trim, 50)
feat_detail = np.array(feat_detail) # (nframe_trim, 6)
feat_shape = np.array(feat_shape) # (nframe_trim, 50)
mean_exp = feat_exp.mean(axis=0)
mean_pos = feat_pos.mean(axis=0)
mean_tex = feat_tex.mean(axis=0)
mean_cam = feat_cam.mean(axis=0)
mean_light = feat_light.mean(axis=0)
mean_detail = feat_detail.mean(axis=0)
mean_shape = feat_shape.mean(axis=0)
print(f"feat_exp shape = {feat_exp.shape}, mean = {mean_exp.shape}, \n{mean_exp}")
print(f"mean_pos shape = {feat_pos.shape}, mean = {mean_pos.shape}, \n{mean_pos}")
print(f"mean_tex shape = {feat_tex.shape}, mean = {mean_tex.shape}, \n{mean_tex}")
print(f"mean_cam shape = {feat_cam.shape}, mean = {mean_cam.shape}, \n{mean_cam}")
print(f"mean_light shape = {feat_light.shape}, mean = {mean_light.shape}, \n{mean_light}")
print(f"mean_detail shape = {feat_detail.shape}, mean = {mean_detail.shape}, \n{mean_detail}")
print(f"mean_shape shape = {feat_shape.shape}, mean = {mean_shape.shape}, \n{mean_shape}")
# save
mean_DECA = {
"exp": mean_exp, # (50, )
"pose": mean_pos, # (6, )
"tex": mean_tex, # (50, )
"cam": mean_cam, # (3, )
"light": mean_light, # (9, 3)
"detail": mean_detail,# (128, )
"shape": mean_shape, # (100, )
}
path_save = "./data/DECA_LuoXData_mean.npy"
np.save(path_save, mean_DECA)
print("save to --> ", path_save)
# Have 21499 frames
# feat_exp shape = (21499, 50), mean = (50,),
# [ 0.44338268 0.4472932 0.3063721 0.7504411 -0.4381568 -0.17690322
# -0.05219001 -0.57315934 0.18184426 0.9165148 -0.59275323 0.56516534
# -0.07709685 0.329883 0.3242076 -0.3435903 -0.6763506 -0.4351912
# -0.04082069 0.8187175 0.03223863 -0.5716034 0.54998404 0.0491897
# -0.1993383 0.09097239 -0.00910581 0.22115254 -0.16818044 -0.29952174
# 0.09535432 -0.33055896 0.28673303 -0.25529468 0.19485517 -0.00993109
# 0.07266268 -0.13707523 0.1642315 -0.05313531 -0.22445893 -0.09244996
# -0.01606068 -0.01136032 -0.18826558 0.17590263 -0.04148029 0.15630233
# -0.04461758 0.03858361]
# mean_pos shape = (21499, 6), mean = (6,),
# [ 0.25185004 0.06190158 -0.04912106 0.0478017 0.00894242 0.03168569]
# mean_tex shape = (21499, 50), mean = (50,),
# [-0.3978834 -0.42889112 -0.16672912 -0.0809032 -0.0311112 0.10049947
# 0.33035028 -0.41055256 -0.11721741 -0.07116426 -0.04352681 0.308682
# 0.25109372 -0.21540923 -0.03529367 0.1724729 0.23672035 0.24651733
# 0.09847663 0.00665621 0.0794858 -0.06461164 0.01242481 0.052638
# -0.03111307 -0.00460155 0.14652304 0.01369311 -0.1782642 0.10161535
# -0.00404513 -0.08375361 0.12226686 0.08011193 -0.14495994 0.05208473
# -0.13073783 0.14158903 -0.00310591 -0.13385871 -0.12640713 0.04086212
# 0.12389808 -0.00319803 0.08630313 0.02669481 -0.04975258 0.06850675
# 0.0145871 -0.03593108]
# mean_cam shape = (21499, 3), mean = (3,),
# [ 9.70313 -0.00973762 0.05297631]
# mean_light shape = (21499, 9, 3), mean = (9, 3),
# [[ 3.668586 3.6666408 3.6884367 ]
# [-0.02417332 -0.01953881 -0.02340931]
# [ 0.13705754 0.14098997 0.1339419 ]
# [-0.3177393 -0.33407646 -0.27969545]
# [ 0.03982113 0.03903044 0.03949506]
# [ 0.00550121 0.0090305 0.00659682]
# [-0.0473443 -0.0428174 -0.04730038]
# [ 0.2589516 0.25872716 0.2667857 ]
# [ 0.3665497 0.3590046 0.37101206]]
# mean_detail shape = (21499, 128), mean = (128,),
# [ 3.61521721e-01 6.14889897e-02 -9.27711353e-02 -4.99111451e-02
# 9.35071558e-02 -4.14181035e-03 8.36418290e-03 1.42222671e-02
# -6.43310547e-02 6.34927675e-02 -4.77789193e-02 -6.49932697e-02
# -1.25051411e-02 -1.42840430e-01 -2.68053383e-01 -4.33399342e-02
# 5.79991080e-02 -6.73886761e-02 -1.68433964e-01 3.68494689e-02
# -1.16020657e-01 1.02660023e-01 5.25341071e-02 -8.19350109e-02
# -1.01520777e-01 1.95464730e-01 -3.04076709e-02 -4.90539931e-02
# -3.66580971e-02 -6.70471564e-02 3.78390849e-01 -5.20394333e-02
# -4.54101205e-01 4.37255716e-03 5.44623472e-02 8.57212916e-02
# 1.58119053e-01 -1.92813739e-01 9.49373189e-03 1.81852393e-02
# 5.11284471e-02 1.03188865e-02 -7.73664191e-02 -2.01583542e-02
# 5.95133752e-02 -7.51507431e-02 -9.99203101e-02 7.36503676e-02
# 1.58722445e-01 6.02622665e-02 -3.20148505e-02 -4.51608598e-02
# -8.57862309e-02 -7.13788047e-02 1.60456672e-02 1.00568458e-01
# -2.49848496e-02 -9.89784896e-02 -3.26840989e-02 -3.01793907e-02
# -6.15731366e-02 4.05075662e-02 6.88920915e-02 -1.12864830e-01
# 2.88244411e-02 -9.44222510e-02 1.49918213e-01 -5.53867444e-02
# -4.31086451e-01 3.11203804e-02 4.79492359e-02 -5.20009361e-02
# 3.43780033e-02 2.66235732e-02 3.38539705e-02 -3.00715804e-01
# -1.81968529e-02 -3.17425169e-02 1.62658636e-02 1.21782655e-02
# -2.83036269e-02 1.15976281e-01 7.14496151e-02 4.37062651e-01
# 4.90688123e-02 2.40370128e-02 -5.72391078e-02 -6.25709668e-02
# 7.10044131e-02 -1.65119901e-01 -2.34024543e-02 -2.69950107e-02
# 6.52964264e-02 2.17279568e-01 -8.76158103e-02 -9.41120610e-02
# 2.69935168e-02 -7.41094574e-02 1.83443710e-01 -7.56433010e-02
# 1.50024280e-01 3.49961817e-01 1.26819417e-01 2.67323870e-02
# -2.79632300e-01 -4.44744639e-02 1.91484280e-02 -2.59159375e-02
# 5.70407100e-02 -2.09884532e-02 -2.51313988e-02 -3.76658551e-02
# 1.85259376e-02 -9.42206103e-03 7.46866986e-02 2.46279147e-02
# -9.56854001e-02 6.84051365e-02 4.84354645e-01 4.01193229e-03
# -2.31952056e-01 4.11941558e-02 -4.09149914e-04 5.58872700e-01
# 3.48035753e-01 2.20942989e-01 -1.54582923e-02 5.18014990e-02]
# mean_shape shape = (21499, 100), mean = (100,),
# [-0.32458988 0.17692271 -0.59014773 -0.0735845 0.16357006 -0.35708523
# 0.06076029 0.07674006 -0.21280588 -0.28636473 0.05864865 0.04630899
# -0.00805237 -0.07572373 -0.01006004 -0.02728044 -0.03204667 0.05797856
# -0.0428825 -0.3848283 0.39713535 0.0483583 0.19617037 0.14579436
# 0.09192853 -0.09590823 -0.05430005 -0.15612626 0.13853826 -0.09018957
# 0.03631187 0.05067807 -0.05036244 -0.00284541 -0.1159773 -0.08631504
# -0.1413492 -0.01819041 -0.08816721 0.03550155 -0.11542681 0.15759806
# 0.00542928 0.01032758 0.11571501 -0.1593183 0.05542826 -0.05267807
# -0.35371011 -0.0929389 0.17742656 -0.38268778 0.0423925 -0.22057873
# 0.05460614 -0.08430341 0.08110942 0.00884286 0.12435686 -0.00792618
# -0.02667568 -0.18690723 -0.06518848 0.06365784 -0.03344199 -0.07648047
# 0.01697154 -0.13141611 -0.01001224 0.00656717 -0.04314337 -0.181731
# 0.0684299 -0.08775398 -0.06183273 -0.04920578 -0.10702839 0.01475282
# 0.1069483 -0.01643799 0.00402089 -0.01572194 0.16098669 0.07922536
# -0.01868843 0.02041192 -0.09030195 -0.03367294 0.01796311 -0.02930326
# 0.10064717 -0.01723173 0.01651016 0.01912417 -0.00323546 -0.00704829
# 0.0334241 -0.02697726 0.01572118 0.04431901]
# save to --> ./data/DECA_LuoXData_mean.npy
+10 -9
View File
@@ -11,13 +11,14 @@ if __name__ == '__main__':
vpath_videos = sorted(path_root.glob("raw/*.mp4"), reverse=False)
print(f"Have {len(vpath_videos)} dir files")
IDs = ["2021-P29"]
# for each video
for i, ipath_item in enumerate(vpath_videos):
iname = ipath_item.stem
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if i < 40: continue
# if iname not in IDs: continue
if iname not in IDs: continue
# data path
ipath_data = path_root.joinpath("processing2", ipath_item.stem)
@@ -55,10 +56,10 @@ if __name__ == '__main__':
nframes = int(video_sub.duration * video_sub.fps)
# check frames
nframe_real = len(list(ipath_frame.glob("*.jpg")))
if nframe_real == nframes:
print(f"\n Skip: have already done!")
continue
# nframe_real = len(list(ipath_frame.glob("*.jpg")))
# if nframe_real == nframes:
# print(f"\n Skip: have already done!")
# continue
# check fps
if int(video_sub.fps) != 50:
@@ -94,7 +95,7 @@ if __name__ == '__main__':
audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps)
print(f"save audio > {ipath_audio_sub}")
# save trim video
print(f"write_images_sequence...")
ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
video_sub.write_images_sequence(ipath_format, fps=50)
# # save trim video
# print(f"write_images_sequence...")
# ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
# video_sub.write_images_sequence(ipath_format, fps=50)
@@ -26,7 +26,7 @@ def main(args):
print(f"Have {len(v_dir_videos)} dir files")
# for each video
for ipath_data in v_dir_videos[17:]:
for ipath_data in v_dir_videos[18:]:
ivideo_name = ipath_data.stem
print("\nprocessing ...", ivideo_name)
@@ -58,7 +58,6 @@ def main(args):
print(f"\n ERROR: nframe_real ={nframe_real} / nframe_info ={nframes}")
continue
# check if finish
nkpt2d = len(list(ipath_kpt2d.glob("*.txt")))
if nkpt2d + 10 > nframes:
@@ -0,0 +1,97 @@
import sys
import numpy as np
import torch
from pathlib import Path
# common
sys.path.insert(0, "/ssdata1/lsen/CODE/Audio2Motion")
from common.animation import save_images_with_audio
sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old")
from decalib.deca import DECA
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
def tensor2image(tensor):
image = tensor.detach().cpu().numpy()
image = image*255.
image = np.maximum(np.minimum(image, 255), 0)
image = image.transpose(1,2,0)[:,:,[2,1,0]]
return image.astype(np.uint8).copy()
if __name__ == "__main__":
# load data
pid = "2021-P09" # "2021-P22"
path_root = Path("/yrfs/lsen/DATA/LuoXData/processing2/")
path_data = path_root.joinpath(pid)
path_pos = path_data.joinpath("audio/feat_DECA_pos_trim.npy")
path_idn = path_data.joinpath("audio/feat_DECA_idn_trim.npy")
path_exp = path_data.joinpath("audio/feat_DECA_exp_trim.npy")
# path_audio = path_data.joinpath("audio/audio_trim.wav")
path_audio = path_data.joinpath("audio/audio_trim_60_120s.wav")
data_pos = np.load(path_pos)[3000:6000] # N x 6
data_idn = np.load(path_idn)[3000:6000] # N x 100
data_exp = np.load(path_exp)[3000:6000] # N x 50
N = data_exp.shape[0]
# load mean
path_deca_mean = Path("./data/DECA_LuoXData_mean.npy")
mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
print(mean_dict.keys())
# load deca model
device = torch.device("cuda:0")
deca_cfg.model.use_tex = False
deca_cfg.dataset.image_size = 512
netR = DECA(config = deca_cfg, device=device)
# render
path_save = path_data.joinpath("video/deca_render_no_pos_60_120s.mp4")
v_render_pt = []
nbatch_render = 10
for k in range(0, N, nbatch_render):
codedict = {}
codedict["exp"] = data_exp[k:k+nbatch_render, :50] # (nbatch_render, 50)
nbatch_real = codedict["exp"].shape[0]
codedict["pose"] = np.zeros((nbatch_real, 6)) # (nbatch_render, 6)
codedict["pose"][:, 3:6] = data_pos[k:k+nbatch_render, 3:6]
# codedict["pose"] = data_pos[k:k+nbatch_render, :] # (nbatch_render, 6)
# codedict["shape"] = np.zeros((nbatch_real, 100)) # (nabtch_render, 100)
codedict["shape"] = data_idn[k:k+nbatch_render, :] # (nabatch_render, 100)
# others ==> to mean
mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]]
codedict["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
codedict["light"] = np.repeat([mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
# codedict["shape"] = np.repeat([mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100)
codedict["detail"] = np.repeat([mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
_, visdict_pt = netR.decode_one(codedict, nbatch_real, device)
render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224)
# print(f"render pt shape = {render_pt.shape}")
for m in range(nbatch_real):
# cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...]))
v_render_pt.append(tensor2image(render_pt[m, ...]))
save_images_with_audio(v_render_pt, path_audio, path_save)
@@ -9,7 +9,7 @@ from scipy import interpolate
import torchaudio
def landmark_resample_fps(y, source_fps = 30, target_fps=25):
"""y, N x 136, with 30fps
""" y, N x 136, with 30fps
"""
nsteps = y.shape[0]
@@ -27,12 +27,11 @@ def landmark_resample_fps(y, source_fps = 30, target_fps=25):
return y_new
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/LuoXData/processing2') # '../data/trinity/source'
path_save = Path('data/LuoXData-raw-deca-8h') # processing
path_save = Path('data/LuoXData-raw-deca-3min') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
@@ -43,26 +42,33 @@ if __name__ == "__main__":
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
vids = set([ipath.stem for ipath in v_dir_videos])
print(f"vids total= {vids}")
# print(f"vids total= {vids}")
# vid_test = set(["2021-P09", "2021-P22"])
# vid_valid = set(["2021-P14", "2021-P20"])
# vid_train = vids - vid_test - vid_test
vids = set(["2021-P09", "2021-P14", "2021-P22"])
vid_test = set(["2021-P09" ])
vid_valid = set(["2021-P14" ])
vid_train = set(["2021-P22" ])
vid_test = set(["2021-P09"])
vid_valid = set(["2021-P14"]) #set(["2021-P14"])
# vid_train = set(['2021-P01', '2021-P02', '2021-P'])
vid_train = vids - vid_test - vid_test
print(f"vid test= {vid_test} \nvalid= {vid_valid}")
print(f"vid train= {vid_train}")
# for each video
data_train, data_valid, data_test = {}, {}, {}
durations_train, durations_valid, durations_test = 0, 0, 0
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
if vid not in vids: continue
print(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
ipath_feat_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
ipath_speech = ipath_data.joinpath("audio/audio_trim.wav")
# check existing
@@ -84,12 +90,16 @@ if __name__ == "__main__":
# laod motion
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 6)
pos_head = data_pos[:, :3] # (nframe, 3)
pos_lips = data_pos[:, 3:] # (nframe, 3)
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 6)
data_idn = np.load(ipath_feat_idn) # (nframe, 100)
data_motion = np.concatenate([data_exp, pos_lips], axis=1) # (nframe, 53) --> fps=30
assert data_exp.shape[0] == data_pos.shape[0], f"data_exp shape={data_exp.shape}, data_pos shape={data_pos.shape}"
assert data_exp.shape[0] == data_idn.shape[0], f"data_exp shape={data_exp.shape}, data_idn shape={data_idn.shape}"
data_pos_head = data_pos[:, :3] # (nframe, 3)
data_pos_lips = data_pos[:, 3:] # (nframe, 3)
data_motion = np.concatenate([data_exp, data_pos_lips], axis=1) # (nframe, 53) --> fps=30
print(f"motion = {data_motion.shape}")
@@ -105,6 +115,16 @@ if __name__ == "__main__":
audio_raw = resampler(audio_raw).squeeze().numpy()
print(f"audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
####################################
# clips 4min
nclip = 4
nframes = nclip * 60 * 50 # min * 60s * fps
nsegmts = nclip * 60 * 16000 # min * 60s * sr
data_motion = data_motion[:nframes]
audio_raw = audio_raw[:nsegmts]
data_idn = data_idn[:nframes]
####################################
if vid in vid_train:
durations_train += nframes/fps
@@ -114,7 +134,8 @@ if __name__ == "__main__":
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw
"data_speech": audio_raw,
"data_shape": data_idn,
}
@@ -126,7 +147,8 @@ if __name__ == "__main__":
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw
"data_speech": audio_raw,
"data_shape": data_idn,
}
@@ -138,7 +160,8 @@ if __name__ == "__main__":
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw
"data_speech": audio_raw,
"data_shape": data_idn,
}
@@ -147,7 +170,6 @@ if __name__ == "__main__":
np.savez(path_save.joinpath("data_test.npz"), data=data_test)
print(f"Total ids: data_train ({len(data_train)}), data_test ({len(data_test)}) data_valid({len(data_valid)})")
print(f"Total frames: data_train ({durations_train / 3600} h), data_test ({durations_test / 60 } min) data_valid({durations_valid / 60} min)")
print(f"Total frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , data_test ({durations_test / 60 } min) data_valid({durations_valid / 60} min)")
print(f"--> {path_save}")
+104
View File
@@ -0,0 +1,104 @@
import sys
import numpy as np
import torch
from pathlib import Path
# common
sys.path.insert(0, "/ssdata1/lsen/CODE/Audio2Motion")
from common.animation import save_images_with_audio
sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old")
from decalib.deca import DECA
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
def tensor2image(tensor):
image = tensor.detach().cpu().numpy()
image = image*255.
image = np.maximum(np.minimum(image, 255), 0)
image = image.transpose(1,2,0)[:,:,[2,1,0]]
return image.astype(np.uint8).copy()
if __name__ == "__main__":
# load data
# pid = "Bringing-Our-Workplace-Policies-into-the-21st-Century" # "2021-P22"
pid = "Celebrating-Independence-Day"
path_root = Path("/yrfs/lsen/DATA/Obama/processing/")
path_data = path_root.joinpath(pid)
path_pos = path_data.joinpath("audio/feat_DECA_pos_trim.npy")
path_idn = path_data.joinpath("audio/feat_DECA_idn_trim.npy")
path_exp = path_data.joinpath("audio/feat_DECA_exp_trim.npy")
# path_audio = path_data.joinpath("audio/audio_trim.wav")
path_audio = path_data.joinpath("audio/audio_trim_60_120s.wav")
fps = 29.97002997002997
nframe_beg = int(60 * fps + 0.5)
nframe = int(120 * fps + 0.5)
print(f"fps = {fps}, beg = {nframe_beg}, len= 120s * fps = frame = {nframe}")
data_pos = np.load(path_pos)[nframe_beg:nframe_beg+nframe] # N x 6
data_idn = np.load(path_idn)[nframe_beg:nframe_beg+nframe] # N x 100
data_exp = np.load(path_exp)[nframe_beg:nframe_beg+nframe] # N x 50
N = data_exp.shape[0]
# load mean
path_deca_mean = Path("./data/DECA_obama_mean.npy")
mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
print(mean_dict.keys())
# load deca model
device = torch.device("cuda:3")
deca_cfg.model.use_tex = False
deca_cfg.dataset.image_size = 512
netR = DECA(config = deca_cfg, device=device)
# render
path_save = path_data.joinpath("video/deca_render_no_pose_60_120s.mp4")
v_render_pt = []
nbatch_render = 10
for k in range(0, N, nbatch_render):
codedict = {}
codedict["exp"] = data_exp[k:k+nbatch_render, :50] # (nbatch_render, 50)
nbatch_real = codedict["exp"].shape[0]
codedict["pose"] = np.zeros((nbatch_real, 6)) # (nbatch_render, 6)
codedict["pose"][:, 3:6] = data_pos[k:k+nbatch_render, 3:6]
# codedict["pose"] = data_pos[k:k+nbatch_render, :] # (nbatch_render, 6)
# codedict["shape"] = np.zeros((nbatch_real, 100)) # (nabtch_render, 100)
codedict["shape"] = data_idn[k:k+nbatch_render, :] # (nabatch_render, 100)
# others ==> to mean
mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]]
codedict["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
codedict["light"] = np.repeat([mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
# codedict["shape"] = np.repeat([mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100)
codedict["detail"] = np.repeat([mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
_, visdict_pt = netR.decode_one(codedict, nbatch_real, device)
render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224)
# print(f"render pt shape = {render_pt.shape}")
for m in range(nbatch_real):
# cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...]))
v_render_pt.append(tensor2image(render_pt[m, ...]))
save_images_with_audio(v_render_pt, path_audio, path_save)
+80
View File
@@ -0,0 +1,80 @@
import numpy as np
from pathlib import Path
if __name__ == "__main__":
# fid = "Bringing-Our-Workplace-Policies-into-the-21st-Century"
fid = "Equipping-Workers-with-Skills-Employers-Need-Now-and-for-the-Future"
path_root = Path("/yrfs/lsen/DATA/Obama/processing/")
path_data = path_root.joinpath(fid)
path_coeff = path_data.joinpath("DECA_coeff")
vpath_coeff = sorted(path_coeff.glob("*.npy"), reverse=False)
print(f"Have {len(vpath_coeff)} frames")
feat_shape = []
feat_tex = []
feat_cam = []
feat_exp = []
feat_pos = []
feat_light = []
feat_detail = []
for ipath_coeff in vpath_coeff:
data_coeff = np.load(ipath_coeff, allow_pickle=True).item()
# print(data_coeff.keys())
feat_exp.append(data_coeff["exp"])
feat_pos.append(data_coeff["pose"])
feat_tex.append(data_coeff["tex"])
feat_cam.append(data_coeff["cam"])
feat_light.append(data_coeff["light"])
feat_detail.append(data_coeff["detail"])
feat_shape.append(data_coeff["shape"])
# save
feat_exp = np.array(feat_exp) # (nframe_trim, 50)
feat_pos = np.array(feat_pos) # (nframe_trim, 6)
feat_tex = np.array(feat_tex) # (nframe_trim, 50)
feat_cam = np.array(feat_cam) # (nframe_trim, 6)
feat_light = np.array(feat_light) # (nframe_trim, 50)
feat_detail = np.array(feat_detail) # (nframe_trim, 6)
feat_shape = np.array(feat_shape) # (nframe_trim, 50)
mean_exp = feat_exp.mean(axis=0)
mean_pos = feat_pos.mean(axis=0)
mean_tex = feat_tex.mean(axis=0)
mean_cam = feat_cam.mean(axis=0)
mean_light = feat_light.mean(axis=0)
mean_detail = feat_detail.mean(axis=0)
mean_shape = feat_shape.mean(axis=0)
print(f"feat_exp shape = {feat_exp.shape}, mean = {mean_exp.shape}, \n{mean_exp}")
print(f"mean_pos shape = {feat_pos.shape}, mean = {mean_pos.shape}, \n{mean_pos}")
print(f"mean_tex shape = {feat_tex.shape}, mean = {mean_tex.shape}, \n{mean_tex}")
print(f"mean_cam shape = {feat_cam.shape}, mean = {mean_cam.shape}, \n{mean_cam}")
print(f"mean_light shape = {feat_light.shape}, mean = {mean_light.shape}, \n{mean_light}")
print(f"mean_detail shape = {feat_detail.shape}, mean = {mean_detail.shape}, \n{mean_detail}")
print(f"mean_shape shape = {feat_shape.shape}, mean = {mean_shape.shape}, \n{mean_shape}")
# save
mean_DECA = {
"exp": mean_exp, # (50, )
"pose": mean_pos, # (6, )
"tex": mean_tex, # (50, )
"cam": mean_cam, # (3, )
"light": mean_light, # (9, 3)
"detail": mean_detail,# (128, )
"shape": mean_shape, # (100, )
}
path_save = "./data/DECA_obama_mean.npy"
# np.save(path_save, mean_DECA)
print("save to --> ", path_save)
@@ -9,41 +9,37 @@ from pathlib2 import Path
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/Obama/processing') # '../data/trinity/source'
path_save = Path('data/obama-deca-mel') # processing
path_save = Path('data/obama-ds-daca-5h') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
print(f"Have {len(v_dir_videos)} dir files")
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
vids = [ipath.stem for ipath in v_dir_videos]
print(f"Have {len(v_dir_videos)} video id[:3] > {vids[:3]}")
nv_total = len(v_dir_videos)
nv_valid, nv_test = 1, 1
nv_train = nv_total - (nv_valid + nv_test)
vid_test = vids[:nv_test]
vid_valid = vids[nv_test:nv_test+nv_valid]
vid_train = vids[nv_test+nv_valid:]
vid_test = set(vids[:1])
vid_valid = set(vids[1:2])
vid_train = set(vids) - vid_test - vid_valid
print("vid_test = ", vid_test)
print("vid_valid = ", vid_valid)
# for each video
data_train, data_valid, data_test = {}, {}, {}
durations_train, durations_valid, durations_test = 0, 0, 0
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
if i % 50 == 0:
print(f"\n processing the {i}-th video {vid} ... ")
print(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
# ipath_speech = ipath_data.joinpath("audio/audio_trim.wav")
ipath_speech = ipath_data.joinpath("audio/feat_mel_no_align_trim.npy")
if not ipath_speech.exists():
print(f"ERROR: NOT Exist {ipath_speech}" )
continue
@@ -53,19 +49,14 @@ if __name__ == "__main__":
continue
# check existing
if not ipath_speech.exists() or not ipath_info.exists():
msg = "ERROR: NOT exsiting "
if not ipath_info.exists():
msg += f"\n\t {ipath_info} "
if not ipath_speech.exists():
msg += f"\n\t {ipath_speech} "
print(msg)
if not ipath_info.exists():
print(f"ERROR: NOT Exist {ipath_info}")
continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["info"] # 29.89990, NOT fixed
width = info["width"][0] # 1280 or 1920
height = info["height"][0] # 720 or 1080
print("\nwidth=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
@@ -81,12 +72,16 @@ if __name__ == "__main__":
continue
# load data
# feat_idn = np.load(ipath_idn) # (nframe_trim, 100)
feat_exp = np.load(ipath_exp) # (nframe_trim, 50)
feat_pos = np.load(ipath_pos) # (nframe_trim, 6) # (N, 6)
data_motion = np.concatenate([feat_exp, feat_pos[:, 3:6]], axis=1) # (N, 53)
data_speech = np.load(ipath_speech) # (M, 80) please note that M != N
feat_exp = np.load(ipath_exp) # (nframe_trim, 50)
feat_pos = np.load(ipath_pos) # (nframe_trim, 6)
feat_pos_head = feat_pos[:, :3] # (nframe_trim, 3)
feat_pos_lips = feat_pos[:, 3:] # (nframe_trim, 3)
data_motion = np.concatenate([feat_exp, feat_pos_lips], axis=1) # (N, 53)
print(f"motion = {data_motion.shape}")
# load raw audio
data_speech = np.load(ipath_speech) # (M, 80) please note that M != N
print(f"motion data = {data_motion.shape}, speech data = {data_speech.shape}")
# assert data_motion.shape[0] == data_speech.shape[0]
@@ -0,0 +1,168 @@
import json
import torchaudio
import numpy as np
from pathlib2 import Path
from scipy import interpolate
def convert_fps(y, source_fps = 30, target_fps=25):
"""
y, N x 136, with 30fps
"""
nsteps = y.shape[0]
x = np.arange(0, nsteps, 1)
# print("x:", x[::30], x[-10:])
func = interpolate.interp1d(x, y=y, axis=0)
x_new = np.arange(0, nsteps-1, 1.0*source_fps/target_fps)
# print("x_new", x_new[::30], x_new[-10:])
y_new = func(x_new)
if source_fps < target_fps:
y_new = np.concatenate([y_new, y[-1:]])
return y_new
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/Obama/processing') # '../data/trinity/source'
path_save = Path('data/obama-raw-deca-9h-50fps') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
vids = [ipath.stem for ipath in v_dir_videos]
print(f"Have {len(v_dir_videos)} video id[:3] > {vids[:3]}")
vid_test = set(vids[:2])
vid_valid = set(vids[2:4])
vid_train = set(vids) - vid_test - vid_valid
print("vid_test = ", vid_test)
print("vid_valid = ", vid_valid)
# for each video
data_train, data_valid, data_test = {}, {}, {}
durations_train, durations_valid, durations_test = 0, 0, 0
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
print(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
ipath_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
ipath_speech = ipath_data.joinpath("audio/audio_trim.wav")
if not ipath_speech.exists():
print(f"ERROR: NOT Exist {ipath_speech}" )
continue
if not ipath_exp.exists() or not ipath_pos.exists():
print(f"ERROR: NOT Exist {ipath_pos} or {ipath_exp}" )
continue
# check existing
if not ipath_info.exists():
print(f"ERROR: NOT Exist {ipath_info}")
continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["fps"] # 29.89990, NOT fixed
width = info["width"][0] # 1280 or 1920
height = info["height"][0] # 720 or 1080
print("\nwidth=",width, "height=",height, "fps=",fps, "-->", ipath_data)
# fps = info["fps"]
if len(info["active_frames"]) == 2:
ibeg = info["active_frames"][0]
iend = info["active_frames"][1]
nframe_trim = iend - ibeg
# print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
else:
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
continue
# load data
feat_exp = np.load(ipath_exp) # (nframe_trim, 50)
feat_pos = np.load(ipath_pos) # (nframe_trim, 6)
feat_idn = np.load(ipath_idn) # (nframe_trim, 100)
feat_pos_head = feat_pos[:, :3] # (nframe_trim, 3)
feat_pos_lips = feat_pos[:, 3:] # (nframe_trim, 3)
data_motion = np.concatenate([feat_exp, feat_pos_lips], axis=1) # (N, 53)
print(f"motion = {data_motion.shape}")
# laod shape
# resample to 30fps
fps_convert = 50
data_motion = convert_fps(data_motion, source_fps=fps, target_fps=fps_convert)
data_shape = convert_fps(feat_idn, source_fps=fps, target_fps=fps_convert)
nframe_convert = data_motion.shape[0]
assert data_motion.shape[0] == data_shape.shape[0], f"motion = {data_motion.shape[0]} shape = {data_shape.shape[0]}"
print(f"after convert motion = {data_motion.shape}, duration = {nframe_convert / fps_convert} vs. orignal duration = {nframe_trim / fps}")
# print(f"after convert shape = {data_shape.shape}, duration = {nframe_convert / fps_convert} vs. orignal duration = {nframe_trim / fps}")
# load raw audioß
audio_raw, sample_rate = torchaudio.load(ipath_speech)
print(f"audio_raw shape = {audio_raw.shape}, sr = {sample_rate}, duration = {(len(audio_raw[0])/sample_rate)}")
if len(audio_raw.shape) == 2:
audio_raw = audio_raw[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
audio_raw = resampler(audio_raw).squeeze().numpy()
print(f"audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
# add to data dict
if vid in vid_train:
durations_train += nframe_trim / fps
data_train[vid] = {
"W": width, "H": height,
"sr":16000, "FPS": fps_convert,
"nframe": nframe_convert,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_shape,
}
if vid in vid_valid:
durations_valid += nframe_trim / fps
data_valid[vid] = {
"W": width, "H": height,
"sr":16000, "FPS": fps_convert,
"nframe": nframe_convert,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_shape,
}
if vid in vid_test:
durations_test += nframe_trim / fps
data_test[vid] = {
"W": width, "H": height,
"sr":16000, "FPS": fps_convert,
"nframe": nframe_convert,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_shape,
}
np.savez(path_save.joinpath("data_train.npz"), data=data_train)
np.savez(path_save.joinpath("data_valid.npz"), data=data_valid)
np.savez(path_save.joinpath("data_test.npz"), data=data_test)
print(f"Total ids: data_train ({len(data_train)}), data_test ({len(data_test)}) data_valid({len(data_valid)})")
print(f"Total frames: data_train ({durations_train / 3600} h), data_test ({durations_test / 60 } min) data_valid({durations_valid / 60} min)")
print(f"--> {path_save}")
+62
View File
@@ -0,0 +1,62 @@
import os
import numpy as np
import moviepy.editor as mpy
from pathlib import Path
if __name__ == "__main__":
fps_save = 30
path_save = "/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/video/audio2mesh_compare_60_115_GT.mp4"
path_clipA = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220225-17H57M52S/audio_trim_60_120s_infer_20220217-17H36M22S_epoch_115_00.mp4"
path_clipB = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220225-17H48M06S/audio_trim_60_120s_infer_20220223-22H17M02S_epoch_060_00.mp4"
path_clipC = "/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/video/deca_render_no_pose_60_120s.mp4"
# path_clipAA = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220224-17H27M45S/audio_trim_120s_infer_20220223-22H17M02S_epoch_060_00.mp4"
# path_clipBB = "/yrfs/lsen/DATA/Obama/processing/Bringing-Our-Workplace-Policies-into-the-21st-Century/video/deca_render_no_pose_120s.mp4"
# path_clipCC = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/deca_render_no_pos_60_120s.mp4"
path_audio = "/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/audio/audio_trim_60_120s.wav"
clip_A = mpy.VideoFileClip(path_clipA)
clip_B = mpy.VideoFileClip(path_clipB)
clip_C = mpy.VideoFileClip(path_clipC)
# clip_AA = mpy.VideoFileClip(path_clipAA)
# clip_BB = mpy.VideoFileClip(path_clipBB)
# clip_CC = mpy.VideoFileClip(path_clipCC)
audio = mpy.AudioFileClip(path_audio)
# txtClip = mpy.TextClip('orignal',color='white', kerning = 5, fontsize=18)
# clip_A = mpy.CompositeVideoClip( [clip_A, txtClip.set_pos('top')], size=(512,512))
# txtClip = mpy.TextClip('-pose',color='white', kerning = 5, fontsize=18)
# clip_B = mpy.CompositeVideoClip( [clip_B, txtClip.set_pos('top')], size=(512,512))
# txtClip = mpy.TextClip('-pose-idn',color='white', kerning = 5, fontsize=18)
# clip_C = mpy.CompositeVideoClip( [clip_C, txtClip.set_pos('top')], size=(512,512))
# align to clipGT
duration = min(min(clip_A.duration, clip_C.duration), audio.duration)
clip_A = clip_A.set_duration(duration)
clip_B = clip_B.set_duration(duration)
clip_C = clip_C.set_duration(duration)
audio = audio.set_duration(duration)
# stack
# video = mpy.clips_array([[clip_A, clip_B], [clip_AA, clip_BB]]) # clip_C
video = mpy.clips_array([[clip_A, clip_B, clip_C]]) # clip_C
video = video.set_audio(audio) # audd audio
# save
video.write_videofile(path_save, fps=fps_save, logger=None)
print(f"save to > {path_save}")
+110
View File
@@ -0,0 +1,110 @@
import moviepy
import numpy as np
from pathlib import Path
from moviepy.editor import *
STEP_VIDEO = False
STEP_CONCATE = True
if __name__ == "__main__":
video_name = "2021-P09"
path_root = Path(f"/yrfs/lsen/DATA/LuoXData/processing2/{video_name}")
path_frame = path_root.joinpath(f"frames")
path_audio = path_root.joinpath("audio/audio_trim.wav")
# load audio
clip_audio = AudioFileClip(str(path_audio))
clip_audio.set_duration(120.0)
# load video
clip_video = ImageSequenceClip(path_frame, fps=50, load_images=True)
clip_video.set_duration(120.0)
# add audio
clip_image.write_videofile(str(path_image_save), fps=25)
concate_clips = concate_clips.set_audio(clip_audio)
# save
path_concate_save = path_data.joinpath("concate4.mp4")
#concate_clips = concate_clips.resize(width=720)
concate_clips.write_videofile(str(path_concate_save), fps=25)
# # to video
# if STEP_VIDEO:
# path_image = path_data.joinpath("frames_crop")
# path_image_save = path_data.joinpath("images.mp4")
# clip_image = ImageSequenceClip(path_image, fps=25, load_images=True)
# clip_image.write_videofile(str(path_image_save), fps=25)
# path_frame = path_data.joinpath("render")
# path_frame_save = path_data.joinpath("render.mp4")
# clip_render = ImageSequenceClip(path_frame, fps=25, load_images=True)
# clip_render.write_videofile(str(path_frame_save), fps=25)
# path_frame = path_data.joinpath("render_pt")
# path_frame_save = path_data.joinpath("render_pt.mp4")
# clip_render_pt = ImageSequenceClip(path_frame, fps=25, load_images=True)
# clip_render_pt.write_videofile(str(path_frame_save), fps=25)
# path_frame = path_data.joinpath("render_pt_fix_idn")
# path_frame_save = path_data.joinpath("render_pt_fix_idn.mp4")
# clip_render_pt2 = ImageSequenceClip(path_frame, fps=25, load_images=True)
# clip_render_pt2.write_videofile(str(path_frame_save), fps=25)
# # concate
# if STEP_CONCATE:
# # image
# clip_image = VideoFileClip(str(path_data.joinpath("images.mp4"))).margin(10)
# clip_text = TextClip("Crop Image", fontsize = 14, color = 'white', stroke_width=3)
# clip_text = clip_text.set_pos((0.4, 0.9), relative=True).set_duration(clip_image.duration)
# clip_image = CompositeVideoClip([clip_image, clip_text])
# # render
# clip_render = VideoFileClip(str(path_data.joinpath("render.mp4"))).margin(10)
# clip_text = TextClip("Render GT", fontsize = 14, color = 'white', stroke_width=3)
# clip_text = clip_text.set_pos((0.4,0.9), relative=True).set_duration(clip_render.duration)
# clip_render = CompositeVideoClip([clip_render, clip_text])
# # render with specific identiy
# clip_render2 = VideoFileClip(str(path_data.joinpath("render_pt.mp4"))).margin(10)
# clip_text = TextClip("Render PT fix identity", fontsize = 14, color = 'white', stroke_width=3)
# clip_text = clip_text.set_pos((0.2,0.9), relative=True).set_duration(clip_render2.duration)
# clip_render2 = CompositeVideoClip([clip_render2, clip_text])
# # render with specific identiy
# clip_render3 = VideoFileClip(str(path_data.joinpath("render_pt_fix_idn.mp4"))).margin(10)
# # clip_text = TextClip("Render PT with fixed identity", fontsize = 14, color = 'red')
# # clip_text = clip_text.set_pos("center", "top").set_duration(clip_render3.duration)
# # clip_render3 = CompositeVideoClip([clip_render3, clip_text])
# # audio
# path_audio = path_data.joinpath("../audio/test_video.wav")
# clip_audio = AudioFileClip(str(path_audio))
# # concate
# # concate_clips = clips_array([[clip_image, clip_render],
# # [clip_render2, clip_render3]])
# concate_clips = clips_array([[clip_image, clip_render, clip_render2]])
# concate_clips = concate_clips.set_audio(clip_audio)
# # save
# path_concate_save = path_data.joinpath("concate4.mp4")
# #concate_clips = concate_clips.resize(width=720)
# concate_clips.write_videofile(str(path_concate_save), fps=25)
+69
View File
@@ -0,0 +1,69 @@
import os
import numpy as np
import moviepy.editor as mpy
from pathlib import Path
if __name__ == "__main__":
# path_clipA = "/ssdata1/lsen/CODE/voca/data/animation_obama/video_save.mp4"
# path_clipB = "/ssdata1/lsen/CODE/Audio2Motion/experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220216-12H58M21S/obama_infer_20220215-15H12M28S_epoch_120_00.mp4"
# path_audio = "/ssdata1/lsen/CODE/voca/data/audio/obama.wav"
# path_clipA = "/ssdata1/lsen/CODE/voca/data/animation_obama2/video_save.mp4"
# path_clipB = "/ssdata1/lsen/CODE/Audio2Motion/experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220216-13H01M33S/audio_trim_infer_20220215-15H12M28S_epoch_120_00.mp4"
# path_audio = "/yrfs/lsen/DATA/Obama/processing/Bringing-Our-Workplace-Policies-into-the-21st-Century/audio/audio_trim.wav"
path_clipA = "/ssdata1/lsen/CODE/Audio2Motion/experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220214-18H49M33S/audio_trim_60_120s_infer_20220211-15H41M37S_epoch_120_00.mp4"
path_clipB = "/ssdata1/lsen/CODE/Audio2Motion/experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220223-19H47M15S/audio_trim_60_120s_infer_20220217-18H29M20S_epoch_160_00.mp4"
path_clipC = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/deca_render_no_idn_no_pos_60_120s.mp4"
# path_audio = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_60_120s.wav"
path_clipAA = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220223-21H45M05S/audio_trim_60_120s_infer_20220215-15H12M28S_epoch_120_00.mp4"
path_clipBB = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220223-20H51M40S/audio_trim_60_120s_infer_20220222-10H37M51S_epoch_235_00.mp4"
path_clipCC = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/deca_render_no_pos_60_120s.mp4"
path_audio = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_60_120s.wav"
clip_A = mpy.VideoFileClip(path_clipA)
clip_B = mpy.VideoFileClip(path_clipB)
clip_C = mpy.VideoFileClip(path_clipC)
clip_AA = mpy.VideoFileClip(path_clipAA)
clip_BB = mpy.VideoFileClip(path_clipBB)
clip_CC = mpy.VideoFileClip(path_clipCC)
audio = mpy.AudioFileClip(path_audio)
# txtClip = mpy.TextClip('orignal',color='white', kerning = 5, fontsize=18)
# clip_A = mpy.CompositeVideoClip( [clip_A, txtClip.set_pos('top')], size=(512,512))
# txtClip = mpy.TextClip('-pose',color='white', kerning = 5, fontsize=18)
# clip_B = mpy.CompositeVideoClip( [clip_B, txtClip.set_pos('top')], size=(512,512))
# txtClip = mpy.TextClip('-pose-idn',color='white', kerning = 5, fontsize=18)
# clip_C = mpy.CompositeVideoClip( [clip_C, txtClip.set_pos('top')], size=(512,512))
# align to clipGT
duration = min(min(clip_A.duration, clip_B.duration), audio.duration)
clip_A = clip_A.set_duration(duration)
clip_B = clip_B.set_duration(duration)
# clip_C = clip_C.set_duration(duration)
audio = audio.set_duration(duration)
# stack
video = mpy.clips_array([[clip_A, clip_B, clip_C], [clip_AA, clip_BB, clip_CC]]) # clip_C
video = video.set_audio(audio) # audd audio
# save
path_save = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/predict_compare_6.mp4"
# path_save = "/ssdata1/lsen/CODE/Audio2Motion/experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220216-12H58M21S/compare_voca.mp4"
video.write_videofile(path_save, fps=50, logger=None)
print(f"save to > {path_save}")
File renamed without changes.
+123
View File
@@ -0,0 +1,123 @@
from pathlib import Path
import json
import moviepy
from moviepy.editor import VideoFileClip, AudioFileClip
if __name__ == '__main__':
path_root = Path("/yrfs/lsen/DATA/TestData")
vpath_videos = sorted(path_root.glob("raw/*.mp4"), reverse=False)
print(f"Have {len(vpath_videos)} dir files")
# IDs = ["2021-P29"]
# for each video
for i, ipath_item in enumerate(vpath_videos):
iname = ipath_item.stem
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if i < 40: continue
# if iname not in IDs: continue
# data path
ipath_data = path_root.joinpath("processing", ipath_item.stem)
ipath_frame = ipath_data.joinpath("frames")
ipath_video = ipath_data.joinpath("video")
ipath_audio = ipath_data.joinpath("audio")
ipath_infor = ipath_data.joinpath("video/info.json")
ipath_frame.mkdir(parents=True, exist_ok=True)
ipath_video.mkdir(parents=True, exist_ok=True)
ipath_audio.mkdir(parents=True, exist_ok=True)
# # load video info
# if ipath_infor.exists():
# with open(str(ipath_infor), "r") as f:
# info = json.load(f)
# nframe_info = info['nframes']
# load video
video = VideoFileClip(str(ipath_item))
print(f"video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
if video.audio is None:
print("\nERROR: audio info is None")
continue
# save sub video fps=50
ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
if ipath_video_sub.exists():
print("\nERROR: ipath_video_sub.exists()")
continue
else:
video.write_videofile(str(ipath_video_sub), fps=50, audio=True)
print(f"save video > {ipath_video_sub}")
# reload video
video.close()
video = VideoFileClip(str(ipath_video_sub))
print(f"video reload duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# Trim
# video = video.subclip(t_start=20.0, t_end=int(video.duration)-20.0)
# print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
nframes = int(video.duration * video.fps)
# check frames
nframe_real = len(list(ipath_frame.glob("*.jpg")))
if nframe_real == nframes:
print(f"\n Skip: have already done!")
continue
# get audio
audio_sub = video.audio
if audio_sub is None:
print("\nERROR: audio info is None")
print(f"audio_sub duration = {audio_sub.duration}, fps = {audio_sub.fps}, (start, end)=({audio_sub.start},{audio_sub.end}), nframes={int(audio_sub.duration * audio_sub.fps)}")
# save audio_sub
ipath_audio_sub = ipath_audio.joinpath("audio_trim.wav")
audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps)
print(f"save audio > {ipath_audio_sub}")
# # check fps
# if int(video.fps) != 50:
# print(f"\n Skip: fps != 50 realy fps={video.fps}, convert to 50fps")
# ipath_video_save = ipath_data.joinpath("video", f"video_50fps.mp4")
# video.write_videofile(str(ipath_video_save), fps=50.0)
# print(f"save video to > {ipath_video_save}...")
# save video feature
info = {"nframes": nframes,
"fps": video.fps,
"width": video.w,
"height": video.h}
with open(str(ipath_infor), 'w+') as f:
json.dump(info, f)
print(info)
print(f"save video info in -> {ipath_infor}\n")
# save trim video
print(f"write_images_sequence...")
ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
video.write_images_sequence(ipath_format, fps=50)
@@ -0,0 +1,145 @@
import os, sys
import numpy as np
import cv2
from time import time
import argparse
import json
from pathlib import Path
from torch.utils.data import DataLoader
sys.path.insert(0, '/ssdata1/lsen/CODE/DECA_old')
from decalib.deca import DECA
from decalib.datasets.datasets2 import ObamaData
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
def main(args):
device = args.device
# run DECA
deca_cfg.model.use_tex = args.useTex
deca = DECA(config = deca_cfg, device=device)
path_data = Path("/yrfs/lsen/DATA/TestData/processing")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files")
# for each video
for ipath_data in v_dir_videos[1:]:
ivideo_name = ipath_data.stem
print("\nprocessing ...", ivideo_name)
ipath_infor = ipath_data.joinpath("video/info.json")
ipath_frame = ipath_data.joinpath("frames")
ipath_kpt2d = ipath_data.joinpath("DECA_kpt2d")
ipath_kpt3d = ipath_data.joinpath("DECA_kpt3d")
ipath_coeff = ipath_data.joinpath("DECA_coeff")
ipath_vis = ipath_data.joinpath("DECA_vis2")
ipath_kpt2d.mkdir(parents=True, exist_ok=True)
ipath_kpt3d.mkdir(parents=True, exist_ok=True)
ipath_coeff.mkdir(parents=True, exist_ok=True)
ipath_vis.mkdir(parents=True, exist_ok=True)
# load video info
if not ipath_infor.exists():
print(f"\n ERROR: info.json not existing {ipath_infor}")
continue
with open(str(ipath_infor), "r") as f:
info = json.load(f)
nframes = info['nframes']
nframe_real = len(list(ipath_frame.glob("*.jpg")))
if nframe_real != nframes:
print(f"\n ERROR: nframe_real ={nframe_real} / nframe_info ={nframes}")
continue
# check if finish
nkpt2d = len(list(ipath_kpt2d.glob("*.txt")))
if nkpt2d + 10 > nframes:
print(f"Have finised before, nkpt2d={nkpt2d} nframes = {nframes}")
continue
datatest = ObamaData(ipath_frame, iscrop=args.iscrop, face_detector=args.detector)
dataloader = DataLoader(datatest, batch_size=48, shuffle=False, drop_last=False)
for i, ibatch_data in enumerate(dataloader):
batch_names = ibatch_data["names"]
batch_image = ibatch_data["image"].to(device)
if i%50 == 0:
print(f"batch {i:04}/{len(dataloader)}... name = ", batch_names[:5])
codedict = deca.encode(batch_image) # encoder
opdict, visdict = deca.decode(codedict, batch_image) # decoder
for j, jname in enumerate(batch_names):
jpath_kpt2d = ipath_kpt2d.joinpath(f"{jname}.txt")
jpath_kpt3d = ipath_kpt3d.joinpath(f"{jname}.txt")
jpath_coeff = ipath_coeff.joinpath(f"{jname}.json")
np.savetxt(jpath_kpt2d, opdict['landmarks2d'][j].cpu().numpy(), fmt="%.6f")
np.savetxt(jpath_kpt3d, opdict['landmarks3d'][j].cpu().numpy(), fmt="%.6f")
# save coeff
jcodedict = {}
for key, value in codedict.items():
jcodedict[key] = value[j].cpu().numpy()
# print("json = ", jcodedict)
np.save(jpath_coeff, jcodedict)
# save render
for vis_name in ['inputs', 'rendered_images', 'albedo_images', 'shape_images', 'shape_detail_images']:
if vis_name not in visdict.keys():
continue
img = util.tensor2image(visdict[vis_name][j])
cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_{vis_name}.jpg")), img)
# save vis
# cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_vis.jpg")), deca.visualize(visdict))
# break
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='DECA: Detailed Expression Capture and Animation')
parser.add_argument('-i', '--inputpath', default='TestSamples/examples', type=str,
help='path to the test data, can be image folder, image path, image list, video')
parser.add_argument('-d', '--device', default='cuda:2', type=str,
help='set device, cpu for using cpu' )
# process test images
parser.add_argument('--iscrop', default=True, type=lambda x: x.lower() in ['true', '1'],
help='whether to crop input image, set false only when the test image are well cropped' )
parser.add_argument('--detector', default='fan', type=str,
help='detector for cropping face, check decalib/detectors.py for details' )
# save
parser.add_argument('--useTex', default=True, type=lambda x: x.lower() in ['true', '1'],
help='whether to use FLAME texture model to generate uv texture map, \
set it to True only if you downloaded texture model' )
parser.add_argument('--saveVis', default=True, type=lambda x: x.lower() in ['true', '1'],
help='whether to save visualization of output' )
parser.add_argument('--saveKpt', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save 2D and 3D keypoints' )
parser.add_argument('--saveDepth', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save depth image' )
parser.add_argument('--saveObj', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save outputs as .obj, detail mesh will end with _detail.obj. \
Note that saving objs could be slow' )
parser.add_argument('--saveMat', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save outputs as .mat' )
parser.add_argument('--saveImages', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save visualization output as seperate images' )
main(parser.parse_args())
@@ -0,0 +1,95 @@
import sys
import numpy as np
import torch
from pathlib import Path
# common
sys.path.insert(0, "/ssdata1/lsen/CODE/Audio2Motion")
from common.animation import save_images_with_audio
sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old")
from decalib.deca import DECA
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
def tensor2image(tensor):
image = tensor.detach().cpu().numpy()
image = image*255.
image = np.maximum(np.minimum(image, 255), 0)
image = image.transpose(1,2,0)[:,:,[2,1,0]]
return image.astype(np.uint8).copy()
if __name__ == "__main__":
# load data
pid = "1645666605877506" # "2021-P22"
path_root = Path("/yrfs/lsen/DATA/TestData/processing/")
path_data = path_root.joinpath(pid)
path_pos = path_data.joinpath("audio/feat_DECA_pos_trim.npy")
path_idn = path_data.joinpath("audio/feat_DECA_idn_trim.npy")
path_exp = path_data.joinpath("audio/feat_DECA_exp_trim.npy")
path_audio = path_data.joinpath("audio/audio_trim.wav")
# path_audio = path_data.joinpath("audio/audio_trim_60_120s.wav")
data_pos = np.load(path_pos) # N x 6
data_idn = np.load(path_idn) # N x 100
data_exp = np.load(path_exp) # N x 50
N = data_exp.shape[0]
# load mean
path_deca_mean = Path("./data/DECA_LuoXData_mean.npy")
mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
print(mean_dict.keys())
# load deca model
device = torch.device("cuda:0")
deca_cfg.model.use_tex = False
deca_cfg.dataset.image_size = 512
netR = DECA(config = deca_cfg, device=device)
# render
path_save = path_data.joinpath("video/deca_render_no_pos_no_idn.mp4")
v_render_pt = []
nbatch_render = 10
for k in range(0, N, nbatch_render):
codedict = {}
codedict["exp"] = data_exp[k:k+nbatch_render, :50] # (nbatch_render, 50)
nbatch_real = codedict["exp"].shape[0]
codedict["pose"] = np.zeros((nbatch_real, 6)) # (nbatch_render, 6)
codedict["pose"][:, 3:6] = data_pos[k:k+nbatch_render, 3:6]
# codedict["pose"] = data_pos[k:k+nbatch_render, :] # (nbatch_render, 6)
codedict["shape"] = np.zeros((nbatch_real, 100)) # (nabtch_render, 100)
# codedict["shape"] = data_idn[k:k+nbatch_render, :] # (nabatch_render, 100)
# others ==> to mean
mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]]
codedict["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
codedict["light"] = np.repeat([mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
codedict["detail"] = np.repeat([mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
_, visdict_pt = netR.decode_one(codedict, nbatch_real, device)
render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224)
# print(f"render pt shape = {render_pt.shape}")
for m in range(nbatch_real):
# cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...]))
v_render_pt.append(tensor2image(render_pt[m, ...]))
save_images_with_audio(v_render_pt, path_audio, path_save)
+101
View File
@@ -0,0 +1,101 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib import Path
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/TestData/processing') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*"))
print(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_coeff = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
ipath_coeff = ipath_data.joinpath("DECA_coeff")
ipath_frame = ipath_data.joinpath("frames")
ipath_save_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_save_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
ipath_save_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
if ipath_save_exp.exists() and ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_exp}")
continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info["nframes"]
print(f"info = {info}, duration ={nframes / fps / 60}")
# check
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_coeff = list(ipath_coeff.glob("*.npy"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
duration_frame += len(vframe_frame) / 50 / 60
duration_coeff += len(vframe_coeff) / 50 / 60
print(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min")
if len(vframe_frame) != nframes:
print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
# continue
if len(vframe_coeff)+1 < nframes:
print(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}")
# continue
if ipath_save_exp.exists() and ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_exp}")
continue
feat_exp = []
feat_pos = []
feat_idn = []
for j in range(len(vframe_frame)):
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:06d}.json.npy")
if not jpath_coeff.exists():
print(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}")
break
data_coeff = np.load(jpath_coeff, allow_pickle=True).item()
feat_exp.append(data_coeff["exp"])
feat_pos.append(data_coeff["pose"])
feat_idn.append(data_coeff["shape"])
# save
feat_exp = np.array(feat_exp) # (nframe_trim, 50)
feat_pos = np.array(feat_pos) # (nframe_trim, 6)
feat_idn = np.array(feat_idn) # (nframe_trim, 100)
# # pad one
# feat_exp = np.pad(feat_exp, ((0,1),(0,0)), mode="edge")
# feat_pos = np.pad(feat_pos, ((0,1),(0,0)), mode="edge")
# feat_idn = np.pad(feat_idn, ((0,1),(0,0)), mode="edge")
if nframes == feat_idn.shape[0]:
np.save(ipath_save_exp, feat_exp)
np.save(ipath_save_pos, feat_pos)
np.save(ipath_save_idn, feat_idn)
print(f"SAVE OK! exp shape = {feat_exp.shape},pos = {feat_pos.shape}, idn={feat_idn.shape} nframe={nframes}\n save to -> {ipath_save_exp}") # (nframe, 68, 2)
else:
print("ERROR, skip! ")
+62
View File
@@ -0,0 +1,62 @@
import os
import numpy as np
import moviepy.editor as mpy
from pathlib import Path
if __name__ == "__main__":
fps_save = 50
path_save = "/yrfs/lsen/DATA/TestData/processing/1645666605877506/video/predict_compare_3.mp4"
path_clipA = "/yrfs/lsen/DATA/TestData/processing/1645666605877506/video/deca_render.mp4"
path_clipB = "/yrfs/lsen/DATA/TestData/processing/1645666605877506/video/deca_render_no_pos.mp4"
path_clipC = "/yrfs/lsen/DATA/TestData/processing/1645666605877506/video/deca_render_no_pos_no_idn.mp4"
# path_clipAA = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220223-21H45M05S/audio_trim_60_120s_infer_20220215-15H12M28S_epoch_120_00.mp4"
# path_clipBB = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220223-20H51M40S/audio_trim_60_120s_infer_20220222-10H37M51S_epoch_235_00.mp4"
# path_clipCC = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/deca_render_no_pos_60_120s.mp4"
path_audio = "/yrfs/lsen/DATA/TestData/processing/1645666605877506/audio/audio_trim.wav"
clip_A = mpy.VideoFileClip(path_clipA)
clip_B = mpy.VideoFileClip(path_clipB)
clip_C = mpy.VideoFileClip(path_clipC)
# clip_AA = mpy.VideoFileClip(path_clipAA)
# clip_BB = mpy.VideoFileClip(path_clipBB)
# clip_CC = mpy.VideoFileClip(path_clipCC)
audio = mpy.AudioFileClip(path_audio)
# txtClip = mpy.TextClip('orignal',color='white', kerning = 5, fontsize=18)
# clip_A = mpy.CompositeVideoClip( [clip_A, txtClip.set_pos('top')], size=(512,512))
# txtClip = mpy.TextClip('-pose',color='white', kerning = 5, fontsize=18)
# clip_B = mpy.CompositeVideoClip( [clip_B, txtClip.set_pos('top')], size=(512,512))
# txtClip = mpy.TextClip('-pose-idn',color='white', kerning = 5, fontsize=18)
# clip_C = mpy.CompositeVideoClip( [clip_C, txtClip.set_pos('top')], size=(512,512))
# align to clipGT
duration = min(min(clip_A.duration, clip_B.duration), audio.duration)
clip_A = clip_A.set_duration(duration)
clip_B = clip_B.set_duration(duration)
# clip_C = clip_C.set_duration(duration)
audio = audio.set_duration(duration)
# stack
# video = mpy.clips_array([[clip_A, clip_B, clip_C], [clip_AA, clip_BB, clip_CC]]) # clip_C
video = mpy.clips_array([[clip_A, clip_B, clip_C]]) # clip_C
video = video.set_audio(audio) # audd audio
# save
video.write_videofile(path_save, fps=fps_save, logger=None)
print(f"save to > {path_save}")