update actor5 & actor6 data processing code

This commit is contained in:
liangsen committed 2022-05-23 22:11:29 +08:00
1 parent 2095b48c56
commit 922a98e36b
29 files changed
+3689 -89

No files matched your search

+6 -4
View File
@@ -29,20 +29,22 @@ class Logger(logging.Logger):
def __init__(self, path_output, path_config=None, postfix=None, level=logging.NOTSET ): def __init__(self, path_output, path_config=None, postfix=None, level=logging.NOTSET ):
logging.Logger.__init__(self, '', level) logging.Logger.__init__(self, '', level)
if postfix is None: # logger filename suffix
postfix = f"{datetime.datetime.now().strftime('%Y%m%d-%HH%MM%SS')}" suffix = f"{datetime.datetime.now().strftime('%Y%m%d-%HH%MM%SS')}"
if postfix is not None:
suffix += str("-" + postfix)
# make dir & set filename # make dir & set filename
if path_config is not None: if path_config is not None:
basename = path_config.name.split(".")[0] basename = path_config.name.split(".")[0]
self.path_output = Path(path_output).joinpath(basename, postfix) self.path_output = Path(path_output).joinpath(basename, suffix)
self.path_output.mkdir(parents=True, exist_ok=True) self.path_output.mkdir(parents=True, exist_ok=True)
filename = self.path_output.joinpath(f"logger.log") filename = self.path_output.joinpath(f"logger.log")
shutil.copyfile(src=path_config, dst=self.path_output.joinpath(path_config.name)) shutil.copyfile(src=path_config, dst=self.path_output.joinpath(path_config.name))
else: else:
self.path_output = Path(path_output) self.path_output = Path(path_output)
self.path_output.mkdir(parents=True, exist_ok=True) self.path_output.mkdir(parents=True, exist_ok=True)
filename = self.path_output.joinpath(postfix + ".log") filename = self.path_output.joinpath(suffix + ".log")
# add file hander # add file hander
fHander = logging.FileHandler(filename) fHander = logging.FileHandler(filename)
@@ -21,7 +21,7 @@ specifict_folder: Actor5-raw-3h
trainer: trainer:
gpus: [1, 4, 8] gpus: [0, 1, 2, 4, 5, 7]
min_epochs: 100 min_epochs: 100
max_epochs: 300 max_epochs: 300
@@ -44,8 +44,9 @@ model:
nc_condit: 1024 nc_condit: 1024
dataset: dataset:
batch_size_train: 128 batch_size_train: 1
batch_size_test: 32 batch_size_test: 32
dataset_train: dataset_train:
@@ -9,7 +9,6 @@ defaults:
- override /logger: tensorboard.yaml - override /logger: tensorboard.yaml
- override /trainer: ddp.yaml - override /trainer: ddp.yaml
# all parameters below will be merged with parameters from default configurations set above # all parameters below will be merged with parameters from default configurations set above
# this allows you to overwrite only specified parameters # this allows you to overwrite only specified parameters
+93
View File
@@ -0,0 +1,93 @@
import numpy as np
from pathlib2 import Path
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
def bbox2point(left, right, top, bottom, type='bbox'):
''' bbox from detector and landmarks are different
'''
if type=='kpt68':
old_size = (right - left + bottom - top) / 2 * 1.1
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top ) / 2.0 ])
elif type=='bbox':
old_size = (right - left + bottom - top)/2
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top ) / 2.0 + old_size*0.12])
else:
raise NotImplementedError
return old_size, center
if __name__ == "__main__":
actor = "Actor5"
sub_folder = "smile" # processing, processing2
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
logger = Logger(f"./data/{actor}", postfix=f"max-bbox-{sub_folder}")
path_mean_bbox = Path(f"./data/{actor}/max_bbox_{sub_folder}.npy")
vpath_videos = sorted(path_data.glob("*"), reverse=True)
logger.info(f"Have {len(vpath_videos)} dir files")
# IDs = ["2-23min"]
mean_bbox = []
for i, ipath_item in enumerate(vpath_videos):
iname = ipath_item.stem
logger.info(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if iname not in IDs: continue
ipath_infor = ipath_item.joinpath("video/info.json")
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
ipath_frame = ipath_item.joinpath("frames")
ipath_ldmks.mkdir(parents=True, exist_ok=True)
# check
vpath_ldmks = list(ipath_ldmks.glob("*.txt"))
kmean_bbox = []
for k, kpath_ldmk in enumerate(vpath_ldmks):
# if k%1000 == 0:
# logger.info(f"batching {k}/{len(vpath_ldmks)} ... ")
kpt = np.loadtxt(kpath_ldmk) # (68, 2)
if kpt.shape[0] > 68:
kpt = kpt[:68, :]
logger.info(f"ERROR: > use first 68-kpts, kpt = {kpt.shape} ipath_ldmk={kpath_ldmk}")
left = np.min(kpt[:,0]); right = np.max(kpt[:,0])
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1])
kmean_bbox.append([left, right, top, bottom])
if len(vpath_ldmks) > 0:
kmean_bbox = np.array(kmean_bbox)
# kmean_bbox = kmean_bbox.max(axis=0)
left, right = np.min(kmean_bbox[:, 0]), np.max(kmean_bbox[:, 1])
top, bottom = np.min(kmean_bbox[:, 2]), np.max(kmean_bbox[:, 3])
mean_bbox.append([left, right, top, bottom])
logger.info(f"\t max bbox ={[left, right, top, bottom]}")
# get toatl mean bbox
mean_bbox = np.array(mean_bbox)
# mean_bbox = mean_bbox.max(axis=0).astype(np.int32)
left, right = np.min(mean_bbox[:, 0]), np.max(mean_bbox[:, 1])
top, bottom = np.min(mean_bbox[:, 2]), np.max(mean_bbox[:, 3])
mean_bbox = [left, right, top, bottom]
logger.info(f"\ntotal max bbox ={mean_bbox}, ")
logger.info(f"wsize = {right - left}, hsize = {bottom - top} ")
# save mean
np.save(path_mean_bbox, mean_bbox)
# break
@@ -0,0 +1,212 @@
import cv2
from cv2 import norm
import numpy as np
from pathlib2 import Path
from skimage.transform import estimate_transform, warp
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
def bbox2point(left, right, top, bottom, type='bbox'):
''' bbox from detector and landmarks are different
'''
if type=='kpt68':
old_size = (right - left + bottom - top) / 2 * 1.1
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top ) / 2.0 ])
elif type=='bbox':
old_size = (right - left + bottom - top)/2
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top ) / 2.0 + old_size*0.12])
else:
raise NotImplementedError
return old_size, center
def processing_one_folder(ipath_frame, ipath_ldmks, ipath_fcrop, ipath_tfrom, ipath_lcrop,
suffix="jpg", crop_size=512, scale=1.25, roation_image=False, use_same_bbox=False, path_same_bbox = None):
# get images
vpath_image = sorted(ipath_frame.glob(f"*.{suffix}"), key=lambda x: int(x.stem.split("-")[-1]), reverse=False)
logger.info(f'--> total have {len(vpath_image)} images, top: \n{vpath_image[:3]}')
# set prev_ldmk
prev_ldmk = None
if use_same_bbox:
same_bbox = np.load(path_same_bbox).reshape(-1) # (4,) [left, right, top, bottom]
logger.info(f"same_bbox = {same_bbox}")
# for iteration
for j, jpath_frame in enumerate(vpath_image):
image_name = jpath_frame.stem # (frame-0000)
if j%100 == 0:
logger.info(f"load jpath_frame --> {jpath_frame}")
# if j < 19300: continue
ipath_ldmk = ipath_ldmks.joinpath(image_name + ".txt")
if not ipath_ldmk.exists():
raise Exception(f"ipath_ldmk not exists --> {ipath_ldmk}")
kpath_fcrop = ipath_fcrop.joinpath(image_name + ".jpg")
kpath_tfrom = ipath_tfrom.joinpath(image_name + ".npy")
kpath_lcrop = ipath_lcrop.joinpath(image_name + ".txt")
###########################
# # check exists
# if kpath_fcrop.exists() and kpath_tfrom.exists() and kpath_lcrop.exists():
# # logger.info(f"kpath_fcrop, kpath_tfrom, kpath_lcrop, have existing! ---> {kpath_fcrop} ")
# print(f"kpath_fcrop, kpath_tfrom, kpath_lcrop, have existing! ---> {kpath_fcrop} ")
# continue
###########################
# load orignal image & landmarks
image = cv2.imread(str(jpath_frame)) # (H, W, 3), dtype=uint8
kpt = np.loadtxt(ipath_ldmk) # (68, 2)
if kpt.shape[0] > 68:
logger.info(f"ERROR: > use first 68-kpts, cropped_ldmk = {kpt.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}")
n_kpt = kpt.shape[0] // 68
max_cos = 0
kpt_selected = None
for idx in range(n_kpt):
cur_kpt = kpt[idx*68:(idx+1)*68, :]
cur_cos = np.dot(prev_ldmk, cur_kpt.reshape(-1)) / (np.linalg.norm(prev_ldmk) * np.linalg.norm(cur_kpt.reshape(-1)))
if cur_cos > max_cos:
max_cos = cur_cos
kpt_selected = cur_kpt
# get kpt, which match the prev_landmarks
logger.info(f"\t SELETCT: max_cos = {max_cos} --> {kpt_selected.reshape(-1)[::10]}")
kpt = kpt_selected
# record prev
prev_ldmk = kpt.copy().reshape(-1) # record prev_ldmk
# reverse H&W
if roation_image:
image = image.transpose(1,0,2) # (H, W, 3)
kpt = kpt[:, ::-1] # (68, 2)
if use_same_bbox:
left, right = same_bbox[0], same_bbox[1]
top, bottom = same_bbox[2], same_bbox[3]
else:
left = np.min(kpt[:,0]); right = np.max(kpt[:,0])
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1])
old_size, center = bbox2point(left, right, top, bottom, type='kpt68')
# crop transform
size = int(old_size * scale)
src_pts = np.array([[center[0] - size/2, center[1] - size/2], # (left, top)
[center[0] - size/2, center[1] + size/2], # (left, bottom)
[center[0] + size/2, center[1] - size/2]]) # (right, top)
DST_PTS = np.array([[0, 0], # (left-top-corner)
[0, crop_size - 1], # (left-botton corner)
[crop_size - 1, 0]]) # (right-top corner)
# tform_params dytpe = float64, shape = (3, 3)
tform = estimate_transform('similarity', src_pts, DST_PTS)
# image = image/255.
# (crop_size, crop_size, 3) ,float64
cropped_imag = warp(image, tform.inverse, output_shape=(crop_size, crop_size)) # scale to (0~1)
cropped_ldmk = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # (68,3)
cropped_ldmk = cropped_ldmk[:, :2]
# logger.info(f"image dytpe = {image.dtype}, shape = {image.shape} ")
# logger.info(f"cropped_imag dytpe = {cropped_imag.dtype}, shape = {cropped_imag.shape} ")
# logger.info(f"tform_params dytpe = {tform.params.dtype}, shape = {tform.params.shape} ")
# logger.info(f"cropped_ldmk dytpe = {cropped_ldmk.dtype}, shape = {cropped_ldmk.shape}, max={cropped_ldmk.max()}, min={cropped_ldmk.min()} ")
np.save(kpath_tfrom, tform.params)
np.savetxt(kpath_lcrop, cropped_ldmk, fmt=" %3d")
cropped_imag = (255*cropped_imag).astype(np.uint8)
cv2.imwrite(str(kpath_fcrop), cropped_imag)
if __name__ == "__main__":
actor = "Actor5"
sub_folder = "processing" # smile, processing, processing2
# logger
logger = Logger(f"./data/{actor}", postfix=f"crop-transform-{sub_folder}")
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
path_same_bbox = f"data/{actor}/max_bbox_{sub_folder}.npy"
#
vpath_videos = sorted(path_data.glob("*"), reverse=False)
logger.info(f"Have {len(vpath_videos)} dir files")
# whole body need roation frame
roation_image = True if sub_folder == "body" else False
logger.info(f"roation_image = {roation_image}")
# for each word
for i, ipath_item in enumerate(vpath_videos):
iname = ipath_item.stem
logger.info(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if iname not in ["4R3A0069"]: continue
if iname not in ["4R3A0068", "4R3A0066", "4R3A0065"]: continue
# if iname not in IDs: continue
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
ipath_frame = ipath_item.joinpath("frames")
ipath_fcrop = ipath_item.joinpath("frames_crop_512")
ipath_tfrom = ipath_item.joinpath("frames_crop_tform_512")
ipath_lcrop = ipath_item.joinpath("frames_crop_ldmks_512")
ipath_fcrop.mkdir(parents=True, exist_ok=True)
ipath_tfrom.mkdir(parents=True, exist_ok=True)
ipath_lcrop.mkdir(parents=True, exist_ok=True)
num_frame = len(list(ipath_frame.glob("*.jpg")))
# check have done
# num_fcrop = len(list(ipath_fcrop.glob("*.jpg")))
# if num_frame == num_fcrop:
# logger.info(f"\n Skip: have already done!")
# continue
# check landmarks have exists
num_ldmks = len(list(ipath_ldmks.glob("*.txt")))
if num_frame != num_ldmks:
logger.info(f"\n ERROR & Skip: ldmaks = {num_ldmks} != nframes {num_frame}!")
continue
# processing one folder
processing_one_folder(
ipath_frame, ipath_ldmks, ipath_fcrop, ipath_tfrom, ipath_lcrop,
suffix="jpg", crop_size=512, scale=1.5,
roation_image=roation_image, use_same_bbox=True, path_same_bbox = path_same_bbox
)
+63 -21
View File
@@ -1,4 +1,5 @@
import cv2 import cv2
from cv2 import norm
import numpy as np import numpy as np
from pathlib2 import Path from pathlib2 import Path
from skimage.transform import estimate_transform, warp from skimage.transform import estimate_transform, warp
@@ -6,7 +7,7 @@ from skimage.transform import estimate_transform, warp
from torch.utils.data import Dataset, DataLoader from torch.utils.data import Dataset, DataLoader
class ImagesDataset(Dataset): class ImagesDataset(Dataset):
def __init__(self, path_frames, path_landmk, suffix="jpg", crop_size=224, scale=1.25, roation_image=False): def __init__(self, path_frames, path_landmk, suffix="jpg", crop_size=512, scale=1.25, roation_image=False, use_same_bbox=False, path_same_bbox = None):
''' '''
path_frames: folder, vpath_image, image path, video path path_frames: folder, vpath_image, image path, video path
''' '''
@@ -19,6 +20,14 @@ class ImagesDataset(Dataset):
self.scale = scale # 1.25 self.scale = scale # 1.25
self.crop_size = crop_size # 224 self.crop_size = crop_size # 224
self.roation_image =roation_image self.roation_image =roation_image
self.use_same_bbox = use_same_bbox
self.prev_ldmk = None
if self.use_same_bbox:
self.same_bbox = np.load(path_same_bbox).reshape(-1) # (4,) [left, right, top, bottom]
print(f"same_bbox = {self.same_bbox}")
def bbox2point(self, left, right, top, bottom, type='bbox'): def bbox2point(self, left, right, top, bottom, type='bbox'):
''' bbox from detector and landmarks are different ''' bbox from detector and landmarks are different
@@ -36,10 +45,10 @@ class ImagesDataset(Dataset):
return old_size, center return old_size, center
def __len__(self): def __len__(self):
return len(self.vpath_image) return len(self.vpath_image)
def __getitem__(self, index): def __getitem__(self, index):
ipath_frame = self.vpath_image[index] ipath_frame = self.vpath_image[index]
image_name = ipath_frame.stem # (frame-0000) image_name = ipath_frame.stem # (frame-0000)
@@ -51,16 +60,40 @@ class ImagesDataset(Dataset):
raise Exception(f"ipath_ldmk not exists --> {ipath_ldmk}") raise Exception(f"ipath_ldmk not exists --> {ipath_ldmk}")
# load orignal image & landmarks # load orignal image & landmarks
image = cv2.imread(str(ipath_frame)) # (H, W, 3), dtype=uint8 image = cv2.imread(str(ipath_frame)) # (H, W, 3), dtype=uint8
kpt = np.loadtxt(ipath_ldmk) # (68, 2) kpt = np.loadtxt(ipath_ldmk) # (68, 2)
kpt_selected = None
if kpt.shape[0] > 68:
# raise Exception(f"cropped_ldmk = {cropped_ldmk.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}")
n_kpt = kpt.shape[0] // 68
max_cos = 0
for idx in range(n_kpt):
cur_kpt = kpt[idx*68:(idx+1)*68, :]
cur_cos = np.dot(self.prev_ldmk, cur_kpt.reshape(-1)) / (np.linalg.norm(self.prev_ldmk) * np.linalg.norm(cur_kpt.reshape(-1)))
if cur_cos > max_cos:
kpt_selected = cur_kpt
# get kpt, which match the prev_landmarks
kpt = kpt_selected
print(f"ERROR: > use first 68-kpts, cropped_ldmk = {kpt.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}")
# record prev_ldmk
self.prev_ldmk = kpt.copy().reshpae(-1)
# reverse H&W # reverse H&W
if self.roation_image: if self.roation_image:
image = image.transpose(1,0,2) # (H, W, 3) image = image.transpose(1,0,2) # (H, W, 3)
kpt = kpt[:, ::-1] # (68, 2) kpt = kpt[:, ::-1] # (68, 2)
left = np.min(kpt[:,0]); right = np.max(kpt[:,0]) if self.use_same_bbox:
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1]) left, right = self.same_bbox[0], self.same_bbox[1]
top, bottom = self.same_bbox[2], self.same_bbox[3]
else:
left = np.min(kpt[:,0]); right = np.max(kpt[:,0])
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1])
old_size, center = self.bbox2point(left, right, top, bottom, type='kpt68') old_size, center = self.bbox2point(left, right, top, bottom, type='kpt68')
# crop transform # crop transform
@@ -78,17 +111,12 @@ class ImagesDataset(Dataset):
# image = image/255. # image = image/255.
# (crop_size, crop_size, 3) ,float64 # (crop_size, crop_size, 3) ,float64
cropped_imag = warp(image, tform.inverse, output_shape=(self.crop_size, self.crop_size)) # scale to (0~1) cropped_imag = warp(image, tform.inverse, output_shape=(self.crop_size, self.crop_size)) # scale to (0~1)
cropped_ldmk = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # (68,3) cropped_ldmk = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # (68,3)
cropped_ldmk = cropped_ldmk[:, :2] cropped_ldmk = cropped_ldmk[:, :2]
# cropped_ldmk[:,:2] = cropped_ldmk[:,:2] / self.crop_size * 2 - 1 # cropped_ldmk[:,:2] = cropped_ldmk[:,:2] / self.crop_size * 2 - 1
if cropped_ldmk.shape[0] > 68:
# raise Exception(f"cropped_ldmk = {cropped_ldmk.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}")
cropped_ldmk = cropped_ldmk[:68, :]
print(f"ERROR: > use first 68-kpts, cropped_ldmk = {cropped_ldmk.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}")
# cropped_mask = warp(mask, tform.inverse, output_shape=(self.crop_size, self.crop_size)) # scale to (0~1) # cropped_mask = warp(mask, tform.inverse, output_shape=(self.crop_size, self.crop_size)) # scale to (0~1)
# print(f"image dytpe = {image.dtype}, shape = {image.shape} ") # print(f"image dytpe = {image.dtype}, shape = {image.shape} ")
@@ -107,13 +135,17 @@ class ImagesDataset(Dataset):
if __name__ == "__main__": if __name__ == "__main__":
sub_folder = "processing" # processing, body, smile sub_folder = "processing2" # processing, processing2
path_data = Path(f"/ssdata1/lsen/DATA/Actor5/{sub_folder}") path_data = Path(f"/ssdata1/lsen/DATA/Actor6/{sub_folder}")
vpath_videos = sorted(path_data.glob("*"), reverse=False) path_same_bbox = f"data/Actor6/max_bbox_{sub_folder}.npy"
vpath_videos = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(vpath_videos)} dir files") print(f"Have {len(vpath_videos)} dir files")
# whole body need roation frame # whole body need roation frame
roation_image = True if sub_folder == "body" else False roation_image = True if sub_folder == "body" else False
print(f"roation_image = {roation_image}")
# IDs = ["2-23min"] # IDs = ["2-23min"]
# for each word # for each word
@@ -133,17 +165,27 @@ if __name__ == "__main__":
ipath_tfrom.mkdir(parents=True, exist_ok=True) ipath_tfrom.mkdir(parents=True, exist_ok=True)
ipath_lcrop.mkdir(parents=True, exist_ok=True) ipath_lcrop.mkdir(parents=True, exist_ok=True)
# check # check have done
num_frame = len(list(ipath_frame.glob("*.jpg"))) num_frame = len(list(ipath_frame.glob("*.jpg")))
num_fcrop = len(list(ipath_fcrop.glob("*.jpg"))) num_fcrop = len(list(ipath_fcrop.glob("*.jpg")))
if num_frame == num_fcrop: if num_frame == num_fcrop:
print(f"\n Skip: have already done!") print(f"\n Skip: have already done!")
continue continue
# only whole body image, need set roation_image=True # check landmarks have exists
dataset = ImagesDataset(ipath_frame, ipath_ldmks, suffix="jpg", crop_size=512, scale=1.5, roation_image=roation_image) num_ldmks = len(list(ipath_ldmks.glob("*.txt")))
dloader = DataLoader(dataset, batch_size=64, num_workers=4, shuffle=False) if num_frame != num_ldmks:
print(f"\n ERROR & Skip: ldmaks = {num_ldmks} != nframes {num_frame}!")
continue
# only whole body image, need set roation_image=True
dataset = ImagesDataset(ipath_frame, ipath_ldmks, suffix="jpg", crop_size=512, scale=1.5,
roation_image=roation_image, use_same_bbox=True, path_same_bbox = path_same_bbox )
dloader = DataLoader(dataset, batch_size=12, num_workers=1, shuffle=False)
print(f"processing crop ... ")
for j, jbatch in enumerate(dloader): for j, jbatch in enumerate(dloader):
# print(f"jbatch_data shape = {jbatch_data.shape}, path={jbatch_name[:3]}") # print(f"jbatch_data shape = {jbatch_data.shape}, path={jbatch_name[:3]}")
if j%100 == 0: if j%100 == 0:
@@ -170,6 +212,6 @@ if __name__ == "__main__":
np.save(kpath_tfrom, jbatch_tfrom[k]) np.save(kpath_tfrom, jbatch_tfrom[k])
np.savetxt(kpath_lcrop, jbatch_ldmks[k], fmt=" %3d") np.savetxt(kpath_lcrop, jbatch_ldmks[k], fmt=" %3d")
cv2.imwrite(str(kpath_fcrop), jbatch_crop[k]) cv2.imwrite(str(kpath_fcrop), jbatch_crop[k])
# cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_{vis_name}.jpg")), img) # cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_{vis_name}.jpg")), img)
# break # break
+110
View File
@@ -0,0 +1,110 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib import Path
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
def load_mask(j, path_parse):
parsing_anno = np.load(path_parse) # (512, 512)
mask = np.zeros_like(parsing_anno).astype(np.uint8) # (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']
# atts_selected = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'l_ear', 'r_ear', 'ear_r',
# 'nose', 'mouth', 'u_lip', 'l_lip', ]
atts_selected = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'nose', 'mouth', 'u_lip', 'l_lip']
class_contains = np.unique(parsing_anno)
if j % 1000 == 0:
logger.info(f"\t the {j:06d}-th frame, class_contains = {class_contains}")
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
if __name__ == "__main__":
actor = "Actor5"
sub_folder = "processing" # smile, processing, processing2
# logger
logger = Logger(f"./data/{actor}", postfix=f"generate-mask-{sub_folder}")
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
logger.info(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_parse = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
logger.info(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
ipath_frame = ipath_data.joinpath("frames")
ipath_parse = ipath_data.joinpath("frames_crop_parse_512")
ipath_parse_skin = ipath_data.joinpath("frames_crop_parse_skin_512")
ipath_parse_skin.mkdir(parents=True, exist_ok=True)
# if ipath_save_parse.exists():
# logger.info(f"ipath_save_exp have already save > {ipath_save_parse}")
# continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info["nframes"]
logger.info(f"info = {info}, duration ={nframes / fps / 60}")
# check equal
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_parse = list(ipath_parse.glob("*.npy"))
logger.info(f"vframe_frame len = {len(vframe_frame)}, vframe_parse={len(vframe_parse)}")
duration_frame += len(vframe_frame) / 50 / 60
duration_parse += len(vframe_parse) / 50 / 60
logger.info(f"add duration_frame = {duration_frame} min, duration_parse={duration_parse} min")
if len(vframe_frame) != nframes:
logger.info(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
continue
# check have done
# vframe_parse = list(ipath_parse_skin.glob("*.npy"))
# if len(vframe_parse) == nframes:
# logger.info(f"ipath_parse_skin have already done!")
# continue
# feat_parse = []
for j in range(len(vframe_frame)):
jpath_parse = ipath_parse.joinpath(f"frame-{j:06d}.npy")
jpath_parse_save = ipath_parse_skin.joinpath(f"frame-{j:06d}.npy")
if not jpath_parse.exists():
logger.info(f"\n ERROR: Path NOT FOUND! -> {jpath_parse}")
break
data_mask = load_mask(j, jpath_parse) # (512, 512)
np.save(jpath_parse_save, data_mask)
# feat_parse.append(data_mask)
@@ -0,0 +1,154 @@
import os, sys
import numpy as np
import cv2
from time import time
import argparse
import json
from pathlib import Path
from torch.utils.data import DataLoader
sys.path.insert(0, '/ssdata1/lsen/CODE/DECA_old')
from decalib.deca import DECA
from decalib.datasets.datasets2 import ObamaData
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
def main(args):
# device = args.device
device = "cuda:3"
# run DECA
deca_cfg.model.use_tex = args.useTex
deca = DECA(config = deca_cfg, device=device)
# path_data = Path("/yrfs/lsen/DATA/TestData/processing")
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files")
# IDs = ["actor-2HD", "actor-3HD"]
# IDs = ["clip_full"]
# for each video
for i, ipath_data in enumerate(v_dir_videos):
ivideo_name = ipath_data.stem
print(f"\n processing {i}/{len(v_dir_videos)} ...", ivideo_name)
# if ivideo_name not in IDs: continue
# if i > 25: break
ipath_infor = ipath_data.joinpath("video/info.json")
# ipath_frame = ipath_data.joinpath("frames")
ipath_frame = ipath_data.joinpath("frames_crop_512")
# ipath_kpt2d = ipath_data.joinpath("DECA_kpt2d")
# ipath_kpt3d = ipath_data.joinpath("DECA_kpt3d")
ipath_coeff = ipath_data.joinpath("deca_coeff_512")
# ipath_vis = ipath_data.joinpath("DECA_vis2")
# ipath_kpt2d.mkdir(parents=True, exist_ok=True)
# ipath_kpt3d.mkdir(parents=True, exist_ok=True)
ipath_coeff.mkdir(parents=True, exist_ok=True)
# ipath_vis.mkdir(parents=True, exist_ok=True)
# load video info
if not ipath_infor.exists():
print(f"\n ERROR: info.json not existing {ipath_infor}")
continue
with open(str(ipath_infor), "r") as f:
info = json.load(f)
nframes = info['nframes']
nframe_real = len(list(ipath_frame.glob("*.jpg")))
if nframe_real != nframes:
print(f"\n ERROR: nframe_real ={nframe_real} / nframe_info ={nframes}")
continue
# check if finish
nkpt2d = len(list(ipath_coeff.glob("*.npy")))
if nkpt2d + 10 > nframes:
print(f"Have finised before, nkpt2d={nkpt2d} nframes = {nframes}")
continue
datatest = ObamaData(ipath_frame, iscrop=args.iscrop, face_detector=args.detector, device=device)
dataloader = DataLoader(datatest, batch_size=128, shuffle=False, drop_last=False)
for i, ibatch_data in enumerate(dataloader):
batch_names = ibatch_data["names"]
batch_image = ibatch_data["image"].to(device)
if i%10 == 0:
print(f"batch {i:04}/{len(dataloader)}... name = ", batch_names[:5])
codedict = deca.encode(batch_image) # encoder
# opdict, visdict = deca.decode(codedict, batch_image) # decoder
for j, jname in enumerate(batch_names):
# jpath_kpt2d = ipath_kpt2d.joinpath(f"{jname}.txt")
# jpath_kpt3d = ipath_kpt3d.joinpath(f"{jname}.txt")
jpath_coeff = ipath_coeff.joinpath(f"{jname}.json")
# np.savetxt(jpath_kpt2d, opdict['landmarks2d'][j].cpu().numpy(), fmt="%.6f")
# np.savetxt(jpath_kpt3d, opdict['landmarks3d'][j].cpu().numpy(), fmt="%.6f")
# save coeff
jcodedict = {}
for key, value in codedict.items():
jcodedict[key] = value[j].cpu().numpy()
# print("json = ", jcodedict)
np.save(jpath_coeff, jcodedict)
# # save render
# render_names = ['inputs', 'rendered_images']
# # render_names = ['inputs', 'rendered_images', 'albedo_images', 'shape_images', 'shape_detail_images']
# for vis_name in render_names:
# if vis_name not in visdict.keys():
# continue
# img = util.tensor2image(visdict[vis_name][j])
# cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_{vis_name}.jpg")), img)
# save vis
# cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_vis.jpg")), deca.visualize(visdict))
# break
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='DECA: Detailed Expression Capture and Animation')
parser.add_argument('-i', '--inputpath', default='TestSamples/examples', type=str,
help='path to the test data, can be image folder, image path, image list, video')
parser.add_argument('-d', '--device', default='cuda:0', type=str,
help='set device, cpu for using cpu' )
# process test images
parser.add_argument('--iscrop', default=True, type=lambda x: x.lower() in ['true', '1'],
help='whether to crop input image, set false only when the test image are well cropped' )
parser.add_argument('--detector', default='fan', type=str,
help='detector for cropping face, check decalib/detectors.py for details' )
# save
parser.add_argument('--useTex', default=True, type=lambda x: x.lower() in ['true', '1'],
help='whether to use FLAME texture model to generate uv texture map, \
set it to True only if you downloaded texture model' )
parser.add_argument('--saveVis', default=True, type=lambda x: x.lower() in ['true', '1'],
help='whether to save visualization of output' )
parser.add_argument('--saveKpt', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save 2D and 3D keypoints' )
parser.add_argument('--saveDepth', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save depth image' )
parser.add_argument('--saveObj', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save outputs as .obj, detail mesh will end with _detail.obj. \
Note that saving objs could be slow' )
parser.add_argument('--saveMat', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save outputs as .mat' )
parser.add_argument('--saveImages', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save visualization output as seperate images' )
main(parser.parse_args())
+28 -19
View File
@@ -5,30 +5,39 @@ import librosa
import numpy as np import numpy as np
from pathlib import Path from pathlib import Path
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
if __name__ == "__main__": if __name__ == "__main__":
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
actor = "Actor5"
sub_folder = "processing" # smile, processing, processing2
# logger
logger = Logger(f"./data/{actor}", postfix=f"feature-3dmm-{sub_folder}")
# path data
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
v_dir_videos = sorted(path_data.glob("*"), reverse=False) v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files") logger.info(f"Have {len(v_dir_videos)} dir files")
# for each video # for each video
duration_frame, duration_coeff = 0, 0 duration_frame, duration_coeff = 0, 0
for ipath_data in v_dir_videos: for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ") logger.info(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json") ipath_infors = ipath_data.joinpath("video/info.json")
ipath_coeff = ipath_data.joinpath("DECA_coeff") # ipath_coeff = ipath_data.joinpath("DECA_coeff")
ipath_coeff = ipath_data.joinpath("deca_coeff_512")
ipath_frame = ipath_data.joinpath("frames") ipath_frame = ipath_data.joinpath("frames")
ipath_save_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy") ipath_save_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_save_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy") ipath_save_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
ipath_save_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy") ipath_save_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
if ipath_save_exp.exists() and ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_exp}")
continue
if not ipath_infors.exists(): if not ipath_infors.exists():
continue continue
@@ -38,28 +47,28 @@ if __name__ == "__main__":
fps = info["fps"] fps = info["fps"]
nframes = info["nframes"] nframes = info["nframes"]
print(f"info = {info}, duration ={nframes / fps / 60}") logger.info(f"info = {info}, duration ={nframes / fps / 60}")
# check # check
vframe_frame = list(ipath_frame.glob("*.jpg")) vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_coeff = list(ipath_coeff.glob("*.npy")) vframe_coeff = list(ipath_coeff.glob("*.npy"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}") logger.info(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
duration_frame += len(vframe_frame) / 50 / 60 duration_frame += len(vframe_frame) / 50 / 60
duration_coeff += len(vframe_coeff) / 50 / 60 duration_coeff += len(vframe_coeff) / 50 / 60
print(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min") logger.info(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min")
if len(vframe_frame) != nframes: if len(vframe_frame) != nframes:
print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}") logger.info(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
continue continue
if len(vframe_coeff)+1 < nframes: if len(vframe_coeff)+1 < nframes:
print(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}") logger.info(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}")
continue continue
if ipath_save_exp.exists() and ipath_save_pos.exists(): # if ipath_save_exp.exists() and ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_exp}") # logger.info(f"ipath_save_exp have already save > {ipath_save_exp}")
continue # continue
feat_exp = [] feat_exp = []
feat_pos = [] feat_pos = []
@@ -69,7 +78,7 @@ if __name__ == "__main__":
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:06d}.json.npy") jpath_coeff = ipath_coeff.joinpath(f"frame-{j:06d}.json.npy")
if not jpath_coeff.exists(): if not jpath_coeff.exists():
print(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}") logger.info(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}")
break break
data_coeff = np.load(jpath_coeff, allow_pickle=True).item() data_coeff = np.load(jpath_coeff, allow_pickle=True).item()
@@ -91,10 +100,10 @@ if __name__ == "__main__":
np.save(ipath_save_exp, feat_exp) np.save(ipath_save_exp, feat_exp)
np.save(ipath_save_pos, feat_pos) np.save(ipath_save_pos, feat_pos)
np.save(ipath_save_idn, feat_idn) np.save(ipath_save_idn, feat_idn)
print(f"SAVE OK! exp shape = {feat_exp.shape},pos = {feat_pos.shape}, idn={feat_idn.shape} nframe={nframes}\n save to -> {ipath_save_exp}") # (nframe, 68, 2) logger.info(f"SAVE OK! exp shape = {feat_exp.shape},pos = {feat_pos.shape}, idn={feat_idn.shape} nframe={nframes}\n save to -> {ipath_save_exp}") # (nframe, 68, 2)
else: else:
print("ERROR, skip! ") logger.info("ERROR, skip! ")
+103
View File
@@ -0,0 +1,103 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib import Path
from scipy.signal import savgol_filter
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
if __name__ == "__main__":
actor = "Actor5"
sub_folder = "processing" # smile, processing, processing2
# logger
logger = Logger(f"./data/{actor}", postfix=f"concat-coeff-{sub_folder}")
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_coeff = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
# ipath_coeff = ipath_data.joinpath("DECA_coeff")
ipath_coeff = ipath_data.joinpath("deca_coeff_512")
ipath_frame = ipath_data.joinpath("frames")
ipath_save_coeff = ipath_data.joinpath("audio/feat_deca_coeff_512p.npy")
# if ipath_save_coeff.exists():
# print(f"ipath_save_exp have already save > {ipath_save_coeff}")
# continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info["nframes"]
print(f"info = {info}, duration ={nframes / fps / 60}")
# check
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_coeff = list(ipath_coeff.glob("*.npy"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
duration_frame += len(vframe_frame) / 50 / 60
duration_coeff += len(vframe_coeff) / 50 / 60
print(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min")
if len(vframe_frame) != nframes:
print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
continue
if len(vframe_coeff)+1 < nframes:
print(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}")
continue
feat_coeff = []
params = ['shape', 'tex', 'exp', 'pose', 'cam', 'light']
for j in range(len(vframe_frame)):
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:06d}.json.npy")
if not jpath_coeff.exists():
print(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}")
break
codedict = np.load(jpath_coeff, allow_pickle=True).item()
# 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 !"
feat_coeff.append(np.array(coeff))
# concate
feat_coeff = np.array(feat_coeff) # (N, 236)
# smooth it
feat_coeff = savgol_filter(feat_coeff, window_length=5, polyorder=3, axis=0, mode='nearest')
if nframes == feat_coeff.shape[0]:
np.save(ipath_save_coeff, feat_coeff)
print(f"SAVE OK! feat shape = {feat_coeff.shape}, nframe={nframes}\n save to -> {ipath_save_coeff}") # (nframe, 68, 2)
else:
print("ERROR, skip! ")
+105
View File
@@ -0,0 +1,105 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib import Path
def load_mask(path_parse):
parsing_anno = np.load(path_parse) # (512, 512)
mask = np.zeros_like(parsing_anno).astype(np.uint8) # (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']
atts_selected = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'l_ear', 'r_ear', 'ear_r',
'nose', 'mouth', '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
if __name__ == "__main__":
path_data = Path("/ssdata1/lsen/DATA/Actor5/smile")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_parse = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
ipath_frame = ipath_data.joinpath("frames")
ipath_parse = ipath_data.joinpath("frames_crop_parse_512")
ipath_parse_skin = ipath_data.joinpath("frames_crop_parse_skin_512")
ipath_parse_skin.mkdir(parents=True, exist_ok=True)
# if ipath_save_parse.exists():
# print(f"ipath_save_exp have already save > {ipath_save_parse}")
# continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info["nframes"]
print(f"info = {info}, duration ={nframes / fps / 60}")
# check equal
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_parse = list(ipath_parse.glob("*.npy"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_parse={len(vframe_parse)}")
duration_frame += len(vframe_frame) / 50 / 60
duration_parse += len(vframe_parse) / 50 / 60
print(f"add duration_frame = {duration_frame} min, duration_parse={duration_parse} min")
if len(vframe_frame) != nframes:
print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
continue
# check have done
# vframe_parse = list(ipath_parse_skin.glob("*.npy"))
# if len(vframe_parse) == nframes:
# print(f"ipath_parse_skin have already done!")
# continue
# feat_parse = []
for j in range(len(vframe_frame)):
jpath_parse = ipath_parse.joinpath(f"frame-{j:06d}.npy")
jpath_parse_save = ipath_parse_skin.joinpath(f"frame-{j:06d}.npy")
if not jpath_parse.exists():
print(f"\n ERROR: Path NOT FOUND! -> {jpath_parse}")
break
data_mask = load_mask(jpath_parse) # (512, 512)
np.save(jpath_parse_save, data_mask)
# feat_parse.append(data_mask)
# feat_parse = np.stack(feat_parse, axis=0)
# if nframes == feat_parse.shape[0]:
# np.save(ipath_save_parse, feat_parse)
# print(f"SAVE OK! feat shape = {feat_parse.shape}, dtype={feat_parse.dtype}, nframe={nframes}\n save to -> {ipath_save_parse}") # (nframe, 68, 2)
# else:
# print("ERROR, skip! ")
@@ -0,0 +1,173 @@
import json
import numpy as np
from pathlib2 import Path
import torchaudio
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
if __name__ == "__main__":
actor= "Actor5"
sub_folder = "processing" # processing, smile, body
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
path_save = Path(f'data/{actor}/{actor}-raw-{sub_folder}-1h')
path_save.mkdir(parents=True, exist_ok=True)
# set logging
logger = Logger(path_save, postfix=f"train-audio2mesh-{sub_folder}")
# get files
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
logger.info(f"Have {len(v_dir_videos)} dir files")
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
vids = set([ipath.stem for ipath in v_dir_videos])
# logger.info(f"vids total= {vids}")
# training set
if sub_folder == "smile":
vid_test = set(["4R3A0071"])
vid_valid = set(["4R3A0071"])
vid_train = vids - vid_test - vid_valid
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
logger.info(f"vid train= {vid_train}")
else:
vid_test = set(["4R3A0063"])
vid_valid = set(["4R3A0063"])
vid_train = vids - vid_test - vid_valid
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
logger.info(f"vid train= {vid_train}")
# for each video
data_train, data_valid, data_test = {}, {}, {}
list_train, list_valid, list_test = [], [], []
durations_train, durations_valid, durations_test = 0, 0, 0
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
# if vid not in vids: continue
# if vid in vid_test: continue
# if vid in vid_valid:continue
# if durations_train / 3600 > 6: break
logger.info(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
ipath_feat_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
ipath_speech = ipath_data.joinpath("audio/audio_trim.wav")
# check existing
if not ipath_speech.exists():
logger.info(f"NOT existing {ipath_speech}")
continue
if not ipath_feat_exp.exists():
logger.info(f"NOT existing {ipath_feat_exp}")
continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info['nframes']
logger.info(f"info={info}, duration = {nframes/fps}")
assert fps == 50, "fps should be 50"
# laod motion
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 6)
data_idn = np.load(ipath_feat_idn) # (nframe, 100)
assert data_exp.shape[0] == data_pos.shape[0], f"data_exp shape={data_exp.shape}, data_pos shape={data_pos.shape}"
assert data_exp.shape[0] == data_idn.shape[0], f"data_exp shape={data_exp.shape}, data_idn shape={data_idn.shape}"
data_pos_head = data_pos[:, :3] # (nframe, 3)
data_pos_lips = data_pos[:, 3:] # (nframe, 3)
data_motion = np.concatenate([data_exp, data_pos_lips], axis=1) # (nframe, 53) --> fps=30
logger.info(f"motion = {data_motion.shape}")
# load raw audio
audio_raw, sample_rate = torchaudio.load(ipath_speech)
logger.info(f"audio_raw shape = {audio_raw.shape}, sr = {sample_rate}, duration = {(len(audio_raw[0])/sample_rate)}")
if len(audio_raw.shape) == 2:
audio_raw = audio_raw[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
audio_raw = resampler(audio_raw).squeeze().numpy()
logger.info(f"audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
# ####################################
# # clips 4min
# nclip = 4
# nframes = nclip * 60 * 50 # min * 60s * fps
# nsegmts = nclip * 60 * 16000 # min * 60s * sr
# data_motion = data_motion[:nframes]
# audio_raw = audio_raw[:nsegmts]
# data_idn = data_idn[:nframes]
# ####################################
if vid in vid_train:
durations_train += nframes/fps
list_train.append(vid)
data_train[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
if vid in vid_valid:
durations_valid += nframes/fps
list_valid.append(vid)
data_valid[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
if vid in vid_test:
durations_test += nframes/fps
list_test.append(vid)
data_test[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
logger.info(f"Total frames: data_train ({durations_train/60:.2f} min) ({durations_train/3600:.2f} h) , ids = ({len(data_train)})")
logger.info(f"Total frames: data_valid ({durations_valid/60:.2f} min) ({durations_valid/3600:.2f} h) , ids = ({len(data_valid)})")
logger.info(f"Total frames: data_test ({durations_test/60:.2f} min) ({durations_test/3600:.2f} h) , ids = ({len(data_test)})")
logger.info(f"actual train ID: > {list_train} ")
logger.info(f"actual valid ID: > {list_valid} ")
logger.info(f"actual test ID: > {list_test} ")
np.savez(path_save.joinpath("data_train.npz"), data=data_train)
np.savez(path_save.joinpath("data_valid.npz"), data=data_valid)
np.savez(path_save.joinpath("data_test.npz"), data=data_test)
logger.info(f"--> {path_save}")
@@ -6,23 +6,25 @@ import torchaudio
import os, sys import os, sys
sys.path.insert(0, os.getcwd()) sys.path.insert(0, os.getcwd())
from common.logger import Logger from common.logger import Logger
if __name__ == "__main__": if __name__ == "__main__":
subfolder = "processing" # processing, smile, body actor= "Actor5"
path_data = Path(f"/ssdata1/lsen/DATA/Actor5/{subfolder}") sub_folder = "processing" # processing, smile, body
path_save = Path(f'data/Actor5/data-list-{subfolder}-1h')
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
path_save = Path(f'data/{actor}/data-render-{sub_folder}-1h')
path_save.mkdir(parents=True, exist_ok=True) path_save.mkdir(parents=True, exist_ok=True)
# set logging # set logging
logger = Logger(path_save) logger = Logger(path_save, postfix=f"train-list-{sub_folder}")
# get files # get files
v_dir_videos = sorted(path_data.glob("*")) v_dir_videos = sorted(path_data.glob("*"))
logger.info(f"Have {len(v_dir_videos)} dir files") logger.info(f"Have {len(v_dir_videos)} dir files")
vids = set([ipath.stem for ipath in v_dir_videos]) vids = set([ipath.stem for ipath in v_dir_videos])
logger.info(f"vids total= {vids}") logger.info(f"vids total= {vids}")
@@ -32,15 +34,15 @@ if __name__ == "__main__":
# vid_train = vids - vid_test - vid_valid # vid_train = vids - vid_test - vid_valid
# actor5 smile # actor5 smile
if subfolder == "smile": if sub_folder == "smile":
vid_test = set(["4R3A0071"]) vid_test = set(["4R3A0071"])
vid_valid = set(["4R3A0071"]) vid_valid = set(["4R3A0071"])
vid_train = set(["4R3A0070", "4R3A0072", "4R3A0073", "4R3A0074", "4R3A0075", "4R3A0076"]) vid_train = vids - vid_test - vid_valid
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}") logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
logger.info(f"vid train= {vid_train}") logger.info(f"vid train= {vid_train}")
else: else:
vid_test = set(["4R3A0063", "4R3A0071"]) vid_test = set(["4R3A0063"])
vid_valid = set(["4R3A0063", "4R3A0071"]) vid_valid = set(["4R3A0063"])
vid_train = vids - vid_test - vid_valid vid_train = vids - vid_test - vid_valid
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}") logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
logger.info(f"vid train= {vid_train}") logger.info(f"vid train= {vid_train}")
@@ -61,11 +63,11 @@ if __name__ == "__main__":
logger.info(f"\n\n processing the {i}-th video {vid} ... ") logger.info(f"\n\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json") ipath_info = ipath_data.joinpath("video/info.json")
ipath_coeff = ipath_data.joinpath("DECA_coeff") # DECA coeff of shape/exp/light # ipath_coeff = ipath_data.joinpath("DECA_coeff") # DECA coeff of shape/exp/light
ipath_coeff = ipath_data.joinpath("deca_coeff_512") # DECA coeff of shape/exp/light
ipath_frame = ipath_data.joinpath("frames_crop_512") # cropped image 512x512 ipath_frame = ipath_data.joinpath("frames_crop_512") # cropped image 512x512
ipath_ldmks = ipath_data.joinpath("frames_crop_ldmks_512") # cropped landmarks within 512x512 ipath_ldmks = ipath_data.joinpath("frames_crop_ldmks_512") # cropped landmarks within 512x512
ipath_parse = ipath_data.joinpath("frames_crop_parse_512") # cropped mask ipath_parse = ipath_data.joinpath("frames_crop_parse_skin_512") # cropped mask
ipath_speech = ipath_data.joinpath("audio/audio_trim.wav") # audio path
# check info existing # check info existing
if not ipath_info.exists(): if not ipath_info.exists():
@@ -94,17 +96,11 @@ if __name__ == "__main__":
logger.info(f"num of ipath_parse ({num_parse}) shoud be {nframes} > {ipath_parse}") logger.info(f"num of ipath_parse ({num_parse}) shoud be {nframes} > {ipath_parse}")
continue continue
# load raw audio # load coeff
audio_raw, sample_rate = torchaudio.load(ipath_speech) # ipath_feat_coeff = ipath_data.joinpath("audio/feat_DECA_trim.npy")
logger.info(f"audio_raw shape = {audio_raw.shape}, sr = {sample_rate}, duration = {(len(audio_raw[0])/sample_rate)}") ipath_feat_coeff = ipath_data.joinpath("audio/feat_deca_coeff_512p.npy")
data_coeff = np.load(ipath_feat_coeff) # (nframe, 236)
if len(audio_raw.shape) == 2: data_coeff = data_coeff.astype(np.float16) # convert float16
audio_raw = audio_raw[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
audio_raw = resampler(audio_raw).squeeze().numpy()
logger.info(f"audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
if vid in vid_train: if vid in vid_train:
@@ -115,8 +111,8 @@ if __name__ == "__main__":
"fps": info["fps"], "fps": info["fps"],
"sr": 16000, "sr": 16000,
"nframe": nframes, "nframe": nframes,
"data_speech": audio_raw, "path_data": str(ipath_data),
"path_data": str(ipath_data) "data_coeff": data_coeff
} }
if vid in vid_valid: if vid in vid_valid:
@@ -127,11 +123,10 @@ if __name__ == "__main__":
"fps": info["fps"], "fps": info["fps"],
"sr": 16000, "sr": 16000,
"nframe": nframes, "nframe": nframes,
"data_speech": audio_raw, "path_data": str(ipath_data),
"path_data": str(ipath_data) "data_coeff": data_coeff
} }
if vid in vid_test: if vid in vid_test:
durations_test += nframes/fps durations_test += nframes/fps
list_test.append(vid) list_test.append(vid)
@@ -140,8 +135,8 @@ if __name__ == "__main__":
"fps": info["fps"], "fps": info["fps"],
"sr": 16000, "sr": 16000,
"nframe": nframes, "nframe": nframes,
"data_speech": audio_raw, "path_data": str(ipath_data),
"path_data": str(ipath_data) "data_coeff": data_coeff
} }
logger.info(f"Total frames: data_train ({durations_train/60:.2f} min) ({durations_train/3600:.2f} h) , ids = ({len(data_train)})") logger.info(f"Total frames: data_train ({durations_train/60:.2f} min) ({durations_train/3600:.2f} h) , ids = ({len(data_train)})")
@@ -1,7 +1,8 @@
from torch.utils.data import Dataset, DataLoader from torch.utils.data import Dataset, DataLoader
import cv2
import torch import torch
import numpy as np import numpy as np
from PIL import Image
from pathlib2 import Path from pathlib2 import Path
from face_alignment import FaceAlignment, LandmarksType from face_alignment import FaceAlignment, LandmarksType
from zmq import device from zmq import device
@@ -20,9 +21,8 @@ class ImagesDataset(Dataset):
def __getitem__(self, idx): def __getitem__(self, idx):
path_frame = self.list_image[idx] path_frame = self.list_image[idx]
# image = Image.open(str(path_frame)).convert('RGB') # (h, w, 3) image = Image.open(str(path_frame)).convert('RGB') # (h, w, 3)
# image = np.asarray(image) image = np.asarray(image)
image = cv2.imread(str(path_frame)).astype(np.float32)
return {"image_name": path_frame.stem, "image": image} return {"image_name": path_frame.stem, "image": image}
@@ -45,22 +45,23 @@ if __name__ == "__main__":
# if iname not in IDs: continue # if iname not in IDs: continue
ipath_infor = ipath_item.joinpath("video/info.json") ipath_infor = ipath_item.joinpath("video/info.json")
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
ipath_frame = ipath_item.joinpath("frames") ipath_frame = ipath_item.joinpath("frames")
ipath_mask = ipath_item.joinpath("skin_mask") ipath_ldmks.mkdir(parents=True, exist_ok=True)
ipath_mask.mkdir(parents=True, exist_ok=True)
# check # check
num_frame = len(list(ipath_frame.glob("*.jpg"))) num_frame = len(list(ipath_frame.glob("*.jpg")))
num_mask = len(list(ipath_mask.glob("*.jpg"))) num_ladmk = len(list(ipath_ldmks.glob("*.txt")))
if num_frame == num_mask: if num_frame == num_ladmk:
print(f"\n Skip: have already done!") print(f"\n Skip: have already done!")
continue continue
vframe_frame = list(ipath_frame.glob("*.jpg"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
dataset = ImagesDataset(ipath_frame)
dloader = DataLoader(dataset, batch_size=16, num_workers=8)
for k, kpath_ in enumerate(dloader): for k, ibatch in enumerate(dloader):
ibatch_name = ibatch["image_name"] ibatch_name = ibatch["image_name"]
ibatch_data = ibatch["image"].to(device) # B x H x W x 3 ibatch_data = ibatch["image"].to(device) # B x H x W x 3
ibatch_data = ibatch_data.permute(0, 3, 1, 2) # B x H x W x 3 ibatch_data = ibatch_data.permute(0, 3, 1, 2) # B x H x W x 3
+99
View File
@@ -0,0 +1,99 @@
from torch.utils.data import Dataset, DataLoader
import torch
import numpy as np
from PIL import Image
from pathlib2 import Path
from face_alignment import FaceAlignment, LandmarksType
from zmq import device
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
def bbox2point(left, right, top, bottom, type='bbox'):
''' bbox from detector and landmarks are different
'''
if type=='kpt68':
old_size = (right - left + bottom - top) / 2 * 1.1
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top ) / 2.0 ])
elif type=='bbox':
old_size = (right - left + bottom - top)/2
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top ) / 2.0 + old_size*0.12])
else:
raise NotImplementedError
return old_size, center
if __name__ == "__main__":
sub_folder = "processing" # processing, processing2
path_data = Path(f"/ssdata1/lsen/DATA/Actor6/{sub_folder}")
logger = Logger("./data/Actor6", postfix=f"max_bbox_{sub_folder}")
path_mean_bbox = Path(f"./data/Actor6/max_bbox_{sub_folder}.npy")
vpath_videos = sorted(path_data.glob("*"), reverse=True)
logger.info(f"Have {len(vpath_videos)} dir files")
# IDs = ["2-23min"]
mean_bbox = []
for i, ipath_item in enumerate(vpath_videos):
iname = ipath_item.stem
logger.info(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if iname not in IDs: continue
ipath_infor = ipath_item.joinpath("video/info.json")
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
ipath_frame = ipath_item.joinpath("frames")
ipath_ldmks.mkdir(parents=True, exist_ok=True)
# check
vpath_ldmks = list(ipath_ldmks.glob("*.txt"))
kmean_bbox = []
for k, kpath_ldmk in enumerate(vpath_ldmks):
# if k%1000 == 0:
# logger.info(f"batching {k}/{len(vpath_ldmks)} ... ")
kpt = np.loadtxt(kpath_ldmk) # (68, 2)
if kpt.shape[0] > 68:
kpt = kpt[:68, :]
logger.info(f"ERROR: > use first 68-kpts, kpt = {kpt.shape} ipath_ldmk={kpath_ldmk}")
left = np.min(kpt[:,0]); right = np.max(kpt[:,0])
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1])
kmean_bbox.append([left, right, top, bottom])
if len(vpath_ldmks) > 0:
kmean_bbox = np.array(kmean_bbox)
# kmean_bbox = kmean_bbox.max(axis=0)
left, right = np.min(kmean_bbox[:, 0]), np.max(kmean_bbox[:, 1])
top, bottom = np.min(kmean_bbox[:, 2]), np.max(kmean_bbox[:, 3])
mean_bbox.append([left, right, top, bottom])
logger.info(f"\t max bbox ={[left, right, top, bottom]}")
# get toatl mean bbox
mean_bbox = np.array(mean_bbox)
# mean_bbox = mean_bbox.max(axis=0).astype(np.int32)
left, right = np.min(mean_bbox[:, 0]), np.max(mean_bbox[:, 1])
top, bottom = np.min(mean_bbox[:, 2]), np.max(mean_bbox[:, 3])
mean_bbox = [left, right, top, bottom]
logger.info(f"total max bbox ={mean_bbox}, ")
logger.info(f"wsize = {right - left}, hsize = {bottom - top} ")
# save mean
np.save(path_mean_bbox, mean_bbox)
# break
@@ -0,0 +1,207 @@
import cv2
from cv2 import norm
import numpy as np
from pathlib2 import Path
from skimage.transform import estimate_transform, warp
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
def bbox2point(left, right, top, bottom, type='bbox'):
''' bbox from detector and landmarks are different
'''
if type=='kpt68':
old_size = (right - left + bottom - top) / 2 * 1.1
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top ) / 2.0 ])
elif type=='bbox':
old_size = (right - left + bottom - top)/2
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top ) / 2.0 + old_size*0.12])
else:
raise NotImplementedError
return old_size, center
def processing_one_folder(ipath_frame, ipath_ldmks, ipath_fcrop, ipath_tfrom, ipath_lcrop,
suffix="jpg", crop_size=512, scale=1.25, roation_image=False, use_same_bbox=False, path_same_bbox = None):
# get images
vpath_image = sorted(ipath_frame.glob(f"*.{suffix}"), key=lambda x: int(x.stem.split("-")[-1]), reverse=False)
logger.info(f'--> total have {len(vpath_image)} images, top: \n{vpath_image[:3]}')
# set prev_ldmk
prev_ldmk = None
if use_same_bbox:
same_bbox = np.load(path_same_bbox).reshape(-1) # (4,) [left, right, top, bottom]
logger.info(f"same_bbox = {same_bbox}")
# for iteration
for j, jpath_frame in enumerate(vpath_image):
image_name = jpath_frame.stem # (frame-0000)
if j%100 == 0:
logger.info(f"load jpath_frame --> {jpath_frame}")
# if j < 19300: continu
ipath_ldmk = ipath_ldmks.joinpath(image_name + ".txt")
if not ipath_ldmk.exists():
raise Exception(f"ipath_ldmk not exists --> {ipath_ldmk}")
kpath_fcrop = ipath_fcrop.joinpath(image_name + ".jpg")
kpath_tfrom = ipath_tfrom.joinpath(image_name + ".npy")
kpath_lcrop = ipath_lcrop.joinpath(image_name + ".txt")
# ##########################
# # check exists
# if kpath_fcrop.exists() and kpath_tfrom.exists() and kpath_lcrop.exists():
# # logger.info(f"kpath_fcrop, kpath_tfrom, kpath_lcrop, have existing! ---> {kpath_fcrop} ")
# print(f"kpath_fcrop, kpath_tfrom, kpath_lcrop, have existing! ---> {kpath_fcrop} ")
# continue
# ##########################
# load orignal image & landmarks
image = cv2.imread(str(jpath_frame)) # (H, W, 3), dtype=uint8
kpt = np.loadtxt(ipath_ldmk) # (68, 2)
if kpt.shape[0] > 68:
logger.info(f"ERROR: > use first 68-kpts, cropped_ldmk = {kpt.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}")
n_kpt = kpt.shape[0] // 68
max_cos = 0
kpt_selected = None
for idx in range(n_kpt):
cur_kpt = kpt[idx*68:(idx+1)*68, :]
cur_cos = np.dot(prev_ldmk, cur_kpt.reshape(-1)) / (np.linalg.norm(prev_ldmk) * np.linalg.norm(cur_kpt.reshape(-1)))
if cur_cos > max_cos:
max_cos = cur_cos
kpt_selected = cur_kpt
# get kpt, which match the prev_landmarks
logger.info(f"\t SELETCT: max_cos = {max_cos} --> {kpt_selected.reshape(-1)[::10]}")
kpt = kpt_selected
# record prev
prev_ldmk = kpt.copy().reshape(-1) # record prev_ldmk
# reverse H&W
if roation_image:
image = image.transpose(1,0,2) # (H, W, 3)
kpt = kpt[:, ::-1] # (68, 2)
if use_same_bbox:
left, right = same_bbox[0], same_bbox[1]
top, bottom = same_bbox[2], same_bbox[3]
else:
left = np.min(kpt[:,0]); right = np.max(kpt[:,0])
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1])
old_size, center = bbox2point(left, right, top, bottom, type='kpt68')
# crop transform
size = int(old_size * scale)
src_pts = np.array([[center[0] - size/2, center[1] - size/2], # (left, top)
[center[0] - size/2, center[1] + size/2], # (left, bottom)
[center[0] + size/2, center[1] - size/2]]) # (right, top)
DST_PTS = np.array([[0, 0], # (left-top-corner)
[0, crop_size - 1], # (left-botton corner)
[crop_size - 1, 0]]) # (right-top corner)
# tform_params dytpe = float64, shape = (3, 3)
tform = estimate_transform('similarity', src_pts, DST_PTS)
# image = image/255.
# (crop_size, crop_size, 3) ,float64
cropped_imag = warp(image, tform.inverse, output_shape=(crop_size, crop_size)) # scale to (0~1)
cropped_ldmk = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # (68,3)
cropped_ldmk = cropped_ldmk[:, :2]
# logger.info(f"image dytpe = {image.dtype}, shape = {image.shape} ")
# logger.info(f"cropped_imag dytpe = {cropped_imag.dtype}, shape = {cropped_imag.shape} ")
# logger.info(f"tform_params dytpe = {tform.params.dtype}, shape = {tform.params.shape} ")
# logger.info(f"cropped_ldmk dytpe = {cropped_ldmk.dtype}, shape = {cropped_ldmk.shape}, max={cropped_ldmk.max()}, min={cropped_ldmk.min()} ")
np.save(kpath_tfrom, tform.params)
np.savetxt(kpath_lcrop, cropped_ldmk, fmt=" %3d")
cropped_imag = (255*cropped_imag).astype(np.uint8)
cv2.imwrite(str(kpath_fcrop), cropped_imag)
if __name__ == "__main__":
actor = "Actor6"
sub_folder = "processing2" # smile, processing, processing2
# logger
logger = Logger(f"./data/{actor}", postfix=f"crop-transform-{sub_folder}")
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
path_same_bbox = f"data/{actor}/max_bbox_{sub_folder}.npy"
#
vpath_videos = sorted(path_data.glob("*"), reverse=False)
logger.info(f"Have {len(vpath_videos)} dir files")
# whole body need roation frame
roation_image = True if sub_folder == "body" else False
logger.info(f"roation_image = {roation_image}")
# for each word
for i, ipath_item in enumerate(vpath_videos):
iname = ipath_item.stem
logger.info(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
if iname not in ["4R3A0139"]: continue
# if iname not in IDs: continue
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
ipath_frame = ipath_item.joinpath("frames")
ipath_fcrop = ipath_item.joinpath("frames_crop_512")
ipath_tfrom = ipath_item.joinpath("frames_crop_tform_512")
ipath_lcrop = ipath_item.joinpath("frames_crop_ldmks_512")
ipath_fcrop.mkdir(parents=True, exist_ok=True)
ipath_tfrom.mkdir(parents=True, exist_ok=True)
ipath_lcrop.mkdir(parents=True, exist_ok=True)
num_frame = len(list(ipath_frame.glob("*.jpg")))
# check have done
# num_fcrop = len(list(ipath_fcrop.glob("*.jpg")))
# if num_frame == num_fcrop:
# logger.info(f"\n Skip: have already done!")
# continue
# check landmarks have exists
num_ldmks = len(list(ipath_ldmks.glob("*.txt")))
if num_frame != num_ldmks:
logger.info(f"\n ERROR & Skip: ldmaks = {num_ldmks} != nframes {num_frame}!")
continue
# processing one folder
processing_one_folder(
ipath_frame, ipath_ldmks, ipath_fcrop, ipath_tfrom, ipath_lcrop,
suffix="jpg", crop_size=512, scale=1.5,
roation_image=roation_image, use_same_bbox=True, path_same_bbox = path_same_bbox
)
+200
View File
@@ -0,0 +1,200 @@
import cv2
import numpy as np
from pathlib2 import Path
from skimage.transform import estimate_transform, warp
from torch.utils.data import Dataset, DataLoader
class ImagesDataset(Dataset):
def __init__(self, path_frames, path_landmk, suffix="jpg", crop_size=224, scale=1.25, roation_image=False, use_same_bbox=False, path_same_bbox = None):
'''
path_frames: folder, vpath_image, image path, video path
'''
self.path_frames = Path(path_frames)
self.path_landmk = Path(path_landmk)
self.vpath_image = sorted(self.path_frames.glob(f"*.{suffix}"), key=lambda x: int(x.stem.split("-")[-1]), reverse=False)
print(f'--> total have {len(self.vpath_image)} images, top: \n{self.vpath_image[:3]}')
self.scale = scale # 1.25
self.crop_size = crop_size # 224
self.roation_image =roation_image
self.use_same_bbox = use_same_bbox
if self.use_same_bbox:
self.same_bbox = np.load(path_same_bbox).reshape(-1) # (4,) [left, right, top, bottom]
print(f"same_bbox = {self.same_bbox}")
def bbox2point(self, left, right, top, bottom, type='bbox'):
''' bbox from detector and landmarks are different
'''
if type=='kpt68':
old_size = (right - left + bottom - top) / 2 * 1.1
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top ) / 2.0 ])
elif type=='bbox':
old_size = (right - left + bottom - top)/2
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top ) / 2.0 + old_size*0.12])
else:
raise NotImplementedError
return old_size, center
def __len__(self):
return len(self.vpath_image)
def __getitem__(self, index):
ipath_frame = self.vpath_image[index]
image_name = ipath_frame.stem # (frame-0000)
# print(f"load ipath_frame --> {ipath_frame}")
ipath_ldmk = self.path_landmk.joinpath(image_name + ".txt")
if not ipath_ldmk.exists():
raise Exception(f"ipath_ldmk not exists --> {ipath_ldmk}")
# load orignal image & landmarks
image = cv2.imread(str(ipath_frame)) # (H, W, 3), dtype=uint8
kpt = np.loadtxt(ipath_ldmk) # (68, 2)
if kpt.shape[0] > 68:
# raise Exception(f"cropped_ldmk = {cropped_ldmk.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}")
kpt = kpt[:68, :]
print(f"ERROR: > use first 68-kpts, cropped_ldmk = {kpt.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}")
# reverse H&W
if self.roation_image:
image = image.transpose(1,0,2) # (H, W, 3)
kpt = kpt[:, ::-1] # (68, 2)
if self.use_same_bbox:
left, right = self.same_bbox[0], self.same_bbox[1]
top, bottom = self.same_bbox[2], self.same_bbox[3]
else:
left = np.min(kpt[:,0]); right = np.max(kpt[:,0])
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1])
old_size, center = self.bbox2point(left, right, top, bottom, type='kpt68')
# crop transform
size = int(old_size * self.scale)
src_pts = np.array([[center[0] - size/2, center[1] - size/2], # (left, top)
[center[0] - size/2, center[1] + size/2], # (left, bottom)
[center[0] + size/2, center[1] - size/2]]) # (right, top)
DST_PTS = np.array([[0, 0], # (left-top-corner)
[0, self.crop_size - 1], # (left-botton corner)
[self.crop_size - 1, 0]]) # (right-top corner)
# tform_params dytpe = float64, shape = (3, 3)
tform = estimate_transform('similarity', src_pts, DST_PTS)
# image = image/255.
# (crop_size, crop_size, 3) ,float64
cropped_imag = warp(image, tform.inverse, output_shape=(self.crop_size, self.crop_size)) # scale to (0~1)
cropped_ldmk = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # (68,3)
cropped_ldmk = cropped_ldmk[:, :2]
# cropped_ldmk[:,:2] = cropped_ldmk[:,:2] / self.crop_size * 2 - 1
# cropped_mask = warp(mask, tform.inverse, output_shape=(self.crop_size, self.crop_size)) # scale to (0~1)
# print(f"image dytpe = {image.dtype}, shape = {image.shape} ")
# print(f"cropped_imag dytpe = {cropped_imag.dtype}, shape = {cropped_imag.shape} ")
# print(f"tform_params dytpe = {tform.params.dtype}, shape = {tform.params.shape} ")
# print(f"cropped_ldmk dytpe = {cropped_ldmk.dtype}, shape = {cropped_ldmk.shape}, max={cropped_ldmk.max()}, min={cropped_ldmk.min()} ")
# # print(f"jbatch_ldmks ={cropped_ldmk}")
return {'image_name': ipath_frame.stem,
'image': image,
'cropped_imag': cropped_imag,
'tform_params': tform.params,
'cropped_ldmk': cropped_ldmk,
}
if __name__ == "__main__":
sub_folder = "processing2" # processing, processing2
path_data = Path(f"/ssdata1/lsen/DATA/Actor6/{sub_folder}")
path_same_bbox = f"data/Actor6/max_bbox_{sub_folder}.npy"
vpath_videos = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(vpath_videos)} dir files")
# whole body need roation frame
roation_image = True if sub_folder == "body" else False
print(f"roation_image = {roation_image}")
# IDs = ["2-23min"]
# for each word
for i, ipath_item in enumerate(vpath_videos):
iname = ipath_item.stem
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if iname not in IDs: continue
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
ipath_frame = ipath_item.joinpath("frames")
ipath_fcrop = ipath_item.joinpath("frames_crop_512")
ipath_tfrom = ipath_item.joinpath("frames_crop_tform_512")
ipath_lcrop = ipath_item.joinpath("frames_crop_ldmks_512")
ipath_fcrop.mkdir(parents=True, exist_ok=True)
ipath_tfrom.mkdir(parents=True, exist_ok=True)
ipath_lcrop.mkdir(parents=True, exist_ok=True)
# check have done
num_frame = len(list(ipath_frame.glob("*.jpg")))
num_fcrop = len(list(ipath_fcrop.glob("*.jpg")))
if num_frame == num_fcrop:
print(f"\n Skip: have already done!")
continue
# check landmarks have exists
num_ldmks = len(list(ipath_ldmks.glob("*.txt")))
if num_frame != num_ldmks:
print(f"\n ERROR & Skip: ldmaks = {num_ldmks} != nframes {num_frame}!")
continue
# only whole body image, need set roation_image=True
dataset = ImagesDataset(ipath_frame, ipath_ldmks, suffix="jpg", crop_size=512, scale=1.5,
roation_image=roation_image, use_same_bbox=True, path_same_bbox = path_same_bbox )
dloader = DataLoader(dataset, batch_size=12, num_workers=1, shuffle=False)
print(f"processing crop ... ")
for j, jbatch in enumerate(dloader):
# print(f"jbatch_data shape = {jbatch_data.shape}, path={jbatch_name[:3]}")
if j%100 == 0:
print(f"batching {j}/{len(dloader)} ... ")
jbatch_name = jbatch["image_name"]
jbatch_crop = (255*jbatch["cropped_imag"]).numpy().astype(np.uint8)
jbatch_tfrom = jbatch["tform_params"].numpy()
jbatch_ldmks = jbatch["cropped_ldmk"].numpy()
# print(f"jbatch_crop dytpe = {jbatch_crop.dtype}, shape = {jbatch_crop.shape} ")
# print(f"jbatch_tfrom dytpe = {jbatch_tfrom.dtype}, shape = {jbatch_tfrom.shape} ")
# print(f"jbatch_ldmks dytpe = {jbatch_ldmks.dtype}, shape = {jbatch_ldmks.shape}, max={jbatch_ldmks.max()}, min={jbatch_ldmks.min()} ")
# save data
for k,kname in enumerate(jbatch_name):
kpath_fcrop = ipath_fcrop.joinpath(kname + ".jpg")
kpath_tfrom = ipath_tfrom.joinpath(kname + ".npy")
kpath_lcrop = ipath_lcrop.joinpath(kname + ".txt")
if kpath_fcrop.exists() and kpath_tfrom.exists() and kpath_lcrop.exists():
continue
np.save(kpath_tfrom, jbatch_tfrom[k])
np.savetxt(kpath_lcrop, jbatch_ldmks[k], fmt=" %3d")
cv2.imwrite(str(kpath_fcrop), jbatch_crop[k])
# cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_{vis_name}.jpg")), img)
# break
+31
View File
@@ -0,0 +1,31 @@
import os
from pathlib2 import Path
if __name__ == "__main__":
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
vpath_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(vpath_videos)} dir files")
# IDs = ["2-23min"]
# for each word
for i, ipath_item in enumerate(vpath_videos):
iname = ipath_item.stem
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if iname not in IDs: continue
ipath_fcrop = ipath_item.joinpath("frames_crop")
ipath_tfrom = ipath_item.joinpath("frames_crop_tform")
if ipath_fcrop.exists():
cmd = f"rm -rf {str(ipath_fcrop)}"
print("RUN: ", cmd)
os.system(cmd)
if ipath_tfrom.exists():
cmd = f"rm -rf {str(ipath_tfrom)}"
print("RUN: ", cmd)
os.system(cmd)
+111
View File
@@ -0,0 +1,111 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib import Path
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
def load_mask(j, path_parse):
parsing_anno = np.load(path_parse) # (512, 512)
mask = np.zeros_like(parsing_anno).astype(np.uint8) # (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']
# atts_selected = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'l_ear', 'r_ear', 'ear_r',
# 'nose', 'mouth', 'u_lip', 'l_lip', ]
atts_selected = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'nose', 'mouth', 'u_lip', 'l_lip']
class_contains = np.unique(parsing_anno)
if j % 1000 == 0:
logger.info(f"\t the {j:06d}-th frame, class_contains = {class_contains}")
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
if __name__ == "__main__":
actor = "Actor6"
sub_folder = "processing2" # smile, processing, processing2
# logger
logger = Logger(f"./data/{actor}", postfix=f"generate-mask-{sub_folder}")
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
logger.info(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_parse = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
logger.info(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
ipath_frame = ipath_data.joinpath("frames")
ipath_parse = ipath_data.joinpath("frames_crop_parse_512")
ipath_parse_skin = ipath_data.joinpath("frames_crop_parse_skin_512")
ipath_parse_skin.mkdir(parents=True, exist_ok=True)
# if ipath_save_parse.exists():
# logger.info(f"ipath_save_exp have already save > {ipath_save_parse}")
# continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info["nframes"]
logger.info(f"info = {info}, duration ={nframes / fps / 60}")
# check equal
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_parse = list(ipath_parse.glob("*.npy"))
logger.info(f"vframe_frame len = {len(vframe_frame)}, vframe_parse={len(vframe_parse)}")
duration_frame += len(vframe_frame) / 50 / 60
duration_parse += len(vframe_parse) / 50 / 60
logger.info(f"add duration_frame = {duration_frame} min, duration_parse={duration_parse} min")
if len(vframe_frame) != nframes:
logger.info(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
continue
# check have done
# vframe_parse = list(ipath_parse_skin.glob("*.npy"))
# if len(vframe_parse) == nframes:
# logger.info(f"ipath_parse_skin have already done!")
# continue
# feat_parse = []
for j in range(len(vframe_frame)):
jpath_parse = ipath_parse.joinpath(f"frame-{j:06d}.npy")
jpath_parse_save = ipath_parse_skin.joinpath(f"frame-{j:06d}.npy")
if not jpath_parse.exists():
logger.info(f"\n ERROR: Path NOT FOUND! -> {jpath_parse}")
break
data_mask = load_mask(j, jpath_parse) # (512, 512)
np.save(jpath_parse_save, data_mask)
# feat_parse.append(data_mask)
@@ -0,0 +1,158 @@
import os, sys
import numpy as np
import cv2
from time import time
import argparse
import json
from pathlib import Path
from torch.utils.data import DataLoader
sys.path.insert(0, '/ssdata1/lsen/CODE/DECA_old')
from decalib.deca import DECA
from decalib.datasets.datasets2 import ObamaData
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
def main(args):
# device = args.device
device = "cuda:9"
# run DECA
deca_cfg.model.use_tex = args.useTex
deca = DECA(config = deca_cfg, device=device)
# path_data = Path("/yrfs/lsen/DATA/TestData/processing")
path_data = Path("/ssdata1/lsen/DATA/Actor6/processing2")
v_dir_videos = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_dir_videos)} dir files")
# IDs = ["actor-2HD", "actor-3HD"]
# IDs = ["clip_full"]
# for each video
for i, ipath_data in enumerate(v_dir_videos):
ivideo_name = ipath_data.stem
print(f"\n processing {i}/{len(v_dir_videos)} ...", ivideo_name)
# if ivideo_name not in IDs: continue
# if i > 25: break
# if ivideo_name not in ["4R3A0139"]: continue
ipath_infor = ipath_data.joinpath("video/info.json")
# ipath_frame = ipath_data.joinpath("frames")
ipath_frame = ipath_data.joinpath("frames_crop_512")
# ipath_kpt2d = ipath_data.joinpath("DECA_kpt2d")
# ipath_kpt3d = ipath_data.joinpath("DECA_kpt3d")
ipath_coeff = ipath_data.joinpath("deca_coeff_512")
# ipath_vis = ipath_data.joinpath("DECA_vis2")
# ipath_kpt2d.mkdir(parents=True, exist_ok=True)
# ipath_kpt3d.mkdir(parents=True, exist_ok=True)
ipath_coeff.mkdir(parents=True, exist_ok=True)
# ipath_vis.mkdir(parents=True, exist_ok=True)
# load video info
if not ipath_infor.exists():
print(f"\n ERROR: info.json not existing {ipath_infor}")
continue
with open(str(ipath_infor), "r") as f:
info = json.load(f)
nframes = info['nframes']
nframe_real = len(list(ipath_frame.glob("*.jpg")))
if nframe_real != nframes:
print(f"\n ERROR: nframe_real ={nframe_real} / nframe_info ={nframes}")
continue
# check if finish
nkpt2d = len(list(ipath_coeff.glob("*.npy")))
if nkpt2d + 10 > nframes:
print(f"Have finised before, nkpt2d={nkpt2d} nframes = {nframes}")
continue
datatest = ObamaData(ipath_frame, iscrop=args.iscrop, face_detector=args.detector, device=device)
dataloader = DataLoader(datatest, batch_size=128, shuffle=False, drop_last=False)
for i, ibatch_data in enumerate(dataloader):
batch_names = ibatch_data["names"]
batch_image = ibatch_data["image"].to(device)
if i%10 == 0:
print(f"batch {i:04}/{len(dataloader)}... name = ", batch_names[:5])
codedict = deca.encode(batch_image) # encoder
# opdict, visdict = deca.decode(codedict, batch_image) # decoder
for j, jname in enumerate(batch_names):
# jpath_kpt2d = ipath_kpt2d.joinpath(f"{jname}.txt")
# jpath_kpt3d = ipath_kpt3d.joinpath(f"{jname}.txt")
jpath_coeff = ipath_coeff.joinpath(f"{jname}.json")
# np.savetxt(jpath_kpt2d, opdict['landmarks2d'][j].cpu().numpy(), fmt="%.6f")
# np.savetxt(jpath_kpt3d, opdict['landmarks3d'][j].cpu().numpy(), fmt="%.6f")
# save coeff
jcodedict = {}
for key, value in codedict.items():
jcodedict[key] = value[j].cpu().numpy()
# print("json = ", jcodedict)
np.save(jpath_coeff, jcodedict)
# # save render
# render_names = ['inputs', 'rendered_images']
# # render_names = ['inputs', 'rendered_images', 'albedo_images', 'shape_images', 'shape_detail_images']
# for vis_name in render_names:
# if vis_name not in visdict.keys():
# continue
# img = util.tensor2image(visdict[vis_name][j])
# cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_{vis_name}.jpg")), img)
# save vis
# cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_vis.jpg")), deca.visualize(visdict))
# break
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='DECA: Detailed Expression Capture and Animation')
parser.add_argument('-i', '--inputpath', default='TestSamples/examples', type=str,
help='path to the test data, can be image folder, image path, image list, video')
parser.add_argument('-d', '--device', default='cuda:0', type=str,
help='set device, cpu for using cpu' )
# process test images
parser.add_argument('--iscrop', default=True, type=lambda x: x.lower() in ['true', '1'],
help='whether to crop input image, set false only when the test image are well cropped' )
parser.add_argument('--detector', default='fan', type=str,
help='detector for cropping face, check decalib/detectors.py for details' )
# save
parser.add_argument('--useTex', default=True, type=lambda x: x.lower() in ['true', '1'],
help='whether to use FLAME texture model to generate uv texture map, \
set it to True only if you downloaded texture model' )
parser.add_argument('--saveVis', default=True, type=lambda x: x.lower() in ['true', '1'],
help='whether to save visualization of output' )
parser.add_argument('--saveKpt', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save 2D and 3D keypoints' )
parser.add_argument('--saveDepth', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save depth image' )
parser.add_argument('--saveObj', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save outputs as .obj, detail mesh will end with _detail.obj. \
Note that saving objs could be slow' )
parser.add_argument('--saveMat', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save outputs as .mat' )
parser.add_argument('--saveImages', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save visualization output as seperate images' )
main(parser.parse_args())
+109
View File
@@ -0,0 +1,109 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib import Path
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
if __name__ == "__main__":
actor = "Actor6"
sub_folder = "processing2" # smile, processing, processing2
# logger
logger = Logger(f"./data/{actor}", postfix=f"feature-3dmm-{sub_folder}")
# path data
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
logger.info(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_coeff = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
logger.info(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
# ipath_coeff = ipath_data.joinpath("DECA_coeff")
ipath_coeff = ipath_data.joinpath("deca_coeff_512")
ipath_frame = ipath_data.joinpath("frames")
ipath_save_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_save_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
ipath_save_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info["nframes"]
logger.info(f"info = {info}, duration ={nframes / fps / 60}")
# check
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_coeff = list(ipath_coeff.glob("*.npy"))
logger.info(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
duration_frame += len(vframe_frame) / 50 / 60
duration_coeff += len(vframe_coeff) / 50 / 60
logger.info(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min")
if len(vframe_frame) != nframes:
logger.info(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
continue
if len(vframe_coeff)+1 < nframes:
logger.info(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}")
continue
if ipath_save_exp.exists() and ipath_save_pos.exists():
logger.info(f"ipath_save_exp have already save > {ipath_save_exp}")
continue
feat_exp = []
feat_pos = []
feat_idn = []
for j in range(len(vframe_frame)):
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:06d}.json.npy")
if not jpath_coeff.exists():
logger.info(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}")
break
data_coeff = np.load(jpath_coeff, allow_pickle=True).item()
feat_exp.append(data_coeff["exp"])
feat_pos.append(data_coeff["pose"])
feat_idn.append(data_coeff["shape"])
# save
feat_exp = np.array(feat_exp) # (nframe_trim, 50)
feat_pos = np.array(feat_pos) # (nframe_trim, 6)
feat_idn = np.array(feat_idn) # (nframe_trim, 100)
# # pad one
# feat_exp = np.pad(feat_exp, ((0,1),(0,0)), mode="edge")
# feat_pos = np.pad(feat_pos, ((0,1),(0,0)), mode="edge")
# feat_idn = np.pad(feat_idn, ((0,1),(0,0)), mode="edge")
if nframes == feat_idn.shape[0]:
np.save(ipath_save_exp, feat_exp)
np.save(ipath_save_pos, feat_pos)
np.save(ipath_save_idn, feat_idn)
logger.info(f"SAVE OK! exp shape = {feat_exp.shape},pos = {feat_pos.shape}, idn={feat_idn.shape} nframe={nframes}\n save to -> {ipath_save_exp}") # (nframe, 68, 2)
else:
logger.info("ERROR, skip! ")
+103
View File
@@ -0,0 +1,103 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib import Path
from scipy.signal import savgol_filter
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
if __name__ == "__main__":
actor = "Actor6"
sub_folder = "processing2" # smile, processing, processing2
# logger
logger = Logger(f"./data/{actor}", postfix=f"concat-coeff-{sub_folder}")
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_coeff = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
# ipath_coeff = ipath_data.joinpath("DECA_coeff")
ipath_coeff = ipath_data.joinpath("deca_coeff_512")
ipath_frame = ipath_data.joinpath("frames")
ipath_save_coeff = ipath_data.joinpath("audio/feat_deca_coeff_512p.npy")
# if ipath_save_coeff.exists():
# print(f"ipath_save_exp have already save > {ipath_save_coeff}")
# continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info["nframes"]
print(f"info = {info}, duration ={nframes / fps / 60}")
# check
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_coeff = list(ipath_coeff.glob("*.npy"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
duration_frame += len(vframe_frame) / 50 / 60
duration_coeff += len(vframe_coeff) / 50 / 60
print(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min")
if len(vframe_frame) != nframes:
print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
continue
if len(vframe_coeff)+1 < nframes:
print(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}")
continue
feat_coeff = []
params = ['shape', 'tex', 'exp', 'pose', 'cam', 'light']
for j in range(len(vframe_frame)):
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:06d}.json.npy")
if not jpath_coeff.exists():
print(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}")
break
codedict = np.load(jpath_coeff, allow_pickle=True).item()
# 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 !"
feat_coeff.append(np.array(coeff))
# concate
feat_coeff = np.array(feat_coeff) # (N, 236)
# smooth it
feat_coeff = savgol_filter(feat_coeff, window_length=5, polyorder=3, axis=0, mode='nearest')
if nframes == feat_coeff.shape[0]:
np.save(ipath_save_coeff, feat_coeff)
print(f"SAVE OK! feat shape = {feat_coeff.shape}, nframe={nframes}\n save to -> {ipath_save_coeff}") # (nframe, 68, 2)
else:
print("ERROR, skip! ")
+91
View File
@@ -0,0 +1,91 @@
import numpy as np
from pathlib import Path
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
if __name__ == "__main__":
# fid = "Bringing-Our-Workplace-Policies-into-the-21st-Century"
# fid = "4R3A0071"
actor= "Actor6"
sub_folder = "processing2" # processing, smile, body
fid = '4R3A0139'
# logger
logger = Logger(f"./data/{actor}", postfix=f"mean-coeff-{sub_folder}")
# data
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}/{fid}")
path_save = Path(f"./data/{actor}/mean_deca_coeff_{actor}_{sub_folder}.npy")
path_save.parent.mkdir(parents=True, exist_ok=True)
# path_coeff = path_data.joinpath("DECA_coeff")
path_coeff = path_data.joinpath("deca_coeff_512")
vpath_coeff = sorted(path_coeff.glob("*.npy"), reverse=False)
logger.info(f"Have {len(vpath_coeff)} frames")
feat_shape = []
feat_tex = []
feat_cam = []
feat_exp = []
feat_pos = []
feat_light = []
feat_detail = []
for i, ipath_coeff in enumerate(vpath_coeff):
if i > 2000: break
data_coeff = np.load(ipath_coeff, allow_pickle=True).item()
feat_exp.append(data_coeff["exp"])
feat_pos.append(data_coeff["pose"])
feat_tex.append(data_coeff["tex"])
feat_cam.append(data_coeff["cam"])
feat_light.append(data_coeff["light"])
feat_detail.append(data_coeff["detail"])
feat_shape.append(data_coeff["shape"])
# save
feat_exp = np.array(feat_exp) # (nframe_trim, 50)
feat_pos = np.array(feat_pos) # (nframe_trim, 6)
feat_tex = np.array(feat_tex) # (nframe_trim, 50)
feat_cam = np.array(feat_cam) # (nframe_trim, 6)
feat_light = np.array(feat_light) # (nframe_trim, 50)
feat_detail = np.array(feat_detail) # (nframe_trim, 6)
feat_shape = np.array(feat_shape) # (nframe_trim, 50)
mean_exp = feat_exp.mean(axis=0)
mean_pos = feat_pos.mean(axis=0)
mean_tex = feat_tex.mean(axis=0)
mean_cam = feat_cam.mean(axis=0)
mean_light = feat_light.mean(axis=0)
mean_detail = feat_detail.mean(axis=0)
mean_shape = feat_shape.mean(axis=0)
logger.info(f"feat_exp shape = {feat_exp.shape}, mean = {mean_exp.shape}, \n{mean_exp}")
logger.info(f"mean_pos shape = {feat_pos.shape}, mean = {mean_pos.shape}, \n{mean_pos}")
logger.info(f"mean_tex shape = {feat_tex.shape}, mean = {mean_tex.shape}, \n{mean_tex}")
logger.info(f"mean_cam shape = {feat_cam.shape}, mean = {mean_cam.shape}, \n{mean_cam}")
logger.info(f"mean_light shape = {feat_light.shape}, mean = {mean_light.shape}, \n{mean_light}")
logger.info(f"mean_detail shape = {feat_detail.shape}, mean = {mean_detail.shape}, \n{mean_detail}")
logger.info(f"mean_shape shape = {feat_shape.shape}, mean = {mean_shape.shape}, \n{mean_shape}")
# save
mean_DECA = {
"exp": mean_exp, # (50, )
"pose": mean_pos, # (6, )
"tex": mean_tex, # (50, )
"cam": mean_cam, # (3, )
"light": mean_light, # (9, 3)
"detail": mean_detail,# (128, )
"shape": mean_shape, # (100, )
}
logger.info(f"mean deca = \n {mean_DECA}")
np.save(path_save, mean_DECA)
logger.info(f"save to --> {path_save}")
@@ -0,0 +1,174 @@
import json
import numpy as np
from pathlib2 import Path
import torchaudio
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
if __name__ == "__main__":
actor= "Actor6"
sub_folder = "processing2" # processing, smile, body
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
path_save = Path(f'data/{actor}/{actor}-raw-{sub_folder}-1h')
path_save.mkdir(parents=True, exist_ok=True)
# set logging
logger = Logger(path_save, postfix=f"train-audio2mesh-{sub_folder}")
# get files
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
logger.info(f"Have {len(v_dir_videos)} dir files")
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
vids = set([ipath.stem for ipath in v_dir_videos])
# logger.info(f"vids total= {vids}")
# training set
if sub_folder == "processing2":
vid_test = set(["4R3A0139", "4R3A0140"])
vid_valid = set(["4R3A0139", "4R3A0140"])
vid_train = vids - vid_test - vid_valid
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
logger.info(f"vid train= {vid_train}")
else:
vid_test = set(["4R3A0110", "4R3A0112", "4R3A0113"])
vid_valid = set(["4R3A0110", "4R3A0112", "4R3A0113"])
vid_train = vids - vid_test - vid_valid
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
logger.info(f"vid train= {vid_train}")
# for each video
data_train, data_valid, data_test = {}, {}, {}
list_train, list_valid, list_test = [], [], []
durations_train, durations_valid, durations_test = 0, 0, 0
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
# if vid not in vids: continue
# if vid in vid_test: continue
# if vid in vid_valid:continue
# if durations_train / 3600 > 6: break
logger.info(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
ipath_feat_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
ipath_speech = ipath_data.joinpath("audio/audio_trim.wav")
# check existing
if not ipath_speech.exists():
logger.info(f"NOT existing {ipath_speech}")
continue
if not ipath_feat_exp.exists():
logger.info(f"NOT existing {ipath_feat_exp}")
continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info['nframes']
logger.info(f"info={info}, duration = {nframes/fps}")
assert fps == 50, "fps should be 50"
# laod motion
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 6)
data_idn = np.load(ipath_feat_idn) # (nframe, 100)
assert data_exp.shape[0] == data_pos.shape[0], f"data_exp shape={data_exp.shape}, data_pos shape={data_pos.shape}"
assert data_exp.shape[0] == data_idn.shape[0], f"data_exp shape={data_exp.shape}, data_idn shape={data_idn.shape}"
data_pos_head = data_pos[:, :3] # (nframe, 3)
data_pos_lips = data_pos[:, 3:] # (nframe, 3)
data_motion = np.concatenate([data_exp, data_pos_lips], axis=1) # (nframe, 53) --> fps=30
logger.info(f"motion = {data_motion.shape}")
# load raw audio
audio_raw, sample_rate = torchaudio.load(ipath_speech)
logger.info(f"audio_raw shape = {audio_raw.shape}, sr = {sample_rate}, duration = {(len(audio_raw[0])/sample_rate)}")
if len(audio_raw.shape) == 2:
audio_raw = audio_raw[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
audio_raw = resampler(audio_raw).squeeze().numpy()
logger.info(f"audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
# ####################################
# # clips 4min
# nclip = 4
# nframes = nclip * 60 * 50 # min * 60s * fps
# nsegmts = nclip * 60 * 16000 # min * 60s * sr
# data_motion = data_motion[:nframes]
# audio_raw = audio_raw[:nsegmts]
# data_idn = data_idn[:nframes]
# ####################################
if vid in vid_train:
durations_train += nframes/fps
list_train.append(vid)
data_train[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
if vid in vid_valid:
durations_valid += nframes/fps
list_valid.append(vid)
data_valid[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
if vid in vid_test:
durations_test += nframes/fps
list_test.append(vid)
data_test[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
logger.info(f"Total frames: data_train ({durations_train/60:.2f} min) ({durations_train/3600:.2f} h) , ids = ({len(data_train)})")
logger.info(f"Total frames: data_valid ({durations_valid/60:.2f} min) ({durations_valid/3600:.2f} h) , ids = ({len(data_valid)})")
logger.info(f"Total frames: data_test ({durations_test/60:.2f} min) ({durations_test/3600:.2f} h) , ids = ({len(data_test)})")
logger.info(f"actual train ID: > {list_train} ")
logger.info(f"actual valid ID: > {list_valid} ")
logger.info(f"actual test ID: > {list_test} ")
np.savez(path_save.joinpath("data_train.npz"), data=data_train)
np.savez(path_save.joinpath("data_valid.npz"), data=data_valid)
np.savez(path_save.joinpath("data_test.npz"), data=data_test)
logger.info(f"--> {path_save}")
@@ -0,0 +1,154 @@
import json
from loguru import logger
import numpy as np
from pathlib2 import Path
import torchaudio
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
if __name__ == "__main__":
actor= "Actor6"
sub_folder = "processing2" # processing, smile, body
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
path_save = Path(f'data/{actor}/data-render-{sub_folder}-1h')
path_save.mkdir(parents=True, exist_ok=True)
# set logging
logger = Logger(path_save, postfix=f"train-list-{sub_folder}")
# get files
v_dir_videos = sorted(path_data.glob("*"))
logger.info(f"Have {len(v_dir_videos)} dir files")
vids = set([ipath.stem for ipath in v_dir_videos])
logger.info(f"vids total= {vids}")
# # # actor5 raw
# vid_test = set(["4R3A0063", "4R3A0071"])
# vid_valid = set(["4R3A0063", "4R3A0071"])
# vid_train = vids - vid_test - vid_valid
# actor5 smile
if sub_folder == "processing2":
vid_test = set(["4R3A0139", "4R3A0140"])
vid_valid = set(["4R3A0139", "4R3A0140"])
vid_train = vids - vid_test - vid_valid
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
logger.info(f"vid train= {vid_train}")
else:
vid_test = set(["4R3A0110", "4R3A0112", "4R3A0113"])
vid_valid = set(["4R3A0110", "4R3A0112", "4R3A0113"])
vid_train = vids - vid_test - vid_valid
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
logger.info(f"vid train= {vid_train}")
# for each video
data_train, data_valid, data_test = {}, {}, {}
list_train, list_valid, list_test = [], [], []
durations_train, durations_valid, durations_test = 0, 0, 0
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
# if vid not in vids: continue
# if vid in vid_test: continue
# if vid in vid_valid:continue
# if durations_train / 3600 > 6: break
logger.info(f"\n\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
# ipath_coeff = ipath_data.joinpath("DECA_coeff") # DECA coeff of shape/exp/light
ipath_coeff = ipath_data.joinpath("deca_coeff_512") # DECA coeff of shape/exp/light
ipath_frame = ipath_data.joinpath("frames_crop_512") # cropped image 512x512
ipath_ldmks = ipath_data.joinpath("frames_crop_ldmks_512") # cropped landmarks within 512x512
ipath_parse = ipath_data.joinpath("frames_crop_parse_skin_512") # cropped mask
# check info existing
if not ipath_info.exists():
logger.info(f"NOT existing {ipath_info}")
continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info['nframes']
assert fps == 50, "fps should be 50"
logger.info(f"info={info}, duration = {nframes/fps}")
# check files total exists
num_coeff = len(list(ipath_coeff.glob("*.npy")))
num_frame = len(list(ipath_frame.glob("*.jpg")))
num_ldmks = len(list(ipath_ldmks.glob("*.txt")))
num_parse = len(list(ipath_parse.glob("*.npy")))
if (num_coeff != nframes) or (num_frame != nframes) or (num_ldmks != nframes) or (num_parse != nframes):
logger.info(f"num of ipath_coeff ({num_coeff}) shoud be {nframes} > {ipath_coeff}")
logger.info(f"num of ipath_frame ({num_frame}) shoud be {nframes} > {ipath_frame}")
logger.info(f"num of ipath_ldmks ({num_ldmks}) shoud be {nframes} > {ipath_ldmks}")
logger.info(f"num of ipath_parse ({num_parse}) shoud be {nframes} > {ipath_parse}")
continue
# load coeff
# ipath_feat_coeff = ipath_data.joinpath("audio/feat_DECA_trim.npy")
ipath_feat_coeff = ipath_data.joinpath("audio/feat_deca_coeff_512p.npy")
data_coeff = np.load(ipath_feat_coeff) # (nframe, 236)
data_coeff = data_coeff.astype(np.float16) # convert float16
if vid in vid_train:
durations_train += nframes/fps
list_train.append(vid)
data_train[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"path_data": str(ipath_data),
"data_coeff": data_coeff
}
if vid in vid_valid:
durations_valid += nframes/fps
list_valid.append(vid)
data_valid[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"path_data": str(ipath_data),
"data_coeff": data_coeff
}
if vid in vid_test:
durations_test += nframes/fps
list_test.append(vid)
data_test[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"path_data": str(ipath_data),
"data_coeff": data_coeff
}
logger.info(f"Total frames: data_train ({durations_train/60:.2f} min) ({durations_train/3600:.2f} h) , ids = ({len(data_train)})")
logger.info(f"Total frames: data_valid ({durations_valid/60:.2f} min) ({durations_valid/3600:.2f} h) , ids = ({len(data_valid)})")
logger.info(f"Total frames: data_test ({durations_test/60:.2f} min) ({durations_test/3600:.2f} h) , ids = ({len(data_test)})")
logger.info(f"actual train ID: > {list_train} ")
logger.info(f"actual valid ID: > {list_valid} ")
logger.info(f"actual test ID: > {list_test} ")
np.savez(path_save.joinpath("data_train.npz"), data=data_train)
np.savez(path_save.joinpath("data_valid.npz"), data=data_valid)
np.savez(path_save.joinpath("data_test.npz"), data=data_test)
logger.info(f"--> {path_save}")
+85
View File
@@ -0,0 +1,85 @@
import os
import cv2
import logging
import datetime
from tqdm import tqdm
from sys import getsizeof, stderr
from itertools import chain
from collections import deque
from reprlib import repr
logging.basicConfig(filename=f"{datetime.datetime.now().strftime('%Y%m%d-%HH%MM%SS')}-test-load-image",
format='[%(asctime)s][%(levelname)s] %(message)s',
level=logging.INFO)
def load_images(input_path, num_frame):
images = []
for i in tqdm(range(num_frame)):
iframe = i%2000
image = cv2.imread(os.path.join(input_path, '%05d.png' % iframe))
images.append(image)
# option - 1 (del images)
# del images[0]
# option - 2 (writer image)
# cv2.imwrite("temp.jpg", image)
if i%100 == 0:
# logging.info(f"iter={i:06d}, [only append], images memory addr=0x{id(images):08x}, size={total_size(images)/1024/1024:0.2f} MB")
# logging.info(f"iter={i:06d}, [append + del images[0]], images memory addr=0x{id(images):08x}, size={total_size(images)/1024/1024:0.2f} MB")
logging.info(f"iter={i:06d}, [append + write], images memory addr=0x{id(images):08x}, size={total_size(images)/1024/1024:0.2f} MB")
return images
def total_size(o, handlers={}, verbose=False):
""" Returns the approximate memory footprint an object and all of its contents.
Automatically finds the contents of the following builtin containers and
their subclasses: tuple, list, deque, dict, set and frozenset.
To search other containers, add handlers to iterate over their contents:
handlers = {SomeContainerClass: iter,
OtherContainerClass: OtherContainerClass.get_elements}
"""
dict_handler = lambda d: chain.from_iterable(d.items())
all_handlers = {tuple: iter,
list: iter,
deque: iter,
dict: dict_handler,
set: iter,
frozenset: iter,
}
all_handlers.update(handlers) # user handlers take precedence
seen = set() # track which object id's have already been seen
default_size = getsizeof(0) # estimate sizeof object without __sizeof__
def sizeof(o):
if id(o) in seen: # do not double count the same object
return 0
seen.add(id(o))
s = getsizeof(o, default_size)
if verbose:
print(s, type(o), repr(o), file=stderr)
for typ, handler in all_handlers.items():
if isinstance(o, typ):
s += sum(map(sizeof, handler(o)))
break
return s
return sizeof(o)
bg = load_images('/ssdata2/chenfeng/data/render/a5/t01/0-ori/ori_frames', 100000)
+2 -1
View File
@@ -245,8 +245,8 @@ class SRenderY(nn.Module):
albedos = albedos.reshape(-1, albedos.shape[-3], albedos.shape[-2], albedos.shape[-1]) # (..., 3, h, w) 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) lights = lights.reshape(-1, lights.shape[-2], lights.shape[-1]) # (..., nfeat1, nfeat2)
batch_size = vertices.shape[0] batch_size = vertices.shape[0]
## rasterizer near 0 far 100. move mesh so minz larger than 0 ## rasterizer near 0 far 100. move mesh so minz larger than 0
transformed_vertices[:,:,2] = transformed_vertices[:,:,2] + 10 transformed_vertices[:,:,2] = transformed_vertices[:,:,2] + 10
# attributes # attributes
@@ -254,6 +254,7 @@ class SRenderY(nn.Module):
normals = util.vertex_normals(vertices, self.faces.expand(batch_size, -1, -1)); face_normals = util.face_vertices(normals, self.faces.expand(batch_size, -1, -1)) normals = util.vertex_normals(vertices, self.faces.expand(batch_size, -1, -1)); face_normals = util.face_vertices(normals, self.faces.expand(batch_size, -1, -1))
transformed_normals = util.vertex_normals(transformed_vertices, self.faces.expand(batch_size, -1, -1)); transformed_face_normals = util.face_vertices(transformed_normals, self.faces.expand(batch_size, -1, -1)) transformed_normals = util.vertex_normals(transformed_vertices, self.faces.expand(batch_size, -1, -1)); transformed_face_normals = util.face_vertices(transformed_normals, self.faces.expand(batch_size, -1, -1))
attributes = torch.cat([self.face_uvcoords.expand(batch_size, -1, -1, -1), attributes = torch.cat([self.face_uvcoords.expand(batch_size, -1, -1, -1),
transformed_face_normals.detach(), transformed_face_normals.detach(),
face_vertices.detach(), face_vertices.detach(),
+464
View File
@@ -0,0 +1,464 @@
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from pathlib import Path
from src.models import init_net
from src.models.base import Base
from src.optims import get_optimizer, get_scheduler
# common
from common.animation import save_animation_with_gt2, save_images_with_audio
from common.debug import debug
from common.losses import WingLoss
# disentangle model
class Audio2motionLive3Model(Base):
def __init__(self, opt, logger):
Base.__init__(self, opt, logger)
self.opt = opt
self.logger = logger
self.names_model = ["G"] # G
# define networks
self.netG = define_netG(opt)
self.netG.to()
self.netG = torch.nn.DataParallel(self.netG, opt.GPUS) # multi-GPUs
init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS)
self.loss_func_l1 = nn.L1Loss(reduction="mean")
self.loss_func_wing = WingLoss(reduction="mean")
if self.isTrain:
self.names_loss = opt.LOSS.names
# define optimizers
self.optimizer_G = get_optimizer(self.netG, opt)
self.optimizers.append(self.optimizer_G)
self.scheduler_G = get_scheduler(self.optimizer_G, opt)
self.schedulers.append(self.scheduler_G)
if self.opt.TRAIN.apply_testing or not self.isTrain:
# load mean lighting & shape
self.netR, self.flame = define_netR(device=self.device)
# self.netG.init_reconstruct_model(self.netR)
path_deca_mean = Path("./data/DECA_obama_mean.npy")
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
print(self.mean_dict.keys())
if self.opt.DATASET.speech_extractor == "wav2vec":
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
print("load Wav2Vec2Model ...")
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
def set_input(self, batch_input):
# motion data
self.data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion)
self.batch_vid = batch_input['vid']
self.batch_nframe = batch_input['nframe']
self.batch_interv = batch_input['frame_interval']
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}", verbose=False)
debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False)
debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False)
debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \
beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
self.B, self.nsteps = self.data.size(0), self.data.size(1)
# speech data
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
if self.opt.DATASET.speech_extractor == "wav2vec":
# raw_speech = raw_speech.reshape(self.B * self.nsteps, -1) # (B*nsteps, nsegments)
# debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
# padding half frame length for bed and end
npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5)
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
debug(self.opt, f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
raw_speech = list(raw_speech)
inputs = self.processor(raw_speech, sampling_rate=16000, return_tensors="pt")
inputs = inputs.to(self.device)
with torch.no_grad():
output = self.extractor(**inputs)
self.cond = output.last_hidden_state
# self.cond = output.extract_features
# B x nsteps x nc_feat
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
debug(self.opt, f"cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
# unfold
# self.data = self.data.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_motion, 16)
# self.data = self.data.permute(0, 1, 3, 2) # (B, nseqs, 16, 53)
self.cond = self.cond.unfold(dimension=1, size=16, step=1) # (nseqs, nc_motion, 16)
self.cond = self.cond.permute(0, 1, 3, 2) # (nseqs, 16, 53)
self.nseq = self.cond.size(1)
self.data = self.data[:, 7:7+self.nseq, :]
debug(self.opt, f"\n a data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
debug(self.opt, f"a cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
def training(self, batch_input):
self.train() # set train model
self.set_input(batch_input)
# forward
self.pred = self.netG(self.cond)
# loss
loss, self.loss_dict = self.eval_losses(self.pred, self.data)
# backward
self.optimizer_G.zero_grad()
loss.backward()
if self.opt.TRAIN.grad_clip_norm: # operate grad
torch.nn.utils.clip_grad_value_(self.netG.parameters(), self.opt.TRAIN.max_grad_clip)
torch.nn.utils.clip_grad_norm_(self.netG.parameters(), self.opt.TRAIN.max_grad_norm)
self.optimizer_G.step()
return loss
def validation(self, batch_input):
self.eval() # set eval model
self.set_input(batch_input)
with torch.no_grad():
self.pred = self.netG(self.cond)
loss, self.loss_dict = self.eval_losses(self.pred, self.data)
return loss
def infer(self, batch_cond, path_audio, suffix=""):
self.eval()
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
with torch.no_grad():
samples_pt = self.netG(self.cond).cpu().numpy() # B x N x dim_motion
print(f"testing pt shape = {samples_pt.shape}")
self.save_reconstruct(samples_pt, path_audio,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix)
# save result
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
np.save(path_save_npy, samples_pt)
print(f"save infer_result shape = {samples_pt.shape} -> {path_save_npy}")
def testing(self, batch_input, cur_epoch=0, cur_batch=0):
self.eval() # set eval model
self.set_input(batch_input)
with torch.no_grad():
samples_pt = self.netG(self.cond).cpu().numpy() # B x N x dim_motion
samples_gt = self.data.cpu().numpy() # B x N x dim_motion
print(f"testing pt shape = {samples_pt.shape}, gt shape = {samples_gt.shape}")
self.save_reconstruct_with_gt(samples_pt, samples_gt,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}')
def get_vertices(self, batch_exp, batch_pos):
"""
batch_exp, (nbatch, seqlen, 50)
batch_pos, (nbatch, seqlen, 3)
"""
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1)
batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50
batch_pos = batch_pos.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3
batch_shape = np.repeat([self.mean_dict["shape"]], nbatch * seqlen, axis=0) # (nbatch * seqlen, 100)
batch_shape= torch.from_numpy(batch_shape).to(self.device)
batch_pose = np.repeat([self.mean_dict["pose"]], nbatch * seqlen, axis=0) # (nbatch * seqlen, 6)
batch_pose = torch.from_numpy(batch_pose).to(self.device)
batch_pose[:, 3:6] = batch_pos
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3
verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
# print(f"verts reshape = {verts.shape}")
return verts
def eval_losses(self, batch_pdt, batch_tgt):
""" Computes the VAE loss function.
pramas:
batch_pred, (nbatch, seqlen, dim_motion)
batch_targt, (nbatch, seqlen, dim_motion)
"""
loss = 0
loss_dict = {}
batch_pdt_exp = batch_pdt[..., :50]
batch_pdt_pos = batch_pdt[..., 50:]
batch_tgt_exp = batch_tgt[..., :50]
batch_tgt_pos = batch_tgt[..., 50:]
# get reconstruction
batch_pdt_geo = self.get_vertices(batch_pdt_exp, batch_pdt_pos) # B x nseq x num_vertices x 3
batch_tgt_geo = self.get_vertices(batch_tgt_exp, batch_tgt_pos) # B x nseq x num_vertices x 3
# rec loss
loss = 0
loss_rec_exp = self.loss_func_wing(batch_pdt_exp, batch_tgt_exp) / 50
loss_dict["loss_rec_exp"] = loss_rec_exp.detach()
loss_rec_pos = self.loss_func_wing(batch_pdt_pos, batch_tgt_pos) / 3
loss_dict["loss_rec_pos"] = loss_rec_pos.detach()
loss += loss_rec_exp * self.opt.LOSS.lambda_rec_exp
loss += loss_rec_pos * self.opt.LOSS.lambda_rec_pos
# rec smooth
diff_pdt_exp = batch_pdt_exp[:, 1:, :] - batch_pdt_exp[:, :-1, :]
diff_tgt_exp = batch_tgt_exp[:, 1:, :] - batch_tgt_exp[:, :-1, :]
loss_vel_exp = self.loss_func_wing(diff_pdt_exp, diff_tgt_exp) / 50
loss_dict["loss_vel_exp"] = loss_vel_exp.detach()
diff_pdt_pos = batch_pdt_pos[:, 1:, :] - batch_pdt_pos[:, :-1, :]
diff_tgt_pos = batch_tgt_pos[:, 1:, :] - batch_tgt_pos[:, :-1, :]
loss_vel_pos = self.loss_func_wing(diff_pdt_pos, diff_tgt_pos) / 3
loss_dict["loss_vel_pos"] = loss_vel_pos.detach()
loss += loss_vel_exp * self.opt.LOSS.lambda_vel_exp
loss += loss_vel_pos * self.opt.LOSS.lambda_vel_pos
# geo rec
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
loss_dict["loss_rec_geo"] = loss_rec_geo.detach()
loss += loss_rec_geo * self.opt.LOSS.lambda_rec_geo
# geo volocity
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo)
loss_dict["loss_vel_geo"] = loss_vel_geo.detach()
loss += loss_vel_geo * self.opt.LOSS.lambda_vel_geo
# total loss
loss_dict['loss_all'] = loss.detach()
return loss, loss_dict
def save_reconstruct(self, samples_pt, path_audio, path_save, suffix=""):
# samples_pt, [B x N x dim_motion]
B, N, _ = samples_pt.shape
nbatch_render = 10
# for each batch
for j in range(B):
jcoeff_pt = samples_pt[j, :, :]
jpath_save = path_save.joinpath(f"{suffix}_{j:02d}.mp4")
v_render_pt = []
for k in range(0, N, nbatch_render):
jcodedict_pt = {}
jcodedict_pt["exp"] = jcoeff_pt[k:k+nbatch_render, :50] # (nbatch_render, 50)
nbatch_real = jcodedict_pt["exp"].shape[0]
# pose
jcodedict_pt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6)
jcodedict_pt["pose"][:, 3:6] = jcoeff_pt[k:k+nbatch_render, 50:53]
# others ==> to mean
mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]]
jcodedict_pt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
jcodedict_pt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
jcodedict_pt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100)
jcodedict_pt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
_, visdict_pt = self.netR.decode_one(jcodedict_pt, nbatch_real, self.device)
render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224)
# print(f"render pt shape = {render_pt.shape}")
for m in range(nbatch_real):
# cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...]))
v_render_pt.append(tensor2image(render_pt[m, ...]))
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}")
save_images_with_audio(v_render_pt, path_audio, jpath_save)
def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""):
# samples_pt, [B x N x dim_motion]
# samples_gt, [B x N x dim_motion]
B, N, _ = samples_pt.shape
nbatch_render = 10
# for each batch
for j in range(B):
jcoeff_pt = samples_pt[j, :, :]
jcoeff_gt = samples_gt[j, :, :]
jpath_save = path_save.joinpath(f"{suffix}_{j:02d}.mp4")
v_render_pt = []
v_render_gt = []
for k in range(0, N, nbatch_render):
jcodedict_pt = {}
jcodedict_gt = {}
# exp
jcodedict_pt["exp"] = jcoeff_pt[k:k+nbatch_render, :50] # (nbatch_render, 50)
jcodedict_gt["exp"] = jcoeff_gt[k:k+nbatch_render, :50] # (nbatch_render, 50)
nbatch_real = jcodedict_pt["exp"].shape[0]
# pose
jcodedict_pt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6)
jcodedict_gt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6)
jcodedict_pt["pose"][:, 3:6] = jcoeff_pt[k:k+nbatch_render, 50:53]
jcodedict_gt["pose"][:, 3:6] = jcoeff_gt[k:k+nbatch_render, 50:53]
# others ==> to mean
mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]]
jcodedict_pt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
jcodedict_pt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
jcodedict_pt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100)
jcodedict_pt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
jcodedict_gt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
jcodedict_gt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
jcodedict_gt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100)
jcodedict_gt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
_, visdict_pt = self.netR.decode_one(jcodedict_pt, nbatch_real, self.device)
_, visdict_gt = self.netR.decode_one(jcodedict_gt, nbatch_real, self.device)
render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224)
render_gt = visdict_gt["shape_images"] # (nbatch_render, 3, 224, 224)
# print(f"render pt shape = {render_pt.shape}, gt {render_gt.shape}")
for m in range(nbatch_real):
# cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...]))
v_render_pt.append(tensor2image(render_pt[m, ...]))
v_render_gt.append(tensor2image(render_gt[m, ...]))
# get audio
jvid = self.batch_vid[j]
jnframe = self.batch_nframe[j].numpy()
jstart_frame = self.batch_interv[0][j].numpy() + 7
jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav"
# jpath_audio = f"/yrfs/lsen/DATA/LuoXData/processing2/{jvid}/audio/audio_trim.wav"
jstart_time = (jstart_frame) / self.opt.DATASET.fps # xxx.yyy min
jend_time = (jstart_frame + self.nseq) / self.opt.DATASET.fps # xxx.yyy min
print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}")
print(f"jstart_time={jstart_time}, jend_time={jend_time}")
# 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, jpath_save, fps=self.opt.DATASET.fps,\
path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time)
#########################################
def tensor2image(tensor):
image = tensor.detach().cpu().numpy()
image = image*255.
image = np.maximum(np.minimum(image, 255), 0)
image = image.transpose(1,2,0)[:,:,[2,1,0]]
return image.astype(np.uint8).copy()
def define_netG(opt):
netG = None
if opt.MODEL.name_netG == "audio2motion_voca4":
from src.nn.audio2motion_voca4 import Audio2MotionVOCA
netG = Audio2MotionVOCA(opt)
elif opt.MODEL.name_netG == "audio2motion_voca":
from src.nn.audio2motion_voca import Audio2MotionVOCA
netG = Audio2MotionVOCA(opt)
elif opt.MODEL.name_netG == "audio2motion_voca34":
from src.nn.audio2motion_voca34 import Audio2MotionVOCA
netG = Audio2MotionVOCA(opt)
elif opt.MODEL.name_netG == "audio2motion_voca33":
from src.nn.audio2motion_voca33 import Audio2MotionVOCA
netG = Audio2MotionVOCA(opt)
elif opt.MODEL.name_netG == "audio2motion":
from src.nn.audio2motion import Audio2Motion
netG = Audio2Motion(opt)
elif opt.MODEL.name_netG == "audio2motion2":
from src.nn.audio2motion2 import Audio2Motion2
netG = Audio2Motion2(opt)
else:
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!")
return netG
def define_netR(device):
# import
from src.nn.FLAME import FLAME
sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old")
from decalib.deca import DECA
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
# use device
# device = "cuda:2"
# whether to use FLAME texture model to generate uv texture map
deca_cfg.model.use_tex = False
deca_cfg.dataset.image_size = 512
# reconstruction model
netR = DECA(config = deca_cfg, device=device)
# flame model
flame = FLAME(deca_cfg.model).to(device)
return netR, flame
+614
View File
@@ -0,0 +1,614 @@
from typing import Any, List
from omegaconf import DictConfig
import numpy as np
import torch
from pytorch_lightning import LightningModule
from torchmetrics import MaxMetric, MeanMetric, MinMetric
import logging
from src.losses import WingLoss
from src.utils.debug import debug
from src.models import init_weights
from src.models.components import flame_mouth_idx
from src.models.components import idx_upper_mouth_68ldmk, idx_lower_mouth_68ldmk
from src.models.components import idx_left_mouth_68ldmk, idx_right_mouth_68ldmk
from src.mesh import util
from src.utils.animation import write_video, write_video_with_gt
class Audio2CoeffModel(LightningModule):
def __init__(
self,
lr: float = 0.001,
weight_decay: float = 0.0005 ,
opt: DictConfig = None,
opt_LOSS: DictConfig = None,
opt_netF: DictConfig = None,
opt_netR: DictConfig = None,
opt_netW: DictConfig = None,
netG: torch.nn.Module = None,
):
super().__init__()
logging.info(f"[__init__] self.device = {self.device}")
# this line allows to access init params with 'self.hparams' attribute
# it also ensures init params will be stored in ckpt
# self.save_hyperparameters(logger=False)
self.lr = lr
self.weight_decay = weight_decay
self.opt = opt
self.opt_LOSS = opt_LOSS
self.netG = netG # load Audio2mesh model
self.netF = self._load_netF(opt_netF) # load FLAME model
self.netR = self._load_netR(opt_netR) # load Render model
self.processor, self.netW = self._load_netW(opt_netW) # load wav2vec model
# 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}")
# load mean
path_deca_mean = self.opt.path_mean_dict
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
# 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_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)
# define
vertices_weight = torch.ones((1, 1, self.opt.num_vertices, 3)).to(self.device)
vertices_weight[:, :, flame_mouth_idx, :] = 10
self.register_buffer("vertices_weight", vertices_weight)
# loss function
self.loss_func_wing = WingLoss(reduction="none") # return (B, )
# use separate metric instance for train, val and test step
# 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()
def _load_netF(self, opt_netF):
from src.mesh.FLAME import FLAME
logging.info("_load_netF, FLAME ...")
model = FLAME(opt_netF)
# set to freeze
for param in model.parameters():
param.requires_grad = False
return model.eval()
def _load_netR(self, opt_netR):
from src.mesh.renderer import SRenderY, set_rasterizer
logging.info("_load_netR, Render ...")
opt_netR.rasterizer_type = opt_netR.rasterizer_type # standard
opt_netR.uv_size = opt_netR.uv_size
opt_netR.image_size = opt_netR.image_size
set_rasterizer(opt_netR.rasterizer_type)
model = SRenderY(opt_netR.image_size,
obj_filename=opt_netR.topology_path,
uv_size=opt_netR.uv_size,
rasterizer_type=opt_netR.rasterizer_type
)
# set to freeze
for param in model.parameters():
param.requires_grad = False
return model.eval()
def _load_netW(self, opt_netW):
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
logging.info("_load_netW, Wav2Vec2Model ...")
# MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
# path_ckpt_wav2vec = "./checkpoints/wav2vec2"
processor = Wav2Vec2FeatureExtractor.from_pretrained(opt_netW.path_ckpt_wav2vec)
extractor = Wav2Vec2Model.from_pretrained(opt_netW.path_ckpt_wav2vec)
# set to freeze
for param in extractor.parameters():
param.requires_grad = False
return processor, extractor.eval()
def on_fit_start(self):
logging.info(f"\n[on_fit_start] self.device = {self.device}")
# self.processor, self.netW = self.define_netP(self.device) # wav2vec 2.0 model
# self.netR = self.define_netR(self.device) # render model
# self.netF = self.define_FLAME(self.device) # FLAME model
def configure_optimizers(self):
"""Choose what optimizers and learning-rate schedulers to use in your optimization.
Normally you'd need one. But in the case of GANs or similar you might have multiple.
See examples here:
https://pytorch-lightning.readthedocs.io/en/latest/common/lightning_module.html#configure-optimizers
"""
# optim = torch.optim.Adam(
# params=self.netG.parameters(), lr=self.lr, weight_decay=self.weight_decay
# )
optim = torch.optim.Adam(
params=filter(lambda p: p.requires_grad, self.netG.parameters()),
lr=self.lr, weight_decay=self.weight_decay
)
# logging.info(f"\n[configure_optimizers] self.device = {self.device}")
return optim
@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)
# batch information
batch_info = {
"vid": batch['vid'],
"nframe": batch['nframe'],
"interv": batch['frame_interval']
}
# 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)
# 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)
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)
# unfold speech data
cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_codit, 16)
cond = cond.permute(0, 1, 3, 2) # (B, nseqs, 16, nc_condit)
# setup
self.B, self.nsteps, self.nwind, self.dim_speech = cond.size()
data = data[:, 7:7+self.nsteps, :] # (B, nseqs, nc_motion)
# self.vert, self.ldmk2d, self.ldmk3d = self.get_vertices(data)
# 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)
# 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)
return cond, data, batch_info
def forward(self, x:torch.Tensor):
return self.netG(x)
def step(self, batch:Any):
batch_x, batch_tgt, batch_info = self.set_input(batch)
batch_pdt = self.forward(batch_x) # (B, N, nc_motion)
loss, loss_dict = self.eval_losses(batch_pdt, batch_tgt)
return loss, loss_dict, batch_pdt, batch_tgt, batch_info
def get_progress_bar_dict(self):
# don't show the version number
items = super().get_progress_bar_dict() # "v_num", "loss"
items.pop("v_num", None)
# logging.info(items)
# return items
# items["test"] = '{:.6f}'.format(items["loss"])
return items
def training_step(self, batch, batch_idx):
loss, loss_dict, *_ = self.step(batch)
# logging.info(f"loss_dict = {loss_dict}")
# log show loss
self.log("train/rec", loss_dict["rec_geo"], on_step=True, on_epoch=False, prog_bar=True)
self.log("train/vel", loss_dict["vel_geo"], on_step=True, on_epoch=False, prog_bar=True)
# # # show metric
# self.log("train/metric_rec", metric_rec, on_step=False, on_epoch=True, prog_bar=True)
# self.log("train/metric_vel", metric_vel, on_step=False, on_epoch=True, prog_bar=True)
return {"loss": loss}
def training_epoch_end(self, outputs: List[Any]):
"""
`outputs` is a list of dicts returned from `training_step()`
"""
pass
def validation_step(self, batch, batch_idx):
loss, loss_dict, *_ = self.step(batch)
# show loss
# self.log("val/total_loss", loss, on_step=False, on_epoch=False, prog_bar=False)
self.log("val/rec", loss_dict["rec_geo"], on_step=True, on_epoch=False, prog_bar=False)
self.log("val/vel", loss_dict["vel_geo"], on_step=True, on_epoch=False, prog_bar=False)
# # # show metric
self.valid_rec(loss_dict["rec_geo"])
self.valid_vel(loss_dict["vel_geo"])
self.val_best(loss)
# self.log("val/metric_rec", metric_rec, on_step=True, on_epoch=True, prog_bar=True)
# self.log("val/metric_vel", metric_vel, on_step=True, on_epoch=True, prog_bar=True)
return {"loss": loss}
# return {"loss": loss, "preds": batch_pdt, "targets": batch_tgt, "info": batch_info}
def validation_epoch_end(self, outputs: List[Any]):
"""
`outputs` is a list of dicts returned from `validation_step()`
"""
self.log("val/rec", self.valid_rec.compute(), on_step=False, on_epoch=True, prog_bar=True)
self.log("val/vel", self.valid_vel.compute(), on_step=False, on_epoch=True, prog_bar=True)
self.log("val/best", self.val_best.compute(), on_epoch=True, prog_bar=True)
def test_step(self, batch, batch_idx):
loss, loss_dict, batch_pdt, batch_tgt, batch_info = self.step(batch)
# update metric
self.test_rec(loss_dict["rec_geo"])
self.test_vel(loss_dict["vel_geo"])
return {"loss": loss}
# return {"batch_pdt": batch_pdt, "batch_tgt": batch_tgt, "batch_info": batch_info}
def test_epoch_end(self, outputs: List[Any]):
"""
`outputs` is a list of dicts returned from `test_step()`
"""
self.log("val/mean_rec", self.test_rec.compute(), on_step=False, on_epoch=True, prog_bar=True)
self.log("val/mean_vel", self.test_vel.compute(), on_step=False, on_epoch=True, prog_bar=True)
def on_epoch_end(self):
# 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):
""" Computes the loss function.
pramas:
batch_tgt, (nbatch, seqlen, dim_motion)
batch_pdt, (nbatch, seqlen, dim_motion)
"""
loss = 0
loss_dict = {}
batch_pdt_exp = batch_pdt[..., :50]
batch_pdt_pos = batch_pdt[..., 50:]
batch_tgt_exp = batch_tgt[..., :50]
batch_tgt_pos = batch_tgt[..., 50:]
# get reconstruction
batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x nseq x num_vertices x 3
batch_tgt_geo, *_ = self.get_vertices(batch_tgt) # B x nseq x num_vertices x 3
# rec loss
# synthesis geo rec
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
loss_dict["rec_geo"] = loss_rec_geo.mean().detach()
loss_rec_geo2 = self.loss_func_wing(batch_pdt, batch_tgt, weight=self.vertices_weight)
# loss_dict["rec_geo_w"] = loss_rec_geo2.mean().detach()
# loss += loss_rec_geo.mean() * self.opt_LOSS.lambda_rec_geo
loss += loss_rec_geo2.mean() * self.opt_LOSS.lambda_rec_geo
# synthesis geo volocity
diff_pdt_geo = batch_pdt[:, 1:, :] - batch_pdt[:, :-1, :]
diff_tgt_geo = batch_tgt[:, 1:, :] - batch_tgt[:, :-1, :]
loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo)
loss_dict["vel_geo"] = loss_vel_geo.mean().detach()
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight)
# loss_dict["vel_geo_w"] = loss_vel_geo2.mean().detach()
# loss += loss_vel_geo.mean() * self.opt_LOSS.lambda_vel_geo
if self.opt_LOSS.lambda_vel_geo > 0:
loss += loss_vel_geo2.mean() * self.opt_LOSS.lambda_vel_geo
# landmarks loss
ldmk3d_pdt = self.netF.seletec_3d68(batch_pdt.reshape(-1, self.opt.num_vertices, 3)) # (B*N, 68, 3)
ldmk3d_tgt = self.netF.seletec_3d68(batch_tgt.reshape(-1, self.opt.num_vertices, 3)) # (B*N, 68, 3)
loss_rec_ldmk = torch.sqrt(((ldmk3d_pdt - ldmk3d_tgt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68)
loss_dict["rec_ldmk"] = loss_rec_ldmk.mean().detach()
if self.opt_LOSS.lambda_rec_ldmk > 0:
loss += loss_rec_ldmk.mean() * self.opt_LOSS.lambda_rec_ldmk
# mouth closure_x loss (left/right mouth)
ldmk3d_pdt_left, ldmk3d_pdt_right = ldmk3d_pdt[:, idx_left_mouth_68ldmk], ldmk3d_pdt[:, idx_right_mouth_68ldmk]
ldmk3d_tgt_left, ldmk3d_tgt_right = ldmk3d_tgt[:, idx_left_mouth_68ldmk], ldmk3d_tgt[:, idx_right_mouth_68ldmk]
diff_pdt_mouth_x = torch.sqrt(((ldmk3d_pdt_left - ldmk3d_pdt_right)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
diff_tgt_mouth_x = torch.sqrt(((ldmk3d_tgt_left - ldmk3d_tgt_right)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
loss_closure_x = (diff_pdt_mouth_x - diff_tgt_mouth_x).abs().mean() # (B*N, 8) ==> (1,)
loss_dict["closure_x"] = loss_closure_x.mean().detach()
if self.opt_LOSS.lambda_closure_x > 0:
loss += loss_closure_x.mean() * self.opt_LOSS.lambda_closure_x
# mouth closure_y loss (upper/lower mouth)
ldmk3d_pdt_upper, ldmk3d_pdt_lower = ldmk3d_pdt[:, idx_upper_mouth_68ldmk], ldmk3d_pdt[:, idx_lower_mouth_68ldmk]
ldmk3d_tgt_upper, ldmk3d_tgt_lower = ldmk3d_tgt[:, idx_upper_mouth_68ldmk], ldmk3d_tgt[:, idx_lower_mouth_68ldmk]
diff_pdt_mouth_y = torch.sqrt(((ldmk3d_pdt_upper - ldmk3d_pdt_lower)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
diff_tgt_mouth_y = torch.sqrt(((ldmk3d_tgt_upper - ldmk3d_tgt_lower)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
loss_closure_y = (diff_pdt_mouth_y - diff_tgt_mouth_y).abs().mean() # (B*N, 8) ==> (1,)
loss_dict["closure_y"] = loss_closure_y.mean().detach()
if self.opt_LOSS.lambda_closure_y > 0:
loss += loss_closure_y.mean() * self.opt_LOSS.lambda_closure_y
# total loss
loss_dict["all"] = loss.detach()
return loss, loss_dict
@torch.no_grad()
def get_template_vertices(self, mean_dict=None):
batch_exp = torch.zeros(1, 50).to(self.device)
batch_pose = torch.zeros(1, 6).to(self.device)
if mean_dict is not None:
batch_shape = self.mean_dict["shape"].reshape(1, 100)
batch_shape = torch.from_numpy(batch_shape).float().to(self.device)
else:
batch_shape = torch.zeros(1, 100).to(self.device)
# predict with netF
# verts = 1 x 5023 x 3, ldmk2d=1 x 68 x 3, ldmk3d=1 x 68 x 3
verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose)
verts = verts.reshape(1, 1, -1, 3) # 1 x 1 x 5023 x 3
ldmk2d = ldmk2d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
ldmk3d = ldmk3d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
logging.info(f"template verts reshape = {verts.shape}")
return verts, ldmk2d, ldmk3d
@torch.no_grad()
def get_vertices(self, batch_motion):
"""
batch_motion, (nbatch, seqlen, 53)
"""
batch_exp = batch_motion[..., :50]
batch_pos_mouth = batch_motion[..., 50:]
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1)
batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50
batch_pos_mouth = batch_pos_mouth.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3
batch_shape= torch.zeros(nbatch * seqlen, 100).to(self.device) # nbatch * seqlen x 50
batch_pose = torch.zeros(nbatch * seqlen, 6).to(self.device) # nbatch * seqlen x 6
batch_pose[:, 3:6] = batch_pos_mouth
# predict with netF
verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3
verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
ldmk2d = ldmk2d.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
ldmk3d = ldmk3d.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
return verts, ldmk2d, ldmk3d
@torch.no_grad()
def render_geometry(self, verts, cam=None, device=None):
"""
verts: [N x 5023 x 3]
"""
batch_size = verts.size(0)
if cam is None:
cam = torch.zeros(batch_size, 3).to(device) # (batch_size, 3)
# orth_proj
verts_proj = util.batch_orth_proj(verts, cam);
verts_proj[:,:,1:] = -verts_proj[:,:,1:]
# render
images = self.netR.render_shape(verts, verts_proj) # (batch_size, 3, 512, 512)
return images
@torch.no_grad()
def save_reconstruct(self, batch_pdt_geo, batch_speech, path_save, suffix="", vis_landmarks=False):
# batch_pdt_pos, [B x N x dim_motion]
# batch_speech, [B x N*sr/fps ]
B, N, *_ = batch_pdt_geo.shape
nbatch_render = 10
# for each batch
for i in range(B):
igeo_pt = batch_pdt_geo[i, ...]
v_render_pt = []
for k in range(0, N, nbatch_render):
# split
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
nbatch_real = kgeo_pt.size(0)
# cam
cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3)
cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}")
# render
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
if vis_landmarks:
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, isScale=True, color = (255, 0, 0))
else:
render_pt = render_pt.cpu()
# append each frame
for m in range(nbatch_real):
v_render_pt.append(self.tensor2image(render_pt[m, ...]))
# write video
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}_pt.mp4")
write_video(v_render_pt, batch_speech, ipath_save, fps=50)
self.logger.info(f"save video to -> {str(ipath_save)}")
@torch.no_grad()
def save_reconstruct_with_gt(self, batch_pdt_geo, batch_tgt_geo, batch_speech, path_save, suffix="", vis_landmarks=True):
# batch_pdt_geo, [B x N x 5023 x 3]
# batch_tgt_geo, [B x N x 5023 x 3]
# batch_speech, [B x N*sr/fps ]
B, N, *_ = batch_pdt_geo.shape
nbatch_render = 10
# for each batch
for i in range(B):
igeo_pt = batch_pdt_geo[i, ...] # [N x 5023 x 3]
igeo_gt = batch_tgt_geo[i, ...] # [N x 5023 x 3]
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
v_render_pt = []
v_render_gt = []
for k in range(0, N, nbatch_render):
# split
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
nbatch_real = kgeo_pt.size(0)
# cam
cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}")
# render
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_gt = self.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
if vis_landmarks:
# landmarks 3d
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
kldmk3d_gt = self.netF.seletec_3d68(kgeo_gt) # [nbatch_real x 68 x 3]
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam);
kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:];
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0))
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = (0, 255, 0))
else:
render_pt = render_pt.cpu()
render_gt = render_gt.cpu()
# append each frame
for m in range(nbatch_real):
v_render_pt.append(self.tensor2image(render_pt[m, ...]))
v_render_gt.append(self.tensor2image(render_gt[m, ...]))
# save animation
write_video_with_gt(v_render_pt, v_render_gt, batch_speech[i], ipath_save, fps=50, sr=16000)
def tensor2image(self, tensor):
# image = tensor.detach().cpu().numpy()
image = tensor.numpy()
image = image*255.
image = np.maximum(np.minimum(image, 255), 0)
image = image.transpose(1,2,0)[:,:,[2,1,0]]
return image.astype(np.uint8).copy()