initial commit

This commit is contained in:
Sen Liang committed 2022-01-21 17:42:41 +08:00
commit c7175dd7ff
127 files changed
+13949

No files matched your search

+163
View File
@@ -0,0 +1,163 @@
import time
import sys
import argparse
from pathlib import Path
import numpy as np
import imageio
import torch
from torch.utils.data import DataLoader
import torch.nn.functional as F
sys.path.insert(0, "/mnt/data/CODE/Audio2Expression")
from src.datasets import create_dataset
from src.models.functions import get_pad_mask, get_subsequent_mask
from src.models import create_model, calculate_model_params
from src.config import config as opt
from src.config import update_config
from src.datasets.grid_ldmk import GRID_LdmkDataset
from src.models.transformer_a2l import TransformerA2L
from common.logger import Logger
from common.vis.visualizer import Visualizer
from common.metrics.utils import AverageMeterDict
from common.image import save_image
from common.landmark import landmark_to_image
def parese_args():
pareser = argparse.ArgumentParser(description='Facial Landmark Disentangle Network')
# general
pareser.add_argument("--opt", type=str, default="experiments/W300/test-landmark.yaml", help="experiment configure file name")
pareser.add_argument("--load_epoch", default=None, help="experiment configure file name")
args, _ = pareser.parse_known_args()
update_config(args.opt)
return pareser.parse_args()
if __name__ == "__main__":
args = parese_args()
device = torch.device(f'cuda:{opt.GPUS[0]}') # get device name: CPU or GPU
path_checkpoint = Path(opt.MODEL.path_checkpoint)
# update load_epoch
if args.load_epoch is not None:
opt.MODEL.load_epoch = args.load_epoch
# setting logger and output dir
path_config = Path(args.opt)
logger = Logger(opt.OUTPUT_DIR, path_config=path_config)
opt.OUTPUT_DIR = logger.path_output
path_save = Path(opt.OUTPUT_DIR)
# update load_epoch
if args.load_epoch is not None:
opt.MODEL.load_epoch = args.load_epoch
# load data
data_test = GRID_LdmkDataset(opt)
data_loader = DataLoader(data_test, batch_size=opt.TEST.batch_size, shuffle=False, drop_last=False)
logger.info(f"test dataset = {len(data_test)}, data_batch = {len(data_loader)}")
# load model
netG = TransformerA2L(opt) # [100, 500, 1000, 2000, 2300]
seleted_epochs = [3390, 3000, 2500, 2000, 1500, 1000, 500] #8000, 9000,10000] #000, 9000, 9500, 10000]
print("load from -->", path_checkpoint)
for epoch in seleted_epochs:
netG.eval()
# load model parameters
ipath_checkpoint = path_checkpoint.joinpath("checkpoints", f'{epoch}_net_G.pth')
state_dict = torch.load(str(ipath_checkpoint), map_location=str(device))
netG.load_state_dict(state_dict)
netG = netG.to(device)
# test data
avg_meter = AverageMeterDict()
for i, ibatch_data in enumerate(data_loader):
with torch.no_grad():
batch_ldmk = ibatch_data['ldmk_norm'] # (1, 25N, 68, 2)
batch_mfcc = ibatch_data['mfcc_feat'] # (1, 100N, 13)
batch_path = ibatch_data['ldmk_path']
# batch_mask = get_subsequent_mask(25) # (1, N, N)
# batch_mask = batch_mask.to(device)
batch_ldmk = batch_ldmk.float().to(device)
batch_mfcc = batch_mfcc.float().to(device)
(B, N, *_) = batch_ldmk.shape
batch_predt = torch.zeros((B, N+1, 68, 2)).float().to(device) # (1, N, 68, 2)
batch_predt[:, :25, :, : ] = batch_ldmk[:, :25, :, :]
print(f"ldmk={batch_ldmk.shape}, mfcc={batch_mfcc.shape}, predt={batch_predt.shape}")
for j in range(24, N):
if j == 0:
jbatch_ldmk = batch_ldmk[:, :1, :, :] # (1, 1, 68, 2)
jbatch_mfcc = batch_mfcc[:, :4, :] # (1, 4, 13)
batch_mask = get_subsequent_mask(1).to(device) # (1, 1, 1)
elif j < 25:
jbatch_ldmk = batch_predt[:, :(j+1), :, :] # (1, J, 68, 2)
jbatch_mfcc = batch_mfcc[:, :4*(j+1), :] # (1, 4J, 13)
batch_mask = get_subsequent_mask(j+1).to(device) # (1, N, N)
else:
jbatch_ldmk = batch_predt[:, j-24 :(j+1), :, :] # (1, 25, 68, 2)
jbatch_mfcc = batch_mfcc[:, 4*j-96 :4*(j+1), :] # (1, 100, 13)
batch_mask = get_subsequent_mask(25).to(device) # (1, N, N)
y = netG(jbatch_mfcc, None, jbatch_ldmk, batch_mask, shift=False) # (1, j, 68, 2)
batch_predt[:, j+1, :, :] = y[:, -1, :, :] # The last one
metr_dict = {}
# reconstruction loss
predt = batch_predt[:, 1:, :, :].reshape(-1, 68, 2) # (BN, 68, 2)
targt = batch_ldmk.reshape(-1, 68, 2) # (BN, 68, 2)
diff = (predt - targt) * (predt - targt) # (BN, 68, 2)
diff = torch.sqrt( diff[:, :, 0] + diff[:, :, 1]) # (NB, 68,)
metr_dict["metric_rec"] = torch.mean(torch.sum(diff, dim=1)) # (1,)
metr_dict["metric_mae"] = F.l1_loss(predt, targt, reduce="mean")
# show image
if i % 10 == 0 and opt.verbose:
frames = []
for j in range(24, N):
img = landmark_to_image(batch_ldmk[0, j, :, :], text=f"frame-{j:02}-render")
img_predt = landmark_to_image(batch_predt[0, j+1, :, :], text=f"frame-{j:02}-render")
frames.append(np.concatenate([img, img_predt], axis=1)) # (2W, H, 3)
jpath_save_img = path_save.joinpath(f"Epoch-{epoch}-Batch-{i:03d}-GIF.gif")
# duration = (N-25) / 30.0
imageio.mimsave(str(jpath_save_img), frames, 'GIF', duration=0.25)
# jpath_save_pdt = path_save.joinpath(f"Epoch-{epoch}-Batch-{i:03d}-predt", f"frame-{j:05d}.jpg")
# jpath_save_img.parent.mkdir(exist_ok=True, parents=True)
# jpath_save_pdt.parent.mkdir(exist_ok=True, parents=True)
# save_image(img, jpath_save_img)
# save_image(img_predt, jpath_save_pdt)
# update
avg_meter.update(metr_dict)
if i% 10 == 0:
print(f"batch {i:03d}:", avg_meter.print_msg())
print(f"Epoch {epoch} validation:\n\t", avg_meter.print_msg())
+143
View File
@@ -0,0 +1,143 @@
import os
from pathlib import Path
import shutil
UNZIP_FILES = False
MV_AUDIO_FILES = False
MV_VIDEO_FILES = False
EXTRACT_AUDIO = True
total_pid = ["s1.", "s2.", "s3.", "s4.", "s5.", "s6.", "s7.", "s8.", "s9.", "s10." ]
# total_pid = [ "s6.", "s7.", "s8.", "s9.", "s21."]
def is_exist_pid(file_name):
for iid in total_pid:
if str(iid) in str(file_name.name):
return True
return False
if __name__ == '__main__':
path_root = Path("/yrfs/lsen/DATA/GRID/")
if UNZIP_FILES:
path_zip = path_root.joinpath("zip_data")
path_data = path_root.joinpath("unzip_data")
path_data.mkdir(parents=True, exist_ok=True)
v_zip_files = sorted(path_zip.glob("./*.tar"))
print(f"Have {len(v_zip_files)} zip files, \n {v_zip_files[:10]}")
for i, izip in enumerate(v_zip_files):
if not is_exist_pid(izip): continue
ipath_data = path_data.joinpath(str(izip.stem))
# if not ipath_data.exists():
cmd = f"cd {str(path_zip)}; tar -xf {str(izip)} -C {str(path_data)}"
print(f"RUN: {cmd}")
os.system(cmd)
#break
if MV_AUDIO_FILES:
path_unzip = path_root.joinpath("unzip_data")
v_ids_file = sorted(path_unzip.glob("*"))
print(f"Have {len(v_ids_file)} persons files, \n {v_ids_file[:10]}")
for i, iid in enumerate(v_ids_file):
cmd = f"cd {str(iid)}; mkdir audio; mv *.wav audio"
print(f"RUN: {cmd}")
os.system(cmd)
#break
if MV_VIDEO_FILES:
path_data = path_root.joinpath("unzip_data")
v_ids = sorted(path_data.glob("*"))
print(f"Have {len(v_ids)} dir files, \n {v_ids[:10]}")
# for each person
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name, "video/mpg_6000")
v_dir_videos = sorted(dir_video.glob("*.mpg"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
# for each video
for ipath_videos in v_dir_videos:
ivideo_name = ipath_videos.stem
# copy video
ipath_video_target = path_root.joinpath("processing", id_name, ivideo_name, "video/video_orignal.mp4")
if not ipath_video_target.exists():
ipath_video_target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(src=str(ipath_videos), dst=str(ipath_video_target))
#print(f"copy {ipath_videos} --> {ipath_video_target}")
# # copy audio
# ipath_audio_source = path_data.joinpath(id_name, f"audio/{ivideo_name}.wav")
# ipath_audio_target = path_root.joinpath("processing", id_name, ivideo_name, "audio/audio_orignal.wav")
# if not ipath_audio_target.exists():
# ipath_audio_target.parent.mkdir(parents=True, exist_ok=True)
# shutil.copy(src=str(ipath_audio_source), dst=str(ipath_audio_target))
# #print(f"copy {ipath_audio_source} --> {ipath_audio_target}")
# break
if EXTRACT_AUDIO:
path_data = path_root.joinpath("processing")
vpath_ids = sorted(path_data.glob("*"))
print(f"Have {len(vpath_ids)} person folders --> {vpath_ids[0]}")
for i, ipath_id in enumerate(vpath_ids):
pid = ipath_id.stem # person id
# if pid in ["s1", "s10", "s11", "s12", "s13", "s14"]:
# continue
# video
vpath_videos = sorted(ipath_id.glob("*/video/video_orignal.mp4"))
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, --> {vpath_videos[0]}")
# for each video
list_dict = []
for iv, ipath_video in enumerate(vpath_videos):
vid = ipath_video.parent.parent.stem # video id
if iv % 50 == 0:
print(f"--> processing the {iv}-th video --> {ipath_video}")
ipath_audio = ipath_video.parent.parent.joinpath("audio/audio_extract.wav")
ipath_audio.parent.mkdir(parents=True, exist_ok=True)
if ipath_audio.exists():
continue
# extract audio
cmd = f'ffmpeg -y -i {str(ipath_video)} -vn -acodec pcm_s16le -ac 1 -ar 16000 {str(ipath_audio)}'
# print(f"RUN: {cmd}")
os.system(cmd)
# break
#break
@@ -0,0 +1,73 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
total_pid = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10" ]
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/GRID/processing') # '../data/trinity/source'
v_ids = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each speaker
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
if id_name not in total_pid: continue
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
# for each video
for iv, ipath_video in enumerate(v_dir_videos):
ipath_data = ipath_video.parent.parent
ipath_audio = ipath_data.joinpath("audio/audio_extract.wav")
ipath_save_feat = ipath_data.joinpath("audio/feat_mel_trim.npy")
if ipath_save_feat.exists() or not ipath_audio.exists():
continue
# load trim audio
fps = 25
data, sr = librosa.load(str(ipath_audio), sr=16000) # 16000 = fps * 640 让这个sr是fps的整数,
hop_len = int(sr / fps)
n_fft = int(sr * 0.13) # default 2048
# print(f"data={data.shape}, sr={sr}, fps={fps}, hop_len={sr/fps}, frames = {(len(data) / sr) * fps}, minmax = {np.min(data)},{np.max(data)}")
# melspectrogram
mel = librosa.feature.melspectrogram(y=data, sr=sr,
n_fft=n_fft, # FFT窗口的长度
hop_length=hop_len, # 帧移
win_length=n_fft, # 窗口长度,默认=n_fft
window="hann", # 加hanming窗
n_mels=27, # 滤波器组
fmin=0.0, fmax=8000)
mel = np.log(mel+1).T
print(f"sr={sr}, data ={data.shape}, mel = {mel.shape}, frames = {(len(data) / sr) * fps}, (min,max)=({np.min(mel), np.max(mel)}")
# align to video
if mel.shape[0] < 75:
print(f"\n skip, mel shape ={mel.shape}, frames={(len(data) / sr) * fps}")
else:
mel_align = mel[:75, :]
# save
np.save(ipath_save_feat, mel_align)
@@ -0,0 +1,82 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
import torch
from scipy.io.wavfile import read
# We're using the audio processing from TacoTron2 to make sure it matches
sys.path.insert(0, '/ssdata1/lsen/CODE/Audio2Expression/3rdpart/')
import tacotron2
from tacotron2.layers import TacotronSTFT
total_pid = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10" ]
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/GRID/processing') # '../data/trinity/source'
# STFT model
model = TacotronSTFT(filter_length=1024,
hop_length=256,
win_length=1024,
sampling_rate=22050,
mel_fmin=0.0, mel_fmax=8000)
# dataset load
v_ids = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each speaker
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
if id_name not in total_pid: continue
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
# for each video
for iv, ipath_video in enumerate(v_dir_videos):
ipath_data = ipath_video.parent.parent
ipath_audio = ipath_data.joinpath("audio/audio_extract.wav")
ipath_save = ipath_data.joinpath("audio/feat_mel_no_align_trim.npy") # feat_mel_trim_split
if ipath_save.exists(): continue
if not ipath_audio.exists():
print(f"ERROR: NOT Exist {ipath_audio}")
continue
# load trim audio
audio, sr = librosa.load(str(ipath_audio), mono=True) # 16484 = fps * 550 让这个sr是fps的整数,
if sr != 22050:
raise ValueError(f"{sr} SR doesn't match target 22050 SR")
audio = torch.from_numpy(audio).float()
audio = audio.unsqueeze(0)
print(f"audio shape = {audio.shape}, audio min-max({audio.min():.4f}, {audio.max():.4f})")
audio[audio > 1.0] = 1.0
audio[audio < -1.0] = -1.0
melspec = model.mel_spectrogram(audio)
melspec = torch.squeeze(melspec, 0) # (80, 20374)
print(f"Melspec shape = {melspec.shape}, min-max({melspec.min():.4f}, {melspec.max():.4f}), rate = {melspec.shape[1] / 75}")
# save
melspec = melspec.permute(1,0) # (nsplits, nsteps, 80)
np.save(ipath_save, melspec) # (nsplit, 173, 80)
print(f"melspec shape = {melspec.shape}, save to --> {ipath_save}")
# break
+68
View File
@@ -0,0 +1,68 @@
import cv2
import os, sys
import glob
import numpy as np
import time
import pdb
import argparse
from pathlib2 import Path
total_pid = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10" ]
if __name__ == "__main__":
path_data = Path("/yrfs/lsen/DATA/GRID/processing")
v_ids = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_ids)} dir files, \n {v_ids[:10]}")
# for each speaker
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
if id_name not in total_pid: continue
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
# for each video
for iv, ipath_video in enumerate(v_dir_videos):
# create data path
path_save_frames = ipath_video.parent.parent.joinpath("frames")
# if already exists frames
if path_save_frames.exists():
if len(list(path_save_frames.glob("*.jpg"))) > 10:
continue
path_save_frames.mkdir(parents=True, exist_ok=True)
#print("save frames dir = ", {path_save_frames})
# STEP1: extract frames
count = 0
cap = cv2.VideoCapture(str(ipath_video))
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
while True:
success, image = cap.read()
if not success:
break
ipath_frame = path_save_frames.joinpath(f"frame-{count:04d}.jpg")
if not ipath_frame.exists():
cv2.imwrite(str(ipath_frame), image)
count += 1
if iv % 50 == 0:
print(f"--> Extract {iv}-th video, have {length} frames, {ipath_video}")
#print(f"extract and save the {count}/{length}-th frame --> {ipath_frame}")
#break
#break
+82
View File
@@ -0,0 +1,82 @@
import numpy as np
from PIL import Image
from pathlib2 import Path
from face_alignment import FaceAlignment, LandmarksType
def select_ldmk(ladmks):
ladmks = np.array(ladmks)
area = []
for i in range(ladmks.shape[0]):
lands = ladmks[i, ...]
xmin, xmax = np.min(lands[:, 0]), np.max(lands[:, 0])
ymin, ymax = np.min(lands[:, 1]), np.max(lands[:, 1])
area.append((xmax - xmin) * (ymax-ymin))
print("area = ", area, "select = ", np.argmax(area))
return ladmks[np.argmax(area), :, :]
if __name__ == "__main__":
path_data = Path("/mnt/data/DATA/GRID/processing")
model = FaceAlignment(LandmarksType._2D, flip_input=False, device="cuda:0")
v_ids = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each person
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
#if id_name != "s29": continue
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for iv, ipath_video in enumerate(v_dir_videos):
ipath_data = ipath_video.parent.parent
#print(f"ipath_data = {ipath_data}")
ipath_frames = ipath_data.joinpath("frames")
ipath_landmk = ipath_data.joinpath("landmk")
ipath_landmk.mkdir(parents=True, exist_ok=True)
# STEP1: get frames
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
if iv % 50 == 0:
print(f"--> Extract {iv}-th video landmark: have {len(v_path_frames)} frames in {ipath_frames}")
# STEP2: extract landmarks
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
if not ipath_landmk_frame.exists():
# detect image
image = Image.open(str(kpath_frame)).convert('RGB') # (h, w, 3)
ldmk_pred = model.get_landmarks(np.array(image))
if ldmk_pred is None:
continue
# select the first one or the bigger one face
if len(ldmk_pred) > 1:
ldmk_pred = select_ldmk(ldmk_pred)
else:
ldmk_pred = ldmk_pred[0]
np.savetxt(str(ipath_landmk_frame), ldmk_pred, fmt=" %3d")
#break
#break
@@ -0,0 +1,93 @@
import os
import numpy as np
import librosa
import python_speech_features
from pathlib import Path
import multiprocessing
def splited_by_windows(data, wind_stride, wind_length, padding=True):
"""
data: seq_len1 x dim1
return: seq_len2 x wind_length x dim1
where seq_len2 = (L + 2p - k) // wind_stride + 1
"""
seq_len1, dim1 = data.shape
seq_len2 = seq_len1 // wind_stride + 1
#print("DATA befor shape=", data.shape) # DATA befor shape= (121, 13)
data = np.pad(data, pad_width=((wind_length//2,wind_length//2), (0,0)), mode="reflect")
#print("DATA after shape=", data.shape) # DATA after shape= (149, 13)
data_output = np.zeros((seq_len2, wind_length, dim1-1), dtype=float)
for i in range(seq_len2):
ibeg = i * wind_stride
iend = i * wind_stride + wind_length
data_output[i, :, :] = data[ibeg : iend, 1:] # TODO: why form 1:
return data_output
# def func_processing(path_audio):
if __name__ == "__main__":
path_data = Path("/mnt/data/DATA/GRID/processing")
v_ids = sorted(path_data.glob("*"))
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each person
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for j, jpath_videos in enumerate(v_dir_videos):
# if (j+1) % 100 == 0: print(f"processing {j+1}/{len(v_dir_videos)}")
jpath_data = jpath_videos.parent.parent
jpath_frame = jpath_data.joinpath("frames")
nframes = len(sorted(jpath_frame.glob("*.jpg")))
#print(f"jpath_data = {jpath_data}, nframe = {nframes}")
ipath_audio = jpath_data.joinpath("audio/audio_extract.wav")
ipath_feat = jpath_data.joinpath("audio/mfcc_feat.npy")
ipath_feat_align = jpath_data.joinpath("audio/mfcc_feat_align.npy")
# for some data not have .wav files
if not ipath_audio.exists():
print(f"NOT EXISTING: {ipath_audio}")
continue
if ipath_feat_align.exists():
continue
# extarct mfcc feature
audio, sr = librosa.load(str(ipath_audio), sr=16000) # 16000, (69760, )
mfcc = python_speech_features.mfcc(audio, 16000, winstep=0.01) # seqlen1 x 13
np.save(ipath_feat, mfcc)
# splited by windows (to fit video frame with fps 25)
wind_stride = 4 # 4 x 10ms = 40 ms, video(25fps) frame = 1/25s = 40ms
wind_length = 28 # 28 x 10ms = 280 ms, = 7 frames * 40 ms
## seq_len2 = (seq_len1 + 2*pad - wind_length) // wind_stride + 1
mfcc_align = splited_by_windows(mfcc, wind_stride, wind_length, padding=True) # seq_len2 x 28 x 12,
np.save(ipath_feat_align, mfcc_align)
if j % 50 == 0:
print(f"--> Extract {j}-th video landmark: audio shape={audio.shape}, mfcc shape={mfcc.shape}, mfcc_align = {mfcc_align.shape} duration={len(audio) / sr}")
# break
# break
Whitespace-only changes.
+98
View File
@@ -0,0 +1,98 @@
import os,sys
import cv2
import math
import numpy as np
from pathlib import Path
import torch
from PIL import Image
from reconstruction import Reconstruction
def get_rect(lands):
xmin, xmax = np.min(lands[:, 0]), np.max(lands[:, 0])
ymin, ymax = np.min(lands[:, 1]), np.max(lands[:, 1])
length = 1.2 * math.sqrt((xmax - xmin) * (xmax - xmin) + (ymax - ymin) * (ymax - ymin))
left = (xmax + xmin) / 2 - length / 2
top = (ymax + ymin) / 2 - length / 2
rect = np.array([left, top, length], dtype=np.float)
return rect
def show_landmarks(path_img, path_save, lands):
img = cv2.imread(str(path_img))
for i in range(68):
cv2.circle(img, (lands[i,0], lands[i,1]), 2, (255,0,0))
ipath_save = path_save.joinpath(path_img.stem + "_land.jpg")
cv2.imwrite(str(ipath_save), img)
if __name__ == "__main__":
# load Reconstruction
model = Reconstruction()
# load data
path_data = Path("/mnt/data/DATA/GRID/processing")
v_ids = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each person
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
# print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for iv, ipath_video in enumerate(v_dir_videos):
if iv % 50 == 0:
print(f"--> Extract {iv}-th video landmark in {ipath_video}")
ipath_data = ipath_video.parent.parent
#print(f"ipath_data = {ipath_data}")
ipath_frames = ipath_data.joinpath("frames")
ipath_ladmks = ipath_data.joinpath("landmk")
ipath_coeffs = ipath_data.joinpath("coeff")
# STEP1: get frames and landmark
vpath_frames = sorted(ipath_frames.glob("*.jpg"), key=lambda ipath: int(ipath.stem[-4:]))
vpath_ladmks = list(ipath_ladmks.glob("*.txt"))
vpath_coeffs = list(ipath_coeffs.glob("*.txt"))
if len(vpath_frames) != len(vpath_ladmks) or len(vpath_frames) ==0: # if missing landmark data
continue
if ipath_coeffs.exists() and len(vpath_coeffs) == len(vpath_frames): # if have already reconstruction
continue
# STEP2: reconstruction
for ik, ipath_frame in enumerate(vpath_frames):
fid = int(ipath_frame.stem[-4:])
ipath_ladmk = ipath_ladmks.joinpath(f"frame-{fid:04d}.txt") # get landmark path
if not ipath_ladmk.exists():
continue
# read image and landmark
image = Image.open(str(ipath_frame)).convert('RGB') # (h, w, 3)
ladmk = np.loadtxt(ipath_ladmk, dtype=int) # (68, 2)
bbox = get_rect(ladmk)
# show_landmarks(image, path_save, ildmk)
# reconstruction
model.eval_rgb(image, ladmk, bbox, iname=ipath_ladmk.stem, path_save=ipath_ladmks.parent)
if ik % 100 == 99:
print(f"reconstruction {ik+1:04} ..., -> {ipath_ladmk}")
@@ -0,0 +1,98 @@
import os,sys
import numpy as np
import librosa
import python_speech_features
from pathlib import Path
import multiprocessing
path_work = "/mnt/data/CODE/Audio-driven-TalkingFace-HeadPose/audio-to-expression"
sys.path.insert(0, path_work)
from src.tools.audio import get_melspec
def splited_by_windows(data, wind_stride, wind_length, padding=True):
"""
data: seq_len1 x dim1
return: seq_len2 x wind_length x dim1
where seq_len2 = (L + 2p - k) // wind_stride + 1
"""
seq_len1, dim1 = data.shape
seq_len2 = seq_len1 // wind_stride + 1
#print("DATA befor shape=", data.shape) # DATA befor shape= (121, 13)
data = np.pad(data, pad_width=((wind_length//2,wind_length//2), (0,0)), mode="reflect")
#print("DATA after shape=", data.shape) # DATA after shape= (149, 13)
data_output = np.zeros((seq_len2, wind_length, dim1-1), dtype=float)
for i in range(seq_len2):
ibeg = i * wind_stride
iend = i * wind_stride + wind_length
data_output[i, :, :] = data[ibeg : iend, 1:] # TODO: why form 1:
return data_output
# def func_processing(path_audio):
if __name__ == "__main__":
path_data = Path("/mnt/data/DATA/GRID/processing")
v_ids = sorted(path_data.glob("*"))
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each person
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for j, jpath_videos in enumerate(v_dir_videos):
# if (j+1) % 100 == 0: print(f"processing {j+1}/{len(v_dir_videos)}")
jpath_data = jpath_videos.parent.parent
jpath_frame = jpath_data.joinpath("frames")
nframes = len(sorted(jpath_frame.glob("*.jpg")))
#print(f"jpath_data = {jpath_data}, nframe = {nframes}")
ipath_audio = jpath_data.joinpath("audio/audio_extract.wav")
ipath_feat_save = jpath_data.joinpath("audio/melspec_feat.npy")
# for some data not have .wav files
if not ipath_audio.exists():
print(f"NOT EXISTING: {ipath_audio}")
continue
if ipath_feat_save.exists():
print(f"EXSTING, {ipath_feat_save}")
continue
# extarct mfcc feature
audio, sr = librosa.load(str(ipath_audio), sr=16000) #16000, (69760, )
mfcc_orig = python_speech_features.mfcc(audio, 16000, winstep=0.01)
y, sr = librosa.load(str(ipath_audio), sr=44100)
melFrames = np.transpose(get_melspec(y, sr, wsize=0.04, hsize=0.04)) # (n_frame, 64)
melDelta = np.insert(np.diff(melFrames, n=1, axis=0), 0, np.zeros((1, 64)), axis=0) # (n_frame - 1 , 64) + (1, 64) --> (n_frame, 64)
melDDelta = np.insert(np.diff(melFrames, n=2, axis=0), 0, np.zeros((2, 64)), axis=0) # (n_frame - 2 , 64) + (2, 64) --> (n_frame, 64)
data_audio = np.concatenate((melDelta, melDDelta), axis=1) # (n_frame, 128)
# save
np.save(str(ipath_feat_save), data_audio)
# print(f"SAVE: mfcc size={data_audio.shape} --> {str(ipath_feat_save)}") # mfcc size=(31, 28, 12)
# break
# break
+69
View File
@@ -0,0 +1,69 @@
import os
import glob
import pdb
import numpy as np
from pathlib import Path
from scipy.io import loadmat,savemat
COMBINE_COEFF_RBGFACE = True
COMBINE_LAMDK_RBGFACE = False
if __name__ == "__main__":
path_data = Path("/mnt/data/DATA/GRID/processing")
v_ids = sorted(path_data.glob("*"))
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each person
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for j, jpath_videos in enumerate(v_dir_videos):
# if (j+1) % 100 == 100: print(f"processing {j+1}/{len(v_dir_videos)}")
jpath_data = jpath_videos.parent.parent
jpath_frame = jpath_data.joinpath("frames")
jpath_ladmk = jpath_data.joinpath("landmk")
jpath_ladmk_save = jpath_data.joinpath("video/landmark.npy")
jpath_ladmk_save.parent.mkdir(parents=True, exist_ok=True)
v_frames = sorted(jpath_frame.glob("*.jpg"), key=lambda x: int(x.stem[-4:]))
v_ladmks = sorted(jpath_ladmk.glob("*.txt"), key=lambda x: int(x.stem[-4:]))
# print(f"contain {len(v_frames)} frames in {str(jpath_data)} -> {v_frames[:5]}")
if len(v_ladmks) != len(v_frames):
print(f"\t ERROR && Continue: This video have missing landmark, {str(jpath_ladmk)}")
continue
elif jpath_ladmk_save.exists():
continue
else:
ladmk_all = np.zeros((len(v_frames), 68, 2), np.float32)
for k, iframe in enumerate(v_frames):
fid = int(iframe.stem[-4:])
# load data
kpath_proj = jpath_ladmk.joinpath(f"frame-{fid:04d}.txt")
ladmk_all[k, :, :] = np.loadtxt(str(kpath_proj)) # (68, 2)
# save combine data
np.save(str(jpath_ladmk_save), ladmk_all)
# print(f"combine the coeff: {str(jpath_videos)} --> {str(jpath_ladmk_save)}")
# break
# break
View File
Whitespace-only changes.
+113
View File
@@ -0,0 +1,113 @@
"""
generated train annotation data
"""
import os
import pickle
import numpy as np
from pathlib import Path
from collections import OrderedDict
from common.landmark import landmark_normalize
pid_for_train = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10",
"s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20",
"s21", "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30"]
pid_for_test = ["s31", "s32", "s33", "s34"]
if __name__ == "__main__":
path_data = Path("/mnt/data/DATA/GRID/processing")
path_anno = Path("data/GRID/anno_test_half.pickle")
annodb = OrderedDict()
# if not existing
vpath_ids = sorted(path_data.glob("*"))
print(f"Have {len(vpath_ids)} person folders --> {vpath_ids[0]}")
# iter
for i, ipath_id in enumerate(vpath_ids):
pid = ipath_id.stem # person id
# select train pid
if pid not in pid_for_test:
continue
# video
vpath_videos = sorted(ipath_id.glob("*/video/video_orignal.mp4"))
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, --> {vpath_videos[0]}")
# for each video
list_dict = []
for iv, ipath_video in enumerate(vpath_videos):
vid = ipath_video.parent.parent.stem # video id
if iv % 50 == 0:
print(f"--> processing the {iv}-th video --> {ipath_video}")
ipath_data = ipath_video.parent.parent
ipath_frame = ipath_data.joinpath("frames")
ipath_ladmk = ipath_data.joinpath("landmk")
# ipath_coeff = ipath_data.joinpath("coeff")
ipath_mfccs = ipath_data.joinpath("audio/mfcc_feat.npy")
# STEP1: check if missing data
vpath_frame = sorted(ipath_frame.glob("*.jpg"), key=lambda ipath: int(ipath.stem[-4:]))
# vpath_coeff = sorted(ipath_coeff.glob("*.txt"), key=lambda ipath: int(ipath.stem[-4:]))
vpath_ladmk = sorted(ipath_ladmk.glob("*.txt"), key=lambda ipath: int(ipath.stem[-4:]))
nframes = len(vpath_frame)
# assert
if (nframes < 25) or (nframes != len(vpath_ladmk)) : # or (nframes != len(vpath_coeff)):
print(f"DEBUG: nframes={nframes}, nladmk={len(vpath_ladmk)}, --> {ipath_video}") # ncoeff={len(vpath_coeff)}
continue
# load mfcc
list_mfcc = np.load(ipath_mfccs) # nframes x 28 x 12
# # load 3DMM & landmarks
# list_idn = np.zeros((nframes, 100), dtype=float) # coeff idn, nframes x 100
# list_exp = np.zeros((nframes, 79), dtype=float) # coeff exp, nframes x 79
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
for k, kpath_frame in enumerate(vpath_frame):
fid = int(kpath_frame.stem[-4:]) # frame id
# # 3dmm
# kpath_3dmm = ipath_coeff.joinpath(f"frame-{fid:04d}.txt")
# coeff = np.loadtxt(kpath_3dmm, dtype=float) # 316: idn-100, exp-79, tex-100, euler-3, trans-3, illum-27, camr-4
# list_idn[k, :] = coeff[:100] # 100 identity coeff
# list_exp[k, :] = coeff[100:100+79] # 79 expression coeff
# ldmk
kpath_ldmk = ipath_ladmk.joinpath(f"frame-{fid:04d}.txt")
ldmk = np.loadtxt(kpath_ldmk) # shape = (68, 2)
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
v_ldmk[k, :, :] = ldmk
v_ldmk_norm[k, :, :] = ldmk_norm
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
# STEP 3: concat data
list_dict.append({"pid": pid, "vid": vid,
"mfcc": list_mfcc,
# "exp": list_exp, "idn":list_idn,
"ldmk": v_ldmk, "ldmk_norm": v_ldmk_norm, "ldmk_auxs":v_ldmk_auxs
})
annodb[pid] = list_dict
# pickle and save
with open(str(path_anno), "wb") as f:
pickle.dump(annodb, f)
print(f"Total have {len(annodb)} item anno, save to --> {path_anno}")
+117
View File
@@ -0,0 +1,117 @@
"""
generated train annotation data
"""
import os
import pickle
import numpy as np
from pathlib import Path
from collections import OrderedDict
from common.landmark import landmark_normalize
pid_for_train = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10",
"s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20",
"s21", "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30"]
pid_for_test = ["s31", "s32", "s33", "s34"]
if __name__ == "__main__":
path_data = Path("/mnt/data/DATA/GRID/processing")
path_anno = Path("data/GRID/anno_train_full.pickle")
annodb = OrderedDict()
# if not existing
vpath_ids = sorted(path_data.glob("*"))
print(f"Have {len(vpath_ids)} person folders --> {vpath_ids[0]}")
# iter
n_videos = 0
for i, ipath_id in enumerate(vpath_ids):
pid = ipath_id.stem # person id
# select train pid
if pid not in pid_for_train:
continue
# video
vpath_videos = sorted(ipath_id.glob("*/video/video_orignal.mp4"))
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, --> {vpath_videos[0]}")
# for each video
list_dict = []
for iv, ipath_video in enumerate(vpath_videos):
vid = ipath_video.parent.parent.stem # video id
if iv % 50 == 0:
print(f"--> processing the {iv}-th video --> {ipath_video}")
ipath_data = ipath_video.parent.parent
ipath_frame = ipath_data.joinpath("frames")
ipath_ladmk = ipath_data.joinpath("landmk")
# ipath_coeff = ipath_data.joinpath("coeff")
ipath_mfccs = ipath_data.joinpath("audio/mfcc_feat.npy")
# STEP1: check if missing data
vpath_frame = sorted(ipath_frame.glob("*.jpg"), key=lambda ipath: int(ipath.stem[-4:]))
# vpath_coeff = sorted(ipath_coeff.glob("*.txt"), key=lambda ipath: int(ipath.stem[-4:]))
vpath_ladmk = sorted(ipath_ladmk.glob("*.txt"), key=lambda ipath: int(ipath.stem[-4:]))
nframes = len(vpath_frame)
# assert
if (nframes < 60) or (nframes != len(vpath_ladmk)) : # or (nframes != len(vpath_coeff)):
print(f"DEBUG: nframes={nframes}, nladmk={len(vpath_ladmk)}, --> {ipath_video}") # ncoeff={len(vpath_coeff)}
continue
# load mfcc
# list_mfcc = np.load(ipath_mfccs) # nframes x 28 x 12
# # load 3DMM & landmarks
# list_idn = np.zeros((nframes, 100), dtype=float) # coeff idn, nframes x 100
# list_exp = np.zeros((nframes, 79), dtype=float) # coeff exp, nframes x 79
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
for k, kpath_frame in enumerate(vpath_frame):
fid = int(kpath_frame.stem[-4:]) # frame id
# # 3dmm
# kpath_3dmm = ipath_coeff.joinpath(f"frame-{fid:04d}.txt")
# coeff = np.loadtxt(kpath_3dmm, dtype=float) # 316: idn-100, exp-79, tex-100, euler-3, trans-3, illum-27, camr-4
# list_idn[k, :] = coeff[:100] # 100 identity coeff
# list_exp[k, :] = coeff[100:100+79] # 79 expression coeff
# ldmk
kpath_ldmk = ipath_ladmk.joinpath(f"frame-{fid:04d}.txt")
ldmk = np.loadtxt(kpath_ldmk) # shape = (68, 2)
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
v_ldmk[k, :, :] = ldmk
v_ldmk_norm[k, :, :] = ldmk_norm
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
# STEP 3: concat data
list_dict.append({"pid": pid, "vid": vid,
# "mfcc": list_mfcc,
# "exp": list_exp, "idn":list_idn,
# "ldmk_norm": v_ldmk_norm, "ldmk_auxs":v_ldmk_auxs
"ldmk": v_ldmk,
})
n_videos += 1
# add to annodb
annodb[pid] = list_dict
# pickle and save
with open(str(path_anno), "wb") as f:
pickle.dump(annodb, f)
print(f"Total have {n_video} video items, save to --> {path_anno}")
@@ -0,0 +1,82 @@
import os
import sys
import json
import numpy as np
from pathlib2 import Path
import sys
sys.path.insert(0, "/ssdata1/lsen/CODE/Audio2Expression")
from common.landmark import landmark_normalize
# from common.animation import save_animation, save_animation_with_gt
total_pid = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10" ]
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/GRID/processing')
v_ids = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each speaker
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
if id_name not in total_pid: continue
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
# for each video
for iv, ipath_video in enumerate(v_dir_videos):
ipath_data = ipath_video.parent.parent
ipath_ldmk = ipath_data.joinpath("landmk-PFLD")
ipath_save_feat = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy")
if ipath_save_feat.exists():
continue
# load landmark
feat_ldmk = []
prev_ldmk = None
nContinue = 0
for j in range(75):
jpath_ldmk = ipath_ldmk.joinpath(f"frame-{j:04d}.txt")
if not jpath_ldmk.exists():
print("ERROR: Missing the landmark of frame --> ", jpath_ldmk)
if nContinue <= 2:
data_ldmk = prev_ldmk
nContinue += 1
else:
nContinue += 1
break
else:
data_ldmk = np.loadtxt(jpath_ldmk).astype(np.float)
data_ldmk, _, _ = landmark_normalize(data_ldmk) # normalize
prev_ldmk = data_ldmk
nContinue = 0
feat_ldmk.append(data_ldmk)
# save
feat_ldmk = np.array(feat_ldmk) # (N, 68, 2)
if nContinue <= 2 and feat_ldmk.shape[0] == 75:
np.save(ipath_save_feat, feat_ldmk)
print(f"feat shape = {feat_ldmk.shape}, save to -> {ipath_save_feat}") # (nframe, 68, 2)
# save to animation
else:
print(f"ERROR: some landmark missing or length not same, length = {feat_ldmk.shape}")
+71
View File
@@ -0,0 +1,71 @@
import os
import sys
from pathlib2 import Path
import shutil
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/GRID/processing/s1')
v_dir_videos = sorted(path_data.glob("*/audio/feat_ldmk_trim_norm.npy"))
path_audio_wav = Path("data/paper_GRID_gt/audio_wav")
path_ldmk_25fps = Path("data/paper_GRID_gt/ldmk_25fps")
path_audio_feat = Path("data/paper_GRID_gt/feat_mel_no_align")
path_video_25fps = Path("data/paper_GRID_gt/video_25fps")
path_audio_wav.mkdir(parents=True, exist_ok=True)
path_ldmk_25fps.mkdir(parents=True, exist_ok=True)
path_video_25fps.mkdir(parents=True, exist_ok=True)
path_audio_feat.mkdir(parents=True, exist_ok=True)
ncount = 0
for i, ipath in enumerate(v_dir_videos):
ipath_data = ipath.parent.parent
print(f"ipath_data = {ipath_data}")
ipath_audio = ipath_data.joinpath("audio/audio_extract.wav")
ipath_ldmks = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy")
ipath_video = ipath_data.joinpath("video/video_orignal.mp4")
ipath_audio_feat = ipath_data.joinpath("audio/feat_mel_no_align_trim.npy")
# skip if not exsits
if not ipath_ldmks.exists(): continue
if not ipath_audio.exists(): continue
if not ipath_video.exists(): continue
# copy to
# ipath_audio_target = path_audio_wav.joinpath(f"clips_{ncount:03d}.wav")
# shutil.copy(src=str(ipath_audio), dst=str(ipath_audio_target))
# print(f"copy {ipath_audio} --> {ipath_audio_target}")
# ipath_ldmks_target = path_ldmk_25fps.joinpath(f"clips_{ncount:03d}.npy")
# shutil.copy(src=str(ipath_ldmks), dst=str(ipath_ldmks_target))
# print(f"copy {ipath_ldmks} --> {ipath_ldmks_target}")
# ipath_video_target = path_video_25fps.joinpath(f"clips_{ncount:03d}.mp4")
# shutil.copy(src=str(ipath_video), dst=str(ipath_video_target))
# print(f"copy {ipath_video} --> {ipath_video_target}")
ipath_audio_feat_tgt = path_audio_feat.joinpath(f"clips_{ncount:03d}.npy")
shutil.copy(src=str(ipath_audio_feat), dst=str(ipath_audio_feat_tgt))
print(f"copy {ipath_audio_feat} --> {ipath_audio_feat_tgt}")
ncount += 1
if ncount >= 100: break