From a4c53e326548cbb7df96547dbeb7460291287933 Mon Sep 17 00:00:00 2001 From: liangsen Date: Thu, 26 May 2022 10:02:37 +0800 Subject: [PATCH] add actor7Data --- scripts/Actor5Data/run-02-crop-transform-2.py | 8 +- scripts/Actor5Data/run-09-remove-files.py | 24 +- .../Actor5Data/run-20-deca-reconstruction.py | 12 +- .../run-42-train-annodb-ganrender.py | 41 +++- .../Actor6Data/run-20-deca-reconstruction.py | 1 - scripts/Actor6Data/run-21-features-3dmm.py | 7 +- scripts/Actor6Data/run-23-mean-coeff.py | 3 +- .../run-41-train-annodb-audio2mesh.py | 2 +- .../run-42-train-annodb-ganrender.py | 41 +++- scripts/Actor7Data/run-01-detect-lm68.py | 81 +++++++ scripts/Actor7Data/run-01-mean-bbox.py | 99 +++++++++ scripts/Actor7Data/run-01-prepare-data.py | 171 +++++++++++++++ scripts/Actor7Data/run-02-crop-transform-2.py | 207 ++++++++++++++++++ scripts/Actor7Data/run-02-crop-transform.py | 200 +++++++++++++++++ scripts/Actor7Data/run-09-remove-files.py | 31 +++ scripts/Actor7Data/run-10-generate-mask.py | 111 ++++++++++ .../Actor7Data/run-20-deca-reconstruction.py | 157 +++++++++++++ scripts/Actor7Data/run-21-features-3dmm.py | 110 ++++++++++ scripts/Actor7Data/run-22-concat-3dmm.py | 103 +++++++++ scripts/Actor7Data/run-23-mean-coeff.py | 92 ++++++++ .../run-41-train-annodb-audio2mesh.py | 174 +++++++++++++++ .../run-42-train-annodb-ganrender.py | 177 +++++++++++++++ 22 files changed, 1802 insertions(+), 50 deletions(-) create mode 100644 scripts/Actor7Data/run-01-detect-lm68.py create mode 100644 scripts/Actor7Data/run-01-mean-bbox.py create mode 100755 scripts/Actor7Data/run-01-prepare-data.py create mode 100644 scripts/Actor7Data/run-02-crop-transform-2.py create mode 100644 scripts/Actor7Data/run-02-crop-transform.py create mode 100644 scripts/Actor7Data/run-09-remove-files.py create mode 100644 scripts/Actor7Data/run-10-generate-mask.py create mode 100644 scripts/Actor7Data/run-20-deca-reconstruction.py create mode 100644 scripts/Actor7Data/run-21-features-3dmm.py create mode 100644 scripts/Actor7Data/run-22-concat-3dmm.py create mode 100644 scripts/Actor7Data/run-23-mean-coeff.py create mode 100644 scripts/Actor7Data/run-41-train-annodb-audio2mesh.py create mode 100644 scripts/Actor7Data/run-42-train-annodb-ganrender.py diff --git a/scripts/Actor5Data/run-02-crop-transform-2.py b/scripts/Actor5Data/run-02-crop-transform-2.py index f53acdd..69dba32 100644 --- a/scripts/Actor5Data/run-02-crop-transform-2.py +++ b/scripts/Actor5Data/run-02-crop-transform-2.py @@ -141,7 +141,7 @@ def processing_one_folder(ipath_frame, ipath_ldmks, ipath_fcrop, ipath_tfrom, ip if __name__ == "__main__": actor = "Actor5" - sub_folder = "processing" # smile, processing, processing2 + sub_folder = "smile" # smile, processing, processing2 # logger logger = Logger(f"./data/{actor}", postfix=f"crop-transform-{sub_folder}") @@ -163,8 +163,7 @@ if __name__ == "__main__": logger.info(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ") # if iname not in ["4R3A0069"]: continue - if iname not in ["4R3A0068", "4R3A0066", "4R3A0065"]: continue - + # if iname not in ["4R3A0068", "4R3A0066", "4R3A0065"]: continue # if iname not in IDs: continue ipath_ldmks = ipath_item.joinpath("landmarks_FAN") @@ -200,9 +199,6 @@ if __name__ == "__main__": ) - - - diff --git a/scripts/Actor5Data/run-09-remove-files.py b/scripts/Actor5Data/run-09-remove-files.py index d96fdfd..ef45211 100644 --- a/scripts/Actor5Data/run-09-remove-files.py +++ b/scripts/Actor5Data/run-09-remove-files.py @@ -4,28 +4,24 @@ from pathlib2 import Path if __name__ == "__main__": - path_data = Path("/ssdata1/lsen/DATA/Actor5/processing") + path_data = Path("/ssdata1/lsen/DATA/Actor6/processing") vpath_videos = sorted(path_data.glob("*"), reverse=False) print(f"Have {len(vpath_videos)} dir files") + clear_folders = ["frames_crop_parse_512", "frames_crop_parse_skin_512", "frames_crop_parse_vis_512", "DECA_kpt2d", "DECA_coeff", "DECA_kpt3d"] + # clear_folders = ["frames_crop_parse_512", "frames_crop_parse_skin_512", "frames_crop_parse_vis_512", "DECA_coeff"] - # IDs = ["2-23min"] # for each word for i, ipath_item in enumerate(vpath_videos): iname = ipath_item.stem print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ") - # if iname not in IDs: continue - ipath_fcrop = ipath_item.joinpath("frames_crop") - ipath_tfrom = ipath_item.joinpath("frames_crop_tform") + for kfolder in clear_folders: + # if iname not in IDs: continue + ipath_fcrop = ipath_item.joinpath(kfolder) - if ipath_fcrop.exists(): - cmd = f"rm -rf {str(ipath_fcrop)}" - print("RUN: ", cmd) - os.system(cmd) - - if ipath_tfrom.exists(): - cmd = f"rm -rf {str(ipath_tfrom)}" - print("RUN: ", cmd) - os.system(cmd) \ No newline at end of file + if ipath_fcrop.exists(): + cmd = f"rm -rf {str(ipath_fcrop)}" + print("RUN: ", cmd) + os.system(cmd) \ No newline at end of file diff --git a/scripts/Actor5Data/run-20-deca-reconstruction.py b/scripts/Actor5Data/run-20-deca-reconstruction.py index 025e271..b61ca4b 100644 --- a/scripts/Actor5Data/run-20-deca-reconstruction.py +++ b/scripts/Actor5Data/run-20-deca-reconstruction.py @@ -17,13 +17,13 @@ from decalib.utils.config import cfg as deca_cfg def main(args): # device = args.device - device = "cuda:3" + device = "cuda:8" # 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("/ssdata1/lsen/DATA/Actor5/processing") + path_data = Path("/ssdata1/lsen/DATA/Actor5/smile") v_dir_videos = sorted(path_data.glob("*"), reverse=False) print(f"Have {len(v_dir_videos)} dir files") @@ -68,10 +68,10 @@ def main(args): continue # check if finish - nkpt2d = len(list(ipath_coeff.glob("*.npy"))) - if nkpt2d + 10 > nframes: - print(f"Have finised before, nkpt2d={nkpt2d} nframes = {nframes}") - continue + # nkpt2d = len(list(ipath_coeff.glob("*.npy"))) + # 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) diff --git a/scripts/Actor5Data/run-42-train-annodb-ganrender.py b/scripts/Actor5Data/run-42-train-annodb-ganrender.py index 1b3e137..b1ef6c9 100644 --- a/scripts/Actor5Data/run-42-train-annodb-ganrender.py +++ b/scripts/Actor5Data/run-42-train-annodb-ganrender.py @@ -3,6 +3,7 @@ from loguru import logger import numpy as np from pathlib2 import Path import torchaudio +from scipy.signal import savgol_filter import os, sys sys.path.insert(0, os.getcwd()) @@ -12,7 +13,7 @@ from common.logger import Logger if __name__ == "__main__": actor= "Actor5" - sub_folder = "processing" # processing, smile, body + sub_folder = "smile" # processing, smile, body path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}") path_save = Path(f'data/{actor}/data-render-{sub_folder}-1h') @@ -63,11 +64,13 @@ if __name__ == "__main__": logger.info(f"\n\n processing the {i}-th video {vid} ... ") ipath_info = ipath_data.joinpath("video/info.json") - # ipath_coeff = ipath_data.joinpath("DECA_coeff") # DECA coeff of shape/exp/light - ipath_coeff = ipath_data.joinpath("deca_coeff_512") # DECA coeff of shape/exp/light - ipath_frame = ipath_data.joinpath("frames_crop_512") # cropped image 512x512 - ipath_ldmks = ipath_data.joinpath("frames_crop_ldmks_512") # cropped landmarks within 512x512 - ipath_parse = ipath_data.joinpath("frames_crop_parse_skin_512") # cropped mask + # ipath_coeff = ipath_data.joinpath("DECA_coeff") # DECA coeff of shape/exp/light + ipath_coeff = ipath_data.joinpath("deca_coeff_512") # DECA coeff of shape/exp/light + ipath_frame = ipath_data.joinpath("frames_crop_512") # cropped image 512x512 + ipath_ldmks = ipath_data.joinpath("frames_crop_ldmks_512") # cropped landmarks within 512x512 + ipath_parse = ipath_data.joinpath("frames_crop_mask_512") # cropped mask + + # ipath_parse = ipath_data.joinpath("frames_crop_parse_skin_512") # cropped mask # check info existing if not ipath_info.exists(): @@ -101,6 +104,22 @@ if __name__ == "__main__": ipath_feat_coeff = ipath_data.joinpath("audio/feat_deca_coeff_512p.npy") data_coeff = np.load(ipath_feat_coeff) # (nframe, 236) data_coeff = data_coeff.astype(np.float16) # convert float16 + + # load landmark + feat_ldmk = [] + for k in range(num_ldmks): + kpath_ldmk = ipath_ldmks.joinpath(f"frame-{k:06d}.txt") + if not kpath_ldmk.exists(): + logger.info(f"\n ERROR: landmark path NOT FOUND! -> {kpath_ldmk}") + break + + kpt = np.loadtxt(kpath_ldmk) # (68, 2) + assert kpt.shape[0] == 68, f"the kpt shape ={kpt.shape}, --> {kpath_ldmk}" + feat_ldmk.append(kpt) + + # smooth landmark it + feat_ldmk = np.array(feat_ldmk) # (N, 68, 2) + feat_ldmk = savgol_filter(feat_ldmk, window_length=5, polyorder=3, axis=0, mode='nearest') if vid in vid_train: @@ -112,7 +131,8 @@ if __name__ == "__main__": "sr": 16000, "nframe": nframes, "path_data": str(ipath_data), - "data_coeff": data_coeff + "data_coeff": data_coeff, + "data_ldmks": feat_ldmk } if vid in vid_valid: @@ -124,7 +144,8 @@ if __name__ == "__main__": "sr": 16000, "nframe": nframes, "path_data": str(ipath_data), - "data_coeff": data_coeff + "data_coeff": data_coeff, + "data_ldmks": feat_ldmk } if vid in vid_test: @@ -136,9 +157,11 @@ if __name__ == "__main__": "sr": 16000, "nframe": nframes, "path_data": str(ipath_data), - "data_coeff": data_coeff + "data_coeff": data_coeff, + "data_ldmks": feat_ldmk } + logger.info(f"Total frames: data_train ({durations_train/60:.2f} min) ({durations_train/3600:.2f} h) , ids = ({len(data_train)})") logger.info(f"Total frames: data_valid ({durations_valid/60:.2f} min) ({durations_valid/3600:.2f} h) , ids = ({len(data_valid)})") logger.info(f"Total frames: data_test ({durations_test/60:.2f} min) ({durations_test/3600:.2f} h) , ids = ({len(data_test)})") diff --git a/scripts/Actor6Data/run-20-deca-reconstruction.py b/scripts/Actor6Data/run-20-deca-reconstruction.py index 62cd4d3..81b7472 100644 --- a/scripts/Actor6Data/run-20-deca-reconstruction.py +++ b/scripts/Actor6Data/run-20-deca-reconstruction.py @@ -14,7 +14,6 @@ from decalib.utils import util from decalib.utils.config import cfg as deca_cfg - def main(args): # device = args.device diff --git a/scripts/Actor6Data/run-21-features-3dmm.py b/scripts/Actor6Data/run-21-features-3dmm.py index 32978f9..2c476a8 100644 --- a/scripts/Actor6Data/run-21-features-3dmm.py +++ b/scripts/Actor6Data/run-21-features-3dmm.py @@ -66,9 +66,9 @@ if __name__ == "__main__": logger.info(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}") continue - if ipath_save_exp.exists() and ipath_save_pos.exists(): - logger.info(f"ipath_save_exp have already save > {ipath_save_exp}") - continue + # if ipath_save_exp.exists() and ipath_save_pos.exists(): + # logger.info(f"ipath_save_exp have already save > {ipath_save_exp}") + # continue feat_exp = [] feat_pos = [] @@ -82,6 +82,7 @@ if __name__ == "__main__": 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"]) diff --git a/scripts/Actor6Data/run-23-mean-coeff.py b/scripts/Actor6Data/run-23-mean-coeff.py index 715823b..fed1fe6 100644 --- a/scripts/Actor6Data/run-23-mean-coeff.py +++ b/scripts/Actor6Data/run-23-mean-coeff.py @@ -12,7 +12,8 @@ if __name__ == "__main__": # fid = "4R3A0071" actor= "Actor6" sub_folder = "processing2" # processing, smile, body - fid = '4R3A0139' + fid = '4R3A0140' + # logger logger = Logger(f"./data/{actor}", postfix=f"mean-coeff-{sub_folder}") diff --git a/scripts/Actor6Data/run-41-train-annodb-audio2mesh.py b/scripts/Actor6Data/run-41-train-annodb-audio2mesh.py index 453b327..8c6eb9e 100644 --- a/scripts/Actor6Data/run-41-train-annodb-audio2mesh.py +++ b/scripts/Actor6Data/run-41-train-annodb-audio2mesh.py @@ -42,7 +42,7 @@ if __name__ == "__main__": vid_train = vids - vid_test - vid_valid logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}") logger.info(f"vid train= {vid_train}") - + # for each video data_train, data_valid, data_test = {}, {}, {} diff --git a/scripts/Actor6Data/run-42-train-annodb-ganrender.py b/scripts/Actor6Data/run-42-train-annodb-ganrender.py index 3c234b7..b6b3e54 100644 --- a/scripts/Actor6Data/run-42-train-annodb-ganrender.py +++ b/scripts/Actor6Data/run-42-train-annodb-ganrender.py @@ -3,6 +3,7 @@ from loguru import logger import numpy as np from pathlib2 import Path import torchaudio +from scipy.signal import savgol_filter import os, sys sys.path.insert(0, os.getcwd()) @@ -15,7 +16,7 @@ if __name__ == "__main__": sub_folder = "processing2" # processing, smile, body path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}") - path_save = Path(f'data/{actor}/data-render-{sub_folder}-1h') + path_save = Path(f'data/{actor}/data-render-{sub_folder}-2h') path_save.mkdir(parents=True, exist_ok=True) # set logging @@ -63,11 +64,13 @@ if __name__ == "__main__": logger.info(f"\n\n processing the {i}-th video {vid} ... ") ipath_info = ipath_data.joinpath("video/info.json") - # ipath_coeff = ipath_data.joinpath("DECA_coeff") # DECA coeff of shape/exp/light - ipath_coeff = ipath_data.joinpath("deca_coeff_512") # DECA coeff of shape/exp/light - ipath_frame = ipath_data.joinpath("frames_crop_512") # cropped image 512x512 - ipath_ldmks = ipath_data.joinpath("frames_crop_ldmks_512") # cropped landmarks within 512x512 - ipath_parse = ipath_data.joinpath("frames_crop_parse_skin_512") # cropped mask + # ipath_coeff = ipath_data.joinpath("DECA_coeff") # DECA coeff of shape/exp/light + ipath_coeff = ipath_data.joinpath("deca_coeff_512") # DECA coeff of shape/exp/light + ipath_frame = ipath_data.joinpath("frames_crop_512") # cropped image 512x512 + ipath_ldmks = ipath_data.joinpath("frames_crop_ldmks_512") # cropped landmarks within 512x512 + ipath_parse = ipath_data.joinpath("frames_crop_mask_512") # cropped mask + + # ipath_parse = ipath_data.joinpath("frames_crop_parse_skin_512") # cropped mask # check info existing if not ipath_info.exists(): @@ -102,6 +105,22 @@ if __name__ == "__main__": data_coeff = np.load(ipath_feat_coeff) # (nframe, 236) data_coeff = data_coeff.astype(np.float16) # convert float16 + # load landmark + feat_ldmk = [] + for k in range(num_ldmks): + kpath_ldmk = ipath_ldmks.joinpath(f"frame-{k:06d}.txt") + if not kpath_ldmk.exists(): + logger.info(f"\n ERROR: landmark path NOT FOUND! -> {kpath_ldmk}") + break + + kpt = np.loadtxt(kpath_ldmk) # (68, 2) + assert kpt.shape[0] == 68, f"the kpt shape ={kpt.shape}, --> {kpath_ldmk}" + feat_ldmk.append(kpt) + + # smooth landmark it + feat_ldmk = np.array(feat_ldmk) # (N, 68, 2) + feat_ldmk = savgol_filter(feat_ldmk, window_length=5, polyorder=3, axis=0, mode='nearest') + if vid in vid_train: durations_train += nframes/fps @@ -112,7 +131,8 @@ if __name__ == "__main__": "sr": 16000, "nframe": nframes, "path_data": str(ipath_data), - "data_coeff": data_coeff + "data_coeff": data_coeff, + "data_ldmks": feat_ldmk } if vid in vid_valid: @@ -124,7 +144,8 @@ if __name__ == "__main__": "sr": 16000, "nframe": nframes, "path_data": str(ipath_data), - "data_coeff": data_coeff + "data_coeff": data_coeff, + "data_ldmks": feat_ldmk } if vid in vid_test: @@ -136,9 +157,11 @@ if __name__ == "__main__": "sr": 16000, "nframe": nframes, "path_data": str(ipath_data), - "data_coeff": data_coeff + "data_coeff": data_coeff, + "data_ldmks": feat_ldmk } + logger.info(f"Total frames: data_train ({durations_train/60:.2f} min) ({durations_train/3600:.2f} h) , ids = ({len(data_train)})") logger.info(f"Total frames: data_valid ({durations_valid/60:.2f} min) ({durations_valid/3600:.2f} h) , ids = ({len(data_valid)})") logger.info(f"Total frames: data_test ({durations_test/60:.2f} min) ({durations_test/3600:.2f} h) , ids = ({len(data_test)})") diff --git a/scripts/Actor7Data/run-01-detect-lm68.py b/scripts/Actor7Data/run-01-detect-lm68.py new file mode 100644 index 0000000..5c75762 --- /dev/null +++ b/scripts/Actor7Data/run-01-detect-lm68.py @@ -0,0 +1,81 @@ +from torch.utils.data import Dataset, DataLoader + +import torch +import numpy as np +from PIL import Image +from pathlib2 import Path +from face_alignment import FaceAlignment, LandmarksType +from zmq import device + + +class ImagesDataset(Dataset): + def __init__(self, path_folder:Path): + + self.path_folder = path_folder + self.list_image = sorted(path_folder.glob("*.jpg"), reverse=False) + print(f"Have {len(self.list_image)} images, like {self.list_image[:3]}") + + def __len__(self): + return len(self.list_image) + + def __getitem__(self, idx): + path_frame = self.list_image[idx] + image = Image.open(str(path_frame)).convert('RGB') # (h, w, 3) + image = np.asarray(image) + return {"image_name": path_frame.stem, "image": image} + + +if __name__ == "__main__": + + path_data = Path("/ssdata1/lsen/DATA/Actor5/processing") + vpath_videos = sorted(path_data.glob("*"), reverse=True) + print(f"Have {len(vpath_videos)} dir files") + + device = "cuda:7" + model = FaceAlignment(LandmarksType._2D, device=device, face_detector='sfd') + print(f"load FaceAlignment model in {device}") + + # IDs = ["2-23min"] + # for each word + for i, ipath_item in enumerate(vpath_videos[16:]): + iname = ipath_item.stem + print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ") + + # if iname not in IDs: continue + + ipath_infor = ipath_item.joinpath("video/info.json") + ipath_ldmks = ipath_item.joinpath("landmarks_FAN") + ipath_frame = ipath_item.joinpath("frames") + ipath_ldmks.mkdir(parents=True, exist_ok=True) + + + # check + num_frame = len(list(ipath_frame.glob("*.jpg"))) + num_ladmk = len(list(ipath_ldmks.glob("*.txt"))) + if num_frame == num_ladmk: + print(f"\n Skip: have already done!") + continue + + + dataset = ImagesDataset(ipath_frame) + dloader = DataLoader(dataset, batch_size=16, num_workers=8) + + for k, ibatch in enumerate(dloader): + ibatch_name = ibatch["image_name"] + ibatch_data = ibatch["image"].to(device) # B x H x W x 3 + ibatch_data = ibatch_data.permute(0, 3, 1, 2) # B x H x W x 3 + # print(f"ibatch_data shape = {ibatch_data.shape}, path={ibatch_name[:3]}") + if k%100 == 0: + print(f"batching {k}/{len(dloader)} ... ") + + pred = model.get_landmarks_from_batch(ibatch_data, return_landmark_score=False) + # print(f"pred len = {len(pred)}, type= {type(pred)}, [0] shape={pred[0].shape}") + + # save landmarks + for jldmk, jname in zip(pred, ibatch_name): + jpath_ldmk = ipath_ldmks.joinpath(jname + ".txt") + np.savetxt(jpath_ldmk, jldmk, fmt=" %3d") + + + + # break \ No newline at end of file diff --git a/scripts/Actor7Data/run-01-mean-bbox.py b/scripts/Actor7Data/run-01-mean-bbox.py new file mode 100644 index 0000000..54c9a7c --- /dev/null +++ b/scripts/Actor7Data/run-01-mean-bbox.py @@ -0,0 +1,99 @@ +from torch.utils.data import Dataset, DataLoader + +import torch +import numpy as np +from PIL import Image +from pathlib2 import Path +from face_alignment import FaceAlignment, LandmarksType +from zmq import device + +import os, sys +sys.path.insert(0, os.getcwd()) +from common.logger import Logger + + +def bbox2point(left, right, top, bottom, type='bbox'): + ''' bbox from detector and landmarks are different + ''' + if type=='kpt68': + old_size = (right - left + bottom - top) / 2 * 1.1 + center = np.array([right - (right - left) / 2.0, + bottom - (bottom - top ) / 2.0 ]) + elif type=='bbox': + old_size = (right - left + bottom - top)/2 + center = np.array([right - (right - left) / 2.0, + bottom - (bottom - top ) / 2.0 + old_size*0.12]) + else: + raise NotImplementedError + + return old_size, center + + +if __name__ == "__main__": + + sub_folder = "processing" # processing, processing2 + + path_data = Path(f"/ssdata1/lsen/DATA/Actor6/{sub_folder}") + + logger = Logger("./data/Actor6", postfix=f"max_bbox_{sub_folder}") + path_mean_bbox = Path(f"./data/Actor6/max_bbox_{sub_folder}.npy") + + + vpath_videos = sorted(path_data.glob("*"), reverse=True) + logger.info(f"Have {len(vpath_videos)} dir files") + + # IDs = ["2-23min"] + mean_bbox = [] + for i, ipath_item in enumerate(vpath_videos): + iname = ipath_item.stem + logger.info(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ") + + # if iname not in IDs: continue + + ipath_infor = ipath_item.joinpath("video/info.json") + ipath_ldmks = ipath_item.joinpath("landmarks_FAN") + ipath_frame = ipath_item.joinpath("frames") + ipath_ldmks.mkdir(parents=True, exist_ok=True) + + # check + vpath_ldmks = list(ipath_ldmks.glob("*.txt")) + + kmean_bbox = [] + for k, kpath_ldmk in enumerate(vpath_ldmks): + # if k%1000 == 0: + # logger.info(f"batching {k}/{len(vpath_ldmks)} ... ") + + + kpt = np.loadtxt(kpath_ldmk) # (68, 2) + + if kpt.shape[0] > 68: + kpt = kpt[:68, :] + logger.info(f"ERROR: > use first 68-kpts, kpt = {kpt.shape} ipath_ldmk={kpath_ldmk}") + + left = np.min(kpt[:,0]); right = np.max(kpt[:,0]) + top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1]) + kmean_bbox.append([left, right, top, bottom]) + + + if len(vpath_ldmks) > 0: + kmean_bbox = np.array(kmean_bbox) + # kmean_bbox = kmean_bbox.max(axis=0) + left, right = np.min(kmean_bbox[:, 0]), np.max(kmean_bbox[:, 1]) + top, bottom = np.min(kmean_bbox[:, 2]), np.max(kmean_bbox[:, 3]) + mean_bbox.append([left, right, top, bottom]) + logger.info(f"\t max bbox ={[left, right, top, bottom]}") + + # get toatl mean bbox + mean_bbox = np.array(mean_bbox) + # mean_bbox = mean_bbox.max(axis=0).astype(np.int32) + left, right = np.min(mean_bbox[:, 0]), np.max(mean_bbox[:, 1]) + top, bottom = np.min(mean_bbox[:, 2]), np.max(mean_bbox[:, 3]) + mean_bbox = [left, right, top, bottom] + + logger.info(f"total max bbox ={mean_bbox}, ") + logger.info(f"wsize = {right - left}, hsize = {bottom - top} ") + + # save mean + np.save(path_mean_bbox, mean_bbox) + + # break \ No newline at end of file diff --git a/scripts/Actor7Data/run-01-prepare-data.py b/scripts/Actor7Data/run-01-prepare-data.py new file mode 100755 index 0000000..7f18f4a --- /dev/null +++ b/scripts/Actor7Data/run-01-prepare-data.py @@ -0,0 +1,171 @@ +from pathlib import Path +import json +import os +import moviepy +from moviepy.editor import VideoFileClip, AudioFileClip + +import os, sys +sys.path.insert(0, os.getcwd()) +from common.logger import Logger + + +if __name__ == '__main__': + + actor = "Actor7" + sub_folder = "processing" # smile, processing, processing2 + + # logger + path_log = Path(f"./data/{actor}") + path_log.mkdir(parents=True, exist_ok=True) + logger = Logger(path_log, postfix=f"crop-transform-{sub_folder}") + + + path_raw = Path("/ssdata1/video_data/actor7") + path_data = Path(f"/mfs/lsen/DATA/{actor}/{sub_folder}") + path_data.mkdir(parents=True, exist_ok=True) + + + # get all videos + vpath_videos = sorted(path_raw.glob("*.MP4"), reverse=False) + logger.info(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 + logger.info(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ") + + # if i > 0: continue + # if iname not in IDs: continue + + # data path + ipath_data = path_data.joinpath(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: + logger.info(f"\n Skip: have already done!") + continue + + # convert image + ipath_item_rotation = ipath_video.joinpath("video_raw_rotation.mp4") + if not ipath_item_rotation.exists(): + cmd = f"ffmpeg -i {str(ipath_item)} -vf 'transpose=1' {str(ipath_item_rotation)}" + logger.info(cmd) + os.system(cmd) + + # load video + # video = VideoFileClip(str(ipath_item)) + video = VideoFileClip(str(ipath_item_rotation)) + logger.info(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: + logger.info("\nERROR: audio info is None") + continue + + if video.duration < 60 : + logger.info("\nERROR: video.duration is too short, skip !") + continue + + + durations += video.duration + logger.info(f"\n\t -> Total durations = ({durations / 60 } min) ({durations / 3600 } h))") + # continue + + # add + # ipath_video_sub = ipath_video.joinpath("video_trim.mp4") + # if not ipath_video_sub.exists(): + # cmd = f"ffmpeg -y -hide_banner -loglevel error -ss 15 -t {int(video.duration)-15.0} -i {str(ipath_item_rotation)} -vcodec copy -acodec copy {str(ipath_video_sub)}" + # os.system(cmd) + # logger.info(f"save video > {ipath_video_sub}") + + + # 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) + logger.info(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())) + # logger.info(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: + logger.info("FPS NOT = 50!! ") + + # save sub video fps=50 + ipath_video_sub = ipath_video.joinpath("video_trim.mp4") + if ipath_video_sub.exists(): + logger.info("\nERROR: ipath_video_sub.exists()") + continue + else: + video.write_videofile(str(ipath_video_sub), fps=50, audio=True) + logger.info(f"save video > {ipath_video_sub}") + + # reload video + video.close() + video = VideoFileClip(str(ipath_video_sub)) + logger.info(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: + logger.info("\nERROR: audio info is None") + continue + + logger.info(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) + logger.info(f"save audio > {ipath_audio_sub}") + + # # check fps + # if int(video.fps) != 50: + # logger.info(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) + # logger.info(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) + logger.info(info) + logger.info(f"save video info in -> {ipath_infor}\n") + + # save trim video + logger.info(f"write_images_sequence...") + ipath_format = str(ipath_frame) + "/frame-%06d.jpg" + video.write_images_sequence(ipath_format, fps=50) + + + + diff --git a/scripts/Actor7Data/run-02-crop-transform-2.py b/scripts/Actor7Data/run-02-crop-transform-2.py new file mode 100644 index 0000000..6793e29 --- /dev/null +++ b/scripts/Actor7Data/run-02-crop-transform-2.py @@ -0,0 +1,207 @@ +import cv2 +from cv2 import norm +import numpy as np +from pathlib2 import Path +from skimage.transform import estimate_transform, warp + +import os, sys +sys.path.insert(0, os.getcwd()) +from common.logger import Logger + +def bbox2point(left, right, top, bottom, type='bbox'): + ''' bbox from detector and landmarks are different + ''' + if type=='kpt68': + old_size = (right - left + bottom - top) / 2 * 1.1 + center = np.array([right - (right - left) / 2.0, + bottom - (bottom - top ) / 2.0 ]) + elif type=='bbox': + old_size = (right - left + bottom - top)/2 + center = np.array([right - (right - left) / 2.0, + bottom - (bottom - top ) / 2.0 + old_size*0.12]) + else: + raise NotImplementedError + + return old_size, center + + +def processing_one_folder(ipath_frame, ipath_ldmks, ipath_fcrop, ipath_tfrom, ipath_lcrop, + suffix="jpg", crop_size=512, scale=1.25, roation_image=False, use_same_bbox=False, path_same_bbox = None): + + # get images + vpath_image = sorted(ipath_frame.glob(f"*.{suffix}"), key=lambda x: int(x.stem.split("-")[-1]), reverse=False) + logger.info(f'--> total have {len(vpath_image)} images, top: \n{vpath_image[:3]}') + + # set prev_ldmk + prev_ldmk = None + + if use_same_bbox: + same_bbox = np.load(path_same_bbox).reshape(-1) # (4,) [left, right, top, bottom] + logger.info(f"same_bbox = {same_bbox}") + + # for iteration + for j, jpath_frame in enumerate(vpath_image): + image_name = jpath_frame.stem # (frame-0000) + + if j%100 == 0: + logger.info(f"load jpath_frame --> {jpath_frame}") + + # if j < 19300: continu + + ipath_ldmk = ipath_ldmks.joinpath(image_name + ".txt") + if not ipath_ldmk.exists(): + raise Exception(f"ipath_ldmk not exists --> {ipath_ldmk}") + + kpath_fcrop = ipath_fcrop.joinpath(image_name + ".jpg") + kpath_tfrom = ipath_tfrom.joinpath(image_name + ".npy") + kpath_lcrop = ipath_lcrop.joinpath(image_name + ".txt") + + + # ########################## + # # check exists + # if kpath_fcrop.exists() and kpath_tfrom.exists() and kpath_lcrop.exists(): + # # logger.info(f"kpath_fcrop, kpath_tfrom, kpath_lcrop, have existing! ---> {kpath_fcrop} ") + # print(f"kpath_fcrop, kpath_tfrom, kpath_lcrop, have existing! ---> {kpath_fcrop} ") + # continue + # ########################## + + # load orignal image & landmarks + image = cv2.imread(str(jpath_frame)) # (H, W, 3), dtype=uint8 + kpt = np.loadtxt(ipath_ldmk) # (68, 2) + + if kpt.shape[0] > 68: + logger.info(f"ERROR: > use first 68-kpts, cropped_ldmk = {kpt.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}") + n_kpt = kpt.shape[0] // 68 + max_cos = 0 + kpt_selected = None + for idx in range(n_kpt): + cur_kpt = kpt[idx*68:(idx+1)*68, :] + cur_cos = np.dot(prev_ldmk, cur_kpt.reshape(-1)) / (np.linalg.norm(prev_ldmk) * np.linalg.norm(cur_kpt.reshape(-1))) + if cur_cos > max_cos: + max_cos = cur_cos + kpt_selected = cur_kpt + + # get kpt, which match the prev_landmarks + logger.info(f"\t SELETCT: max_cos = {max_cos} --> {kpt_selected.reshape(-1)[::10]}") + kpt = kpt_selected + + # record prev + prev_ldmk = kpt.copy().reshape(-1) # record prev_ldmk + + # reverse H&W + if roation_image: + image = image.transpose(1,0,2) # (H, W, 3) + kpt = kpt[:, ::-1] # (68, 2) + + if use_same_bbox: + left, right = same_bbox[0], same_bbox[1] + top, bottom = same_bbox[2], same_bbox[3] + else: + left = np.min(kpt[:,0]); right = np.max(kpt[:,0]) + top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1]) + + + old_size, center = bbox2point(left, right, top, bottom, type='kpt68') + + # crop transform + size = int(old_size * scale) + src_pts = np.array([[center[0] - size/2, center[1] - size/2], # (left, top) + [center[0] - size/2, center[1] + size/2], # (left, bottom) + [center[0] + size/2, center[1] - size/2]]) # (right, top) + + DST_PTS = np.array([[0, 0], # (left-top-corner) + [0, crop_size - 1], # (left-botton corner) + [crop_size - 1, 0]]) # (right-top corner) + + # tform_params dytpe = float64, shape = (3, 3) + tform = estimate_transform('similarity', src_pts, DST_PTS) + + # image = image/255. + # (crop_size, crop_size, 3) ,float64 + cropped_imag = warp(image, tform.inverse, output_shape=(crop_size, crop_size)) # scale to (0~1) + cropped_ldmk = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # (68,3) + cropped_ldmk = cropped_ldmk[:, :2] + + # logger.info(f"image dytpe = {image.dtype}, shape = {image.shape} ") + # logger.info(f"cropped_imag dytpe = {cropped_imag.dtype}, shape = {cropped_imag.shape} ") + # logger.info(f"tform_params dytpe = {tform.params.dtype}, shape = {tform.params.shape} ") + # logger.info(f"cropped_ldmk dytpe = {cropped_ldmk.dtype}, shape = {cropped_ldmk.shape}, max={cropped_ldmk.max()}, min={cropped_ldmk.min()} ") + + + np.save(kpath_tfrom, tform.params) + np.savetxt(kpath_lcrop, cropped_ldmk, fmt=" %3d") + + cropped_imag = (255*cropped_imag).astype(np.uint8) + cv2.imwrite(str(kpath_fcrop), cropped_imag) + + +if __name__ == "__main__": + + actor = "Actor6" + sub_folder = "processing2" # smile, processing, processing2 + + # logger + logger = Logger(f"./data/{actor}", postfix=f"crop-transform-{sub_folder}") + + path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}") + path_same_bbox = f"data/{actor}/max_bbox_{sub_folder}.npy" + + # + vpath_videos = sorted(path_data.glob("*"), reverse=False) + logger.info(f"Have {len(vpath_videos)} dir files") + + # whole body need roation frame + roation_image = True if sub_folder == "body" else False + logger.info(f"roation_image = {roation_image}") + + # for each word + for i, ipath_item in enumerate(vpath_videos): + iname = ipath_item.stem + logger.info(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ") + + if iname not in ["4R3A0139"]: continue + + # if iname not in IDs: continue + ipath_ldmks = ipath_item.joinpath("landmarks_FAN") + ipath_frame = ipath_item.joinpath("frames") + ipath_fcrop = ipath_item.joinpath("frames_crop_512") + ipath_tfrom = ipath_item.joinpath("frames_crop_tform_512") + ipath_lcrop = ipath_item.joinpath("frames_crop_ldmks_512") + + ipath_fcrop.mkdir(parents=True, exist_ok=True) + ipath_tfrom.mkdir(parents=True, exist_ok=True) + ipath_lcrop.mkdir(parents=True, exist_ok=True) + + num_frame = len(list(ipath_frame.glob("*.jpg"))) + + # check have done + # num_fcrop = len(list(ipath_fcrop.glob("*.jpg"))) + # if num_frame == num_fcrop: + # logger.info(f"\n Skip: have already done!") + # continue + + # check landmarks have exists + num_ldmks = len(list(ipath_ldmks.glob("*.txt"))) + if num_frame != num_ldmks: + logger.info(f"\n ERROR & Skip: ldmaks = {num_ldmks} != nframes {num_frame}!") + continue + + + # processing one folder + processing_one_folder( + ipath_frame, ipath_ldmks, ipath_fcrop, ipath_tfrom, ipath_lcrop, + suffix="jpg", crop_size=512, scale=1.5, + roation_image=roation_image, use_same_bbox=True, path_same_bbox = path_same_bbox + ) + + + + + + + + + + + + \ No newline at end of file diff --git a/scripts/Actor7Data/run-02-crop-transform.py b/scripts/Actor7Data/run-02-crop-transform.py new file mode 100644 index 0000000..dce109b --- /dev/null +++ b/scripts/Actor7Data/run-02-crop-transform.py @@ -0,0 +1,200 @@ +import cv2 +import numpy as np +from pathlib2 import Path +from skimage.transform import estimate_transform, warp + +from torch.utils.data import Dataset, DataLoader + +class ImagesDataset(Dataset): + def __init__(self, path_frames, path_landmk, suffix="jpg", crop_size=224, scale=1.25, roation_image=False, use_same_bbox=False, path_same_bbox = None): + ''' + path_frames: folder, vpath_image, image path, video path + ''' + + self.path_frames = Path(path_frames) + self.path_landmk = Path(path_landmk) + self.vpath_image = sorted(self.path_frames.glob(f"*.{suffix}"), key=lambda x: int(x.stem.split("-")[-1]), reverse=False) + print(f'--> total have {len(self.vpath_image)} images, top: \n{self.vpath_image[:3]}') + + self.scale = scale # 1.25 + self.crop_size = crop_size # 224 + self.roation_image =roation_image + self.use_same_bbox = use_same_bbox + + if self.use_same_bbox: + self.same_bbox = np.load(path_same_bbox).reshape(-1) # (4,) [left, right, top, bottom] + print(f"same_bbox = {self.same_bbox}") + + + def bbox2point(self, left, right, top, bottom, type='bbox'): + ''' bbox from detector and landmarks are different + ''' + if type=='kpt68': + old_size = (right - left + bottom - top) / 2 * 1.1 + center = np.array([right - (right - left) / 2.0, + bottom - (bottom - top ) / 2.0 ]) + elif type=='bbox': + old_size = (right - left + bottom - top)/2 + center = np.array([right - (right - left) / 2.0, + bottom - (bottom - top ) / 2.0 + old_size*0.12]) + else: + raise NotImplementedError + + return old_size, center + + + def __len__(self): + return len(self.vpath_image) + + def __getitem__(self, index): + ipath_frame = self.vpath_image[index] + image_name = ipath_frame.stem # (frame-0000) + + # print(f"load ipath_frame --> {ipath_frame}") + + ipath_ldmk = self.path_landmk.joinpath(image_name + ".txt") + if not ipath_ldmk.exists(): + raise Exception(f"ipath_ldmk not exists --> {ipath_ldmk}") + + # load orignal image & landmarks + image = cv2.imread(str(ipath_frame)) # (H, W, 3), dtype=uint8 + kpt = np.loadtxt(ipath_ldmk) # (68, 2) + if kpt.shape[0] > 68: + # raise Exception(f"cropped_ldmk = {cropped_ldmk.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}") + kpt = kpt[:68, :] + print(f"ERROR: > use first 68-kpts, cropped_ldmk = {kpt.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}") + + + # reverse H&W + if self.roation_image: + image = image.transpose(1,0,2) # (H, W, 3) + kpt = kpt[:, ::-1] # (68, 2) + + if self.use_same_bbox: + left, right = self.same_bbox[0], self.same_bbox[1] + top, bottom = self.same_bbox[2], self.same_bbox[3] + else: + left = np.min(kpt[:,0]); right = np.max(kpt[:,0]) + top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1]) + + + old_size, center = self.bbox2point(left, right, top, bottom, type='kpt68') + + # crop transform + size = int(old_size * self.scale) + src_pts = np.array([[center[0] - size/2, center[1] - size/2], # (left, top) + [center[0] - size/2, center[1] + size/2], # (left, bottom) + [center[0] + size/2, center[1] - size/2]]) # (right, top) + + DST_PTS = np.array([[0, 0], # (left-top-corner) + [0, self.crop_size - 1], # (left-botton corner) + [self.crop_size - 1, 0]]) # (right-top corner) + + # tform_params dytpe = float64, shape = (3, 3) + tform = estimate_transform('similarity', src_pts, DST_PTS) + + # image = image/255. + # (crop_size, crop_size, 3) ,float64 + cropped_imag = warp(image, tform.inverse, output_shape=(self.crop_size, self.crop_size)) # scale to (0~1) + cropped_ldmk = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # (68,3) + cropped_ldmk = cropped_ldmk[:, :2] + + # cropped_ldmk[:,:2] = cropped_ldmk[:,:2] / self.crop_size * 2 - 1 + + # cropped_mask = warp(mask, tform.inverse, output_shape=(self.crop_size, self.crop_size)) # scale to (0~1) + + # print(f"image dytpe = {image.dtype}, shape = {image.shape} ") + # print(f"cropped_imag dytpe = {cropped_imag.dtype}, shape = {cropped_imag.shape} ") + # print(f"tform_params dytpe = {tform.params.dtype}, shape = {tform.params.shape} ") + # print(f"cropped_ldmk dytpe = {cropped_ldmk.dtype}, shape = {cropped_ldmk.shape}, max={cropped_ldmk.max()}, min={cropped_ldmk.min()} ") + # # print(f"jbatch_ldmks ={cropped_ldmk}") + + return {'image_name': ipath_frame.stem, + 'image': image, + 'cropped_imag': cropped_imag, + 'tform_params': tform.params, + 'cropped_ldmk': cropped_ldmk, + } + + +if __name__ == "__main__": + + sub_folder = "processing2" # processing, processing2 + path_data = Path(f"/ssdata1/lsen/DATA/Actor6/{sub_folder}") + path_same_bbox = f"data/Actor6/max_bbox_{sub_folder}.npy" + + vpath_videos = sorted(path_data.glob("*"), reverse=True) + print(f"Have {len(vpath_videos)} dir files") + + # whole body need roation frame + roation_image = True if sub_folder == "body" else False + print(f"roation_image = {roation_image}") + + + # IDs = ["2-23min"] + # for each word + for i, ipath_item in enumerate(vpath_videos): + iname = ipath_item.stem + print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ") + + # if iname not in IDs: continue + ipath_ldmks = ipath_item.joinpath("landmarks_FAN") + ipath_frame = ipath_item.joinpath("frames") + ipath_fcrop = ipath_item.joinpath("frames_crop_512") + ipath_tfrom = ipath_item.joinpath("frames_crop_tform_512") + ipath_lcrop = ipath_item.joinpath("frames_crop_ldmks_512") + + ipath_fcrop.mkdir(parents=True, exist_ok=True) + ipath_tfrom.mkdir(parents=True, exist_ok=True) + ipath_lcrop.mkdir(parents=True, exist_ok=True) + + # check have done + num_frame = len(list(ipath_frame.glob("*.jpg"))) + num_fcrop = len(list(ipath_fcrop.glob("*.jpg"))) + if num_frame == num_fcrop: + print(f"\n Skip: have already done!") + continue + + # check landmarks have exists + num_ldmks = len(list(ipath_ldmks.glob("*.txt"))) + if num_frame != num_ldmks: + print(f"\n ERROR & Skip: ldmaks = {num_ldmks} != nframes {num_frame}!") + continue + + # only whole body image, need set roation_image=True + dataset = ImagesDataset(ipath_frame, ipath_ldmks, suffix="jpg", crop_size=512, scale=1.5, + roation_image=roation_image, use_same_bbox=True, path_same_bbox = path_same_bbox ) + + dloader = DataLoader(dataset, batch_size=12, num_workers=1, shuffle=False) + + + print(f"processing crop ... ") + for j, jbatch in enumerate(dloader): + # print(f"jbatch_data shape = {jbatch_data.shape}, path={jbatch_name[:3]}") + if j%100 == 0: + print(f"batching {j}/{len(dloader)} ... ") + + jbatch_name = jbatch["image_name"] + jbatch_crop = (255*jbatch["cropped_imag"]).numpy().astype(np.uint8) + jbatch_tfrom = jbatch["tform_params"].numpy() + jbatch_ldmks = jbatch["cropped_ldmk"].numpy() + + # print(f"jbatch_crop dytpe = {jbatch_crop.dtype}, shape = {jbatch_crop.shape} ") + # print(f"jbatch_tfrom dytpe = {jbatch_tfrom.dtype}, shape = {jbatch_tfrom.shape} ") + # print(f"jbatch_ldmks dytpe = {jbatch_ldmks.dtype}, shape = {jbatch_ldmks.shape}, max={jbatch_ldmks.max()}, min={jbatch_ldmks.min()} ") + + # save data + for k,kname in enumerate(jbatch_name): + kpath_fcrop = ipath_fcrop.joinpath(kname + ".jpg") + kpath_tfrom = ipath_tfrom.joinpath(kname + ".npy") + kpath_lcrop = ipath_lcrop.joinpath(kname + ".txt") + + if kpath_fcrop.exists() and kpath_tfrom.exists() and kpath_lcrop.exists(): + continue + + np.save(kpath_tfrom, jbatch_tfrom[k]) + np.savetxt(kpath_lcrop, jbatch_ldmks[k], fmt=" %3d") + cv2.imwrite(str(kpath_fcrop), jbatch_crop[k]) + # cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_{vis_name}.jpg")), img) + + # break \ No newline at end of file diff --git a/scripts/Actor7Data/run-09-remove-files.py b/scripts/Actor7Data/run-09-remove-files.py new file mode 100644 index 0000000..d96fdfd --- /dev/null +++ b/scripts/Actor7Data/run-09-remove-files.py @@ -0,0 +1,31 @@ + +import os +from pathlib2 import Path + +if __name__ == "__main__": + + path_data = Path("/ssdata1/lsen/DATA/Actor5/processing") + vpath_videos = sorted(path_data.glob("*"), reverse=False) + print(f"Have {len(vpath_videos)} dir files") + + + # IDs = ["2-23min"] + # for each word + for i, ipath_item in enumerate(vpath_videos): + iname = ipath_item.stem + print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ") + + # if iname not in IDs: continue + ipath_fcrop = ipath_item.joinpath("frames_crop") + ipath_tfrom = ipath_item.joinpath("frames_crop_tform") + + + if ipath_fcrop.exists(): + cmd = f"rm -rf {str(ipath_fcrop)}" + print("RUN: ", cmd) + os.system(cmd) + + if ipath_tfrom.exists(): + cmd = f"rm -rf {str(ipath_tfrom)}" + print("RUN: ", cmd) + os.system(cmd) \ No newline at end of file diff --git a/scripts/Actor7Data/run-10-generate-mask.py b/scripts/Actor7Data/run-10-generate-mask.py new file mode 100644 index 0000000..63997d0 --- /dev/null +++ b/scripts/Actor7Data/run-10-generate-mask.py @@ -0,0 +1,111 @@ +import os +import sys +import json +import librosa +import numpy as np +from pathlib import Path + +import os, sys +sys.path.insert(0, os.getcwd()) +from common.logger import Logger + + +def load_mask(j, path_parse): + + parsing_anno = np.load(path_parse) # (512, 512) + mask = np.zeros_like(parsing_anno).astype(np.uint8) # (512, 512) + + + + atts = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'l_ear', 'r_ear', 'ear_r', + 'nose', 'mouth', 'u_lip', 'l_lip', 'neck', 'neck_l', 'cloth', 'hair', 'hat'] + + # atts_selected = ['skin', 'l_brow', 'r_brow', 'nose', 'u_lip', 'l_lip'] + # atts_selected = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'l_ear', 'r_ear', 'ear_r', + # 'nose', 'mouth', 'u_lip', 'l_lip', ] + atts_selected = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'nose', 'mouth', 'u_lip', 'l_lip'] + + class_contains = np.unique(parsing_anno) + + if j % 1000 == 0: + logger.info(f"\t the {j:06d}-th frame, class_contains = {class_contains}") + + for iclass, iatt in enumerate(atts, 1): + if (iatt in atts_selected) and (iclass in class_contains): + index = np.where(parsing_anno == iclass) + mask[index[0], index[1]] = 1 + + return mask + + +if __name__ == "__main__": + + actor = "Actor6" + sub_folder = "processing2" # smile, processing, processing2 + + # logger + logger = Logger(f"./data/{actor}", postfix=f"generate-mask-{sub_folder}") + + + path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}") + v_dir_videos = sorted(path_data.glob("*"), reverse=False) + logger.info(f"Have {len(v_dir_videos)} dir files") + + # for each video + duration_frame, duration_parse = 0, 0 + for ipath_data in v_dir_videos: + ivideo_name = ipath_data.stem + + logger.info(f"\n processing {ivideo_name} ... ") + ipath_infors = ipath_data.joinpath("video/info.json") + ipath_frame = ipath_data.joinpath("frames") + ipath_parse = ipath_data.joinpath("frames_crop_parse_512") + ipath_parse_skin = ipath_data.joinpath("frames_crop_parse_skin_512") + ipath_parse_skin.mkdir(parents=True, exist_ok=True) + + # if ipath_save_parse.exists(): + # logger.info(f"ipath_save_exp have already save > {ipath_save_parse}") + # 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"] + logger.info(f"info = {info}, duration ={nframes / fps / 60}") + + # check equal + vframe_frame = list(ipath_frame.glob("*.jpg")) + vframe_parse = list(ipath_parse.glob("*.npy")) + logger.info(f"vframe_frame len = {len(vframe_frame)}, vframe_parse={len(vframe_parse)}") + + duration_frame += len(vframe_frame) / 50 / 60 + duration_parse += len(vframe_parse) / 50 / 60 + logger.info(f"add duration_frame = {duration_frame} min, duration_parse={duration_parse} min") + + if len(vframe_frame) != nframes: + logger.info(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}") + continue + + # check have done + # vframe_parse = list(ipath_parse_skin.glob("*.npy")) + # if len(vframe_parse) == nframes: + # logger.info(f"ipath_parse_skin have already done!") + # continue + + # feat_parse = [] + for j in range(len(vframe_frame)): + jpath_parse = ipath_parse.joinpath(f"frame-{j:06d}.npy") + jpath_parse_save = ipath_parse_skin.joinpath(f"frame-{j:06d}.npy") + + if not jpath_parse.exists(): + logger.info(f"\n ERROR: Path NOT FOUND! -> {jpath_parse}") + break + + data_mask = load_mask(j, jpath_parse) # (512, 512) + np.save(jpath_parse_save, data_mask) + + # feat_parse.append(data_mask) \ No newline at end of file diff --git a/scripts/Actor7Data/run-20-deca-reconstruction.py b/scripts/Actor7Data/run-20-deca-reconstruction.py new file mode 100644 index 0000000..81b7472 --- /dev/null +++ b/scripts/Actor7Data/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:9" + # 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("/ssdata1/lsen/DATA/Actor6/processing2") + + v_dir_videos = sorted(path_data.glob("*"), reverse=True) + 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 + + # if ivideo_name not in ["4R3A0139"]: continue + + ipath_infor = ipath_data.joinpath("video/info.json") + # ipath_frame = ipath_data.joinpath("frames") + ipath_frame = ipath_data.joinpath("frames_crop_512") + + # ipath_kpt2d = ipath_data.joinpath("DECA_kpt2d") + # ipath_kpt3d = ipath_data.joinpath("DECA_kpt3d") + ipath_coeff = ipath_data.joinpath("deca_coeff_512") + # 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_coeff.glob("*.npy"))) + 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/Actor7Data/run-21-features-3dmm.py b/scripts/Actor7Data/run-21-features-3dmm.py new file mode 100644 index 0000000..2c476a8 --- /dev/null +++ b/scripts/Actor7Data/run-21-features-3dmm.py @@ -0,0 +1,110 @@ +import os +import sys +import json +import librosa +import numpy as np +from pathlib import Path + +import os, sys +sys.path.insert(0, os.getcwd()) +from common.logger import Logger + + +if __name__ == "__main__": + + + actor = "Actor6" + sub_folder = "processing2" # smile, processing, processing2 + + # logger + logger = Logger(f"./data/{actor}", postfix=f"feature-3dmm-{sub_folder}") + + # path data + path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}") + v_dir_videos = sorted(path_data.glob("*"), reverse=False) + logger.info(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 + + logger.info(f"\n processing {ivideo_name} ... ") + ipath_infors = ipath_data.joinpath("video/info.json") + # ipath_coeff = ipath_data.joinpath("DECA_coeff") + ipath_coeff = ipath_data.joinpath("deca_coeff_512") + 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 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"] + + logger.info(f"info = {info}, duration ={nframes / fps / 60}") + + # check + vframe_frame = list(ipath_frame.glob("*.jpg")) + vframe_coeff = list(ipath_coeff.glob("*.npy")) + logger.info(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 + logger.info(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min") + + if len(vframe_frame) != nframes: + logger.info(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}") + continue + + if len(vframe_coeff)+1 < nframes: + logger.info(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}") + continue + + # if ipath_save_exp.exists() and ipath_save_pos.exists(): + # logger.info(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(): + logger.info(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) + logger.info(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: + logger.info("ERROR, skip! ") + + + diff --git a/scripts/Actor7Data/run-22-concat-3dmm.py b/scripts/Actor7Data/run-22-concat-3dmm.py new file mode 100644 index 0000000..3bfbe50 --- /dev/null +++ b/scripts/Actor7Data/run-22-concat-3dmm.py @@ -0,0 +1,103 @@ +import os +import sys +import json +import librosa +import numpy as np +from pathlib import Path + +from scipy.signal import savgol_filter + +import os, sys +sys.path.insert(0, os.getcwd()) +from common.logger import Logger + +if __name__ == "__main__": + + actor = "Actor6" + sub_folder = "processing2" # smile, processing, processing2 + + # logger + logger = Logger(f"./data/{actor}", postfix=f"concat-coeff-{sub_folder}") + + + path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}") + v_dir_videos = sorted(path_data.glob("*"), reverse=False) + 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_coeff = ipath_data.joinpath("deca_coeff_512") + ipath_frame = ipath_data.joinpath("frames") + ipath_save_coeff = ipath_data.joinpath("audio/feat_deca_coeff_512p.npy") + + # if ipath_save_coeff.exists(): + # print(f"ipath_save_exp have already save > {ipath_save_coeff}") + # 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 + + + feat_coeff = [] + params = ['shape', 'tex', 'exp', 'pose', 'cam', 'light'] + 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 + + codedict = np.load(jpath_coeff, allow_pickle=True).item() + + # dim of shape = 100, tex = 50, exp = 50, pose = 6, cam = 3, light = 27 + coeff = [] + for ikey in params: + coeff += list(codedict[ikey].reshape(-1)) + + assert len(coeff) == 236, f"coeff len = {len(coeff)} should be 236 !" + feat_coeff.append(np.array(coeff)) + + # concate + feat_coeff = np.array(feat_coeff) # (N, 236) + + # smooth it + feat_coeff = savgol_filter(feat_coeff, window_length=5, polyorder=3, axis=0, mode='nearest') + + + if nframes == feat_coeff.shape[0]: + np.save(ipath_save_coeff, feat_coeff) + print(f"SAVE OK! feat shape = {feat_coeff.shape}, nframe={nframes}\n save to -> {ipath_save_coeff}") # (nframe, 68, 2) + else: + print("ERROR, skip! ") + + diff --git a/scripts/Actor7Data/run-23-mean-coeff.py b/scripts/Actor7Data/run-23-mean-coeff.py new file mode 100644 index 0000000..fed1fe6 --- /dev/null +++ b/scripts/Actor7Data/run-23-mean-coeff.py @@ -0,0 +1,92 @@ +import numpy as np +from pathlib import Path + +import os, sys +sys.path.insert(0, os.getcwd()) +from common.logger import Logger + + +if __name__ == "__main__": + + # fid = "Bringing-Our-Workplace-Policies-into-the-21st-Century" + # fid = "4R3A0071" + actor= "Actor6" + sub_folder = "processing2" # processing, smile, body + fid = '4R3A0140' + + + # logger + logger = Logger(f"./data/{actor}", postfix=f"mean-coeff-{sub_folder}") + + # data + path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}/{fid}") + path_save = Path(f"./data/{actor}/mean_deca_coeff_{actor}_{sub_folder}.npy") + path_save.parent.mkdir(parents=True, exist_ok=True) + + + # path_coeff = path_data.joinpath("DECA_coeff") + path_coeff = path_data.joinpath("deca_coeff_512") + vpath_coeff = sorted(path_coeff.glob("*.npy"), reverse=False) + logger.info(f"Have {len(vpath_coeff)} frames") + + feat_shape = [] + feat_tex = [] + feat_cam = [] + feat_exp = [] + feat_pos = [] + feat_light = [] + feat_detail = [] + + for i, ipath_coeff in enumerate(vpath_coeff): + if i > 2000: break + + 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) + + logger.info(f"feat_exp shape = {feat_exp.shape}, mean = {mean_exp.shape}, \n{mean_exp}") + logger.info(f"mean_pos shape = {feat_pos.shape}, mean = {mean_pos.shape}, \n{mean_pos}") + logger.info(f"mean_tex shape = {feat_tex.shape}, mean = {mean_tex.shape}, \n{mean_tex}") + logger.info(f"mean_cam shape = {feat_cam.shape}, mean = {mean_cam.shape}, \n{mean_cam}") + logger.info(f"mean_light shape = {feat_light.shape}, mean = {mean_light.shape}, \n{mean_light}") + logger.info(f"mean_detail shape = {feat_detail.shape}, mean = {mean_detail.shape}, \n{mean_detail}") + logger.info(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, ) + } + logger.info(f"mean deca = \n {mean_DECA}") + + np.save(path_save, mean_DECA) + + logger.info(f"save to --> {path_save}") \ No newline at end of file diff --git a/scripts/Actor7Data/run-41-train-annodb-audio2mesh.py b/scripts/Actor7Data/run-41-train-annodb-audio2mesh.py new file mode 100644 index 0000000..8c6eb9e --- /dev/null +++ b/scripts/Actor7Data/run-41-train-annodb-audio2mesh.py @@ -0,0 +1,174 @@ +import json +import numpy as np +from pathlib2 import Path +import torchaudio + +import os, sys +sys.path.insert(0, os.getcwd()) +from common.logger import Logger + + + +if __name__ == "__main__": + + actor= "Actor6" + sub_folder = "processing2" # processing, smile, body + + path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}") + path_save = Path(f'data/{actor}/{actor}-raw-{sub_folder}-1h') + path_save.mkdir(parents=True, exist_ok=True) + + # set logging + logger = Logger(path_save, postfix=f"train-audio2mesh-{sub_folder}") + + # get files + v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy")) + logger.info(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]) + # logger.info(f"vids total= {vids}") + + # training set + if sub_folder == "processing2": + vid_test = set(["4R3A0139", "4R3A0140"]) + vid_valid = set(["4R3A0139", "4R3A0140"]) + vid_train = vids - vid_test - vid_valid + logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}") + logger.info(f"vid train= {vid_train}") + else: + vid_test = set(["4R3A0110", "4R3A0112", "4R3A0113"]) + vid_valid = set(["4R3A0110", "4R3A0112", "4R3A0113"]) + vid_train = vids - vid_test - vid_valid + logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}") + logger.info(f"vid train= {vid_train}") + + + # for each video + data_train, data_valid, data_test = {}, {}, {} + list_train, list_valid, list_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 + + logger.info(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(): + logger.info(f"NOT existing {ipath_speech}") + continue + + if not ipath_feat_exp.exists(): + logger.info(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'] + logger.info(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 + logger.info(f"motion = {data_motion.shape}") + + # load raw audio + audio_raw, sample_rate = torchaudio.load(ipath_speech) + logger.info(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() + logger.info(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 + list_train.append(vid) + + 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 + list_valid.append(vid) + + 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 + list_test.append(vid) + + data_test[vid] = { + "fps": info["fps"], + "sr": 16000, + "nframe": nframes, + "data_motion": data_motion, + "data_speech": audio_raw, + "data_shape": data_idn, + } + + + logger.info(f"Total frames: data_train ({durations_train/60:.2f} min) ({durations_train/3600:.2f} h) , ids = ({len(data_train)})") + logger.info(f"Total frames: data_valid ({durations_valid/60:.2f} min) ({durations_valid/3600:.2f} h) , ids = ({len(data_valid)})") + logger.info(f"Total frames: data_test ({durations_test/60:.2f} min) ({durations_test/3600:.2f} h) , ids = ({len(data_test)})") + + logger.info(f"actual train ID: > {list_train} ") + logger.info(f"actual valid ID: > {list_valid} ") + logger.info(f"actual test ID: > {list_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) + + logger.info(f"--> {path_save}") \ No newline at end of file diff --git a/scripts/Actor7Data/run-42-train-annodb-ganrender.py b/scripts/Actor7Data/run-42-train-annodb-ganrender.py new file mode 100644 index 0000000..b6b3e54 --- /dev/null +++ b/scripts/Actor7Data/run-42-train-annodb-ganrender.py @@ -0,0 +1,177 @@ +import json +from loguru import logger +import numpy as np +from pathlib2 import Path +import torchaudio +from scipy.signal import savgol_filter + +import os, sys +sys.path.insert(0, os.getcwd()) +from common.logger import Logger + + +if __name__ == "__main__": + + actor= "Actor6" + sub_folder = "processing2" # processing, smile, body + + path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}") + path_save = Path(f'data/{actor}/data-render-{sub_folder}-2h') + path_save.mkdir(parents=True, exist_ok=True) + + # set logging + logger = Logger(path_save, postfix=f"train-list-{sub_folder}") + + # get files + v_dir_videos = sorted(path_data.glob("*")) + logger.info(f"Have {len(v_dir_videos)} dir files") + + vids = set([ipath.stem for ipath in v_dir_videos]) + logger.info(f"vids total= {vids}") + + # # # actor5 raw + # vid_test = set(["4R3A0063", "4R3A0071"]) + # vid_valid = set(["4R3A0063", "4R3A0071"]) + # vid_train = vids - vid_test - vid_valid + + # actor5 smile + if sub_folder == "processing2": + vid_test = set(["4R3A0139", "4R3A0140"]) + vid_valid = set(["4R3A0139", "4R3A0140"]) + vid_train = vids - vid_test - vid_valid + logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}") + logger.info(f"vid train= {vid_train}") + else: + vid_test = set(["4R3A0110", "4R3A0112", "4R3A0113"]) + vid_valid = set(["4R3A0110", "4R3A0112", "4R3A0113"]) + vid_train = vids - vid_test - vid_valid + logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}") + logger.info(f"vid train= {vid_train}") + + + # for each video + data_train, data_valid, data_test = {}, {}, {} + list_train, list_valid, list_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 + logger.info(f"\n\n processing the {i}-th video {vid} ... ") + + ipath_info = ipath_data.joinpath("video/info.json") + # ipath_coeff = ipath_data.joinpath("DECA_coeff") # DECA coeff of shape/exp/light + ipath_coeff = ipath_data.joinpath("deca_coeff_512") # DECA coeff of shape/exp/light + ipath_frame = ipath_data.joinpath("frames_crop_512") # cropped image 512x512 + ipath_ldmks = ipath_data.joinpath("frames_crop_ldmks_512") # cropped landmarks within 512x512 + ipath_parse = ipath_data.joinpath("frames_crop_mask_512") # cropped mask + + # ipath_parse = ipath_data.joinpath("frames_crop_parse_skin_512") # cropped mask + + # check info existing + if not ipath_info.exists(): + logger.info(f"NOT existing {ipath_info}") + continue + + # load video info + with open(str(ipath_info), "r") as f: + info = json.load(f) + fps = info["fps"] + nframes = info['nframes'] + assert fps == 50, "fps should be 50" + logger.info(f"info={info}, duration = {nframes/fps}") + + + # check files total exists + num_coeff = len(list(ipath_coeff.glob("*.npy"))) + num_frame = len(list(ipath_frame.glob("*.jpg"))) + num_ldmks = len(list(ipath_ldmks.glob("*.txt"))) + num_parse = len(list(ipath_parse.glob("*.npy"))) + + if (num_coeff != nframes) or (num_frame != nframes) or (num_ldmks != nframes) or (num_parse != nframes): + logger.info(f"num of ipath_coeff ({num_coeff}) shoud be {nframes} > {ipath_coeff}") + logger.info(f"num of ipath_frame ({num_frame}) shoud be {nframes} > {ipath_frame}") + logger.info(f"num of ipath_ldmks ({num_ldmks}) shoud be {nframes} > {ipath_ldmks}") + logger.info(f"num of ipath_parse ({num_parse}) shoud be {nframes} > {ipath_parse}") + continue + + # load coeff + # ipath_feat_coeff = ipath_data.joinpath("audio/feat_DECA_trim.npy") + ipath_feat_coeff = ipath_data.joinpath("audio/feat_deca_coeff_512p.npy") + data_coeff = np.load(ipath_feat_coeff) # (nframe, 236) + data_coeff = data_coeff.astype(np.float16) # convert float16 + + # load landmark + feat_ldmk = [] + for k in range(num_ldmks): + kpath_ldmk = ipath_ldmks.joinpath(f"frame-{k:06d}.txt") + if not kpath_ldmk.exists(): + logger.info(f"\n ERROR: landmark path NOT FOUND! -> {kpath_ldmk}") + break + + kpt = np.loadtxt(kpath_ldmk) # (68, 2) + assert kpt.shape[0] == 68, f"the kpt shape ={kpt.shape}, --> {kpath_ldmk}" + feat_ldmk.append(kpt) + + # smooth landmark it + feat_ldmk = np.array(feat_ldmk) # (N, 68, 2) + feat_ldmk = savgol_filter(feat_ldmk, window_length=5, polyorder=3, axis=0, mode='nearest') + + + if vid in vid_train: + durations_train += nframes/fps + list_train.append(vid) + + data_train[vid] = { + "fps": info["fps"], + "sr": 16000, + "nframe": nframes, + "path_data": str(ipath_data), + "data_coeff": data_coeff, + "data_ldmks": feat_ldmk + } + + if vid in vid_valid: + durations_valid += nframes/fps + list_valid.append(vid) + + data_valid[vid] = { + "fps": info["fps"], + "sr": 16000, + "nframe": nframes, + "path_data": str(ipath_data), + "data_coeff": data_coeff, + "data_ldmks": feat_ldmk + } + + if vid in vid_test: + durations_test += nframes/fps + list_test.append(vid) + + data_test[vid] = { + "fps": info["fps"], + "sr": 16000, + "nframe": nframes, + "path_data": str(ipath_data), + "data_coeff": data_coeff, + "data_ldmks": feat_ldmk + } + + + logger.info(f"Total frames: data_train ({durations_train/60:.2f} min) ({durations_train/3600:.2f} h) , ids = ({len(data_train)})") + logger.info(f"Total frames: data_valid ({durations_valid/60:.2f} min) ({durations_valid/3600:.2f} h) , ids = ({len(data_valid)})") + logger.info(f"Total frames: data_test ({durations_test/60:.2f} min) ({durations_test/3600:.2f} h) , ids = ({len(data_test)})") + + logger.info(f"actual train ID: > {list_train} ") + logger.info(f"actual valid ID: > {list_valid} ") + logger.info(f"actual test ID: > {list_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) + + logger.info(f"--> {path_save}") \ No newline at end of file