diff --git a/.env.example b/.env.example deleted file mode 100644 index bc979dd..0000000 --- a/.env.example +++ /dev/null @@ -1,7 +0,0 @@ -# this is example of the file that can be used for storing private and user specific environment variables, like keys or system paths -# create a file named .env (by default .env will be excluded from version control) -# the variables declared in .env are loaded in train.py automatically -# hydra allows you to reference variables in .yaml configs with special syntax: ${oc.env:MY_VAR} - -MY_VAR="/home/user/my/system/path" -MY_KEY="asdgjhawi8y23ihsghsueity23ihwd" diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml deleted file mode 100644 index 9173e1e..0000000 --- a/.pre-commit-config.yaml +++ /dev/null @@ -1,44 +0,0 @@ -repos: - - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.1.0 - hooks: - # list of supported hooks: https://pre-commit.com/hooks.html - - id: trailing-whitespace - - id: end-of-file-fixer - - id: check-yaml - - id: check-added-large-files - - id: debug-statements - - id: detect-private-key - - # python code formatting - - repo: https://github.com/psf/black - rev: 22.1.0 - hooks: - - id: black - args: [--line-length, "99"] - - # python import sorting - - repo: https://github.com/PyCQA/isort - rev: 5.10.1 - hooks: - - id: isort - args: ["--profile", "black", "--filter-files"] - - # yaml formatting - - repo: https://github.com/pre-commit/mirrors-prettier - rev: v2.5.1 - hooks: - - id: prettier - types: [yaml] - - # python code analysis - - repo: https://github.com/PyCQA/flake8 - rev: 4.0.1 - hooks: - - id: flake8 - - # jupyter notebook cell output clearing - - repo: https://github.com/kynan/nbstripout - rev: 0.5.0 - hooks: - - id: nbstripout diff --git a/README.md b/README.md index 5f9abe7..484f446 100644 --- a/README.md +++ b/README.md @@ -495,10 +495,10 @@ defaults: # path to original working directory # hydra hijacks working directory by changing it to the new log directory # https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory -original_work_dir: ${hydra:runtime.cwd} +path_cwd: ${hydra:runtime.cwd} # path to folder with data -data_dir: ${original_work_dir}/data/ +data_dir: ${path_cwd}/data/ # pretty print config at the start of the run using Rich library print_config: True diff --git a/config.py b/config.py new file mode 100644 index 0000000..37beccc --- /dev/null +++ b/config.py @@ -0,0 +1,372 @@ +import os +from django import conf +import yaml + +import numpy as np +from easydict import EasyDict as edict + +config = edict() + +config.OUTPUT_DIR = '' +config.LOG_DIR = '' +config.LOG_PREFIX = '' +config.GPUS = '1' +config.WORKERS = 8 +config.DEBUG = False + +# pxxxx +config.isTrain = True +config.preprocess = '' +config.verbose = True + + +config.FLAME = edict() +config.FLAME.flame_model_path = "./data/mesh/generic_model.pkl" +config.FLAME.flame_lmk_embedding_path = "./data/mesh/landmark_embedding.npy" + +config.FLAME.n_shape = 100 +config.FLAME.n_tex = 50 +config.FLAME.n_exp = 50 +config.FLAME.n_cam = 3 +config.FLAME.n_pose = 6 +config.FLAME.n_light = 27 + +# texture +config.FLAME.use_tex = False +config.FLAME.tex_type = 'BFM' # BFM, FLAME, albedoMM +config.FLAME.tex_path = "./data/mesh/FLAME_albedo_from_BFM.npz" +config.FLAME.flame_tex_path = "" + + +config.RENDER = edict() +config.RENDER.rasterizer_type = 'pytorch3d' + +config.RENDER.image_size = 512 +config.RENDER.uv_size = 256 +config.RENDER.topology_path = './data/mesh/head_template.obj' + +# frequence +config.FREQ = edict() +config.FREQ.batch_save = 20 +config.FREQ.batch_print = 1 +config.FREQ.batch_display = 100 +config.FREQ.batch_test = 100000 + +config.FREQ.epoch_save = 1 +config.FREQ.epoch_print = 1 +config.FREQ.epoch_display = 10 +config.FREQ.epoch_valid = 1 +config.FREQ.epoch_test = 1 + +config.FREQ.update_html = 1 + + +# visual +config.VISUAL = edict() +config.VISUAL.use_HTML = False +config.VISUAL.use_visdom = False + +config.VISUAL.vsdm_id = 0 +config.VISUAL.vsdm_wsize = 256 +config.VISUAL.vsdm_port = 8098 +config.VISUAL.vsdm_ncol = 3 +config.VISUAL.vsdm_server = "http://localhost" +config.VISUAL.vsdm_env = "main-2" + +# cudnn related params +config.CUDNN = edict() +config.CUDNN.benchmark = True +config.CUDNN.deterministic = True +config.CUDNN.enable = True + + +########################## +# model related params +config.MODEL = edict() +config.MODEL.name = "LandmarkAE" +config.MODEL.name_netG = "MLP" +config.MODEL.name_header = "resnet50" +config.MODEL.dropout = 0.1 + +# load & init model +config.MODEL.pretrain = False +config.MODEL.path_pretrained = "" +config.MODEL.path_checkpoint = "" +config.MODEL.load_epoch = 0 + +config.MODEL.dim_motion = 0 +config.MODEL.dim_speech = 0 +config.MODEL.dim_hidden = 0 + +config.MODEL.num_vertices = 0 # 5023 + +config.MODEL.n_lookprevs_motion = 0 +config.MODEL.n_lookprevs_speech = 0 + +config.MODEL.n_lookahead_motion = 0 +config.MODEL.n_lookahead_speech = 0 + +config.MODEL.n_layer_lstm = 0 + + +# for MOGLOW +config.MODEL.n_flowstep = 0 +config.MODEL.n_early_every = 0 +config.MODEL.n_early_size = 0 +config.MODEL.n_layer_wave = 0 +config.MODEL.kernel_size = 0 +config.MODEL.lambda_std = [] +config.MODEL.fix_dims = [] + +# # for transformer +# config.MODEL.n_src_vocab = 0 +# config.MODEL.n_tgt_vocab = 0 +# config.MODEL.src_pad_idx = 0 +# config.MODEL.tgt_pad_idx = 0 +# config.MODEL.d_input = 68*2 +# config.MODEL.d_output = 68*2 +# config.MODEL.d_embed = 512 +# config.MODEL.d_model = 512 +# config.MODEL.d_latent = 256 +# config.MODEL.d_inner = 2048 +# config.MODEL.d_k = 64 +# config.MODEL.d_v = 64 +# config.MODEL.n_head = 8 +# config.MODEL.n_layers = 6 +# config.MODEL.max_position = 200 + +# In section 3.4 of paper "Attention Is All You Need", there is such detail: +# "In our model, we share the same weight matrix between the two +# embedding layers and the pre-softmax linear transformation... +# In the embedding layers, we multiply those weights by \sqrt{d_model}". +# Options here: +# 'emb': multiply \sqrt{d_model} to embedding output +# 'prj': multiply (\sqrt{d_model} ^ -1) to linear projection output +# 'none': no multiplication +# config.MODEL.scale_emb_or_prj = 'prj' +# config.MODEL.scale_emb = False +# config.MODEL.trg_emb_prj_weight_sharing = True +# config.MODEL.emb_src_trg_weight_sharing = True + + +########################## +# dataset related params +config.DATASET = edict() +config.DATASET.fps = 30 +config.DATASET.sr = 16000 +config.DATASET.name = 'ravdess' +config.DATASET.name_train = 'train_dataset' +config.DATASET.name_valid = "valid_dataset" +config.DATASET.type = '' # "clips" | "frame" | "none" +config.DATASET.root = "../data/" +config.DATASET.root_raw = "/data/lsen/DATA/xxxx/processing" +config.DATASET.path_mean_dict = "./data/xxxx_mean.npy" + +# from dataset iteratiion +config.DATASET.nwind_second_train = 0 +config.DATASET.nwind_second_valid = 0 +config.DATASET.nwind_second_test = 0 +config.DATASET.speech_extractor = '' +# for data smooth +config.DATASET.filter = '' # "gaussian" | "savgol" + +# augmentation +config.DATASET.flip = False +config.DATASET.shifting_speed = False + + +############################# +# Trainning related parameter +config.TRAIN = edict() + +config.TRAIN.apply_validation = False +config.TRAIN.apply_testing = False +config.TRAIN.apply_update_parameters = False +config.TRAIN.apply_lr_scheduler = False + +config.TRAIN.lr = 0.001 +config.TRAIN.lr_step = [50, 100] +config.TRAIN.lr_factor = 0.1 +config.TRAIN.beta1 = 0.5 +config.TRAIN.beta2 = 0.999 +config.TRAIN.lambda1 = 100 +config.TRAIN.lr_policy = '' +config.TRAIN.lr_decay_iters = 0 +config.TRAIN.lr_step_gamma = 0.1 +config.TRAIN.lr_milestones = [10,100,1000] + +config.TRAIN.grad_clip_norm = False +config.TRAIN.max_grad_clip = 0 +config.TRAIN.max_grad_norm = 0 + +# for motionVAE +config.TRAIN.p_use_pt = 0.5 + +config.TRAIN.reset_lr = False +config.TRAIN.resume = False +config.TRAIN.resume_suffix = "" +config.TRAIN.checkpoints = "" +config.TRAIN.batch_size = 24 +config.TRAIN.shuffle = True +config.TRAIN.epoch_begin = 0 +config.TRAIN.epoch_end = 100 +config.TRAIN.niter = 0 +config.TRAIN.niter_decay = 100 +config.TRAIN.load_iter = 0 +config.TRAIN.epoch = 0 + +# for cyclical schedule +config.TRAIN.n_cycle_period = 50 + +# for scheular sampling +config.TRAIN.epoch_teacher = 0 +config.TRAIN.epoch_sampling = 0 + +config.TRAIN.optimizer = 'adam' +config.TRAIN.momentum = 0.9 +config.TRAIN.weight_decay = 0 #0.0001 +config.TRAIN.nesterov = False +config.TRAIN.gamma1 = 0.99 +config.TRAIN.gamma2 = 0.0 + +############################### +# loss related params +config.LOSS = edict() +config.LOSS.names = ["all", "L1"] + +config.LOSS.lambda_rec = 1 +config.LOSS.lambda_rec_smooth = 0 + +config.LOSS.lambda_rec_exp = 0 +config.LOSS.lambda_rec_pos = 0 +config.LOSS.lambda_rec_geo = 0 +config.LOSS.lambda_rec_syn = 0 + +config.LOSS.lambda_vel_exp = 0 +config.LOSS.lambda_vel_pos = 0 +config.LOSS.lambda_vel_geo = 0 +config.LOSS.lambda_vel_syn = 0 + +config.LOSS.lambda_closure = 0 +config.LOSS.lambda_rec_code = 0 + +config.LOSS.lambda_rec_ldmk = 0 +config.LOSS.lambda_closure_x = 0 +config.LOSS.lambda_closure_y = 0 + +# for Flow +config.LOSS.lambda_logp = 0 +config.LOSS.lambda_logdet = 0 + +# for vae +config.LOSS.lambda_kl = 0 +config.LOSS.lambda_vel = 0 + +############################# +# TEST related params +config.TEST = edict() +config.TEST.batch_size = 24 +config.TEST.path_input = "" +config.TEST.path_save = "" + +############################# +# INFER related params +config.INFER = edict() +config.INFER.batch_size = 24 +config.INFER.path_input = "" +config.INFER.path_save = "" + +############################# +# DEBUG related params +config.DEBUG = edict() +config.DEBUG.debug = False +config.DEBUG.save_batch_image_gt = False +config.DEBUG.save_batch_image_pred = False +config.DEBUG.save_heatmaps_gt = False +config.DEBUG.save_heatmaps_pred = False + + +def update_index_exp(index_exp): + # prepare index + str_ids = index_exp.split(',') + + result = [] + for i in range(int(len(str_ids) / 2)): + start = int(str_ids[ 2*i]) + end = int(str_ids[2*i + 1]) + + if end > start: + result += range(start, end) + + # print('indexes', result) + + return result + + +def _update_dict(k, v): + if k == 'DATASET': + if 'MEAN' in v and v['MEAN']: + v['MEAN'] = np.array([eval(x) if isinstance(x, str) else x for x in v['MEAN']]) + if 'STD' in v and v['STD']: + v['STD'] = np.array([eval(x) if isinstance(x, str) else x for x in v['STD']]) + + # if "expression_indx" in v and v['expression_indx']: + # v['expression_indx'] = update_index_exp(v['expression_indx']) + + if k == 'MODEL': + if 'EXTRA' in v and 'HEATMAP_SIZE' in v['EXTRA']: + if isinstance(v['EXTRA']['HEATMAP_SIZE'], int): + v['EXTRA']['HEATMAP_SIZE'] = np.array( + [v['EXTRA']['HEATMAP_SIZE'], v['EXTRA']['HEATMAP_SIZE']]) + else: + v['EXTRA']['HEATMAP_SIZE'] = np.array(v['EXTRA']['HEATMAP_SIZE']) + + if 'IMAGE_SIZE' in v: + if isinstance(v['IMAGE_SIZE'], int): + v['IMAGE_SIZE'] = np.array([v['IMAGE_SIZE'], v['IMAGE_SIZE']]) + else: + v['IMAGE_SIZE'] = np.array(v['IMAGE_SIZE']) + + for vk, vv in v.items(): + if vk in config[k]: + config[k][vk] = vv + else: + raise ValueError("{}.{} not exist in config.py".format(k, vk)) + + +def update_config(config_file): + exp_config = None + with open(config_file) as f: + exp_config = edict(yaml.safe_load(f)) + + for k, v in exp_config.items(): + + if k in config: + if isinstance(v, dict): + _update_dict(k, v) + else: + if k == 'SCALES': + config[k][0] = (tuple(v)) + else: + config[k] = v + else: + raise ValueError("{} not exist in config.py".format(k)) + + # update some config item + config.GPUS = [int(i) for i in config.GPUS.split(',')] + + +def gen_config(config_file): + cfg = dict(config) + for k, v in cfg.items(): + if isinstance(v, edict): + cfg[k] = dict(v) + + with open(config_file, 'w') as f: + yaml.dump(dict(cfg), f, default_flow_style=False) + + + +if __name__ == '__main__': + import sys + gen_config(sys.argv[1]) diff --git a/configs/callbacks/callback_audio2mesh.yaml b/configs/callbacks/callback_audio2mesh.yaml new file mode 100644 index 0000000..13f2adb --- /dev/null +++ b/configs/callbacks/callback_audio2mesh.yaml @@ -0,0 +1,36 @@ +model_checkpoint: + _target_: pytorch_lightning.callbacks.ModelCheckpoint + monitor: "val/best" # name of the logged metric which determines when model is improving + mode: "min" # "max" means higher metric value is better, can be also "min" + save_top_k: 3 # save k best models (determined by above metric) + save_last: False # additionaly always save model from last epoch + verbose: False + every_n_epochs: 1 + save_weights_only: True + dirpath: "checkpoints/" + filename: "epoch_{epoch:03d}" + auto_insert_metric_name: False + +early_stopping: + _target_: pytorch_lightning.callbacks.EarlyStopping + monitor: "val/best" # name of the logged metric which determines when model is improving + mode: "max" # "max" means higher metric value is better, can be also "min" + patience: 10 # how many validation epochs of not improving until training stops + min_delta: 0 # minimum change in the monitored metric needed to qualify as an improvement + + +model_summary: + _target_: pytorch_lightning.callbacks.RichModelSummary + max_depth: 2 + +rich_progress_bar: + # _target_: pytorch_lightning.callbacks.TQDMProgressBar + _target_: pytorch_lightning.callbacks.RichProgressBar + leave: True + + + +# save_test_video: +# _target_: src.modles.callbacks.audio2mesh_callback.Audio2MeshCallback +# path_data_raw: "/yrfs/lsen/DATA/LuoXData/processing2/" +# fps: 50.0 \ No newline at end of file diff --git a/configs/callbacks/default.yaml b/configs/callbacks/default.yaml index 3c22ea0..d06c9d1 100644 --- a/configs/callbacks/default.yaml +++ b/configs/callbacks/default.yaml @@ -1,9 +1,9 @@ model_checkpoint: _target_: pytorch_lightning.callbacks.ModelCheckpoint - monitor: "val/acc" # name of the logged metric which determines when model is improving - mode: "max" # "max" means higher metric value is better, can be also "min" - save_top_k: 1 # save k best models (determined by above metric) - save_last: True # additionaly always save model from last epoch + monitor: "val/acc" # name of the logged metric which determines when model is improving + mode: "max" # "max" means higher metric value is better, can be also "min" + save_top_k: 1 # save k best models (determined by above metric) + save_last: True # additionaly always save model from last epoch verbose: False dirpath: "checkpoints/" filename: "epoch_{epoch:03d}" @@ -11,10 +11,10 @@ model_checkpoint: early_stopping: _target_: pytorch_lightning.callbacks.EarlyStopping - monitor: "val/acc" # name of the logged metric which determines when model is improving - mode: "max" # "max" means higher metric value is better, can be also "min" - patience: 100 # how many validation epochs of not improving until training stops - min_delta: 0 # minimum change in the monitored metric needed to qualify as an improvement + monitor: "val/acc" # name of the logged metric which determines when model is improving + mode: "max" # "max" means higher metric value is better, can be also "min" + patience: 100 # how many validation epochs of not improving until training stops + min_delta: 0 # minimum change in the monitored metric needed to qualify as an improvement model_summary: _target_: pytorch_lightning.callbacks.RichModelSummary @@ -22,3 +22,4 @@ model_summary: rich_progress_bar: _target_: pytorch_lightning.callbacks.RichProgressBar + diff --git a/configs/datamodule/mnist.yaml b/configs/datamodule/mnist.yaml deleted file mode 100644 index cc9a005..0000000 --- a/configs/datamodule/mnist.yaml +++ /dev/null @@ -1,7 +0,0 @@ -_target_: src.datamodules.mnist_datamodule.MNISTDataModule - -data_dir: ${data_dir} # data_dir is specified in config.yaml -batch_size: 64 -train_val_test_split: [55_000, 5_000, 10_000] -num_workers: 0 -pin_memory: False diff --git a/configs/dataset/data_actor4.yaml b/configs/dataset/data_actor4.yaml new file mode 100644 index 0000000..a3ddc76 --- /dev/null +++ b/configs/dataset/data_actor4.yaml @@ -0,0 +1,35 @@ +_target_: src.datasets.motion_datamodule.MotionDataModule + +batch_size_train: 128 +batch_size_test: 32 +num_workers: 8 +pin_memory: False + + +dataset_train: + _target_: src.datasets.components.motion_train.MotionTrainDataset + path_data: xxx/data_train.npz + fps: 50 + sr: 16000 + num_windows: 3 + filter: "savgol" + flip: False + shifting_speed: False + + +dataset_valid: + _target_: src.datasets.components.motion_eval.MotionEvalDataset + path_data: xxx/data_valid.npz + fps: 50 + sr: 16000 + num_windows: 3 + filter: "savgol" + + +dataset_test: + _target_: src.datasets.components.motion_eval.MotionEvalDataset + path_data: xxx/data_test.npz + fps: 50 + sr: 16000 + num_windows: 15 + filter: "savgol" \ No newline at end of file diff --git a/src/datamodules/__init__.py b/configs/dataset/data_actor5.yaml similarity index 100% rename from src/datamodules/__init__.py rename to configs/dataset/data_actor5.yaml diff --git a/configs/dataset/mnist.yaml b/configs/dataset/mnist.yaml new file mode 100644 index 0000000..903dfd3 --- /dev/null +++ b/configs/dataset/mnist.yaml @@ -0,0 +1,6 @@ +_target_: src.datasets.minist_datamodule.MNISTDataModule + +data_dir: ${data_dir} # data_dir is specified in config.yaml +batch_size: 64 +num_workers: 4 +pin_memory: False diff --git a/configs/dataset/motion.yaml b/configs/dataset/motion.yaml new file mode 100644 index 0000000..2fb23fe --- /dev/null +++ b/configs/dataset/motion.yaml @@ -0,0 +1,32 @@ +_target_: src.datasets.motion_datamodule.MotionDataModule + +batch_size: 64 +num_workers: 4 +pin_memory: False + +dataset_train: + _target_: src.datasets.components.motion_train.MotionTrainDataset + path_data: ${path_data}/data_train.npz + fps: 50 + sr: 16000 + num_windows: 3 + filter: "savgol" + flip: False + shifting_speed: False + + +dataset_valid: + _target_: src.datasets.components.motion_eval.MotionEvalDataset + path_data: ${path_data}/data_valid.npz + fps: 50 + sr: 16000 + num_windows: 3 + filter: "savgol" + +dataset_test: + _target_: src.datasets.components.motion_eval.MotionEvalDataset + path_data: ${path_data}/data_test.npz + fps: 50 + sr: 16000 + num_windows: 15 + filter: "savgol" \ No newline at end of file diff --git a/configs/experiment/audio2mesh/infer_audio2mesh_CN_20220312.yaml b/configs/experiment/audio2mesh/infer_audio2mesh_CN_20220312.yaml new file mode 100644 index 0000000..bf968cd --- /dev/null +++ b/configs/experiment/audio2mesh/infer_audio2mesh_CN_20220312.yaml @@ -0,0 +1,41 @@ +GPUS: '9' +WORKERS: 4 +OUTPUT_DIR: 'experiments/audio2mesh' + +DEBUG: False +verbose: False +isTrain: False + + +MODEL: + # name: 'audio2mesh' + name: 'audio2mesh' + name_netG: "audio2mesh" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + num_vertices: 5023 + + pretrain: True + # path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220315-16H55M15S" + # load_epoch: 35 + # path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220315-16H46M54S" + # load_epoch: 75 + + # path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220321-15H11M43S" + # load_epoch: 65 + + # 5h, 1:10, epoch 25 + path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220321-15H10M14S" + load_epoch: 25 + + +DATASET: + fps: 50 + sr: 16000 + path_mean_dict: './data/Actor2/DECA_Actor2_mean.npy' + +TRAIN: + apply_testing: True + apply_validation: True + diff --git a/configs/experiment/audio2mesh/train_audio2mesh_CN_20220312.yaml b/configs/experiment/audio2mesh/train_audio2mesh_CN_20220312.yaml new file mode 100644 index 0000000..8530606 --- /dev/null +++ b/configs/experiment/audio2mesh/train_audio2mesh_CN_20220312.yaml @@ -0,0 +1,45 @@ +# @package _global_ +# to execute this experiment run: +# python train.py experiment=example + +defaults: + - override /datamodule: motion.yaml + - override /model: audio2mesh_CN.yaml + - override /callbacks: audio2mesh_callback.yaml + - override /logger: tensorboard.yaml + - override /trainer: default.yaml + + +# all parameters below will be merged with parameters from default configurations set above +# this allows you to overwrite only specified parameters + +# name of the run determines folder name in logs +name: "audio2mesh" +seed: 12345 + +trainer: + gpus: [9,] + min_epochs: 50 + max_epochs: 200 + + gradient_clip_val: 0.5 + num_sanity_val_steps: 0 + check_val_every_n_epoch: 5 + enable_checkpointing: True + log_every_n_steps: 20 + + +model: + lr: 0.0001 + + netG: + _target_: src.models.components.audio2mesh.Audio2Mesh + num_vertices: 5023 + nc_condit: 1024 + +datamodule: + batch_size: 128 + batch_size_test: 32 + # data_dir: "./data/LuoXData-raw-8h" + + diff --git a/configs/experiment/audio2mesh/train_audio2mesh_CN_20220425.yaml b/configs/experiment/audio2mesh/train_audio2mesh_CN_20220425.yaml new file mode 100644 index 0000000..a94ddd1 --- /dev/null +++ b/configs/experiment/audio2mesh/train_audio2mesh_CN_20220425.yaml @@ -0,0 +1,62 @@ +# @package _global_ +# to execute this experiment run: +# python train.py experiment=audio2mesh/train_audio2mesh_CN_20220425.yaml + +defaults: + - override /dataset: data_actor4.yaml + - override /model: model_audio2mesh.yaml + - override /callbacks: callback_audio2mesh.yaml + - override /logger: tensorboard.yaml + - override /trainer: ddp.yaml + + +# all parameters below will be merged with parameters from default configurations set above +# this allows you to overwrite only specified parameters + + +# name of the run determines folder name in logs +name: "audio2mesh" +seed: 12345 +path_data: /ssdata1/lsen/CODE/Audio2Motion/data/Actor4 +specifict_folder: Actor4-raw-1h + +trainer: + gpus: [2, 3, 4, 5] + min_epochs: 300 + max_epochs: 300 + + gradient_clip_val: 0.5 + num_sanity_val_steps: 0 + check_val_every_n_epoch: 1 + enable_checkpointing: True + log_every_n_steps: 20 + + +model: + lr: 0.0001 + + opt: + path_mean_dict: ${path_data}/DECA_Actor4_mean.npy + + netG: + _target_: src.models.components.audio2mesh.Audio2Mesh + num_vertices: 5023 + nc_condit: 1024 + + +dataset: + batch_size_train: 128 + batch_size_test: 32 + + dataset_train: + path_data: ${path_data}/${specifict_folder}/data_train.npz + + dataset_valid: + path_data: ${path_data}/${specifict_folder}/data_valid.npz + + dataset_test: + path_data: ${path_data}/${specifict_folder}/data_test.npz + + # data_dir: "./data/LuoXData-raw-8h" + + diff --git a/configs/experiment/example.yaml b/configs/experiment/example.yaml index 305d96c..21fdfd0 100644 --- a/configs/experiment/example.yaml +++ b/configs/experiment/example.yaml @@ -7,8 +7,8 @@ defaults: - override /datamodule: mnist.yaml - override /model: mnist.yaml - override /callbacks: default.yaml - - override /logger: null - - override /trainer: default.yaml + - override /logger: tensorboard.yaml + - override /trainer: ddp.yaml # all parameters below will be merged with parameters from default configurations set above # this allows you to overwrite only specified parameters @@ -20,7 +20,7 @@ seed: 12345 trainer: min_epochs: 10 - max_epochs: 10 + max_epochs: 100 gradient_clip_val: 0.5 model: diff --git a/configs/model/mnist.yaml b/configs/model/mnist.yaml index 7799b31..7e8d583 100644 --- a/configs/model/mnist.yaml +++ b/configs/model/mnist.yaml @@ -1,7 +1,12 @@ _target_: src.models.mnist_module.MNISTLitModule + +opt: + speech_extractor: wav2vec + AA: ss + BB: 22 + lr: 0.001 weight_decay: 0.0005 - net: _target_: src.models.components.simple_dense_net.SimpleDenseNet input_size: 784 diff --git a/configs/model/model_audio2mesh.yaml b/configs/model/model_audio2mesh.yaml new file mode 100644 index 0000000..fcf7843 --- /dev/null +++ b/configs/model/model_audio2mesh.yaml @@ -0,0 +1,48 @@ +_target_: src.models.module_audio2mesh.Audio2MeshModel + + +lr: 0.001 +weight_decay: 0.0005 + +opt: + speech_extractor: wav2vec + sr: 16000 + fps: 50 + num_vertices: 5023 + lambda_rec_geo: 1 + lambda_vel_geo: 10 + path_mean_dict: xxx/DECA_actor_mean.npy + path_init_expression_basis: ${path_cwd}/checkpoints/init_expression_basis.npy + +opt_LOSS: + lambda_rec_geo: 1 + lambda_vel_geo: 10 + lambda_rec_ldmk: 0 + lambda_closure_x: 0 + lambda_closure_y: 0 + + +opt_netF: + n_shape: 100 + n_exp: 50 + flame_model_path: ${path_cwd}/data/mesh/generic_model.pkl + flame_lmk_embedding_path: ${path_cwd}/data/mesh/landmark_embedding.npy + +opt_netR: + rasterizer_type: pytorch3d + image_size: 512 + uv_size: 256 + topology_path: ${path_cwd}/data/mesh/head_template.obj + +opt_netW: + path_ckpt_wav2vec: ${path_cwd}/checkpoints/wav2vec2 + + +netG: + _target_: src.models.components.audio2mesh.Audio2Mesh + num_vertices: 5023 + nc_condit: 1024 + + + + diff --git a/configs/test.yaml b/configs/test.yaml index 1e10d5c..b218859 100644 --- a/configs/test.yaml +++ b/configs/test.yaml @@ -16,9 +16,9 @@ defaults: - override hydra/hydra_logging: colorlog - override hydra/job_logging: colorlog -original_work_dir: ${hydra:runtime.cwd} +path_cwd: ${hydra:runtime.cwd} -data_dir: ${original_work_dir}/data/ +data_dir: ${path_cwd}/data/ print_config: True diff --git a/configs/train.yaml b/configs/train.yaml index 2266a48..fffe071 100644 --- a/configs/train.yaml +++ b/configs/train.yaml @@ -3,16 +3,16 @@ # specify here default training configuration defaults: - _self_ - - datamodule: mnist.yaml + - dataset: mnist.yaml - model: mnist.yaml - callbacks: default.yaml - logger: null # set logger here or use command line (e.g. `python train.py logger=tensorboard`) - trainer: default.yaml - log_dir: default.yaml - + # experiment configs allow for version control of specific configurations # e.g. best hyperparameters for each combination of model and datamodule - - experiment: null + - experiment: example.yaml # debugging config (enable through command line, e.g. `python train.py debug=default) - debug: null @@ -28,13 +28,15 @@ defaults: - override hydra/hydra_logging: colorlog - override hydra/job_logging: colorlog + + # path to original working directory # hydra hijacks working directory by changing it to the new log directory # https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory -original_work_dir: ${hydra:runtime.cwd} +path_cwd: ${hydra:runtime.cwd} # path to folder with data -data_dir: ${original_work_dir}/data/ +# data_dir: ${path_cwd}/data/ # pretty print config at the start of the run using Rich library print_config: True diff --git a/configs/trainer/ddp.yaml b/configs/trainer/ddp.yaml index 8a11249..9b5a53d 100644 --- a/configs/trainer/ddp.yaml +++ b/configs/trainer/ddp.yaml @@ -1,6 +1,6 @@ defaults: - default.yaml -gpus: 4 +gpus: [2,3,6] strategy: ddp sync_batchnorm: True diff --git a/configs/trainer/default.yaml b/configs/trainer/default.yaml index a414acb..683b28c 100644 --- a/configs/trainer/default.yaml +++ b/configs/trainer/default.yaml @@ -1,6 +1,7 @@ _target_: pytorch_lightning.Trainer -gpus: 0 +# gpus: [2,3,6] +gpus: [9,] min_epochs: 1 max_epochs: 10 diff --git a/model_audio2mesh.py b/model_audio2mesh.py new file mode 100644 index 0000000..0b33710 --- /dev/null +++ b/model_audio2mesh.py @@ -0,0 +1,582 @@ + +import numpy as np +from collections import OrderedDict + +import torch +import torch.nn as nn +from pathlib import Path + +from src.models.info import flame_mouth_idx +from src.models.info import idx_upper_mouth_68ldmk, idx_lower_mouth_68ldmk +from src.models.info import idx_left_mouth_68ldmk, idx_right_mouth_68ldmk + +from src.models import init_net +from src.models.base import Base +from src.optims import get_optimizer, get_scheduler +from src.utils import util + +# common +from common.animation import write_video, write_video_with_gt +from common.debug import debug +from common.losses import WingLoss + +# disentangle model +class Audio2MeshModel(Base): + + def __init__(self, opt, logger): + Base.__init__(self, opt, logger) + + self.opt = opt + self.logger = logger + self.names_model = ["G"] # G + + # define networks + self.netG = define_netG(opt) + init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS) + + # init last layer + init_exp_weight = np.load("./data/init_expression_basis.npy") + init_exp_weight = torch.from_numpy(init_exp_weight).float().to(self.device) + init_exp_weight = init_exp_weight[:, :50] + if isinstance(self.netG, torch.nn.DataParallel): + self.netG.module.decoder_mesh.weight.data = init_exp_weight + else: + self.netG.decoder_mesh.weight.data = init_exp_weight + print(f"init_exp_weight shape = {init_exp_weight.shape}") + + self.netF = define_FLAME(opt, self.device) + self.netR = define_render(opt, self.device) + self.processor, self.extractor = define_extractor(opt, self.device) + + # path_deca_mean = Path("./data/DECA_obama_mean.npy") + path_deca_mean = self.opt.DATASET.path_mean_dict + self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item() + print(f"load mean deca coeff from > {path_deca_mean}, \nkeys = {self.mean_dict.keys()}") + + # get template + self.temp_verts, self.temp_ldmk2d, self.temp_ldmk3d \ + = self.get_template_vertices() # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3) + + + self.temp_verts_specific, self.temp_ldmk2d_specific, self.temp_ldmk3d_specific \ + = self.get_template_vertices(self.mean_dict) # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3) + + # self.temp_verts_specific = np.load("/ssdata1/lsen/CODE/audio-to-motion/data/Actor4/template_meiyan2.npy") # (5023, 3) + # self.temp_verts_specific = self.temp_verts_specific.reshape(1, 1, 5023, 3) + # self.temp_verts_specific = torch.from_numpy(self.temp_verts_specific).to(self.device) + + # save to + + # loss function + self.loss_func_wing = WingLoss(reduction="none") # return (B, ) + self.loss_func_l1 = nn.L1Loss(reduction="none") + self.names_loss = opt.LOSS.names + + # define loss weight + self.vertices_weight = torch.ones((1, 1, self.opt.MODEL.num_vertices, 3)).to(self.device) + self.vertices_weight[:, :, flame_mouth_idx, :] = 10 + + if self.isTrain: + # define optimizers + self.optimizer_G = get_optimizer(self.netG, opt) + self.optimizers.append(self.optimizer_G) + + self.scheduler_G = get_scheduler(self.optimizer_G, opt) + self.schedulers.append(self.scheduler_G) + + @torch.no_grad() + def set_input(self, batch_input): + """ """ + # motion data + data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion) + + self.batch_vid = batch_input['vid'] + self.batch_nframe = batch_input['nframe'] + self.batch_interv = batch_input['frame_interval'] + + debug(self.opt, f"data = {data.shape}, dtype={data.dtype}", verbose=False) + debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False) + debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False) + debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \ + beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False) + + # speech data + cond = None + raw_speech = batch_input["cond"].numpy() # (B, nsegments) + debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False) + + # padding half frame length for bed and end + npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5) + pad_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge") + debug(self.opt, f"after padding pad_speech = {pad_speech.shape}, dtype={pad_speech.dtype}", verbose=False) + + inputs = self.processor(list(pad_speech), sampling_rate=16000, return_tensors="pt") + cond = self.extractor(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat + debug(self.opt, f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False) + + # unfold speech data + cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_codit, 16) + cond = cond.permute(0, 1, 3, 2) # (B, nseqs, 16, nc_condit) + + # setup + self.cond = cond + self.B, self.nsteps, self.nwind, self.dim_speech = cond.size() + data = data[:, 7:7+self.nsteps, :] + self.vert, self.ldmk2d, self.ldmk3d = self.get_vertices(data) + + # cut audio clips + idx_beg = int(7 * self.opt.DATASET.sr / self.opt.DATASET.fps + 0.5) + idx_end = int((7 + self.nsteps) * self.opt.DATASET.sr / self.opt.DATASET.fps + 0.5) + self.raw_speech = raw_speech[:, idx_beg: idx_end] # (B, nsteps * sr / fps) + + debug(self.opt, f"[set_input] vert = {self.vert.shape}, dtype={self.vert.dtype}, device={self.vert.device}", verbose=False) + debug(self.opt, f"[set_input] cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False) + debug(self.opt, f"[set_input] ldmk2d = {self.ldmk2d.shape}, dtype={self.ldmk2d.dtype}, device={self.ldmk2d.device}", verbose=False) + debug(self.opt, f"[set_input] ldmk3d = {self.ldmk3d.shape}, dtype={self.ldmk3d.dtype}, device={self.ldmk3d.device}", verbose=False) + + + def forward(self, batch_input): + self.set_input(batch_input) + + # forward + pred = self.netG(self.cond) + debug(self.opt, f"traing pred = {pred.shape}", verbose=False) + + return pred + + + def training(self, batch_input, idx_epoch=0, idx_batch=0): + self.train() # set train model + self.set_input(batch_input) + + # forward + self.pred = self.netG(self.cond) + self.pred += self.temp_verts + debug(self.opt, f"traing pred = {self.pred.shape}", verbose=False) + + # loss + loss, loss_dict = self.eval_losses(self.pred, self.vert) + + # backward + self.optimizer_G.zero_grad() + loss.backward() + + if self.opt.TRAIN.grad_clip_norm: # operate grad + torch.nn.utils.clip_grad_value_(self.netG.parameters(), self.opt.TRAIN.max_grad_clip) + torch.nn.utils.clip_grad_norm_(self.netG.parameters(), self.opt.TRAIN.max_grad_norm) + + self.optimizer_G.step() + + return loss_dict + + + def validation(self, batch_input, idx_epoch=0, idx_batch=0): + self.eval() # set eval model + self.set_input(batch_input) + + with torch.no_grad(): + pred = self.netG(self.cond) + pred += self.temp_verts + + loss, loss_dict = self.eval_losses(pred, self.vert) + + return loss_dict + + + def infer_with_gt(self, batch_cond, batch_data, batch_speech, suffix="", save_npy=True): + self.eval() + + cond = batch_cond.float().to(self.device) # (nsteps, dim_cond) + data = batch_data.float().to(self.device) # (B, nframe, 53) + vert, ldmk2d, ldmk3d = self.get_vertices(data) + + # add a dimensions + if batch_speech.dims == 1: + batch_speech = batch_speech.unsqueeze(0) # (B, nsegmt) + + + with torch.no_grad(): + batch_pdt_geo = self.netG(cond) # B x N x dim_motion + batch_pdt_geo += self.temp_verts # B x N x 5023 x 3 + print(f"testing pt shape = {batch_pdt_geo.shape}") + + # !! add specific when render & output !! + batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific + + # render & and save + + self.save_reconstruct(batch_pdt_geo, batch_speech, + path_save=Path(self.opt.OUTPUT_DIR), + suffix=suffix, vis_landmarks=False) + + # render & and save + print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {vert.shape}") + self.save_reconstruct_with_gt(batch_pdt_geo, vert, batch_speech, + path_save=Path(self.opt.OUTPUT_DIR), + suffix=suffix,vis_landmarks=False) + + + if save_npy: + # save result + batch_pdt_geo = batch_pdt_geo.cpu().numpy() + path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy") + np.save(path_save_npy, batch_pdt_geo) + print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}") + + + def infer(self, batch_cond, batch_speech, suffix="", save_npy=True): + self.eval() + self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond) + + with torch.no_grad(): + batch_pdt_geo = self.netG(self.cond) # B x N x dim_motion + batch_pdt_geo += self.temp_verts # B x N x 5023 x 3 + + print(f"testing pt shape = {batch_pdt_geo.shape}") + + # !! add specific when render & output !! + batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific + + # render & and save + self.save_reconstruct(batch_pdt_geo, batch_speech, path_save=Path(self.opt.OUTPUT_DIR), + suffix=suffix, vis_landmarks=False) + + if save_npy: + # save result + batch_pdt_geo = batch_pdt_geo.cpu().numpy() + path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy") + np.save(path_save_npy, batch_pdt_geo) + print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}") + + + def testing(self, batch_input, idx_epoch=0, idx_batch=0): + self.eval() # set eval model + self.set_input(batch_input) + + with torch.no_grad(): + batch_pdt_geo = self.netG(self.cond) # B x N x 5023 x 3 + batch_pdt_geo += self.temp_verts # B x N x 5023 x 3 + + # !! add specific when render & output !! + batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific + + print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {self.vert.shape}") + self.save_reconstruct_with_gt(batch_pdt_geo, self.vert, self.raw_speech, + path_save=Path(self.opt.OUTPUT_DIR), + suffix=f'sampled_{idx_epoch:05d}_{idx_batch:03d}') + + + def get_template_vertices(self, mean_dict=None): + + batch_exp = torch.zeros(1, 50).to(self.device) + batch_pose = torch.zeros(1, 6).to(self.device) + + if mean_dict is not None: + batch_shape = self.mean_dict["shape"].reshape(1, 100) + batch_shape = torch.from_numpy(batch_shape).float().to(self.device) + else: + batch_shape = torch.zeros(1, 100).to(self.device) + + with torch.no_grad(): + # verts = 1 x 5023 x 3, ldmk2d=1 x 68 x 3, ldmk3d=1 x 68 x 3 + verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose) + verts = verts.reshape(1, 1, -1, 3) # 1 x 1 x 5023 x 3 + ldmk2d = ldmk2d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3 + ldmk3d = ldmk3d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3 + + print(f"template verts reshape = {verts.shape}") + + + return verts, ldmk2d, ldmk3d + + + def get_vertices(self, batch_motion): + """ + batch_motion, (nbatch, seqlen, 53) + """ + batch_exp = batch_motion[..., :50] + batch_pos_mouth = batch_motion[..., 50:] + nbatch, seqlen = batch_exp.size(0), batch_exp.size(1) + + batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50 + batch_pos_mouth = batch_pos_mouth.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3 + + batch_shape= torch.zeros(nbatch * seqlen, 100).to(self.device) # nbatch * seqlen x 50 + batch_pose = torch.zeros(nbatch * seqlen, 6).to(self.device) # nbatch * seqlen x 6 + batch_pose[:, 3:6] = batch_pos_mouth + + with torch.no_grad(): + verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3 + verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3 + ldmk2d = ldmk2d.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3 + ldmk3d = ldmk3d.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3 + + return verts, ldmk2d, ldmk3d + + + def eval_losses(self, batch_pdt_geo, batch_tgt_geo): + """ Computes the loss function. + pramas: + batch_tgt_geo, (nbatch, seqlen, num_vertices, 3) + batch_pdt_geo, (nbatch, seqlen, num_vertices, 3) + """ + loss = 0 + loss_dict = OrderedDict() + + # synthesis geo rec + loss = 0 + loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) + loss_dict["rec_geo"] = loss_rec_geo.mean().detach() + + loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight) + # loss_dict["rec_geo_w"] = loss_rec_geo2.mean().detach() + # loss += loss_rec_geo.mean() * self.opt.LOSS.lambda_rec_geo + loss += loss_rec_geo2.mean() * self.opt.LOSS.lambda_rec_geo + + # synthesis geo volocity + diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :] + diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :] + + loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) + loss_dict["vel_geo"] = loss_vel_geo.mean().detach() + + loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight) + # loss_dict["vel_geo_w"] = loss_vel_geo2.mean().detach() + # loss += loss_vel_geo.mean() * self.opt.LOSS.lambda_vel_geo + + if self.opt.LOSS.lambda_vel_geo > 0: + loss += loss_vel_geo2.mean() * self.opt.LOSS.lambda_vel_geo + + # landmarks loss + ldmk3d_pdt = self.netF.seletec_3d68(batch_pdt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # (B*N, 68, 3) + ldmk3d_tgt = self.netF.seletec_3d68(batch_tgt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # (B*N, 68, 3) + loss_rec_ldmk = torch.sqrt(((ldmk3d_pdt - ldmk3d_tgt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68) + loss_dict["rec_ldmk"] = loss_rec_ldmk.mean().detach() + + if self.opt.LOSS.lambda_rec_ldmk > 0: + loss += loss_rec_ldmk.mean() * self.opt.LOSS.lambda_rec_ldmk + + # mouth closure_x loss (left/right mouth) + ldmk3d_pdt_left, ldmk3d_pdt_right = ldmk3d_pdt[:, idx_left_mouth_68ldmk], ldmk3d_pdt[:, idx_right_mouth_68ldmk] + ldmk3d_tgt_left, ldmk3d_tgt_right = ldmk3d_tgt[:, idx_left_mouth_68ldmk], ldmk3d_tgt[:, idx_right_mouth_68ldmk] + diff_pdt_mouth_x = torch.sqrt(((ldmk3d_pdt_left - ldmk3d_pdt_right)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8) + diff_tgt_mouth_x = torch.sqrt(((ldmk3d_tgt_left - ldmk3d_tgt_right)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8) + + loss_closure_x = (diff_pdt_mouth_x - diff_tgt_mouth_x).abs().mean() # (B*N, 8) ==> (1,) + loss_dict["closure_x"] = loss_closure_x.mean().detach() + + if self.opt.LOSS.lambda_closure_x > 0: + loss += loss_closure_x.mean() * self.opt.LOSS.lambda_closure_x + + # mouth closure_y loss (upper/lower mouth) + ldmk3d_pdt_upper, ldmk3d_pdt_lower = ldmk3d_pdt[:, idx_upper_mouth_68ldmk], ldmk3d_pdt[:, idx_lower_mouth_68ldmk] + ldmk3d_tgt_upper, ldmk3d_tgt_lower = ldmk3d_tgt[:, idx_upper_mouth_68ldmk], ldmk3d_tgt[:, idx_lower_mouth_68ldmk] + diff_pdt_mouth_y = torch.sqrt(((ldmk3d_pdt_upper - ldmk3d_pdt_lower)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8) + diff_tgt_mouth_y = torch.sqrt(((ldmk3d_tgt_upper - ldmk3d_tgt_lower)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8) + + loss_closure_y = (diff_pdt_mouth_y - diff_tgt_mouth_y).abs().mean() # (B*N, 8) ==> (1,) + loss_dict["closure_y"] = loss_closure_y.mean().detach() + + if self.opt.LOSS.lambda_closure_y > 0: + loss += loss_closure_y.mean() * self.opt.LOSS.lambda_closure_y + + + # total loss + loss_dict["all"] = loss.detach() + + return loss, loss_dict + + def save_reconstruct(self, batch_pdt_geo, batch_speech, path_save, suffix="", vis_landmarks=False): + # batch_pdt_pos, [B x N x dim_motion] + # batch_speech, [B x N*sr/fps ] + + B, N, *_ = batch_pdt_geo.shape + nbatch_render = 10 + + # for each batch + for i in range(B): + igeo_pt = batch_pdt_geo[i, ...] + + v_render_pt = [] + for k in range(0, N, nbatch_render): + # split + kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] + nbatch_real = kgeo_pt.size(0) + + # cam + cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3) + cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3) + # print(f"cam shape = {cam.shape}") + + # render + render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) + # print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}") + + if vis_landmarks: + kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3] + kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam); + kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:]; + render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, isScale=True, color = (255, 0, 0)) + else: + render_pt = render_pt.cpu() + + # append each frame + for m in range(nbatch_real): + v_render_pt.append(tensor2image(render_pt[m, ...])) + + # write video + ipath_save = path_save.joinpath(f"{suffix}_{i:02d}_pt.mp4") + write_video(v_render_pt, batch_speech, ipath_save, fps=50) + self.logger.info(f"save video to -> {str(ipath_save)}") + + + @torch.no_grad() + def render_geometry(self, verts, cam=None, device=None): + """ + verts: [N x 5023 x 3] + """ + batch_size = verts.size(0) + + if cam is None: + cam = torch.zeros(batch_size, 3).to(device) # (batch_size, 3) + + # orth_proj + verts_proj = util.batch_orth_proj(verts, cam); + verts_proj[:,:,1:] = -verts_proj[:,:,1:] + + # render + images = self.netR.render_shape(verts, verts_proj) # (batch_size, 3, 512, 512) + + return images + + + @torch.no_grad() + def save_reconstruct_with_gt(self, batch_pdt_geo, batch_tgt_geo, batch_speech, path_save, suffix="", vis_landmarks=True): + # batch_pdt_geo, [B x N x 5023 x 3] + # batch_tgt_geo, [B x N x 5023 x 3] + # batch_speech, [B x N*sr/fps ] + + B, N, *_ = batch_pdt_geo.shape + nbatch_render = 10 + + # for each batch + for i in range(B): + igeo_pt = batch_pdt_geo[i, ...] # [N x 5023 x 3] + igeo_gt = batch_tgt_geo[i, ...] # [N x 5023 x 3] + ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4") + + v_render_pt = [] + v_render_gt = [] + + for k in range(0, N, nbatch_render): + + # split + kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] + kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] + + nbatch_real = kgeo_pt.size(0) + + # cam + cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3) + # print(f"cam shape = {cam.shape}") + + # render + render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) + render_gt = self.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512) + # print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}") + + if vis_landmarks: + # landmarks 3d + kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3] + kldmk3d_gt = self.netF.seletec_3d68(kgeo_gt) # [nbatch_real x 68 x 3] + + kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam); + kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:]; + + kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam); + kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:]; + + render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0)) + render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = (0, 255, 0)) + else: + render_pt = render_pt.cpu() + render_gt = render_gt.cpu() + + # append each frame + for m in range(nbatch_real): + v_render_pt.append(tensor2image(render_pt[m, ...])) + v_render_gt.append(tensor2image(render_gt[m, ...])) + + # save animation + write_video_with_gt(v_render_pt, v_render_gt, batch_speech[i], ipath_save, fps=50, sr=16000) + +######################################### +def tensor2image(tensor): + # image = tensor.detach().cpu().numpy() + image = tensor.numpy() + image = image*255. + image = np.maximum(np.minimum(image, 255), 0) + image = image.transpose(1,2,0)[:,:,[2,1,0]] + + return image.astype(np.uint8).copy() + + +def define_netG(opt): + netG = None + + if opt.MODEL.name_netG == "audio2mesh": + from src.nn.audio2mesh import Audio2Mesh + netG = Audio2Mesh(opt) + + elif opt.MODEL.name_netG == "audio2mesh_voca": + from src.nn.audio2mesh_voca import Audio2Mesh + netG = Audio2Mesh(opt) + + elif opt.MODEL.name_netG == "audio2mesh_resnet": + from src.nn.audio2mesh_resnet import Audio2Mesh + netG = Audio2Mesh(opt) + + else: + raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!") + + # to GPU + netG.to(f"cuda:{opt.GPUS[0]}") + if len(opt.GPUS) > 1: + netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs + + return netG + + +def define_FLAME(opt, device): + from src.nn.FLAME import FLAME + + model = FLAME(opt.FLAME).to(device) + + return model + + +def define_render(opt, device): + from src.utils.renderer import SRenderY, set_rasterizer + + set_rasterizer(opt.RENDER.rasterizer_type) + + model = SRenderY(opt.RENDER.image_size, + obj_filename=opt.RENDER.topology_path, + uv_size=opt.RENDER.uv_size, + rasterizer_type=opt.RENDER.rasterizer_type + ).to(device) + + return model + +def define_extractor(opt, device): + from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model + print("load Wav2Vec2Model ...") + # MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn" + # self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID) + # self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device) + + path_ckpt_wav2vec = "./checkpoints/wav2vec2" + processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec) + extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device) + + return processor, extractor diff --git a/src/datamodules/components/__init__.py b/src/datasets/__init__.py similarity index 100% rename from src/datamodules/components/__init__.py rename to src/datasets/__init__.py diff --git a/src/datasets/components/__init__.py b/src/datasets/components/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/datasets/components/motion_eval.py b/src/datasets/components/motion_eval.py new file mode 100644 index 0000000..1c55342 --- /dev/null +++ b/src/datasets/components/motion_eval.py @@ -0,0 +1,99 @@ +import numpy as np +from torch.utils.data import Dataset +from pathlib import Path +from scipy.signal import savgol_filter +import logging + +class MotionEvalDataset(Dataset): + """ + Motion dataset. + Prepares conditioning information (previous poses + control signal) and the corresponding next poses""" + + def __init__( + self, + path_data = "./data_valid.npz", # opt.DATASET.root + fps = 50, # opt.DATASET.fps + sr = 16000, # opt.DATASET.sr + num_windows = 3, # eval(f"opt.DATASET.nwind_second_{phase}") + filter = "savgol", + ): + super(MotionEvalDataset, self).__init__() + + logging.info(f"load data ... --> {path_data}") + self.annodb = np.load(path_data, allow_pickle=True)['data'].item() + self.num_pid = len(self.annodb) + self.pids = list(self.annodb.keys()) + self.overlap = 0.5 + + self.filter = filter + self.nsteps_frame = num_windows * fps + self.nsteps_segmt = num_windows * sr + + self.annodb_accums = self.count_annotations() + logging.info(f'''num_pid={self.num_pid}, niters={self.annodb_accums[-1]}, nsteps_frame={self.nsteps_frame}, nsteps_segmt={self.nsteps_segmt} ''') + + + def __len__(self): + return self.annodb_accums[-1] + + + def count_annotations(self): + acc = 0 + annodb_accums = np.zeros(self.num_pid + 1, dtype=int) # the first element set 0 + for i, ikey in enumerate(self.annodb): + acc += self.annodb[ikey]["data_motion"].shape[0] // (self.nsteps_frame * (1-self.overlap)) - 1 # ncount_windows + annodb_accums[i+1] = acc # 2 + return annodb_accums + + def __getitem__(self, idx): + """ + Returns poses and conditioning. + If data-dropout sould be applied, a random selection of the previous poses is masked. + The control is not masked + return: + motion: (nsteps, nc_motion), current frame's pose (15 joint, xyz position) + speech: (nsteps, nc_speech), conditional data = previous motion data + full windows contrl data + """ + + for i, iacc in enumerate(self.annodb_accums): + if idx > iacc -1 and idx < self.annodb_accums[i+1]: + pid, new_idx = i, idx - iacc + break + # logging.info(f"DEBUG: idx={idx}, pid = {pid}, iacc ={self.annodb_accums[i]}, new_idx = {new_idx}") + + # return item + vid = self.pids[pid] + data = self.annodb[vid] + data_motion = data["data_motion"] # (nframes, nc_motion) + data_speech = data["data_speech"] # (nsegemts, ) + + nframe = data_motion.shape[0] + nsegmt = data_speech.shape[0] + + # random select beg:end frame + beg_frame = new_idx + end_frame = beg_frame + self.nsteps_frame + + beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt) + end_segmt = beg_segmt + self.nsteps_segmt + # logging.info(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\nnsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}") + + data_motion = data_motion[beg_frame:end_frame] # (nteps, 53) + data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, ) + # logging.info(f"data_motion-{data_motion.shape} data_speech={data_speech.shape}") + assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}" + + # filter, explore doc: ./notebook/explore_pose.ipynb + if self.filter == "savgol": + data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest') + + result = { + "data": data_motion, # (nsteps_frame, dim_motion) + "cond": data_speech, # (nsteps_frame, dim_speech) + "vid": vid, + "nframe": nframe, + "frame_interval": [beg_frame, end_frame], + # "duration_interval": [beg_frame/nframe, end_frame/nframe] + } + + return result diff --git a/src/datasets/components/motion_train.py b/src/datasets/components/motion_train.py new file mode 100644 index 0000000..0d04f4a --- /dev/null +++ b/src/datasets/components/motion_train.py @@ -0,0 +1,157 @@ +import numpy as np +import time +import random +from torch.utils.data import Dataset +from pathlib import Path +from scipy.signal import savgol_filter +import logging + + +# common +from src.utils.resampling import resample_by_nsteps + + +class MotionTrainDataset(Dataset): + """ + Motion dataset. + Prepares conditioning information (previous poses + control signal) and the corresponding next poses""" + + + def __init__( + self, + path_data = "../data_train.npz", # opt.DATASET.root + fps = 50, # opt.DATASET.fps + sr = 16000, # opt.DATASET.sr + num_windows = 3, # eval(f"opt.DATASET.nwind_second_{phase}") + filter = "savgol", + flip = False, + shifting_speed = False, + + ): + + super(MotionTrainDataset, self).__init__() + + logging.info(f"load data ... --> {path_data}") + self.annodb = np.load(path_data, allow_pickle=True)['data'].item() + self.num_pid = len(self.annodb) + self.pids = list(self.annodb.keys()) + + self.filter = filter + self.nsteps_frame = num_windows * fps + self.nsteps_segmt = num_windows * sr + + # others augments + self.flip = flip + self.shifting_speed = shifting_speed + + self.overlap = 0.2 + self.annodb_accums = self.count_annotations() + # logging.info(f'''num_pid={self.num_pid}, niters={self.annodb_accums[-1]}, nsteps_frame={self.nsteps_frame}, nsteps_segmt={self.nsteps_segmt} ''') + logging.info(f'''num_pid={self.num_pid}, niters={self.__len__()}, nsteps_frame={self.nsteps_frame}, nsteps_segmt={self.nsteps_segmt} ''') + + + def __len__(self): + # return self.annodb_accums[-1] + return 20000 + + def count_annotations(self): + acc = 0 + annodb_accums = np.zeros(self.num_pid + 1, dtype=int) # the first element set 0 + for i, ikey in enumerate(self.annodb): + # logging.info(f"i = {i}, ikey={ikey}, shape = {self.annodb[ikey]['data_motion'].shape}") + acc += self.annodb[ikey]["data_motion"].shape[0] // (self.nsteps_frame * self.overlap) - 1 # ncount_windows + annodb_accums[i+1] = acc # 2 + + return annodb_accums + + + def __getitem__(self, idx): + """ + Returns poses and conditioning. + If data-dropout sould be applied, a random selection of the previous poses is masked. + The control is not masked + return: + motion: (nsteps, nc_motion), current frame's pose (15 joint, xyz position) + speech: (nsteps, nc_speech), conditional data = previous motion data + full windows contrl data + """ + np.random.seed(int(idx + time.time())) + vid = self.pids[idx % self.num_pid] + + # random select idx + data = self.annodb[vid] + data_motion = data["data_motion"] # (nframes, nc_motion) + data_speech = data["data_speech"] # (nsegemts, ) + + nframe = data_motion.shape[0] + nsegmt = data_speech.shape[0] + + if self.shifting_speed and random.random() < 0.3: + speed = random.sample({0.5, 0.7, 0.8, 0.9, 1.1, 1.2, 1.3, 1.4, 1.5},1)[0] + + beg_frame = np.random.randint(nframe - int(self.nsteps_frame * speed) - 10) + 5 # select from (5:-5) + end_frame = beg_frame + int(self.nsteps_frame * speed) + + beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt) + end_segmt = beg_segmt + int(self.nsteps_segmt * speed) + + data_motion = data_motion[beg_frame:end_frame] # (nteps, 53) + data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, ) + + assert data_speech.shape[0] == int(self.nsteps_segmt * speed), f"data_speech shape={data_speech.shape}, vid={vid}" + assert data_motion.shape[0] == int(self.nsteps_frame * speed), f"data_motion shape={data_motion.shape}, vid={vid}" + # logging.info(f"speed={speed}, data_speech shape={data_speech.shape} data_motion shape={data_motion.shape}") + + # resample to same nsteps + data_motion = resample_by_nsteps(data_motion, nsteps_tgt=self.nsteps_frame) + data_speech = resample_by_nsteps(data_speech, nsteps_tgt=self.nsteps_segmt) + # logging.info(f"resampling > data_speech shape={data_speech.shape} data_motion shape={data_motion.shape} \n") + + else: + # random select beg:end frame + beg_frame = np.random.randint(nframe - self.nsteps_frame - 10) + 5 # select from (5:-5) + end_frame = beg_frame + self.nsteps_frame + + beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt) + end_segmt = beg_segmt + self.nsteps_segmt + # logging.info(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\t nsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}") + + data_motion = data_motion[beg_frame:end_frame] # (nteps, 53) + data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, ) + assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}, [{beg_segmt:04d},{end_segmt:04d})" + assert data_motion.shape[0] == self.nsteps_frame, f"data_motion shape={data_motion.shape}, vid={vid}" + + # filter, explore doc: ./notebook/explore_pose.ipynb + if self.filter == "savgol": + data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest') + # data_shape = savgol_filter(data_shape, window_length=5, polyorder=3, axis=0, mode='nearest') + + + # random augments: reverse + if self.flip: + data_motion, data_speech = self.make_auguments_flip(data_motion, data_speech, p=0.3) + # logging.info(f"flip: data_motion-{data_motion.shape} data_speech={data_speech.shape}") + + # random augments: shuffle speed + result = { + "data": data_motion, # (nsteps_frame, dim_motion) + "cond": data_speech, # (nsteps_frame, dim_speech) + "vid": vid, + "nframe": nframe, + "frame_interval": [beg_frame, end_frame], + } + + return result + + + def make_auguments_flip(self, data_motion, data_speech, p=0.5): + ''' + parameters: + data_motion: (nsteps_motion, 53) + data_speech: (nsteps_speech, ), where nsteps_speech!= nsteps_motion + ''' + + if random.random() < p: + data_motion = data_motion[::-1].copy() + data_speech = data_speech[::-1].copy() + + return data_motion, data_speech diff --git a/src/datamodules/mnist_datamodule.py b/src/datasets/mnist_datamodule.py similarity index 100% rename from src/datamodules/mnist_datamodule.py rename to src/datasets/mnist_datamodule.py diff --git a/src/datasets/motion_datamodule.py b/src/datasets/motion_datamodule.py new file mode 100644 index 0000000..47b8daa --- /dev/null +++ b/src/datasets/motion_datamodule.py @@ -0,0 +1,77 @@ +from typing import Optional +from pytorch_lightning import LightningDataModule +from torch.utils.data import DataLoader, Dataset + + +class MotionDataModule(LightningDataModule): + """ + Example of LightningDataModule for MNIST dataset. + + A DataModule implements 5 key methods: + - prepare_data (things to do on 1 GPU/TPU, not on every GPU/TPU in distributed mode) + - setup (things to do on every accelerator in distributed mode) + - train_dataloader (the training dataloader) + - val_dataloader (the validation dataloader(s)) + - test_dataloader (the test dataloader(s)) + + This allows you to share a full dataset without explaining how to download, + split, transform and process the data. + + Read the docs: + https://pytorch-lightning.readthedocs.io/en/latest/extensions/datamodules.html + """ + + def __init__( + self, + batch_size_train: int = 128, + batch_size_test: int = 32, + num_workers: int = 0, + pin_memory: bool = False, + dataset_train: Optional[Dataset] = None, + dataset_valid: Optional[Dataset] = None, + dataset_test : Optional[Dataset] = None, + ): + super().__init__() + # this line allows to access init params with 'self' attribute + # self.save_hyperparameters(logger=False) + self.batch_size_train = batch_size_train + self.batch_size_test = batch_size_test + self.num_workers = num_workers + self.pin_memory = pin_memory + + self.dataset_train = dataset_train + self.dataset_valid = dataset_valid + self.dataset_test = dataset_test + + + def train_dataloader(self): + return DataLoader( + dataset=self.dataset_train, + batch_size=self.batch_size_train, + num_workers=self.num_workers, + pin_memory=self.pin_memory, + drop_last=False, + shuffle=True, + ) + + + def val_dataloader(self): + return DataLoader( + dataset=self.dataset_valid, + batch_size=self.batch_size_train, + num_workers=self.num_workers, + pin_memory=self.pin_memory, + drop_last=False, + shuffle=False, + ) + + + def test_dataloader(self): + return DataLoader( + dataset=self.dataset_test, + batch_size=self.batch_size_test, + num_workers=self.num_workers, + pin_memory=self.pin_memory, + drop_last=False, + shuffle=False, + ) diff --git a/src/losses/MultiLossManager.py b/src/losses/MultiLossManager.py new file mode 100644 index 0000000..57c3436 --- /dev/null +++ b/src/losses/MultiLossManager.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- + +import torch +import torch.nn as nn +from collections import OrderedDict + +class MultiLossManager(nn.Module): + """Managment Multiple-Loss + """ + + def __init__(self, opt, autoWeight=False): + super(MultiLossManager, self).__init__() + + self.opt = opt + self.autoWeight = autoWeight + + self.weight = {} + self.weigth_name = [] + + for iname in opt.LOSS.names: + iname_full = f"lambda_{iname}" + if iname_full in opt.LOSS.keys() and opt.LOSS[iname_full] > 0: + self.weight[ "loss_"+iname ] = opt.LOSS[iname_full] + self.weigth_name.append("loss_" + iname ) + + n_weight = len(self.weight) + + print(f"WEIGHT of LOSS (n={n_weight}) = {self.weight}") + + if autoWeight: + self.weight = torch.ones(n_weight, requires_grad=True) + self.weight = torch.nn.Parameter(self.weight) + + + def forward(self, dict_loss): + assert isinstance(dict_loss, OrderedDict), "dict_loss should be a OrderedDict" + + loss_sum = 0 + i = 0 + for name in dict_loss.keys(): + if name not in self.weigth_name: continue + + if self.autoWeight: + loss_sum += 0.5 / (self.weight[i] ** 2) * dict_loss[name] + torch.log(1 + self.weight[i] ** 2) + else: + loss_sum += (self.weight[name] * dict_loss[name]) + + i += 1 + + # print(f"update WEIGHT of LOSS {self.weight}") + + return loss_sum + + + +class AutomaticWeightedLoss(nn.Module): + """automatically weighted multi-task loss + Params: + num: int,the number of loss + x: multi-task loss + Examples: + loss1=1 + loss2=2 + awl = AutomaticWeightedLoss(2) + loss_sum = awl(loss1, loss2) + """ + def __init__(self, num=2): + super(AutomaticWeightedLoss, self).__init__() + params = torch.ones(num, requires_grad=True) + self.params = torch.nn.Parameter(params) + + + def forward(self, dict_loss): + + assert isinstance(dict_loss, OrderedDict), "dict_loss should be a OrderedDict" + + loss_sum = 0 + for i, name in enumerate(dict_loss.keys()): + + loss_sum += 0.5 / (self.params[i] ** 2) * dict_loss[name] + torch.log(1 + self.params[i] ** 2) + + return loss_sum + + +if __name__ == '__main__': + awl = AutomaticWeightedLoss(2) + print(awl.parameters()) \ No newline at end of file diff --git a/src/losses/__init__.py b/src/losses/__init__.py new file mode 100644 index 0000000..8ee66a3 --- /dev/null +++ b/src/losses/__init__.py @@ -0,0 +1,12 @@ +from .wing import WingLoss +from .smooth_l1_loss import SmoothL1Loss, L1Loss +# from .landmarkloss import LandmarkPolygonLoss, LandmarkFocalLoss +""" +Source: https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/losses/__init__.py + +""" + +__all__ = [ + "WingLoss", "AdaptiveWingLoss", "LandmarkPolygonLoss", "LandmarkFocalLoss" +] + diff --git a/src/losses/adaptive_wing.py b/src/losses/adaptive_wing.py new file mode 100644 index 0000000..e69de29 diff --git a/src/losses/landmarkloss.py b/src/losses/landmarkloss.py new file mode 100644 index 0000000..bba6953 --- /dev/null +++ b/src/losses/landmarkloss.py @@ -0,0 +1,115 @@ +import torch +import torch.nn as nn +import numpy as np + +from shapely.geometry import Polygon + + +class LandmarkPolygonLoss(nn.Module): + def __init__(self, opt): + super(LandmarkPolygonLoss, self).__init__() + + self.opt = opt + self.lmdk_indx = { + "chin": list(range(0,17)), + "eyebrow_lt": [17, 18, 19, 20, 21], + "eyebrow_rt": [22, 23, 24, 25, 26], + "nose": [27, 31, 32, 33, 34, 35], + "eye_lt": [36, 37, 38, 39, 40, 41], + "eye_rt": [42, 43, 44, 45, 46, 47], + "mouth_out": list(range(48, 60)), + "mouth_inn": list(range(60, 68)), + } + + def forward(self, pred, target): + # predit, (nbatch, 68*2) + # target, (nbatch, 68*2) + + #print(f"pred shape = {predit.shape}, target shape = {target.shape}") + pred = pred.reshape(-1, 68, 2) * 128 + target = target.reshape(-1, 68, 2) * 128 + + loss_chin = self.area_diff(pred, target, "chin") + loss_nose = self.area_diff(pred, target, "nose") + loss_eyebrow = self.area_diff(pred, target, "eyebrow_lt") \ + + self.area_diff(pred, target, "eyebrow_rt") + loss_eye = self.area_diff(pred, target, "eye_lt") \ + + self.area_diff(pred, target, "eye_rt") + loss_mouth = self.area_diff(pred, target, "mouth_out") \ + + self.area_diff(pred, target, "mouth_inn") + + loss = loss_chin + loss_nose + loss_eyebrow + loss_eye # + loss_mouth + loss = torch.mean(loss) + + return loss + + + + def area_diff(self, pred, target, part): + indx = self.lmdk_indx[part] + + area_pt = self.PolygonArea(pred, indx) + area_gt = self.PolygonArea(target, indx) + + diff = torch.abs(area_pt - area_gt) + return diff + + + def PolygonArea(self, corners, indx): + """PolygonArea Function. + Args: + corners (torch.Tensor): the keypoints of corners, (nbatch, 68, 2) + indx (list, int): the polygon index from the keypoints + Return: + area (torch.Tensor): (nbatch, ) + + """ + area, n = 0, len(indx) + for i in range(n): + j = (i + 1) % n + area += corners[:, i, 0] * corners[:, j, 1] + area -= corners[:, j, 0] * corners[:, i, 1] + + area = torch.abs(area) / 2.0 + return area + + + + + + +class LandmarkFocalLoss(nn.Module): + def __init__(self, opt): + super(LandmarkFocalLoss, self).__init__() + self.opt = opt + + + def forward(self, predit, target): + + # predit, (nbatch, 68*2) + # target, (nbatch, 68*2) + + #print(f"pred shape = {predit.shape}, target shape = {target.shape}") + predit = predit.reshape(-1, 68, 2) + target = target.reshape(-1, 68, 2) + + x = torch.abs(predit - target) # (nbatch, 68, 2) + x = torch.sqrt(x[:,:,0] * x[:,:,0] + x[:,:,1] * x[:,:,1]) # (nbatch, 68) + + #print(f"xsqrt = {x[0, :]}") + + x = torch.torch.pow(1 + 1000*x, x) - 1 # (nbatch, 68) + x = torch.clamp_max_(x, 10) + + #print(f"xpow = {x[0, :]}") + weight = torch.ones((68,), dtype=x.dtype, device=x.device) + weight[48:68] = 10 + + + x = torch.mean(x, dim=0) # (68, ) + x = torch.mean(x * weight) # (1, ) + + return x + + + diff --git a/src/losses/pfld_loss.py b/src/losses/pfld_loss.py new file mode 100644 index 0000000..d818107 --- /dev/null +++ b/src/losses/pfld_loss.py @@ -0,0 +1,13 @@ +import torch +import torch.nn as nn + +from .utils import weighted_loss + +@weighted_loss +def pfld_loss(pred, target, euler_pt, euler_gt, attribute_gt): + """PFLD loss. + Args: + pred (torch.Tensor): The prediction landmark. (nbatch, 68*2) + + + """ \ No newline at end of file diff --git a/src/losses/smooth_l1_loss.py b/src/losses/smooth_l1_loss.py new file mode 100644 index 0000000..c6dc963 --- /dev/null +++ b/src/losses/smooth_l1_loss.py @@ -0,0 +1,101 @@ +import torch +import torch.nn as nn + +from .utils import weighted_loss + +@weighted_loss +def l1_loss(pred, target): + """ L1 loss. + Args: + pred (torch.Tensor): The prediction. + target(torch.Tensor): The ground truth of the prediction + + Returns: + torch.Tensor: loss + """ + + assert pred.size() == target.size() and target.numel() > 0 + + loss = torch.abs(pred - target) + + return loss + +@weighted_loss +def smooth_l1_loss(pred, target, beta=1.0): + """Smooth L1 Loss. + Args: + pred (torch.Tensor): The prediction + target (torch.Tensor): The GT of the prediction + + Returns: + torch.Tensor: loss + """ + + assert beta > 0 + assert pred.size() == target.size() and target.numel() > 0 + + diff = torch.abs(pred - target) + loss = torch.where(diff < beta, 0.5 * diff * diff / beta, diff - 0.5 * beta) + + return loss + + + +class L1Loss(nn.Module): + """L1 Loss + Args: + reduction (str, optional): The method to reduce the loss, Options are `none|mean|sum` + loss_weight (float, optional): The weight of loss. + """ + + def __init__(self, reduction='mean', loss_weight=1.0): + super(L1Loss, self).__init__() + + self.reduction = reduction + self.loss_weight = loss_weight + + + def forward(self, pred, target, weight=None, avg_factor=None): + """Forward function. + + Args: + pred (troch.Tensor): The prediction + target (torch.Tensor): The GT of the prediction. + weight (torch.Tensor, optional): The weight of loss for each prediction. + avg_factor(int, optional): Average factor that is used to average the loss. + """ + + loss = l1_loss(pred, target, weight=weight, reduction=self.reduction, avg_factor=avg_factor) + loss = self.loss_weight * loss + + return loss + + +class SmoothL1Loss(nn.Module): + """Smooth L1 Loss. + Args: + beta (float, optional): The threshold in the piecewise function. Default 1.0 + reduction (str, optional): The reduce loss method, options are `none|mean|sum` + loss_weight (float, optional): The weight of loss + Return: + torch.Tensor: Loss + """ + + def __init__(self, beta=1.0, reduction="mean", loss_weight=1.0): + super(SmoothL1Loss, self).__init__() + self.beta = beta + self.reduction = reduction + self.loss_weight = loss_weight + + def forward(self, pred, target, weight=None, avg_factor=None): + """Forward function. + Args: + pred (torch.Tensor): The prediction. + target (torch.Tensor): The GT of the prediction + weight (torch.Tensor, optional): The weigth of loss for each prediction. Default to None + avg_factor (int, optional): Average factor that is used to average the loss. + """ + + loss = smooth_l1_loss(pred, target, beta=self.beta, weight=weight, avg_factor=avg_factor) + loss = self.loss_weight * loss + return loss diff --git a/src/losses/utils.py b/src/losses/utils.py new file mode 100644 index 0000000..92c7684 --- /dev/null +++ b/src/losses/utils.py @@ -0,0 +1,104 @@ +import functools + +import torch.nn.functional as F + +""" +Source: https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/losses/utils.py +""" + + +def reduce_loss(loss, reduction): + """Reduce loss as specified. + + Args: + loss (Tensor): Elementwise loss tensor. + reduction (str): Options are "none", "mean" and "sum". + + Return: + Tensor: Reduced loss tensor. + """ + reduction_enum = F._Reduction.get_enum(reduction) + # none: 0, elementwise_mean:1, sum: 2 + if reduction_enum == 0: + return loss + elif reduction_enum == 1: + return loss.mean() + elif reduction_enum == 2: + return loss.sum() + + +def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None): + """Apply element-wise weight and reduce loss. + + Args: + loss (Tensor): Element-wise loss. + weight (Tensor): Element-wise weights. + reduction (str): Same as built-in losses of PyTorch. + avg_factor (float): Avarage factor when computing the mean of losses. + + Returns: + Tensor: Processed loss values. + """ + # if weight is specified, apply element-wise weight + if weight is not None: + loss = loss * weight + + # if avg_factor is not specified, just reduce the loss + if avg_factor is None: + loss = reduce_loss(loss, reduction) + else: + # if reduction is mean, then average the loss by avg_factor + if reduction == 'mean': + loss = loss.sum() / avg_factor + # if reduction is 'none', then do nothing, otherwise raise an error + elif reduction != 'none': + raise ValueError('avg_factor can not be used with reduction="sum"') + return loss + + +def weighted_loss(loss_func): + """Create a weighted version of a given loss function. + + To use this decorator, the loss function must have the signature like + `loss_func(pred, target, **kwargs)`. The function only needs to compute + element-wise loss without any reduction. This decorator will add weight + and reduction arguments to the function. The decorated function will have + the signature like `loss_func(pred, target, weight=None, reduction='mean', + avg_factor=None, **kwargs)`. + + :Example: + + >>> import torch + >>> @weighted_loss + >>> def l1_loss(pred, target): + >>> return (pred - target).abs() + + >>> pred = torch.Tensor([0, 2, 3]) + >>> target = torch.Tensor([1, 1, 1]) + >>> weight = torch.Tensor([1, 0, 1]) + + >>> l1_loss(pred, target) + tensor(1.3333) + >>> l1_loss(pred, target, weight) + tensor(1.) + >>> l1_loss(pred, target, reduction='none') + tensor([1., 1., 2.]) + >>> l1_loss(pred, target, weight, avg_factor=2) + tensor(1.5000) + """ + + @functools.wraps(loss_func) + def wrapper(pred, + target, + weight=None, + reduction='mean', + avg_factor=None, + **kwargs): + + # get element-wise loss + loss = loss_func(pred, target, **kwargs) + + loss = weight_reduce_loss(loss, weight, reduction, avg_factor) + return loss + + return wrapper \ No newline at end of file diff --git a/src/losses/wing.py b/src/losses/wing.py new file mode 100644 index 0000000..2b69397 --- /dev/null +++ b/src/losses/wing.py @@ -0,0 +1,73 @@ +import math +import torch +from torch import nn + +from .utils import weighted_loss + +""" +The Wing loss: + +It has been proposed in `Wing Loss for Roubst Facial Landmark Localisation with +Convolutional Neural Networks`. https://arxiv.org/abs/1711.06753 + +""" + + +@weighted_loss +def wing_loss(pred, target, w=5, epsilon=0.5): + """ + Source: https://github.com/BloodAxe/pytorch-toolbelt/blob/develop/pytorch_toolbelt/losses/functional.py + + """ + + diff = torch.abs(pred - target) + C = w - w * math.log(1 + w / epsilon) + loss = torch.where(diff < w, w * torch.log(1 + diff / epsilon), diff - C) + + return loss + + + +class WingLoss(nn.Module): + + def __init__(self, w=10, epsilon=0.5, reduction='mean', loss_weight=1.0): + super(WingLoss,self).__init__() + + self.w = w + self.epsilon = epsilon + self.reduction = reduction + self.loss_weight = loss_weight + + def forward(self, pred, target, weight=None, avg_factor=None): + """Forward function. + Args: + pred (torch.Tensor, Bx68*2): The prediction + target (torch.Tensor, Bx68*2): The GT of prediction + weight (torch.Tensor, optional): The weight of each loss, default None + avg_factor(int, optional): The average of the reduction loss + """ + + loss = wing_loss(pred, target, w=self.w, epsilon=self.epsilon, weight=weight, avg_factor=avg_factor) + loss = self.loss_weight * loss + + return loss + + + + + + + +if __name__ == "__main__": + crieation = WingLoss() + + GT = torch.zeros((2, 68, 64, 64)) + PT = torch.ones((2, 68, 64, 64)) + PT.requires_grad_(True) + + loss = crieation(PT, GT) + loss.backward() + + print(loss) + + diff --git a/src/mesh/FLAME.py b/src/mesh/FLAME.py new file mode 100644 index 0000000..e898904 --- /dev/null +++ b/src/mesh/FLAME.py @@ -0,0 +1,320 @@ +# -*- coding: utf-8 -*- +# +# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is +# holder of all proprietary rights on this computer program. +# Using this computer program means that you agree to the terms +# in the LICENSE file included with this software distribution. +# Any use not explicitly granted by the LICENSE is prohibited. +# +# Copyright©2019 Max-Planck-Gesellschaft zur Förderung +# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute +# for Intelligent Systems. All rights reserved. +# +# For comments or questions, please email us at deca@tue.mpg.de +# For commercial licensing contact, please contact ps-license@tuebingen.mpg.de +import torch +import torch.nn as nn +import numpy as np +import pickle +import torch.nn.functional as F +import pprint + +from .lbs import lbs, batch_rodrigues, vertices2landmarks, rot_mat_to_euler + +def to_tensor(array, dtype=torch.float32): + if 'torch.tensor' not in str(type(array)): + return torch.tensor(array, dtype=dtype) +def to_np(array, dtype=np.float32): + if 'scipy.sparse' in str(type(array)): + array = array.todense() + return np.array(array, dtype=dtype) + +class Struct(object): + def __init__(self, **kwargs): + for key, val in kwargs.items(): + setattr(self, key, val) + +class FLAME(nn.Module): + """ + borrowed from https://github.com/soubhiksanyal/FLAME_PyTorch/blob/master/FLAME.py + Given flame parameters this class generates a differentiable FLAME function + which outputs the a mesh and 2D/3D facial landmarks + """ + def __init__(self, config): + super(FLAME, self).__init__() + + # print("creating the FLAME Decoder") + with open(config.flame_model_path, 'rb') as f: + ss = pickle.load(f, encoding='latin1') + flame_model = Struct(**ss) + + self.dtype = torch.float32 + self.register_buffer('faces_tensor', to_tensor(to_np(flame_model.f, dtype=np.int64), dtype=torch.long)) # (9976 x 3) + # print(f"[init FLAME] faces_tensor shape = {self.faces_tensor.shape}") + + # The vertices of the template model + self.register_buffer('v_template', to_tensor(to_np(flame_model.v_template), dtype=self.dtype)) # (5023 x 3) + # print(f"[init FLAME] v_template shape = {self.v_template.shape}") + + # The shape components and expression + shapedirs = to_tensor(to_np(flame_model.shapedirs), dtype=self.dtype) # (5023, 3, 400) + # print(f"[init FLAME] shapedirs shape = {shapedirs.shape}") + + shapedirs = torch.cat([shapedirs[:, :, :config.n_shape], # (5023, 3, 100) + shapedirs[:, :, 300:300+config.n_exp]], 2) # (5023, 3, 50) + self.register_buffer('shapedirs', shapedirs) # (5023, 3, 150) + # print(f"[init FLAME] shapedirs shape (after trim)= {self.shapedirs.shape}") + + # The pose components + num_pose_basis = flame_model.posedirs.shape[-1] + posedirs = np.reshape(flame_model.posedirs, [-1, num_pose_basis]).T # (36, 15069) + self.register_buffer('posedirs', to_tensor(to_np(posedirs), dtype=self.dtype)) + # print(f"[init FLAME] posedirs shape = {self.posedirs.shape}") + + # Joint regressor + self.register_buffer('J_regressor', to_tensor(to_np(flame_model.J_regressor), dtype=self.dtype)) + + # parents + parents = to_tensor(to_np(flame_model.kintree_table[0])).long(); parents[0] = -1 + self.register_buffer('parents', parents) + + # lbs weigth + self.register_buffer('lbs_weights', to_tensor(to_np(flame_model.weights), dtype=self.dtype)) + + # Fixing Eyeball and neck rotation + default_eyball_pose = torch.zeros([1, 6], dtype=self.dtype, requires_grad=False) + self.register_parameter('eye_pose', nn.Parameter(default_eyball_pose, requires_grad=False)) + + default_neck_pose = torch.zeros([1, 3], dtype=self.dtype, requires_grad=False) + self.register_parameter('neck_pose', nn.Parameter(default_neck_pose, requires_grad=False)) + + # Static and Dynamic Landmark embeddings for FLAME + lmk_embeddings = np.load(config.flame_lmk_embedding_path, allow_pickle=True, encoding='latin1') + lmk_embeddings = lmk_embeddings[()] + self.register_buffer('lmk_faces_idx', torch.from_numpy(lmk_embeddings['static_lmk_faces_idx']).long()) + self.register_buffer('lmk_bary_coords', torch.from_numpy(lmk_embeddings['static_lmk_bary_coords']).to(self.dtype)) + self.register_buffer('dynamic_lmk_faces_idx', lmk_embeddings['dynamic_lmk_faces_idx'].long()) + self.register_buffer('dynamic_lmk_bary_coords', lmk_embeddings['dynamic_lmk_bary_coords'].to(self.dtype)) + self.register_buffer('full_lmk_faces_idx', torch.from_numpy(lmk_embeddings['full_lmk_faces_idx']).long()) + self.register_buffer('full_lmk_bary_coords', torch.from_numpy(lmk_embeddings['full_lmk_bary_coords']).to(self.dtype)) + + neck_kin_chain = []; NECK_IDX=1 + curr_idx = torch.tensor(NECK_IDX, dtype=torch.long) + while curr_idx != -1: + neck_kin_chain.append(curr_idx) + curr_idx = self.parents[curr_idx] + self.register_buffer('neck_kin_chain', torch.stack(neck_kin_chain)) + + def _find_dynamic_lmk_idx_and_bcoords(self, pose, dynamic_lmk_faces_idx, + dynamic_lmk_b_coords, + neck_kin_chain, dtype=torch.float32): + """ + Selects the face contour depending on the reletive position of the head + Input: + vertices: N X num_of_vertices X 3 + pose: N X full pose + dynamic_lmk_faces_idx: The list of contour face indexes + dynamic_lmk_b_coords: The list of contour barycentric weights + neck_kin_chain: The tree to consider for the relative rotation + dtype: Data type + return: + The contour face indexes and the corresponding barycentric weights + """ + + batch_size = pose.shape[0] + + aa_pose = torch.index_select(pose.view(batch_size, -1, 3), 1, neck_kin_chain) + + rot_mats = batch_rodrigues(aa_pose.view(-1, 3), dtype=dtype)\ + .view(batch_size, -1, 3, 3) + + rel_rot_mat = torch.eye(3, device=pose.device, dtype=dtype)\ + .unsqueeze_(dim=0).expand(batch_size, -1, -1) + + for idx in range(len(neck_kin_chain)): + rel_rot_mat = torch.bmm(rot_mats[:, idx], rel_rot_mat) + + y_rot_angle = torch.round(torch.clamp(rot_mat_to_euler(rel_rot_mat) * 180.0 / np.pi, max=39)).to(dtype=torch.long) + + neg_mask = y_rot_angle.lt(0).to(dtype=torch.long) + mask = y_rot_angle.lt(-39).to(dtype=torch.long) + neg_vals = mask * 78 + (1 - mask) * (39 - y_rot_angle) + y_rot_angle = (neg_mask * neg_vals + (1 - neg_mask) * y_rot_angle) + + dyn_lmk_faces_idx = torch.index_select(dynamic_lmk_faces_idx, 0, y_rot_angle) + dyn_lmk_b_coords = torch.index_select(dynamic_lmk_b_coords, 0, y_rot_angle) + return dyn_lmk_faces_idx, dyn_lmk_b_coords + + def _vertices2landmarks(self, vertices, faces, lmk_faces_idx, lmk_bary_coords): + """ + Calculates landmarks by barycentric interpolation + Input: + vertices: torch.tensor NxVx3, dtype = torch.float32 + The tensor of input vertices + faces: torch.tensor (N*F)x3, dtype = torch.long + The faces of the mesh + lmk_faces_idx: torch.tensor N X L, dtype = torch.long + The tensor with the indices of the faces used to calculate the + landmarks. + lmk_bary_coords: torch.tensor N X L X 3, dtype = torch.float32 + The tensor of barycentric coordinates that are used to interpolate + the landmarks + + Returns: + landmarks: torch.tensor NxLx3, dtype = torch.float32 + The coordinates of the landmarks for each mesh in the batch + """ + # Extract the indices of the vertices for each face + # NxLx3 + batch_size, num_verts = vertices.shape[:2] + lmk_faces = torch.index_select(faces, 0, lmk_faces_idx.view(-1))\ + .view(1, -1, 3).view(batch_size, lmk_faces_idx.shape[1], -1) + + lmk_faces += torch.arange(batch_size, dtype=torch.long)\ + .view(-1, 1, 1).to(device=vertices.device) * num_verts + + lmk_vertices = vertices.view(-1, 3)[lmk_faces] + landmarks = torch.einsum('blfi,blf->bli', [lmk_vertices, lmk_bary_coords]) + + return landmarks + + + def seletec_2d68(self, vertices, pose): + """ need pose parameters + """ + + batch_size = vertices.shape[0] + + lmk_faces_idx = self.lmk_faces_idx.unsqueeze(dim=0).expand(batch_size, -1) + lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).expand(batch_size, -1, -1) + + dyn_lmk_faces_idx, dyn_lmk_bary_coords = self._find_dynamic_lmk_idx_and_bcoords( + pose, self.dynamic_lmk_faces_idx, + self.dynamic_lmk_bary_coords, + self.neck_kin_chain, dtype=self.dtype) + lmk_faces_idx = torch.cat([dyn_lmk_faces_idx, lmk_faces_idx], 1) + lmk_bary_coords = torch.cat([dyn_lmk_bary_coords, lmk_bary_coords], 1) + + landmarks2d = vertices2landmarks(vertices, self.faces_tensor, + lmk_faces_idx, + lmk_bary_coords) + + return landmarks2d + + + def seletec_3d68(self, vertices): + landmarks3d = vertices2landmarks(vertices, self.faces_tensor, + self.full_lmk_faces_idx.repeat(vertices.shape[0], 1), + self.full_lmk_bary_coords.repeat(vertices.shape[0], 1, 1)) + return landmarks3d + + + def forward(self, shape_params=None, expression_params=None, pose_params=None, eye_pose_params=None, template_vertices=None): + """ + Input: + shape_params: N X number of shape parameters + expression_params: N X number of expression parameters + pose_params: N X number of pose parameters (6) + return:d + vertices: N X V X 3 + landmarks: N X number of landmarks X 3 + """ + + + batch_size = shape_params.shape[0] + + if pose_params is None: + pose_params = self.eye_pose.expand(batch_size, -1) # (B x 6) + if eye_pose_params is None: + eye_pose_params = self.eye_pose.expand(batch_size, -1) # (B x 6) + + # print(f"shape_params = {shape_params.shape}, expression_params={expression_params.shape}, pose_params={pose_params.shape}") + # print(f"batch_size = {batch_size}, self.neck_pose={self.neck_pose.shape}") + + betas = torch.cat([ # (B x 150) + shape_params, # (B x 100), shape + expression_params # (B x 50), expression + ], dim=1) + + pose = torch.cat([ # (B x 18) + pose_params[:, :3], # (B x 3), head pose + self.neck_pose.expand(batch_size, -1), # (B x 6), neck pose + pose_params[:, 3:], # (B x 3), mouth pose + eye_pose_params # (B x 6), eye pose + ], dim=1) + + if template_vertices is None: + template_vertices = self.v_template.unsqueeze(0).expand(batch_size, -1, -1) # (B x 5023 x 3) + + vertices, _ = lbs(betas, pose, template_vertices, + self.shapedirs, self.posedirs, + self.J_regressor, self.parents, + self.lbs_weights, dtype=self.dtype) + + lmk_faces_idx = self.lmk_faces_idx.unsqueeze(dim=0).expand(batch_size, -1) + lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).expand(batch_size, -1, -1) + + dyn_lmk_faces_idx, dyn_lmk_bary_coords = self._find_dynamic_lmk_idx_and_bcoords( + pose, self.dynamic_lmk_faces_idx, + self.dynamic_lmk_bary_coords, + self.neck_kin_chain, dtype=self.dtype) + lmk_faces_idx = torch.cat([dyn_lmk_faces_idx, lmk_faces_idx], 1) + lmk_bary_coords = torch.cat([dyn_lmk_bary_coords, lmk_bary_coords], 1) + + landmarks2d = vertices2landmarks(vertices, self.faces_tensor, + lmk_faces_idx, + lmk_bary_coords) + bz = vertices.shape[0] + landmarks3d = vertices2landmarks(vertices, self.faces_tensor, + self.full_lmk_faces_idx.repeat(bz, 1), + self.full_lmk_bary_coords.repeat(bz, 1, 1)) + + return vertices, landmarks2d, landmarks3d + +class FLAMETex(nn.Module): + """ + FLAME texture: + https://github.com/TimoBolkart/TF_FLAME/blob/ade0ab152300ec5f0e8555d6765411555c5ed43d/sample_texture.py#L64 + FLAME texture converted from BFM: + https://github.com/TimoBolkart/BFM_to_FLAME + """ + def __init__(self, config): + super(FLAMETex, self).__init__() + if config.tex_type == 'BFM': + mu_key = 'MU' + pc_key = 'PC' + n_pc = 199 + tex_path = config.tex_path + tex_space = np.load(tex_path) + texture_mean = tex_space[mu_key].reshape(1, -1) + texture_basis = tex_space[pc_key].reshape(-1, n_pc) + + elif config.tex_type == 'FLAME': + mu_key = 'mean' + pc_key = 'tex_dir' + n_pc = 200 + tex_path = config.flame_tex_path + tex_space = np.load(tex_path) + texture_mean = tex_space[mu_key].reshape(1, -1)/255. + texture_basis = tex_space[pc_key].reshape(-1, n_pc)/255. + else: + print('texture type ', config.tex_type, 'not exist!') + raise NotImplementedError + + n_tex = config.n_tex + num_components = texture_basis.shape[1] + texture_mean = torch.from_numpy(texture_mean).float()[None,...] + texture_basis = torch.from_numpy(texture_basis[:,:n_tex]).float()[None,...] + self.register_buffer('texture_mean', texture_mean) + self.register_buffer('texture_basis', texture_basis) + + def forward(self, texcode): + ''' + texcode: [batchsize, n_tex] + texture: [bz, 3, 256, 256], range: 0-1 + ''' + texture = self.texture_mean + (self.texture_basis*texcode[:,None,:]).sum(-1) + texture = texture.reshape(texcode.shape[0], 512, 512, 3).permute(0,3,1,2) + texture = F.interpolate(texture, [256, 256]) + texture = texture[:,[2,1,0], :,:] + return texture \ No newline at end of file diff --git a/src/mesh/lbs.py b/src/mesh/lbs.py new file mode 100644 index 0000000..b9c8748 --- /dev/null +++ b/src/mesh/lbs.py @@ -0,0 +1,377 @@ +# -*- coding: utf-8 -*- + +# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is +# holder of all proprietary rights on this computer program. +# You can only use this computer program if you have closed +# a license agreement with MPG or you get the right to use the computer +# program from someone who is authorized to grant you that right. +# Any use of the computer program without a valid license is prohibited and +# liable to prosecution. +# +# Copyright©2019 Max-Planck-Gesellschaft zur Förderung +# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute +# for Intelligent Systems. All rights reserved. +# +# Contact: ps-license@tuebingen.mpg.de + +from __future__ import absolute_import +from __future__ import print_function +from __future__ import division + +import numpy as np + +import torch +import torch.nn.functional as F + +def rot_mat_to_euler(rot_mats): + # Calculates rotation matrix to euler angles + # Careful for extreme cases of eular angles like [0.0, pi, 0.0] + + sy = torch.sqrt(rot_mats[:, 0, 0] * rot_mats[:, 0, 0] + + rot_mats[:, 1, 0] * rot_mats[:, 1, 0]) + return torch.atan2(-rot_mats[:, 2, 0], sy) + +def find_dynamic_lmk_idx_and_bcoords(vertices, pose, dynamic_lmk_faces_idx, + dynamic_lmk_b_coords, + neck_kin_chain, dtype=torch.float32): + ''' Compute the faces, barycentric coordinates for the dynamic landmarks + + + To do so, we first compute the rotation of the neck around the y-axis + and then use a pre-computed look-up table to find the faces and the + barycentric coordinates that will be used. + + Special thanks to Soubhik Sanyal (soubhik.sanyal@tuebingen.mpg.de) + for providing the original TensorFlow implementation and for the LUT. + + Parameters + ---------- + vertices: torch.tensor BxVx3, dtype = torch.float32 + The tensor of input vertices + pose: torch.tensor Bx(Jx3), dtype = torch.float32 + The current pose of the body model + dynamic_lmk_faces_idx: torch.tensor L, dtype = torch.long + The look-up table from neck rotation to faces + dynamic_lmk_b_coords: torch.tensor Lx3, dtype = torch.float32 + The look-up table from neck rotation to barycentric coordinates + neck_kin_chain: list + A python list that contains the indices of the joints that form the + kinematic chain of the neck. + dtype: torch.dtype, optional + + Returns + ------- + dyn_lmk_faces_idx: torch.tensor, dtype = torch.long + A tensor of size BxL that contains the indices of the faces that + will be used to compute the current dynamic landmarks. + dyn_lmk_b_coords: torch.tensor, dtype = torch.float32 + A tensor of size BxL that contains the indices of the faces that + will be used to compute the current dynamic landmarks. + ''' + + batch_size = vertices.shape[0] + + aa_pose = torch.index_select(pose.view(batch_size, -1, 3), 1, + neck_kin_chain) + rot_mats = batch_rodrigues( + aa_pose.view(-1, 3), dtype=dtype).view(batch_size, -1, 3, 3) + + rel_rot_mat = torch.eye(3, device=vertices.device, + dtype=dtype).unsqueeze_(dim=0) + for idx in range(len(neck_kin_chain)): + rel_rot_mat = torch.bmm(rot_mats[:, idx], rel_rot_mat) + + y_rot_angle = torch.round( + torch.clamp(-rot_mat_to_euler(rel_rot_mat) * 180.0 / np.pi, + max=39)).to(dtype=torch.long) + neg_mask = y_rot_angle.lt(0).to(dtype=torch.long) + mask = y_rot_angle.lt(-39).to(dtype=torch.long) + neg_vals = mask * 78 + (1 - mask) * (39 - y_rot_angle) + y_rot_angle = (neg_mask * neg_vals + + (1 - neg_mask) * y_rot_angle) + + dyn_lmk_faces_idx = torch.index_select(dynamic_lmk_faces_idx, + 0, y_rot_angle) + dyn_lmk_b_coords = torch.index_select(dynamic_lmk_b_coords, + 0, y_rot_angle) + + return dyn_lmk_faces_idx, dyn_lmk_b_coords + + +def vertices2landmarks(vertices, faces, lmk_faces_idx, lmk_bary_coords): + ''' Calculates landmarks by barycentric interpolation + + Parameters + ---------- + vertices: torch.tensor BxVx3, dtype = torch.float32 + The tensor of input vertices + faces: torch.tensor Fx3, dtype = torch.long + The faces of the mesh + lmk_faces_idx: torch.tensor L, dtype = torch.long + The tensor with the indices of the faces used to calculate the + landmarks. + lmk_bary_coords: torch.tensor Lx3, dtype = torch.float32 + The tensor of barycentric coordinates that are used to interpolate + the landmarks + + Returns + ------- + landmarks: torch.tensor BxLx3, dtype = torch.float32 + The coordinates of the landmarks for each mesh in the batch + ''' + # Extract the indices of the vertices for each face + # BxLx3 + batch_size, num_verts = vertices.shape[:2] + device = vertices.device + + lmk_faces = torch.index_select(faces, 0, lmk_faces_idx.view(-1)).view( + batch_size, -1, 3) + + lmk_faces += torch.arange( + batch_size, dtype=torch.long, device=device).view(-1, 1, 1) * num_verts + + lmk_vertices = vertices.view(-1, 3)[lmk_faces].view( + batch_size, -1, 3, 3) + + landmarks = torch.einsum('blfi,blf->bli', [lmk_vertices, lmk_bary_coords]) + return landmarks + + +def lbs(betas, pose, v_template, shapedirs, posedirs, J_regressor, parents, + lbs_weights, pose2rot=True, dtype=torch.float32): + ''' Performs Linear Blend Skinning with the given shape and pose parameters + + Parameters + ---------- + betas : torch.tensor BxNB + The tensor of shape parameters + pose : torch.tensor Bx(J + 1) * 3 + The pose parameters in axis-angle format + v_template torch.tensor BxVx3 + The template mesh that will be deformed + shapedirs : torch.tensor 1xNB + The tensor of PCA shape displacements + posedirs : torch.tensor Px(V * 3) + The pose PCA coefficients + J_regressor : torch.tensor JxV + The regressor array that is used to calculate the joints from + the position of the vertices + parents: torch.tensor J + The array that describes the kinematic tree for the model + lbs_weights: torch.tensor N x V x (J + 1) + The linear blend skinning weights that represent how much the + rotation matrix of each part affects each vertex + pose2rot: bool, optional + Flag on whether to convert the input pose tensor to rotation + matrices. The default value is True. If False, then the pose tensor + should already contain rotation matrices and have a size of + Bx(J + 1)x9 + dtype: torch.dtype, optional + + Returns + ------- + verts: torch.tensor BxVx3 + The vertices of the mesh after applying the shape and pose + displacements. + joints: torch.tensor BxJx3 + The joints of the model + ''' + + batch_size = max(betas.shape[0], pose.shape[0]) + device = betas.device + + # Add shape contribution + v_shaped = v_template + blend_shapes(betas, shapedirs) + + # Get the joints + # NxJx3 array + J = vertices2joints(J_regressor, v_shaped) + + # 3. Add pose blend shapes + # N x J x 3 x 3 + ident = torch.eye(3, dtype=dtype, device=device) + if pose2rot: + rot_mats = batch_rodrigues( + pose.view(-1, 3), dtype=dtype).view([batch_size, -1, 3, 3]) + + pose_feature = (rot_mats[:, 1:, :, :] - ident).view([batch_size, -1]) + # (N x P) x (P, V * 3) -> N x V x 3 + pose_offsets = torch.matmul(pose_feature, posedirs).view(batch_size, -1, 3) + else: + pose_feature = pose[:, 1:].view(batch_size, -1, 3, 3) - ident + rot_mats = pose.view(batch_size, -1, 3, 3) + + pose_offsets = torch.matmul(pose_feature.view(batch_size, -1), + posedirs).view(batch_size, -1, 3) + + v_posed = pose_offsets + v_shaped + # 4. Get the global joint location + J_transformed, A = batch_rigid_transform(rot_mats, J, parents, dtype=dtype) + + # 5. Do skinning: + # W is N x V x (J + 1) + W = lbs_weights.unsqueeze(dim=0).expand([batch_size, -1, -1]) + # (N x V x (J + 1)) x (N x (J + 1) x 16) + num_joints = J_regressor.shape[0] + T = torch.matmul(W, A.view(batch_size, num_joints, 16)) \ + .view(batch_size, -1, 4, 4) + + homogen_coord = torch.ones([batch_size, v_posed.shape[1], 1], + dtype=dtype, device=device) + v_posed_homo = torch.cat([v_posed, homogen_coord], dim=2) + v_homo = torch.matmul(T, torch.unsqueeze(v_posed_homo, dim=-1)) + + verts = v_homo[:, :, :3, 0] + + return verts, J_transformed + + +def vertices2joints(J_regressor, vertices): + ''' Calculates the 3D joint locations from the vertices + + Parameters + ---------- + J_regressor : torch.tensor JxV + The regressor array that is used to calculate the joints from the + position of the vertices + vertices : torch.tensor BxVx3 + The tensor of mesh vertices + + Returns + ------- + torch.tensor BxJx3 + The location of the joints + ''' + + return torch.einsum('bik,ji->bjk', [vertices, J_regressor]) + + +def blend_shapes(betas, shape_disps): + ''' Calculates the per vertex displacement due to the blend shapes + + + Parameters + ---------- + betas : torch.tensor Bx(num_betas) + Blend shape coefficients + shape_disps: torch.tensor Vx3x(num_betas) + Blend shapes + + Returns + ------- + torch.tensor BxVx3 + The per-vertex displacement due to shape deformation + ''' + + # Displacement[b, m, k] = sum_{l} betas[b, l] * shape_disps[m, k, l] + # i.e. Multiply each shape displacement by its corresponding beta and + # then sum them. + blend_shape = torch.einsum('bl,mkl->bmk', [betas, shape_disps]) + return blend_shape + + +def batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32): + ''' Calculates the rotation matrices for a batch of rotation vectors + Parameters + ---------- + rot_vecs: torch.tensor Nx3 + array of N axis-angle vectors + Returns + ------- + R: torch.tensor Nx3x3 + The rotation matrices for the given axis-angle parameters + ''' + + batch_size = rot_vecs.shape[0] + device = rot_vecs.device + + angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True) + rot_dir = rot_vecs / angle + + cos = torch.unsqueeze(torch.cos(angle), dim=1) + sin = torch.unsqueeze(torch.sin(angle), dim=1) + + # Bx1 arrays + rx, ry, rz = torch.split(rot_dir, 1, dim=1) + K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device) + + zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device) + K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \ + .view((batch_size, 3, 3)) + + ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0) + rot_mat = ident + sin * K + (1 - cos) * torch.bmm(K, K) + return rot_mat + + +def transform_mat(R, t): + ''' Creates a batch of transformation matrices + Args: + - R: Bx3x3 array of a batch of rotation matrices + - t: Bx3x1 array of a batch of translation vectors + Returns: + - T: Bx4x4 Transformation matrix + ''' + # No padding left or right, only add an extra row + return torch.cat([F.pad(R, [0, 0, 0, 1]), + F.pad(t, [0, 0, 0, 1], value=1)], dim=2) + + +def batch_rigid_transform(rot_mats, joints, parents, dtype=torch.float32): + """ + Applies a batch of rigid transformations to the joints + + Parameters + ---------- + rot_mats : torch.tensor BxNx3x3 + Tensor of rotation matrices + joints : torch.tensor BxNx3 + Locations of joints + parents : torch.tensor BxN + The kinematic tree of each object + dtype : torch.dtype, optional: + The data type of the created tensors, the default is torch.float32 + + Returns + ------- + posed_joints : torch.tensor BxNx3 + The locations of the joints after applying the pose rotations + rel_transforms : torch.tensor BxNx4x4 + The relative (with respect to the root joint) rigid transformations + for all the joints + """ + + joints = torch.unsqueeze(joints, dim=-1) + + rel_joints = joints.clone() + rel_joints[:, 1:] -= joints[:, parents[1:]] + + # transforms_mat = transform_mat( + # rot_mats.view(-1, 3, 3), + # rel_joints.view(-1, 3, 1)).view(-1, joints.shape[1], 4, 4) + transforms_mat = transform_mat( + rot_mats.view(-1, 3, 3), + rel_joints.reshape(-1, 3, 1)).reshape(-1, joints.shape[1], 4, 4) + + transform_chain = [transforms_mat[:, 0]] + for i in range(1, parents.shape[0]): + # Subtract the joint location at the rest pose + # No need for rotation, since it's identity when at rest + curr_res = torch.matmul(transform_chain[parents[i]], + transforms_mat[:, i]) + transform_chain.append(curr_res) + + transforms = torch.stack(transform_chain, dim=1) + + # The last column of the transformations contains the posed joints + posed_joints = transforms[:, :, :3, 3] + + # The last column of the transformations contains the posed joints + posed_joints = transforms[:, :, :3, 3] + + joints_homogen = F.pad(joints, [0, 0, 0, 1]) + + rel_transforms = transforms - F.pad( + torch.matmul(transforms, joints_homogen), [3, 0, 0, 0, 0, 0, 0, 0]) + + return posed_joints, rel_transforms \ No newline at end of file diff --git a/src/mesh/rasterizer/INSTALL.md b/src/mesh/rasterizer/INSTALL.md new file mode 100644 index 0000000..de2cc01 --- /dev/null +++ b/src/mesh/rasterizer/INSTALL.md @@ -0,0 +1,29 @@ +## Install +from standard_rasterize_cuda import standard_rasterize + # from .rasterizer.standard_rasterize_cuda import standard_rasterize + +in this folder, run +```python setup.py build_ext -i ``` + +then remember to set --rasterizer_type=standard when runing demos :) + +## Alg +https://www.scratchapixel.com/lessons/3d-basic-rendering/rasterization-practical-implementation + +## Speed Comparison +runtime for raterization only +In PIXIE, number of faces in SMPLX: 20908 + +for image size = 1024 +pytorch3d: 0.031s +standard: 0.01s + +for image size = 224 +pytorch3d: 0.0035s +standard: 0.0014s + +why standard rasterizer is faster than pytorch3d? +Ref: https://github.com/facebookresearch/pytorch3d/blob/master/pytorch3d/csrc/rasterize_meshes/rasterize_meshes.cu +pytorch3d: for each pixel in image space (each pixel is parallel in cuda), loop through the faces, check if this pixel is in the projection bounding box of the face, then sorting faces according to z, record the face id of closest K faces. +standard rasterization: for each face in mesh (each face is parallel in cuda), loop through pixels in the projection bounding box (normally a very samll number), compare z, record face id of that pixel + diff --git a/src/mesh/rasterizer/__init__.py b/src/mesh/rasterizer/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/src/mesh/rasterizer/setup.py b/src/mesh/rasterizer/setup.py new file mode 100755 index 0000000..8c559a1 --- /dev/null +++ b/src/mesh/rasterizer/setup.py @@ -0,0 +1,24 @@ +# To install, run +# python setup.py build_ext -i +# Ref: https://github.com/pytorch/pytorch/blob/11a40410e755b1fe74efe9eaa635e7ba5712846b/test/cpp_extensions/setup.py#L62 + +from setuptools import setup +from torch.utils.cpp_extension import BuildExtension, CUDAExtension +import os + +# USE_NINJA = os.getenv('USE_NINJA') == '1' +os.environ["CC"] = "gcc-7" +os.environ["CXX"] = "gcc-7" + +USE_NINJA = os.getenv('USE_NINJA') == '1' + +setup( + name='standard_rasterize_cuda', + ext_modules=[ + CUDAExtension('standard_rasterize_cuda', [ + 'standard_rasterize_cuda.cpp', + 'standard_rasterize_cuda_kernel.cu', + ]) + ], + cmdclass={'build_ext': BuildExtension.with_options(use_ninja=USE_NINJA)} +) diff --git a/src/mesh/rasterizer/standard_rasterize_cuda.cpp b/src/mesh/rasterizer/standard_rasterize_cuda.cpp new file mode 100755 index 0000000..d481580 --- /dev/null +++ b/src/mesh/rasterizer/standard_rasterize_cuda.cpp @@ -0,0 +1,48 @@ +#include +#include +#include + +std::vector forward_rasterize_cuda( + at::Tensor face_vertices, + at::Tensor depth_buffer, + at::Tensor triangle_buffer, + at::Tensor baryw_buffer, + int h, + int w); + +std::vector standard_rasterize( + at::Tensor face_vertices, + at::Tensor depth_buffer, + at::Tensor triangle_buffer, + at::Tensor baryw_buffer, + int height, int width + ) { + return forward_rasterize_cuda(face_vertices, depth_buffer, triangle_buffer, baryw_buffer, height, width); +} + +std::vector forward_rasterize_colors_cuda( + at::Tensor face_vertices, + at::Tensor face_colors, + at::Tensor depth_buffer, + at::Tensor triangle_buffer, + at::Tensor images, + int h, + int w); + +std::vector standard_rasterize_colors( + at::Tensor face_vertices, + at::Tensor face_colors, + at::Tensor depth_buffer, + at::Tensor triangle_buffer, + at::Tensor images, + int height, int width + ) { + return forward_rasterize_colors_cuda(face_vertices, face_colors, depth_buffer, triangle_buffer, images, height, width); +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("standard_rasterize", &standard_rasterize, "RASTERIZE (CUDA)"); + m.def("standard_rasterize_colors", &standard_rasterize_colors, "RASTERIZE COLORS (CUDA)"); +} + +// TODO: backward \ No newline at end of file diff --git a/src/mesh/rasterizer/standard_rasterize_cuda_kernel.cu b/src/mesh/rasterizer/standard_rasterize_cuda_kernel.cu new file mode 100755 index 0000000..f88432b --- /dev/null +++ b/src/mesh/rasterizer/standard_rasterize_cuda_kernel.cu @@ -0,0 +1,319 @@ +// Ref: https://github.com/daniilidis-group/neural_renderer/blob/master/neural_renderer/cuda/rasterize_cuda_kernel.cu +// https://github.com/YadiraF/face3d/blob/master/face3d/mesh/cython/mesh_core.cpp + +#include + +#include +#include + +namespace{ +__device__ __forceinline__ float atomicMin(float* address, float val) +{ + int* address_as_i = (int*) address; + int old = *address_as_i, assumed; + do { + assumed = old; + old = atomicCAS(address_as_i, assumed, + __float_as_int(fminf(val, __int_as_float(assumed)))); + } while (assumed != old); + return __int_as_float(old); +} +__device__ __forceinline__ double atomicMin(double* address, double val) +{ + unsigned long long int* address_as_i = (unsigned long long int*) address; + unsigned long long int old = *address_as_i, assumed; + do { + assumed = old; + old = atomicCAS(address_as_i, assumed, + __double_as_longlong(fminf(val, __longlong_as_double(assumed)))); + } while (assumed != old); + return __longlong_as_double(old); +} + +template +__device__ __forceinline__ bool check_face_frontside(const scalar_t *face) { + return (face[7] - face[1]) * (face[3] - face[0]) < (face[4] - face[1]) * (face[6] - face[0]); +} + + +template struct point +{ + public: + scalar_t x; + scalar_t y; + + __host__ __device__ scalar_t dot(point p) + { + return this->x * p.x + this->y * p.y; + }; + + __host__ __device__ point operator-(point& p) + { + point np; + np.x = this->x - p.x; + np.y = this->y - p.y; + return np; + }; + + __host__ __device__ point operator+(point& p) + { + point np; + np.x = this->x + p.x; + np.y = this->y + p.y; + return np; + }; + + __host__ __device__ point operator*(scalar_t s) + { + point np; + np.x = s * this->x; + np.y = s * this->y; + return np; + }; +}; + +template +__device__ __forceinline__ bool check_pixel_inside(const scalar_t *w) { + return w[0] <= 1 && w[0] >= 0 && w[1] <= 1 && w[1] >= 0 && w[2] <= 1 && w[2] >= 0; +} + +template +__device__ __forceinline__ void barycentric_weight(scalar_t *w, point p, point p0, point p1, point p2) { + + // vectors + point v0, v1, v2; + scalar_t s = p.dot(p); + v0 = p2 - p0; + v1 = p1 - p0; + v2 = p - p0; + + // dot products + scalar_t dot00 = v0.dot(v0); //v0.x * v0.x + v0.y * v0.y //np.dot(v0.T, v0) + scalar_t dot01 = v0.dot(v1); //v0.x * v1.x + v0.y * v1.y //np.dot(v0.T, v1) + scalar_t dot02 = v0.dot(v2); //v0.x * v2.x + v0.y * v2.y //np.dot(v0.T, v2) + scalar_t dot11 = v1.dot(v1); //v1.x * v1.x + v1.y * v1.y //np.dot(v1.T, v1) + scalar_t dot12 = v1.dot(v2); //v1.x * v2.x + v1.y * v2.y//np.dot(v1.T, v2) + + // barycentric coordinates + scalar_t inverDeno; + if(dot00*dot11 - dot01*dot01 == 0) + inverDeno = 0; + else + inverDeno = 1/(dot00*dot11 - dot01*dot01); + + scalar_t u = (dot11*dot02 - dot01*dot12)*inverDeno; + scalar_t v = (dot00*dot12 - dot01*dot02)*inverDeno; + + // weight + w[0] = 1 - u - v; + w[1] = v; + w[2] = u; +} + +// Ref: https://www.scratchapixel.com/lessons/3d-basic-rendering/rasterization-practical-implementation/overview-rasterization-algorithm +template +__global__ void forward_rasterize_cuda_kernel( + const scalar_t* __restrict__ face_vertices, //[bz, nf, 3, 3] + scalar_t* depth_buffer, + int* triangle_buffer, + scalar_t* baryw_buffer, + int batch_size, int h, int w, + int ntri) { + + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= batch_size * ntri) { + return; + } + int bn = i/ntri; + const scalar_t* face = &face_vertices[i * 9]; + scalar_t bw[3]; + point p0, p1, p2, p; + + p0.x = face[0]; p0.y=face[1]; + p1.x = face[3]; p1.y=face[4]; + p2.x = face[6]; p2.y=face[7]; + + int x_min = max((int)ceil(min(p0.x, min(p1.x, p2.x))), 0); + int x_max = min((int)floor(max(p0.x, max(p1.x, p2.x))), w - 1); + int y_min = max((int)ceil(min(p0.y, min(p1.y, p2.y))), 0); + int y_max = min((int)floor(max(p0.y, max(p1.y, p2.y))), h - 1); + + for(int y = y_min; y <= y_max; y++) //h + { + for(int x = x_min; x <= x_max; x++) //w + { + p.x = x; p.y = y; + barycentric_weight(bw, p, p0, p1, p2); + // if(((bw[2] >= 0) && (bw[1] >= 0) && (bw[0]>0)) && check_face_frontside(face)) + if((bw[2] >= 0) && (bw[1] >= 0) && (bw[0]>0)) + { + // perspective correct: https://www.scratchapixel.com/lessons/3d-basic-rendering/rasterization-practical-implementation/perspective-correct-interpolation-vertex-attributes + scalar_t zp = 1. / (bw[0] / face[2] + bw[1] / face[5] + bw[2] / face[8]); + // printf("%f %f %f \n", (float)zp, (float)face[2], (float)bw[2]); + atomicMin(&depth_buffer[bn*h*w + y*w + x], zp); + if(depth_buffer[bn*h*w + y*w + x] == zp) + { + triangle_buffer[bn*h*w + y*w + x] = (int)(i%ntri); + for(int k=0; k<3; k++){ + baryw_buffer[bn*h*w*3 + y*w*3 + x*3 + k] = bw[k]; + } + } + } + } + } + +} + +template +__global__ void forward_rasterize_colors_cuda_kernel( + const scalar_t* __restrict__ face_vertices, //[bz, nf, 3, 3] + const scalar_t* __restrict__ face_colors, //[bz, nf, 3, 3] + scalar_t* depth_buffer, + int* triangle_buffer, + scalar_t* images, + int batch_size, int h, int w, + int ntri) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= batch_size * ntri) { + return; + } + int bn = i/ntri; + const scalar_t* face = &face_vertices[i * 9]; + const scalar_t* color = &face_colors[i * 9]; + scalar_t bw[3]; + point p0, p1, p2, p; + + p0.x = face[0]; p0.y=face[1]; + p1.x = face[3]; p1.y=face[4]; + p2.x = face[6]; p2.y=face[7]; + scalar_t cl[3][3]; + for (int num = 0; num < 3; num++) { + for (int dim = 0; dim < 3; dim++) { + cl[num][dim] = color[3 * num + dim]; //[3p,3rgb] + } + } + int x_min = max((int)ceil(min(p0.x, min(p1.x, p2.x))), 0); + int x_max = min((int)floor(max(p0.x, max(p1.x, p2.x))), w - 1); + int y_min = max((int)ceil(min(p0.y, min(p1.y, p2.y))), 0); + int y_max = min((int)floor(max(p0.y, max(p1.y, p2.y))), h - 1); + + for(int y = y_min; y <= y_max; y++) //h + { + for(int x = x_min; x <= x_max; x++) //w + { + p.x = x; p.y = y; + barycentric_weight(bw, p, p0, p1, p2); + if(((bw[2] >= 0) && (bw[1] >= 0) && (bw[0]>0)) && check_face_frontside(face)) + // if((bw[2] >= 0) && (bw[1] >= 0) && (bw[0]>0)) + { + scalar_t zp = 1. / (bw[0] / face[2] + bw[1] / face[5] + bw[2] / face[8]); + + atomicMin(&depth_buffer[bn*h*w + y*w + x], zp); + if(depth_buffer[bn*h*w + y*w + x] == zp) + { + triangle_buffer[bn*h*w + y*w + x] = (int)(i%ntri); + for(int k=0; k<3; k++){ + // baryw_buffer[bn*h*w*3 + y*w*3 + x*3 + k] = bw[k]; + images[bn*h*w*3 + y*w*3 + x*3 + k] = bw[0]*cl[0][k] + bw[1]*cl[1][k] + bw[2]*cl[2][k]; + } + // buffers[bn*h*w*2 + y*w*2 + x*2 + 1] = p_depth; + } + } + } + } + +} + +} + +std::vector forward_rasterize_cuda( + at::Tensor face_vertices, + at::Tensor depth_buffer, + at::Tensor triangle_buffer, + at::Tensor baryw_buffer, + int h, + int w){ + + const auto batch_size = face_vertices.size(0); + const auto ntri = face_vertices.size(1); + + // print(channel_size) + const int threads = 512; + const dim3 blocks_1 ((batch_size * ntri - 1) / threads +1); + + AT_DISPATCH_FLOATING_TYPES(face_vertices.type(), "forward_rasterize_cuda1", ([&] { + forward_rasterize_cuda_kernel<<>>( + face_vertices.data(), + depth_buffer.data(), + triangle_buffer.data(), + baryw_buffer.data(), + batch_size, h, w, + ntri); + })); + + // better to do it twice (or there will be balck spots in the rendering) + AT_DISPATCH_FLOATING_TYPES(face_vertices.type(), "forward_rasterize_cuda2", ([&] { + forward_rasterize_cuda_kernel<<>>( + face_vertices.data(), + depth_buffer.data(), + triangle_buffer.data(), + baryw_buffer.data(), + batch_size, h, w, + ntri); + })); + cudaError_t err = cudaGetLastError(); + if (err != cudaSuccess) + printf("Error in forward_rasterize_cuda_kernel: %s\n", cudaGetErrorString(err)); + + return {depth_buffer, triangle_buffer, baryw_buffer}; +} + + +std::vector forward_rasterize_colors_cuda( + at::Tensor face_vertices, + at::Tensor face_colors, + at::Tensor depth_buffer, + at::Tensor triangle_buffer, + at::Tensor images, + int h, + int w){ + + const auto batch_size = face_vertices.size(0); + const auto ntri = face_vertices.size(1); + + // print(channel_size) + const int threads = 512; + const dim3 blocks_1 ((batch_size * ntri - 1) / threads +1); + //initial + + AT_DISPATCH_FLOATING_TYPES(face_vertices.type(), "forward_rasterize_colors_cuda", ([&] { + forward_rasterize_colors_cuda_kernel<<>>( + face_vertices.data(), + face_colors.data(), + depth_buffer.data(), + triangle_buffer.data(), + images.data(), + batch_size, h, w, + ntri); + })); + // better to do it twice + // AT_DISPATCH_FLOATING_TYPES(face_vertices.type(), "forward_rasterize_colors_cuda", ([&] { + // forward_rasterize_colors_cuda_kernel<<>>( + // face_vertices.data(), + // face_colors.data(), + // depth_buffer.data(), + // triangle_buffer.data(), + // images.data(), + // batch_size, h, w, + // ntri); + // })); + cudaError_t err = cudaGetLastError(); + if (err != cudaSuccess) + printf("Error in forward_rasterize_cuda_kernel: %s\n", cudaGetErrorString(err)); + + return {depth_buffer, triangle_buffer, images}; +} + + + + diff --git a/src/mesh/renderer.py b/src/mesh/renderer.py new file mode 100755 index 0000000..417b37b --- /dev/null +++ b/src/mesh/renderer.py @@ -0,0 +1,458 @@ +# -*- coding: utf-8 -*- +# +# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is +# holder of all proprietary rights on this computer program. +# Using this computer program means that you agree to the terms +# in the LICENSE file included with this software distribution. +# Any use not explicitly granted by the LICENSE is prohibited. +# +# Copyright©2019 Max-Planck-Gesellschaft zur Förderung +# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute +# for Intelligent Systems. All rights reserved. +# +# For comments or questions, please email us at deca@tue.mpg.de +# For commercial licensing contact, please contact ps-license@tuebingen.mpg.de + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from skimage.io import imread +import imageio + +from . import util + +def set_rasterizer(type = 'pytorch3d'): + if type == 'pytorch3d': + global Meshes, load_obj, rasterize_meshes + from pytorch3d.structures import Meshes + from pytorch3d.io import load_obj + from pytorch3d.renderer.mesh import rasterize_meshes + + elif type == 'standard': + global standard_rasterize, load_obj + import os + from .util import load_obj + # Use JIT Compiling Extensions + # ref: https://pytorch.org/tutorials/advanced/cpp_extension.html + from torch.utils.cpp_extension import load, CUDA_HOME + curr_dir = os.path.dirname(__file__) + standard_rasterize_cuda = \ + load(name='standard_rasterize_cuda', + sources=[f'{curr_dir}/rasterizer/standard_rasterize_cuda.cpp', f'{curr_dir}/rasterizer/standard_rasterize_cuda_kernel.cu'], + extra_cuda_cflags = ['-std=c++14', '-ccbin=$$(which gcc-7)']) # cuda10.2 is not compatible with gcc9. Specify gcc 7 + from standard_rasterize_cuda import standard_rasterize + # If JIT does not work, try manually installation first + # 1. see instruction here: pixielib/utils/rasterizer/INSTALL.md + # 2. add this: "from .rasterizer.standard_rasterize_cuda import standard_rasterize" here + +class StandardRasterizer(nn.Module): + """ Alg: https://www.scratchapixel.com/lessons/3d-basic-rendering/rasterization-practical-implementation + Notice: + x,y,z are in image space, normalized to [-1, 1] + can render non-squared image + not differentiable + """ + def __init__(self, height, width=None): + """ + use fixed raster_settings for rendering faces + """ + super().__init__() + if width is None: + width = height + self.h = h = height; self.w = w = width + + def forward(self, vertices, faces, attributes=None, h=None, w=None): + device = vertices.device + if h is None: + h = self.h + if w is None: + w = self.h; + bz = vertices.shape[0] + depth_buffer = torch.zeros([bz, h, w]).float().to(device) + 1e6 + triangle_buffer = torch.zeros([bz, h, w]).int().to(device) - 1 + baryw_buffer = torch.zeros([bz, h, w, 3]).float().to(device) + vert_vis = torch.zeros([bz, vertices.shape[1]]).float().to(device) + vertices = vertices.clone().float() + # compatibale with pytorch3d ndc, see https://github.com/facebookresearch/pytorch3d/blob/e42b0c4f704fa0f5e262f370dccac537b5edf2b1/pytorch3d/csrc/rasterize_meshes/rasterize_meshes.cu#L232 + vertices[...,:2] = -vertices[...,:2] + vertices[...,0] = vertices[..., 0]*w/2 + w/2 + vertices[...,1] = vertices[..., 1]*h/2 + h/2 + vertices[...,0] = w - 1 - vertices[..., 0] + vertices[...,1] = h - 1 - vertices[..., 1] + vertices[...,0] = -1 + (2*vertices[...,0] + 1)/w + vertices[...,1] = -1 + (2*vertices[...,1] + 1)/h + # + vertices = vertices.clone().float() + vertices[...,0] = vertices[..., 0]*w/2 + w/2 + vertices[...,1] = vertices[..., 1]*h/2 + h/2 + vertices[...,2] = vertices[..., 2]*w/2 + f_vs = util.face_vertices(vertices, faces) + + standard_rasterize(f_vs, depth_buffer, triangle_buffer, baryw_buffer, h, w) + pix_to_face = triangle_buffer[:,:,:,None].long() + bary_coords = baryw_buffer[:,:,:,None,:] + vismask = (pix_to_face > -1).float() + D = attributes.shape[-1] + attributes = attributes.clone(); attributes = attributes.view(attributes.shape[0]*attributes.shape[1], 3, attributes.shape[-1]) + N, H, W, K, _ = bary_coords.shape + mask = pix_to_face == -1 + pix_to_face = pix_to_face.clone() + pix_to_face[mask] = 0 + idx = pix_to_face.view(N * H * W * K, 1, 1).expand(N * H * W * K, 3, D) + pixel_face_vals = attributes.gather(0, idx).view(N, H, W, K, 3, D) + pixel_vals = (bary_coords[..., None] * pixel_face_vals).sum(dim=-2) + pixel_vals[mask] = 0 # Replace masked values in output. + pixel_vals = pixel_vals[:,:,:,0].permute(0,3,1,2) + pixel_vals = torch.cat([pixel_vals, vismask[:,:,:,0][:,None,:,:]], dim=1) + return pixel_vals + +class Pytorch3dRasterizer(nn.Module): + ## TODO: add support for rendering non-squared images, since pytorc3d supports this now + """ Borrowed from https://github.com/facebookresearch/pytorch3d + Notice: + x,y,z are in image space, normalized + can only render squared image now + """ + + def __init__(self, image_size=224): + """ + use fixed raster_settings for rendering faces + """ + super().__init__() + raster_settings = { + 'image_size': image_size, + 'blur_radius': 0.0, + 'faces_per_pixel': 1, + 'bin_size': None, + 'max_faces_per_bin': None, + 'perspective_correct': False, + } + raster_settings = util.dict2obj(raster_settings) + self.raster_settings = raster_settings + + def forward(self, vertices, faces, attributes=None, h=None, w=None): + fixed_vertices = vertices.clone() + fixed_vertices[...,:2] = -fixed_vertices[...,:2] + raster_settings = self.raster_settings + if h is None and w is None: + image_size = raster_settings.image_size + else: + image_size = [h, w] + if h>w: + fixed_vertices[..., 1] = fixed_vertices[..., 1]*h/w + else: + fixed_vertices[..., 0] = fixed_vertices[..., 0]*w/h + + meshes_screen = Meshes(verts=fixed_vertices.float(), faces=faces.long()) + pix_to_face, zbuf, bary_coords, dists = rasterize_meshes( + meshes_screen, + image_size=image_size, + blur_radius=raster_settings.blur_radius, + faces_per_pixel=raster_settings.faces_per_pixel, + bin_size=raster_settings.bin_size, + max_faces_per_bin=raster_settings.max_faces_per_bin, + perspective_correct=raster_settings.perspective_correct, + ) + vismask = (pix_to_face > -1).float() + D = attributes.shape[-1] + attributes = attributes.clone(); attributes = attributes.view(attributes.shape[0]*attributes.shape[1], 3, attributes.shape[-1]) + N, H, W, K, _ = bary_coords.shape + mask = pix_to_face == -1 + pix_to_face = pix_to_face.clone() + pix_to_face[mask] = 0 + idx = pix_to_face.view(N * H * W * K, 1, 1).expand(N * H * W * K, 3, D) + pixel_face_vals = attributes.gather(0, idx).view(N, H, W, K, 3, D) + pixel_vals = (bary_coords[..., None] * pixel_face_vals).sum(dim=-2) + pixel_vals[mask] = 0 # Replace masked values in output. + pixel_vals = pixel_vals[:,:,:,0].permute(0,3,1,2) + pixel_vals = torch.cat([pixel_vals, vismask[:,:,:,0][:,None,:,:]], dim=1) + # print(image_size) + # import ipdb; ipdb.set_trace() + return pixel_vals + +class SRenderY(nn.Module): + def __init__(self, image_size, obj_filename, uv_size=256, rasterizer_type='pytorch3d'): + super(SRenderY, self).__init__() + self.image_size = image_size + self.uv_size = uv_size + + if rasterizer_type == 'pytorch3d': + self.rasterizer = Pytorch3dRasterizer(image_size) + self.uv_rasterizer = Pytorch3dRasterizer(uv_size) + + verts, faces, aux = load_obj(obj_filename) + uvcoords = aux.verts_uvs[None, ...] # (N, V, 2) + uvfaces = faces.textures_idx[None, ...] # (N, F, 3) + faces = faces.verts_idx[None,...] + + elif rasterizer_type == 'standard': + self.rasterizer = StandardRasterizer(image_size) + self.uv_rasterizer = StandardRasterizer(uv_size) + verts, uvcoords, faces, uvfaces = load_obj(obj_filename) + verts = verts[None, ...] + uvcoords = uvcoords[None, ...] + faces = faces[None, ...] + uvfaces = uvfaces[None, ...] + + else: + NotImplementedError + + # faces + dense_triangles = util.generate_triangles(uv_size, uv_size) + self.register_buffer('dense_faces', torch.from_numpy(dense_triangles).long()[None,:,:]) + self.register_buffer('faces', faces) + self.register_buffer('raw_uvcoords', uvcoords) + + # uv coords + uvcoords = torch.cat([uvcoords, uvcoords[:,:,0:1]*0.+1.], -1) #[bz, ntv, 3] + uvcoords = uvcoords*2 - 1; uvcoords[...,1] = -uvcoords[...,1] + face_uvcoords = util.face_vertices(uvcoords, uvfaces) + self.register_buffer('uvcoords', uvcoords) + self.register_buffer('uvfaces', uvfaces) + self.register_buffer('face_uvcoords', face_uvcoords) + + # shape colors, for rendering shape overlay + colors = torch.tensor([180, 180, 180])[None, None, :].repeat(1, faces.max()+1, 1).float()/255. + face_colors = util.face_vertices(colors, faces) + self.register_buffer('face_colors', face_colors) + + ## SH factors for lighting + pi = np.pi + constant_factor = torch.tensor([1/np.sqrt(4*pi), ((2*pi)/3)*(np.sqrt(3/(4*pi))), ((2*pi)/3)*(np.sqrt(3/(4*pi))),\ + ((2*pi)/3)*(np.sqrt(3/(4*pi))), (pi/4)*(3)*(np.sqrt(5/(12*pi))), (pi/4)*(3)*(np.sqrt(5/(12*pi))),\ + (pi/4)*(3)*(np.sqrt(5/(12*pi))), (pi/4)*(3/2)*(np.sqrt(5/(12*pi))), (pi/4)*(1/2)*(np.sqrt(5/(4*pi)))]).float() + self.register_buffer('constant_factor', constant_factor) + + def forward(self, vertices, transformed_vertices, albedos, lights=None, light_type='point'): + ''' + -- Texture Rendering + vertices: [batch_size, V, 3], vertices in world space, for calculating normals, then shading + transformed_vertices: [batch_size, V, 3], range:normalized to [-1,1], projected vertices in image space (that is aligned to the iamge pixel), for rasterization + albedos: [batch_size, 3, h, w], uv map + lights: + spherical homarnic: [N, 9(shcoeff), 3(rgb)] + points/directional lighting: [N, n_lights, 6(xyzrgb)] + light_type: + point or directional + ''' + batch_size = vertices.shape[0] + ## rasterizer near 0 far 100. move mesh so minz larger than 0 + transformed_vertices[:,:,2] = transformed_vertices[:,:,2] + 10 + # attributes + face_vertices = util.face_vertices(vertices, 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)) + + attributes = torch.cat([self.face_uvcoords.expand(batch_size, -1, -1, -1), + transformed_face_normals.detach(), + face_vertices.detach(), + face_normals], + -1) + # rasterize + rendering = self.rasterizer(transformed_vertices, self.faces.expand(batch_size, -1, -1), attributes) + + #### + # vis mask + alpha_images = rendering[:, -1, :, :][:, None, :, :].detach() + + # albedo + uvcoords_images = rendering[:, :3, :, :]; grid = (uvcoords_images).permute(0, 2, 3, 1)[:, :, :, :2] + albedo_images = F.grid_sample(albedos, grid, align_corners=False) + + # visible mask for pixels with positive normal direction + transformed_normal_map = rendering[:, 3:6, :, :].detach() + pos_mask = (transformed_normal_map[:, 2:, :, :] < -0.05).float() + + # shading + normal_images = rendering[:, 9:12, :, :] + if lights is not None: + if lights.shape[1] == 9: + shading_images = self.add_SHlight(normal_images, lights) + else: + if light_type=='point': + vertice_images = rendering[:, 6:9, :, :].detach() + shading = self.add_pointlight(vertice_images.permute(0,2,3,1).reshape([batch_size, -1, 3]), normal_images.permute(0,2,3,1).reshape([batch_size, -1, 3]), lights) + shading_images = shading.reshape([batch_size, albedo_images.shape[2], albedo_images.shape[3], 3]).permute(0,3,1,2) + else: + shading = self.add_directionlight(normal_images.permute(0,2,3,1).reshape([batch_size, -1, 3]), lights) + shading_images = shading.reshape([batch_size, albedo_images.shape[2], albedo_images.shape[3], 3]).permute(0,3,1,2) + images = albedo_images*shading_images + else: + images = albedo_images + shading_images = images.detach()*0. + + outputs = { + 'images': images*alpha_images, + 'albedo_images': albedo_images*alpha_images, + 'alpha_images': alpha_images, + 'pos_mask': pos_mask, + 'shading_images': shading_images, + 'grid': grid, + 'normals': normals, + 'normal_images': normal_images*alpha_images, + 'transformed_normals': transformed_normals, + } + + return outputs + + def add_SHlight(self, normal_images, sh_coeff): + ''' + sh_coeff: [bz, 9, 3] + ''' + N = normal_images + sh = torch.stack([ + N[:,0]*0.+1., N[:,0], N[:,1], \ + N[:,2], N[:,0]*N[:,1], N[:,0]*N[:,2], + N[:,1]*N[:,2], N[:,0]**2 - N[:,1]**2, 3*(N[:,2]**2) - 1 + ], + 1) # [bz, 9, h, w] + sh = sh*self.constant_factor[None,:,None,None] + shading = torch.sum(sh_coeff[:,:,:,None,None]*sh[:,:,None,:,:], 1) # [bz, 9, 3, h, w] + return shading + + def add_pointlight(self, vertices, normals, lights): + ''' + vertices: [bz, nv, 3] + lights: [bz, nlight, 6] + returns: + shading: [bz, nv, 3] + ''' + light_positions = lights[:,:,:3]; light_intensities = lights[:,:,3:] + directions_to_lights = F.normalize(light_positions[:,:,None,:] - vertices[:,None,:,:], dim=3) + # normals_dot_lights = torch.clamp((normals[:,None,:,:]*directions_to_lights).sum(dim=3), 0., 1.) + normals_dot_lights = (normals[:,None,:,:]*directions_to_lights).sum(dim=3) + shading = normals_dot_lights[:,:,:,None]*light_intensities[:,:,None,:] + return shading.mean(1) + + def add_directionlight(self, normals, lights): + ''' + normals: [bz, nv, 3] + lights: [bz, nlight, 6] + returns: + shading: [bz, nv, 3] + ''' + light_direction = lights[:,:,:3]; light_intensities = lights[:,:,3:] + directions_to_lights = F.normalize(light_direction[:,:,None,:].expand(-1,-1,normals.shape[1],-1), dim=3) + # normals_dot_lights = torch.clamp((normals[:,None,:,:]*directions_to_lights).sum(dim=3), 0., 1.) + # normals_dot_lights = (normals[:,None,:,:]*directions_to_lights).sum(dim=3) + normals_dot_lights = torch.clamp((normals[:,None,:,:]*directions_to_lights).sum(dim=3), 0., 1.) + shading = normals_dot_lights[:,:,:,None]*light_intensities[:,:,None,:] + return shading.mean(1) + + def render_shape(self, vertices, transformed_vertices, colors = None, images=None, detail_normal_images=None, + lights=None, return_grid=False, uv_detail_normals=None, h=None, w=None): + ''' + -- rendering shape with detail normal map + ''' + batch_size = vertices.shape[0] + # set lighting + if lights is None: + light_positions = torch.tensor( + [ + [-1,1,1], + [1,1,1], + [-1,-1,1], + [1,-1,1], + [0,0,1] + ] + )[None,:,:].expand(batch_size, -1, -1).float() + light_intensities = torch.ones_like(light_positions).float()*1.7 + lights = torch.cat((light_positions, light_intensities), 2).to(vertices.device) + transformed_vertices[:,:,2] = transformed_vertices[:,:,2] + 10 + + # Attributes + face_vertices = util.face_vertices(vertices, 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)) + if colors is None: + colors = self.face_colors.expand(batch_size, -1, -1, -1) + attributes = torch.cat([colors, + transformed_face_normals.detach(), + face_vertices.detach(), + face_normals, + self.face_uvcoords.expand(batch_size, -1, -1, -1)], + -1) + + # rasterize + # import ipdb; ipdb.set_trace() + rendering = self.rasterizer(transformed_vertices, self.faces.expand(batch_size, -1, -1), attributes, h, w) + + #### + alpha_images = rendering[:, -1, :, :][:, None, :, :].detach() + + # albedo + albedo_images = rendering[:, :3, :, :] + # mask + transformed_normal_map = rendering[:, 3:6, :, :].detach() + pos_mask = (transformed_normal_map[:, 2:, :, :] < 0.15).float() + + # shading + normal_images = rendering[:, 9:12, :, :].detach() + vertice_images = rendering[:, 6:9, :, :].detach() + if detail_normal_images is not None: + normal_images = detail_normal_images + + shading = self.add_directionlight(normal_images.permute(0,2,3,1).reshape([batch_size, -1, 3]), lights) + shading_images = shading.reshape([batch_size, albedo_images.shape[2], albedo_images.shape[3], 3]).permute(0,3,1,2).contiguous() + shaded_images = albedo_images*shading_images + + alpha_images = alpha_images*pos_mask + if images is None: + shape_images = shaded_images*alpha_images + torch.zeros_like(shaded_images).to(vertices.device)*(1-alpha_images) + else: + shape_images = shaded_images*alpha_images + images*(1-alpha_images) + if return_grid: + uvcoords_images = rendering[:, 12:15, :, :]; + grid = (uvcoords_images).permute(0, 2, 3, 1)[:, :, :, :2] + return shape_images, normal_images, grid, alpha_images + else: + return shape_images + + def render_depth(self, transformed_vertices): + ''' + -- rendering depth + ''' + batch_size = transformed_vertices.shape[0] + + transformed_vertices[:,:,2] = transformed_vertices[:,:,2] - transformed_vertices[:,:,2].min() + z = -transformed_vertices[:,:,2:].repeat(1,1,3).clone() + z = z-z.min() + z = z/z.max() + # Attributes + attributes = util.face_vertices(z, self.faces.expand(batch_size, -1, -1)) + # rasterize + transformed_vertices[:,:,2] = transformed_vertices[:,:,2] + 10 + rendering = self.rasterizer(transformed_vertices, self.faces.expand(batch_size, -1, -1), attributes) + + #### + alpha_images = rendering[:, -1, :, :][:, None, :, :].detach() + depth_images = rendering[:, :1, :, :] + return depth_images + + def render_colors(self, transformed_vertices, colors): + ''' + -- rendering colors: could be rgb color/ normals, etc + colors: [bz, num of vertices, 3] + ''' + batch_size = colors.shape[0] + + # Attributes + attributes = util.face_vertices(colors, self.faces.expand(batch_size, -1, -1)) + # rasterize + rendering = self.rasterizer(transformed_vertices, self.faces.expand(batch_size, -1, -1), attributes) + #### + alpha_images = rendering[:, [-1], :, :].detach() + images = rendering[:, :3, :, :]* alpha_images + return images + + def world2uv(self, vertices): + ''' + warp vertices from world space to uv space + vertices: [bz, V, 3] + uv_vertices: [bz, 3, h, w] + ''' + batch_size = vertices.shape[0] + face_vertices = util.face_vertices(vertices, self.faces.expand(batch_size, -1, -1)) + uv_vertices = self.uv_rasterizer(self.uvcoords.expand(batch_size, -1, -1), self.uvfaces.expand(batch_size, -1, -1), face_vertices)[:, :3] + return uv_vertices \ No newline at end of file diff --git a/src/mesh/tensor_cropper.py b/src/mesh/tensor_cropper.py new file mode 100644 index 0000000..3100d6b --- /dev/null +++ b/src/mesh/tensor_cropper.py @@ -0,0 +1,136 @@ +''' +crop +for torch tensor +Given image, bbox(center, bboxsize) +return: cropped image, tform(used for transform the keypoint accordingly) +only support crop to squared images +''' +import torch +from kornia.geometry.transform.imgwarp import ( + warp_perspective, get_perspective_transform, warp_affine +) + +def points2bbox(points, points_scale=None): + if points_scale: + assert points_scale[0]==points_scale[1] + points = points.clone() + points[:,:,:2] = (points[:,:,:2]*0.5 + 0.5)*points_scale[0] + min_coords, _ = torch.min(points, dim=1) + xmin, ymin = min_coords[:, 0], min_coords[:, 1] + max_coords, _ = torch.max(points, dim=1) + xmax, ymax = max_coords[:, 0], max_coords[:, 1] + center = torch.stack([xmax + xmin, ymax + ymin], dim=-1) * 0.5 + + width = (xmax - xmin) + height = (ymax - ymin) + # Convert the bounding box to a square box + size = torch.max(width, height).unsqueeze(-1) + return center, size + +def augment_bbox(center, bbox_size, scale=[1.0, 1.0], trans_scale=0.): + batch_size = center.shape[0] + trans_scale = (torch.rand([batch_size, 2], device=center.device)*2. -1.) * trans_scale + center = center + trans_scale*bbox_size # 0.5 + scale = torch.rand([batch_size,1], device=center.device) * (scale[1] - scale[0]) + scale[0] + size = bbox_size*scale + return center, size + +def crop_tensor(image, center, bbox_size, crop_size, interpolation = 'bilinear', align_corners=False): + ''' for batch image + Args: + image (torch.Tensor): the reference tensor of shape BXHxWXC. + center: [bz, 2] + bboxsize: [bz, 1] + crop_size; + interpolation (str): Interpolation flag. Default: 'bilinear'. + align_corners (bool): mode for grid_generation. Default: False. See + https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details + Returns: + cropped_image + tform + ''' + dtype = image.dtype + device = image.device + batch_size = image.shape[0] + # points: top-left, top-right, bottom-right, bottom-left + src_pts = torch.zeros([4,2], dtype=dtype, device=device).unsqueeze(0).expand(batch_size, -1, -1).contiguous() + + src_pts[:, 0, :] = center - bbox_size*0.5 # / (self.crop_size - 1) + src_pts[:, 1, 0] = center[:, 0] + bbox_size[:, 0] * 0.5 + src_pts[:, 1, 1] = center[:, 1] - bbox_size[:, 0] * 0.5 + src_pts[:, 2, :] = center + bbox_size * 0.5 + src_pts[:, 3, 0] = center[:, 0] - bbox_size[:, 0] * 0.5 + src_pts[:, 3, 1] = center[:, 1] + bbox_size[:, 0] * 0.5 + + DST_PTS = torch.tensor([[ + [0, 0], + [crop_size - 1, 0], + [crop_size - 1, crop_size - 1], + [0, crop_size - 1], + ]], dtype=dtype, device=device).expand(batch_size, -1, -1) + # estimate transformation between points + dst_trans_src = get_perspective_transform(src_pts, DST_PTS) + # simulate broadcasting + # dst_trans_src = dst_trans_src.expand(batch_size, -1, -1) + + # warp images + cropped_image = warp_affine( + image, dst_trans_src[:, :2, :], (crop_size, crop_size), + flags=interpolation, align_corners=align_corners) + + tform = torch.transpose(dst_trans_src, 2, 1) + # tform = torch.inverse(dst_trans_src) + return cropped_image, tform + +class Cropper(object): + def __init__(self, crop_size, scale=[1,1], trans_scale = 0.): + self.crop_size = crop_size + self.scale = scale + self.trans_scale = trans_scale + + def crop(self, image, points, points_scale=None): + # points to bbox + center, bbox_size = points2bbox(points.clone(), points_scale) + # argument bbox. TODO: add rotation? + center, bbox_size = augment_bbox(center, bbox_size, scale=self.scale, trans_scale=self.trans_scale) + # crop + cropped_image, tform = crop_tensor(image, center, bbox_size, self.crop_size) + return cropped_image, tform + + def transform_points(self, points, tform, points_scale=None, normalize = True): + points_2d = points[:,:,:2] + + #'input points must use original range' + if points_scale: + assert points_scale[0]==points_scale[1] + points_2d = (points_2d*0.5 + 0.5)*points_scale[0] + + batch_size, n_points, _ = points.shape + trans_points_2d = torch.bmm( + torch.cat([points_2d, torch.ones([batch_size, n_points, 1], device=points.device, dtype=points.dtype)], dim=-1), + tform + ) + trans_points = torch.cat([trans_points_2d[:,:,:2], points[:,:,2:]], dim=-1) + if normalize: + trans_points[:,:,:2] = trans_points[:,:,:2]/self.crop_size*2 - 1 + return trans_points + +def transform_points(points, tform, points_scale=None, out_scale=None): + points_2d = points[:,:,:2] + + #'input points must use original range' + if points_scale: + assert points_scale[0]==points_scale[1] + points_2d = (points_2d*0.5 + 0.5)*points_scale[0] + # import ipdb; ipdb.set_trace() + + batch_size, n_points, _ = points.shape + trans_points_2d = torch.bmm( + torch.cat([points_2d, torch.ones([batch_size, n_points, 1], device=points.device, dtype=points.dtype)], dim=-1), + tform + ) + if out_scale: # h,w of output image size + trans_points_2d[:,:,0] = trans_points_2d[:,:,0]/out_scale[1]*2 - 1 + trans_points_2d[:,:,1] = trans_points_2d[:,:,1]/out_scale[0]*2 - 1 + trans_points = torch.cat([trans_points_2d[:,:,:2], points[:,:,2:]], dim=-1) + return trans_points \ No newline at end of file diff --git a/src/mesh/util.py b/src/mesh/util.py new file mode 100755 index 0000000..246997c --- /dev/null +++ b/src/mesh/util.py @@ -0,0 +1,719 @@ +# -*- coding: utf-8 -*- +# +# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is +# holder of all proprietary rights on this computer program. +# Using this computer program means that you agree to the terms +# in the LICENSE file included with this software distribution. +# Any use not explicitly granted by the LICENSE is prohibited. +# +# Copyright©2019 Max-Planck-Gesellschaft zur Förderung +# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute +# for Intelligent Systems. All rights reserved. +# +# For comments or questions, please email us at deca@tue.mpg.de +# For commercial licensing contact, please contact ps-license@tuebingen.mpg.de + +import numpy as np +import torch +import torch.nn.functional as F +import math +from collections import OrderedDict +import os +from scipy.ndimage import morphology +from skimage.io import imsave +import cv2 +import torchvision + +def upsample_mesh(vertices, normals, faces, displacement_map, texture_map, dense_template): + ''' Credit to Timo + upsampling coarse mesh (with displacment map) + vertices: vertices of coarse mesh, [nv, 3] + normals: vertex normals, [nv, 3] + faces: faces of coarse mesh, [nf, 3] + texture_map: texture map, [256, 256, 3] + displacement_map: displacment map, [256, 256] + dense_template: + Returns: + dense_vertices: upsampled vertices with details, [number of dense vertices, 3] + dense_colors: vertex color, [number of dense vertices, 3] + dense_faces: [number of dense faces, 3] + ''' + img_size = dense_template['img_size'] + dense_faces = dense_template['f'] + x_coords = dense_template['x_coords'] + y_coords = dense_template['y_coords'] + valid_pixel_ids = dense_template['valid_pixel_ids'] + valid_pixel_3d_faces = dense_template['valid_pixel_3d_faces'] + valid_pixel_b_coords = dense_template['valid_pixel_b_coords'] + + pixel_3d_points = vertices[valid_pixel_3d_faces[:, 0], :] * valid_pixel_b_coords[:, 0][:, np.newaxis] + \ + vertices[valid_pixel_3d_faces[:, 1], :] * valid_pixel_b_coords[:, 1][:, np.newaxis] + \ + vertices[valid_pixel_3d_faces[:, 2], :] * valid_pixel_b_coords[:, 2][:, np.newaxis] + vertex_normals = normals + pixel_3d_normals = vertex_normals[valid_pixel_3d_faces[:, 0], :] * valid_pixel_b_coords[:, 0][:, np.newaxis] + \ + vertex_normals[valid_pixel_3d_faces[:, 1], :] * valid_pixel_b_coords[:, 1][:, np.newaxis] + \ + vertex_normals[valid_pixel_3d_faces[:, 2], :] * valid_pixel_b_coords[:, 2][:, np.newaxis] + pixel_3d_normals = pixel_3d_normals / np.linalg.norm(pixel_3d_normals, axis=-1)[:, np.newaxis] + displacements = displacement_map[y_coords[valid_pixel_ids].astype(int), x_coords[valid_pixel_ids].astype(int)] + dense_colors = texture_map[y_coords[valid_pixel_ids].astype(int), x_coords[valid_pixel_ids].astype(int)] + offsets = np.einsum('i,ij->ij', displacements, pixel_3d_normals) + dense_vertices = pixel_3d_points + offsets + return dense_vertices, dense_colors, dense_faces + +# borrowed from https://github.com/YadiraF/PRNet/blob/master/utils/write.py +def write_obj(obj_name, + vertices, + faces, + colors=None, + texture=None, + uvcoords=None, + uvfaces=None, + inverse_face_order=False, + normal_map=None, + ): + ''' Save 3D face model with texture. + Ref: https://github.com/patrikhuber/eos/blob/bd00155ebae4b1a13b08bf5a991694d682abbada/include/eos/core/Mesh.hpp + Args: + obj_name: str + vertices: shape = (nver, 3) + colors: shape = (nver, 3) + faces: shape = (ntri, 3) + texture: shape = (uv_size, uv_size, 3) + uvcoords: shape = (nver, 2) max value<=1 + ''' + if os.path.splitext(obj_name)[-1] != 'obj': + obj_name = obj_name + '.obj' + mtl_name = obj_name.replace('.obj', '.mtl') + texture_name = obj_name.replace('.obj', '.png') + material_name = 'FaceTexture' + + faces = faces.copy() + # mesh lab start with 1, python/c++ start from 0 + faces += 1 + if inverse_face_order: + faces = faces[:, [2, 1, 0]] + if uvfaces is not None: + uvfaces = uvfaces[:, [2, 1, 0]] + + # write obj + with open(obj_name, 'w') as f: + # first line: write mtlib(material library) + # f.write('# %s\n' % os.path.basename(obj_name)) + # f.write('#\n') + # f.write('\n') + if texture is not None: + f.write('mtllib %s\n\n' % os.path.basename(mtl_name)) + + # write vertices + if colors is None: + for i in range(vertices.shape[0]): + f.write('v {} {} {}\n'.format(vertices[i, 0], vertices[i, 1], vertices[i, 2])) + else: + for i in range(vertices.shape[0]): + f.write('v {} {} {} {} {} {}\n'.format(vertices[i, 0], vertices[i, 1], vertices[i, 2], colors[i, 0], colors[i, 1], colors[i, 2])) + + # write uv coords + if texture is None: + for i in range(faces.shape[0]): + f.write('f {} {} {}\n'.format(faces[i, 2], faces[i, 1], faces[i, 0])) + else: + for i in range(uvcoords.shape[0]): + f.write('vt {} {}\n'.format(uvcoords[i,0], uvcoords[i,1])) + f.write('usemtl %s\n' % material_name) + # write f: ver ind/ uv ind + uvfaces = uvfaces + 1 + for i in range(faces.shape[0]): + f.write('f {}/{} {}/{} {}/{}\n'.format( + # faces[i, 2], uvfaces[i, 2], + # faces[i, 1], uvfaces[i, 1], + # faces[i, 0], uvfaces[i, 0] + faces[i, 0], uvfaces[i, 0], + faces[i, 1], uvfaces[i, 1], + faces[i, 2], uvfaces[i, 2] + ) + ) + # write mtl + with open(mtl_name, 'w') as f: + f.write('newmtl %s\n' % material_name) + s = 'map_Kd {}\n'.format(os.path.basename(texture_name)) # map to image + f.write(s) + + if normal_map is not None: + name, _ = os.path.splitext(obj_name) + normal_name = f'{name}_normals.png' + f.write(f'disp {normal_name}') + # out_normal_map = normal_map / (np.linalg.norm( + # normal_map, axis=-1, keepdims=True) + 1e-9) + # out_normal_map = (out_normal_map + 1) * 0.5 + + cv2.imwrite( + normal_name, + # (out_normal_map * 255).astype(np.uint8)[:, :, ::-1] + normal_map + ) + cv2.imwrite(texture_name, texture) + + +## load obj, similar to load_obj from pytorch3d +def load_obj(obj_filename): + """ Ref: https://github.com/facebookresearch/pytorch3d/blob/25c065e9dafa90163e7cec873dbb324a637c68b7/pytorch3d/io/obj_io.py + Load a mesh from a file-like object. + """ + with open(obj_filename, 'r') as f: + lines = [line.strip() for line in f] + + verts, uvcoords = [], [] + faces, uv_faces = [], [] + # startswith expects each line to be a string. If the file is read in as + # bytes then first decode to strings. + if lines and isinstance(lines[0], bytes): + lines = [el.decode("utf-8") for el in lines] + + for line in lines: + tokens = line.strip().split() + if line.startswith("v "): # Line is a vertex. + vert = [float(x) for x in tokens[1:4]] + if len(vert) != 3: + msg = "Vertex %s does not have 3 values. Line: %s" + raise ValueError(msg % (str(vert), str(line))) + verts.append(vert) + elif line.startswith("vt "): # Line is a texture. + tx = [float(x) for x in tokens[1:3]] + if len(tx) != 2: + raise ValueError( + "Texture %s does not have 2 values. Line: %s" % (str(tx), str(line)) + ) + uvcoords.append(tx) + elif line.startswith("f "): # Line is a face. + # Update face properties info. + face = tokens[1:] + face_list = [f.split("/") for f in face] + for vert_props in face_list: + # Vertex index. + faces.append(int(vert_props[0])) + if len(vert_props) > 1: + if vert_props[1] != "": + # Texture index is present e.g. f 4/1/1. + uv_faces.append(int(vert_props[1])) + + verts = torch.tensor(verts, dtype=torch.float32) + uvcoords = torch.tensor(uvcoords, dtype=torch.float32) + faces = torch.tensor(faces, dtype=torch.long); faces = faces.reshape(-1, 3) - 1 + uv_faces = torch.tensor(uv_faces, dtype=torch.long); uv_faces = uv_faces.reshape(-1, 3) - 1 + return ( + verts, + uvcoords, + faces, + uv_faces + ) + +# ---------------------------- process/generate vertices, normals, faces +def generate_triangles(h, w, margin_x=2, margin_y=5, mask = None): + # quad layout: + # 0 1 ... w-1 + # w w+1 + #. + # w*h + triangles = [] + for x in range(margin_x, w-1-margin_x): + for y in range(margin_y, h-1-margin_y): + triangle0 = [y*w + x, y*w + x + 1, (y+1)*w + x] + triangle1 = [y*w + x + 1, (y+1)*w + x + 1, (y+1)*w + x] + triangles.append(triangle0) + triangles.append(triangle1) + triangles = np.array(triangles) + triangles = triangles[:,[0,2,1]] + return triangles + +# borrowed from https://github.com/daniilidis-group/neural_renderer/blob/master/neural_renderer/vertices_to_faces.py +def face_vertices(vertices, faces): + """ + :param vertices: [batch size, number of vertices, 3] + :param faces: [batch size, number of faces, 3] + :return: [batch size, number of faces, 3, 3] + """ + assert (vertices.ndimension() == 3) + assert (faces.ndimension() == 3) + assert (vertices.shape[0] == faces.shape[0]) + assert (vertices.shape[2] == 3) + assert (faces.shape[2] == 3) + + bs, nv = vertices.shape[:2] + bs, nf = faces.shape[:2] + device = vertices.device + faces = faces + (torch.arange(bs, dtype=torch.int32).to(device) * nv)[:, None, None] + vertices = vertices.reshape((bs * nv, 3)) + # pytorch only supports long and byte tensors for indexing + return vertices[faces.long()] + +def vertex_normals(vertices, faces): + """ + :param vertices: [batch size, number of vertices, 3] + :param faces: [batch size, number of faces, 3] + :return: [batch size, number of vertices, 3] + """ + assert (vertices.ndimension() == 3) + assert (faces.ndimension() == 3) + assert (vertices.shape[0] == faces.shape[0]) + assert (vertices.shape[2] == 3) + assert (faces.shape[2] == 3) + bs, nv = vertices.shape[:2] + bs, nf = faces.shape[:2] + device = vertices.device + normals = torch.zeros(bs * nv, 3).to(device) + + faces = faces + (torch.arange(bs, dtype=torch.int32).to(device) * nv)[:, None, None] # expanded faces + vertices_faces = vertices.reshape((bs * nv, 3))[faces.long()] + + faces = faces.reshape(-1, 3) + vertices_faces = vertices_faces.reshape(-1, 3, 3) + + normals.index_add_(0, faces[:, 1].long(), + torch.cross(vertices_faces[:, 2] - vertices_faces[:, 1], vertices_faces[:, 0] - vertices_faces[:, 1])) + normals.index_add_(0, faces[:, 2].long(), + torch.cross(vertices_faces[:, 0] - vertices_faces[:, 2], vertices_faces[:, 1] - vertices_faces[:, 2])) + normals.index_add_(0, faces[:, 0].long(), + torch.cross(vertices_faces[:, 1] - vertices_faces[:, 0], vertices_faces[:, 2] - vertices_faces[:, 0])) + + normals = F.normalize(normals, eps=1e-6, dim=1) + normals = normals.reshape((bs, nv, 3)) + # pytorch only supports long and byte tensors for indexing + return normals + +def batch_orth_proj(X, camera): + ''' orthgraphic projection + X: 3d vertices, [bz, n_point, 3] + camera: scale and translation, [bz, 3], [scale, tx, ty] + ''' + camera = camera.clone().view(-1, 1, 3) + X_trans = X[:, :, :2] + camera[:, :, 1:] + X_trans = torch.cat([X_trans, X[:,:,2:]], 2) + shape = X_trans.shape + Xn = (camera[:, :, 0:1] * X_trans) + return Xn + +# -------------------------------------- image processing +# borrowed from: https://torchgeometry.readthedocs.io/en/latest/_modules/kornia/filters +def gaussian(window_size, sigma): + def gauss_fcn(x): + return -(x - window_size // 2)**2 / float(2 * sigma**2) + gauss = torch.stack( + [torch.exp(torch.tensor(gauss_fcn(x))) for x in range(window_size)]) + return gauss / gauss.sum() + +def get_gaussian_kernel(kernel_size: int, sigma: float): + r"""Function that returns Gaussian filter coefficients. + + Args: + kernel_size (int): filter size. It should be odd and positive. + sigma (float): gaussian standard deviation. + + Returns: + Tensor: 1D tensor with gaussian filter coefficients. + + Shape: + - Output: :math:`(\text{kernel_size})` + + Examples:: + + >>> kornia.image.get_gaussian_kernel(3, 2.5) + tensor([0.3243, 0.3513, 0.3243]) + + >>> kornia.image.get_gaussian_kernel(5, 1.5) + tensor([0.1201, 0.2339, 0.2921, 0.2339, 0.1201]) + """ + if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or \ + kernel_size <= 0: + raise TypeError("kernel_size must be an odd positive integer. " + "Got {}".format(kernel_size)) + window_1d = gaussian(kernel_size, sigma) + return window_1d + +def get_gaussian_kernel2d(kernel_size, sigma): + r"""Function that returns Gaussian filter matrix coefficients. + + Args: + kernel_size (Tuple[int, int]): filter sizes in the x and y direction. + Sizes should be odd and positive. + sigma (Tuple[int, int]): gaussian standard deviation in the x and y + direction. + + Returns: + Tensor: 2D tensor with gaussian filter matrix coefficients. + + Shape: + - Output: :math:`(\text{kernel_size}_x, \text{kernel_size}_y)` + + Examples:: + + >>> kornia.image.get_gaussian_kernel2d((3, 3), (1.5, 1.5)) + tensor([[0.0947, 0.1183, 0.0947], + [0.1183, 0.1478, 0.1183], + [0.0947, 0.1183, 0.0947]]) + + >>> kornia.image.get_gaussian_kernel2d((3, 5), (1.5, 1.5)) + tensor([[0.0370, 0.0720, 0.0899, 0.0720, 0.0370], + [0.0462, 0.0899, 0.1123, 0.0899, 0.0462], + [0.0370, 0.0720, 0.0899, 0.0720, 0.0370]]) + """ + if not isinstance(kernel_size, tuple) or len(kernel_size) != 2: + raise TypeError("kernel_size must be a tuple of length two. Got {}" + .format(kernel_size)) + if not isinstance(sigma, tuple) or len(sigma) != 2: + raise TypeError("sigma must be a tuple of length two. Got {}" + .format(sigma)) + ksize_x, ksize_y = kernel_size + sigma_x, sigma_y = sigma + kernel_x = get_gaussian_kernel(ksize_x, sigma_x) + kernel_y = get_gaussian_kernel(ksize_y, sigma_y) + kernel_2d = torch.matmul( + kernel_x.unsqueeze(-1), kernel_y.unsqueeze(-1).t()) + return kernel_2d + +def gaussian_blur(x, kernel_size=(3,3), sigma=(0.8,0.8)): + b, c, h, w = x.shape + kernel = get_gaussian_kernel2d(kernel_size, sigma).to(x.device).to(x.dtype) + kernel = kernel.repeat(c, 1, 1, 1) + padding = [(k - 1) // 2 for k in kernel_size] + return F.conv2d(x, kernel, padding=padding, stride=1, groups=c) + +def _compute_binary_kernel(window_size): + r"""Creates a binary kernel to extract the patches. If the window size + is HxW will create a (H*W)xHxW kernel. + """ + window_range = window_size[0] * window_size[1] + kernel: torch.Tensor = torch.zeros(window_range, window_range) + for i in range(window_range): + kernel[i, i] += 1.0 + return kernel.view(window_range, 1, window_size[0], window_size[1]) + +def median_blur(x, kernel_size=(3,3)): + b, c, h, w = x.shape + kernel = _compute_binary_kernel(kernel_size).to(x.device).to(x.dtype) + kernel = kernel.repeat(c, 1, 1, 1) + padding = [(k - 1) // 2 for k in kernel_size] + features = F.conv2d(x, kernel, padding=padding, stride=1, groups=c) + features = features.view(b,c,-1,h,w) + median = torch.median(features, dim=2)[0] + return median + +def get_laplacian_kernel2d(kernel_size: int): + r"""Function that returns Gaussian filter matrix coefficients. + + Args: + kernel_size (int): filter size should be odd. + + Returns: + Tensor: 2D tensor with laplacian filter matrix coefficients. + + Shape: + - Output: :math:`(\text{kernel_size}_x, \text{kernel_size}_y)` + + Examples:: + + >>> kornia.image.get_laplacian_kernel2d(3) + tensor([[ 1., 1., 1.], + [ 1., -8., 1.], + [ 1., 1., 1.]]) + + >>> kornia.image.get_laplacian_kernel2d(5) + tensor([[ 1., 1., 1., 1., 1.], + [ 1., 1., 1., 1., 1.], + [ 1., 1., -24., 1., 1.], + [ 1., 1., 1., 1., 1.], + [ 1., 1., 1., 1., 1.]]) + + """ + if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or \ + kernel_size <= 0: + raise TypeError("ksize must be an odd positive integer. Got {}" + .format(kernel_size)) + + kernel = torch.ones((kernel_size, kernel_size)) + mid = kernel_size // 2 + kernel[mid, mid] = 1 - kernel_size ** 2 + kernel_2d: torch.Tensor = kernel + return kernel_2d + +def laplacian(x): + # https://torchgeometry.readthedocs.io/en/latest/_modules/kornia/filters/laplacian.html + b, c, h, w = x.shape + kernel_size = 3 + kernel = get_laplacian_kernel2d(kernel_size).to(x.device).to(x.dtype) + kernel = kernel.repeat(c, 1, 1, 1) + padding = (kernel_size - 1) // 2 + return F.conv2d(x, kernel, padding=padding, stride=1, groups=c) + +def angle2matrix(angles): + ''' get rotation matrix from three rotation angles(degree). right-handed. + Args: + angles: [batch_size, 3] tensor containing X, Y, and Z angles. + x: pitch. positive for looking down. + y: yaw. positive for looking left. + z: roll. positive for tilting head right. + Returns: + R: [batch_size, 3, 3]. rotation matrices. + ''' + angles = angles*(np.pi)/180. + s = torch.sin(angles) + c = torch.cos(angles) + + cx, cy, cz = (c[:, 0], c[:, 1], c[:, 2]) + sx, sy, sz = (s[:, 0], s[:, 1], s[:, 2]) + + zeros = torch.zeros_like(s[:, 0]).to(angles.device) + ones = torch.ones_like(s[:, 0]).to(angles.device) + + # Rz.dot(Ry.dot(Rx)) + R_flattened = torch.stack( + [ + cz * cy, cz * sy * sx - sz * cx, cz * sy * cx + sz * sx, + sz * cy, sz * sy * sx + cz * cx, sz * sy * cx - cz * sx, + -sy, cy * sx, cy * cx, + ], + dim=0) #[batch_size, 9] + R = torch.reshape(R_flattened, (-1, 3, 3)) #[batch_size, 3, 3] + return R + +def binary_erosion(tensor, kernel_size=5): + # tensor: [bz, 1, h, w]. + device = tensor.device + mask = tensor.cpu().numpy() + structure=np.ones((kernel_size,kernel_size)) + new_mask = mask.copy() + for i in range(mask.shape[0]): + new_mask[i,0] = morphology.binary_erosion(mask[i,0], structure) + return torch.from_numpy(new_mask.astype(np.float32)).to(device) + +def flip_image(src_image, kps): + ''' + purpose: + flip a image given by src_image and the 2d keypoints + flip_mode: + 0: horizontal flip + >0: vertical flip + <0: horizontal & vertical flip + ''' + h, w = src_image.shape[0], src_image.shape[1] + src_image = cv2.flip(src_image, 1) + if kps is not None: + kps[:, 0] = w - 1 - kps[:, 0] + kp_map = [5, 4, 3, 2, 1, 0, 11, 10, 9, 8, 7, 6, 12, 13] + kps[:, :] = kps[kp_map] + + return src_image, kps + +# -------------------------------------- io +def copy_state_dict(cur_state_dict, pre_state_dict, prefix='', load_name=None): + def _get_params(key): + key = prefix + key + if key in pre_state_dict: + return pre_state_dict[key] + return None + for k in cur_state_dict.keys(): + if load_name is not None: + if load_name not in k: + continue + v = _get_params(k) + try: + if v is None: + # print('parameter {} not found'.format(k)) + continue + cur_state_dict[k].copy_(v) + except: + # print('copy param {} failed'.format(k)) + continue + +def check_mkdir(path): + if not os.path.exists(path): + print('creating %s' % path) + os.makedirs(path) + +def check_mkdirlist(pathlist): + for path in pathlist: + if not os.path.exists(path): + print('creating %s' % path) + os.makedirs(path) + +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 dict2obj(d): + # if isinstance(d, list): + # d = [dict2obj(x) for x in d] + if not isinstance(d, dict): + return d + class C(object): + pass + o = C() + for k in d: + o.__dict__[k] = dict2obj(d[k]) + return o + +class Struct(object): + def __init__(self, **kwargs): + for key, val in kwargs.items(): + setattr(self, key, val) + +# original saved file with DataParallel +def remove_module(state_dict): +# create new OrderedDict that does not contain `module.` + new_state_dict = OrderedDict() + for k, v in state_dict.items(): + name = k[7:] # remove `module.` + new_state_dict[name] = v + return new_state_dict + +def dict_tensor2npy(tensor_dict): + npy_dict = {} + for key in tensor_dict: + npy_dict[key] = tensor_dict[key][0].cpu().numpy() + return npy_dict + +# ---------------------------------- visualization +# end_list = np.array([17, 22, 27, 42, 48, 31, 36, 68], dtype = np.int32) - 1 +end_list = np.array([17, 22, 27, 31, 36], dtype = np.int32) - 1 + +def plot_kpts(image, kpts, color = 'r'): + ''' Draw 68 key points + Args: + image: the input image + kpt: (68, 3). + ''' + if color == 'r': + c = (255, 0, 0) + elif color == 'g': + c = (0, 255, 0) + elif color == 'b': + c = (255, 0, 0) + image = image.copy() + kpts = kpts.copy() + + # radius = max(int(min(image.shape[0], image.shape[1])/200), 1) + radius = 1 + + for i in range(kpts.shape[0]): + st = kpts[i, :2] + if kpts.shape[1]==4: + if kpts[i, 3] > 0.5: + c = (0, 255, 0) + else: + c = (0, 0, 255) + + # draw cicle + image = cv2.circle(image,(int(st[0]), int(st[1])), radius, c, -1) + + # draw line + if i not in end_list: + ed = kpts[i + 1, :2] if i != 67 else kpts[60, :2] + ed = kpts[36, :2] if i == 41 else ed + ed = kpts[42, :2] if i == 47 else ed + image = cv2.line(image, (int(st[0]), int(st[1])), (int(ed[0]), int(ed[1])), (255, 255, 255), radius) + + return image + +def plot_verts(image, kpts, color = 'r'): + ''' Draw 68 key points + Args: + image: the input image + kpt: (68, 3). + ''' + c = (0, 0, 0) + c = (255, 0, 0) if color == 'r' else c + c = (0, 255, 0) if color == 'g' else c + c = (0, 0, 255) if color == 'b' else c + c = (0, 255, 255) if color == 'y' else c + + image = image.copy() + + for i in range(kpts.shape[0]): + st = kpts[i, :2] + image = cv2.circle(image,(int(st[0]), int(st[1])), 1, c, -1) + + return image + +def tensor_vis_landmarks(images, landmarks, gt_landmarks=None, color = 'g', isScale=True, gt_color = 'r'): + # visualize landmarks + vis_landmarks = [] + images = images.cpu().numpy() + predicted_landmarks = landmarks.detach().cpu().numpy() + + if gt_landmarks is not None: + gt_landmarks_np = gt_landmarks.detach().cpu().numpy() + + for i in range(images.shape[0]): + image = images[i] + image = image.transpose(1,2,0)[:,:,[2,1,0]].copy(); image = (image*255) + + # if landmarks is scale + if isScale: + predicted_landmark = predicted_landmarks[i] + predicted_landmark[...,0] = predicted_landmark[...,0]*image.shape[1]/2 + image.shape[1]/2 + predicted_landmark[...,1] = predicted_landmark[...,1]*image.shape[0]/2 + image.shape[0]/2 + else: + predicted_landmark = predicted_landmarks[i] + + # + if predicted_landmark.shape[0] == 68: + image_landmarks = plot_kpts(image, predicted_landmark, color) + if gt_landmarks is not None: + image_landmarks = plot_verts(image_landmarks, gt_landmarks_np[i]*image.shape[0]/2 + image.shape[0]/2, gt_color) + else: + image_landmarks = plot_verts(image, predicted_landmark, color) + if gt_landmarks is not None: + image_landmarks = plot_verts(image_landmarks, gt_landmarks_np[i]*image.shape[0]/2 + image.shape[0]/2, gt_color) + + vis_landmarks.append(image_landmarks) + + vis_landmarks = np.stack(vis_landmarks) + vis_landmarks = torch.from_numpy(vis_landmarks[:,:,:,[2,1,0]].transpose(0,3,1,2))/255.#, dtype=torch.float32) + return vis_landmarks + + +############### for training +def load_local_mask(image_size=256, mode='bbx'): + if mode == 'bbx': + # UV space face attributes bbx in size 2048 (l r t b) + # face = np.array([512, 1536, 512, 1536]) # + face = np.array([400, 1648, 400, 1648]) + # if image_size == 512: + # face = np.array([400, 400+512*2, 400, 400+512*2]) + # face = np.array([512, 512+512*2, 512, 512+512*2]) + + forehead = np.array([550, 1498, 430, 700+50]) + eye_nose = np.array([490, 1558, 700, 1050+50]) + mouth = np.array([574, 1474, 1050, 1550]) + ratio = image_size / 2048. + face = (face * ratio).astype(np.int) + forehead = (forehead * ratio).astype(np.int) + eye_nose = (eye_nose * ratio).astype(np.int) + mouth = (mouth * ratio).astype(np.int) + regional_mask = np.array([face, forehead, eye_nose, mouth]) + + return regional_mask + +def visualize_grid(visdict, savepath=None, size=224, dim=1, return_gird=True): + ''' + image range should be [0,1] + dim: 2 for horizontal. 1 for vertical + ''' + assert dim == 1 or dim==2 + grids = {} + for key in visdict: + _,_,h,w = visdict[key].shape + if dim == 2: + new_h = size; new_w = int(w*size/h) + elif dim == 1: + new_h = int(h*size/w); new_w = size + grids[key] = torchvision.utils.make_grid(F.interpolate(visdict[key], [new_h, new_w]).detach().cpu()) + grid = torch.cat(list(grids.values()), dim) + grid_image = (grid.numpy().transpose(1,2,0).copy()*255)[:,:,[2,1,0]] + grid_image = np.minimum(np.maximum(grid_image, 0), 255).astype(np.uint8) + if savepath: + cv2.imwrite(savepath, grid_image) + if return_gird: + return grid_image \ No newline at end of file diff --git a/src/models/__init__.py b/src/models/__init__.py index e69de29..d92e6bc 100644 --- a/src/models/__init__.py +++ b/src/models/__init__.py @@ -0,0 +1,60 @@ +import torch +import torch.nn as nn +import logging + +def init_weights(net, init_type='normal', init_gain=0.02): + """Initialize network weights. + + Parameters: + net (network) -- network to be initialized + init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal + init_gain (float) -- scaling factor for normal, xavier and orthogonal. + + We use 'normal' in the original pix2pix and CycleGAN paper. But xavier and kaiming might + work better for some applications. Feel free to try yourself. + """ + def init_func(m): # define the initialization function + classname = m.__class__.__name__ + #print(classname, hasattr(m, 'weight'),) + if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1): + if init_type == 'normal': + nn.init.normal_(m.weight.data, 0.0, init_gain) + elif init_type == 'xavier': + nn.init.xavier_normal_(m.weight.data, gain=init_gain) + elif init_type == 'kaiming': + nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in') + elif init_type == 'orthogonal': + nn.init.orthogonal_(m.weight.data, gain=init_gain) + else: + raise NotImplementedError('initialization method [%s] is not implemented' % init_type) + + if hasattr(m, 'bias') and m.bias is not None: + nn.init.constant_(m.bias.data, 0.0) + + elif classname.find('BatchNorm2d') != -1: # BatchNorm Layer's weight is not a matrix; only normal distribution applies. + nn.init.normal_(m.weight.data, 1.0, init_gain) + nn.init.constant_(m.bias.data, 0.0) + + logging.info('initialize network with %s' % init_type) + net.apply(init_func) # apply the initialization function + + +# def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]): +# """Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights +# Parameters: +# net (network) -- the network to be initialized +# init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal +# gain (float) -- scaling factor for normal, xavier and orthogonal. +# gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2 + +# Return an initialized network. +# """ + +# if len(gpu_ids) > 0: +# assert(torch.cuda.is_available()) +# net.to(f"cuda:{gpu_ids[0]}") +# net = torch.nn.DataParallel(net, gpu_ids) # multi-GPUs + +# init_weights(net, init_type, init_gain=init_gain) + +# return net \ No newline at end of file diff --git a/src/models/callbacks/__init__.py b/src/models/callbacks/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/models/callbacks/audio2mesh_callback.py b/src/models/callbacks/audio2mesh_callback.py new file mode 100644 index 0000000..99bf9a6 --- /dev/null +++ b/src/models/callbacks/audio2mesh_callback.py @@ -0,0 +1,162 @@ +import numpy as np +from pathlib2 import Path + +import torch +from pytorch_lightning.callbacks import Callback +from src.utils.animation import save_animation_with_gt2, save_images_with_audio + +class Audio2MeshCallback(Callback): + + def __init__( + self, + path_data_raw: str = "/data/LuoXData/processing", + fps: float = 50.0, + ): + super.__init__() + + self.device = "cuda:9" + self.fps = fps + self.path_data_raw = path_data_raw + self.netR = self.define_netR(device=self.device) + + def define_netR(self, device): + # import + import sys + 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) + + return netR + + + def on_train_start(self, trainer, pl_module): + print("on_train_start") + + + def on_test_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): + print("on_test_batch_end") + + # output first video + if batch_idx ==0 and dataloader_idx == 0: + print(f"contains nbatch={len(outputs)} in test_step output") + batch_pdt = outputs[0]["batch_pdt"] # B x nsteps x num_vertices x 3 + batch_tgt = outputs[0]["batch_tgt"] # B x nsteps x num_vertices x 3 + batch_info = outputs[0]["batch_info"] + print(f"testing pt shape = {batch_pdt.shape}, gt shape = {batch_tgt.shape}") + + # save video + path_save = Path(trainer.log_dir).joinpath("test_save") + path_save.mkdir(parents=True, exist_ok=True) + + self.save_reconstruct_with_gt(batch_pdt, batch_tgt, batch_info, + path_save=path_save, + suffix=f'sampled_{trainer.current_epoch:05d}_{batch_idx:03d}') + + + def tensor2image(self, 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 save_reconstruct(self, batch_pdt, path_audio, batch_info, path_save, num_video_save=3, suffix=""): + # batch_pdt, [B x N x 5023 x 3] + + B, N, *_ = batch_pdt.shape + batchsize_render = 10 + + # for each batch + for i in range(min(num_video_save, B)): + igeo_pt = batch_pdt[i, ...] + ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4") + + v_render_pt = [] + for k in range(0, N, batchsize_render): + # split + kgeo_pt = igeo_pt[k:k+batchsize_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.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) + # print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}") + + # append each frame + for m in range(nbatch_real): + v_render_pt.append(self.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, ipath_save) + + + def save_reconstruct_with_gt(self, batch_pdt, batch_tgt, batch_info, path_save, num_video_save=3, suffix=""): + # batch_pdt, [B x N x 5023 x 3] + # batch_tgt, [B x N x 5023 x 3] + B, N, *_ = batch_pdt.shape + batchsize_render = 10 + + # for each batch + for i in range(min(num_video_save, B)): + igeo_pt = batch_pdt[i, ...] # [N x 5023 x 3] + igeo_gt = batch_tgt[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, batchsize_render): + + # split + kgeo_pt = igeo_pt[k:k+batchsize_render, ...] # [nbatch_real x 5023 x 3] + kgeo_gt = igeo_gt[k:k+batchsize_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.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) + render_gt = self.netR.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512) + # print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}") + + # 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, ...])) + + + # get audio + jvid = batch_info["vid"][i] + jnframe = batch_info["nframe"][i].numpy() + jstart_frame = batch_info["interv"][0][i].numpy() + + + jpath_audio = f"{self.path_data_raw}/{jvid}/audio/audio_trim.wav" + jstart_time = (jstart_frame + 7) / self.fps # xxx.yyy min + jend_time = (jstart_frame + 7 + self.nseq) / self.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, ipath_save, fps=self.fps,\ + path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time) + diff --git a/src/models/components/__init__.py b/src/models/components/__init__.py index e69de29..5634429 100644 --- a/src/models/components/__init__.py +++ b/src/models/components/__init__.py @@ -0,0 +1,62 @@ + +flame_mouth_idx = [ + 1576, 1577, 1578, 1579, 1580, 1581, 1582, 1583, 1584, 1585, + 1586, 1587, 1590, 1596, 1597, 1598, 1599, 1601, 1603, 1657, + 1658, 1662, 1663, 1667, 1668, 1669, 1670, 1671, 1672, 1673, + 1674, 1686, 1687, 1688, 1689, 1690, 1691, 1693, 1694, 1695, + 1696, 1697, 1698, 1699, 1700, 1701, 1702, 1703, 1704, 1705, + 1706, 1707, 1708, 1709, 1710, 1711, 1712, 1713, 1714, 1715, + 1716, 1717, 1718, 1719, 1720, 1721, 1722, 1723, 1724, 1725, + 1728, 1729, 1730, 1731, 1732, 1733, 1734, 1735, 1736, 1737, + 1738, 1740, 1741, 1743, 1748, 1749, 1750, 1751, 1758, 1763, + 1766, 1767, 1768, 1769, 1770, 1771, 1773, 1774, 1775, 1776, + 1777, 1778, 1781, 1782, 1787, 1788, 1789, 1791, 1792, 1793, + 1794, 1795, 1796, 1797, 1798, 1799, 1800, 1801, 1802, 1803, + 1804, 1805, 1826, 1827, 1836, 1848, 1849, 1850, 1863, 1864, + 1865, 1866, 2712, 2713, 2714, 2715, 2716, 2717, 2718, 2719, + 2720, 2721, 2722, 2723, 2726, 2727, 2729, 2732, 2733, 2734, + 2735, 2737, 2738, 2739, 2774, 2775, 2780, 2784, 2786, 2787, + 2788, 2789, 2790, 2791, 2803, 2804, 2805, 2806, 2807, 2808, + 2810, 2811, 2812, 2813, 2814, 2815, 2816, 2817, 2818, 2819, + 2820, 2821, 2822, 2823, 2824, 2825, 2826, 2827, 2828, 2829, + 2830, 2831, 2832, 2833, 2834, 2835, 2836, 2837, 2838, 2839, + 2840, 2841, 2842, 2843, 2844, 2845, 2846, 2847, 2848, 2849, + 2850, 2851, 2852, 2853, 2855, 2858, 2863, 2864, 2865, 2866, + 2869, 2871, 2873, 2874, 2875, 2876, 2877, 2878, 2879, 2880, + 2881, 2882, 2883, 2884, 2885, 2887, 2888, 2889, 2890, 2891, + 2892, 2894, 2895, 2896, 2897, 2898, 2899, 2900, 2901, 2902, + 2903, 2904, 2905, 2906, 2907, 2908, 2928, 2929, 2934, 2937, + 2938, 2939, 2946, 2947, 2948, 2949, 3174, 3429, 3430, 3431, + 3432, 3433, 3434, 3489, 3490, 3491, 3492, 3493, 3499, 3502, + 3503, 3504, 3506, 3507, 3509, 3511, 3513, 3515, 3531, 3537, + 3538, 3541, 3543, 3546, 3659, 3660, 3662, 3663, 3664, 3761, + 3762, 3769, 3771, 3772, 3790, 3791, 3792, 3793, 3794, 3795, + 3796, 3797, 3798, 3799, 3800, 3801, 3802, 3803, 3804, 3805, + 3806, 3914, 3915, 3916, 3917, 3918, 3919, 3920, 3921, 3922, + 3923, 3924, 3925, 3926, 3927, 3928 + ] + + +idx_upper_mouth_68ldmk = [ + 49, 50, 51, 52, 53, + 61, 62, 63, +] + + +idx_lower_mouth_68ldmk = [ + 59, 58, 57, 56, 55, + 67, 66, 65, +] + + +idx_left_mouth_68ldmk = [ + 48, + 49, 60, 59, + 50, 61, 67, 58 +] + +idx_right_mouth_68ldmk = [ + 54, + 53, 64, 55, + 52, 63, 65, 56 +] diff --git a/src/models/components/audio2mesh.py b/src/models/components/audio2mesh.py new file mode 100644 index 0000000..0dcac61 --- /dev/null +++ b/src/models/components/audio2mesh.py @@ -0,0 +1,90 @@ +import torch +import torch.nn as nn +from src.utils.debug import debug + + +class Audio2Mesh(nn.Module): + + def __init__( + self, + num_vertices: int = 5023, # opt.MODEL.num_vertices + nc_condit: int = 1024, # opt.MODEL.dim_speech + + ): + super(Audio2Mesh, self).__init__() + + self.num_vertices = num_vertices + self.nc_condit = nc_condit # 1024 + self.nc_motion = 3 * self.num_vertices # 3 * 5023 + + # encoder + self.encoder = nn.Sequential( # (nbatch, nchannel=1024, H=16, W=1) + nn.BatchNorm2d(self.nc_condit), + + # block 1 + nn.Conv2d(self.nc_condit, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1 + nn.LeakyReLU(0.02, True), + nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1 + nn.LeakyReLU(0.02, True), + + nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1 + nn.LeakyReLU(0.02, True), + nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1 + nn.LeakyReLU(0.02, True), + + + nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1 + nn.LeakyReLU(0.02, True), + nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1 + nn.LeakyReLU(0.02, True), + + + nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1 + nn.LeakyReLU(0.02, True), + nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1 + nn.LeakyReLU(0.02, True), + + nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1 + nn.LeakyReLU(0.02, True), + + nn.Flatten(), # 64, + + nn.Linear(in_features=128, out_features=2048), + # nn.Dropout(0.3), # 128, + nn.Tanh(), + + nn.Linear(in_features=2048, out_features=50) # 50, + ) + + # output FLAME mesh + self.decoder_mesh = nn.Linear(in_features=50, out_features=self.nc_motion) + + + def forward(self, x): + """ forward function + Args: + x: torch.Tensor, [nbatch x seqlen x nwind x dim_condit] + return: + pred: torch.Tensor, [nbatch x seqlen x nc_motion] + """ + (nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, 29) + debug(f"[forward] input x shape = {x.shape}", verbose=False) + + # preprocessing data + x = x.reshape(nbatch * nseqlen, 1, nwind, nfeat) # (B * nseq, 1, 16, 29) + x = torch.transpose(x, 1, 3) # (B * nseq, 29, 16, 1) + debug(f"[forward] transpose x shape = {x.shape}", verbose=False) + + feat = self.encoder(x) # (B * nseq, 50) + debug(f"[forward] encoder shape = {feat.shape}", verbose=False) + + # predict FLAME mesh + pred_vert = self.decoder_mesh(feat) # (B * nseq, dim_mesh) + debug(f"[forward] decoder mesh shape = {pred_vert.shape}", verbose=False) + + pred_vert = pred_vert.reshape(nbatch, nseqlen, self.num_vertices, 3) # (B, nseq, num_vertices, 3) + debug(f"[forward] reshape shape = {pred_vert.shape}", verbose=False) + + return pred_vert + + diff --git a/src/models/components/simple_dense_net.py b/src/models/components/simple_dense_net.py index c6544cd..b55e516 100644 --- a/src/models/components/simple_dense_net.py +++ b/src/models/components/simple_dense_net.py @@ -1,6 +1,5 @@ from torch import nn - class SimpleDenseNet(nn.Module): def __init__( self, diff --git a/src/models/mesh/FLAME.py b/src/models/mesh/FLAME.py new file mode 100644 index 0000000..e898904 --- /dev/null +++ b/src/models/mesh/FLAME.py @@ -0,0 +1,320 @@ +# -*- coding: utf-8 -*- +# +# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is +# holder of all proprietary rights on this computer program. +# Using this computer program means that you agree to the terms +# in the LICENSE file included with this software distribution. +# Any use not explicitly granted by the LICENSE is prohibited. +# +# Copyright©2019 Max-Planck-Gesellschaft zur Förderung +# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute +# for Intelligent Systems. All rights reserved. +# +# For comments or questions, please email us at deca@tue.mpg.de +# For commercial licensing contact, please contact ps-license@tuebingen.mpg.de +import torch +import torch.nn as nn +import numpy as np +import pickle +import torch.nn.functional as F +import pprint + +from .lbs import lbs, batch_rodrigues, vertices2landmarks, rot_mat_to_euler + +def to_tensor(array, dtype=torch.float32): + if 'torch.tensor' not in str(type(array)): + return torch.tensor(array, dtype=dtype) +def to_np(array, dtype=np.float32): + if 'scipy.sparse' in str(type(array)): + array = array.todense() + return np.array(array, dtype=dtype) + +class Struct(object): + def __init__(self, **kwargs): + for key, val in kwargs.items(): + setattr(self, key, val) + +class FLAME(nn.Module): + """ + borrowed from https://github.com/soubhiksanyal/FLAME_PyTorch/blob/master/FLAME.py + Given flame parameters this class generates a differentiable FLAME function + which outputs the a mesh and 2D/3D facial landmarks + """ + def __init__(self, config): + super(FLAME, self).__init__() + + # print("creating the FLAME Decoder") + with open(config.flame_model_path, 'rb') as f: + ss = pickle.load(f, encoding='latin1') + flame_model = Struct(**ss) + + self.dtype = torch.float32 + self.register_buffer('faces_tensor', to_tensor(to_np(flame_model.f, dtype=np.int64), dtype=torch.long)) # (9976 x 3) + # print(f"[init FLAME] faces_tensor shape = {self.faces_tensor.shape}") + + # The vertices of the template model + self.register_buffer('v_template', to_tensor(to_np(flame_model.v_template), dtype=self.dtype)) # (5023 x 3) + # print(f"[init FLAME] v_template shape = {self.v_template.shape}") + + # The shape components and expression + shapedirs = to_tensor(to_np(flame_model.shapedirs), dtype=self.dtype) # (5023, 3, 400) + # print(f"[init FLAME] shapedirs shape = {shapedirs.shape}") + + shapedirs = torch.cat([shapedirs[:, :, :config.n_shape], # (5023, 3, 100) + shapedirs[:, :, 300:300+config.n_exp]], 2) # (5023, 3, 50) + self.register_buffer('shapedirs', shapedirs) # (5023, 3, 150) + # print(f"[init FLAME] shapedirs shape (after trim)= {self.shapedirs.shape}") + + # The pose components + num_pose_basis = flame_model.posedirs.shape[-1] + posedirs = np.reshape(flame_model.posedirs, [-1, num_pose_basis]).T # (36, 15069) + self.register_buffer('posedirs', to_tensor(to_np(posedirs), dtype=self.dtype)) + # print(f"[init FLAME] posedirs shape = {self.posedirs.shape}") + + # Joint regressor + self.register_buffer('J_regressor', to_tensor(to_np(flame_model.J_regressor), dtype=self.dtype)) + + # parents + parents = to_tensor(to_np(flame_model.kintree_table[0])).long(); parents[0] = -1 + self.register_buffer('parents', parents) + + # lbs weigth + self.register_buffer('lbs_weights', to_tensor(to_np(flame_model.weights), dtype=self.dtype)) + + # Fixing Eyeball and neck rotation + default_eyball_pose = torch.zeros([1, 6], dtype=self.dtype, requires_grad=False) + self.register_parameter('eye_pose', nn.Parameter(default_eyball_pose, requires_grad=False)) + + default_neck_pose = torch.zeros([1, 3], dtype=self.dtype, requires_grad=False) + self.register_parameter('neck_pose', nn.Parameter(default_neck_pose, requires_grad=False)) + + # Static and Dynamic Landmark embeddings for FLAME + lmk_embeddings = np.load(config.flame_lmk_embedding_path, allow_pickle=True, encoding='latin1') + lmk_embeddings = lmk_embeddings[()] + self.register_buffer('lmk_faces_idx', torch.from_numpy(lmk_embeddings['static_lmk_faces_idx']).long()) + self.register_buffer('lmk_bary_coords', torch.from_numpy(lmk_embeddings['static_lmk_bary_coords']).to(self.dtype)) + self.register_buffer('dynamic_lmk_faces_idx', lmk_embeddings['dynamic_lmk_faces_idx'].long()) + self.register_buffer('dynamic_lmk_bary_coords', lmk_embeddings['dynamic_lmk_bary_coords'].to(self.dtype)) + self.register_buffer('full_lmk_faces_idx', torch.from_numpy(lmk_embeddings['full_lmk_faces_idx']).long()) + self.register_buffer('full_lmk_bary_coords', torch.from_numpy(lmk_embeddings['full_lmk_bary_coords']).to(self.dtype)) + + neck_kin_chain = []; NECK_IDX=1 + curr_idx = torch.tensor(NECK_IDX, dtype=torch.long) + while curr_idx != -1: + neck_kin_chain.append(curr_idx) + curr_idx = self.parents[curr_idx] + self.register_buffer('neck_kin_chain', torch.stack(neck_kin_chain)) + + def _find_dynamic_lmk_idx_and_bcoords(self, pose, dynamic_lmk_faces_idx, + dynamic_lmk_b_coords, + neck_kin_chain, dtype=torch.float32): + """ + Selects the face contour depending on the reletive position of the head + Input: + vertices: N X num_of_vertices X 3 + pose: N X full pose + dynamic_lmk_faces_idx: The list of contour face indexes + dynamic_lmk_b_coords: The list of contour barycentric weights + neck_kin_chain: The tree to consider for the relative rotation + dtype: Data type + return: + The contour face indexes and the corresponding barycentric weights + """ + + batch_size = pose.shape[0] + + aa_pose = torch.index_select(pose.view(batch_size, -1, 3), 1, neck_kin_chain) + + rot_mats = batch_rodrigues(aa_pose.view(-1, 3), dtype=dtype)\ + .view(batch_size, -1, 3, 3) + + rel_rot_mat = torch.eye(3, device=pose.device, dtype=dtype)\ + .unsqueeze_(dim=0).expand(batch_size, -1, -1) + + for idx in range(len(neck_kin_chain)): + rel_rot_mat = torch.bmm(rot_mats[:, idx], rel_rot_mat) + + y_rot_angle = torch.round(torch.clamp(rot_mat_to_euler(rel_rot_mat) * 180.0 / np.pi, max=39)).to(dtype=torch.long) + + neg_mask = y_rot_angle.lt(0).to(dtype=torch.long) + mask = y_rot_angle.lt(-39).to(dtype=torch.long) + neg_vals = mask * 78 + (1 - mask) * (39 - y_rot_angle) + y_rot_angle = (neg_mask * neg_vals + (1 - neg_mask) * y_rot_angle) + + dyn_lmk_faces_idx = torch.index_select(dynamic_lmk_faces_idx, 0, y_rot_angle) + dyn_lmk_b_coords = torch.index_select(dynamic_lmk_b_coords, 0, y_rot_angle) + return dyn_lmk_faces_idx, dyn_lmk_b_coords + + def _vertices2landmarks(self, vertices, faces, lmk_faces_idx, lmk_bary_coords): + """ + Calculates landmarks by barycentric interpolation + Input: + vertices: torch.tensor NxVx3, dtype = torch.float32 + The tensor of input vertices + faces: torch.tensor (N*F)x3, dtype = torch.long + The faces of the mesh + lmk_faces_idx: torch.tensor N X L, dtype = torch.long + The tensor with the indices of the faces used to calculate the + landmarks. + lmk_bary_coords: torch.tensor N X L X 3, dtype = torch.float32 + The tensor of barycentric coordinates that are used to interpolate + the landmarks + + Returns: + landmarks: torch.tensor NxLx3, dtype = torch.float32 + The coordinates of the landmarks for each mesh in the batch + """ + # Extract the indices of the vertices for each face + # NxLx3 + batch_size, num_verts = vertices.shape[:2] + lmk_faces = torch.index_select(faces, 0, lmk_faces_idx.view(-1))\ + .view(1, -1, 3).view(batch_size, lmk_faces_idx.shape[1], -1) + + lmk_faces += torch.arange(batch_size, dtype=torch.long)\ + .view(-1, 1, 1).to(device=vertices.device) * num_verts + + lmk_vertices = vertices.view(-1, 3)[lmk_faces] + landmarks = torch.einsum('blfi,blf->bli', [lmk_vertices, lmk_bary_coords]) + + return landmarks + + + def seletec_2d68(self, vertices, pose): + """ need pose parameters + """ + + batch_size = vertices.shape[0] + + lmk_faces_idx = self.lmk_faces_idx.unsqueeze(dim=0).expand(batch_size, -1) + lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).expand(batch_size, -1, -1) + + dyn_lmk_faces_idx, dyn_lmk_bary_coords = self._find_dynamic_lmk_idx_and_bcoords( + pose, self.dynamic_lmk_faces_idx, + self.dynamic_lmk_bary_coords, + self.neck_kin_chain, dtype=self.dtype) + lmk_faces_idx = torch.cat([dyn_lmk_faces_idx, lmk_faces_idx], 1) + lmk_bary_coords = torch.cat([dyn_lmk_bary_coords, lmk_bary_coords], 1) + + landmarks2d = vertices2landmarks(vertices, self.faces_tensor, + lmk_faces_idx, + lmk_bary_coords) + + return landmarks2d + + + def seletec_3d68(self, vertices): + landmarks3d = vertices2landmarks(vertices, self.faces_tensor, + self.full_lmk_faces_idx.repeat(vertices.shape[0], 1), + self.full_lmk_bary_coords.repeat(vertices.shape[0], 1, 1)) + return landmarks3d + + + def forward(self, shape_params=None, expression_params=None, pose_params=None, eye_pose_params=None, template_vertices=None): + """ + Input: + shape_params: N X number of shape parameters + expression_params: N X number of expression parameters + pose_params: N X number of pose parameters (6) + return:d + vertices: N X V X 3 + landmarks: N X number of landmarks X 3 + """ + + + batch_size = shape_params.shape[0] + + if pose_params is None: + pose_params = self.eye_pose.expand(batch_size, -1) # (B x 6) + if eye_pose_params is None: + eye_pose_params = self.eye_pose.expand(batch_size, -1) # (B x 6) + + # print(f"shape_params = {shape_params.shape}, expression_params={expression_params.shape}, pose_params={pose_params.shape}") + # print(f"batch_size = {batch_size}, self.neck_pose={self.neck_pose.shape}") + + betas = torch.cat([ # (B x 150) + shape_params, # (B x 100), shape + expression_params # (B x 50), expression + ], dim=1) + + pose = torch.cat([ # (B x 18) + pose_params[:, :3], # (B x 3), head pose + self.neck_pose.expand(batch_size, -1), # (B x 6), neck pose + pose_params[:, 3:], # (B x 3), mouth pose + eye_pose_params # (B x 6), eye pose + ], dim=1) + + if template_vertices is None: + template_vertices = self.v_template.unsqueeze(0).expand(batch_size, -1, -1) # (B x 5023 x 3) + + vertices, _ = lbs(betas, pose, template_vertices, + self.shapedirs, self.posedirs, + self.J_regressor, self.parents, + self.lbs_weights, dtype=self.dtype) + + lmk_faces_idx = self.lmk_faces_idx.unsqueeze(dim=0).expand(batch_size, -1) + lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).expand(batch_size, -1, -1) + + dyn_lmk_faces_idx, dyn_lmk_bary_coords = self._find_dynamic_lmk_idx_and_bcoords( + pose, self.dynamic_lmk_faces_idx, + self.dynamic_lmk_bary_coords, + self.neck_kin_chain, dtype=self.dtype) + lmk_faces_idx = torch.cat([dyn_lmk_faces_idx, lmk_faces_idx], 1) + lmk_bary_coords = torch.cat([dyn_lmk_bary_coords, lmk_bary_coords], 1) + + landmarks2d = vertices2landmarks(vertices, self.faces_tensor, + lmk_faces_idx, + lmk_bary_coords) + bz = vertices.shape[0] + landmarks3d = vertices2landmarks(vertices, self.faces_tensor, + self.full_lmk_faces_idx.repeat(bz, 1), + self.full_lmk_bary_coords.repeat(bz, 1, 1)) + + return vertices, landmarks2d, landmarks3d + +class FLAMETex(nn.Module): + """ + FLAME texture: + https://github.com/TimoBolkart/TF_FLAME/blob/ade0ab152300ec5f0e8555d6765411555c5ed43d/sample_texture.py#L64 + FLAME texture converted from BFM: + https://github.com/TimoBolkart/BFM_to_FLAME + """ + def __init__(self, config): + super(FLAMETex, self).__init__() + if config.tex_type == 'BFM': + mu_key = 'MU' + pc_key = 'PC' + n_pc = 199 + tex_path = config.tex_path + tex_space = np.load(tex_path) + texture_mean = tex_space[mu_key].reshape(1, -1) + texture_basis = tex_space[pc_key].reshape(-1, n_pc) + + elif config.tex_type == 'FLAME': + mu_key = 'mean' + pc_key = 'tex_dir' + n_pc = 200 + tex_path = config.flame_tex_path + tex_space = np.load(tex_path) + texture_mean = tex_space[mu_key].reshape(1, -1)/255. + texture_basis = tex_space[pc_key].reshape(-1, n_pc)/255. + else: + print('texture type ', config.tex_type, 'not exist!') + raise NotImplementedError + + n_tex = config.n_tex + num_components = texture_basis.shape[1] + texture_mean = torch.from_numpy(texture_mean).float()[None,...] + texture_basis = torch.from_numpy(texture_basis[:,:n_tex]).float()[None,...] + self.register_buffer('texture_mean', texture_mean) + self.register_buffer('texture_basis', texture_basis) + + def forward(self, texcode): + ''' + texcode: [batchsize, n_tex] + texture: [bz, 3, 256, 256], range: 0-1 + ''' + texture = self.texture_mean + (self.texture_basis*texcode[:,None,:]).sum(-1) + texture = texture.reshape(texcode.shape[0], 512, 512, 3).permute(0,3,1,2) + texture = F.interpolate(texture, [256, 256]) + texture = texture[:,[2,1,0], :,:] + return texture \ No newline at end of file diff --git a/src/models/mesh/__init__.py b/src/models/mesh/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/models/mesh/lbs.py b/src/models/mesh/lbs.py new file mode 100644 index 0000000..b9c8748 --- /dev/null +++ b/src/models/mesh/lbs.py @@ -0,0 +1,377 @@ +# -*- coding: utf-8 -*- + +# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is +# holder of all proprietary rights on this computer program. +# You can only use this computer program if you have closed +# a license agreement with MPG or you get the right to use the computer +# program from someone who is authorized to grant you that right. +# Any use of the computer program without a valid license is prohibited and +# liable to prosecution. +# +# Copyright©2019 Max-Planck-Gesellschaft zur Förderung +# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute +# for Intelligent Systems. All rights reserved. +# +# Contact: ps-license@tuebingen.mpg.de + +from __future__ import absolute_import +from __future__ import print_function +from __future__ import division + +import numpy as np + +import torch +import torch.nn.functional as F + +def rot_mat_to_euler(rot_mats): + # Calculates rotation matrix to euler angles + # Careful for extreme cases of eular angles like [0.0, pi, 0.0] + + sy = torch.sqrt(rot_mats[:, 0, 0] * rot_mats[:, 0, 0] + + rot_mats[:, 1, 0] * rot_mats[:, 1, 0]) + return torch.atan2(-rot_mats[:, 2, 0], sy) + +def find_dynamic_lmk_idx_and_bcoords(vertices, pose, dynamic_lmk_faces_idx, + dynamic_lmk_b_coords, + neck_kin_chain, dtype=torch.float32): + ''' Compute the faces, barycentric coordinates for the dynamic landmarks + + + To do so, we first compute the rotation of the neck around the y-axis + and then use a pre-computed look-up table to find the faces and the + barycentric coordinates that will be used. + + Special thanks to Soubhik Sanyal (soubhik.sanyal@tuebingen.mpg.de) + for providing the original TensorFlow implementation and for the LUT. + + Parameters + ---------- + vertices: torch.tensor BxVx3, dtype = torch.float32 + The tensor of input vertices + pose: torch.tensor Bx(Jx3), dtype = torch.float32 + The current pose of the body model + dynamic_lmk_faces_idx: torch.tensor L, dtype = torch.long + The look-up table from neck rotation to faces + dynamic_lmk_b_coords: torch.tensor Lx3, dtype = torch.float32 + The look-up table from neck rotation to barycentric coordinates + neck_kin_chain: list + A python list that contains the indices of the joints that form the + kinematic chain of the neck. + dtype: torch.dtype, optional + + Returns + ------- + dyn_lmk_faces_idx: torch.tensor, dtype = torch.long + A tensor of size BxL that contains the indices of the faces that + will be used to compute the current dynamic landmarks. + dyn_lmk_b_coords: torch.tensor, dtype = torch.float32 + A tensor of size BxL that contains the indices of the faces that + will be used to compute the current dynamic landmarks. + ''' + + batch_size = vertices.shape[0] + + aa_pose = torch.index_select(pose.view(batch_size, -1, 3), 1, + neck_kin_chain) + rot_mats = batch_rodrigues( + aa_pose.view(-1, 3), dtype=dtype).view(batch_size, -1, 3, 3) + + rel_rot_mat = torch.eye(3, device=vertices.device, + dtype=dtype).unsqueeze_(dim=0) + for idx in range(len(neck_kin_chain)): + rel_rot_mat = torch.bmm(rot_mats[:, idx], rel_rot_mat) + + y_rot_angle = torch.round( + torch.clamp(-rot_mat_to_euler(rel_rot_mat) * 180.0 / np.pi, + max=39)).to(dtype=torch.long) + neg_mask = y_rot_angle.lt(0).to(dtype=torch.long) + mask = y_rot_angle.lt(-39).to(dtype=torch.long) + neg_vals = mask * 78 + (1 - mask) * (39 - y_rot_angle) + y_rot_angle = (neg_mask * neg_vals + + (1 - neg_mask) * y_rot_angle) + + dyn_lmk_faces_idx = torch.index_select(dynamic_lmk_faces_idx, + 0, y_rot_angle) + dyn_lmk_b_coords = torch.index_select(dynamic_lmk_b_coords, + 0, y_rot_angle) + + return dyn_lmk_faces_idx, dyn_lmk_b_coords + + +def vertices2landmarks(vertices, faces, lmk_faces_idx, lmk_bary_coords): + ''' Calculates landmarks by barycentric interpolation + + Parameters + ---------- + vertices: torch.tensor BxVx3, dtype = torch.float32 + The tensor of input vertices + faces: torch.tensor Fx3, dtype = torch.long + The faces of the mesh + lmk_faces_idx: torch.tensor L, dtype = torch.long + The tensor with the indices of the faces used to calculate the + landmarks. + lmk_bary_coords: torch.tensor Lx3, dtype = torch.float32 + The tensor of barycentric coordinates that are used to interpolate + the landmarks + + Returns + ------- + landmarks: torch.tensor BxLx3, dtype = torch.float32 + The coordinates of the landmarks for each mesh in the batch + ''' + # Extract the indices of the vertices for each face + # BxLx3 + batch_size, num_verts = vertices.shape[:2] + device = vertices.device + + lmk_faces = torch.index_select(faces, 0, lmk_faces_idx.view(-1)).view( + batch_size, -1, 3) + + lmk_faces += torch.arange( + batch_size, dtype=torch.long, device=device).view(-1, 1, 1) * num_verts + + lmk_vertices = vertices.view(-1, 3)[lmk_faces].view( + batch_size, -1, 3, 3) + + landmarks = torch.einsum('blfi,blf->bli', [lmk_vertices, lmk_bary_coords]) + return landmarks + + +def lbs(betas, pose, v_template, shapedirs, posedirs, J_regressor, parents, + lbs_weights, pose2rot=True, dtype=torch.float32): + ''' Performs Linear Blend Skinning with the given shape and pose parameters + + Parameters + ---------- + betas : torch.tensor BxNB + The tensor of shape parameters + pose : torch.tensor Bx(J + 1) * 3 + The pose parameters in axis-angle format + v_template torch.tensor BxVx3 + The template mesh that will be deformed + shapedirs : torch.tensor 1xNB + The tensor of PCA shape displacements + posedirs : torch.tensor Px(V * 3) + The pose PCA coefficients + J_regressor : torch.tensor JxV + The regressor array that is used to calculate the joints from + the position of the vertices + parents: torch.tensor J + The array that describes the kinematic tree for the model + lbs_weights: torch.tensor N x V x (J + 1) + The linear blend skinning weights that represent how much the + rotation matrix of each part affects each vertex + pose2rot: bool, optional + Flag on whether to convert the input pose tensor to rotation + matrices. The default value is True. If False, then the pose tensor + should already contain rotation matrices and have a size of + Bx(J + 1)x9 + dtype: torch.dtype, optional + + Returns + ------- + verts: torch.tensor BxVx3 + The vertices of the mesh after applying the shape and pose + displacements. + joints: torch.tensor BxJx3 + The joints of the model + ''' + + batch_size = max(betas.shape[0], pose.shape[0]) + device = betas.device + + # Add shape contribution + v_shaped = v_template + blend_shapes(betas, shapedirs) + + # Get the joints + # NxJx3 array + J = vertices2joints(J_regressor, v_shaped) + + # 3. Add pose blend shapes + # N x J x 3 x 3 + ident = torch.eye(3, dtype=dtype, device=device) + if pose2rot: + rot_mats = batch_rodrigues( + pose.view(-1, 3), dtype=dtype).view([batch_size, -1, 3, 3]) + + pose_feature = (rot_mats[:, 1:, :, :] - ident).view([batch_size, -1]) + # (N x P) x (P, V * 3) -> N x V x 3 + pose_offsets = torch.matmul(pose_feature, posedirs).view(batch_size, -1, 3) + else: + pose_feature = pose[:, 1:].view(batch_size, -1, 3, 3) - ident + rot_mats = pose.view(batch_size, -1, 3, 3) + + pose_offsets = torch.matmul(pose_feature.view(batch_size, -1), + posedirs).view(batch_size, -1, 3) + + v_posed = pose_offsets + v_shaped + # 4. Get the global joint location + J_transformed, A = batch_rigid_transform(rot_mats, J, parents, dtype=dtype) + + # 5. Do skinning: + # W is N x V x (J + 1) + W = lbs_weights.unsqueeze(dim=0).expand([batch_size, -1, -1]) + # (N x V x (J + 1)) x (N x (J + 1) x 16) + num_joints = J_regressor.shape[0] + T = torch.matmul(W, A.view(batch_size, num_joints, 16)) \ + .view(batch_size, -1, 4, 4) + + homogen_coord = torch.ones([batch_size, v_posed.shape[1], 1], + dtype=dtype, device=device) + v_posed_homo = torch.cat([v_posed, homogen_coord], dim=2) + v_homo = torch.matmul(T, torch.unsqueeze(v_posed_homo, dim=-1)) + + verts = v_homo[:, :, :3, 0] + + return verts, J_transformed + + +def vertices2joints(J_regressor, vertices): + ''' Calculates the 3D joint locations from the vertices + + Parameters + ---------- + J_regressor : torch.tensor JxV + The regressor array that is used to calculate the joints from the + position of the vertices + vertices : torch.tensor BxVx3 + The tensor of mesh vertices + + Returns + ------- + torch.tensor BxJx3 + The location of the joints + ''' + + return torch.einsum('bik,ji->bjk', [vertices, J_regressor]) + + +def blend_shapes(betas, shape_disps): + ''' Calculates the per vertex displacement due to the blend shapes + + + Parameters + ---------- + betas : torch.tensor Bx(num_betas) + Blend shape coefficients + shape_disps: torch.tensor Vx3x(num_betas) + Blend shapes + + Returns + ------- + torch.tensor BxVx3 + The per-vertex displacement due to shape deformation + ''' + + # Displacement[b, m, k] = sum_{l} betas[b, l] * shape_disps[m, k, l] + # i.e. Multiply each shape displacement by its corresponding beta and + # then sum them. + blend_shape = torch.einsum('bl,mkl->bmk', [betas, shape_disps]) + return blend_shape + + +def batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32): + ''' Calculates the rotation matrices for a batch of rotation vectors + Parameters + ---------- + rot_vecs: torch.tensor Nx3 + array of N axis-angle vectors + Returns + ------- + R: torch.tensor Nx3x3 + The rotation matrices for the given axis-angle parameters + ''' + + batch_size = rot_vecs.shape[0] + device = rot_vecs.device + + angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True) + rot_dir = rot_vecs / angle + + cos = torch.unsqueeze(torch.cos(angle), dim=1) + sin = torch.unsqueeze(torch.sin(angle), dim=1) + + # Bx1 arrays + rx, ry, rz = torch.split(rot_dir, 1, dim=1) + K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device) + + zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device) + K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \ + .view((batch_size, 3, 3)) + + ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0) + rot_mat = ident + sin * K + (1 - cos) * torch.bmm(K, K) + return rot_mat + + +def transform_mat(R, t): + ''' Creates a batch of transformation matrices + Args: + - R: Bx3x3 array of a batch of rotation matrices + - t: Bx3x1 array of a batch of translation vectors + Returns: + - T: Bx4x4 Transformation matrix + ''' + # No padding left or right, only add an extra row + return torch.cat([F.pad(R, [0, 0, 0, 1]), + F.pad(t, [0, 0, 0, 1], value=1)], dim=2) + + +def batch_rigid_transform(rot_mats, joints, parents, dtype=torch.float32): + """ + Applies a batch of rigid transformations to the joints + + Parameters + ---------- + rot_mats : torch.tensor BxNx3x3 + Tensor of rotation matrices + joints : torch.tensor BxNx3 + Locations of joints + parents : torch.tensor BxN + The kinematic tree of each object + dtype : torch.dtype, optional: + The data type of the created tensors, the default is torch.float32 + + Returns + ------- + posed_joints : torch.tensor BxNx3 + The locations of the joints after applying the pose rotations + rel_transforms : torch.tensor BxNx4x4 + The relative (with respect to the root joint) rigid transformations + for all the joints + """ + + joints = torch.unsqueeze(joints, dim=-1) + + rel_joints = joints.clone() + rel_joints[:, 1:] -= joints[:, parents[1:]] + + # transforms_mat = transform_mat( + # rot_mats.view(-1, 3, 3), + # rel_joints.view(-1, 3, 1)).view(-1, joints.shape[1], 4, 4) + transforms_mat = transform_mat( + rot_mats.view(-1, 3, 3), + rel_joints.reshape(-1, 3, 1)).reshape(-1, joints.shape[1], 4, 4) + + transform_chain = [transforms_mat[:, 0]] + for i in range(1, parents.shape[0]): + # Subtract the joint location at the rest pose + # No need for rotation, since it's identity when at rest + curr_res = torch.matmul(transform_chain[parents[i]], + transforms_mat[:, i]) + transform_chain.append(curr_res) + + transforms = torch.stack(transform_chain, dim=1) + + # The last column of the transformations contains the posed joints + posed_joints = transforms[:, :, :3, 3] + + # The last column of the transformations contains the posed joints + posed_joints = transforms[:, :, :3, 3] + + joints_homogen = F.pad(joints, [0, 0, 0, 1]) + + rel_transforms = transforms - F.pad( + torch.matmul(transforms, joints_homogen), [3, 0, 0, 0, 0, 0, 0, 0]) + + return posed_joints, rel_transforms \ No newline at end of file diff --git a/src/models/mesh/rasterizer/INSTALL.md b/src/models/mesh/rasterizer/INSTALL.md new file mode 100644 index 0000000..de2cc01 --- /dev/null +++ b/src/models/mesh/rasterizer/INSTALL.md @@ -0,0 +1,29 @@ +## Install +from standard_rasterize_cuda import standard_rasterize + # from .rasterizer.standard_rasterize_cuda import standard_rasterize + +in this folder, run +```python setup.py build_ext -i ``` + +then remember to set --rasterizer_type=standard when runing demos :) + +## Alg +https://www.scratchapixel.com/lessons/3d-basic-rendering/rasterization-practical-implementation + +## Speed Comparison +runtime for raterization only +In PIXIE, number of faces in SMPLX: 20908 + +for image size = 1024 +pytorch3d: 0.031s +standard: 0.01s + +for image size = 224 +pytorch3d: 0.0035s +standard: 0.0014s + +why standard rasterizer is faster than pytorch3d? +Ref: https://github.com/facebookresearch/pytorch3d/blob/master/pytorch3d/csrc/rasterize_meshes/rasterize_meshes.cu +pytorch3d: for each pixel in image space (each pixel is parallel in cuda), loop through the faces, check if this pixel is in the projection bounding box of the face, then sorting faces according to z, record the face id of closest K faces. +standard rasterization: for each face in mesh (each face is parallel in cuda), loop through pixels in the projection bounding box (normally a very samll number), compare z, record face id of that pixel + diff --git a/src/models/mesh/rasterizer/__init__.py b/src/models/mesh/rasterizer/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/src/models/mesh/rasterizer/setup.py b/src/models/mesh/rasterizer/setup.py new file mode 100755 index 0000000..8c559a1 --- /dev/null +++ b/src/models/mesh/rasterizer/setup.py @@ -0,0 +1,24 @@ +# To install, run +# python setup.py build_ext -i +# Ref: https://github.com/pytorch/pytorch/blob/11a40410e755b1fe74efe9eaa635e7ba5712846b/test/cpp_extensions/setup.py#L62 + +from setuptools import setup +from torch.utils.cpp_extension import BuildExtension, CUDAExtension +import os + +# USE_NINJA = os.getenv('USE_NINJA') == '1' +os.environ["CC"] = "gcc-7" +os.environ["CXX"] = "gcc-7" + +USE_NINJA = os.getenv('USE_NINJA') == '1' + +setup( + name='standard_rasterize_cuda', + ext_modules=[ + CUDAExtension('standard_rasterize_cuda', [ + 'standard_rasterize_cuda.cpp', + 'standard_rasterize_cuda_kernel.cu', + ]) + ], + cmdclass={'build_ext': BuildExtension.with_options(use_ninja=USE_NINJA)} +) diff --git a/src/models/mesh/rasterizer/standard_rasterize_cuda.cpp b/src/models/mesh/rasterizer/standard_rasterize_cuda.cpp new file mode 100755 index 0000000..d481580 --- /dev/null +++ b/src/models/mesh/rasterizer/standard_rasterize_cuda.cpp @@ -0,0 +1,48 @@ +#include +#include +#include + +std::vector forward_rasterize_cuda( + at::Tensor face_vertices, + at::Tensor depth_buffer, + at::Tensor triangle_buffer, + at::Tensor baryw_buffer, + int h, + int w); + +std::vector standard_rasterize( + at::Tensor face_vertices, + at::Tensor depth_buffer, + at::Tensor triangle_buffer, + at::Tensor baryw_buffer, + int height, int width + ) { + return forward_rasterize_cuda(face_vertices, depth_buffer, triangle_buffer, baryw_buffer, height, width); +} + +std::vector forward_rasterize_colors_cuda( + at::Tensor face_vertices, + at::Tensor face_colors, + at::Tensor depth_buffer, + at::Tensor triangle_buffer, + at::Tensor images, + int h, + int w); + +std::vector standard_rasterize_colors( + at::Tensor face_vertices, + at::Tensor face_colors, + at::Tensor depth_buffer, + at::Tensor triangle_buffer, + at::Tensor images, + int height, int width + ) { + return forward_rasterize_colors_cuda(face_vertices, face_colors, depth_buffer, triangle_buffer, images, height, width); +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("standard_rasterize", &standard_rasterize, "RASTERIZE (CUDA)"); + m.def("standard_rasterize_colors", &standard_rasterize_colors, "RASTERIZE COLORS (CUDA)"); +} + +// TODO: backward \ No newline at end of file diff --git a/src/models/mesh/rasterizer/standard_rasterize_cuda_kernel.cu b/src/models/mesh/rasterizer/standard_rasterize_cuda_kernel.cu new file mode 100755 index 0000000..f88432b --- /dev/null +++ b/src/models/mesh/rasterizer/standard_rasterize_cuda_kernel.cu @@ -0,0 +1,319 @@ +// Ref: https://github.com/daniilidis-group/neural_renderer/blob/master/neural_renderer/cuda/rasterize_cuda_kernel.cu +// https://github.com/YadiraF/face3d/blob/master/face3d/mesh/cython/mesh_core.cpp + +#include + +#include +#include + +namespace{ +__device__ __forceinline__ float atomicMin(float* address, float val) +{ + int* address_as_i = (int*) address; + int old = *address_as_i, assumed; + do { + assumed = old; + old = atomicCAS(address_as_i, assumed, + __float_as_int(fminf(val, __int_as_float(assumed)))); + } while (assumed != old); + return __int_as_float(old); +} +__device__ __forceinline__ double atomicMin(double* address, double val) +{ + unsigned long long int* address_as_i = (unsigned long long int*) address; + unsigned long long int old = *address_as_i, assumed; + do { + assumed = old; + old = atomicCAS(address_as_i, assumed, + __double_as_longlong(fminf(val, __longlong_as_double(assumed)))); + } while (assumed != old); + return __longlong_as_double(old); +} + +template +__device__ __forceinline__ bool check_face_frontside(const scalar_t *face) { + return (face[7] - face[1]) * (face[3] - face[0]) < (face[4] - face[1]) * (face[6] - face[0]); +} + + +template struct point +{ + public: + scalar_t x; + scalar_t y; + + __host__ __device__ scalar_t dot(point p) + { + return this->x * p.x + this->y * p.y; + }; + + __host__ __device__ point operator-(point& p) + { + point np; + np.x = this->x - p.x; + np.y = this->y - p.y; + return np; + }; + + __host__ __device__ point operator+(point& p) + { + point np; + np.x = this->x + p.x; + np.y = this->y + p.y; + return np; + }; + + __host__ __device__ point operator*(scalar_t s) + { + point np; + np.x = s * this->x; + np.y = s * this->y; + return np; + }; +}; + +template +__device__ __forceinline__ bool check_pixel_inside(const scalar_t *w) { + return w[0] <= 1 && w[0] >= 0 && w[1] <= 1 && w[1] >= 0 && w[2] <= 1 && w[2] >= 0; +} + +template +__device__ __forceinline__ void barycentric_weight(scalar_t *w, point p, point p0, point p1, point p2) { + + // vectors + point v0, v1, v2; + scalar_t s = p.dot(p); + v0 = p2 - p0; + v1 = p1 - p0; + v2 = p - p0; + + // dot products + scalar_t dot00 = v0.dot(v0); //v0.x * v0.x + v0.y * v0.y //np.dot(v0.T, v0) + scalar_t dot01 = v0.dot(v1); //v0.x * v1.x + v0.y * v1.y //np.dot(v0.T, v1) + scalar_t dot02 = v0.dot(v2); //v0.x * v2.x + v0.y * v2.y //np.dot(v0.T, v2) + scalar_t dot11 = v1.dot(v1); //v1.x * v1.x + v1.y * v1.y //np.dot(v1.T, v1) + scalar_t dot12 = v1.dot(v2); //v1.x * v2.x + v1.y * v2.y//np.dot(v1.T, v2) + + // barycentric coordinates + scalar_t inverDeno; + if(dot00*dot11 - dot01*dot01 == 0) + inverDeno = 0; + else + inverDeno = 1/(dot00*dot11 - dot01*dot01); + + scalar_t u = (dot11*dot02 - dot01*dot12)*inverDeno; + scalar_t v = (dot00*dot12 - dot01*dot02)*inverDeno; + + // weight + w[0] = 1 - u - v; + w[1] = v; + w[2] = u; +} + +// Ref: https://www.scratchapixel.com/lessons/3d-basic-rendering/rasterization-practical-implementation/overview-rasterization-algorithm +template +__global__ void forward_rasterize_cuda_kernel( + const scalar_t* __restrict__ face_vertices, //[bz, nf, 3, 3] + scalar_t* depth_buffer, + int* triangle_buffer, + scalar_t* baryw_buffer, + int batch_size, int h, int w, + int ntri) { + + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= batch_size * ntri) { + return; + } + int bn = i/ntri; + const scalar_t* face = &face_vertices[i * 9]; + scalar_t bw[3]; + point p0, p1, p2, p; + + p0.x = face[0]; p0.y=face[1]; + p1.x = face[3]; p1.y=face[4]; + p2.x = face[6]; p2.y=face[7]; + + int x_min = max((int)ceil(min(p0.x, min(p1.x, p2.x))), 0); + int x_max = min((int)floor(max(p0.x, max(p1.x, p2.x))), w - 1); + int y_min = max((int)ceil(min(p0.y, min(p1.y, p2.y))), 0); + int y_max = min((int)floor(max(p0.y, max(p1.y, p2.y))), h - 1); + + for(int y = y_min; y <= y_max; y++) //h + { + for(int x = x_min; x <= x_max; x++) //w + { + p.x = x; p.y = y; + barycentric_weight(bw, p, p0, p1, p2); + // if(((bw[2] >= 0) && (bw[1] >= 0) && (bw[0]>0)) && check_face_frontside(face)) + if((bw[2] >= 0) && (bw[1] >= 0) && (bw[0]>0)) + { + // perspective correct: https://www.scratchapixel.com/lessons/3d-basic-rendering/rasterization-practical-implementation/perspective-correct-interpolation-vertex-attributes + scalar_t zp = 1. / (bw[0] / face[2] + bw[1] / face[5] + bw[2] / face[8]); + // printf("%f %f %f \n", (float)zp, (float)face[2], (float)bw[2]); + atomicMin(&depth_buffer[bn*h*w + y*w + x], zp); + if(depth_buffer[bn*h*w + y*w + x] == zp) + { + triangle_buffer[bn*h*w + y*w + x] = (int)(i%ntri); + for(int k=0; k<3; k++){ + baryw_buffer[bn*h*w*3 + y*w*3 + x*3 + k] = bw[k]; + } + } + } + } + } + +} + +template +__global__ void forward_rasterize_colors_cuda_kernel( + const scalar_t* __restrict__ face_vertices, //[bz, nf, 3, 3] + const scalar_t* __restrict__ face_colors, //[bz, nf, 3, 3] + scalar_t* depth_buffer, + int* triangle_buffer, + scalar_t* images, + int batch_size, int h, int w, + int ntri) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= batch_size * ntri) { + return; + } + int bn = i/ntri; + const scalar_t* face = &face_vertices[i * 9]; + const scalar_t* color = &face_colors[i * 9]; + scalar_t bw[3]; + point p0, p1, p2, p; + + p0.x = face[0]; p0.y=face[1]; + p1.x = face[3]; p1.y=face[4]; + p2.x = face[6]; p2.y=face[7]; + scalar_t cl[3][3]; + for (int num = 0; num < 3; num++) { + for (int dim = 0; dim < 3; dim++) { + cl[num][dim] = color[3 * num + dim]; //[3p,3rgb] + } + } + int x_min = max((int)ceil(min(p0.x, min(p1.x, p2.x))), 0); + int x_max = min((int)floor(max(p0.x, max(p1.x, p2.x))), w - 1); + int y_min = max((int)ceil(min(p0.y, min(p1.y, p2.y))), 0); + int y_max = min((int)floor(max(p0.y, max(p1.y, p2.y))), h - 1); + + for(int y = y_min; y <= y_max; y++) //h + { + for(int x = x_min; x <= x_max; x++) //w + { + p.x = x; p.y = y; + barycentric_weight(bw, p, p0, p1, p2); + if(((bw[2] >= 0) && (bw[1] >= 0) && (bw[0]>0)) && check_face_frontside(face)) + // if((bw[2] >= 0) && (bw[1] >= 0) && (bw[0]>0)) + { + scalar_t zp = 1. / (bw[0] / face[2] + bw[1] / face[5] + bw[2] / face[8]); + + atomicMin(&depth_buffer[bn*h*w + y*w + x], zp); + if(depth_buffer[bn*h*w + y*w + x] == zp) + { + triangle_buffer[bn*h*w + y*w + x] = (int)(i%ntri); + for(int k=0; k<3; k++){ + // baryw_buffer[bn*h*w*3 + y*w*3 + x*3 + k] = bw[k]; + images[bn*h*w*3 + y*w*3 + x*3 + k] = bw[0]*cl[0][k] + bw[1]*cl[1][k] + bw[2]*cl[2][k]; + } + // buffers[bn*h*w*2 + y*w*2 + x*2 + 1] = p_depth; + } + } + } + } + +} + +} + +std::vector forward_rasterize_cuda( + at::Tensor face_vertices, + at::Tensor depth_buffer, + at::Tensor triangle_buffer, + at::Tensor baryw_buffer, + int h, + int w){ + + const auto batch_size = face_vertices.size(0); + const auto ntri = face_vertices.size(1); + + // print(channel_size) + const int threads = 512; + const dim3 blocks_1 ((batch_size * ntri - 1) / threads +1); + + AT_DISPATCH_FLOATING_TYPES(face_vertices.type(), "forward_rasterize_cuda1", ([&] { + forward_rasterize_cuda_kernel<<>>( + face_vertices.data(), + depth_buffer.data(), + triangle_buffer.data(), + baryw_buffer.data(), + batch_size, h, w, + ntri); + })); + + // better to do it twice (or there will be balck spots in the rendering) + AT_DISPATCH_FLOATING_TYPES(face_vertices.type(), "forward_rasterize_cuda2", ([&] { + forward_rasterize_cuda_kernel<<>>( + face_vertices.data(), + depth_buffer.data(), + triangle_buffer.data(), + baryw_buffer.data(), + batch_size, h, w, + ntri); + })); + cudaError_t err = cudaGetLastError(); + if (err != cudaSuccess) + printf("Error in forward_rasterize_cuda_kernel: %s\n", cudaGetErrorString(err)); + + return {depth_buffer, triangle_buffer, baryw_buffer}; +} + + +std::vector forward_rasterize_colors_cuda( + at::Tensor face_vertices, + at::Tensor face_colors, + at::Tensor depth_buffer, + at::Tensor triangle_buffer, + at::Tensor images, + int h, + int w){ + + const auto batch_size = face_vertices.size(0); + const auto ntri = face_vertices.size(1); + + // print(channel_size) + const int threads = 512; + const dim3 blocks_1 ((batch_size * ntri - 1) / threads +1); + //initial + + AT_DISPATCH_FLOATING_TYPES(face_vertices.type(), "forward_rasterize_colors_cuda", ([&] { + forward_rasterize_colors_cuda_kernel<<>>( + face_vertices.data(), + face_colors.data(), + depth_buffer.data(), + triangle_buffer.data(), + images.data(), + batch_size, h, w, + ntri); + })); + // better to do it twice + // AT_DISPATCH_FLOATING_TYPES(face_vertices.type(), "forward_rasterize_colors_cuda", ([&] { + // forward_rasterize_colors_cuda_kernel<<>>( + // face_vertices.data(), + // face_colors.data(), + // depth_buffer.data(), + // triangle_buffer.data(), + // images.data(), + // batch_size, h, w, + // ntri); + // })); + cudaError_t err = cudaGetLastError(); + if (err != cudaSuccess) + printf("Error in forward_rasterize_cuda_kernel: %s\n", cudaGetErrorString(err)); + + return {depth_buffer, triangle_buffer, images}; +} + + + + diff --git a/src/models/mesh/renderer.py b/src/models/mesh/renderer.py new file mode 100755 index 0000000..417b37b --- /dev/null +++ b/src/models/mesh/renderer.py @@ -0,0 +1,458 @@ +# -*- coding: utf-8 -*- +# +# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is +# holder of all proprietary rights on this computer program. +# Using this computer program means that you agree to the terms +# in the LICENSE file included with this software distribution. +# Any use not explicitly granted by the LICENSE is prohibited. +# +# Copyright©2019 Max-Planck-Gesellschaft zur Förderung +# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute +# for Intelligent Systems. All rights reserved. +# +# For comments or questions, please email us at deca@tue.mpg.de +# For commercial licensing contact, please contact ps-license@tuebingen.mpg.de + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from skimage.io import imread +import imageio + +from . import util + +def set_rasterizer(type = 'pytorch3d'): + if type == 'pytorch3d': + global Meshes, load_obj, rasterize_meshes + from pytorch3d.structures import Meshes + from pytorch3d.io import load_obj + from pytorch3d.renderer.mesh import rasterize_meshes + + elif type == 'standard': + global standard_rasterize, load_obj + import os + from .util import load_obj + # Use JIT Compiling Extensions + # ref: https://pytorch.org/tutorials/advanced/cpp_extension.html + from torch.utils.cpp_extension import load, CUDA_HOME + curr_dir = os.path.dirname(__file__) + standard_rasterize_cuda = \ + load(name='standard_rasterize_cuda', + sources=[f'{curr_dir}/rasterizer/standard_rasterize_cuda.cpp', f'{curr_dir}/rasterizer/standard_rasterize_cuda_kernel.cu'], + extra_cuda_cflags = ['-std=c++14', '-ccbin=$$(which gcc-7)']) # cuda10.2 is not compatible with gcc9. Specify gcc 7 + from standard_rasterize_cuda import standard_rasterize + # If JIT does not work, try manually installation first + # 1. see instruction here: pixielib/utils/rasterizer/INSTALL.md + # 2. add this: "from .rasterizer.standard_rasterize_cuda import standard_rasterize" here + +class StandardRasterizer(nn.Module): + """ Alg: https://www.scratchapixel.com/lessons/3d-basic-rendering/rasterization-practical-implementation + Notice: + x,y,z are in image space, normalized to [-1, 1] + can render non-squared image + not differentiable + """ + def __init__(self, height, width=None): + """ + use fixed raster_settings for rendering faces + """ + super().__init__() + if width is None: + width = height + self.h = h = height; self.w = w = width + + def forward(self, vertices, faces, attributes=None, h=None, w=None): + device = vertices.device + if h is None: + h = self.h + if w is None: + w = self.h; + bz = vertices.shape[0] + depth_buffer = torch.zeros([bz, h, w]).float().to(device) + 1e6 + triangle_buffer = torch.zeros([bz, h, w]).int().to(device) - 1 + baryw_buffer = torch.zeros([bz, h, w, 3]).float().to(device) + vert_vis = torch.zeros([bz, vertices.shape[1]]).float().to(device) + vertices = vertices.clone().float() + # compatibale with pytorch3d ndc, see https://github.com/facebookresearch/pytorch3d/blob/e42b0c4f704fa0f5e262f370dccac537b5edf2b1/pytorch3d/csrc/rasterize_meshes/rasterize_meshes.cu#L232 + vertices[...,:2] = -vertices[...,:2] + vertices[...,0] = vertices[..., 0]*w/2 + w/2 + vertices[...,1] = vertices[..., 1]*h/2 + h/2 + vertices[...,0] = w - 1 - vertices[..., 0] + vertices[...,1] = h - 1 - vertices[..., 1] + vertices[...,0] = -1 + (2*vertices[...,0] + 1)/w + vertices[...,1] = -1 + (2*vertices[...,1] + 1)/h + # + vertices = vertices.clone().float() + vertices[...,0] = vertices[..., 0]*w/2 + w/2 + vertices[...,1] = vertices[..., 1]*h/2 + h/2 + vertices[...,2] = vertices[..., 2]*w/2 + f_vs = util.face_vertices(vertices, faces) + + standard_rasterize(f_vs, depth_buffer, triangle_buffer, baryw_buffer, h, w) + pix_to_face = triangle_buffer[:,:,:,None].long() + bary_coords = baryw_buffer[:,:,:,None,:] + vismask = (pix_to_face > -1).float() + D = attributes.shape[-1] + attributes = attributes.clone(); attributes = attributes.view(attributes.shape[0]*attributes.shape[1], 3, attributes.shape[-1]) + N, H, W, K, _ = bary_coords.shape + mask = pix_to_face == -1 + pix_to_face = pix_to_face.clone() + pix_to_face[mask] = 0 + idx = pix_to_face.view(N * H * W * K, 1, 1).expand(N * H * W * K, 3, D) + pixel_face_vals = attributes.gather(0, idx).view(N, H, W, K, 3, D) + pixel_vals = (bary_coords[..., None] * pixel_face_vals).sum(dim=-2) + pixel_vals[mask] = 0 # Replace masked values in output. + pixel_vals = pixel_vals[:,:,:,0].permute(0,3,1,2) + pixel_vals = torch.cat([pixel_vals, vismask[:,:,:,0][:,None,:,:]], dim=1) + return pixel_vals + +class Pytorch3dRasterizer(nn.Module): + ## TODO: add support for rendering non-squared images, since pytorc3d supports this now + """ Borrowed from https://github.com/facebookresearch/pytorch3d + Notice: + x,y,z are in image space, normalized + can only render squared image now + """ + + def __init__(self, image_size=224): + """ + use fixed raster_settings for rendering faces + """ + super().__init__() + raster_settings = { + 'image_size': image_size, + 'blur_radius': 0.0, + 'faces_per_pixel': 1, + 'bin_size': None, + 'max_faces_per_bin': None, + 'perspective_correct': False, + } + raster_settings = util.dict2obj(raster_settings) + self.raster_settings = raster_settings + + def forward(self, vertices, faces, attributes=None, h=None, w=None): + fixed_vertices = vertices.clone() + fixed_vertices[...,:2] = -fixed_vertices[...,:2] + raster_settings = self.raster_settings + if h is None and w is None: + image_size = raster_settings.image_size + else: + image_size = [h, w] + if h>w: + fixed_vertices[..., 1] = fixed_vertices[..., 1]*h/w + else: + fixed_vertices[..., 0] = fixed_vertices[..., 0]*w/h + + meshes_screen = Meshes(verts=fixed_vertices.float(), faces=faces.long()) + pix_to_face, zbuf, bary_coords, dists = rasterize_meshes( + meshes_screen, + image_size=image_size, + blur_radius=raster_settings.blur_radius, + faces_per_pixel=raster_settings.faces_per_pixel, + bin_size=raster_settings.bin_size, + max_faces_per_bin=raster_settings.max_faces_per_bin, + perspective_correct=raster_settings.perspective_correct, + ) + vismask = (pix_to_face > -1).float() + D = attributes.shape[-1] + attributes = attributes.clone(); attributes = attributes.view(attributes.shape[0]*attributes.shape[1], 3, attributes.shape[-1]) + N, H, W, K, _ = bary_coords.shape + mask = pix_to_face == -1 + pix_to_face = pix_to_face.clone() + pix_to_face[mask] = 0 + idx = pix_to_face.view(N * H * W * K, 1, 1).expand(N * H * W * K, 3, D) + pixel_face_vals = attributes.gather(0, idx).view(N, H, W, K, 3, D) + pixel_vals = (bary_coords[..., None] * pixel_face_vals).sum(dim=-2) + pixel_vals[mask] = 0 # Replace masked values in output. + pixel_vals = pixel_vals[:,:,:,0].permute(0,3,1,2) + pixel_vals = torch.cat([pixel_vals, vismask[:,:,:,0][:,None,:,:]], dim=1) + # print(image_size) + # import ipdb; ipdb.set_trace() + return pixel_vals + +class SRenderY(nn.Module): + def __init__(self, image_size, obj_filename, uv_size=256, rasterizer_type='pytorch3d'): + super(SRenderY, self).__init__() + self.image_size = image_size + self.uv_size = uv_size + + if rasterizer_type == 'pytorch3d': + self.rasterizer = Pytorch3dRasterizer(image_size) + self.uv_rasterizer = Pytorch3dRasterizer(uv_size) + + verts, faces, aux = load_obj(obj_filename) + uvcoords = aux.verts_uvs[None, ...] # (N, V, 2) + uvfaces = faces.textures_idx[None, ...] # (N, F, 3) + faces = faces.verts_idx[None,...] + + elif rasterizer_type == 'standard': + self.rasterizer = StandardRasterizer(image_size) + self.uv_rasterizer = StandardRasterizer(uv_size) + verts, uvcoords, faces, uvfaces = load_obj(obj_filename) + verts = verts[None, ...] + uvcoords = uvcoords[None, ...] + faces = faces[None, ...] + uvfaces = uvfaces[None, ...] + + else: + NotImplementedError + + # faces + dense_triangles = util.generate_triangles(uv_size, uv_size) + self.register_buffer('dense_faces', torch.from_numpy(dense_triangles).long()[None,:,:]) + self.register_buffer('faces', faces) + self.register_buffer('raw_uvcoords', uvcoords) + + # uv coords + uvcoords = torch.cat([uvcoords, uvcoords[:,:,0:1]*0.+1.], -1) #[bz, ntv, 3] + uvcoords = uvcoords*2 - 1; uvcoords[...,1] = -uvcoords[...,1] + face_uvcoords = util.face_vertices(uvcoords, uvfaces) + self.register_buffer('uvcoords', uvcoords) + self.register_buffer('uvfaces', uvfaces) + self.register_buffer('face_uvcoords', face_uvcoords) + + # shape colors, for rendering shape overlay + colors = torch.tensor([180, 180, 180])[None, None, :].repeat(1, faces.max()+1, 1).float()/255. + face_colors = util.face_vertices(colors, faces) + self.register_buffer('face_colors', face_colors) + + ## SH factors for lighting + pi = np.pi + constant_factor = torch.tensor([1/np.sqrt(4*pi), ((2*pi)/3)*(np.sqrt(3/(4*pi))), ((2*pi)/3)*(np.sqrt(3/(4*pi))),\ + ((2*pi)/3)*(np.sqrt(3/(4*pi))), (pi/4)*(3)*(np.sqrt(5/(12*pi))), (pi/4)*(3)*(np.sqrt(5/(12*pi))),\ + (pi/4)*(3)*(np.sqrt(5/(12*pi))), (pi/4)*(3/2)*(np.sqrt(5/(12*pi))), (pi/4)*(1/2)*(np.sqrt(5/(4*pi)))]).float() + self.register_buffer('constant_factor', constant_factor) + + def forward(self, vertices, transformed_vertices, albedos, lights=None, light_type='point'): + ''' + -- Texture Rendering + vertices: [batch_size, V, 3], vertices in world space, for calculating normals, then shading + transformed_vertices: [batch_size, V, 3], range:normalized to [-1,1], projected vertices in image space (that is aligned to the iamge pixel), for rasterization + albedos: [batch_size, 3, h, w], uv map + lights: + spherical homarnic: [N, 9(shcoeff), 3(rgb)] + points/directional lighting: [N, n_lights, 6(xyzrgb)] + light_type: + point or directional + ''' + batch_size = vertices.shape[0] + ## rasterizer near 0 far 100. move mesh so minz larger than 0 + transformed_vertices[:,:,2] = transformed_vertices[:,:,2] + 10 + # attributes + face_vertices = util.face_vertices(vertices, 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)) + + attributes = torch.cat([self.face_uvcoords.expand(batch_size, -1, -1, -1), + transformed_face_normals.detach(), + face_vertices.detach(), + face_normals], + -1) + # rasterize + rendering = self.rasterizer(transformed_vertices, self.faces.expand(batch_size, -1, -1), attributes) + + #### + # vis mask + alpha_images = rendering[:, -1, :, :][:, None, :, :].detach() + + # albedo + uvcoords_images = rendering[:, :3, :, :]; grid = (uvcoords_images).permute(0, 2, 3, 1)[:, :, :, :2] + albedo_images = F.grid_sample(albedos, grid, align_corners=False) + + # visible mask for pixels with positive normal direction + transformed_normal_map = rendering[:, 3:6, :, :].detach() + pos_mask = (transformed_normal_map[:, 2:, :, :] < -0.05).float() + + # shading + normal_images = rendering[:, 9:12, :, :] + if lights is not None: + if lights.shape[1] == 9: + shading_images = self.add_SHlight(normal_images, lights) + else: + if light_type=='point': + vertice_images = rendering[:, 6:9, :, :].detach() + shading = self.add_pointlight(vertice_images.permute(0,2,3,1).reshape([batch_size, -1, 3]), normal_images.permute(0,2,3,1).reshape([batch_size, -1, 3]), lights) + shading_images = shading.reshape([batch_size, albedo_images.shape[2], albedo_images.shape[3], 3]).permute(0,3,1,2) + else: + shading = self.add_directionlight(normal_images.permute(0,2,3,1).reshape([batch_size, -1, 3]), lights) + shading_images = shading.reshape([batch_size, albedo_images.shape[2], albedo_images.shape[3], 3]).permute(0,3,1,2) + images = albedo_images*shading_images + else: + images = albedo_images + shading_images = images.detach()*0. + + outputs = { + 'images': images*alpha_images, + 'albedo_images': albedo_images*alpha_images, + 'alpha_images': alpha_images, + 'pos_mask': pos_mask, + 'shading_images': shading_images, + 'grid': grid, + 'normals': normals, + 'normal_images': normal_images*alpha_images, + 'transformed_normals': transformed_normals, + } + + return outputs + + def add_SHlight(self, normal_images, sh_coeff): + ''' + sh_coeff: [bz, 9, 3] + ''' + N = normal_images + sh = torch.stack([ + N[:,0]*0.+1., N[:,0], N[:,1], \ + N[:,2], N[:,0]*N[:,1], N[:,0]*N[:,2], + N[:,1]*N[:,2], N[:,0]**2 - N[:,1]**2, 3*(N[:,2]**2) - 1 + ], + 1) # [bz, 9, h, w] + sh = sh*self.constant_factor[None,:,None,None] + shading = torch.sum(sh_coeff[:,:,:,None,None]*sh[:,:,None,:,:], 1) # [bz, 9, 3, h, w] + return shading + + def add_pointlight(self, vertices, normals, lights): + ''' + vertices: [bz, nv, 3] + lights: [bz, nlight, 6] + returns: + shading: [bz, nv, 3] + ''' + light_positions = lights[:,:,:3]; light_intensities = lights[:,:,3:] + directions_to_lights = F.normalize(light_positions[:,:,None,:] - vertices[:,None,:,:], dim=3) + # normals_dot_lights = torch.clamp((normals[:,None,:,:]*directions_to_lights).sum(dim=3), 0., 1.) + normals_dot_lights = (normals[:,None,:,:]*directions_to_lights).sum(dim=3) + shading = normals_dot_lights[:,:,:,None]*light_intensities[:,:,None,:] + return shading.mean(1) + + def add_directionlight(self, normals, lights): + ''' + normals: [bz, nv, 3] + lights: [bz, nlight, 6] + returns: + shading: [bz, nv, 3] + ''' + light_direction = lights[:,:,:3]; light_intensities = lights[:,:,3:] + directions_to_lights = F.normalize(light_direction[:,:,None,:].expand(-1,-1,normals.shape[1],-1), dim=3) + # normals_dot_lights = torch.clamp((normals[:,None,:,:]*directions_to_lights).sum(dim=3), 0., 1.) + # normals_dot_lights = (normals[:,None,:,:]*directions_to_lights).sum(dim=3) + normals_dot_lights = torch.clamp((normals[:,None,:,:]*directions_to_lights).sum(dim=3), 0., 1.) + shading = normals_dot_lights[:,:,:,None]*light_intensities[:,:,None,:] + return shading.mean(1) + + def render_shape(self, vertices, transformed_vertices, colors = None, images=None, detail_normal_images=None, + lights=None, return_grid=False, uv_detail_normals=None, h=None, w=None): + ''' + -- rendering shape with detail normal map + ''' + batch_size = vertices.shape[0] + # set lighting + if lights is None: + light_positions = torch.tensor( + [ + [-1,1,1], + [1,1,1], + [-1,-1,1], + [1,-1,1], + [0,0,1] + ] + )[None,:,:].expand(batch_size, -1, -1).float() + light_intensities = torch.ones_like(light_positions).float()*1.7 + lights = torch.cat((light_positions, light_intensities), 2).to(vertices.device) + transformed_vertices[:,:,2] = transformed_vertices[:,:,2] + 10 + + # Attributes + face_vertices = util.face_vertices(vertices, 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)) + if colors is None: + colors = self.face_colors.expand(batch_size, -1, -1, -1) + attributes = torch.cat([colors, + transformed_face_normals.detach(), + face_vertices.detach(), + face_normals, + self.face_uvcoords.expand(batch_size, -1, -1, -1)], + -1) + + # rasterize + # import ipdb; ipdb.set_trace() + rendering = self.rasterizer(transformed_vertices, self.faces.expand(batch_size, -1, -1), attributes, h, w) + + #### + alpha_images = rendering[:, -1, :, :][:, None, :, :].detach() + + # albedo + albedo_images = rendering[:, :3, :, :] + # mask + transformed_normal_map = rendering[:, 3:6, :, :].detach() + pos_mask = (transformed_normal_map[:, 2:, :, :] < 0.15).float() + + # shading + normal_images = rendering[:, 9:12, :, :].detach() + vertice_images = rendering[:, 6:9, :, :].detach() + if detail_normal_images is not None: + normal_images = detail_normal_images + + shading = self.add_directionlight(normal_images.permute(0,2,3,1).reshape([batch_size, -1, 3]), lights) + shading_images = shading.reshape([batch_size, albedo_images.shape[2], albedo_images.shape[3], 3]).permute(0,3,1,2).contiguous() + shaded_images = albedo_images*shading_images + + alpha_images = alpha_images*pos_mask + if images is None: + shape_images = shaded_images*alpha_images + torch.zeros_like(shaded_images).to(vertices.device)*(1-alpha_images) + else: + shape_images = shaded_images*alpha_images + images*(1-alpha_images) + if return_grid: + uvcoords_images = rendering[:, 12:15, :, :]; + grid = (uvcoords_images).permute(0, 2, 3, 1)[:, :, :, :2] + return shape_images, normal_images, grid, alpha_images + else: + return shape_images + + def render_depth(self, transformed_vertices): + ''' + -- rendering depth + ''' + batch_size = transformed_vertices.shape[0] + + transformed_vertices[:,:,2] = transformed_vertices[:,:,2] - transformed_vertices[:,:,2].min() + z = -transformed_vertices[:,:,2:].repeat(1,1,3).clone() + z = z-z.min() + z = z/z.max() + # Attributes + attributes = util.face_vertices(z, self.faces.expand(batch_size, -1, -1)) + # rasterize + transformed_vertices[:,:,2] = transformed_vertices[:,:,2] + 10 + rendering = self.rasterizer(transformed_vertices, self.faces.expand(batch_size, -1, -1), attributes) + + #### + alpha_images = rendering[:, -1, :, :][:, None, :, :].detach() + depth_images = rendering[:, :1, :, :] + return depth_images + + def render_colors(self, transformed_vertices, colors): + ''' + -- rendering colors: could be rgb color/ normals, etc + colors: [bz, num of vertices, 3] + ''' + batch_size = colors.shape[0] + + # Attributes + attributes = util.face_vertices(colors, self.faces.expand(batch_size, -1, -1)) + # rasterize + rendering = self.rasterizer(transformed_vertices, self.faces.expand(batch_size, -1, -1), attributes) + #### + alpha_images = rendering[:, [-1], :, :].detach() + images = rendering[:, :3, :, :]* alpha_images + return images + + def world2uv(self, vertices): + ''' + warp vertices from world space to uv space + vertices: [bz, V, 3] + uv_vertices: [bz, 3, h, w] + ''' + batch_size = vertices.shape[0] + face_vertices = util.face_vertices(vertices, self.faces.expand(batch_size, -1, -1)) + uv_vertices = self.uv_rasterizer(self.uvcoords.expand(batch_size, -1, -1), self.uvfaces.expand(batch_size, -1, -1), face_vertices)[:, :3] + return uv_vertices \ No newline at end of file diff --git a/src/models/mesh/rotation_converter.py b/src/models/mesh/rotation_converter.py new file mode 100644 index 0000000..fc48a9b --- /dev/null +++ b/src/models/mesh/rotation_converter.py @@ -0,0 +1,374 @@ +import torch + +''' Rotation Converter +Repre: euler angle(3), angle axis(3), rotation matrix(3x3), quaternion(4) +ref: https://kornia.readthedocs.io/en/v0.1.2/_modules/torchgeometry/core/conversions.html# +"pi", +"rad2deg", +"deg2rad", +# "angle_axis_to_rotation_matrix", batch_rodrigues +"rotation_matrix_to_angle_axis", +"rotation_matrix_to_quaternion", +"quaternion_to_angle_axis", +# "angle_axis_to_quaternion", + +euler2quat_conversion_sanity_batch + +ref: smplx/lbs +batch_rodrigues: axis angle -> matrix +# +''' +pi = torch.Tensor([3.14159265358979323846]) + +def rad2deg(tensor): + """Function that converts angles from radians to degrees. + + See :class:`~torchgeometry.RadToDeg` for details. + + Args: + tensor (Tensor): Tensor of arbitrary shape. + + Returns: + Tensor: Tensor with same shape as input. + + Example: + >>> input = tgm.pi * torch.rand(1, 3, 3) + >>> output = tgm.rad2deg(input) + """ + if not torch.is_tensor(tensor): + raise TypeError("Input type is not a torch.Tensor. Got {}" + .format(type(tensor))) + + return 180. * tensor / pi.to(tensor.device).type(tensor.dtype) + +def deg2rad(tensor): + """Function that converts angles from degrees to radians. + + See :class:`~torchgeometry.DegToRad` for details. + + Args: + tensor (Tensor): Tensor of arbitrary shape. + + Returns: + Tensor: Tensor with same shape as input. + + Examples:: + + >>> input = 360. * torch.rand(1, 3, 3) + >>> output = tgm.deg2rad(input) + """ + if not torch.is_tensor(tensor): + raise TypeError("Input type is not a torch.Tensor. Got {}" + .format(type(tensor))) + + return tensor * pi.to(tensor.device).type(tensor.dtype) / 180. + +######### to quaternion +def euler_to_quaternion(r): + x = r[..., 0] + y = r[..., 1] + z = r[..., 2] + + z = z/2.0 + y = y/2.0 + x = x/2.0 + cz = torch.cos(z) + sz = torch.sin(z) + cy = torch.cos(y) + sy = torch.sin(y) + cx = torch.cos(x) + sx = torch.sin(x) + quaternion = torch.zeros_like(r.repeat(1,2))[..., :4].to(r.device) + quaternion[..., 0] += cx*cy*cz - sx*sy*sz + quaternion[..., 1] += cx*sy*sz + cy*cz*sx + quaternion[..., 2] += cx*cz*sy - sx*cy*sz + quaternion[..., 3] += cx*cy*sz + sx*cz*sy + return quaternion + +def rotation_matrix_to_quaternion(rotation_matrix, eps=1e-6): + """Convert 3x4 rotation matrix to 4d quaternion vector + + This algorithm is based on algorithm described in + https://github.com/KieranWynn/pyquaternion/blob/master/pyquaternion/quaternion.py#L201 + + Args: + rotation_matrix (Tensor): the rotation matrix to convert. + + Return: + Tensor: the rotation in quaternion + + Shape: + - Input: :math:`(N, 3, 4)` + - Output: :math:`(N, 4)` + + Example: + >>> input = torch.rand(4, 3, 4) # Nx3x4 + >>> output = tgm.rotation_matrix_to_quaternion(input) # Nx4 + """ + if not torch.is_tensor(rotation_matrix): + raise TypeError("Input type is not a torch.Tensor. Got {}".format( + type(rotation_matrix))) + + if len(rotation_matrix.shape) > 3: + raise ValueError( + "Input size must be a three dimensional tensor. Got {}".format( + rotation_matrix.shape)) + # if not rotation_matrix.shape[-2:] == (3, 4): + # raise ValueError( + # "Input size must be a N x 3 x 4 tensor. Got {}".format( + # rotation_matrix.shape)) + + rmat_t = torch.transpose(rotation_matrix, 1, 2) + + mask_d2 = rmat_t[:, 2, 2] < eps + + mask_d0_d1 = rmat_t[:, 0, 0] > rmat_t[:, 1, 1] + mask_d0_nd1 = rmat_t[:, 0, 0] < -rmat_t[:, 1, 1] + + t0 = 1 + rmat_t[:, 0, 0] - rmat_t[:, 1, 1] - rmat_t[:, 2, 2] + q0 = torch.stack([rmat_t[:, 1, 2] - rmat_t[:, 2, 1], + t0, rmat_t[:, 0, 1] + rmat_t[:, 1, 0], + rmat_t[:, 2, 0] + rmat_t[:, 0, 2]], -1) + t0_rep = t0.repeat(4, 1).t() + + t1 = 1 - rmat_t[:, 0, 0] + rmat_t[:, 1, 1] - rmat_t[:, 2, 2] + q1 = torch.stack([rmat_t[:, 2, 0] - rmat_t[:, 0, 2], + rmat_t[:, 0, 1] + rmat_t[:, 1, 0], + t1, rmat_t[:, 1, 2] + rmat_t[:, 2, 1]], -1) + t1_rep = t1.repeat(4, 1).t() + + t2 = 1 - rmat_t[:, 0, 0] - rmat_t[:, 1, 1] + rmat_t[:, 2, 2] + q2 = torch.stack([rmat_t[:, 0, 1] - rmat_t[:, 1, 0], + rmat_t[:, 2, 0] + rmat_t[:, 0, 2], + rmat_t[:, 1, 2] + rmat_t[:, 2, 1], t2], -1) + t2_rep = t2.repeat(4, 1).t() + + t3 = 1 + rmat_t[:, 0, 0] + rmat_t[:, 1, 1] + rmat_t[:, 2, 2] + q3 = torch.stack([t3, rmat_t[:, 1, 2] - rmat_t[:, 2, 1], + rmat_t[:, 2, 0] - rmat_t[:, 0, 2], + rmat_t[:, 0, 1] - rmat_t[:, 1, 0]], -1) + t3_rep = t3.repeat(4, 1).t() + + mask_c0 = mask_d2 * mask_d0_d1.float() + mask_c1 = mask_d2 * (1 - mask_d0_d1.float()) + mask_c2 = (1 - mask_d2.float()) * mask_d0_nd1 + mask_c3 = (1 - mask_d2.float()) * (1 - mask_d0_nd1.float()) + mask_c0 = mask_c0.view(-1, 1).type_as(q0) + mask_c1 = mask_c1.view(-1, 1).type_as(q1) + mask_c2 = mask_c2.view(-1, 1).type_as(q2) + mask_c3 = mask_c3.view(-1, 1).type_as(q3) + + q = q0 * mask_c0 + q1 * mask_c1 + q2 * mask_c2 + q3 * mask_c3 + q /= torch.sqrt(t0_rep * mask_c0 + t1_rep * mask_c1 + # noqa + t2_rep * mask_c2 + t3_rep * mask_c3) # noqa + q *= 0.5 + return q + +# def angle_axis_to_quaternion(theta): +# batch_size = theta.shape[0] +# l1norm = torch.norm(theta + 1e-8, p=2, dim=1) +# angle = torch.unsqueeze(l1norm, -1) +# normalized = torch.div(theta, angle) +# angle = angle * 0.5 +# v_cos = torch.cos(angle) +# v_sin = torch.sin(angle) +# quat = torch.cat([v_cos, v_sin * normalized], dim=1) +# return quat + +def angle_axis_to_quaternion(angle_axis: torch.Tensor) -> torch.Tensor: + """Convert an angle axis to a quaternion. + + Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h + + Args: + angle_axis (torch.Tensor): tensor with angle axis. + + Return: + torch.Tensor: tensor with quaternion. + + Shape: + - Input: :math:`(*, 3)` where `*` means, any number of dimensions + - Output: :math:`(*, 4)` + + Example: + >>> angle_axis = torch.rand(2, 4) # Nx4 + >>> quaternion = tgm.angle_axis_to_quaternion(angle_axis) # Nx3 + """ + if not torch.is_tensor(angle_axis): + raise TypeError("Input type is not a torch.Tensor. Got {}".format( + type(angle_axis))) + + if not angle_axis.shape[-1] == 3: + raise ValueError("Input must be a tensor of shape Nx3 or 3. Got {}" + .format(angle_axis.shape)) + # unpack input and compute conversion + a0: torch.Tensor = angle_axis[..., 0:1] + a1: torch.Tensor = angle_axis[..., 1:2] + a2: torch.Tensor = angle_axis[..., 2:3] + theta_squared: torch.Tensor = a0 * a0 + a1 * a1 + a2 * a2 + + theta: torch.Tensor = torch.sqrt(theta_squared) + half_theta: torch.Tensor = theta * 0.5 + + mask: torch.Tensor = theta_squared > 0.0 + ones: torch.Tensor = torch.ones_like(half_theta) + + k_neg: torch.Tensor = 0.5 * ones + k_pos: torch.Tensor = torch.sin(half_theta) / theta + k: torch.Tensor = torch.where(mask, k_pos, k_neg) + w: torch.Tensor = torch.where(mask, torch.cos(half_theta), ones) + + quaternion: torch.Tensor = torch.zeros_like(angle_axis) + quaternion[..., 0:1] += a0 * k + quaternion[..., 1:2] += a1 * k + quaternion[..., 2:3] += a2 * k + return torch.cat([w, quaternion], dim=-1) + +#### quaternion to +def quaternion_to_rotation_matrix(quat): + """Convert quaternion coefficients to rotation matrix. + Args: + quat: size = [B, 4] 4 <===>(w, x, y, z) + Returns: + Rotation matrix corresponding to the quaternion -- size = [B, 3, 3] + """ + norm_quat = quat + norm_quat = norm_quat / norm_quat.norm(p=2, dim=1, keepdim=True) + w, x, y, z = norm_quat[:, 0], norm_quat[:, 1], norm_quat[:, 2], norm_quat[:, 3] + + B = quat.size(0) + + w2, x2, y2, z2 = w.pow(2), x.pow(2), y.pow(2), z.pow(2) + wx, wy, wz = w * x, w * y, w * z + xy, xz, yz = x * y, x * z, y * z + + rotMat = torch.stack([w2 + x2 - y2 - z2, 2 * xy - 2 * wz, 2 * wy + 2 * xz, + 2 * wz + 2 * xy, w2 - x2 + y2 - z2, 2 * yz - 2 * wx, + 2 * xz - 2 * wy, 2 * wx + 2 * yz, w2 - x2 - y2 + z2], dim=1).view(B, 3, 3) + return rotMat + +def quaternion_to_angle_axis(quaternion: torch.Tensor): + """Convert quaternion vector to angle axis of rotation. TODO: CORRECT + + Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h + + Args: + quaternion (torch.Tensor): tensor with quaternions. + + Return: + torch.Tensor: tensor with angle axis of rotation. + + Shape: + - Input: :math:`(*, 4)` where `*` means, any number of dimensions + - Output: :math:`(*, 3)` + + Example: + >>> quaternion = torch.rand(2, 4) # Nx4 + >>> angle_axis = tgm.quaternion_to_angle_axis(quaternion) # Nx3 + """ + if not torch.is_tensor(quaternion): + raise TypeError("Input type is not a torch.Tensor. Got {}".format( + type(quaternion))) + + if not quaternion.shape[-1] == 4: + raise ValueError("Input must be a tensor of shape Nx4 or 4. Got {}" + .format(quaternion.shape)) + # unpack input and compute conversion + q1: torch.Tensor = quaternion[..., 1] + q2: torch.Tensor = quaternion[..., 2] + q3: torch.Tensor = quaternion[..., 3] + sin_squared_theta: torch.Tensor = q1 * q1 + q2 * q2 + q3 * q3 + + sin_theta: torch.Tensor = torch.sqrt(sin_squared_theta) + cos_theta: torch.Tensor = quaternion[..., 0] + two_theta: torch.Tensor = 2.0 * torch.where( + cos_theta < 0.0, + torch.atan2(-sin_theta, -cos_theta), + torch.atan2(sin_theta, cos_theta)) + + k_pos: torch.Tensor = two_theta / sin_theta + k_neg: torch.Tensor = 2.0 * torch.ones_like(sin_theta).to(quaternion.device) + k: torch.Tensor = torch.where(sin_squared_theta > 0.0, k_pos, k_neg) + + angle_axis: torch.Tensor = torch.zeros_like(quaternion).to(quaternion.device)[..., :3] + angle_axis[..., 0] += q1 * k + angle_axis[..., 1] += q2 * k + angle_axis[..., 2] += q3 * k + return angle_axis + +#### batch converter +def batch_euler2axis(r): + return quaternion_to_angle_axis(euler_to_quaternion(r)) + +def batch_euler2matrix(r): + return quaternion_to_rotation_matrix(euler_to_quaternion(r)) + +def batch_matrix2euler(rot_mats): + # Calculates rotation matrix to euler angles + # Careful for extreme cases of eular angles like [0.0, pi, 0.0] + ### only y? + # TODO: + sy = torch.sqrt(rot_mats[:, 0, 0] * rot_mats[:, 0, 0] + + rot_mats[:, 1, 0] * rot_mats[:, 1, 0]) + return torch.atan2(-rot_mats[:, 2, 0], sy) + +def batch_matrix2axis(rot_mats): + return quaternion_to_angle_axis(rotation_matrix_to_quaternion(rot_mats)) + +def batch_axis2matrix(theta): + # angle axis to rotation matrix + # theta N x 3 + # return quat2mat(quat) + # batch_rodrigues + return quaternion_to_rotation_matrix(angle_axis_to_quaternion(theta)) + +def batch_axis2euler(theta): + return batch_matrix2euler(batch_axis2matrix(theta)) + +def batch_axis2euler(r): + return rot_mat_to_euler(batch_rodrigues(r)) + + +def batch_orth_proj(X, camera): + ''' + X is N x num_pquaternion_to_angle_axisoints x 3 + ''' + camera = camera.clone().view(-1, 1, 3) + X_trans = X[:, :, :2] + camera[:, :, 1:] + X_trans = torch.cat([X_trans, X[:,:,2:]], 2) + Xn = (camera[:, :, 0:1] * X_trans) + return Xn + +def batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32): + ''' same as batch_matrix2axis + Calculates the rotation matrices for a batch of rotation vectors + Parameters + ---------- + rot_vecs: torch.tensor Nx3 + array of N axis-angle vectors + Returns + ------- + R: torch.tensor Nx3x3 + The rotation matrices for the given axis-angle parameters + ''' + + batch_size = rot_vecs.shape[0] + device = rot_vecs.device + + angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True) + rot_dir = rot_vecs / angle + + cos = torch.unsqueeze(torch.cos(angle), dim=1) + sin = torch.unsqueeze(torch.sin(angle), dim=1) + + # Bx1 arrays + rx, ry, rz = torch.split(rot_dir, 1, dim=1) + K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device) + + zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device) + K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \ + .view((batch_size, 3, 3)) + + ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0) + rot_mat = ident + sin * K + (1 - cos) * torch.bmm(K, K) + return rot_mat diff --git a/src/models/mesh/tensor_cropper.py b/src/models/mesh/tensor_cropper.py new file mode 100644 index 0000000..3100d6b --- /dev/null +++ b/src/models/mesh/tensor_cropper.py @@ -0,0 +1,136 @@ +''' +crop +for torch tensor +Given image, bbox(center, bboxsize) +return: cropped image, tform(used for transform the keypoint accordingly) +only support crop to squared images +''' +import torch +from kornia.geometry.transform.imgwarp import ( + warp_perspective, get_perspective_transform, warp_affine +) + +def points2bbox(points, points_scale=None): + if points_scale: + assert points_scale[0]==points_scale[1] + points = points.clone() + points[:,:,:2] = (points[:,:,:2]*0.5 + 0.5)*points_scale[0] + min_coords, _ = torch.min(points, dim=1) + xmin, ymin = min_coords[:, 0], min_coords[:, 1] + max_coords, _ = torch.max(points, dim=1) + xmax, ymax = max_coords[:, 0], max_coords[:, 1] + center = torch.stack([xmax + xmin, ymax + ymin], dim=-1) * 0.5 + + width = (xmax - xmin) + height = (ymax - ymin) + # Convert the bounding box to a square box + size = torch.max(width, height).unsqueeze(-1) + return center, size + +def augment_bbox(center, bbox_size, scale=[1.0, 1.0], trans_scale=0.): + batch_size = center.shape[0] + trans_scale = (torch.rand([batch_size, 2], device=center.device)*2. -1.) * trans_scale + center = center + trans_scale*bbox_size # 0.5 + scale = torch.rand([batch_size,1], device=center.device) * (scale[1] - scale[0]) + scale[0] + size = bbox_size*scale + return center, size + +def crop_tensor(image, center, bbox_size, crop_size, interpolation = 'bilinear', align_corners=False): + ''' for batch image + Args: + image (torch.Tensor): the reference tensor of shape BXHxWXC. + center: [bz, 2] + bboxsize: [bz, 1] + crop_size; + interpolation (str): Interpolation flag. Default: 'bilinear'. + align_corners (bool): mode for grid_generation. Default: False. See + https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details + Returns: + cropped_image + tform + ''' + dtype = image.dtype + device = image.device + batch_size = image.shape[0] + # points: top-left, top-right, bottom-right, bottom-left + src_pts = torch.zeros([4,2], dtype=dtype, device=device).unsqueeze(0).expand(batch_size, -1, -1).contiguous() + + src_pts[:, 0, :] = center - bbox_size*0.5 # / (self.crop_size - 1) + src_pts[:, 1, 0] = center[:, 0] + bbox_size[:, 0] * 0.5 + src_pts[:, 1, 1] = center[:, 1] - bbox_size[:, 0] * 0.5 + src_pts[:, 2, :] = center + bbox_size * 0.5 + src_pts[:, 3, 0] = center[:, 0] - bbox_size[:, 0] * 0.5 + src_pts[:, 3, 1] = center[:, 1] + bbox_size[:, 0] * 0.5 + + DST_PTS = torch.tensor([[ + [0, 0], + [crop_size - 1, 0], + [crop_size - 1, crop_size - 1], + [0, crop_size - 1], + ]], dtype=dtype, device=device).expand(batch_size, -1, -1) + # estimate transformation between points + dst_trans_src = get_perspective_transform(src_pts, DST_PTS) + # simulate broadcasting + # dst_trans_src = dst_trans_src.expand(batch_size, -1, -1) + + # warp images + cropped_image = warp_affine( + image, dst_trans_src[:, :2, :], (crop_size, crop_size), + flags=interpolation, align_corners=align_corners) + + tform = torch.transpose(dst_trans_src, 2, 1) + # tform = torch.inverse(dst_trans_src) + return cropped_image, tform + +class Cropper(object): + def __init__(self, crop_size, scale=[1,1], trans_scale = 0.): + self.crop_size = crop_size + self.scale = scale + self.trans_scale = trans_scale + + def crop(self, image, points, points_scale=None): + # points to bbox + center, bbox_size = points2bbox(points.clone(), points_scale) + # argument bbox. TODO: add rotation? + center, bbox_size = augment_bbox(center, bbox_size, scale=self.scale, trans_scale=self.trans_scale) + # crop + cropped_image, tform = crop_tensor(image, center, bbox_size, self.crop_size) + return cropped_image, tform + + def transform_points(self, points, tform, points_scale=None, normalize = True): + points_2d = points[:,:,:2] + + #'input points must use original range' + if points_scale: + assert points_scale[0]==points_scale[1] + points_2d = (points_2d*0.5 + 0.5)*points_scale[0] + + batch_size, n_points, _ = points.shape + trans_points_2d = torch.bmm( + torch.cat([points_2d, torch.ones([batch_size, n_points, 1], device=points.device, dtype=points.dtype)], dim=-1), + tform + ) + trans_points = torch.cat([trans_points_2d[:,:,:2], points[:,:,2:]], dim=-1) + if normalize: + trans_points[:,:,:2] = trans_points[:,:,:2]/self.crop_size*2 - 1 + return trans_points + +def transform_points(points, tform, points_scale=None, out_scale=None): + points_2d = points[:,:,:2] + + #'input points must use original range' + if points_scale: + assert points_scale[0]==points_scale[1] + points_2d = (points_2d*0.5 + 0.5)*points_scale[0] + # import ipdb; ipdb.set_trace() + + batch_size, n_points, _ = points.shape + trans_points_2d = torch.bmm( + torch.cat([points_2d, torch.ones([batch_size, n_points, 1], device=points.device, dtype=points.dtype)], dim=-1), + tform + ) + if out_scale: # h,w of output image size + trans_points_2d[:,:,0] = trans_points_2d[:,:,0]/out_scale[1]*2 - 1 + trans_points_2d[:,:,1] = trans_points_2d[:,:,1]/out_scale[0]*2 - 1 + trans_points = torch.cat([trans_points_2d[:,:,:2], points[:,:,2:]], dim=-1) + return trans_points \ No newline at end of file diff --git a/src/models/mesh/util.py b/src/models/mesh/util.py new file mode 100755 index 0000000..246997c --- /dev/null +++ b/src/models/mesh/util.py @@ -0,0 +1,719 @@ +# -*- coding: utf-8 -*- +# +# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is +# holder of all proprietary rights on this computer program. +# Using this computer program means that you agree to the terms +# in the LICENSE file included with this software distribution. +# Any use not explicitly granted by the LICENSE is prohibited. +# +# Copyright©2019 Max-Planck-Gesellschaft zur Förderung +# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute +# for Intelligent Systems. All rights reserved. +# +# For comments or questions, please email us at deca@tue.mpg.de +# For commercial licensing contact, please contact ps-license@tuebingen.mpg.de + +import numpy as np +import torch +import torch.nn.functional as F +import math +from collections import OrderedDict +import os +from scipy.ndimage import morphology +from skimage.io import imsave +import cv2 +import torchvision + +def upsample_mesh(vertices, normals, faces, displacement_map, texture_map, dense_template): + ''' Credit to Timo + upsampling coarse mesh (with displacment map) + vertices: vertices of coarse mesh, [nv, 3] + normals: vertex normals, [nv, 3] + faces: faces of coarse mesh, [nf, 3] + texture_map: texture map, [256, 256, 3] + displacement_map: displacment map, [256, 256] + dense_template: + Returns: + dense_vertices: upsampled vertices with details, [number of dense vertices, 3] + dense_colors: vertex color, [number of dense vertices, 3] + dense_faces: [number of dense faces, 3] + ''' + img_size = dense_template['img_size'] + dense_faces = dense_template['f'] + x_coords = dense_template['x_coords'] + y_coords = dense_template['y_coords'] + valid_pixel_ids = dense_template['valid_pixel_ids'] + valid_pixel_3d_faces = dense_template['valid_pixel_3d_faces'] + valid_pixel_b_coords = dense_template['valid_pixel_b_coords'] + + pixel_3d_points = vertices[valid_pixel_3d_faces[:, 0], :] * valid_pixel_b_coords[:, 0][:, np.newaxis] + \ + vertices[valid_pixel_3d_faces[:, 1], :] * valid_pixel_b_coords[:, 1][:, np.newaxis] + \ + vertices[valid_pixel_3d_faces[:, 2], :] * valid_pixel_b_coords[:, 2][:, np.newaxis] + vertex_normals = normals + pixel_3d_normals = vertex_normals[valid_pixel_3d_faces[:, 0], :] * valid_pixel_b_coords[:, 0][:, np.newaxis] + \ + vertex_normals[valid_pixel_3d_faces[:, 1], :] * valid_pixel_b_coords[:, 1][:, np.newaxis] + \ + vertex_normals[valid_pixel_3d_faces[:, 2], :] * valid_pixel_b_coords[:, 2][:, np.newaxis] + pixel_3d_normals = pixel_3d_normals / np.linalg.norm(pixel_3d_normals, axis=-1)[:, np.newaxis] + displacements = displacement_map[y_coords[valid_pixel_ids].astype(int), x_coords[valid_pixel_ids].astype(int)] + dense_colors = texture_map[y_coords[valid_pixel_ids].astype(int), x_coords[valid_pixel_ids].astype(int)] + offsets = np.einsum('i,ij->ij', displacements, pixel_3d_normals) + dense_vertices = pixel_3d_points + offsets + return dense_vertices, dense_colors, dense_faces + +# borrowed from https://github.com/YadiraF/PRNet/blob/master/utils/write.py +def write_obj(obj_name, + vertices, + faces, + colors=None, + texture=None, + uvcoords=None, + uvfaces=None, + inverse_face_order=False, + normal_map=None, + ): + ''' Save 3D face model with texture. + Ref: https://github.com/patrikhuber/eos/blob/bd00155ebae4b1a13b08bf5a991694d682abbada/include/eos/core/Mesh.hpp + Args: + obj_name: str + vertices: shape = (nver, 3) + colors: shape = (nver, 3) + faces: shape = (ntri, 3) + texture: shape = (uv_size, uv_size, 3) + uvcoords: shape = (nver, 2) max value<=1 + ''' + if os.path.splitext(obj_name)[-1] != 'obj': + obj_name = obj_name + '.obj' + mtl_name = obj_name.replace('.obj', '.mtl') + texture_name = obj_name.replace('.obj', '.png') + material_name = 'FaceTexture' + + faces = faces.copy() + # mesh lab start with 1, python/c++ start from 0 + faces += 1 + if inverse_face_order: + faces = faces[:, [2, 1, 0]] + if uvfaces is not None: + uvfaces = uvfaces[:, [2, 1, 0]] + + # write obj + with open(obj_name, 'w') as f: + # first line: write mtlib(material library) + # f.write('# %s\n' % os.path.basename(obj_name)) + # f.write('#\n') + # f.write('\n') + if texture is not None: + f.write('mtllib %s\n\n' % os.path.basename(mtl_name)) + + # write vertices + if colors is None: + for i in range(vertices.shape[0]): + f.write('v {} {} {}\n'.format(vertices[i, 0], vertices[i, 1], vertices[i, 2])) + else: + for i in range(vertices.shape[0]): + f.write('v {} {} {} {} {} {}\n'.format(vertices[i, 0], vertices[i, 1], vertices[i, 2], colors[i, 0], colors[i, 1], colors[i, 2])) + + # write uv coords + if texture is None: + for i in range(faces.shape[0]): + f.write('f {} {} {}\n'.format(faces[i, 2], faces[i, 1], faces[i, 0])) + else: + for i in range(uvcoords.shape[0]): + f.write('vt {} {}\n'.format(uvcoords[i,0], uvcoords[i,1])) + f.write('usemtl %s\n' % material_name) + # write f: ver ind/ uv ind + uvfaces = uvfaces + 1 + for i in range(faces.shape[0]): + f.write('f {}/{} {}/{} {}/{}\n'.format( + # faces[i, 2], uvfaces[i, 2], + # faces[i, 1], uvfaces[i, 1], + # faces[i, 0], uvfaces[i, 0] + faces[i, 0], uvfaces[i, 0], + faces[i, 1], uvfaces[i, 1], + faces[i, 2], uvfaces[i, 2] + ) + ) + # write mtl + with open(mtl_name, 'w') as f: + f.write('newmtl %s\n' % material_name) + s = 'map_Kd {}\n'.format(os.path.basename(texture_name)) # map to image + f.write(s) + + if normal_map is not None: + name, _ = os.path.splitext(obj_name) + normal_name = f'{name}_normals.png' + f.write(f'disp {normal_name}') + # out_normal_map = normal_map / (np.linalg.norm( + # normal_map, axis=-1, keepdims=True) + 1e-9) + # out_normal_map = (out_normal_map + 1) * 0.5 + + cv2.imwrite( + normal_name, + # (out_normal_map * 255).astype(np.uint8)[:, :, ::-1] + normal_map + ) + cv2.imwrite(texture_name, texture) + + +## load obj, similar to load_obj from pytorch3d +def load_obj(obj_filename): + """ Ref: https://github.com/facebookresearch/pytorch3d/blob/25c065e9dafa90163e7cec873dbb324a637c68b7/pytorch3d/io/obj_io.py + Load a mesh from a file-like object. + """ + with open(obj_filename, 'r') as f: + lines = [line.strip() for line in f] + + verts, uvcoords = [], [] + faces, uv_faces = [], [] + # startswith expects each line to be a string. If the file is read in as + # bytes then first decode to strings. + if lines and isinstance(lines[0], bytes): + lines = [el.decode("utf-8") for el in lines] + + for line in lines: + tokens = line.strip().split() + if line.startswith("v "): # Line is a vertex. + vert = [float(x) for x in tokens[1:4]] + if len(vert) != 3: + msg = "Vertex %s does not have 3 values. Line: %s" + raise ValueError(msg % (str(vert), str(line))) + verts.append(vert) + elif line.startswith("vt "): # Line is a texture. + tx = [float(x) for x in tokens[1:3]] + if len(tx) != 2: + raise ValueError( + "Texture %s does not have 2 values. Line: %s" % (str(tx), str(line)) + ) + uvcoords.append(tx) + elif line.startswith("f "): # Line is a face. + # Update face properties info. + face = tokens[1:] + face_list = [f.split("/") for f in face] + for vert_props in face_list: + # Vertex index. + faces.append(int(vert_props[0])) + if len(vert_props) > 1: + if vert_props[1] != "": + # Texture index is present e.g. f 4/1/1. + uv_faces.append(int(vert_props[1])) + + verts = torch.tensor(verts, dtype=torch.float32) + uvcoords = torch.tensor(uvcoords, dtype=torch.float32) + faces = torch.tensor(faces, dtype=torch.long); faces = faces.reshape(-1, 3) - 1 + uv_faces = torch.tensor(uv_faces, dtype=torch.long); uv_faces = uv_faces.reshape(-1, 3) - 1 + return ( + verts, + uvcoords, + faces, + uv_faces + ) + +# ---------------------------- process/generate vertices, normals, faces +def generate_triangles(h, w, margin_x=2, margin_y=5, mask = None): + # quad layout: + # 0 1 ... w-1 + # w w+1 + #. + # w*h + triangles = [] + for x in range(margin_x, w-1-margin_x): + for y in range(margin_y, h-1-margin_y): + triangle0 = [y*w + x, y*w + x + 1, (y+1)*w + x] + triangle1 = [y*w + x + 1, (y+1)*w + x + 1, (y+1)*w + x] + triangles.append(triangle0) + triangles.append(triangle1) + triangles = np.array(triangles) + triangles = triangles[:,[0,2,1]] + return triangles + +# borrowed from https://github.com/daniilidis-group/neural_renderer/blob/master/neural_renderer/vertices_to_faces.py +def face_vertices(vertices, faces): + """ + :param vertices: [batch size, number of vertices, 3] + :param faces: [batch size, number of faces, 3] + :return: [batch size, number of faces, 3, 3] + """ + assert (vertices.ndimension() == 3) + assert (faces.ndimension() == 3) + assert (vertices.shape[0] == faces.shape[0]) + assert (vertices.shape[2] == 3) + assert (faces.shape[2] == 3) + + bs, nv = vertices.shape[:2] + bs, nf = faces.shape[:2] + device = vertices.device + faces = faces + (torch.arange(bs, dtype=torch.int32).to(device) * nv)[:, None, None] + vertices = vertices.reshape((bs * nv, 3)) + # pytorch only supports long and byte tensors for indexing + return vertices[faces.long()] + +def vertex_normals(vertices, faces): + """ + :param vertices: [batch size, number of vertices, 3] + :param faces: [batch size, number of faces, 3] + :return: [batch size, number of vertices, 3] + """ + assert (vertices.ndimension() == 3) + assert (faces.ndimension() == 3) + assert (vertices.shape[0] == faces.shape[0]) + assert (vertices.shape[2] == 3) + assert (faces.shape[2] == 3) + bs, nv = vertices.shape[:2] + bs, nf = faces.shape[:2] + device = vertices.device + normals = torch.zeros(bs * nv, 3).to(device) + + faces = faces + (torch.arange(bs, dtype=torch.int32).to(device) * nv)[:, None, None] # expanded faces + vertices_faces = vertices.reshape((bs * nv, 3))[faces.long()] + + faces = faces.reshape(-1, 3) + vertices_faces = vertices_faces.reshape(-1, 3, 3) + + normals.index_add_(0, faces[:, 1].long(), + torch.cross(vertices_faces[:, 2] - vertices_faces[:, 1], vertices_faces[:, 0] - vertices_faces[:, 1])) + normals.index_add_(0, faces[:, 2].long(), + torch.cross(vertices_faces[:, 0] - vertices_faces[:, 2], vertices_faces[:, 1] - vertices_faces[:, 2])) + normals.index_add_(0, faces[:, 0].long(), + torch.cross(vertices_faces[:, 1] - vertices_faces[:, 0], vertices_faces[:, 2] - vertices_faces[:, 0])) + + normals = F.normalize(normals, eps=1e-6, dim=1) + normals = normals.reshape((bs, nv, 3)) + # pytorch only supports long and byte tensors for indexing + return normals + +def batch_orth_proj(X, camera): + ''' orthgraphic projection + X: 3d vertices, [bz, n_point, 3] + camera: scale and translation, [bz, 3], [scale, tx, ty] + ''' + camera = camera.clone().view(-1, 1, 3) + X_trans = X[:, :, :2] + camera[:, :, 1:] + X_trans = torch.cat([X_trans, X[:,:,2:]], 2) + shape = X_trans.shape + Xn = (camera[:, :, 0:1] * X_trans) + return Xn + +# -------------------------------------- image processing +# borrowed from: https://torchgeometry.readthedocs.io/en/latest/_modules/kornia/filters +def gaussian(window_size, sigma): + def gauss_fcn(x): + return -(x - window_size // 2)**2 / float(2 * sigma**2) + gauss = torch.stack( + [torch.exp(torch.tensor(gauss_fcn(x))) for x in range(window_size)]) + return gauss / gauss.sum() + +def get_gaussian_kernel(kernel_size: int, sigma: float): + r"""Function that returns Gaussian filter coefficients. + + Args: + kernel_size (int): filter size. It should be odd and positive. + sigma (float): gaussian standard deviation. + + Returns: + Tensor: 1D tensor with gaussian filter coefficients. + + Shape: + - Output: :math:`(\text{kernel_size})` + + Examples:: + + >>> kornia.image.get_gaussian_kernel(3, 2.5) + tensor([0.3243, 0.3513, 0.3243]) + + >>> kornia.image.get_gaussian_kernel(5, 1.5) + tensor([0.1201, 0.2339, 0.2921, 0.2339, 0.1201]) + """ + if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or \ + kernel_size <= 0: + raise TypeError("kernel_size must be an odd positive integer. " + "Got {}".format(kernel_size)) + window_1d = gaussian(kernel_size, sigma) + return window_1d + +def get_gaussian_kernel2d(kernel_size, sigma): + r"""Function that returns Gaussian filter matrix coefficients. + + Args: + kernel_size (Tuple[int, int]): filter sizes in the x and y direction. + Sizes should be odd and positive. + sigma (Tuple[int, int]): gaussian standard deviation in the x and y + direction. + + Returns: + Tensor: 2D tensor with gaussian filter matrix coefficients. + + Shape: + - Output: :math:`(\text{kernel_size}_x, \text{kernel_size}_y)` + + Examples:: + + >>> kornia.image.get_gaussian_kernel2d((3, 3), (1.5, 1.5)) + tensor([[0.0947, 0.1183, 0.0947], + [0.1183, 0.1478, 0.1183], + [0.0947, 0.1183, 0.0947]]) + + >>> kornia.image.get_gaussian_kernel2d((3, 5), (1.5, 1.5)) + tensor([[0.0370, 0.0720, 0.0899, 0.0720, 0.0370], + [0.0462, 0.0899, 0.1123, 0.0899, 0.0462], + [0.0370, 0.0720, 0.0899, 0.0720, 0.0370]]) + """ + if not isinstance(kernel_size, tuple) or len(kernel_size) != 2: + raise TypeError("kernel_size must be a tuple of length two. Got {}" + .format(kernel_size)) + if not isinstance(sigma, tuple) or len(sigma) != 2: + raise TypeError("sigma must be a tuple of length two. Got {}" + .format(sigma)) + ksize_x, ksize_y = kernel_size + sigma_x, sigma_y = sigma + kernel_x = get_gaussian_kernel(ksize_x, sigma_x) + kernel_y = get_gaussian_kernel(ksize_y, sigma_y) + kernel_2d = torch.matmul( + kernel_x.unsqueeze(-1), kernel_y.unsqueeze(-1).t()) + return kernel_2d + +def gaussian_blur(x, kernel_size=(3,3), sigma=(0.8,0.8)): + b, c, h, w = x.shape + kernel = get_gaussian_kernel2d(kernel_size, sigma).to(x.device).to(x.dtype) + kernel = kernel.repeat(c, 1, 1, 1) + padding = [(k - 1) // 2 for k in kernel_size] + return F.conv2d(x, kernel, padding=padding, stride=1, groups=c) + +def _compute_binary_kernel(window_size): + r"""Creates a binary kernel to extract the patches. If the window size + is HxW will create a (H*W)xHxW kernel. + """ + window_range = window_size[0] * window_size[1] + kernel: torch.Tensor = torch.zeros(window_range, window_range) + for i in range(window_range): + kernel[i, i] += 1.0 + return kernel.view(window_range, 1, window_size[0], window_size[1]) + +def median_blur(x, kernel_size=(3,3)): + b, c, h, w = x.shape + kernel = _compute_binary_kernel(kernel_size).to(x.device).to(x.dtype) + kernel = kernel.repeat(c, 1, 1, 1) + padding = [(k - 1) // 2 for k in kernel_size] + features = F.conv2d(x, kernel, padding=padding, stride=1, groups=c) + features = features.view(b,c,-1,h,w) + median = torch.median(features, dim=2)[0] + return median + +def get_laplacian_kernel2d(kernel_size: int): + r"""Function that returns Gaussian filter matrix coefficients. + + Args: + kernel_size (int): filter size should be odd. + + Returns: + Tensor: 2D tensor with laplacian filter matrix coefficients. + + Shape: + - Output: :math:`(\text{kernel_size}_x, \text{kernel_size}_y)` + + Examples:: + + >>> kornia.image.get_laplacian_kernel2d(3) + tensor([[ 1., 1., 1.], + [ 1., -8., 1.], + [ 1., 1., 1.]]) + + >>> kornia.image.get_laplacian_kernel2d(5) + tensor([[ 1., 1., 1., 1., 1.], + [ 1., 1., 1., 1., 1.], + [ 1., 1., -24., 1., 1.], + [ 1., 1., 1., 1., 1.], + [ 1., 1., 1., 1., 1.]]) + + """ + if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or \ + kernel_size <= 0: + raise TypeError("ksize must be an odd positive integer. Got {}" + .format(kernel_size)) + + kernel = torch.ones((kernel_size, kernel_size)) + mid = kernel_size // 2 + kernel[mid, mid] = 1 - kernel_size ** 2 + kernel_2d: torch.Tensor = kernel + return kernel_2d + +def laplacian(x): + # https://torchgeometry.readthedocs.io/en/latest/_modules/kornia/filters/laplacian.html + b, c, h, w = x.shape + kernel_size = 3 + kernel = get_laplacian_kernel2d(kernel_size).to(x.device).to(x.dtype) + kernel = kernel.repeat(c, 1, 1, 1) + padding = (kernel_size - 1) // 2 + return F.conv2d(x, kernel, padding=padding, stride=1, groups=c) + +def angle2matrix(angles): + ''' get rotation matrix from three rotation angles(degree). right-handed. + Args: + angles: [batch_size, 3] tensor containing X, Y, and Z angles. + x: pitch. positive for looking down. + y: yaw. positive for looking left. + z: roll. positive for tilting head right. + Returns: + R: [batch_size, 3, 3]. rotation matrices. + ''' + angles = angles*(np.pi)/180. + s = torch.sin(angles) + c = torch.cos(angles) + + cx, cy, cz = (c[:, 0], c[:, 1], c[:, 2]) + sx, sy, sz = (s[:, 0], s[:, 1], s[:, 2]) + + zeros = torch.zeros_like(s[:, 0]).to(angles.device) + ones = torch.ones_like(s[:, 0]).to(angles.device) + + # Rz.dot(Ry.dot(Rx)) + R_flattened = torch.stack( + [ + cz * cy, cz * sy * sx - sz * cx, cz * sy * cx + sz * sx, + sz * cy, sz * sy * sx + cz * cx, sz * sy * cx - cz * sx, + -sy, cy * sx, cy * cx, + ], + dim=0) #[batch_size, 9] + R = torch.reshape(R_flattened, (-1, 3, 3)) #[batch_size, 3, 3] + return R + +def binary_erosion(tensor, kernel_size=5): + # tensor: [bz, 1, h, w]. + device = tensor.device + mask = tensor.cpu().numpy() + structure=np.ones((kernel_size,kernel_size)) + new_mask = mask.copy() + for i in range(mask.shape[0]): + new_mask[i,0] = morphology.binary_erosion(mask[i,0], structure) + return torch.from_numpy(new_mask.astype(np.float32)).to(device) + +def flip_image(src_image, kps): + ''' + purpose: + flip a image given by src_image and the 2d keypoints + flip_mode: + 0: horizontal flip + >0: vertical flip + <0: horizontal & vertical flip + ''' + h, w = src_image.shape[0], src_image.shape[1] + src_image = cv2.flip(src_image, 1) + if kps is not None: + kps[:, 0] = w - 1 - kps[:, 0] + kp_map = [5, 4, 3, 2, 1, 0, 11, 10, 9, 8, 7, 6, 12, 13] + kps[:, :] = kps[kp_map] + + return src_image, kps + +# -------------------------------------- io +def copy_state_dict(cur_state_dict, pre_state_dict, prefix='', load_name=None): + def _get_params(key): + key = prefix + key + if key in pre_state_dict: + return pre_state_dict[key] + return None + for k in cur_state_dict.keys(): + if load_name is not None: + if load_name not in k: + continue + v = _get_params(k) + try: + if v is None: + # print('parameter {} not found'.format(k)) + continue + cur_state_dict[k].copy_(v) + except: + # print('copy param {} failed'.format(k)) + continue + +def check_mkdir(path): + if not os.path.exists(path): + print('creating %s' % path) + os.makedirs(path) + +def check_mkdirlist(pathlist): + for path in pathlist: + if not os.path.exists(path): + print('creating %s' % path) + os.makedirs(path) + +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 dict2obj(d): + # if isinstance(d, list): + # d = [dict2obj(x) for x in d] + if not isinstance(d, dict): + return d + class C(object): + pass + o = C() + for k in d: + o.__dict__[k] = dict2obj(d[k]) + return o + +class Struct(object): + def __init__(self, **kwargs): + for key, val in kwargs.items(): + setattr(self, key, val) + +# original saved file with DataParallel +def remove_module(state_dict): +# create new OrderedDict that does not contain `module.` + new_state_dict = OrderedDict() + for k, v in state_dict.items(): + name = k[7:] # remove `module.` + new_state_dict[name] = v + return new_state_dict + +def dict_tensor2npy(tensor_dict): + npy_dict = {} + for key in tensor_dict: + npy_dict[key] = tensor_dict[key][0].cpu().numpy() + return npy_dict + +# ---------------------------------- visualization +# end_list = np.array([17, 22, 27, 42, 48, 31, 36, 68], dtype = np.int32) - 1 +end_list = np.array([17, 22, 27, 31, 36], dtype = np.int32) - 1 + +def plot_kpts(image, kpts, color = 'r'): + ''' Draw 68 key points + Args: + image: the input image + kpt: (68, 3). + ''' + if color == 'r': + c = (255, 0, 0) + elif color == 'g': + c = (0, 255, 0) + elif color == 'b': + c = (255, 0, 0) + image = image.copy() + kpts = kpts.copy() + + # radius = max(int(min(image.shape[0], image.shape[1])/200), 1) + radius = 1 + + for i in range(kpts.shape[0]): + st = kpts[i, :2] + if kpts.shape[1]==4: + if kpts[i, 3] > 0.5: + c = (0, 255, 0) + else: + c = (0, 0, 255) + + # draw cicle + image = cv2.circle(image,(int(st[0]), int(st[1])), radius, c, -1) + + # draw line + if i not in end_list: + ed = kpts[i + 1, :2] if i != 67 else kpts[60, :2] + ed = kpts[36, :2] if i == 41 else ed + ed = kpts[42, :2] if i == 47 else ed + image = cv2.line(image, (int(st[0]), int(st[1])), (int(ed[0]), int(ed[1])), (255, 255, 255), radius) + + return image + +def plot_verts(image, kpts, color = 'r'): + ''' Draw 68 key points + Args: + image: the input image + kpt: (68, 3). + ''' + c = (0, 0, 0) + c = (255, 0, 0) if color == 'r' else c + c = (0, 255, 0) if color == 'g' else c + c = (0, 0, 255) if color == 'b' else c + c = (0, 255, 255) if color == 'y' else c + + image = image.copy() + + for i in range(kpts.shape[0]): + st = kpts[i, :2] + image = cv2.circle(image,(int(st[0]), int(st[1])), 1, c, -1) + + return image + +def tensor_vis_landmarks(images, landmarks, gt_landmarks=None, color = 'g', isScale=True, gt_color = 'r'): + # visualize landmarks + vis_landmarks = [] + images = images.cpu().numpy() + predicted_landmarks = landmarks.detach().cpu().numpy() + + if gt_landmarks is not None: + gt_landmarks_np = gt_landmarks.detach().cpu().numpy() + + for i in range(images.shape[0]): + image = images[i] + image = image.transpose(1,2,0)[:,:,[2,1,0]].copy(); image = (image*255) + + # if landmarks is scale + if isScale: + predicted_landmark = predicted_landmarks[i] + predicted_landmark[...,0] = predicted_landmark[...,0]*image.shape[1]/2 + image.shape[1]/2 + predicted_landmark[...,1] = predicted_landmark[...,1]*image.shape[0]/2 + image.shape[0]/2 + else: + predicted_landmark = predicted_landmarks[i] + + # + if predicted_landmark.shape[0] == 68: + image_landmarks = plot_kpts(image, predicted_landmark, color) + if gt_landmarks is not None: + image_landmarks = plot_verts(image_landmarks, gt_landmarks_np[i]*image.shape[0]/2 + image.shape[0]/2, gt_color) + else: + image_landmarks = plot_verts(image, predicted_landmark, color) + if gt_landmarks is not None: + image_landmarks = plot_verts(image_landmarks, gt_landmarks_np[i]*image.shape[0]/2 + image.shape[0]/2, gt_color) + + vis_landmarks.append(image_landmarks) + + vis_landmarks = np.stack(vis_landmarks) + vis_landmarks = torch.from_numpy(vis_landmarks[:,:,:,[2,1,0]].transpose(0,3,1,2))/255.#, dtype=torch.float32) + return vis_landmarks + + +############### for training +def load_local_mask(image_size=256, mode='bbx'): + if mode == 'bbx': + # UV space face attributes bbx in size 2048 (l r t b) + # face = np.array([512, 1536, 512, 1536]) # + face = np.array([400, 1648, 400, 1648]) + # if image_size == 512: + # face = np.array([400, 400+512*2, 400, 400+512*2]) + # face = np.array([512, 512+512*2, 512, 512+512*2]) + + forehead = np.array([550, 1498, 430, 700+50]) + eye_nose = np.array([490, 1558, 700, 1050+50]) + mouth = np.array([574, 1474, 1050, 1550]) + ratio = image_size / 2048. + face = (face * ratio).astype(np.int) + forehead = (forehead * ratio).astype(np.int) + eye_nose = (eye_nose * ratio).astype(np.int) + mouth = (mouth * ratio).astype(np.int) + regional_mask = np.array([face, forehead, eye_nose, mouth]) + + return regional_mask + +def visualize_grid(visdict, savepath=None, size=224, dim=1, return_gird=True): + ''' + image range should be [0,1] + dim: 2 for horizontal. 1 for vertical + ''' + assert dim == 1 or dim==2 + grids = {} + for key in visdict: + _,_,h,w = visdict[key].shape + if dim == 2: + new_h = size; new_w = int(w*size/h) + elif dim == 1: + new_h = int(h*size/w); new_w = size + grids[key] = torchvision.utils.make_grid(F.interpolate(visdict[key], [new_h, new_w]).detach().cpu()) + grid = torch.cat(list(grids.values()), dim) + grid_image = (grid.numpy().transpose(1,2,0).copy()*255)[:,:,[2,1,0]] + grid_image = np.minimum(np.maximum(grid_image, 0), 255).astype(np.uint8) + if savepath: + cv2.imwrite(savepath, grid_image) + if return_gird: + return grid_image \ No newline at end of file diff --git a/src/models/mnist_module.py b/src/models/mnist_module.py index 1c85911..363c2c9 100644 --- a/src/models/mnist_module.py +++ b/src/models/mnist_module.py @@ -1,5 +1,5 @@ from typing import Any, List - +from omegaconf import DictConfig import torch from pytorch_lightning import LightningModule from torchmetrics import MaxMetric @@ -25,12 +25,16 @@ class MNISTLitModule(LightningModule): def __init__( self, + opt: DictConfig, net: torch.nn.Module, lr: float = 0.001, weight_decay: float = 0.0005, ): super().__init__() + + self.opt = opt + print(f"\n\n >>>>>> {opt}") # 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) @@ -120,3 +124,4 @@ class MNISTLitModule(LightningModule): return torch.optim.Adam( params=self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.weight_decay ) + diff --git a/src/models/module_audio2mesh.py b/src/models/module_audio2mesh.py new file mode 100644 index 0000000..3fdabd1 --- /dev/null +++ b/src/models/module_audio2mesh.py @@ -0,0 +1,601 @@ +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 Audio2MeshModel(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.cond = cond + self.B, self.nsteps, self.nwind, self.dim_speech = cond.size() + data = data[:, 7:7+self.nsteps, :] + self.vert, self.ldmk2d, self.ldmk3d = self.get_vertices(data) + + # cut audio clips + idx_beg = int(7 * self.opt.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 = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False) + debug(f"[set_input] ldmk2d = {self.ldmk2d.shape}, dtype={self.ldmk2d.dtype}, device={self.ldmk2d.device}", verbose=False) + debug(f"[set_input] ldmk3d = {self.ldmk3d.shape}, dtype={self.ldmk3d.dtype}, device={self.ldmk3d.device}", verbose=False) + + return self.cond, self.vert, 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) + batch_pdt += self.temp_verts + + 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_geo, batch_tgt_geo): + """ Computes the loss function. + pramas: + batch_tgt_geo, (nbatch, seqlen, num_vertices, 3) + batch_pdt_geo, (nbatch, seqlen, num_vertices, 3) + """ + loss = 0 + loss_dict = {} + + # synthesis geo rec + loss = 0 + loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) + loss_dict["rec_geo"] = loss_rec_geo.mean().detach() + + loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight) + # loss_dict["rec_geo_w"] = loss_rec_geo2.mean().detach() + # loss += loss_rec_geo.mean() * self.opt_LOSS.lambda_rec_geo + loss += loss_rec_geo2.mean() * self.opt_LOSS.lambda_rec_geo + + # synthesis geo volocity + diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :] + diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :] + + loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) + loss_dict["vel_geo"] = loss_vel_geo.mean().detach() + + loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight) + # loss_dict["vel_geo_w"] = loss_vel_geo2.mean().detach() + # loss += loss_vel_geo.mean() * self.opt_LOSS.lambda_vel_geo + + if self.opt_LOSS.lambda_vel_geo > 0: + loss += loss_vel_geo2.mean() * self.opt_LOSS.lambda_vel_geo + + # landmarks loss + ldmk3d_pdt = self.netF.seletec_3d68(batch_pdt_geo.reshape(-1, self.opt.num_vertices, 3)) # (B*N, 68, 3) + ldmk3d_tgt = self.netF.seletec_3d68(batch_tgt_geo.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() + diff --git a/src/models/module_audio2mesh_copy.py b/src/models/module_audio2mesh_copy.py new file mode 100644 index 0000000..1ca6a6e --- /dev/null +++ b/src/models/module_audio2mesh_copy.py @@ -0,0 +1,573 @@ +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 +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 Audio2MeshModel(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 = MaxMetric() + + + def _load_netF(self, opt_netF): + from src.mesh.FLAME import FLAME + + logging.info("_load_netF, FLAME ...") + return FLAME(opt_netF) + + 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) + + return SRenderY(opt_netR.image_size, + obj_filename=opt_netR.topology_path, + uv_size=opt_netR.uv_size, + rasterizer_type=opt_netR.rasterizer_type + ) + + 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) + + return processor, extractor + + + 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 + ) + + # 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.cond = cond + self.B, self.nsteps, self.nwind, self.dim_speech = cond.size() + data = data[:, 7:7+self.nsteps, :] + self.vert, self.ldmk2d, self.ldmk3d = self.get_vertices(data) + + # cut audio clips + idx_beg = int(7 * self.opt.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 = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False) + debug(f"[set_input] ldmk2d = {self.ldmk2d.shape}, dtype={self.ldmk2d.dtype}, device={self.ldmk2d.device}", verbose=False) + debug(f"[set_input] ldmk3d = {self.ldmk3d.shape}, dtype={self.ldmk3d.dtype}, device={self.ldmk3d.device}", verbose=False) + + return self.cond, self.vert, 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) + batch_pdt += self.temp_verts + + 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_geo, batch_tgt_geo): + """ Computes the loss function. + pramas: + batch_tgt_geo, (nbatch, seqlen, num_vertices, 3) + batch_pdt_geo, (nbatch, seqlen, num_vertices, 3) + """ + loss = 0 + loss_dict = {} + + # synthesis geo rec + loss = 0 + loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) + loss_dict["rec_geo"] = loss_rec_geo.mean().detach() + + loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight) + # loss_dict["rec_geo_w"] = loss_rec_geo2.mean().detach() + # loss += loss_rec_geo.mean() * self.opt_LOSS.lambda_rec_geo + loss += loss_rec_geo2.mean() * self.opt_LOSS.lambda_rec_geo + + # synthesis geo volocity + diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :] + diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :] + + loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) + loss_dict["vel_geo"] = loss_vel_geo.mean().detach() + + loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight) + # loss_dict["vel_geo_w"] = loss_vel_geo2.mean().detach() + # loss += loss_vel_geo.mean() * self.opt_LOSS.lambda_vel_geo + + if self.opt_LOSS.lambda_vel_geo > 0: + loss += loss_vel_geo2.mean() * self.opt_LOSS.lambda_vel_geo + + # landmarks loss + ldmk3d_pdt = self.netF.seletec_3d68(batch_pdt_geo.reshape(-1, self.opt.num_vertices, 3)) # (B*N, 68, 3) + ldmk3d_tgt = self.netF.seletec_3d68(batch_tgt_geo.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() + diff --git a/src/training_pipeline.py b/src/training_pipeline.py index 46e82ee..f3b4c51 100644 --- a/src/training_pipeline.py +++ b/src/training_pipeline.py @@ -1,5 +1,6 @@ import os from typing import List, Optional +from pytorch_lightning.plugins import DDPPlugin import hydra from omegaconf import DictConfig @@ -40,12 +41,13 @@ def train(config: DictConfig) -> Optional[float]: ) # Init lightning datamodule - log.info(f"Instantiating datamodule <{config.datamodule._target_}>") - datamodule: LightningDataModule = hydra.utils.instantiate(config.datamodule) + log.info(f"Instantiating datamodule <{config.dataset._target_}>") + datamodule = hydra.utils.instantiate(config.dataset) # Init lightning model log.info(f"Instantiating model <{config.model._target_}>") - model: LightningModule = hydra.utils.instantiate(config.model) + # model: LightningModule = hydra.utils.instantiate(config.model, opt=config) + model = hydra.utils.instantiate(config.model) # Init lightning callbacks callbacks: List[Callback] = [] @@ -66,7 +68,7 @@ def train(config: DictConfig) -> Optional[float]: # Init lightning trainer log.info(f"Instantiating trainer <{config.trainer._target_}>") trainer: Trainer = hydra.utils.instantiate( - config.trainer, callbacks=callbacks, logger=logger, _convert_="partial" + config.trainer, callbacks=callbacks, logger=logger, _convert_="partial", ) # Send some parameters from config to all lightning loggers diff --git a/src/utils/__init__.py b/src/utils/__init__.py index baf94b8..642aa40 100644 --- a/src/utils/__init__.py +++ b/src/utils/__init__.py @@ -130,7 +130,7 @@ def log_hyperparameters( p.numel() for p in model.parameters() if not p.requires_grad ) - hparams["datamodule"] = config["datamodule"] + hparams["dataset"] = config["dataset"] hparams["trainer"] = config["trainer"] if "seed" in config: diff --git a/src/utils/animation.py b/src/utils/animation.py new file mode 100644 index 0000000..07217d4 --- /dev/null +++ b/src/utils/animation.py @@ -0,0 +1,342 @@ +import moviepy.editor as mpy +import numpy as np +import os +import cv2 + +from .landmark import landmark_to_images + +import tempfile +from scipy.io import wavfile + + +def save_animation(data_motion, path_save, suffix, w=128*5, h=72*5, dpi=80): + """ convert data_motion to .mp4 animation + data_motion, shape [B, N, 136, ...] + """ + # no need invert + # anim_clips = inv_standardize(data_motion[:self.nseq_test, :, :], self.motion_scaler) + fps = 30 + B, *_ = data_motion.shape + + for i in range(B): + idata_pt = data_motion[i, :, :].reshape(-1, 68, 2) + images_pt = landmark_to_images(idata_pt, w=w, h=h, dpi=dpi, norm=True, prex="PT") + + duration = idata_pt.shape[0] / fps + # animation = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5) - 1,...], duration= duration ) + animation = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5),...], duration= duration ) + + ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4") + animation.write_videofile(str(ipath_save), fps=fps, logger=None) + + +def save_animation_ws_audio(data_motion, path_save, path_audio=None, start_time=None, end_time=None, fps=30, w=256, h=256, dpi=150): + """ convert data_motion to .mp4 animation + data_motion, shape [nsteps, 136] + """ + + # fps = 30 + nsteps = data_motion.shape[0] + + data_motion = data_motion.copy().reshape(nsteps, 68, 2) # nsteps x 68 x 2 + image = landmark_to_images(data_motion, w=w, h=h, dpi=dpi, norm=True, prex="PT") # (nsteps, H, W, 3) + + duration = nsteps / fps + animation = mpy.VideoClip(lambda t: image[int(fps * t + 0.5),...], duration= duration ) + duration = animation.duration + + if path_audio is not None: + audioclip = mpy.AudioFileClip(str(path_audio)) + + # cut-off + if (start_time is not None) and (end_time is not None): + audioclip = audioclip.subclip(start_time, end_time) + + # alignment to video + audioclip = audioclip.set_duration(duration) + + # add audio to animation + animation = animation.set_audio(audioclip) + animation = animation.set_duration(duration) + # save + animation.write_videofile(str(path_save), fps=fps, logger=None) + + +def save_animation_grid(data_motion, path_save, path_audio=None, start_time=None, end_time=None, ncol=3, w=128*5, h=72*5, dpi=80): + """ convert data_motion to .mp4 animation + data_motion, shape [N, nsteps, 136] + """ + # no need invert + # anim_clips = inv_standardize(data_motion[:self.nseq_test, :, :], self.motion_scaler) + fps = 30 + N, nsteps, _ = data_motion.shape + + total_image = [] + for i in range(N): + idata_pt = data_motion[i, :, :].reshape(-1, 68, 2) # nsteps x 68 x 2 + prex = "ground-truth" if i == 0 else f"prediction-{i-0:02d}" + image = landmark_to_images(idata_pt, w=w, h=h, dpi=dpi, norm=True, prex=prex) # (nsteps, H, W, 3) + total_image.append(image) + print(f"images shape = {image.shape}") + + + total_image = np.concatenate(total_image, axis=0) # N x nsteps x H x W x 3 + total_image = total_image.reshape(N//ncol, ncol, nsteps, h, w, 3) + + total_image = total_image.transpose((2, 0, 3, 1, 4, 5)) # nsteps x nrow x H x ncol x W x 3 + total_image = total_image.reshape(nsteps, -1, ncol*w, 3) # nsteps x nrow*H x ncol*W x 3 + print(f"total images shape = {total_image.shape}") + + duration = nsteps / fps + animation = mpy.VideoClip(lambda t: total_image[int(fps * t + 0.5),...], duration= duration ) + # animation = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5) ,...], duration= duration ) + duration = animation.duration + + if path_audio is not None: + audioclip = mpy.AudioFileClip(str(path_audio)) + + # cut-off + if (start_time is not None) and (end_time is not None): + audioclip = audioclip.cutout(start_time, end_time) + + # alignment to video + audioclip = audioclip.set_duration(duration) + + # add audio to animation + animation = animation.set_audio(audioclip) + animation = animation.set_duration(duration) + + # save + animation.write_videofile(str(path_save), fps=fps, logger=None) + + +def save_animation2(images, path_save): + fps = 30 + duration = len(images) / fps + animation = mpy.VideoClip(lambda t: images[int(fps * t + 0.5) - 1], duration= duration ) + animation.write_videofile(str(path_save), fps=fps, logger=None) + + +def save_animation_with_gts(images_list, path_save): + """ convert images_pt to .mp4 animation + images_pt, shape len=N list [224, 224, 3] + images_gt, shape len=N list [224, 224, 3] + """ + # print(f"images_pt shape = {len(images_list[0])}, shape[0]={images_pt[0].shape}") + + fps = 30 + N = len(images_list[0]) + duration = N / fps + print(f"fps = {fps}, N ={N}, duration={duration}") + + # assert len(images_pt) == len(images_gt), f"pt and gt imamge size not the same ({len(images_pt)}, {len(images_pt)})" + animations = [] + for images in images_list: + animations.append(mpy.VideoClip(lambda t: images[int(fps * t + 0.5) -1], duration= duration)) + + # mixture & save + animation = mpy.clips_array([animations]) + animation.write_videofile(str(path_save), fps=fps, logger=None) + + # close + animation.close() + + +# def write_videos(images, raw_speech, path_save, fps=50): + +def write_video(list_images, raw_speech, path_video, fps=50, sr=16000): + """ convert images_pt to .mp4 animation + list_images, shape len=N list [512, 512, 3], or [1080, 1920, 3] + raw_speech, shape = (nsegmet, ) + """ + + num_frame = len(list_images) + H, W = list_images[0].shape[:2] + + file_audio = tempfile.NamedTemporaryFile(suffix='.wav') + file_video = tempfile.NamedTemporaryFile(suffix='.mp4') + + # write audio + wavfile.write(file_audio.name, rate=sr, data=raw_speech) + + # write video + if int(cv2.__version__[0]) < 3: + writer = cv2.VideoWriter(file_video.name, cv2.cv.CV_FOURCC(*'mp4v'), fps, (W, H), True) + else: + writer = cv2.VideoWriter(file_video.name, cv2.VideoWriter_fourcc(*'mp4v'), fps, (W, H), True) + + for i in range(num_frame): + writer.write(list_images[i]) + + # close + writer.release() + cv2.destroyAllWindows + + # concate to video + cmd = f"ffmpeg -y -i {file_video.name} -i {file_audio.name} -map 0:v -vcodec libx264 -map 1:a -c:v copy -shortest -loglevel quiet {str(path_video)}" + os.system(cmd) + + # close tmp file + file_audio.close() + file_video.close() + + + +def write_video_with_gt(images_pt, images_gt, raw_speech, path_video, fps=50, sr=16000): + """ convert images_pt to .mp4 animation + images_pt, shape len= N list [H, W, 3], like [224, 224, 3], [512, 512, 3], or [1080, 1920, 3] + images_gt, shape len= N list [H, W, 3], like [224, 224, 3], [512, 512, 3], or [1080, 1920, 3] + raw_speech, shape = (nsegmet, ) + """ + + num_frame = len(images_pt) + H, W = images_pt[0].shape[:2] + + file_audio = tempfile.NamedTemporaryFile(suffix='.wav') + file_video = tempfile.NamedTemporaryFile(suffix='.mp4') + + # write audio + wavfile.write(file_audio.name, rate=sr, data=raw_speech) + + # write video + if int(cv2.__version__[0]) < 3: + writer = cv2.VideoWriter(file_video.name, cv2.cv.CV_FOURCC(*'mp4v'), fps, (2*W, H), True) + else: + writer = cv2.VideoWriter(file_video.name, cv2.VideoWriter_fourcc(*'mp4v'), fps, (2*W, H), True) + + for i in range(num_frame): + concate_image = np.concatenate((images_pt[i], images_gt[i]), axis=1) # (H, 2*W, 3) + writer.write(concate_image) + + # close + writer.release() + cv2.destroyAllWindows + + # concate to video + cmd = f"ffmpeg -y -i {file_video.name} -i {file_audio.name} -map 0:v -vcodec libx264 -map 1:a -c:v copy -shortest -loglevel quiet {str(path_video)}" + os.system(cmd) + + # close tmp file + file_audio.close() + file_video.close() + + +def save_images_with_audio(images, path_audio, path_save, fps=50): + """ convert images_pt to .mp4 animation + images_pt, shape len=N list [224, 224, 3] + images_gt, shape len=N list [224, 224, 3] + """ + + N = len(images) + duration = N / fps + + audioclip = mpy.AudioFileClip(str(path_audio)) + print(f"\naudio clip duration = {audioclip.duration}, N={N}, fps={fps}, duration_N/fps={duration}") + + if audioclip.duration + 0.0001 < duration: + print("\n\n\n ERROR: ") + # assert audioclip.duration + 0.0001 < duration, + + audioclip = audioclip.set_duration(duration) + + + # add video + animation = mpy.VideoClip(lambda t: images[int(fps * t + 0.5) -1], duration= duration) + animation = animation.set_audio(audioclip) # add audio to animation + + # save + animation.write_videofile(str(path_save), fps=fps) + print(f"animation duration={animation.duration}, > save to = {path_save}") + + # close + audioclip.close() + animation.close() + + # add + path_save2 = str(path_save).replace(".mp4", "2.mp4") + cmd = f"ffmpeg -y -i {str(path_save)} -i {str(path_audio)} -map 0:v -vcodec libx264 -map 1:a -c:v copy -shortest {str(path_save2)}" + os.system(cmd) + + # del + cmd = f"rm {str(path_save)}" + os.system(cmd) + + +def save_animation_with_gt2(images_pt, images_gt, path_save, fps=None, path_audio=None, start_time=None, end_time=None): + """ convert images_pt to .mp4 animation + images_pt, shape len= N list [224, 224, 3] + images_gt, shape len= N list [224, 224, 3] + """ + # print(f"images_pt shape = {len(images_pt)}, shape[0]={images_pt[0].shape}") + + fps = fps if fps else 50 + + N = len(images_pt) + duration = N / fps + # print(f"fps = {fps}, N ={N}, duration={duration}") + + # assert len(images_pt) == len(images_gt), f"pt and gt imamge size not the same ({len(images_pt)}, {len(images_pt)})" + animation_pt = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5) -1], duration= duration) + animation_gt = mpy.VideoClip(lambda t: images_gt[int(fps * t + 0.5) -1], duration= duration) + + # mixture & save + animation = mpy.clips_array([[animation_pt, animation_gt]]) + + + if path_audio is not None: + audioclip = mpy.AudioFileClip(str(path_audio)) + + # cut-off + if (start_time is not None) and (end_time is not None): + print(f"subclip clips {start_time}:{end_time}") + audioclip = audioclip.subclip(start_time, end_time) + + # alignment to video + audioclip = audioclip.set_duration(duration) + + # add audio to animation + animation = animation.set_audio(audioclip) + animation = animation.set_duration(duration) + + animation.write_videofile(str(path_save), fps=fps) + + # close + animation_pt.close() + animation_gt.close() + animation.close() + + +def save_animation_with_gt(data_motion, data_motion_gt, path_save, suffix, w=128*5, h=72*5, dpi=80, maxsave=3, fps=30): + """ convert data_motion to .mp4 animation + data_motion, shape [B, N, 68, 2] + data_motion_gt, shape [B, N, 68, 2] + """ + + B, *_ = data_motion.shape + B = min(B, maxsave) + + for i in range(B): + idata_pt = data_motion[i].reshape(-1, 68, 2) + idata_gt = data_motion_gt[i].reshape(-1, 68, 2) + + images_pt = landmark_to_images(idata_pt, w=w, h=h, dpi=dpi, norm=True, prex="PT") + images_gt = landmark_to_images(idata_gt, w=w, h=h, dpi=dpi, norm=True, prex="GT") + + duration = idata_pt.shape[0] / fps + # animation = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5) - 1,...], duration= duration ) + animation_pt = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5),...], duration= duration) + animation_gt = mpy.VideoClip(lambda t: images_gt[int(fps * t + 0.5),...], duration= duration) + + # mixture + animation = mpy.clips_array([[animation_pt, animation_gt]]) + + + ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4") + animation.write_videofile(str(ipath_save), fps=fps, logger=None) + + # close + animation_pt.close() + animation_gt.close() + animation.close() + + diff --git a/src/utils/debug.py b/src/utils/debug.py new file mode 100644 index 0000000..9eb0164 --- /dev/null +++ b/src/utils/debug.py @@ -0,0 +1,7 @@ + +FLAG_DEBUG = False + +def debug(msg="", verbose=False): + if FLAG_DEBUG or verbose: + print(msg) + diff --git a/src/utils/landmark.py b/src/utils/landmark.py new file mode 100644 index 0000000..27db615 --- /dev/null +++ b/src/utils/landmark.py @@ -0,0 +1,252 @@ +import cv2 +import torch +import numpy as np +from matplotlib import pyplot as plt +plt.rcParams['axes.facecolor'] = 'black' + +def landmark_normalize(ldmk): + # ldmk shape = (68, 2) + + pos_mean = np.mean(ldmk, axis=0) # (2, ) + pos_max = np.max(ldmk, axis=0) # (2, ) + pos_min = np.min(ldmk, axis=0) # (2, ) + + side = int(1.5 * np.max(pos_max - pos_min)) # (1, ) + # print(f"landmarks = {ldmk[::10, :]}, \n mean={pos_mean}, max={pos_max}, min={pos_min}, side={side}") + + tran = pos_mean - 0.5 * side # (2, ) + ldmk_tran = ldmk - tran[np.newaxis, :] # (68, 2) + ldmk_norm = ldmk_tran / side # (68, 2) + # print(f"ldmk_tran = {ldmk_tran[::10, :]}, \n ldmk_tran = {ldmk_norm[::10, :]}") + + return ldmk_norm, pos_mean, side + + +def landmark_normalize_by_param(ldmk, params): + # ldmk shape = (B, 68, 2) + # params shape = (B, 3) + + pos_mean = params[:, 0:2 ] # (B, 2) + pos_mean = pos_mean[:, np.newaxis, :] # (B, 1, 2) + side = params[:, 2:] # (B, 2) + side = side[:, np.newaxis, :] # (B, 1, 2) + + tran = pos_mean - 0.5 * side # (B, 1, 2) + ldmk_norm = (ldmk - tran) / side # (B, 68, 2) + + return ldmk_norm + +def landmark_to_images(ldmks, w=256, h=256, dpi=100, norm=True, prex=""): + # landmarks shape = (nbatch, 68, 2) + nframe = ldmks.shape[0] + + v_images = [] + for i in range(nframe): + ildmk = ldmks[i, :, :] + if prex is not None: + text = f"{prex}-frame-{i:04d}" + else: + text = None + + v_images.append(landmark_to_image(ildmk, w, h, dpi, norm, text)) + + return np.asarray(v_images) + + +def landmark_to_image(ildmk, w=256, h=256, dpi=100, norm=True, text=None): + # landmarks shape = (68, 2) + + if norm: + ildmk[:, 0] = w - ildmk[:, 0] * w + ildmk[:, 1] = h - ildmk[:, 1] * h + + else: + # ildmk[:, 0] = w - ildmk[:, 0] + ildmk[:, 1] = h - ildmk[:, 1] + + if isinstance(ildmk, torch.Tensor): + ildmk = ildmk.cpu().numpy() + + # plot + fig = plt.figure(figsize=(w/dpi, h/dpi), dpi=dpi) + fig.patch.set_facecolor('w') + + ax = fig.add_subplot(1,1,1) + # ax.imshow(np.zeros(shape=(w, h))) + + ax.set_facecolor('m') + # plt.subplots_adjust(left=0, right=1, top=1, bottom=0) + # ax.scatter(ildmk[:, 0], ildmk[:, 1], marker='o', s=5, color="#808080",alpha=1) + ax.scatter(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='o', s=3, color="#008B8B",alpha=1) + ax.scatter(ildmk[17:22,0], ildmk[17:22,1], marker='o', s=3, color="#F4A460",alpha=1) + ax.scatter(ildmk[22:27,0], ildmk[22:27,1], marker='o', s=3, color="#F4A460",alpha=1) + ax.scatter(ildmk[27:36,0], ildmk[27:36,1], marker='o', s=3, color="blue",alpha=1) + ax.scatter(ildmk[36:48,0], ildmk[36:48,1], marker='o', s=3, color="#DC143C",alpha=1) + ax.scatter(ildmk[48:60,0], ildmk[48:60,1], marker='o', s=3, color="#DC143C",alpha=1) + ax.scatter(ildmk[60:68,0], ildmk[60:68,1], marker='o', s=3, color="#FF1493",alpha=1) + + #chin + ax.plot(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='', markersize=1, linestyle='-', color='#008B8B', lw=2, alpha=1) + + #left and right eyebrow + ax.plot(ildmk[17:22,0], ildmk[17:22,1], marker='', markersize=1, linestyle='-', color='#F4A460', lw=2, alpha=1) + ax.plot(ildmk[22:27,0], ildmk[22:27,1], marker='', markersize=1, linestyle='-', color='#F4A460', lw=2, alpha=1) + + #nose + ax.plot(ildmk[27:31,0], ildmk[27:31,1], marker='', markersize=1, linestyle='-', color='blue', lw=2, alpha=1) + ax.plot(ildmk[31:36,0], ildmk[31:36,1], marker='', markersize=1, linestyle='-', color='blue', lw=2, alpha=1) + + #left and right eye + ax.plot(ildmk[36:42,0], ildmk[36:42,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) + ax.plot(ildmk[42:48,0], ildmk[42:48,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) + + ax.plot(ildmk[[41,36],0], ildmk[[41,36],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) + ax.plot(ildmk[[47,42],0], ildmk[[47,42],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) + + #outer and inner lip + ax.plot(ildmk[48:60,0], ildmk[48:60,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) + ax.plot(ildmk[60:68,0], ildmk[60:68,1], marker='', markersize=1, linestyle='-', color='#FF1493', lw=2, alpha=1) + + ax.plot(ildmk[[59,48],0], ildmk[[59,48],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) + ax.plot(ildmk[[67,60],0], ildmk[[67,60],1], marker='', markersize=1, linestyle='-', color='#FF1493', lw=2, alpha=1) + + ax.set_xlim(0, w) + ax.set_ylim(0, h) + ax.axis('off') + + if text is not None: + ax.text(2, 2, text) + + fig.canvas.draw() + w, h = fig.canvas.get_width_height() + + buffer = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) + buffer = buffer.reshape((h, w, 3)) + image = np.asarray(buffer) + # print(f"w,h={w},{h}, buffer shape = {buffer.shape}, dtype = {buffer.dtype}, class = {(buffer)}") + + plt.close(fig) + + return image + +# def landmark_to_image(ildmk, w=256, h=256, dpi=100, norm=True, text=None): +# # landmarks shape = (68, 2) + +# if norm: +# ildmk = w - ildmk * w +# else: +# ildmk[:, 1] = h - ildmk[:, 1] + +# if isinstance(ildmk, torch.Tensor): +# ildmk = ildmk.cpu().numpy() + +# # plot +# fig = plt.figure(figsize=(w/dpi, h/dpi), dpi=dpi) +# fig.patch.set_facecolor('w') + +# ax = fig.add_subplot(1,1,1) +# # ax.imshow(np.zeros(shape=(w, h))) + +# ax.set_facecolor('m') +# # plt.subplots_adjust(left=0, right=1, top=1, bottom=0) +# # ax.scatter(ildmk[:, 0], ildmk[:, 1], marker='o', s=5, color="#808080",alpha=1) +# ax.scatter(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='o', s=3, color="#008B8B",alpha=1) +# ax.scatter(ildmk[17:22,0], ildmk[17:22,1], marker='o', s=3, color="#F4A460",alpha=1) +# ax.scatter(ildmk[22:27,0], ildmk[22:27,1], marker='o', s=3, color="#F4A460",alpha=1) +# ax.scatter(ildmk[27:36,0], ildmk[27:36,1], marker='o', s=3, color="blue",alpha=1) +# ax.scatter(ildmk[36:48,0], ildmk[36:48,1], marker='o', s=3, color="#DC143C",alpha=1) +# ax.scatter(ildmk[48:60,0], ildmk[48:60,1], marker='o', s=3, color="#DC143C",alpha=1) +# ax.scatter(ildmk[60:68,0], ildmk[60:68,1], marker='o', s=3, color="#FF1493",alpha=1) + +# #chin +# ax.plot(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='', markersize=1, linestyle='-', color='#008B8B', lw=2, alpha=1) + +# #left and right eyebrow +# ax.plot(ildmk[17:22,0], ildmk[17:22,1], marker='', markersize=1, linestyle='-', color='#F4A460', lw=2, alpha=1) +# ax.plot(ildmk[22:27,0], ildmk[22:27,1], marker='', markersize=1, linestyle='-', color='#F4A460', lw=2, alpha=1) + +# #nose +# ax.plot(ildmk[27:31,0], ildmk[27:31,1], marker='', markersize=1, linestyle='-', color='blue', lw=2, alpha=1) +# ax.plot(ildmk[31:36,0], ildmk[31:36,1], marker='', markersize=1, linestyle='-', color='blue', lw=2, alpha=1) + +# #left and right eye +# ax.plot(ildmk[36:42,0], ildmk[36:42,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) +# ax.plot(ildmk[42:48,0], ildmk[42:48,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) + +# ax.plot(ildmk[[41,36],0], ildmk[[41,36],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) +# ax.plot(ildmk[[47,42],0], ildmk[[47,42],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) + +# #outer and inner lip +# ax.plot(ildmk[48:60,0], ildmk[48:60,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) +# ax.plot(ildmk[60:68,0], ildmk[60:68,1], marker='', markersize=1, linestyle='-', color='#FF1493', lw=2, alpha=1) + +# ax.plot(ildmk[[59,48],0], ildmk[[59,48],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) +# ax.plot(ildmk[[67,60],0], ildmk[[67,60],1], marker='', markersize=1, linestyle='-', color='#FF1493', lw=2, alpha=1) + +# ax.set_xlim(0, w) +# ax.set_ylim(0, h) +# ax.axis('off') + +# if text is not None: +# ax.text(10, 10, text) + +# fig.canvas.draw() +# w, h = fig.canvas.get_width_height() + +# buffer = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) +# buffer = buffer.reshape((h, w, 3)) +# image = np.asarray(buffer) +# # print(f"w,h={w},{h}, buffer shape = {buffer.shape}, dtype = {buffer.dtype}, class = {(buffer)}") + +# plt.close(fig) + +# return image + +def landmark_to_mask(ildmk, w=256, h=256, dpi=100, norm=True): + # landmarks shape = (68, 2) + # print(f"landmark data shape = {ildmk.shape}") + if norm: + ildmk = ildmk * w + + # plot + fig = plt.figure(figsize=(h/dpi, w/dpi), dpi=dpi) + ax = fig.add_subplot(1,1,1) + + # ax.imshow(np.ones(shape=(w, h))) + # plt.subplots_adjust(left=0, right=1, top=1, bottom=0) + + #chin + ax.plot(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='', markersize=1, linestyle='-', color='green', lw=2) + #left and right eyebrow + ax.plot(ildmk[17:22,0], ildmk[17:22,1], marker='', markersize=1, linestyle='-', color='orange', lw=2) + ax.plot(ildmk[22:27,0], ildmk[22:27,1], marker='', markersize=1, linestyle='-', color='orange', lw=2) + #nose + ax.plot(ildmk[27:31,0], ildmk[27:31,1], marker='', markersize=1, linestyle='-', color='blue', lw=2) + ax.plot(ildmk[31:36,0], ildmk[31:36,1], marker='', markersize=1, linestyle='-', color='blue', lw=2) + #left and right eye + ax.plot(ildmk[36:42,0], ildmk[36:42,1], marker='', markersize=1, linestyle='-', color='red', lw=2) + ax.plot(ildmk[42:48,0], ildmk[42:48,1], marker='', markersize=1, linestyle='-', color='red', lw=2) + #outer and inner lip + ax.plot(ildmk[48:60,0], ildmk[48:60,1], marker='', markersize=1, linestyle='-', color='purple', lw=2) + ax.plot(ildmk[60:68,0], ildmk[60:68,1], marker='', markersize=1, linestyle='-', color='pink', lw=2) + ax.axis('off') + + + fig.canvas.draw() + + + buffer = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) + # buffer.shape = (w, h, 4) + + image = buffer.reshape(fig.canvas.get_width_height()[::-1] + (3,)) + + plt.close(fig) + + return image + + + + + + + diff --git a/src/utils/resampling.py b/src/utils/resampling.py new file mode 100644 index 0000000..7ed3fb9 --- /dev/null +++ b/src/utils/resampling.py @@ -0,0 +1,39 @@ +import numpy as np +from scipy import interpolate + +def resample_by_nsteps(feat, nsteps_tgt): + """ + feat, (nframes, ... ) (with source_fps) + """ + + nsteps_src = feat.shape[0] + data_idx = np.arange(0, nsteps_src, 1) + samp_idx = np.arange(0, nsteps_src-1, (nsteps_src - 1) / nsteps_tgt) + # print(f"data_idx = {list(data_idx)} \nsmap_idx = {list(samp_idx)}") + + # sample function + func = interpolate.interp1d(data_idx, y=feat, axis=0) + data_interpolate = func(samp_idx) + + return data_interpolate + + +def convert_fps(data, source_fps = 30, target_fps=25): + """ + data, (nframes, ... ) (with source_fps) + """ + + nsize = data.shape[0] + data_idx = np.arange(0, nsize, 1) + samp_idx = np.arange(0, nsize-1, 1.0*source_fps/target_fps) + + func = interpolate.interp1d(data_idx, data=data, axis=0) + data_interpolate = func(samp_idx) + + if source_fps < target_fps: + data_interpolate = np.concatenate([data_interpolate, data[-1:]]) + + return data_interpolate + + +# def \ No newline at end of file diff --git a/tests/unit/test_mnist_datamodule.py b/tests/unit/test_mnist_datamodule.py index 91e6182..5536bc2 100644 --- a/tests/unit/test_mnist_datamodule.py +++ b/tests/unit/test_mnist_datamodule.py @@ -3,7 +3,7 @@ import os import pytest import torch -from src.datamodules.mnist_datamodule import MNISTDataModule +from src.datasets.mnist_datamodule import MNISTDataModule @pytest.mark.parametrize("batch_size", [32, 128])