584 lines
24 KiB
Python
584 lines
24 KiB
Python
|
|
import numpy as np
|
|
from collections import OrderedDict
|
|
|
|
import torch
|
|
import torch.nn as nn
|
|
from pathlib import Path
|
|
|
|
from src.models.info import flame_mouth_idx
|
|
from src.models.info import idx_upper_mouth_68ldmk, idx_lower_mouth_68ldmk
|
|
from src.models.info import idx_left_mouth_68ldmk, idx_right_mouth_68ldmk
|
|
|
|
from src.models import init_net
|
|
from src.models.base import Base
|
|
from src.optims import get_optimizer, get_scheduler
|
|
from src.utils import util
|
|
|
|
# common
|
|
from common.animation import write_video, write_video_with_gt
|
|
from common.debug import debug
|
|
from common.losses import WingLoss
|
|
|
|
# disentangle model
|
|
class Audio2MeshModel(Base):
|
|
|
|
def __init__(self, opt, logger):
|
|
Base.__init__(self, opt, logger)
|
|
|
|
self.opt = opt
|
|
self.logger = logger
|
|
self.names_model = ["G"] # G
|
|
|
|
# define networks
|
|
self.netG = define_netG(opt)
|
|
init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS)
|
|
|
|
# init last layer
|
|
init_exp_weight = np.load("./data/init_expression_basis.npy")
|
|
init_exp_weight = torch.from_numpy(init_exp_weight).float().to(self.device)
|
|
init_exp_weight = init_exp_weight[:, :50]
|
|
if isinstance(self.netG, torch.nn.DataParallel):
|
|
self.netG.module.decoder_mesh.weight.data = init_exp_weight
|
|
else:
|
|
self.netG.decoder_mesh.weight.data = init_exp_weight
|
|
print(f"init_exp_weight shape = {init_exp_weight.shape}")
|
|
|
|
self.netF = define_FLAME(opt, self.device)
|
|
self.netR = define_render(opt, self.device)
|
|
self.processor, self.extractor = define_extractor(opt, self.device)
|
|
|
|
# path_deca_mean = Path("./data/DECA_obama_mean.npy")
|
|
path_deca_mean = self.opt.DATASET.path_mean_dict
|
|
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
|
|
print(f"load mean deca coeff from > {path_deca_mean}, \nkeys = {self.mean_dict.keys()}")
|
|
|
|
# get template
|
|
self.temp_verts, self.temp_ldmk2d, self.temp_ldmk3d \
|
|
= self.get_template_vertices() # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
|
|
|
|
|
|
self.temp_verts_specific, self.temp_ldmk2d_specific, self.temp_ldmk3d_specific \
|
|
= self.get_template_vertices(self.mean_dict) # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
|
|
|
|
# self.temp_verts_specific = np.load("/ssdata1/lsen/CODE/audio-to-motion/data/Actor4/template_meiyan2.npy") # (5023, 3)
|
|
# self.temp_verts_specific = self.temp_verts_specific.reshape(1, 1, 5023, 3)
|
|
# self.temp_verts_specific = torch.from_numpy(self.temp_verts_specific).to(self.device)
|
|
|
|
# save to
|
|
|
|
# loss function
|
|
self.loss_func_wing = WingLoss(reduction="none") # return (B, )
|
|
self.loss_func_l1 = nn.L1Loss(reduction="none")
|
|
self.names_loss = opt.LOSS.names
|
|
|
|
# define loss weight
|
|
self.vertices_weight = torch.ones((1, 1, self.opt.MODEL.num_vertices, 3)).to(self.device)
|
|
self.vertices_weight[:, :, flame_mouth_idx, :] = 10
|
|
|
|
if self.isTrain:
|
|
# define optimizers
|
|
self.optimizer_G = get_optimizer(self.netG, opt)
|
|
self.optimizers.append(self.optimizer_G)
|
|
|
|
self.scheduler_G = get_scheduler(self.optimizer_G, opt)
|
|
self.schedulers.append(self.scheduler_G)
|
|
|
|
@torch.no_grad()
|
|
def set_input(self, batch_input):
|
|
""" """
|
|
# motion data
|
|
data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion)
|
|
|
|
self.batch_vid = batch_input['vid']
|
|
self.batch_nframe = batch_input['nframe']
|
|
self.batch_interv = batch_input['frame_interval']
|
|
|
|
debug(self.opt, f"data = {data.shape}, dtype={data.dtype}", verbose=False)
|
|
debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False)
|
|
debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False)
|
|
debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \
|
|
beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
|
|
|
|
# speech data
|
|
cond = None
|
|
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
|
|
debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
|
|
|
# padding half frame length for bed and end
|
|
npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5)
|
|
pad_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
|
|
debug(self.opt, f"after padding pad_speech = {pad_speech.shape}, dtype={pad_speech.dtype}", verbose=False)
|
|
|
|
inputs = self.processor(list(pad_speech), sampling_rate=16000, return_tensors="pt")
|
|
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)
|
|
|
|
# unfold speech data
|
|
cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_codit, 16)
|
|
cond = cond.permute(0, 1, 3, 2) # (B, nseqs, 16, nc_condit)
|
|
|
|
# setup
|
|
self.cond = cond
|
|
self.B, self.nsteps, self.nwind, self.dim_speech = cond.size()
|
|
data = data[:, 7:7+self.nsteps, :]
|
|
self.vert, self.ldmk2d, self.ldmk3d = self.get_vertices(data)
|
|
|
|
# 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)
|
|
|
|
debug(self.opt, f"[set_input] vert = {self.vert.shape}, dtype={self.vert.dtype}, device={self.vert.device}", verbose=False)
|
|
debug(self.opt, f"[set_input] cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
|
|
debug(self.opt, f"[set_input] ldmk2d = {self.ldmk2d.shape}, dtype={self.ldmk2d.dtype}, device={self.ldmk2d.device}", verbose=False)
|
|
debug(self.opt, f"[set_input] ldmk3d = {self.ldmk3d.shape}, dtype={self.ldmk3d.dtype}, device={self.ldmk3d.device}", verbose=False)
|
|
|
|
|
|
def forward(self, batch_input):
|
|
self.set_input(batch_input)
|
|
|
|
# forward
|
|
pred = self.netG(self.cond)
|
|
debug(self.opt, f"traing pred = {pred.shape}", verbose=False)
|
|
|
|
return pred
|
|
|
|
|
|
def training(self, batch_input, idx_epoch=0, idx_batch=0):
|
|
self.train() # set train model
|
|
self.set_input(batch_input)
|
|
|
|
# forward
|
|
self.pred = self.netG(self.cond)
|
|
self.pred += self.temp_verts
|
|
debug(self.opt, f"traing pred = {self.pred.shape}", verbose=False)
|
|
|
|
# loss
|
|
loss, loss_dict = self.eval_losses(self.pred, self.vert)
|
|
|
|
# backward
|
|
self.optimizer_G.zero_grad()
|
|
loss.backward()
|
|
|
|
if self.opt.TRAIN.grad_clip_norm: # operate grad
|
|
torch.nn.utils.clip_grad_value_(self.netG.parameters(), self.opt.TRAIN.max_grad_clip)
|
|
torch.nn.utils.clip_grad_norm_(self.netG.parameters(), self.opt.TRAIN.max_grad_norm)
|
|
|
|
self.optimizer_G.step()
|
|
|
|
return loss_dict
|
|
|
|
|
|
def validation(self, batch_input, idx_epoch=0, idx_batch=0):
|
|
self.eval() # set eval model
|
|
self.set_input(batch_input)
|
|
|
|
with torch.no_grad():
|
|
pred = self.netG(self.cond)
|
|
pred += self.temp_verts
|
|
|
|
loss, loss_dict = self.eval_losses(pred, self.vert)
|
|
|
|
return loss_dict
|
|
|
|
|
|
def infer_with_gt(self, batch_cond, batch_data, batch_speech, suffix="", save_npy=True):
|
|
self.eval()
|
|
|
|
cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
|
|
data = batch_data.float().to(self.device) # (B, nframe, 53)
|
|
vert, ldmk2d, ldmk3d = self.get_vertices(data)
|
|
|
|
# add a dimensions
|
|
# if batch_speech.dims == 1:
|
|
print(f"batch_speech shape = {batch_speech}")
|
|
batch_speech = batch_speech[np.newaxis, :] # (B, nsegmt)
|
|
|
|
|
|
with torch.no_grad():
|
|
batch_pdt_geo = self.netG(cond) # B x N x dim_motion
|
|
batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
|
|
print(f"testing pt shape = {batch_pdt_geo.shape}")
|
|
|
|
# !! add specific when render & output !!
|
|
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
|
|
|
|
# render & and save
|
|
|
|
self.save_reconstruct(batch_pdt_geo, batch_speech,
|
|
path_save=Path(self.opt.OUTPUT_DIR),
|
|
suffix=suffix, vis_landmarks=False)
|
|
|
|
# render & and save
|
|
print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {vert.shape}")
|
|
self.save_reconstruct_with_gt(batch_pdt_geo, vert, batch_speech,
|
|
path_save=Path(self.opt.OUTPUT_DIR),
|
|
suffix=suffix, vis_landmarks=False)
|
|
|
|
|
|
if save_npy:
|
|
# save result
|
|
batch_pdt_geo = batch_pdt_geo.cpu().numpy()
|
|
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
|
|
np.save(path_save_npy, batch_pdt_geo)
|
|
print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}")
|
|
|
|
|
|
def infer(self, batch_cond, batch_speech, suffix="", save_npy=True):
|
|
self.eval()
|
|
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
|
|
|
|
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
|
|
|
|
print(f"testing pt shape = {batch_pdt_geo.shape}")
|
|
|
|
# !! add specific when render & output !!
|
|
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
|
|
|
|
# render & and save
|
|
self.save_reconstruct(batch_pdt_geo, batch_speech, path_save=Path(self.opt.OUTPUT_DIR),
|
|
suffix=suffix, vis_landmarks=False)
|
|
|
|
if save_npy:
|
|
# save result
|
|
batch_pdt_geo = batch_pdt_geo.cpu().numpy()
|
|
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
|
|
np.save(path_save_npy, batch_pdt_geo)
|
|
print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}")
|
|
|
|
|
|
def testing(self, batch_input, idx_epoch=0, idx_batch=0):
|
|
self.eval() # set eval model
|
|
self.set_input(batch_input)
|
|
|
|
with torch.no_grad():
|
|
batch_pdt_geo = self.netG(self.cond) # B x N x 5023 x 3
|
|
batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
|
|
|
|
# !! add specific when render & output !!
|
|
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
|
|
|
|
print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {self.vert.shape}")
|
|
self.save_reconstruct_with_gt(batch_pdt_geo, self.vert, self.raw_speech,
|
|
path_save=Path(self.opt.OUTPUT_DIR),
|
|
suffix=f'sampled_{idx_epoch:05d}_{idx_batch:03d}')
|
|
|
|
|
|
def get_template_vertices(self, mean_dict=None):
|
|
|
|
batch_exp = torch.zeros(1, 50).to(self.device)
|
|
batch_pose = torch.zeros(1, 6).to(self.device)
|
|
|
|
if mean_dict is not None:
|
|
batch_shape = self.mean_dict["shape"].reshape(1, 100)
|
|
batch_shape = torch.from_numpy(batch_shape).float().to(self.device)
|
|
else:
|
|
batch_shape = torch.zeros(1, 100).to(self.device)
|
|
|
|
with torch.no_grad():
|
|
# verts = 1 x 5023 x 3, ldmk2d=1 x 68 x 3, ldmk3d=1 x 68 x 3
|
|
verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose)
|
|
verts = verts.reshape(1, 1, -1, 3) # 1 x 1 x 5023 x 3
|
|
ldmk2d = ldmk2d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
|
|
ldmk3d = ldmk3d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
|
|
|
|
print(f"template verts reshape = {verts.shape}")
|
|
|
|
|
|
return verts, ldmk2d, ldmk3d
|
|
|
|
|
|
def get_vertices(self, batch_motion):
|
|
"""
|
|
batch_motion, (nbatch, seqlen, 53)
|
|
"""
|
|
batch_exp = batch_motion[..., :50]
|
|
batch_pos_mouth = batch_motion[..., 50:]
|
|
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1)
|
|
|
|
batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50
|
|
batch_pos_mouth = batch_pos_mouth.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3
|
|
|
|
batch_shape= torch.zeros(nbatch * seqlen, 100).to(self.device) # nbatch * seqlen x 50
|
|
batch_pose = torch.zeros(nbatch * seqlen, 6).to(self.device) # nbatch * seqlen x 6
|
|
batch_pose[:, 3:6] = batch_pos_mouth
|
|
|
|
with torch.no_grad():
|
|
verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3
|
|
verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
|
|
ldmk2d = ldmk2d.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
|
|
ldmk3d = ldmk3d.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
|
|
|
|
return verts, ldmk2d, ldmk3d
|
|
|
|
|
|
def eval_losses(self, batch_pdt_geo, batch_tgt_geo):
|
|
""" Computes the VAE loss function.
|
|
pramas:
|
|
batch_tgt_geo, (nbatch, seqlen, num_vertices, 3)
|
|
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
|
|
"""
|
|
loss = 0
|
|
loss_dict = OrderedDict()
|
|
|
|
# synthesis geo rec
|
|
loss = 0
|
|
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
|
|
loss_dict["rec_geo"] = loss_rec_geo.mean().detach()
|
|
|
|
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight)
|
|
# loss_dict["rec_geo_w"] = loss_rec_geo2.mean().detach()
|
|
# loss += loss_rec_geo.mean() * self.opt.LOSS.lambda_rec_geo
|
|
loss += loss_rec_geo2.mean() * self.opt.LOSS.lambda_rec_geo
|
|
|
|
# synthesis geo volocity
|
|
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
|
|
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
|
|
|
|
loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo)
|
|
loss_dict["vel_geo"] = loss_vel_geo.mean().detach()
|
|
|
|
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight)
|
|
# loss_dict["vel_geo_w"] = loss_vel_geo2.mean().detach()
|
|
# loss += loss_vel_geo.mean() * self.opt.LOSS.lambda_vel_geo
|
|
|
|
if self.opt.LOSS.lambda_vel_geo > 0:
|
|
loss += loss_vel_geo2.mean() * self.opt.LOSS.lambda_vel_geo
|
|
|
|
# landmarks loss
|
|
ldmk3d_pdt = self.netF.seletec_3d68(batch_pdt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # (B*N, 68, 3)
|
|
ldmk3d_tgt = self.netF.seletec_3d68(batch_tgt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # (B*N, 68, 3)
|
|
loss_rec_ldmk = torch.sqrt(((ldmk3d_pdt - ldmk3d_tgt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68)
|
|
loss_dict["rec_ldmk"] = loss_rec_ldmk.mean().detach()
|
|
|
|
if self.opt.LOSS.lambda_rec_ldmk > 0:
|
|
loss += loss_rec_ldmk.mean() * self.opt.LOSS.lambda_rec_ldmk
|
|
|
|
# mouth closure_x loss (left/right mouth)
|
|
ldmk3d_pdt_left, ldmk3d_pdt_right = ldmk3d_pdt[:, idx_left_mouth_68ldmk], ldmk3d_pdt[:, idx_right_mouth_68ldmk]
|
|
ldmk3d_tgt_left, ldmk3d_tgt_right = ldmk3d_tgt[:, idx_left_mouth_68ldmk], ldmk3d_tgt[:, idx_right_mouth_68ldmk]
|
|
diff_pdt_mouth_x = torch.sqrt(((ldmk3d_pdt_left - ldmk3d_pdt_right)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
|
|
diff_tgt_mouth_x = torch.sqrt(((ldmk3d_tgt_left - ldmk3d_tgt_right)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
|
|
|
|
loss_closure_x = (diff_pdt_mouth_x - diff_tgt_mouth_x).abs().mean() # (B*N, 8) ==> (1,)
|
|
loss_dict["closure_x"] = loss_closure_x.mean().detach()
|
|
|
|
if self.opt.LOSS.lambda_closure_x > 0:
|
|
loss += loss_closure_x.mean() * self.opt.LOSS.lambda_closure_x
|
|
|
|
# mouth closure_y loss (upper/lower mouth)
|
|
ldmk3d_pdt_upper, ldmk3d_pdt_lower = ldmk3d_pdt[:, idx_upper_mouth_68ldmk], ldmk3d_pdt[:, idx_lower_mouth_68ldmk]
|
|
ldmk3d_tgt_upper, ldmk3d_tgt_lower = ldmk3d_tgt[:, idx_upper_mouth_68ldmk], ldmk3d_tgt[:, idx_lower_mouth_68ldmk]
|
|
diff_pdt_mouth_y = torch.sqrt(((ldmk3d_pdt_upper - ldmk3d_pdt_lower)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
|
|
diff_tgt_mouth_y = torch.sqrt(((ldmk3d_tgt_upper - ldmk3d_tgt_lower)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
|
|
|
|
loss_closure_y = (diff_pdt_mouth_y - diff_tgt_mouth_y).abs().mean() # (B*N, 8) ==> (1,)
|
|
loss_dict["closure_y"] = loss_closure_y.mean().detach()
|
|
|
|
if self.opt.LOSS.lambda_closure_y > 0:
|
|
loss += loss_closure_y.mean() * self.opt.LOSS.lambda_closure_y
|
|
|
|
|
|
# total loss
|
|
loss_dict["all"] = loss.detach()
|
|
|
|
return loss, loss_dict
|
|
|
|
def save_reconstruct(self, batch_pdt_geo, batch_speech, path_save, suffix="", vis_landmarks=False):
|
|
# batch_pdt_pos, [B x N x dim_motion]
|
|
# batch_speech, [B x N*sr/fps ]
|
|
|
|
B, N, *_ = batch_pdt_geo.shape
|
|
nbatch_render = 10
|
|
|
|
# for each batch
|
|
for i in range(B):
|
|
igeo_pt = batch_pdt_geo[i, ...]
|
|
|
|
v_render_pt = []
|
|
for k in range(0, N, nbatch_render):
|
|
# split
|
|
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
|
nbatch_real = kgeo_pt.size(0)
|
|
|
|
# cam
|
|
cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3)
|
|
cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3)
|
|
# print(f"cam shape = {cam.shape}")
|
|
|
|
# render
|
|
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
|
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
|
|
|
|
if vis_landmarks:
|
|
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
|
|
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
|
|
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
|
|
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, isScale=True, color = (255, 0, 0))
|
|
else:
|
|
render_pt = render_pt.cpu()
|
|
|
|
# append each frame
|
|
for m in range(nbatch_real):
|
|
v_render_pt.append(tensor2image(render_pt[m, ...]))
|
|
|
|
# write video
|
|
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()
|
|
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
|
|
|
|
|
|
@torch.no_grad()
|
|
def save_reconstruct_with_gt(self, batch_pdt_geo, batch_tgt_geo, batch_speech, path_save, suffix="", vis_landmarks=True):
|
|
# batch_pdt_geo, [B x N x 5023 x 3]
|
|
# batch_tgt_geo, [B x N x 5023 x 3]
|
|
# batch_speech, [B x N*sr/fps ]
|
|
|
|
B, N, *_ = batch_pdt_geo.shape
|
|
nbatch_render = 10
|
|
|
|
# for each batch
|
|
for i in range(B):
|
|
igeo_pt = batch_pdt_geo[i, ...] # [N x 5023 x 3]
|
|
igeo_gt = batch_tgt_geo[i, ...] # [N x 5023 x 3]
|
|
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
|
|
|
|
v_render_pt = []
|
|
v_render_gt = []
|
|
|
|
for k in range(0, N, nbatch_render):
|
|
|
|
# split
|
|
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
|
kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
|
|
|
nbatch_real = kgeo_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(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
|
render_gt = self.render_geometry(kgeo_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, ...]))
|
|
|
|
# save animation
|
|
write_video_with_gt(v_render_pt, v_render_gt, batch_speech[i], ipath_save, fps=50, sr=16000)
|
|
|
|
#########################################
|
|
def tensor2image(tensor):
|
|
# image = tensor.detach().cpu().numpy()
|
|
image = tensor.numpy()
|
|
image = image*255.
|
|
image = np.maximum(np.minimum(image, 255), 0)
|
|
image = image.transpose(1,2,0)[:,:,[2,1,0]]
|
|
|
|
return image.astype(np.uint8).copy()
|
|
|
|
|
|
def define_netG(opt):
|
|
netG = None
|
|
|
|
if opt.MODEL.name_netG == "audio2mesh":
|
|
from src.nn.audio2mesh import Audio2Mesh
|
|
netG = Audio2Mesh(opt)
|
|
|
|
elif opt.MODEL.name_netG == "audio2mesh_voca":
|
|
from src.nn.audio2mesh_voca import Audio2Mesh
|
|
netG = Audio2Mesh(opt)
|
|
|
|
elif opt.MODEL.name_netG == "audio2mesh_resnet":
|
|
from src.nn.audio2mesh_resnet import Audio2Mesh
|
|
netG = Audio2Mesh(opt)
|
|
|
|
else:
|
|
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!")
|
|
|
|
# to GPU
|
|
netG.to(f"cuda:{opt.GPUS[0]}")
|
|
if len(opt.GPUS) > 1:
|
|
netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs
|
|
|
|
return netG
|
|
|
|
|
|
def define_FLAME(opt, device):
|
|
from src.nn.FLAME import FLAME
|
|
|
|
model = FLAME(opt.FLAME).to(device)
|
|
|
|
return model
|
|
|
|
|
|
def define_render(opt, device):
|
|
from src.utils.renderer import SRenderY, set_rasterizer
|
|
|
|
set_rasterizer(opt.RENDER.rasterizer_type)
|
|
|
|
model = SRenderY(opt.RENDER.image_size,
|
|
obj_filename=opt.RENDER.topology_path,
|
|
uv_size=opt.RENDER.uv_size,
|
|
rasterizer_type=opt.RENDER.rasterizer_type
|
|
).to(device)
|
|
|
|
return model
|
|
|
|
def define_extractor(opt, device):
|
|
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
|
|
print("load Wav2Vec2Model ...")
|
|
# MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
|
|
# self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
|
|
# self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
|
|
|
|
path_ckpt_wav2vec = "./checkpoints/wav2vec2"
|
|
processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec)
|
|
extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device)
|
|
|
|
return processor, extractor
|