Merge branch 'master' of ssh://dev.rcrai.com:30022/liangsen/audio-to-motion

This commit is contained in:
Sen Liang committed 2022-04-25 22:24:30 +08:00
commit 5ac0678f51
18 files changed
+571 -392

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
from pathlib import Path
import json
import moviepy
from moviepy.editor import VideoFileClip, AudioFileClip
if __name__ == '__main__':
# path_root = Path("/yrfs/lsen/DATA/Actor1")
path_root = Path("/data1/yrfs/lsen/DATA/bj_chinsee_data")
vpath_videos = sorted(path_root.glob("**/*.mp4"), reverse=False)
print(f"Have {len(vpath_videos)} dir files")
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} ... ")
# 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)}")
# durations += video.duration
# print(f"\t -> Total durations = ({durations / 60 } min) ({durations / 3600 } h))")
# continue
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))")
# cont
@@ -0,0 +1,74 @@
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("/mfs/lsen/DATA/Actor1/processing")
vpath_videos = sorted(path_data.glob("*"))
print(f"Have {len(vpath_videos)} dir files")
device = "cuda:0"
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):
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)
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
+3 -3
View File
@@ -5,9 +5,9 @@ from pathlib import Path
if __name__ == "__main__":
# fid = "Bringing-Our-Workplace-Policies-into-the-21st-Century"
fid = "BU6A9965"
path_root = Path("/mfs/lsen/DATA/Actor3/processing")
path_save = Path("./data/Actor3/DECA_Actor3_mean.npy")
fid = "4R3A0024"
path_root = Path("/mfs/lsen/DATA/Actor4/processing")
path_save = Path("./data/Actor4/DECA_Actor4_mean.npy")
path_save.parent.mkdir(parents=True, exist_ok=True)
path_data = path_root.joinpath(fid)
@@ -16,7 +16,6 @@ from decalib.utils.config import cfg as deca_cfg
def main(args):
# device = args.device
device = "cuda:7"
@@ -25,16 +24,16 @@ def main(args):
deca = DECA(config = deca_cfg, device=device)
# path_data = Path("/yrfs/lsen/DATA/TestData/processing")
path_data = Path("/mfs/lsen/DATA/Actor3/processing")
path_data = Path("/mfs/lsen/DATA/Actor4/processing")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
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):
for i, ipath_data in enumerate(v_dir_videos[1:]):
ivideo_name = ipath_data.stem
print(f"\n processing {i}/{len(v_dir_videos)} ...", ivideo_name)
# if ivideo_name not in IDs: continue
+2 -2
View File
@@ -7,8 +7,8 @@ from pathlib import Path
if __name__ == "__main__":
path_data = Path("/mfs/lsen/DATA/Actor3/processing")
v_dir_videos = sorted(path_data.glob("*"))
path_data = Path("/mfs/lsen/DATA/Actor4/processing")
v_dir_videos = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_dir_videos)} dir files")
# for each video
@@ -1,36 +1,12 @@
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("/mfs/lsen/DATA/Actor3/processing")
path_save = Path('data/Actor3/Actor3-raw-2h') # processing
path_data = Path("/mfs/lsen/DATA/Actor4/processing")
path_save = Path('data/Actor4/Actor4-raw-1h') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
@@ -40,22 +16,9 @@ if __name__ == "__main__":
vids = set([ipath.stem for ipath in v_dir_videos])
# print(f"vids total= {vids}")
vid_test = set(["BU6A9978"])
vid_valid = set(["BU6A9965","BU6A9980","BU6A9978"])
# 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_test = set(["4R3A0024"])
vid_valid = set(["4R3A0024"])
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}")
@@ -171,7 +134,6 @@ if __name__ == "__main__":
}
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)})")
@@ -0,0 +1,51 @@
from pathlib import Path
from skimage.metrics import structural_similarity
from imageio import imread
import numpy as np
from pathlib import Path
import multiprocessing
from os import getpid
path_root = Path("/mfs/lsen/DATA/Actor4/bg")
# idx_frame = 3530
# fname = "body1"
idx_frame = 3740 #100
fname = "head"
path_frames = path_root.joinpath(fname, "frames")
# read inference images
path_frame_ref = path_frames.joinpath(f"frame-{idx_frame:06d}.jpg")
img_ref = imread(str(path_frame_ref))
def worker_ssim(i):
if i % 100 == 0: print(f"[{getpid()}] procssing the {i:06d}-th... ")
ipath_frame = path_frames.joinpath(f"frame-{i:06d}.jpg")
img = imread(str(ipath_frame))
ssim = structural_similarity(img_ref, img, multichannel = True)
return ssim
if __name__ == '__main__':
# save path
path_save = path_root.joinpath(fname, "video", f"ssim_ref_{idx_frame}.npy")
path_save.parent.mkdir(parents=True, exist_ok=True)
# check frames
nframe = len(list(path_frames.glob("*.jpg")))
# multi-processing
pool = multiprocessing.Pool(24)
results = list(pool.map(worker_ssim, range(nframe)))
# print(results)
# save to npy
np.save(path_save, np.array(results))