beta add render

This commit is contained in:
liangsen committed 2022-05-14 23:20:55 +08:00
1 parent 83f99d9ec5
commit b4c197a8ac
30 files changed
+3210 -235

No files matched your search

@@ -0,0 +1,181 @@
import time
import logging
from pathlib import Path
import numpy as np
from skimage.io import imread
from torch.utils.data import Dataset
from scipy.signal import savgol_filter
class MotionRenderTrainDataset(Dataset):
"""
Motion dataset.
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
def __init__(
self,
path_data = "../data_train.npz", # opt.DATASET.root
fps = 50, # opt.DATASET.fps
sr = 16000, # opt.DATASET.sr
num_second_wind = 3, # eval(f"opt.DATASET.nwind_second_{phase}")
filter = "savgol",
):
super(MotionRenderTrainDataset, self).__init__()
logging.info(f"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.image_size = 512
self.filter = filter
self.nsteps_frame = num_second_wind * fps
self.nsteps_segmt = num_second_wind * sr
self.overlap = 0.2
self.annodb_accums = self.count_annotations()
logging.info(f'''num_pid={self.num_pid}, niters={self.__len__()}, nsteps_frame={self.nsteps_frame}, nsteps_segmt={self.nsteps_segmt} ''')
def __len__(self):
# return self.annodb_accums[-1]
return 20000
def count_annotations(self):
acc = 0
annodb_accums = np.zeros(self.num_pid + 1, dtype=int) # the first element set 0
for i, ikey in enumerate(self.annodb):
# logging.info(f"i = {i}, ikey={ikey}, nframe = {self.annodb[ikey]["nframe"]}")
acc += self.annodb[ikey]["nframe"] // (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
"""
np.random.seed(int(idx + time.time()))
vid = self.pids[idx % self.num_pid]
# random select idx
data = self.annodb[vid]
data_speech = data["data_speech"] # (nsegemts, )
nframe = data["nframe"] # nframe of this video
nsegmt = data_speech.shape[0] # nsegmt of correspoding audio
path_data = Path(data["path_data"]) # "xxx/xxx/Actor5/processing/4R3A0073"
path_coeff = path_data.joinpath("DECA_coeff") # DECA coeff of shape/exp/light
path_frame = path_data.joinpath("frames_crop_512") # cropped image 512x512
path_ldmks = path_data.joinpath("frames_crop_ldmks_512") # cropped landmarks within 512x512
path_parse = path_data.joinpath("frames_crop_parse_512") # cropped mask
# random select beg:end frame
beg_frame = np.random.randint(nframe - self.nsteps_frame - 10) + 5 # select from (5:-5)
end_frame = beg_frame + self.nsteps_frame
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + self.nsteps_segmt
# logging.info(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_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})"
# load image & landmark & mask
data_frame, data_ldmk, data_mask, data_coeff = [], [], [], []
for iframe in range(beg_frame, end_frame):
ipath_frame = path_frame.joinpath(f"frame-{iframe:06d}.jpg")
ipath_ldmks = path_ldmks.joinpath(f"frame-{iframe:06d}.txt")
ipath_parse = path_parse.joinpath(f"frame-{iframe:06d}.npy")
ipath_coeff = path_coeff.joinpath(f"frame-{iframe:06d}.json.npy")
idata_frame = imread(str(ipath_frame)) / 255 # (512, 512, 3), normalize to 0-1
idata_ldmk = np.loadtxt(ipath_ldmks)[:, :2] # (68, 2)
idata_mask = self.load_mask(ipath_parse) # (512, 512)
idata_coeff = self.load_coeff(ipath_coeff) # (256, )
# normalized kpt, why ?
idata_ldmk = idata_ldmk / self.image_size * 2 - 1
# add to list
data_frame.append(idata_frame.transpose(2,0,1)) # (3, 512, 512)
data_ldmk.append(idata_ldmk) # (68, 2)
data_mask.append(idata_mask) # (512, 512)
data_coeff.append(idata_coeff) # (236, )
# concate to numpy
data_frame = np.array(data_frame).astype(np.float32) # (nsteps_frame, 3, 512, 512)
data_ldmk = np.array(data_ldmk).astype(np.float32) # (nsteps_frame, 68, 2)
data_mask = np.array(data_mask).astype(np.float32) # (nsteps_frame, 512, 512)
data_coeff = np.array(data_coeff).astype(np.float32) # (nsteps_frame, 236)
# logging.info(f"data_frame = {data_frame.shape}, dtype={data_frame.dtype}")
# logging.info(f"data_ldmk = {data_ldmk.shape}, dtype={data_ldmk.dtype}")
# logging.info(f"data_mask = {data_mask.shape}, dtype={data_mask.dtype}")
# logging.info(f"data_coeff = {data_coeff.shape}, dtype={data_coeff.dtype}")
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.filter == "savgol":
data_coeff = savgol_filter(data_coeff, window_length=5, polyorder=3, axis=0, mode='nearest')
data_ldmk = savgol_filter(data_ldmk, window_length=5, polyorder=3, axis=0, mode='nearest')
# random augments: shuffle speed
result = {
"data_audio": data_speech, # (nsteps_frame, dim_speech)
"data_frame": data_frame, # (nsteps_frame, 3, 512, 512)
"data_mask": data_mask, # (nsteps_frame, 512, 512)
"data_ldmk": data_ldmk, # (nsteps_frame, 68, 2)
"data_coeff": data_coeff, # (nsteps_frame, 236)
"vid": vid,
"nframe": nframe,
"frame_interval": [beg_frame, end_frame],
}
return result
def load_coeff(self, path_coeff):
codedict = np.load(path_coeff, allow_pickle=True).item() # dict of {}
params = ['shape', 'tex', 'exp', 'pose', 'cam', 'light']
# dim of shape = 100, tex = 50, exp = 50, pose = 6, cam = 3, light = 27
coeff = []
for ikey in params:
coeff += list(codedict[ikey].reshape(-1))
# assert len(coeff) == 236, f"coeff len = {len(coeff)} should be 236 !"
return np.array(coeff)
def load_mask(self, path_parse):
parsing_anno = np.load(path_parse) # (512, 512)
mask = np.zeros_like(parsing_anno) # (512, 512)
atts = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'l_ear', 'r_ear', 'ear_r',
'nose', 'mouth', 'u_lip', 'l_lip', 'neck', 'neck_l', 'cloth', 'hair', 'hat']
atts_selected = ['skin', 'l_brow', 'r_brow', 'nose', 'u_lip', 'l_lip']
class_contains = np.unique(parsing_anno)
for iclass, iatt in enumerate(atts, 1):
if (iatt in atts_selected) and (iclass in class_contains):
index = np.where(parsing_anno == iclass)
mask[index[0], index[1]] = 1
return mask
+232
View File
@@ -0,0 +1,232 @@
import os
import torch
import numpy as np
from skimage.io import imread
from skimage.transform import estimate_transform, warp
from torch.utils.data import Dataset
class VGGFace2Dataset(Dataset):
def __init__(self, K, image_size, scale, trans_scale = 0, isTemporal=False, isEval=False, isSingle=False):
'''
K must be less than 6
'''
self.K = K
self.image_size = image_size
self.imagefolder = '/ps/scratch/face2d3d/train'
self.kptfolder = '/ps/scratch/face2d3d/train_annotated_torch7'
self.segfolder = '/ps/scratch/face2d3d/texture_in_the_wild_code/VGGFace2_seg/test_crop_size_400_batch'
# hq:
# datafile = '/ps/scratch/face2d3d/texture_in_the_wild_code/VGGFace2_cleaning_codes/ringnetpp_training_lists/second_cleaning/vggface2_bbx_size_bigger_than_400_train_list_max_normal_100_ring_5_1_serial.npy'
datafile = '/ps/scratch/face2d3d/texture_in_the_wild_code/VGGFace2_cleaning_codes/ringnetpp_training_lists/second_cleaning/vggface2_train_list_max_normal_100_ring_5_1_serial.npy'
if isEval:
datafile = '/ps/scratch/face2d3d/texture_in_the_wild_code/VGGFace2_cleaning_codes/ringnetpp_training_lists/second_cleaning/vggface2_val_list_max_normal_100_ring_5_1_serial.npy'
self.data_lines = np.load(datafile).astype('str')
self.isTemporal = isTemporal
self.scale = scale #[scale_min, scale_max]
self.trans_scale = trans_scale #[dx, dy]
self.isSingle = isSingle
if isSingle:
self.K = 1
def __len__(self):
return len(self.data_lines)
def __getitem__(self, idx):
images_list = [];
kpt_list = [];
mask_list = []
random_ind = np.random.permutation(5)[:self.K]
for i in random_ind:
name = self.data_lines[idx, i]
image_path = os.path.join(self.imagefolder, name + '.jpg')
seg_path = os.path.join(self.segfolder, name + '.npy')
kpt_path = os.path.join(self.kptfolder, name + '.npy')
image = imread(image_path)/255.
kpt = np.load(kpt_path)[:,:2]
mask = self.load_mask(seg_path, image.shape[0], image.shape[1])
### crop information
tform = self.crop(image, kpt)
## crop
cropped_image = warp(image, tform.inverse, output_shape=(self.image_size, self.image_size))
cropped_mask = warp(mask, tform.inverse, output_shape=(self.image_size, self.image_size))
cropped_kpt = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # np.linalg.inv(tform.params)
# normalized kpt
cropped_kpt[:,:2] = cropped_kpt[:,:2]/self.image_size * 2 - 1
images_list.append(cropped_image.transpose(2,0,1))
kpt_list.append(cropped_kpt)
mask_list.append(cropped_mask)
###
images_array = torch.from_numpy(np.array(images_list)).type(dtype = torch.float32) # (K, 224, 224, 3)
kpt_array = torch.from_numpy(np.array(kpt_list)).type(dtype = torch.float32) # (K, 68, 2)
mask_array = torch.from_numpy(np.array(mask_list)).type(dtype = torch.float32) # (K, 224, 224, 3)
if self.isSingle:
images_array = images_array.squeeze()
kpt_array = kpt_array.squeeze()
mask_array = mask_array.squeeze()
data_dict = {
'image': images_array,
'landmark': kpt_array,
'mask': mask_array
}
return data_dict
def crop(self, image, kpt):
left = np.min(kpt[:,0]); right = np.max(kpt[:,0]);
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1])
h, w, _ = image.shape
old_size = (right - left + bottom - top)/2
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top) / 2.0 ])#+ old_size*0.1])
# translate center
trans_scale = (np.random.rand(2)*2 -1) * self.trans_scale # 0
center = center + trans_scale*old_size # 0.5
scale = np.random.rand() * (self.scale[1] - self.scale[0]) + self.scale[0]
size = int(old_size*scale)
# crop image
src_pts = np.array([[center[0]-size/2, center[1]-size/2], [center[0] - size/2, center[1]+size/2], [center[0]+size/2, center[1]-size/2]])
DST_PTS = np.array([[0,0], [0,self.image_size - 1], [self.image_size - 1, 0]])
tform = estimate_transform('similarity', src_pts, DST_PTS)
# cropped_image = warp(image, tform.inverse, output_shape=(self.image_size, self.image_size))
# # change kpt accordingly
# cropped_kpt = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # np.linalg.inv(tform.params)
return tform
def load_mask(self, maskpath, h, w):
# print(maskpath)
if os.path.isfile(maskpath):
vis_parsing_anno = np.load(maskpath)
# atts = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'l_ear', 'r_ear', 'ear_r',
# 'nose', 'mouth', 'u_lip', 'l_lip', 'neck', 'neck_l', 'cloth', 'hair', 'hat']
mask = np.zeros_like(vis_parsing_anno)
# for i in range(1, 16):
mask[vis_parsing_anno>0.5] = 1.
else:
mask = np.ones((h, w))
return mask
class VGGFace2HQDataset(Dataset):
def __init__(self, K, image_size, scale, trans_scale = 0, isTemporal=False, isEval=False, isSingle=False):
'''
K must be less than 6
'''
self.K = K
self.image_size = image_size
self.imagefolder = '/ps/scratch/face2d3d/train'
self.kptfolder = '/ps/scratch/face2d3d/train_annotated_torch7'
self.segfolder = '/ps/scratch/face2d3d/texture_in_the_wild_code/VGGFace2_seg/test_crop_size_400_batch'
# hq:
# datafile = '/ps/scratch/face2d3d/texture_in_the_wild_code/VGGFace2_cleaning_codes/ringnetpp_training_lists/second_cleaning/vggface2_bbx_size_bigger_than_400_train_list_max_normal_100_ring_5_1_serial.npy'
datafile = '/ps/scratch/face2d3d/texture_in_the_wild_code/VGGFace2_cleaning_codes/ringnetpp_training_lists/second_cleaning/vggface2_bbx_size_bigger_than_400_train_list_max_normal_100_ring_5_1_serial.npy'
self.data_lines = np.load(datafile).astype('str')
self.isTemporal = isTemporal
self.scale = scale #[scale_min, scale_max]
self.trans_scale = trans_scale #[dx, dy]
self.isSingle = isSingle
if isSingle:
self.K = 1
def __len__(self):
return len(self.data_lines)
def __getitem__(self, idx):
images_list = []; kpt_list = []; mask_list = []
for i in range(self.K):
name = self.data_lines[idx, i]
image_path = os.path.join(self.imagefolder, name + '.jpg')
seg_path = os.path.join(self.segfolder, name + '.npy')
kpt_path = os.path.join(self.kptfolder, name + '.npy')
image = imread(image_path)/255.
kpt = np.load(kpt_path)[:,:2]
mask = self.load_mask(seg_path, image.shape[0], image.shape[1])
### crop information
tform = self.crop(image, kpt)
## crop
cropped_image = warp(image, tform.inverse, output_shape=(self.image_size, self.image_size))
cropped_mask = warp(mask, tform.inverse, output_shape=(self.image_size, self.image_size))
cropped_kpt = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # np.linalg.inv(tform.params)
# normalized kpt
cropped_kpt[:,:2] = cropped_kpt[:,:2]/self.image_size * 2 - 1
images_list.append(cropped_image.transpose(2,0,1))
kpt_list.append(cropped_kpt)
mask_list.append(cropped_mask)
###
images_array = torch.from_numpy(np.array(images_list)).type(dtype = torch.float32) #K,224,224,3
kpt_array = torch.from_numpy(np.array(kpt_list)).type(dtype = torch.float32) #K,224,224,3
mask_array = torch.from_numpy(np.array(mask_list)).type(dtype = torch.float32) #K,224,224,3
if self.isSingle:
images_array = images_array.squeeze()
kpt_array = kpt_array.squeeze()
mask_array = mask_array.squeeze()
data_dict = {
'image': images_array,
'landmark': kpt_array,
'mask': mask_array
}
return data_dict
def crop(self, image, kpt):
left = np.min(kpt[:,0]); right = np.max(kpt[:,0]);
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1])
h, w, _ = image.shape
old_size = (right - left + bottom - top)/2
center = np.array([right - (right - left) / 2.0, bottom - (bottom - top) / 2.0 ])#+ old_size*0.1])
# translate center
trans_scale = (np.random.rand(2)*2 -1) * self.trans_scale
center = center + trans_scale*old_size # 0.5
scale = np.random.rand() * (self.scale[1] - self.scale[0]) + self.scale[0]
size = int(old_size*scale)
# crop image
src_pts = np.array([[center[0]-size/2, center[1]-size/2], [center[0] - size/2, center[1]+size/2], [center[0]+size/2, center[1]-size/2]])
DST_PTS = np.array([[0,0], [0,self.image_size - 1], [self.image_size - 1, 0]])
tform = estimate_transform('similarity', src_pts, DST_PTS)
# cropped_image = warp(image, tform.inverse, output_shape=(self.image_size, self.image_size))
# # change kpt accordingly
# cropped_kpt = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # np.linalg.inv(tform.params)
return tform
def load_mask(self, maskpath, h, w):
# print(maskpath)
if os.path.isfile(maskpath):
vis_parsing_anno = np.load(maskpath)
# atts = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'l_ear', 'r_ear', 'ear_r',
# 'nose', 'mouth', 'u_lip', 'l_lip', 'neck', 'neck_l', 'cloth', 'hair', 'hat']
mask = np.zeros_like(vis_parsing_anno)
# for i in range(1, 16):
mask[vis_parsing_anno>0.5] = 1.
else:
mask = np.ones((h, w))
return mask
-1
View File
@@ -43,7 +43,6 @@ class MotionDataModule(LightningDataModule):
self.dataset_valid = dataset_valid
self.dataset_test = dataset_test
def train_dataloader(self):
return DataLoader(
dataset=self.dataset_train,
+25 -18
View File
@@ -128,13 +128,14 @@ def batch_kp_2d_l1_loss(real_2d_kp, predicted_2d_kp, weights=None):
kp_pred: N x K x 2
"""
if weights is not None:
real_2d_kp[:,:,2] = weights[None,:]*real_2d_kp[:,:,2]
real_2d_kp[..., 2] = weights[None, None, :] * real_2d_kp[...,2]
kp_gt = real_2d_kp.view(-1, 3)
kp_pred = predicted_2d_kp.contiguous().view(-1, 2)
vis = kp_gt[:, 2]
vis = kp_gt[..., 2]
k = torch.sum(vis) * 2.0 + 1e-8
dif_abs = torch.abs(kp_gt[:, :2] - kp_pred).sum(1)
dif_abs = torch.abs(kp_gt[..., :2] - kp_pred).sum(1)
return torch.matmul(dif_abs, vis) * 1.0 / k
@@ -142,9 +143,11 @@ def batch_kp_2d_l1_loss(real_2d_kp, predicted_2d_kp, weights=None):
def landmark_loss(predicted_landmarks, landmarks_gt, weight=1.):
# (predicted_theta, predicted_verts, predicted_landmarks) = ringnet_outputs[-1]
if torch.is_tensor(landmarks_gt) is not True:
real_2d = torch.cat(landmarks_gt).cuda()
real_2d = torch.cat(landmarks_gt).to(predicted_landmarks.device)
else:
real_2d = torch.cat([landmarks_gt, torch.ones((landmarks_gt.shape[0], 68, 1)).cuda()], dim=-1)
dims = landmarks_gt.shape
real_2d = torch.cat([landmarks_gt,
torch.ones(dims[:-2]+[68, 1]).to(landmarks_gt.device)], dim=-1) # (..., 68, 3)
# real_2d = torch.cat(landmarks_gt).cuda()
loss_lmk_2d = batch_kp_2d_l1_loss(real_2d, predicted_landmarks)
@@ -154,20 +157,22 @@ def landmark_loss(predicted_landmarks, landmarks_gt, weight=1.):
def eye_dis(landmarks):
# left eye: [38,42], [39,41] - 1
# right eye: [44,48], [45,47] -1
eye_up = landmarks[:,[37, 38, 43, 44], :]
eye_bottom = landmarks[:,[41, 40, 47, 46], :]
eye_up = landmarks[..., [37, 38, 43, 44], :]
eye_bottom = landmarks[..., [41, 40, 47, 46], :]
dis = torch.sqrt(((eye_up - eye_bottom)**2).sum(2)) #[bz, 4]
return dis
def eyed_loss(predicted_landmarks, landmarks_gt, weight=1.):
if torch.is_tensor(landmarks_gt) is not True:
real_2d = torch.cat(landmarks_gt).cuda()
real_2d = torch.cat(landmarks_gt).to(predicted_landmarks.device)
else:
real_2d = torch.cat([landmarks_gt, torch.ones((landmarks_gt.shape[0], 68, 1)).cuda()], dim=-1)
pred_eyed = eye_dis(predicted_landmarks[:,:,:2])
gt_eyed = eye_dis(real_2d[:,:,:2])
dims = landmarks_gt.shape
real_2d = torch.cat([landmarks_gt,
torch.ones(dims[:-2]+[68, 1]).to(landmarks_gt.device)], dim=-1)
pred_eyed = eye_dis(predicted_landmarks[..., :2])
gt_eyed = eye_dis(real_2d[..., :2])
loss = (pred_eyed - gt_eyed).abs().mean()
return loss
@@ -176,19 +181,21 @@ def eyed_loss(predicted_landmarks, landmarks_gt, weight=1.):
def lip_dis(landmarks):
# up inner lip: [62, 63, 64] - 1
# down innder lip: [68, 67, 66] -1
lip_up = landmarks[:,[61, 62, 63], :]
lip_down = landmarks[:,[67, 66, 65], :]
lip_up = landmarks[..., [61, 62, 63], :]
lip_down = landmarks[..., [67, 66, 65], :]
dis = torch.sqrt(((lip_up - lip_down)**2).sum(2)) #[bz, 4]
return dis
def lipd_loss(predicted_landmarks, landmarks_gt, weight=1.):
if torch.is_tensor(landmarks_gt) is not True:
real_2d = torch.cat(landmarks_gt).cuda()
real_2d = torch.cat(landmarks_gt).to(predicted_landmarks.device)
else:
real_2d = torch.cat([landmarks_gt, torch.ones((landmarks_gt.shape[0], 68, 1)).cuda()], dim=-1)
pred_lipd = lip_dis(predicted_landmarks[:,:,:2])
dims = landmarks_gt.shape
real_2d = torch.cat([landmarks_gt,
torch.ones(dims[:-2]+[68, 1]).to(landmarks_gt.device)], dim=-1)
pred_lipd = lip_dis(predicted_landmarks[...,:2])
gt_lipd = lip_dis(real_2d[:,:,:2])
loss = (pred_lipd - gt_lipd).abs().mean()
+41 -6
View File
@@ -215,18 +215,35 @@ class FLAME(nn.Module):
shape_params: N X number of shape parameters
expression_params: N X number of expression parameters
pose_params: N X number of pose parameters (6)
eye_pose_params: N x number of eye pose parameters(6)
template_vertices: N x 5023 x 3
return:d
vertices: N X V X 3
landmarks: N X number of landmarks X 3
"""
# remember high dimenstion
shape_dims = shape_params.shape
if len(shape_dims) > 2:
shape_params = shape_params.reshape(-1, shape_params.shape[-1])
expression_params = expression_params.reshape(-1, expression_params.shape[-1])
if pose_params is not None:
pose_params = pose_params.reshape(-1, pose_params.shape[-1])
if eye_pose_params is not None:
eye_pose_params = eye_pose_params.reshape(-1, eye_pose_params.shape[-1]) # (B x 6)
if template_vertices is not None:
template_vertices = template_vertices.reshape(-1, template_vertices.shape[-2], template_vertices.shape[-1]) # (B x 5023 x 3)
# get update batch size
batch_size = shape_params.shape[0]
if pose_params is None:
pose_params = self.eye_pose.expand(batch_size, -1) # (B x 6)
if eye_pose_params is None:
eye_pose_params = self.eye_pose.expand(batch_size, -1) # (B x 6)
if template_vertices is None:
template_vertices = self.v_template.unsqueeze(0).expand(batch_size, -1, -1) # (B x 5023 x 3)
# print(f"shape_params = {shape_params.shape}, expression_params={expression_params.shape}, pose_params={pose_params.shape}")
# print(f"batch_size = {batch_size}, self.neck_pose={self.neck_pose.shape}")
@@ -243,9 +260,7 @@ class FLAME(nn.Module):
eye_pose_params # (B x 6), eye pose
], dim=1)
if template_vertices is None:
template_vertices = self.v_template.unsqueeze(0).expand(batch_size, -1, -1) # (B x 5023 x 3)
vertices, _ = lbs(betas, pose, template_vertices,
self.shapedirs, self.posedirs,
self.J_regressor, self.parents,
@@ -269,6 +284,14 @@ class FLAME(nn.Module):
self.full_lmk_faces_idx.repeat(bz, 1),
self.full_lmk_bary_coords.repeat(bz, 1, 1))
# expand dimension
if len(shape_dims) > 2:
vertices = vertices.reshape(list(shape_dims[:-1]) + list(vertices.shape[1:]))
landmarks2d = landmarks2d.reshape(list(shape_dims[:-1]) + list(landmarks2d.shape[1:]))
landmarks3d = landmarks3d.reshape(list(shape_dims[:-1]) + list(landmarks3d.shape[1:]))
return vertices, landmarks2d, landmarks3d
class FLAMETex(nn.Module):
@@ -311,10 +334,22 @@ class FLAMETex(nn.Module):
def forward(self, texcode):
'''
texcode: [batchsize, n_tex]
texture: [bz, 3, 256, 256], range: 0-1
texture: [batchsize, 3, 512, 512], range: 0-1
##### texture: [batchsize, 3, 256, 256], range: 0-1
'''
# remember high dimenstion
shape_dims = texcode.shape
if len(shape_dims) > 2:
texcode = texcode.reshape(-1, texcode.shape[-1])
texture = self.texture_mean + (self.texture_basis*texcode[:,None,:]).sum(-1)
texture = texture.reshape(texcode.shape[0], 512, 512, 3).permute(0,3,1,2)
texture = F.interpolate(texture, [256, 256])
texture = texture[:,[2,1,0], :,:]
##### texture = F.interpolate(texture, [256, 256])
texture = texture[:, [2,1,0], :,:]
# expand dimension
if len(shape_dims) > 2:
texture = texture.reshape(list(shape_dims[:-1]) + list(texture.shape[1:]))
return texture
+20 -5
View File
@@ -182,8 +182,8 @@ class SRenderY(nn.Module):
self.uv_rasterizer = Pytorch3dRasterizer(uv_size)
verts, faces, aux = load_obj(obj_filename)
uvcoords = aux.verts_uvs[None, ...] # (N, V, 2)
uvfaces = faces.textures_idx[None, ...] # (N, F, 3)
uvcoords = aux.verts_uvs[None, ...] # (N, V, 2)
uvfaces = faces.textures_idx[None, ...] # (N, F, 3)
faces = faces.verts_idx[None,...]
elif rasterizer_type == 'standard':
@@ -236,6 +236,16 @@ class SRenderY(nn.Module):
light_type:
point or directional
'''
# remember high dimenstion
shape_dims = vertices.shape
if len(shape_dims) > 3:
vertices = vertices.reshape(-1, vertices.shape[-2], vertices.shape[-1]) # (..., V, 3)
transformed_vertices = transformed_vertices.reshape(-1, transformed_vertices.shape[-2], transformed_vertices.shape[-1]) # (..., V, 3)
albedos = albedos.reshape(-1, albedos.shape[-3], albedos.shape[-2], albedos.shape[-1]) # (..., 3, h, w)
lights = lights.reshape(-1, lights.shape[-2], lights.shape[-1]) # (..., nfeat1, nfeat2)
batch_size = vertices.shape[0]
## rasterizer near 0 far 100. move mesh so minz larger than 0
transformed_vertices[:,:,2] = transformed_vertices[:,:,2] + 10
@@ -283,17 +293,22 @@ class SRenderY(nn.Module):
shading_images = images.detach()*0.
outputs = {
'images': images*alpha_images,
'albedo_images': albedo_images*alpha_images,
'images': images * alpha_images,
'albedo_images': albedo_images * alpha_images,
'alpha_images': alpha_images,
'pos_mask': pos_mask,
'shading_images': shading_images,
'grid': grid,
'normals': normals,
'normal_images': normal_images*alpha_images,
'normal_images': normal_images * alpha_images,
'transformed_normals': transformed_normals,
}
# expand dimension
if len(shape_dims) > 3:
for i in outputs.keys():
outputs[i] = outputs[i].reshape(list(shape_dims[:-2]) + list(outputs[i].shape[1:]))
return outputs
def add_SHlight(self, normal_images, sh_coeff):
+12
View File
@@ -284,12 +284,24 @@ 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
+7 -8
View File
@@ -1,5 +1,4 @@
import torch
import torch.nn as nn
import logging
def init_weights(net, init_type='normal', init_gain=0.02):
@@ -18,22 +17,22 @@ def init_weights(net, init_type='normal', init_gain=0.02):
#print(classname, hasattr(m, 'weight'),)
if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):
if init_type == 'normal':
nn.init.normal_(m.weight.data, 0.0, init_gain)
torch.nn.init.normal_(m.weight.data, 0.0, init_gain)
elif init_type == 'xavier':
nn.init.xavier_normal_(m.weight.data, gain=init_gain)
torch.nn.init.xavier_normal_(m.weight.data, gain=init_gain)
elif init_type == 'kaiming':
nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
torch.nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
elif init_type == 'orthogonal':
nn.init.orthogonal_(m.weight.data, gain=init_gain)
torch.nn.init.orthogonal_(m.weight.data, gain=init_gain)
else:
raise NotImplementedError('initialization method [%s] is not implemented' % init_type)
if hasattr(m, 'bias') and m.bias is not None:
nn.init.constant_(m.bias.data, 0.0)
torch.nn.init.constant_(m.bias.data, 0.0)
elif classname.find('BatchNorm2d') != -1: # BatchNorm Layer's weight is not a matrix; only normal distribution applies.
nn.init.normal_(m.weight.data, 1.0, init_gain)
nn.init.constant_(m.bias.data, 0.0)
torch.nn.init.normal_(m.weight.data, 1.0, init_gain)
torch.nn.init.constant_(m.bias.data, 0.0)
logging.info('initialize network with %s' % init_type)
net.apply(init_func) # apply the initialization function <init_func>
-72
View File
@@ -1,72 +0,0 @@
import torch
import torch.nn as nn
import logging
from .encoders import ResnetEncoder, VOCAEncoder
from ..mesh.FLAME import FLAME, FLAMETex
class Audio2Coeff(nn.Module):
def __init__(self, opt, opt_FLAME):
super(Audio2Coeff, self).__init__()
self.opt = opt
self.dim_motion = opt.dim_motion # 53
self.dim_speech = opt.dim_speech # 29
self.dim_hidden = opt.dim_hidden # 256
# creat model
self.driven = VOCAEncoder(outsize=self.dim_motion)
self.flame = FLAME(opt_FLAME)
# setup render
def _setup_renderer(self, model_cfg):
set_rasterizer(self.cfg.rasterizer_type)
self.render = SRenderY(self.image_size, obj_filename=model_cfg.topology_path, uv_size=model_cfg.uv_size, rasterizer_type=self.cfg.rasterizer_type).to(self.device)
# face mask for rendering details
mask = imread(model_cfg.face_eye_mask_path).astype(np.float32)/255.; mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous()
self.uv_face_eye_mask = F.interpolate(mask, [model_cfg.uv_size, model_cfg.uv_size]).to(self.device)
mask = imread(model_cfg.face_mask_path).astype(np.float32)/255.; mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous()
self.uv_face_mask = F.interpolate(mask, [model_cfg.uv_size, model_cfg.uv_size]).to(self.device)
# displacement correction
fixed_dis = np.load(model_cfg.fixed_displacement_path)
self.fixed_uv_dis = torch.tensor(fixed_dis).float().to(self.device)
# mean texture
mean_texture = imread(model_cfg.mean_tex_path).astype(np.float32)/255.; mean_texture = torch.from_numpy(mean_texture.transpose(2,0,1))[None,:,:,:].contiguous()
self.mean_texture = F.interpolate(mean_texture, [model_cfg.uv_size, model_cfg.uv_size]).to(self.device)
# dense mesh template, for save detail mesh
self.dense_template = np.load(model_cfg.dense_template_path, allow_pickle=True, encoding='latin1').item()
def forward(self, x):
""" forward function
Args:
x: torch.Tensor, [nbatch x seqlen x nwind x dim_condit]
return:
pred: torch.Tensor, [nbatch x seqlen x dim_motion]
"""
(nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, 29)
logging.debug(f"[forward] input x shape = {x.shape}")
# preprocessing data
x = x.reshape(nbatch * nseqlen, 1, nwind, nfeat) # (B * nseq, 1, 16, 29)
x = torch.transpose(x, 1, 3) # (B * nseq, 29, 16, 1)
logging.debug(f"[forward] transpose x shape = {x.shape}")
feat = self.encoder(x) # (B * nseq, 50)
logging.debug(f"[forward] encoder shape = {feat.shape}")
pred = self.decoder(feat) # (B * nseq, dim_motion)
logging.debug(f"[forward] decoder shape = {pred.shape}")
pred = pred.reshape(nbatch, nseqlen, -1) # (B, nseq, dim_motion)
logging.debug(f"[forward] reshape shape = {pred.shape}")
return pred
+89
View File
@@ -0,0 +1,89 @@
import torch
import torch.nn as nn
import logging
class Audio2Motion(nn.Module):
def __init__(self, nc_motion, nc_condit):
super(Audio2Motion, self).__init__()
self.nc_motion = nc_motion # 53
self.nc_condit = nc_condit # 29
# creat model
self.encoder = nn.Sequential( # (nbatch, nchannel=29, H=16, W=1)
nn.BatchNorm2d(self.nc_condit),
# block 1
nn.Conv2d(self.nc_condit, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
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, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1
nn.LeakyReLU(0.02, True),
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
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
nn.LeakyReLU(0.02, True),
nn.Flatten(), # 64,
nn.Linear(in_features=128, out_features=2048), # 128,
nn.Tanh(),
nn.Linear(in_features=2048, out_features=128) # 50,
)
# output
self.decoder = nn.Sequential(
nn.Linear(in_features=128, out_features=self.nc_motion),
)
def forward(self, x):
""" forward function
Args:
x: torch.Tensor, [B x nwind x dim_condit]
return:
pred: torch.Tensor, [B x nc_motion]
"""
logging.debug(f"[forward] input x shape = {x.shape}")
# remember high dimenstion
shape_dims = x.shape
if len(shape_dims) > 3:
x = x.reshape(-1, x.shape[-2], x.shape[-1])
# preprocessing data
x = x.unsqueeze(dim=1).transpose(1,3) # (B, 1, W, nc_motion) --> (B, nc_motion, W, 1)
logging.debug(f"[forward] transpose x shape = {x.shape}")
feat = self.encoder(x) # (B, 50)
logging.debug(f"[forward] encoder shape = {feat.shape}")
pred = self.decoder(feat) # (B, nc_motion)
logging.debug(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}")
return pred
@@ -24,7 +24,7 @@ from src.mesh import util
from src.utils.animation import write_video, write_video_with_gt
class Audio2CoeffModel(LightningModule):
class Audio2RenderModel(LightningModule):
def __init__(
self,
@@ -61,23 +61,26 @@ class Audio2CoeffModel(LightningModule):
# init netG
init_weights(self.netG, 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}")
# # 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
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
# save mean shape
self.register_buffer("mean_shape", torch.from_numpy(self.mean_dict["shape"].reshape(1, 1, 100))) # (1,1,100)
# get template (with specific avator)
temp_verts, temp_ldmk2d, temp_ldmk3d = self.get_template_vertices() # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
temp_verts, temp_ldmk2d, temp_ldmk3d = self.get_template_vertices() # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
temp_verts_specific, temp_ldmk2d_specific, 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.register_buffer("temp_verts", temp_verts)
self.register_buffer("temp_verts_specific", temp_verts_specific)
@@ -86,8 +89,8 @@ class Audio2CoeffModel(LightningModule):
vertices_weight[:, :, flame_mouth_idx, :] = 10
self.register_buffer("vertices_weight", vertices_weight)
landmarks_weight = self._set_landmark68_weight()
self.register_buffer("landmarks_weight", landmarks_weight)
landmark_weight = self._set_landmark68_weight()
self.register_buffer("landmark_weight", landmark_weight)
# loss function
self.loss_func_wing = WingLoss(reduction="none") # return (B, )
@@ -166,14 +169,18 @@ class Audio2CoeffModel(LightningModule):
param.requires_grad = False
# face mask for rendering details
mask = imread(opt_netR.face_eye_mask_path).astype(np.float32)/255.
mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous()
uv_face_eye_mask = F.interpolate(mask, [opt_netR.uv_size, opt_netR.uv_size])
mask = imread(opt_netR.face_eye_mask_path).astype(np.float32)/255.
mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous() # (1, 1, 256, 256)
uv_face_eye_mask = F.interpolate(mask, [opt_netR.uv_size, opt_netR.uv_size]) # (1, 1, 512, 512)
# mask = torch.from_numpy(mask[:,:,0])[None, None,None,:,:].contiguous() # (1, 1, 1, 256, 256)
# uv_face_eye_mask = F.interpolate(mask, [1, opt_netR.uv_size, opt_netR.uv_size]) # (1, 1, 1, 512, 512)
self.register_buffer("uv_face_eye_mask", uv_face_eye_mask)
mask = imread(opt_netR.face_mask_path).astype(np.float32)/255.
mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous()
uv_face_mask = F.interpolate(mask, [opt_netR.uv_size, opt_netR.uv_size])
# mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous() # (1, 1, 256, 256)
# uv_face_mask = F.interpolate(mask, [opt_netR.uv_size, opt_netR.uv_size]) # (1, 1, 512, 512)
mask = torch.from_numpy(mask[:,:,0])[None, None,None,:,:].contiguous() # (1, 1, 1, 256, 256)
uv_face_mask = F.interpolate(mask, [1, opt_netR.uv_size, opt_netR.uv_size]) # (1, 1, 1, 512, 512)
self.register_buffer("uv_face_mask", uv_face_mask)
# # displacement correction
@@ -183,10 +190,14 @@ class Audio2CoeffModel(LightningModule):
# mean texture
mean_texture = imread(opt_netR.mean_tex_path).astype(np.float32)/255.
mean_texture = torch.from_numpy(mean_texture.transpose(2,0,1))[None,:,:,:].contiguous()
mean_texture = F.interpolate(mean_texture, [opt_netR.uv_size, opt_netR.uv_size])
mean_texture = torch.from_numpy(mean_texture.transpose(2,0,1))[None,None, :,:,:].contiguous() # (1, 1, 1, 256, 256)
mean_texture = F.interpolate(mean_texture, [1, opt_netR.uv_size, opt_netR.uv_size]) # (1, 1, 1, 512, 512)
self.register_buffer("mean_texture", mean_texture)
debug(f"uv_face_eye_mask = {uv_face_eye_mask.shape}, uv_face_mask={uv_face_mask.shape},mean_texture={mean_texture.shape}")
# # dense mesh template, for save detail mesh
# self.dense_template = np.load(opt_netR.dense_template_path, allow_pickle=True, encoding='latin1').item()
@@ -233,34 +244,9 @@ class Audio2CoeffModel(LightningModule):
@torch.no_grad()
def set_input(self, batch:Any):
# logging.info(f"\n[set_input] self.device = {self.device}")
# motion data
data = batch["data"].float() # (B, nsteps, nc_motion)
debug(f"data = {data.shape}, dtype={data.dtype}", verbose=False)
images = batch['image'] # [B, nsteps, 3, size, size] ==> [BxK, 3, size, size]
images = images.view(-1, images.shape[-3], images.shape[-2], images.shape[-1])
lmk = batch['landmark'] # [B, nsteps, 3, size, size] ==> [BxK, 3, size, size]
lmk = lmk.view(-1, lmk.shape[-2], lmk.shape[-1])
masks = batch['mask'] # [B, nsteps, 3, size, size] ==> [BxK, 3, size, size]
masks = masks.view(-1, images.shape[-2], images.shape[-1])
# batch information
batch_info = {
"vid": batch['vid'],
"nframe": batch['nframe'],
"interv": batch['frame_interval'],
"images": images,
"lmk": lmk,
"masks": masks
}
# speech data
cond = None
raw_speech = batch["cond"].cpu().numpy() # (B, nsegments)
# processing speech feature
raw_speech = batch["data_audio"].cpu().numpy() # (B, nsegments)
debug(f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
# padding half frame length for bed and end
@@ -269,103 +255,122 @@ class Audio2CoeffModel(LightningModule):
debug(f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
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)
audio_feat = self.netW(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat
debug(f"audio_feat = {audio_feat.shape}, dtype={audio_feat.dtype}, device={audio_feat.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)
audio_feat = audio_feat.unfold(dimension=1, size=16, step=1) # (B, N, nc_codit, 16)
audio_feat = audio_feat.permute(0, 1, 3, 2) # (B, N, 16, nc_condit)
B, N, W, nc_condit = audio_feat.size()
# 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)
# setup raw-speech
idx_segmt_beg = int(7 * self.opt.sr / self.opt.fps + 0.5)
idx_segmt_end = int((7 + N) * self.opt.sr / self.opt.fps + 0.5)
raw_speech = raw_speech[:, idx_segmt_beg: idx_segmt_end] # (B, nsteps * sr / fps)
# cut audio clips
idx_beg = int(7 * self.opt.sr / self.opt.fps + 0.5)
idx_end = int((7 + self.nsteps) * self.opt.sr / self.opt.fps + 0.5)
self.raw_speech = raw_speech[:, idx_beg: idx_end] # (B, nsteps * sr / fps)
# setup others data
data_coeff = batch["data_coeff"][:, 7:7+N] # (B, N, nc_coeff)
data_frame = batch['data_frame'][:, 7:7+N] # [B, N, 3, 512, 512]
data_mask = batch['data_mask'][:, 7:7+N] # [B, N, 512, 512]
data_ldmk = batch['data_ldmk'][:, 7:7+N] # [B, N, 68, 2]
debug(f"[set_input] vert = {self.vert.shape}, dtype={self.vert.dtype}, device={self.vert.device}", verbose=False)
debug(f"[set_input] cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.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)
# update batch information
batch["data_audio"] = audio_feat # (B, N, 16, nc_condit)
batch["data_frame"] = data_frame # [B, N, 3, 512, 512]
batch["data_mask"] = data_mask # [B, N, 512, 512]
batch["data_ldmk"] = data_ldmk # [B, N, 68, 2]
batch["data_coeff"] = data_coeff # (B, N, 236)
batch["raw_speech"] = raw_speech # (B, N * sr / fps)
return self.cond, self.vert, batch_info
debug(f"[set_input] audio_feat = {audio_feat.shape}, dtype={audio_feat.dtype}, device={audio_feat.device}", verbose=False)
debug(f"[set_input] data_frame = {data_frame.shape}, dtype={data_frame.dtype}, device={data_frame.device}", verbose=False)
debug(f"[set_input] data_mask = {data_mask.shape}, dtype={data_mask.dtype}, device={data_mask.device}", verbose=False)
debug(f"[set_input] data_ldmk = {data_ldmk.shape}, dtype={data_ldmk.dtype}, device={data_ldmk.device}", verbose=False)
debug(f"[set_input] data_coeff = {data_coeff.shape}, dtype={data_coeff.dtype}, device={data_coeff.device}", verbose=False)
debug(f"[set_input] raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
return B, N, batch
def forward(self, x:torch.Tensor):
return self.netG(x)
pass
def step(self, batch:Any, return_vis:bool=False):
def step(self, batch:Any):
batch_x, batch_tgt, batch_info = self.set_input(batch)
B, N = batch_x.size(0), batch_x.size(1) # get batch_size
B, N, batch_set = self.set_input(batch)
batch_x = batch_set["data_audio"] # (B, N, 16, nc_condit)
batch_pdt = self.netG(batch_x) # (B, N, nc_motion=53)
debug(f"batch_pdt = {batch_pdt.shape}")
# get exp + pos
batch_pdt = self.netG(batch_x) # B*N x dim_motion
# prepare codedict for render
codedict = {}
codedict["exp"] = batch_pdt['exp'] # from predict
codedict["pos"] = batch_pdt['pos'] # from predict
codedict["exp"] = batch_pdt[:, :, :50] # (B, N, 50), from predict
codedict["shape"] = self.mean_shape.expand(B, N, -1) # (B, N, 100), use mean shape, NOT GT
codedict["tex"] = batch_set['data_coeff'][:, :, 100:150] # (B, N, 50), from GT
codedict["cam"] = batch_set['data_coeff'][:, :, 206:209] # (B, N, 3), from GT
codedict["light"] = batch_set['data_coeff'][:, :, 209:236].reshape(B, N, 9, 3) # (B, N, 9, 3), from GT
codedict["pose"]= torch.cat([ # (B, N, 6), from GT & predict
batch_set['data_coeff'][:, :, 150:153], # head pose, from GT
batch_pdt[:, :, 50:53], # mouth pose, from predict result
], dim=2)
codedict["shape"] = batch_info['shape'] # from ** mean ** shape
codedict["tex"] = batch_info['tex'] # from predict
codedict["cam"] = batch_info['cam'] # from predict
codedict["pose"] = batch_info['pose'] # from predict
codedict["light"] = batch_info['light'] # from predict
#
# get geometry vertice
verts, landmarks2d, landmarks3d = self.netF(
verts, landmarks2d, landmarks3d = self.netF( # (B, N, 5023, 3), (B,N,68,3), (B,N,68,3)
shape_params=codedict['shape'], expression_params=codedict['exp'], pose_params=codedict['pose'])
debug(f"verts = {verts.shape},landmarks2d={landmarks2d.shape}, landmarks3d = {landmarks3d.shape}")
# get albedo texture
albedo = self.netT(codedict['tex'])
albedo = self.netT(codedict['tex']) # (B, N, 3, 512, 512)
debug(f"albedo = {albedo.shape}")
## projection with camera (2D landmarks, 3D landmarks, verts)
landmarks3d_world = landmarks3d.clone()
landmarks2d = util.batch_orth_proj(landmarks2d, codedict['cam'])[:,:,:2]
landmarks2d[:,:,1:] = -landmarks2d[:,:,1:]
landmarks2d = util.batch_orth_proj(landmarks2d, codedict['cam'])[..., :2]
landmarks2d[..., 1:] = -landmarks2d[..., 1:]
landmarks3d = util.batch_orth_proj(landmarks3d, codedict['cam'])
landmarks3d[:,:,1:] = -landmarks3d[:,:,1:]
landmarks3d[..., 1:] = -landmarks3d[..., 1:]
trans_verts = util.batch_orth_proj(verts, codedict['cam'])
trans_verts[:,:,1:] = -trans_verts[:,:,1:]
trans_verts[..., 1:] = -trans_verts[..., 1:]
# render to image
ops = self.netR(verts, trans_verts, albedo, codedict['light'])
## output
opdict = {
'images': batch_info['images'],
'lmk': batch_info['lmk'],
'albedo': albedo,
'verts': verts,
'trans_verts': trans_verts,
'landmarks2d': landmarks2d,
'landmarks3d': landmarks3d,
'landmarks3d_world': landmarks3d_world,
'grid': ops['grid'],
'rendered_images': ops['images'],
'alpha_images': ops['alpha_images'],
'normal_images': ops['normal_images']
'albedo': albedo, # (B, N, 3, 512, 512)
'verts': verts, # (B, N, 5023, 3)
'trans_verts': trans_verts, # (B, N, 5023, 3)
'landmarks2d': landmarks2d, # (B, N, 68, 2)
'landmarks3d': landmarks3d, # (B, N, 68, 3)
'landmarks3d_world': landmarks3d_world, # (B, N, 68, 3)
'grid': ops['grid'], # (B, N, 512, 512, 2)
'rendered_images': ops['images'], # (B, N, 3, 512, 512)
'alpha_images': ops['alpha_images'], # (B, N, 1, 512, 512)
'normal_images': ops['normal_images'] # (B, N, 3, 512, 512)
}
# get mask predicted_images
mask_face_eye = F.grid_sample(self.uv_face_eye_mask.expand(B,-1,-1,-1), opdict['grid'].detach(), align_corners=False)
debug(f"grid = {ops['grid'].shape},rendered_images={ops['images'].shape}, alpha_images={ops['alpha_images'].shape}, normal_images={ops['normal_images'].shape}")
# get mask predicted_images # uv_face_eye_mask > (1, 1, 1, 512, 512)
opdict['grid'] = opdict['grid'].reshape(B*N, 512, 512, 2)
mask_face_eye = F.grid_sample(self.uv_face_eye_mask.expand(B*N, -1,-1,-1), opdict['grid'].detach(), align_corners=False)
mask_face_eye = mask_face_eye.reshape(B, N, mask_face_eye.shape[-3], mask_face_eye.shape[-2], mask_face_eye.shape[-1])
predicted_images = opdict['rendered_images'] * mask_face_eye * opdict['alpha_images']
opdict['predicted_images'] = predicted_images
debug(f"mask_face_eye = {mask_face_eye.shape}, predicted_images={predicted_images.shape}")
# eval loss
loss, loss_dict = self.eval_losses(batch_pdt, batch_tgt)
return loss, loss_dict, batch_pdt, batch_tgt, batch_info
loss, loss_dict = self.eval_losses(batch_set, opdict, mask_face_eye, batch_pdt)
return loss, loss_dict
def training_step(self, batch, batch_idx):
@@ -439,45 +444,54 @@ class Audio2CoeffModel(LightningModule):
self.test_rec.reset(), self.test_vel.reset()
def eval_loss(self, lmk, mask_face_eye, images, predicted_images, opdict, codedict):
def eval_losses(self, batch_set, opdict, mask_face_eye, batch_pdt):
loss = 0
loss_dict = {}
## base shape
predicted_landmarks = opdict['landmarks2d']
tgt_ldmk = batch_set["data_ldmk"] # [B, N, 68, 2], GT 2D landmarks
pdt_ldmk = opdict['landmarks2d'] # [B, N, 68, 2], PT 2D lanmdarks
# landmarks loss
loss_lmk = lossfunc.landmark_loss(predicted_landmarks, lmk, self.landmak_weight)
loss_lmk = lossfunc.landmark_loss(pdt_ldmk, tgt_ldmk, self.landmark_weight)
loss_dict['landmark'] = loss_lmk.detach()
if self.opt_loss.lmk > 0.0:
loss += loss_lmk * self.opt_loss.lmk
if self.opt_loss.lambda_lmk > 0.0:
loss += loss_lmk * self.opt_loss.lambda_lmk
# eye closure loss
loss_eye = lossfunc.eyed_loss(predicted_landmarks, lmk)
loss_eye = lossfunc.eyed_loss(pdt_ldmk, tgt_ldmk)
loss_dict['eye_distance'] = loss_eye.detach()
if self.opt_loss.eyed > 0.0:
loss += loss_eye * self.opt_loss.eyed
if self.opt_loss.lambda_eyed > 0.0:
loss += loss_eye * self.opt_loss.lambda_eyed
# lip closure loss
loss_lip = lossfunc.lipd_loss(predicted_landmarks, lmk)
loss_lip = lossfunc.lipd_loss(pdt_ldmk, tgt_ldmk)
loss_dict['lip_distance'] = loss_lip.detach()
if self.opt_loss.lipd > 0.0:
loss += loss_lip * self.opt_loss.lipd
if self.opt_loss.lambda_lipd > 0.0:
loss += loss_lip * self.opt_loss.lambda_lipd
# photometric loss
masks = masks[:,None,:,:] if self.opt_loss.useSeg else (mask_face_eye * opdict['alpha_images'])
loss_pho = masks * (predicted_images - images).abs().mean()
tgt_image = batch_set["data_frame"] # [B, N, 3, 512, 512]
pdt_image = opdict['predicted_images'] # [B, N, 3, 512, 512]
tgt_mask = batch_set["data_mask"] # [B, N, 512, 512]
if self.opt_loss.useSeg:
tgt_mask = tgt_mask[:,:,None,:,:] # [B, N, 1, 512, 512]
else:
tgt_mask = (mask_face_eye * opdict['alpha_images'])
loss_pho = tgt_mask * (pdt_image - tgt_image).abs().mean()
loss_dict['photometric_texture'] = loss_pho.detach()
if self.opt_loss.photo > 0.0:
loss += loss_pho * self.opt_loss.photo
if self.opt_loss.lambda_photo > 0.0:
loss += loss_pho * self.opt_loss.lambda_photo
# expression regularization
loss_reg = torch.sum(codedict['exp']**2)/2
loss_reg = torch.sum(batch_pdt**2)/2
loss_dict['expression_reg'] = loss_reg.detach()
if self.opt_loss.reg > 0.0 :
if self.opt_loss.lambda_reg > 0.0 :
# import ipdb; ipdb.set_trace()
loss += loss_reg * self.opt_loss.reg
loss += loss_reg * self.opt_loss.lambda_reg
#########################################################
@@ -486,8 +500,7 @@ class Audio2CoeffModel(LightningModule):
return loss, loss_dict
def eval_losses(self, batch_pdt_geo, batch_tgt_geo):
def eval_losses2(self, batch_pdt_geo, batch_tgt_geo):
""" Computes the loss function.
pramas:
batch_tgt_geo, (nbatch, seqlen, num_vertices, 3)
@@ -633,7 +646,7 @@ class Audio2CoeffModel(LightningModule):
@torch.no_grad()
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_pdt_pos, [B x N x nc_motion]
# batch_speech, [B x N*sr/fps ]
B, N, *_ = batch_pdt_geo.shape
+1 -1
View File
@@ -1,5 +1,5 @@
FLAG_DEBUG = False
FLAG_DEBUG = True
def debug(msg="", verbose=False):
if FLAG_DEBUG or verbose: