update audio2motion_gan

This commit is contained in:
sen.liang committed 2022-06-10 10:26:12 +08:00
1 parent 4785646e32
commit 5a6725072a
24 files changed
+20496 -132

No files matched your search

+38 -61
View File
@@ -284,24 +284,12 @@ def batch_orth_proj(X, camera):
''' orthgraphic projection
X: 3d vertices, [bz, n_point, 3]
camera: scale and translation, [bz, 3], [scale, tx, ty]
Xn:
'''
# remember high dimenstion
shape_dims = X.shape
if len(shape_dims) > 3:
X = X.reshape(-1, X.shape[-2], X.shape[-1]) # (..., n_point, 3)
camera = camera.reshape(-1, camera.shape[-1]) # (..., 3)
camera = camera.clone().view(-1, 1, 3)
X_trans = X[:, :, :2] + camera[:, :, 1:]
X_trans = torch.cat([X_trans, X[:,:,2:]], 2)
shape = X_trans.shape
Xn = (camera[:, :, 0:1] * X_trans)
# expand dimension
if len(shape_dims) > 3:
Xn = Xn.reshape(list(shape_dims[:-2]) + list(Xn.shape[1:]))
return Xn
# -------------------------------------- image processing
@@ -589,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)
@@ -57,46 +57,45 @@ class Generator(nn.Module):
)
def forward(self, c, z):
def forward(self, z, c):
""" forward function
Args:
c, motion data, (B, nseqs, 16, dim_c=1024)
z, randon noise, (B, dim_z=32)
z, randon noise, (B, N, dim_z=32)
c, motion data, (B, N, 16, dim_c=1024)
return:
(B x dim_x)
"""
logging.debug(f"[forward] input x shape = {c.shape}")
# logging.info(f"[forward] input x shape = {c.shape}")
# remember high dimenstion
shape_dims = c.shape
if len(shape_dims) > 3:
c = c.reshape(-1, c.shape[-2], c.shape[-1]) # (BN, nwind, dim_c)
c = c.reshape(-1, c.shape[-2], c.shape[-1]) # (BN, W, dim_c)
z = z.reshape(-1, z.shape[-1]) # (BN, dim_z)
# add noise
z_expand = z.unsqueeze(dim=1).repeat([shape_dims[1], shape_dims[2], 1]) # (BN, nwind, dim_z)
z_expand = z.unsqueeze(dim=1).repeat([1, shape_dims[2], 1]) # (BN, W, dim_z)
c = torch.cat([c, z_expand], dim=2) # (BN, nwind, dim_z + nc_c)
c = c.unsqueeze(dim=1).transpose(1,3) # (BN, 1, W, dim_x) --> (B, dim_x, W, 1)
# logging.info(f"[forward] transpose c shape = {c.shape}")
# preprocessing data
c = c.unsqueeze(dim=1).transpose(1,3) # (B, 1, W, dim_x) --> (B, dim_x, W, 1)
logging.debug(f"[forward] transpose c shape = {c.shape}")
feat = self.encoder(c) # (B, 50)
logging.debug(f"[forward] encoder shape = {feat.shape}")
feat = self.encoder(c) # (BN, 128)
# logging.info(f"[forward] encoder shape = {feat.shape}")
# add noise again
feat = torch.cat([feat, z], dim=1) # (B, 128 + dim_z)
logging.debug(f"[forward] decoder shape = {pred.shape}")
pred = self.decoder(feat) # (B, dim_x)
logging.debug(f"[forward] decoder shape = {pred.shape}")
feat = torch.cat([feat, z], dim=1) # (BN, 128 + dim_z)
# logging.info(f"[forward] concat feat + z shape = {feat.shape}")
pred = self.decoder(feat) # (BN, dim_x)
# logging.info(f"[forward] decoder shape = {pred.shape}")
# recover high dimension
if len(shape_dims) > 3:
pred = pred.reshape(list(shape_dims[:-2]) + list(pred.shape[1:]))
logging.debug(f"[forward] reshape shape = {pred.shape}")
# logging.info(f"[forward] reshape shape = {pred.shape}")
return pred
@@ -108,7 +107,6 @@ class Discriminator(torch.nn.Module):
super(Discriminator, self).__init__()
# creat model
self.encoder = nn.Sequential( # (nbatch, nchannel=1024 H=16, W=1)
nn.BatchNorm2d(dim_c),
@@ -170,21 +168,21 @@ class Discriminator(torch.nn.Module):
return:
(B x dim_x)
"""
logging.debug(f"[forward] input x shape = {x.shape}")
# logging.info(f"[D-forward] input x shape = {x.shape}")
# remember high dimenstion
c = c.reshape(-1, c.shape[-2], c.shape[-1]) # (BN, W, dim_c)
# preprocessing data
x = x.reshape(-1, x.shape[-1]) # (BN, 53)
c = c.reshape(-1, c.shape[-2], c.shape[-1]) # (BN, W, dim_c)
c = c.unsqueeze(dim=1).transpose(1,3) # (BN, 1, W, dim_x) --> (B, dim_x, W, 1)
feat = self.encoder(x) # (BN, 128)
logging.debug(f"[forward] encoder shape = {feat.shape}")
# logging.info(f"[D-forward] preprocessing c shape = {c.shape}")
feat = self.encoder(c) # (BN, 128)
# logging.info(f"[D-forward] encoder shape = {feat.shape}")
# add noise again
feat = torch.cat([feat, x], dim=1) # (BN, 128 + dim_x)
pred = self.decoder(feat) # (BN, 16)
logging.debug(f"[forward] decoder shape = {pred.shape}")
# logging.info(f"[D-forward] decoder shape = {pred.shape}")
return pred
+46 -35
View File
@@ -67,13 +67,6 @@ class Audio2MotionGANModel(LightningModule):
init_weights(self.netG, init_type='kaiming')
init_weights(self.netD, init_type='kaiming')
# init last layer
init_exp_weight = np.load(opt.path_init_expression_basis)
init_exp_weight = torch.from_numpy(init_exp_weight).float() #.to(self.device)
init_exp_weight = init_exp_weight[:, :50]
self.netG.decoder_mesh.weight.data = init_exp_weight
logging.info(f"init_exp_weight shape = {init_exp_weight.shape}")
# load mean
path_deca_mean = self.opt.path_mean_dict
@@ -100,11 +93,32 @@ class Audio2MotionGANModel(LightningModule):
# to ensure a proper reduction over the epoch
self.train_rec, self.train_vel = MeanMetric(), MeanMetric()
self.valid_rec, self.valid_vel = MeanMetric(), MeanMetric()
self.test_rec, self.test_vel = MeanMetric(), MeanMetric()
# for logging best so far validation accuracy
self.val_best = MinMetric()
self.train_best = MinMetric()
self.valid_best = MinMetric()
def load_pretrain_model(self, pretrain_path):
state_dict = torch.load(pretrain_path, map_location=self.device)["state_dict"]
# for netG
state_dict_netG = {k[5:]:v for k, v in state_dict.items() if (k[:4] == "netG" and k[5:] in self.netG.state_dict().keys())}
state_dict_netD = {k[5:]:v for k, v in state_dict.items() if (k[:4] == "netD" and k[5:] in self.netD.state_dict().keys())}
# print(f"\nself.netG state \n: {self.netG.state_dict().keys()}, \n\n state_dict_netG = {state_dict_netG.keys()}")
# print(f"\nself.netD state \n: {self.netD.state_dict().keys()}, \n\n state_dict_netD = {state_dict_netD.keys()}")
# 看看哪些参数没有初始化
diff_G = set(self.netG.state_dict().keys()).difference(set(state_dict_netG.keys())) # 在netG.keys()中,但不在state_dict_netG中
diff_D = set(self.netD.state_dict().keys()).difference(set(state_dict_netD.keys())) # 在netG.keys()中,但不在state_dict_netG中
print(f"\nself.netG, not init keys from pretrained model: \n {diff_G}")
print(f"\nself.netD, not init keys from pretrained model: \n {diff_D}")
# update
self.netG.load_state_dict(state_dict_netG, strict=False)
self.netD.load_state_dict(state_dict_netD, strict=False)
def _load_netF(self, opt_netF):
from src.mesh.FLAME import FLAME
@@ -190,16 +204,16 @@ class Audio2MotionGANModel(LightningModule):
# speech data
cond = None
raw_speech = batch["cond"].cpu().numpy() # (B, nsegments)
debug(f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
# logging.info(f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}")
# padding half frame length for bed and end
npad = int(0.5 * self.opt.sr * ( 1 / self.opt.fps) + 0.5)
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
debug(f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
# logging.info(f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}")
inputs = self.processor(list(raw_speech), sampling_rate=16000, return_tensors="pt")
cond = self.netW(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat
debug(f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False)
# logging.info(f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}")
# unfold speech data
cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_codit, 16)
@@ -210,7 +224,7 @@ class Audio2MotionGANModel(LightningModule):
# motion data
data = batch["data"].float() # (B, nsteps, nc_motion)
debug(f"data = {data.shape}, dtype={data.dtype}", verbose=False)
# logging.info(f"data = {data.shape}, dtype={data.dtype}")
data = data[:, 7:7+N, :] # (B, nseqs, nc_motion)
# self.vert, self.ldmk2d, self.ldmk3d = self.get_vertices(data)
@@ -220,10 +234,8 @@ class Audio2MotionGANModel(LightningModule):
idx_end = int((7 + N) * self.opt.sr / self.opt.fps + 0.5)
batch_info["raw_speech"] = raw_speech[:, idx_beg: idx_end] # (B, nsteps * sr / fps)
# debug(f"[set_input] vert = {self.vert.shape}, dtype={self.vert.dtype}, device={self.vert.device}", verbose=False)
debug(f"[set_input] cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False)
debug(f"[set_input] ldmk2d = {self.ldmk2d.shape}, dtype={self.ldmk2d.dtype}, device={self.ldmk2d.device}", verbose=False)
debug(f"[set_input] ldmk3d = {self.ldmk3d.shape}, dtype={self.ldmk3d.dtype}, device={self.ldmk3d.device}", verbose=False)
# logging.info(f"[set_input] data = {data.shape}, dtype={data.dtype}, device={data.device}")
# logging.info(f"[set_input] cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}")
return B, N, cond, data, batch_info
@@ -234,7 +246,7 @@ class Audio2MotionGANModel(LightningModule):
B, N, batch_c, batch_tgt, batch_info = self.set_input(batch)
# get noise input z
batch_z = torch.randn(B, N, self.opt.z_dim).type_as(batch_c) # (B, N, dim_latent)
batch_z = torch.randn(B, N, self.opt.dim_z).type_as(batch_c) # (B, N, dim_latent)
batch_pdt = self.netG(batch_z, batch_c) #(B, N, nc_motion)
@@ -316,12 +328,15 @@ class Audio2MotionGANModel(LightningModule):
if not (self.global_step % every_step == 0 and self.global_rank == 0):
return
batch_pdt = batch_pdt[0, ::3] # (N//3, nc_motion)
batch_tgt = batch_tgt[0, ::3] # (N//3, nc_motion)
batch_pdt = batch_pdt[:1, ::3] # (1, N//3, nc_motion)
batch_tgt = batch_tgt[:1, ::3] # (1, N//3, nc_motion)
# get mesh
batch_pdt_geo, *_ = self.get_vertices(batch_pdt[:4]) # 4 x 5023 x 3
batch_tgt_geo, *_ = self.get_vertices(batch_tgt[:4]) # 4 x 5023 x 3
batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # 1 x N//3 x 5023 x 3
batch_tgt_geo, *_ = self.get_vertices(batch_tgt) # 1 x N//3 x 5023 x 3
batch_pdt_geo = batch_pdt_geo[0, :4] # 4 x 5023 x 3
batch_tgt_geo = batch_tgt_geo[0, :4] # 4 x 5023 x 3
# render image
cam = torch.tensor([5, 0, 0], device=self.device).repeat(4, 1) # (4, 3)
@@ -340,7 +355,7 @@ class Audio2MotionGANModel(LightningModule):
render_pt = util.tensor_vis_landmarks(render_pt, ldmk3d_pt, gt_landmarks=ldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0))
render_gt = util.tensor_vis_landmarks(render_gt, ldmk3d_gt, isScale=True, color = (0, 255, 0))
print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
# logging.info(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
grid_pdt = torchvision.utils.make_grid(render_pt)
@@ -355,7 +370,7 @@ class Audio2MotionGANModel(LightningModule):
# get noise input z
batch_z = torch.randn(B, N, self.opt.z_dim).type_as(batch_c) # (B, N, dim_latent)
batch_z = torch.randn(B, N, self.opt.dim_z).type_as(batch_c) # (B, dim_latent)
batch_pdt = self.netG(batch_z, batch_c) #(B, N, nc_motion)
@@ -436,7 +451,6 @@ class Audio2MotionGANModel(LightningModule):
# reset metrics at the end of every epoch
self.train_rec.reset(), self.train_vel.reset()
self.valid_rec.reset(), self.valid_vel.reset()
self.test_rec.reset(), self.test_vel.reset()
def eval_losses(self, batch_pdt, batch_tgt):
@@ -534,6 +548,7 @@ class Audio2MotionGANModel(LightningModule):
"""
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)
@@ -594,11 +609,11 @@ class Audio2MotionGANModel(LightningModule):
# 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}")
# # logging.info(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}")
# # logging.info(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]
@@ -646,12 +661,12 @@ class Audio2MotionGANModel(LightningModule):
# cam
cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}")
# # logging.info(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}")
# # logging.info(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
if vis_landmarks:
# landmarks 3d
@@ -695,10 +710,6 @@ class Audio2MotionGANModel(LightningModule):
items.pop("v_num", None)
# logging.info(items)
# return items
# items["test"] = '{:.6f}'.format(items["loss"])
return items
items["loss"] = '{:0.4f}'.format(float(items["loss"]))
return items