update write_video with ffmpeg

This commit is contained in:
sen.liang committed 2022-04-24 17:49:11 +08:00
1 parent 4d4015350c
commit 0d5689979f
8 files changed
+186 -173

No files matched your search

+1 -3
View File
@@ -31,7 +31,6 @@ def save_animation(data_motion, path_save, suffix, w=128*5, h=72*5, dpi=80):
animation.write_videofile(str(ipath_save), fps=fps, logger=None) animation.write_videofile(str(ipath_save), fps=fps, logger=None)
def save_animation_ws_audio(data_motion, path_save, path_audio=None, start_time=None, end_time=None, fps=30, w=256, h=256, dpi=150): def save_animation_ws_audio(data_motion, path_save, path_audio=None, start_time=None, end_time=None, fps=30, w=256, h=256, dpi=150):
""" convert data_motion to .mp4 animation """ convert data_motion to .mp4 animation
data_motion, shape [nsteps, 136] data_motion, shape [nsteps, 136]
@@ -207,7 +206,7 @@ def write_video_with_gt(images_pt, images_gt, raw_speech, path_video, fps=50, sr
writer = cv2.VideoWriter(file_video.name, cv2.VideoWriter_fourcc(*'mp4v'), fps, (2*W, H), True) writer = cv2.VideoWriter(file_video.name, cv2.VideoWriter_fourcc(*'mp4v'), fps, (2*W, H), True)
for i in range(num_frame): for i in range(num_frame):
concate_image = np.concatenate((images_pt[i], images_gt), axis=1) # (H, 2*W, 3) concate_image = np.concatenate((images_pt[i], images_gt[i]), axis=1) # (H, 2*W, 3)
writer.write(concate_image) writer.write(concate_image)
# close # close
@@ -308,7 +307,6 @@ def save_animation_with_gt2(images_pt, images_gt, path_save, fps=None, path_audi
animation.close() animation.close()
def save_animation_with_gt(data_motion, data_motion_gt, path_save, suffix, w=128*5, h=72*5, dpi=80, maxsave=3, fps=30): def save_animation_with_gt(data_motion, data_motion_gt, path_save, suffix, w=128*5, h=72*5, dpi=80, maxsave=3, fps=30):
""" convert data_motion to .mp4 animation """ convert data_motion to .mp4 animation
data_motion, shape [B, N, 68, 2] data_motion, shape [B, N, 68, 2]
@@ -1,13 +1,10 @@
GPUS: '9' GPUS: '6'
WORKERS: 4 WORKERS: 4
OUTPUT_DIR: 'experiments/audio2pose' OUTPUT_DIR: 'experiments/audio2pose'
DEBUG: False DEBUG: False
verbose: False verbose: False
VISUAL:
vsdm_env: "actor2-1h-happy-pretrain"
FREQ: FREQ:
batch_print: 20 batch_print: 20
epoch_save: 5 epoch_save: 5
@@ -40,11 +37,9 @@ DATASET:
flip: False flip: False
shifting_speed: False shifting_speed: False
root: './data/LuoXData/LuoXData-pose-16h' # obama-deca-3-5-08-mini root: './data/LuoXData/LuoXData-pose-16h'
root_raw: '/mfs/lsen/DATA/LuoXData/processing2'
path_mean_dict: './data/LuoXData/DECA_LuoXData_mean.npy' path_mean_dict: './data/LuoXData/DECA_LuoXData_mean.npy'
filter: 'savgol' filter: 'savgol'
speech_extractor: 'wav2vec'
nwind_second_train: 3 nwind_second_train: 3
nwind_second_valid: 3 nwind_second_valid: 3
@@ -54,12 +49,14 @@ TEST:
batch_size: 2 batch_size: 2
TRAIN: TRAIN:
lr: 0.00005 lr: 0.0001
batch_size: 100 batch_size: 128
shuffle: True shuffle: True
apply_testing: True apply_testing: True
apply_validation: True apply_validation: True
apply_lr_scheduler: False
apply_update_parameters: True
optimizer: 'Adam' optimizer: 'Adam'
momentum: 0.9 momentum: 0.9
@@ -70,15 +67,13 @@ TRAIN:
grad_clip_norm: False grad_clip_norm: False
# lr_policy: 'multistep' # lr_policy: 'multistep'
# lr_milestones: [20, 50] # lr_milestones: [20, 50]
lr_policy: 'plateau' # lr_policy: 'plateau'
resume: False resume: False
reset_lr: False reset_lr: False
resume_suffix: "20220128-10H10M10S" resume_suffix: "20220128-10H10M10S"
epoch_begin: 0 # 5000 # 2300 # 2600 epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 150 epoch_end: 300
# for cyclical schedule # for cyclical schedule
apply_update_parameters: True apply_update_parameters: True
@@ -0,0 +1,91 @@
GPUS: '3'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2pose'
DEBUG: False
verbose: False
FREQ:
batch_print: 20
epoch_save: 5
epoch_valid: 1
epoch_test: 5
MODEL:
name: 'audio2pose'
name_netG: "audio2pose_mvae"
dim_motion: 6
dim_speech: 1024
dim_hidden: 64
num_vertices: 5023
n_lookahead_motion: 1
n_lookprevs_motion: 1
pretrain: False
path_checkpoint: "experiments/audio2pose/train_audio2pose_luox_20220415/20220416-02H02M55S"
load_epoch: 300
DATASET:
fps: 50
sr: 16000
name_train: "motion_pose"
name_valid: "motion_pose"
flip: False
shifting_speed: False
root: './data/Obama/obama-pose-8h' # obama-deca-3-5-08-mini
path_mean_dict: './data/Obama/DECA_obama_mean_wf.npy'
filter: 'savgol'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TEST:
batch_size: 2
TRAIN:
lr: 0.0001
batch_size: 128
shuffle: True
apply_testing: True
apply_validation: True
apply_lr_scheduler: False
apply_update_parameters: True
optimizer: 'Adam'
momentum: 0.9
beta1: 0.5
beta2: 0.999
weight_decay: 0.0001
nesterov: True
grad_clip_norm: False
# lr_policy: 'multistep'
# lr_milestones: [20, 50]
# lr_policy: 'plateau'
resume: False
reset_lr: False
resume_suffix: "20220128-10H10M10S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 300
# for cyclical schedule
apply_update_parameters: True
n_cycle_period: 25
epoch_teacher: 50
epoch_sampling: 100
LOSS:
names: ["rec", "kl", "vel", "all"]
lambda_kl: 1
lambda_vel: 10
@@ -16,7 +16,6 @@ from decalib.utils.config import cfg as deca_cfg
def main(args): def main(args):
# device = args.device # device = args.device
device = "cuda:7" device = "cuda:7"
@@ -25,9 +24,9 @@ def main(args):
deca = DECA(config = deca_cfg, device=device) deca = DECA(config = deca_cfg, device=device)
# path_data = Path("/yrfs/lsen/DATA/TestData/processing") # 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") print(f"Have {len(v_dir_videos)} dir files")
# IDs = ["actor-2HD", "actor-3HD"] # IDs = ["actor-2HD", "actor-3HD"]
+1
View File
@@ -182,6 +182,7 @@ config.TRAIN = edict()
config.TRAIN.apply_validation = False config.TRAIN.apply_validation = False
config.TRAIN.apply_testing = False config.TRAIN.apply_testing = False
config.TRAIN.apply_update_parameters = False config.TRAIN.apply_update_parameters = False
config.TRAIN.apply_lr_scheduler = False
config.TRAIN.lr = 0.001 config.TRAIN.lr = 0.001
config.TRAIN.lr_step = [50, 100] config.TRAIN.lr_step = [50, 100]
+7 -8
View File
@@ -241,7 +241,7 @@ class Audio2MeshModel(Base):
print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}") print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}")
def infer(self, batch_cond, raw_speech, suffix="", save_npy=True): def infer(self, batch_cond, batch_speech, suffix="", save_npy=True):
self.eval() self.eval()
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond) self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
@@ -255,7 +255,7 @@ class Audio2MeshModel(Base):
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
# render & and save # render & and save
self.save_reconstruct(batch_pdt_geo, raw_speech, path_save=Path(self.opt.OUTPUT_DIR), self.save_reconstruct(batch_pdt_geo, batch_speech, path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix, vis_landmarks=False) suffix=suffix, vis_landmarks=False)
if save_npy: if save_npy:
@@ -402,7 +402,7 @@ class Audio2MeshModel(Base):
return loss, loss_dict return loss, loss_dict
def save_reconstruct(self, batch_pdt_geo, raw_speech, path_save, suffix="", vis_landmarks=False): def save_reconstruct(self, batch_pdt_geo, batch_speech, path_save, suffix="", vis_landmarks=False):
# batch_pdt_geo, [B x N x dim_motion] # batch_pdt_geo, [B x N x dim_motion]
B, N, *_ = batch_pdt_geo.shape B, N, *_ = batch_pdt_geo.shape
@@ -441,7 +441,7 @@ class Audio2MeshModel(Base):
# write video # write video
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}_pt.mp4") ipath_save = path_save.joinpath(f"{suffix}_{i:02d}_pt.mp4")
write_video(v_render_pt, raw_speech, ipath_save, fps=50) write_video(v_render_pt, batch_speech, ipath_save, fps=50)
self.logger.info(f"save video to -> {str(ipath_save)}") self.logger.info(f"save video to -> {str(ipath_save)}")
@@ -465,7 +465,7 @@ class Audio2MeshModel(Base):
return images return images
@torch.no_grad() @torch.no_grad()
def save_reconstruct_with_gt2(self, batch_pdt_geo, batch_tgt_geo, raw_speech, path_save, suffix="", vis_landmarks=True): def save_reconstruct_with_gt2(self, batch_pdt_geo, batch_tgt_geo, batch_speech, path_save, suffix="", vis_landmarks=True):
# batch_pdt_geo, [1 x N x 5023 x 3] # batch_pdt_geo, [1 x N x 5023 x 3]
# batch_tgt_geo, [1 x N x 5023 x 3] # batch_tgt_geo, [1 x N x 5023 x 3]
@@ -518,7 +518,7 @@ class Audio2MeshModel(Base):
# save animation # save animation
write_video_with_gt(v_render_pt, v_render_gt, raw_speech, ipath_save, fps=50, sr=16000) write_video_with_gt(v_render_pt, v_render_gt, batch_speech, ipath_save, fps=50, sr=16000)
# print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}") # print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}")
@@ -587,8 +587,7 @@ class Audio2MeshModel(Base):
jstart_time = (jstart_frame + 7) / self.opt.DATASET.fps # xxx.yyy min jstart_time = (jstart_frame + 7) / self.opt.DATASET.fps # xxx.yyy min
jend_time = (jstart_frame + 7 + self.nseq) / self.opt.DATASET.fps # xxx.yyy min jend_time = (jstart_frame + 7 + self.nseq) / self.opt.DATASET.fps # xxx.yyy min
# print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}") # print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}")
# print(f"jstart_time={jstart_time}, jend_time={jend_time}") # print(f"jstart_time={jstart_time}, jend_time={jend_time}")
# save animation # save animation
# print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}") # print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}")
+74 -145
View File
@@ -15,7 +15,7 @@ from src.optims import get_optimizer, get_scheduler
from src.utils import util from src.utils import util
# common # common
from common.animation import save_animation_with_gt2, save_images_with_audio from common.animation import write_video, write_video_with_gt
from common.debug import debug from common.debug import debug
from common.losses import WingLoss from common.losses import WingLoss
@@ -104,10 +104,10 @@ class Audio2PoseModel(Base):
# padding half frame length for bed and end # padding half frame length for bed and end
npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5) npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5)
raw_pad = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge") pad_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
debug(self.opt, f"after padding raw_pad = {raw_pad.shape}, dtype={raw_pad.dtype}", verbose=False) debug(self.opt, f"after padding pad_speech = {pad_speech.shape}, dtype={pad_speech.dtype}", verbose=False)
inputs = self.processor(list(raw_pad), sampling_rate=16000, return_tensors="pt") inputs = self.processor(list(pad_speech), sampling_rate=16000, return_tensors="pt")
with torch.no_grad(): with torch.no_grad():
cond = self.extractor(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat cond = self.extractor(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat
debug(self.opt, f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False) debug(self.opt, f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False)
@@ -120,8 +120,11 @@ class Audio2PoseModel(Base):
self.c = cond # (B, nsteps, 16, nc_speech) self.c = cond # (B, nsteps, 16, nc_speech)
self.B, self.nsteps, self.nwind, self.dim_speech = cond.size() self.B, self.nsteps, self.nwind, self.dim_speech = cond.size()
self.x = self.x[:, 7:7+self.nsteps, :] # (B, nsteps, nc_motion) self.x = self.x[:, 7:7+self.nsteps, :] # (B, nsteps, nc_motion)
self.raw_speech = raw_speech[:, 7*self.opt.DATASET.sr: (7+self.nsteps)*self.opt.DATASET.sr] # (B, nsteps * sr)
# cut audio clips
idx_beg = int(7 * self.opt.DATASET.sr / self.opt.DATASET.fps + 0.5)
idx_end = int((7 + self.nsteps) * self.opt.DATASET.sr / self.opt.DATASET.fps + 0.5)
self.raw_speech = raw_speech[:, idx_beg: idx_end] # (B, nsteps * sr / fps)
self.idn = self.idn[:, 7:7+self.nsteps, :] self.idn = self.idn[:, 7:7+self.nsteps, :]
self.exp = self.exp[:, 7:7+self.nsteps, :] self.exp = self.exp[:, 7:7+self.nsteps, :]
@@ -170,7 +173,6 @@ class Audio2PoseModel(Base):
self.logger.info(f"\t[UPDATE] lambda_kl = {self.opt.LOSS.lambda_kl}") self.logger.info(f"\t[UPDATE] lambda_kl = {self.opt.LOSS.lambda_kl}")
def training(self, batch_input, idx_epoch=0, idx_batch=0): def training(self, batch_input, idx_epoch=0, idx_batch=0):
self.train() # set train model self.train() # set train model
self.set_input(batch_input) self.set_input(batch_input)
@@ -265,61 +267,58 @@ class Audio2PoseModel(Base):
return loss_dict return loss_dict
def infer(self, batch_cond, path_audio, suffix="", save_npy=True):
def infer(self, batch_cond, batch_speech, suffix="", save_npy=True):
self.eval() self.eval()
c = batch_cond.float().to(self.device) # (B, nsteps, 16, nc_speech) self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
nbtach, nstep, *_ = c.shape
with torch.no_grad(): with torch.no_grad():
batch_pdt_geo = self.netG(self.cond) # B x N x dim_motion
batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
batch_pos = self.netG(self.cond) # B x N x dim_motion print(f"testing pt shape = {batch_pdt_geo.shape}")
batch_pos += self.temp_verts # B x N x 5023 x 3
print(f"testing pt shape = {batch_pos.shape}")
# !! add specific when render & output !! # !! add specific when render & output !!
batch_pos = batch_pos - self.temp_verts + self.temp_verts_specific batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
# render & and save # render & and save
self.save_reconstruct(batch_pos, path_audio, self.save_reconstruct(batch_pdt_geo, batch_speech, path_save=Path(self.opt.OUTPUT_DIR),
path_save=Path(self.opt.OUTPUT_DIR), suffix=suffix, vis_landmarks=False)
suffix=suffix)
if save_npy: if save_npy:
# save result # save result
batch_pos = batch_pos.cpu().numpy() batch_pdt_geo = batch_pdt_geo.cpu().numpy()
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy") path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
np.save(path_save_npy, batch_pos) np.save(path_save_npy, batch_pdt_geo)
print(f"save infer_result shape = {batch_pos.shape} -> {path_save_npy}") print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}")
@torch.no_grad()
def testing(self, batch_input, idx_epoch=0, idx_batch=0): def testing(self, batch_input, idx_epoch=0, idx_batch=0):
self.eval() # set eval model self.eval() # set eval model
self.set_input(batch_input) self.set_input(batch_input)
with torch.no_grad(): batch_pt = torch.zeros_like(self.x) # [B, nsteps, nc_motion]
# batch_pt[:, 0, 3] = self.x[:, 0, 3] # T-pose + first scale from input data
batch_pt = torch.zeros_like(self.x) # [B, nsteps, nc_motion] batch_pt[:, 0] = self.x[:, 0] # T-pose + first scale from input data
# batch_pt[:, 0, 3] = self.x[:, 0, 3] # T-pose + first scale from input data
batch_pt[:, 0] = self.x[:, 0] # T-pose + first scale from input data
for istep in range(1, self.nsteps): for istep in range(1, self.nsteps):
ibatch_z = torch.randn((self.B, self.dim_latent), device=self.device) # [B, dim_latent] ibatch_z = torch.randn((self.B, self.dim_latent), device=self.device) # [B, dim_latent]
ibatch_c = self.c[:, istep] # [B, nwind, nc_speech] ibatch_c = self.c[:, istep] # [B, nwind, nc_speech]
ibatch_x_prev = batch_pt[:, istep-1] # [B, nc_motion] ibatch_x_prev = batch_pt[:, istep-1] # [B, nc_motion]
# forward # forward
ibatch_pt = self.netG.sample(ibatch_z, ibatch_x_prev, ibatch_c) # [B, nc_motion] ibatch_pt = self.netG.sample(ibatch_z, ibatch_x_prev, ibatch_c) # [B, nc_motion]
debug(self.opt, f"[test] ibatch_pt = {ibatch_pt.shape}") debug(self.opt, f"[test] ibatch_pt = {ibatch_pt.shape}")
batch_pt[:, istep] = ibatch_pt.detach().clone() # update batch_pt batch_pt[:, istep] = ibatch_pt.detach().clone() # update batch_pt
# save video # save video
# print(f"testing pt shape = {batch_pt.shape}, gt shape = {self.x.shape}") # print(f"testing pt shape = {batch_pt.shape}, gt shape = {self.x.shape}")
self.save_reconstruct_with_gt(batch_pt, self.x, self.raw_speech,
self.save_reconstruct_with_gt(batch_pt, self.x, path_save=Path(self.opt.OUTPUT_DIR),
path_save=Path(self.opt.OUTPUT_DIR), suffix=f'sampled_{idx_epoch:05d}_{idx_batch:03d}')
suffix=f'sampled_{idx_epoch:05d}_{idx_batch:03d}')
@torch.no_grad() @torch.no_grad()
@@ -345,6 +344,28 @@ class Audio2PoseModel(Base):
return verts, ldmk2d, ldmk3d return verts, ldmk2d, ldmk3d
@torch.no_grad()
def render_geometry(self, verts, cam=None, device=None):
"""
verts: [N x 5023 x 3]
"""
batch_size = verts.size(0)
if cam is None:
cam = torch.zeros(batch_size, 3).to(device) # (batch_size, 3)
# orth_proj
verts_proj = util.batch_orth_proj(verts, cam);
verts_proj[:,:,1:] = -verts_proj[:,:,1:]
# render
images = self.netR.render_shape(verts, verts_proj) # (batch_size, 3, 512, 512)
return images
def eval_losses(self, batch_pt, batch_gt, batch_mu, batch_lv): def eval_losses(self, batch_pt, batch_gt, batch_mu, batch_lv):
""" Computes the VAE loss function. """ Computes the VAE loss function.
pramas: pramas:
@@ -387,8 +408,9 @@ class Audio2PoseModel(Base):
@torch.no_grad() @torch.no_grad()
def save_reconstruct(self, batch_pdt_pos, raw_speech, path_save, suffix="", vis_landmarks=True): def save_reconstruct(self, batch_pdt_pos, batch_speech, path_save, suffix="", vis_landmarks=True):
# batch_pdt_pos, [B x N x dim_motion] # batch_pdt_pos, [B x N x dim_motion]
# batch_speech, [B x N*sr ]
B, N, *_ = batch_pdt_pos.shape B, N, *_ = batch_pdt_pos.shape
nbatch_render = 10 nbatch_render = 10
@@ -428,99 +450,18 @@ class Audio2PoseModel(Base):
for m in range(nbatch_real): for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...])) v_render_pt.append(tensor2image(render_pt[m, ...]))
# write tmp audio
tmp_audio = tempfile.NamedTemporaryFile(suffix='.wav')
wavfile.write(tmp_audio.name, rate=16000, data=raw_speech)
# save animation # write video
save_images_with_audio(v_render_pt, tmp_audio.name, ipath_save) ipath_save = path_save.joinpath(f"{suffix}_{i:02d}_pt.mp4")
write_video(v_render_pt, batch_speech, ipath_save, fps=50)
self.logger.info(f"save video to -> {str(ipath_save)}")
@torch.no_grad() @torch.no_grad()
def render_geometry(self, verts, cam=None, device=None): def save_reconstruct_with_gt(self, batch_pdt_pos, batch_tgt_pos, batch_speech, path_save, suffix=""):
"""
verts: [N x 5023 x 3]
"""
batch_size = verts.size(0)
if cam is None:
cam = torch.zeros(batch_size, 3).to(device) # (batch_size, 3)
# orth_proj
verts_proj = util.batch_orth_proj(verts, cam);
verts_proj[:,:,1:] = -verts_proj[:,:,1:]
# render
images = self.netR.render_shape(verts, verts_proj) # (batch_size, 3, 512, 512)
return images
@torch.no_grad()
def save_reconstruct_with_gt2(self, batch_pdt_pos, batch_tgt_geo, raw_speech, path_save, suffix="", vis_landmarks=True):
# batch_pdt_pos, [1 x N x 5023 x 3]
# batch_tgt_geo, [1 x N x 5023 x 3]
B, N, *_ = batch_pdt_pos.shape
ipos_pt = batch_pdt_pos[0, ...] # [N x 5023 x 3]
ipos_gt = batch_tgt_geo[0, ...] # [N x 5023 x 3]
ipath_save = path_save.joinpath(f"{suffix}_{0:02d}.mp4")
v_render_pt = []
v_render_gt = []
nbatch_render = 10
for k in range(0, N, nbatch_render):
# split
kpos_pt = ipos_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
kpos_gt = ipos_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
nbatch_real = kpos_pt.size(0)
# cam
cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}")
# render
render_pt = self.render_geometry(kpos_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_gt = self.render_geometry(kpos_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
if vis_landmarks:
# landmarks 3d
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
kldmk3d_gt = self.netF.seletec_3d68(kgeo_gt) # [nbatch_real x 68 x 3]
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam);
kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:];
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0))
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = (0, 255, 0))
else:
render_pt = render_pt.cpu()
render_gt = render_gt.cpu()
# append each frame
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
v_render_gt.append(tensor2image(render_gt[m, ...]))
# write tmp audio
tmp_audio = tempfile.NamedTemporaryFile(suffix='.wav')
wavfile.write(tmp_audio.name, rate=16000, data=raw_speech)
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}")
save_animation_with_gt2(v_render_pt, v_render_gt, ipath_save, fps=50, path_audio=tmp_audio.name)
@torch.no_grad()
def save_reconstruct_with_gt(self, batch_pdt_pos, batch_tgt_pos, path_save, suffix=""):
# batch_pdt_pos, [B x N x nc_motion=6] # batch_pdt_pos, [B x N x nc_motion=6]
# batch_pdt_pos, [B x N x nc_motion=6] # batch_pdt_pos, [B x N x nc_motion=6]
# batch_speech, [B x N*sr ]
B, N, *_ = batch_pdt_pos.shape B, N, *_ = batch_pdt_pos.shape
nbatch_render = 10 nbatch_render = 10
@@ -570,19 +511,10 @@ class Audio2PoseModel(Base):
# get audio # get audio
jvid = self.batch_vid[i]
jstart_frame = self.batch_interv[0][i].numpy()
jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav"
jstart_time = (jstart_frame + 7) / self.opt.DATASET.fps # xxx.yyy min
jend_time = (jstart_frame + 7 + self.nsteps) / self.opt.DATASET.fps # xxx.yyy min
# print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}")
# print(f"jstart_time={jstart_time}, jend_time={jend_time}")
# save animation # save animation
# print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}") write_video_with_gt(v_render_pt, v_render_gt, batch_speech[i], ipath_save, fps=50, sr=16000)
save_animation_with_gt2(v_render_pt, v_render_gt, ipath_save, fps=self.opt.DATASET.fps,\
path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time)
######################################### #########################################
def tensor2image(tensor): def tensor2image(tensor):
@@ -645,7 +577,4 @@ def define_extractor(opt, device):
processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec) processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec)
extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device) extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device)
return processor, extractor return processor, extractor
+2 -1
View File
@@ -147,7 +147,8 @@ if __name__ == "__main__":
plot_loss(visor, epoch+1, valid_loss_dict, suffix="valid") plot_loss(visor, epoch+1, valid_loss_dict, suffix="valid")
################ upate learning rate by validataion ################ upate learning rate by validataion
model.update_learning_rate(valid_loss_dict["all"]) if opt.TRAIN.apply_lr_scheduler:
model.update_learning_rate(valid_loss_dict["all"])
################# testing ################# testing
if opt.TRAIN.apply_testing and (epoch+1) % opt.FREQ.epoch_test == 0: if opt.TRAIN.apply_testing and (epoch+1) % opt.FREQ.epoch_test == 0: