add audio2mesh_ar

This commit is contained in:
Sen Liang committed 2022-03-14 18:13:13 +08:00
1 parent ded9b27f71
commit e0f24982d1
46 files changed
+3917 -325

No files matched your search

+125
View File
@@ -0,0 +1,125 @@
from pathlib import Path
import json
import moviepy
from moviepy.editor import VideoFileClip, AudioFileClip
if __name__ == '__main__':
# path_root = Path("/yrfs/lsen/DATA/Actor1")
path_root = Path("/yrfs/lsen/DATA/Actor1")
vpath_videos = sorted(path_root.glob("raw/*.MP4"), reverse=False)
print(f"Have {len(vpath_videos)} dir files")
IDs = ["1-29min", "2-23min", "3-27min"]
# 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 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
# Trim
# video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.0)
video = video.subclip(t_start=15.0, t_end=int(video.duration)-15.0)
# video = video.subclip(t_start=5.0, t_end=60.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)
# nframes = len(list(video.iter_frames()))
# print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# if fps != 50
if video.fps != 50:
print("FPS NOT = 50!! ")
# 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)}")
nframes = len(list(video.iter_frames()))
# 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,155 @@
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
device = "cuda:3"
# run DECA
deca_cfg.model.use_tex = args.useTex
deca = DECA(config = deca_cfg, device=device)
# path_data = Path("/yrfs/lsen/DATA/TestData/processing")
path_data = Path("/yrfs/lsen/DATA/Actor1/processing")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files")
# IDs = ["actor-2HD", "actor-3HD"]
# IDs = ["clip_full"]
# for each video
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print("\nprocessing ...", ivideo_name)
# if ivideo_name not in IDs: continue
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, device=device)
dataloader = DataLoader(datatest, batch_size=128, 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%10 == 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
# render_names = ['inputs', 'rendered_images']
# # render_names = ['inputs', 'rendered_images', 'albedo_images', 'shape_images', 'shape_detail_images']
# for vis_name in render_names:
# 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:0', 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())
+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'
path_data = Path("/yrfs/lsen/DATA/Actor1/processing")
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! ")
@@ -25,8 +25,10 @@ def tensor2image(tensor):
if __name__ == "__main__":
# load data
pid = "1645666605877506" # "2021-P22"
path_root = Path("/yrfs/lsen/DATA/TestData/processing/")
pid = "2022-P01" # "2021-P22", actor-2HD
# path_root = Path("/yrfs/lsen/DATA/TestData/processing/")
path_root = Path("/yrfs/lsen/DATA/Actor1/processing")
path_data = path_root.joinpath(pid)
path_pos = path_data.joinpath("audio/feat_DECA_pos_trim.npy")
@@ -53,7 +55,7 @@ if __name__ == "__main__":
netR = DECA(config = deca_cfg, device=device)
# render
path_save = path_data.joinpath("video/deca_render_no_pos_no_idn.mp4")
path_save = path_data.joinpath("video/deca_render_no_pos.mp4")
v_render_pt = []
nbatch_render = 10
for k in range(0, N, nbatch_render):
@@ -67,8 +69,8 @@ if __name__ == "__main__":
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)
# 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"]]
+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}")
+120
View File
@@ -0,0 +1,120 @@
import numpy as np
from pathlib import Path
if __name__ == "__main__":
# fid = "Bringing-Our-Workplace-Policies-into-the-21st-Century"
fid = "AA7A9571"
path_root = Path("/yrfs/lsen/DATA/Actor2/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/Actor2/DECA_Actor2_mean.npy"
np.save(path_save, mean_DECA)
print("save to --> ", path_save)
print(f"mean deca = \n {mean_DECA}")
# Have 21499 frames
# 'cam': array([ 9.8221273e+00, -9.2755520e-04, 2.8869644e-02], dtype=float32),
# 'pose': array([ 0.04063781, -0.00623041, -0.01067916,
# 0.11206006, 0.00411261, 0.02320058], dtype=float32),
# 'exp': array([-0.6491158 , -0.0998203 , 0.10486019, 0.37043977, -0.29840025,
# -0.41017675, 0.327057 , 0.04885808, -0.06325228, 0.4434316 ,
# 0.05493879, 0.66853815, -0.10403663, 0.01440001, 0.25900015,
# -0.46350944, -0.41076973, -0.10278799, -0.08775225, 0.51222765,
# 0.10053314, -0.26408502, 0.11820181, -0.05676581, 0.02643572,
# 0.16058844, -0.11792275, 0.12630136, -0.23953533, -0.10915831,
# -0.16660552, 0.00958887, 0.2679962 , -0.26946628, 0.19901456,
# -0.09804437, -0.03807065, -0.12970755, 0.01078465, 0.19384004,
# -0.06548703, -0.03329738, 0.11319494, -0.02613433, 0.02363422,
# 0.02380173, -0.11122038, 0.13734889, 0.1255798 , 0.13813666],
# dtype=float32),
# 'shape': array([ 0.00951388, -0.22505675, -0.53953266, -0.4397285 , 0.37905172,
# 0.11540896, -0.36891365, -0.218832 , -0.3684414 , 0.24644622,
# 0.6223965 , -0.16298303, -0.35899413, -0.11834836, -0.04909257,
# -0.13188031, 0.35037243, -0.10429271, 0.25443867, -0.18088193,
# 0.16413063, 0.20566346, 0.0501059 , -0.19294368, -0.00809607,
# -0.08120474, -0.07019995, 0.01174292, 0.33962983, 0.04500978,
# -0.25193816, -0.2265279 , 0.14124256, 0.21158281, -0.09555811,
# 0.14076404, 0.04877019, 0.03229018, -0.00235608, -0.08356833,
# 0.09741616, 0.2644469 , 0.13229795, -0.14537199, -0.2314888 ,
# -0.48501098, -0.13492987, -0.13772976, -0.18299519, -0.11046503,
# 0.04127223, -0.4613573 , -0.06382176, 0.08914807, 0.08793663,
# 0.11848436, 0.03956904, 0.04172374, -0.04793308, 0.30301905,
# -0.06345342, 0.04190513, 0.13665007, -0.03253645, 0.08728135,
# 0.06684338, 0.02282041, 0.00583193, -0.11710295, -0.06365721,
# -0.00492529, -0.14196472, 0.03584495, -0.00815303, -0.00147824,
# 0.2087406 , -0.11037645, -0.04405028, -0.129121 , 0.03147175,
# -0.03467533, -0.00330734, 0.13060835, -0.02846657, 0.05666886,
# -0.07806987, -0.17371002, 0.05375125, -0.04018219, 0.08453278,
# -0.05303599, -0.11419729, -0.16071273, -0.00130347, -0.1172006 ,
# -0.06073425, -0.03826162, -0.0587554 , -0.06399846, -0.14208533],
# dtype=float32)}
+130
View File
@@ -0,0 +1,130 @@
from pathlib import Path
import json
import moviepy
from moviepy.editor import VideoFileClip, AudioFileClip
if __name__ == '__main__':
# path_root = Path("/yrfs/lsen/DATA/Actor1")
path_raw = Path("/ssdata1/cf/data/raw/20220311")
path_root = Path("/yrfs/lsen/DATA/Actor2")
vpath_videos = sorted(path_raw.glob("*.MP4"), reverse=False)
print(f"Have {len(vpath_videos)} dir files")
# IDs = ["clip_full"]
# for each video
for i, ipath_item in enumerate(vpath_videos[2:]):
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():
continue
# 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
# Trim
# video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.0) before 03.14
video = video.subclip(t_start=15.0, t_end=int(video.duration)-15.0)
# video = video.subclip(t_start=5.0, t_end=60.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)
# nframes = len(list(video.iter_frames()))
# print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# if fps != 50
if video.fps != 50:
print("FPS NOT = 50!! ")
# 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)}")
nframes = len(list(video.iter_frames()))
# 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,157 @@
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
device = "cuda:0"
# run DECA
deca_cfg.model.use_tex = args.useTex
deca = DECA(config = deca_cfg, device=device)
# path_data = Path("/yrfs/lsen/DATA/TestData/processing")
path_data = Path("/yrfs/lsen/DATA/Actor2/processing")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files")
# IDs = ["actor-2HD", "actor-3HD"]
# IDs = ["clip_full"]
# for each video
for i, ipath_data in enumerate(v_dir_videos):
ivideo_name = ipath_data.stem
print(f"\n processing {i}/{len(v_dir_videos)} ...", ivideo_name)
# if ivideo_name not in IDs: continue
if i > 18: break
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, device=device)
dataloader = DataLoader(datatest, batch_size=128, 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%10 == 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
# render_names = ['inputs', 'rendered_images']
# # render_names = ['inputs', 'rendered_images', 'albedo_images', 'shape_images', 'shape_detail_images']
# for vis_name in render_names:
# 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:0', 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())
@@ -7,11 +7,12 @@ from pathlib import Path
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/TestData/processing') # '../data/trinity/source'
# path_data = Path('/yrfs/lsen/DATA/TestData/processing') # '../data/trinity/source'
path_data = Path("/yrfs/lsen/DATA/Actor2/processing")
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:
@@ -0,0 +1,103 @@
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
device = torch.device("cuda:4")
pid = "AA7A9568" # "2021-P22", actor-2HD
# path_root = Path("/yrfs/lsen/DATA/TestData/processing/")
path_root = Path("/yrfs/lsen/DATA/Actor2/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_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]
data_pos = np.load(path_pos)[:6000] # N x 6
data_idn = np.load(path_idn)[:6000] # N x 100
data_exp = np.load(path_exp)[:6000] # N x 50
N = data_exp.shape[0]
# load mean
path_deca_mean = Path("./data/Actor2/DECA_Actor2_mean.npy")
mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
print(mean_dict.keys())
# load deca model
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_trim_120s.mp4")
v_render_pt = []
nbatch_render = 5
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)
@@ -0,0 +1,182 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
from scipy import interpolate
import torchaudio
def landmark_resample_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/Actor2/processing")
path_save = Path('data/Actor2/Actor2-raw-2h') # 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 = set([ipath.stem for ipath in v_dir_videos])
# print(f"vids total= {vids}")
vid_test = set(["AA7A9568"])
vid_valid = set(["AA7A9569"])
vid_train = vids - vid_test - vid_valid
# vids = set(["2021-P09", "2021-P14", "2021-P22"])
# vid_test = set(["2021-P09" ])
# vid_valid = set(["2021-P14" ])
# vid_train = set(["2021-P22" ])
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
# if vid in vid_test: continue
# if vid in vid_valid:continue
if durations_train / 3600 > 2: break
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
if not ipath_speech.exists():
print(f"NOT existing {ipath_speech}")
continue
if not ipath_feat_exp.exists():
print(f"NOT existing {ipath_feat_exp}")
continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info['nframes']
print(f"info={info}, duration = {nframes/fps}")
assert fps == 50, "fps should be 50"
# laod motion
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)
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}")
# 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)}")
# ####################################
# # 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
data_train[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
if vid in vid_valid:
durations_valid += nframes/fps
data_valid[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
if vid in vid_test:
durations_test += nframes/fps
data_test[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
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 frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
print(f"Total frames: data_valid ({durations_valid / 60 } min) ({durations_valid / 3600 } h) , ids = ({len(data_valid)})")
print(f"Total frames: data_test ({durations_test / 60 } min) ({durations_test / 3600 } h) , ids = ({len(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 / 60 } min) ({durations_train / 3600 } h) , data_test ({durations_test / 60 } min) data_valid({durations_valid / 60} min)")
print(f"--> {path_save}")
+65
View File
@@ -0,0 +1,65 @@
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/Actor2/processing/AA7A9568/video/predict_compare_22.mp4"
path_clipA = "experiments/audio2mesh/infer_audio2mesh_CN_20220312/20220314-15H08M06S/audio_trim_120s_infer_20220313-13H26M47S_epoch_100_002.mp4"
path_clipB = "/yrfs/lsen/DATA/Actor2/processing/AA7A9568/video/deca_render_no_pose_120s.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/Actor2/processing/AA7A9568/audio/audio_trim_120s.wav"
clip_A = mpy.VideoFileClip(path_clipA)
clip_B = mpy.VideoFileClip(path_clipB)
# clip_C = mpy.VideoFileClip(path_clipC)
print(f"clip_A duration = {clip_A.duration}, clip_B duration = {clip_B.duration}")
# clip_AA = mpy.VideoFileClip(path_clipAA)
# clip_BB = mpy.VideoFileClip(path_clipBB)
# clip_CC = mpy.VideoFileClip(path_clipCC)
audio = mpy.AudioFileClip(path_audio)
print(f"audio duration = {audio.duration}")
# 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)
print(f"duration min = {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
video = video.set_audio(audio) # audd audio
# save
video.write_videofile(path_save, fps=fps_save, logger=None)
print(f"save to > {path_save}")
@@ -31,12 +31,9 @@ if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/LuoXData/processing2') # '../data/trinity/source'
path_save = Path('data/LuoXData-raw-deca-3min') # processing
path_save = Path('data/LuoXData-raw-16h') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files, \n {v_dir_videos[:3]}")
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
print(f"Have {len(v_dir_videos)} dir files")
@@ -44,14 +41,14 @@ if __name__ == "__main__":
vids = set([ipath.stem for ipath in v_dir_videos])
# 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
vid_test = set(["2021-P09", "2021-P22"])
vid_valid = set(["2021-P14", "2021-P20"])
vid_train = vids - vid_test - vid_valid
vids = set(["2021-P09", "2021-P14", "2021-P22"])
vid_test = set(["2021-P09" ])
vid_valid = set(["2021-P14" ])
vid_train = set(["2021-P22" ])
# vids = set(["2021-P09", "2021-P14", "2021-P22"])
# vid_test = set(["2021-P09" ])
# vid_valid = set(["2021-P14" ])
# vid_train = set(["2021-P22" ])
print(f"vid test= {vid_test} \nvalid= {vid_valid}")
print(f"vid train= {vid_train}")
@@ -63,6 +60,9 @@ if __name__ == "__main__":
vid = ipath_data.stem
if vid not in vids: continue
if vid in vid_test: continue
if vid in vid_valid:continue
print(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
@@ -70,6 +70,7 @@ if __name__ == "__main__":
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")
ipath_idx = ipath_data.joinpath("audio/idx_w150_20220228-18H41M46S_175.npy")
# check existing
if not ipath_speech.exists():
@@ -93,6 +94,7 @@ if __name__ == "__main__":
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_idx = np.load(ipath_idx, allow_pickle=True).tolist() # (nframe_for_sampling, ), set
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}"
@@ -115,17 +117,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]
####################################
# ####################################
# # 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
@@ -136,40 +137,49 @@ if __name__ == "__main__":
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
"idx_sampling": data_idx,
}
if durations_train / 3600 > 16:
break
if vid in vid_valid:
durations_valid += nframes/fps
# if vid in vid_valid:
# durations_valid += nframes/fps
data_valid[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
# data_valid[vid] = {
# "fps": info["fps"],
# "sr": 16000,
# "nframe": nframes,
# "data_motion": data_motion,
# "data_speech": audio_raw,
# "data_shape": data_idn,
# "idx_sampling": data_idx,
# }
if vid in vid_test:
durations_test += nframes/fps
# if vid in vid_test:
# durations_test += nframes/fps
# data_test[vid] = {
# "fps": info["fps"],
# "sr": 16000,
# "nframe": nframes,
# "data_motion": data_motion,
# "data_speech": audio_raw,
# "data_shape": data_idn,
# "idx_sampling": data_idx,
# }
data_test[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
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)
# 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 / 60 } min) ({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) , ids = ({len(data_train)})")
# 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 / 60 } min) ({durations_train / 3600 } h) , data_test ({durations_test / 60 } min) data_valid({durations_valid / 60} min)")
print(f"--> {path_save}")
+12 -13
View File
@@ -18,13 +18,14 @@ if __name__ == "__main__":
path_clipA = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220223-19H47M15S/audio_trim_60_120s_infer_20220217-18H29M20S_epoch_160_00.mp4"
path_clipB = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220302-10H48M39S/audio_trim_60_120s_infer_20220228-18H41M46S_epoch_175_00.mp4"
path_clipC = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/deca_render_no_idn_no_pos_60_120s.mp4"
path_clipC = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220303-19H05M13S/audio_trim_60_120s_infer_20220303-14H22M20S_epoch_025_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_CN_20220208/20220223-20H51M40S/audio_trim_60_120s_infer_20220222-10H37M51S_epoch_235_00.mp4"
path_clipBB = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220302-10H38M39S/audio_trim_60_120s_infer_20220225-19H08M53S_epoch_280_00.mp4"
path_clipCC = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/deca_render_no_pos_60_120s.mp4"
# path_clipAA = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220223-20H51M40S/audio_trim_60_120s_infer_20220222-10H37M51S_epoch_235_00.mp4"
# path_clipBB = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220302-10H38M39S/audio_trim_60_120s_infer_20220225-19H08M53S_epoch_280_00.mp4"
path_clipD = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/deca_render_no_pos_60_120s.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"
@@ -34,10 +35,11 @@ if __name__ == "__main__":
clip_A = mpy.VideoFileClip(path_clipA)
clip_B = mpy.VideoFileClip(path_clipB)
clip_C = mpy.VideoFileClip(path_clipC)
clip_D = mpy.VideoFileClip(path_clipD)
clip_AA = mpy.VideoFileClip(path_clipAA)
clip_BB = mpy.VideoFileClip(path_clipBB)
clip_CC = mpy.VideoFileClip(path_clipCC)
# clip_AA = mpy.VideoFileClip(path_clipAA)
# clip_BB = mpy.VideoFileClip(path_clipBB)
# clip_CC = mpy.VideoFileClip(path_clipCC)
audio = mpy.AudioFileClip(path_audio)
@@ -59,15 +61,12 @@ if __name__ == "__main__":
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 = 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_D]]) # clip_C
video = video.set_audio(audio) # audd audio
# save
path_save = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/predict_compare_20220302.mp4"
path_save = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/predict_compare4_20220303.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}")
@@ -6,7 +6,7 @@ from scipy import interpolate
def convert_fps(y, source_fps = 30, target_fps=25):
"""
y, N x 136, with 30fps
y, nframes x nc_feat (with source_fps)
"""
nsteps = y.shape[0]
@@ -27,7 +27,7 @@ def convert_fps(y, source_fps = 30, target_fps=25):
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 = Path('data/obama-raw-deca-8h-50fps') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
@@ -38,6 +38,7 @@ if __name__ == "__main__":
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)
@@ -48,12 +49,15 @@ if __name__ == "__main__":
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
if vid not in vids: continue
if vid in vid_test: continue
if vid in vid_valid:continue
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_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
ipath_speech = ipath_data.joinpath("audio/audio_trim.wav")
if not ipath_speech.exists():
@@ -90,7 +94,7 @@ if __name__ == "__main__":
# 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_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)
@@ -103,10 +107,9 @@ if __name__ == "__main__":
# 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)
# 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]}"
# 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}")
@@ -131,38 +134,43 @@ if __name__ == "__main__":
"nframe": nframe_convert,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_shape,
# "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 durations_train / 3600 > 8:
break
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,
}
# 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)
# 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"Total frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
# 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}")
+19 -10
View File
@@ -8,23 +8,31 @@ 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"
fps_save = 50
# 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_save = "./data/compare_test_obama.mp4"
path_clipA = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220303-14H18M22S/obama_train_infer_20220217-17H36M22S_epoch_115_00.mp4"
path_clipB = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220303-14H15M46S/obama_train_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_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"
path_audio = "/yrfs/cf/data/render/obama_train.wav"
# 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_C = mpy.VideoFileClip(path_clipC)
# clip_AA = mpy.VideoFileClip(path_clipAA)
# clip_BB = mpy.VideoFileClip(path_clipBB)
@@ -42,16 +50,17 @@ if __name__ == "__main__":
# 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)
# duration = min(min(clip_A.duration, clip_C.duration), audio.duration)
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)
# 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 = mpy.clips_array([[clip_A, clip_B]]) # clip_C
video = video.set_audio(audio) # audd audio
# save
+15 -19
View File
@@ -6,12 +6,13 @@ from moviepy.editor import VideoFileClip, AudioFileClip
if __name__ == '__main__':
# path_root = Path("/yrfs/lsen/DATA/Actor1")
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"]
IDs = ["clip_full"]
# for each video
for i, ipath_item in enumerate(vpath_videos):
@@ -19,7 +20,7 @@ if __name__ == '__main__':
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("processing", ipath_item.stem)
@@ -39,21 +40,24 @@ if __name__ == '__main__':
# 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
# Trim
# video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.0)
# video = video.subclip(t_start=5.0, t_end=60.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)
# nframes = len(list(video.iter_frames()))
# 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
@@ -61,23 +65,17 @@ if __name__ == '__main__':
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)
nframes = len(list(video.iter_frames()))
# 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
# get audio
audio_sub = video.audio
@@ -91,7 +89,6 @@ if __name__ == '__main__':
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")
@@ -111,7 +108,6 @@ if __name__ == '__main__':
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"
@@ -22,13 +22,18 @@ def main(args):
deca = DECA(config = deca_cfg, device=device)
path_data = Path("/yrfs/lsen/DATA/TestData/processing")
# path_data = Path("/yrfs/lsen/DATA/Actor1/processing")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files")
# IDs = ["actor-2HD", "actor-3HD"]
IDs = ["clip_full"]
# for each video
for ipath_data in v_dir_videos[1:]:
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print("\nprocessing ...", ivideo_name)
if ivideo_name not in IDs: continue
ipath_infor = ipath_data.joinpath("video/info.json")
ipath_frame = ipath_data.joinpath("frames")
@@ -50,7 +55,7 @@ def main(args):
with open(str(ipath_infor), "r") as f:
info = json.load(f)
nframes = info['nframes']
nframes = info['nframes']
nframe_real = len(list(ipath_frame.glob("*.jpg")))
@@ -58,7 +63,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:
@@ -66,7 +70,7 @@ def main(args):
continue
datatest = ObamaData(ipath_frame, iscrop=args.iscrop, face_detector=args.detector)
dataloader = DataLoader(datatest, batch_size=48, shuffle=False, drop_last=False)
dataloader = DataLoader(datatest, batch_size=64, shuffle=False, drop_last=False)
for i, ibatch_data in enumerate(dataloader):
@@ -114,7 +118,7 @@ if __name__ == '__main__':
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,
parser.add_argument('-d', '--device', default='cuda:0', 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'],
+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'
path_data = Path("/yrfs/lsen/DATA/Actor1/processing")
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! ")
@@ -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 = "2022-P01" # "2021-P22", actor-2HD
# path_root = Path("/yrfs/lsen/DATA/TestData/processing/")
path_root = Path("/yrfs/lsen/DATA/Actor1/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.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)