diff --git a/scripts/Actor3Data/run-00-mean-coeff.py b/scripts/Actor3Data/run-00-mean-coeff.py new file mode 100644 index 0000000..7bfba31 --- /dev/null +++ b/scripts/Actor3Data/run-00-mean-coeff.py @@ -0,0 +1,117 @@ +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() + + 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)} \ No newline at end of file diff --git a/scripts/Actor3Data/run-01-prepare-data.py b/scripts/Actor3Data/run-01-prepare-data.py new file mode 100755 index 0000000..a867f24 --- /dev/null +++ b/scripts/Actor3Data/run-01-prepare-data.py @@ -0,0 +1,133 @@ +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/20220331") + path_root = Path("/mfs/lsen/DATA/Actor3") + + vpath_videos = sorted(path_raw.glob("**/*.MP4"), reverse=False) + print(f"Have {len(vpath_videos)} dir files") + + # IDs = ["clip_full"] + durations = 0 + # 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 & check + if ipath_infor.exists(): + # continue + with open(str(ipath_infor), "r") as f: + info = json.load(f) + nframe_info = info['nframes'] + + # check frames + nframe_real = len(list(ipath_frame.glob("*.jpg"))) + if nframe_real == nframe_info: + print(f"\n Skip: have already done!") + continue + + # 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 + + durations += video.duration + print(f"\n\t -> Total durations = ({durations / 60 } min) ({durations / 3600 } h))") + # 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())) + + + + # 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) + + + + diff --git a/scripts/Actor3Data/run-20-deca-reconstruction.py b/scripts/Actor3Data/run-20-deca-reconstruction.py new file mode 100644 index 0000000..e241b24 --- /dev/null +++ b/scripts/Actor3Data/run-20-deca-reconstruction.py @@ -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:2" + + # 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 > 25: 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()) + + + diff --git a/scripts/Actor3Data/run-21-features-3dmm.py b/scripts/Actor3Data/run-21-features-3dmm.py new file mode 100644 index 0000000..5d0cb0a --- /dev/null +++ b/scripts/Actor3Data/run-21-features-3dmm.py @@ -0,0 +1,100 @@ +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/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: + 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! ") + + + diff --git a/scripts/Actor3Data/run-22-deca-render-video.py b/scripts/Actor3Data/run-22-deca-render-video.py new file mode 100644 index 0000000..4bbf54a --- /dev/null +++ b/scripts/Actor3Data/run-22-deca-render-video.py @@ -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) + + + + + + diff --git a/scripts/Actor3Data/run-41-train-dict-data-raw-deca.py b/scripts/Actor3Data/run-41-train-dict-data-raw-deca.py new file mode 100644 index 0000000..e69bb83 --- /dev/null +++ b/scripts/Actor3Data/run-41-train-dict-data-raw-deca.py @@ -0,0 +1,188 @@ +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-7h') # 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", "AA7A9577"]) + # vid_valid = set(["AA7A9569", "AA7A9578"]) + vid_train = set(['AA7A9570', 'AA7A9571', 'AA7A9572', 'AA7A9573', 'AA7A9574', 'AA7A9575', 'AA7A9576', 'AA7A9579', + 'AA7A9580', 'AA7A9582', 'AA7A9583', 'AA7A9584', 'AA7A9585', 'AA7A9600', 'AA7A9601', 'AA7A9602', + 'AA7A9603', 'AA7A9604', 'AA7A9605', 'AA7A9606', 'AA7A9607', 'AA7A9608', 'AA7A9609', 'AA7A9610', + 'AA7A9611', 'AA7A9612', 'AA7A9613', 'AA7A9614', 'AA7A9615', 'AA7A9616', 'AA7A9617', 'AA7A9618', + 'AA7A9619', 'AA7A9620', 'AA7A9621', 'AA7A9622', 'AA7A9623', 'AA7A9625', 'AA7A9626', 'AA7A9627', + 'AA7A9628']) + + # vid_train = vids - vid_test - vid_valid + vid_valid = vids - vid_test - vid_train + + # 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 > 6: 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, + } + + + + 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)})") + + + 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 / 60 } min) ({durations_train / 3600 } h) , data_test ({durations_test / 60 } min) data_valid({durations_valid / 60} min)") + + print(f"--> {path_save}") \ No newline at end of file diff --git a/scripts/Actor3Data/stack_video.py b/scripts/Actor3Data/stack_video.py new file mode 100644 index 0000000..13598c8 --- /dev/null +++ b/scripts/Actor3Data/stack_video.py @@ -0,0 +1,66 @@ +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_3_AR.mp4" + + path_clipA = "experiments/audio2mesh/infer_audio2mesh_CN_20220312/20220314-15H08M06S/audio_trim_120s_infer_20220313-13H26M47S_epoch_100_002.mp4" + path_clipB = "experiments/audio2mesh/infer_audio2meshAR_CN_20220314/20220317-15H57M26S/audio_trim_120s_infer_20220316-23H56M06S_epoch_050_002.mp4" + path_clipC = "/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]]) # 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}") + + + diff --git a/scripts/Actor3Data/valid-test-train.json b/scripts/Actor3Data/valid-test-train.json new file mode 100644 index 0000000..e69de29