add onnx export
This commit is contained in:
1 parent
e2e8d8baf8
commit
28810e9ed3
22 files changed
+835
-342
No files matched your search
@@ -10,13 +10,6 @@ class MotionEvalDataset(Dataset):
|
||||
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
|
||||
|
||||
def __init__(self, opt, phase="train"):
|
||||
# self,
|
||||
# path_data = "./data_valid.npz", # opt.DATASET.root
|
||||
# fps = 50, # opt.DATASET.fps
|
||||
# sr = 16000, # opt.DATASET.sr
|
||||
# num_windows = 3, # eval(f"opt.DATASET.nwind_second_{phase}")
|
||||
# filter = "savgol",
|
||||
# ):
|
||||
super(MotionEvalDataset, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
|
||||
+7
-136
@@ -25,16 +25,8 @@ class MotionLiveDataset(Dataset):
|
||||
self.phase = phase
|
||||
path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz")
|
||||
|
||||
# for test
|
||||
# if phase == "valid":
|
||||
# path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz")
|
||||
# if phase == "test":
|
||||
# path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz")
|
||||
|
||||
print(f"[{self.phase}] load data ... --> {path_data}")
|
||||
# dict vid: {"data_motion", # [nframe, 53]
|
||||
# "data_speech", # [duration * sample_rate, ] raw deepseep
|
||||
# "nframe", "fps", "sr"}
|
||||
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
|
||||
self.num_pid = len(self.annodb)
|
||||
self.pids = list(self.annodb.keys())
|
||||
@@ -50,22 +42,11 @@ class MotionLiveDataset(Dataset):
|
||||
f'''nsteps_frame={self.nsteps_frame}\t'''
|
||||
f'''nsteps_segmt={self.nsteps_segmt} ''')
|
||||
|
||||
# path_motion = self.path_data.joinpath(f"motion_{phase}.npz")
|
||||
# path_speech = self.path_data.joinpath(f"speech_{phase}.npz")
|
||||
# print(f"load data ... --> {path_motion} | {path_speech}")
|
||||
|
||||
# self.data_motion = np.load(path_motion)['data'].astype(np.float32) # (N, nsteps, dim_motion)
|
||||
# self.data_speech = np.load(path_speech)['data'].astype(np.float32) # (N, nsteps, dim_speech)
|
||||
# print(f"motion data ={self.data_motion.shape}, output={self.data_speech.shape}")
|
||||
|
||||
# self.nc_motion = self.data_motion.shape[-1]
|
||||
# self.nc_speech = self.data_speech.shape[-1]
|
||||
# debug(opt, f"nc_motion={self.nc_motion}, nc_speech ={self.nc_speech }")
|
||||
|
||||
|
||||
def __len__(self):
|
||||
if self.phase == "train":
|
||||
return 10000
|
||||
return 20000
|
||||
elif self.phase == "valid":
|
||||
return 3000 #3000
|
||||
else:
|
||||
@@ -83,10 +64,6 @@ class MotionLiveDataset(Dataset):
|
||||
np.random.seed(int(idx + time.time()))
|
||||
vid = self.pids[idx % self.num_pid]
|
||||
|
||||
# # filter "2021-P29"
|
||||
# while vid == "2021-P29":
|
||||
# vid = self.pids[idx % self.num_pid]
|
||||
|
||||
# random select idx
|
||||
data = self.annodb[vid]
|
||||
data_motion = data["data_motion"] # (nframes, nc_motion)
|
||||
@@ -107,7 +84,7 @@ class MotionLiveDataset(Dataset):
|
||||
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
|
||||
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
|
||||
|
||||
assert data_speech.shape[0] == int(self.nsteps_segmt * speed), f"data_speech shape={data_speech.shape}, vid={vid}"
|
||||
assert data_speech.shape[0] == int(self.nsteps_segmt * speed), f"data_speech shape={data_speech.shape}, int(self.nsteps_segmt * speed) = {int(self.nsteps_segmt * speed)}, vid={vid}"
|
||||
assert data_motion.shape[0] == int(self.nsteps_frame * speed), f"data_motion shape={data_motion.shape}, vid={vid}"
|
||||
# print(f"speed={speed}, data_speech shape={data_speech.shape} data_motion shape={data_motion.shape}")
|
||||
|
||||
@@ -126,10 +103,12 @@ class MotionLiveDataset(Dataset):
|
||||
# print(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\t nsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
|
||||
|
||||
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
|
||||
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
|
||||
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}"
|
||||
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
|
||||
|
||||
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}, [{beg_segmt:04d},{end_segmt:04d})"
|
||||
assert data_motion.shape[0] == self.nsteps_frame, f"data_motion shape={data_motion.shape}, vid={vid}"
|
||||
|
||||
|
||||
# filter, explore doc: ./notebook/explore_pose.ipynb
|
||||
if self.opt.DATASET.filter == "savgol":
|
||||
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
|
||||
@@ -184,114 +163,6 @@ class MotionLiveDataset(Dataset):
|
||||
if speed < 0:
|
||||
data_motion = data_motion[:nsteps_motion*speed]
|
||||
data_speech = data_speech[:nsteps_speech*speed]
|
||||
|
||||
|
||||
|
||||
|
||||
return data_motion, data_speech
|
||||
|
||||
|
||||
|
||||
class MotionLiveEvalDataset(Dataset):
|
||||
"""
|
||||
Motion dataset.
|
||||
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
|
||||
|
||||
def __init__(self, opt, phase="train"):
|
||||
"""
|
||||
phase = "valid | test "
|
||||
"""
|
||||
super(MotionLiveEvalDataset, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.phase = phase
|
||||
path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz")
|
||||
print(f"\n [{self.phase}] load data ... --> {path_data}")
|
||||
|
||||
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
|
||||
self.num_pid = len(self.annodb)
|
||||
self.pids = list(self.annodb.keys())
|
||||
self.annodb_accums = self.count_annotations()
|
||||
self.overlap = 0.5
|
||||
|
||||
self.fps = opt.DATASET.fps # 50
|
||||
self.sr = opt.DATASET.sr # 16000
|
||||
|
||||
self.nwind = eval(f"opt.DATASET.nwind_second_{phase}")
|
||||
self.nsteps_frame = self.nwind * self.fps
|
||||
self.nsteps_segmt = self.nwind * self.sr
|
||||
|
||||
print(f'''len(annodb)={len(self.annodb)}\t'''
|
||||
f'''nsteps_frame={self.nsteps_frame}\t'''
|
||||
f'''nsteps_segmt={self.nsteps_segmt} ''')
|
||||
|
||||
|
||||
def __len__(self):
|
||||
return self.annodb_accums[-1]
|
||||
|
||||
|
||||
def count_annotations(self):
|
||||
acc = 0
|
||||
annodb_accums = np.zeros(self.num_pid + 1, dtype=int) # the first element set 0
|
||||
for i, anno_dict in enumerate(self.annodb.values()):
|
||||
acc += anno_dict["data_motion"].shape[0] // (self.nsteps_frame * self.overlap) - 1 # ncount_windows
|
||||
annodb_accums[i+1] = acc # 2
|
||||
|
||||
return annodb_accums
|
||||
|
||||
|
||||
def __getitem__(self, idx):
|
||||
"""
|
||||
Returns poses and conditioning.
|
||||
If data-dropout sould be applied, a random selection of the previous poses is masked.
|
||||
The control is not masked
|
||||
return:
|
||||
motion: (nsteps, nc_motion), current frame's pose (15 joint, xyz position)
|
||||
speech: (nsteps, nc_speech), conditional data = previous motion data + full windows contrl data
|
||||
"""
|
||||
|
||||
for i, iacc in enumerate(self.annodb_accums):
|
||||
if idx > iacc -1 and idx < self.annodb_accums[i+1]:
|
||||
pid, new_idx = i, idx - iacc
|
||||
break
|
||||
print(f"DEBUG: idx={idx}, pid = {pid}, iacc ={self.annodb_accums[i]}, new_idx = {new_idx}")
|
||||
|
||||
# return item
|
||||
vid = self.pids[pid]
|
||||
data = self.annodb[vid]
|
||||
data_motion = data["data_motion"] # (nframes, nc_motion)
|
||||
data_speech = data["data_speech"] # (nsegemts, )
|
||||
|
||||
nframe = data_motion.shape[0]
|
||||
nsegmt = data_speech.shape[0]
|
||||
|
||||
# random select beg:end frame
|
||||
beg_frame = new_idx
|
||||
end_frame = beg_frame + self.nsteps_frame
|
||||
|
||||
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
|
||||
end_segmt = beg_segmt + self.nsteps_segmt
|
||||
print(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\nnsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
|
||||
|
||||
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
|
||||
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
|
||||
print(f"data_motion-{data_motion.shape} data_speech={data_speech.shape}")
|
||||
|
||||
|
||||
# filter, explore doc: ./notebook/explore_pose.ipynb
|
||||
if self.opt.DATASET.filter == "savgol":
|
||||
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
|
||||
|
||||
|
||||
result = {
|
||||
"data": data_motion, # (nsteps_frame, dim_motion)
|
||||
"cond": data_speech, # (nsteps_frame, dim_speech)
|
||||
"vid": vid,
|
||||
"nframe": nframe,
|
||||
"frame_interval": [beg_frame, end_frame],
|
||||
# "duration_interval": [beg_frame/nframe, end_frame/nframe]
|
||||
}
|
||||
|
||||
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}"
|
||||
|
||||
return result
|
||||
return data_motion, data_speech
|
||||
+120
-86
@@ -1,10 +1,12 @@
|
||||
from collections import OrderedDict
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
from collections import OrderedDict
|
||||
|
||||
import tempfile
|
||||
from scipy.io import wavfile
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from pathlib import Path
|
||||
|
||||
from src.models.info import flame_mouth_idx
|
||||
@@ -16,8 +18,6 @@ from src.models.base import Base
|
||||
from src.optims import get_optimizer, get_scheduler
|
||||
from src.utils import util
|
||||
|
||||
from torchmetrics import MaxMetric, MeanMetric
|
||||
|
||||
# common
|
||||
from common.animation import save_animation_with_gt2, save_images_with_audio
|
||||
from common.debug import debug
|
||||
@@ -41,7 +41,10 @@ class Audio2Mesh2Model(Base):
|
||||
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]
|
||||
self.netG.module.decoder_mesh.weight.data = init_exp_weight
|
||||
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}")
|
||||
|
||||
# # print network parameters
|
||||
@@ -96,6 +99,7 @@ class Audio2Mesh2Model(Base):
|
||||
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec)
|
||||
self.extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(self.device)
|
||||
|
||||
|
||||
def set_input(self, batch_input):
|
||||
|
||||
# motion data
|
||||
@@ -133,7 +137,7 @@ class Audio2Mesh2Model(Base):
|
||||
with torch.no_grad():
|
||||
output = self.extractor(**inputs)
|
||||
cond = output.last_hidden_state
|
||||
# cond = output.extract_features
|
||||
|
||||
else:
|
||||
assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' "
|
||||
|
||||
@@ -142,8 +146,8 @@ class Audio2Mesh2Model(Base):
|
||||
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) # (nseqs, nc_motion, 16)
|
||||
cond = cond.permute(0, 1, 3, 2) # (nseqs, 16, 53)
|
||||
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)
|
||||
self.cond = cond
|
||||
|
||||
self.nseq = cond.size(1)
|
||||
@@ -155,6 +159,17 @@ class Audio2Mesh2Model(Base):
|
||||
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):
|
||||
self.train() # set train model
|
||||
self.set_input(batch_input)
|
||||
@@ -193,12 +208,41 @@ class Audio2Mesh2Model(Base):
|
||||
return loss_dict
|
||||
|
||||
|
||||
def infer_with_gt(self, batch_cond, batch_data, audio_raw, 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)
|
||||
|
||||
|
||||
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
|
||||
print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {vert.shape}")
|
||||
self.save_reconstruct_with_gt2(batch_pdt_geo, vert, audio_raw,
|
||||
path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=suffix)
|
||||
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, path_audio, 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.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}")
|
||||
@@ -270,11 +314,11 @@ class Audio2Mesh2Model(Base):
|
||||
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_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_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():
|
||||
@@ -286,74 +330,6 @@ class Audio2Mesh2Model(Base):
|
||||
return verts, ldmk2d, ldmk3d
|
||||
|
||||
|
||||
def eval_losses_for_valid(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_dict = {}
|
||||
|
||||
# synthesis geo rec
|
||||
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) # (B, N, num_vertices, 3)
|
||||
loss_dict["rec_geo"] = loss_rec_geo.mean().detach()
|
||||
|
||||
# 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) # (B, N-1, num_vertices, 3)
|
||||
loss_dict["vel_geo"] = loss_vel_geo.mean().detach()
|
||||
|
||||
# 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()
|
||||
|
||||
# ldmk3d_pdt_dis = torch.sqrt(((ldmk3d_pdt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68)
|
||||
# ldmk3d_tgt_dis = torch.sqrt(((ldmk3d_tgt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68)
|
||||
# loss_rec_ldmk = (ldmk3d_pdt_dis - ldmk3d_tgt_dis).abs().mean() # (B*N, 68) ==> (1,)
|
||||
|
||||
# loss_rec_ldmk= self.loss_func_wing(ldmk3d_pdt_dis, ldmk3d_tgt_dis)
|
||||
# loss_dict["rec_ldmk"] = loss_rec_ldmk.mean().detach()
|
||||
|
||||
# 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()
|
||||
|
||||
# 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()
|
||||
|
||||
|
||||
# # closure loss
|
||||
# diff_pdf_closure = batch_pdt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
|
||||
# - batch_pdt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
|
||||
|
||||
# diff_tgt_closure = batch_tgt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
|
||||
# - batch_tgt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
|
||||
|
||||
# loss_closure = self.loss_func_wing(diff_pdf_closure, diff_tgt_closure)
|
||||
# loss_dict["closure"] = loss_closure.mean().detach()
|
||||
|
||||
# if self.opt.LOSS.lambda_closure > 0:
|
||||
# loss += loss_closure.mean() * self.opt.LOSS.lambda_closure
|
||||
|
||||
|
||||
return loss_dict
|
||||
|
||||
|
||||
def eval_losses(self, batch_pdt_geo, batch_tgt_geo):
|
||||
""" Computes the VAE loss function.
|
||||
pramas:
|
||||
@@ -451,6 +427,7 @@ class Audio2Mesh2Model(Base):
|
||||
|
||||
# render
|
||||
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
||||
render_pt = render_pt.cpu()
|
||||
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
|
||||
|
||||
# append each frame
|
||||
@@ -481,6 +458,64 @@ class Audio2Mesh2Model(Base):
|
||||
|
||||
return images
|
||||
|
||||
@torch.no_grad()
|
||||
def save_reconstruct_with_gt2(self, batch_pdt_geo, batch_tgt_geo, raw_speech, path_save, suffix=""):
|
||||
# batch_pdt_geo, [1 x N x 5023 x 3]
|
||||
# batch_tgt_geo, [1 x N x 5023 x 3]
|
||||
|
||||
B, N, *_ = batch_pdt_geo.shape
|
||||
|
||||
igeo_pt = batch_pdt_geo[0, ...] # [N x 5023 x 3]
|
||||
igeo_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
|
||||
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}")
|
||||
|
||||
# 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))
|
||||
|
||||
# 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_geo, batch_tgt_geo, path_save, suffix=""):
|
||||
# batch_pdt_geo, [B x N x 5023 x 3]
|
||||
@@ -529,9 +564,8 @@ class Audio2Mesh2Model(Base):
|
||||
# write to image
|
||||
# render_pt = tensor2image(render_pt) # (nbatch_real, 3, 512, 512), on cpu
|
||||
# render_gt = tensor2image(render_gt) # (nbatch_real, 3, 512, 512), on cpu
|
||||
|
||||
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = 'r', gt_color='g')
|
||||
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = 'g')
|
||||
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))
|
||||
|
||||
# append each frame
|
||||
for m in range(nbatch_real):
|
||||
@@ -586,12 +620,12 @@ def define_netG(opt):
|
||||
|
||||
# to GPU
|
||||
netG.to(f"cuda:{opt.GPUS[0]}")
|
||||
netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs
|
||||
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
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ class Audio2Mesh(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(Audio2Mesh, self).__init__()
|
||||
|
||||
|
||||
self.opt = opt
|
||||
self.num_vertices = opt.MODEL.num_vertices
|
||||
|
||||
@@ -29,13 +29,11 @@ class Audio2Mesh(nn.Module):
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
|
||||
+38
-49
@@ -577,96 +577,85 @@ def dict_tensor2npy(tensor_dict):
|
||||
# ---------------------------------- visualization
|
||||
# end_list = np.array([17, 22, 27, 42, 48, 31, 36, 68], dtype = np.int32) - 1
|
||||
end_list = np.array([17, 22, 27, 31, 36], dtype = np.int32) - 1
|
||||
|
||||
def plot_kpts(image, kpts, color = 'r'):
|
||||
def plot_kpts(image, kpts, color = (255,0,0), color_line=(255,255,255)):
|
||||
''' Draw 68 key points
|
||||
Args:
|
||||
image: the input image
|
||||
kpt: (68, 3).
|
||||
'''
|
||||
if color == 'r':
|
||||
c = (255, 0, 0)
|
||||
elif color == 'g':
|
||||
c = (0, 255, 0)
|
||||
elif color == 'b':
|
||||
c = (255, 0, 0)
|
||||
image = image.copy()
|
||||
kpts = kpts.copy()
|
||||
|
||||
# radius = max(int(min(image.shape[0], image.shape[1])/200), 1)
|
||||
radius = 1
|
||||
|
||||
for i in range(kpts.shape[0]):
|
||||
st = kpts[i, :2]
|
||||
if kpts.shape[1]==4:
|
||||
if kpts[i, 3] > 0.5:
|
||||
c = (0, 255, 0)
|
||||
else:
|
||||
c = (0, 0, 255)
|
||||
|
||||
# draw cicle
|
||||
image = cv2.circle(image,(int(st[0]), int(st[1])), radius, c, -1)
|
||||
|
||||
# draw line
|
||||
if i not in end_list:
|
||||
ed = kpts[i + 1, :2] if i != 67 else kpts[60, :2]
|
||||
ed = kpts[36, :2] if i == 41 else ed
|
||||
ed = kpts[42, :2] if i == 47 else ed
|
||||
image = cv2.line(image, (int(st[0]), int(st[1])), (int(ed[0]), int(ed[1])), (255, 255, 255), radius)
|
||||
image = cv2.line(image, (int(st[0]), int(st[1])), (int(ed[0]), int(ed[1])), color_line, radius)
|
||||
|
||||
# draw cicle
|
||||
image = cv2.circle(image,(int(st[0]), int(st[1])), radius, color, -1)
|
||||
|
||||
|
||||
return image
|
||||
|
||||
def plot_verts(image, kpts, color = 'r'):
|
||||
|
||||
|
||||
def plot_verts(image, kpts, color = (255,0,0)):
|
||||
''' Draw 68 key points
|
||||
Args:
|
||||
image: the input image
|
||||
kpt: (68, 3).
|
||||
'''
|
||||
c = (0, 0, 0)
|
||||
c = (255, 0, 0) if color == 'r' else c
|
||||
c = (0, 255, 0) if color == 'g' else c
|
||||
c = (0, 0, 255) if color == 'b' else c
|
||||
c = (0, 255, 255) if color == 'y' else c
|
||||
|
||||
image = image.copy()
|
||||
|
||||
image = image.copy()
|
||||
for i in range(kpts.shape[0]):
|
||||
st = kpts[i, :2]
|
||||
image = cv2.circle(image,(int(st[0]), int(st[1])), 1, c, -1)
|
||||
image = cv2.circle(image,(int(st[0]), int(st[1])), 1, color, -1)
|
||||
|
||||
return image
|
||||
|
||||
def tensor_vis_landmarks(images, landmarks, gt_landmarks=None, color = 'g', isScale=True, gt_color = 'r'):
|
||||
def tensor_vis_landmarks(images, landmarks, gt_landmarks=None, color = (0, 255, 0), isScale=True, color_gt = (255, 0, 0)):
|
||||
# visualize landmarks
|
||||
vis_landmarks = []
|
||||
|
||||
images = images.cpu().numpy()
|
||||
predicted_landmarks = landmarks.detach().cpu().numpy()
|
||||
|
||||
if gt_landmarks is not None:
|
||||
gt_landmarks_np = gt_landmarks.detach().cpu().numpy()
|
||||
ldmks_pt = landmarks.detach().cpu().numpy()
|
||||
ldmks_gt = gt_landmarks.detach().cpu().numpy() if gt_landmarks is not None else None
|
||||
|
||||
vis_landmarks = []
|
||||
for i in range(images.shape[0]):
|
||||
image = images[i]
|
||||
image = image.transpose(1,2,0)[:,:,[2,1,0]].copy(); image = (image*255)
|
||||
|
||||
image = images[i].transpose(1,2,0)[:,:,[2,1,0]].copy()
|
||||
image = image*255
|
||||
|
||||
# if landmarks is scale
|
||||
ildmks_pt = ldmks_pt[i]
|
||||
if isScale:
|
||||
predicted_landmark = predicted_landmarks[i]
|
||||
predicted_landmark[...,0] = predicted_landmark[...,0]*image.shape[1]/2 + image.shape[1]/2
|
||||
predicted_landmark[...,1] = predicted_landmark[...,1]*image.shape[0]/2 + image.shape[0]/2
|
||||
else:
|
||||
predicted_landmark = predicted_landmarks[i]
|
||||
ildmks_pt[...,0] = ildmks_pt[...,0]*image.shape[1]/2 + image.shape[1]/2
|
||||
ildmks_pt[...,1] = ildmks_pt[...,1]*image.shape[0]/2 + image.shape[0]/2
|
||||
|
||||
#
|
||||
if predicted_landmark.shape[0] == 68:
|
||||
image_landmarks = plot_kpts(image, predicted_landmark, color)
|
||||
if gt_landmarks is not None:
|
||||
image_landmarks = plot_verts(image_landmarks, gt_landmarks_np[i]*image.shape[0]/2 + image.shape[0]/2, gt_color)
|
||||
if ildmks_pt.shape[0] == 68:
|
||||
image_landmarks = plot_kpts(image, ildmks_pt, color, color_line=color)
|
||||
else:
|
||||
image_landmarks = plot_verts(image, predicted_landmark, color)
|
||||
if gt_landmarks is not None:
|
||||
image_landmarks = plot_verts(image_landmarks, gt_landmarks_np[i]*image.shape[0]/2 + image.shape[0]/2, gt_color)
|
||||
image_landmarks = plot_verts(image, ildmks_pt, color, color_line=color)
|
||||
|
||||
# if have landmarks gt
|
||||
if ldmks_gt is not None:
|
||||
ildmks_gt = ldmks_gt[i]
|
||||
if isScale:
|
||||
ildmks_gt[...,0] = ildmks_gt[...,0]*image.shape[1]/2 + image.shape[1]/2
|
||||
ildmks_gt[...,1] = ildmks_gt[...,1]*image.shape[0]/2 + image.shape[0]/2
|
||||
|
||||
if ildmks_gt.shape[0] == 68:
|
||||
image_landmarks = plot_kpts(image_landmarks, ildmks_gt, color_gt, color_line=color_gt)
|
||||
else:
|
||||
image_landmarks = plot_verts(image_landmarks, ildmks_gt, color_gt, color_line=color_gt)
|
||||
|
||||
|
||||
vis_landmarks.append(image_landmarks)
|
||||
|
||||
vis_landmarks = np.stack(vis_landmarks)
|
||||
|
||||
Reference in new issue
Block a user