add data processing for crop & skin-mask
This commit is contained in:
1 parent
e51d3d1a6f
commit
83f99d9ec5
33 files changed
+2262
-2524
No files matched your search
@@ -1 +1,2 @@
|
||||
*.onnx filter=lfs diff=lfs merge=lfs -text
|
||||
data/mesh/** filter=lfs diff=lfs merge=lfs -text
|
||||
@@ -1,35 +0,0 @@
|
||||
_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"
|
||||
Whitespace-only changes.
@@ -1,12 +1,14 @@
|
||||
_target_: src.datasets.motion_datamodule.MotionDataModule
|
||||
|
||||
batch_size: 64
|
||||
num_workers: 4
|
||||
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: ${path_data}/data_train.npz
|
||||
path_data: xxx/data_train.npz
|
||||
fps: 50
|
||||
sr: 16000
|
||||
num_windows: 3
|
||||
@@ -17,15 +19,16 @@ dataset_train:
|
||||
|
||||
dataset_valid:
|
||||
_target_: src.datasets.components.motion_eval.MotionEvalDataset
|
||||
path_data: ${path_data}/data_valid.npz
|
||||
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: ${path_data}/data_test.npz
|
||||
path_data: xxx/data_test.npz
|
||||
fps: 50
|
||||
sr: 16000
|
||||
num_windows: 15
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# @package _global_
|
||||
# to execute this experiment run:
|
||||
# python train.py experiment=audio2mesh/train_audio2mesh_CN_20220425.yaml
|
||||
|
||||
defaults:
|
||||
- override /dataset: motion.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/Actor5
|
||||
specifict_folder: Actor5-raw-3h
|
||||
|
||||
|
||||
trainer:
|
||||
gpus: [1, 4, 8]
|
||||
min_epochs: 100
|
||||
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_Actor5_mean_smile.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"
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""This script is the data preparation script for Deep3DFaceRecon_pytorch
|
||||
"""
|
||||
|
||||
import os
|
||||
import numpy as np
|
||||
import argparse
|
||||
from .detect_lm68 import detect_68p, load_lm_graph
|
||||
from .skin_mask import get_skin_mask
|
||||
from .generate_list import check_list, write_list
|
||||
import warnings
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--data_root', type=str, default='datasets', help='root directory for training data')
|
||||
parser.add_argument('--img_folder', nargs="+", required=True, help='folders of training images')
|
||||
parser.add_argument('--mode', type=str, default='train', help='train or val')
|
||||
opt = parser.parse_args()
|
||||
|
||||
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
||||
|
||||
def data_prepare(folder_list, mode):
|
||||
|
||||
lm_sess,input_op,output_op = load_lm_graph('./checkpoints/lm_model/68lm_detector.pb') # load a tensorflow version 68-landmark detector
|
||||
|
||||
for img_folder in folder_list:
|
||||
detect_68p(img_folder,lm_sess, input_op, output_op) # detect landmarks for images
|
||||
get_skin_mask(img_folder) # generate skin attention mask for images
|
||||
|
||||
|
||||
# create files that record path to all training data
|
||||
msks_list = []
|
||||
for img_folder in folder_list:
|
||||
path = os.path.join(img_folder, 'mask')
|
||||
msks_list += ['/'.join([img_folder, 'mask', i]) for i in sorted(os.listdir(path)) if 'jpg' in i or
|
||||
'png' in i or 'jpeg' in i or 'PNG' in i]
|
||||
|
||||
imgs_list = [i.replace('mask/', '') for i in msks_list]
|
||||
lms_list = [i.replace('mask', 'landmarks') for i in msks_list]
|
||||
lms_list = ['.'.join(i.split('.')[:-1]) + '.txt' for i in lms_list]
|
||||
|
||||
lms_list_final, imgs_list_final, msks_list_final = check_list(lms_list, imgs_list, msks_list) # check if the path is valid
|
||||
write_list(lms_list_final, imgs_list_final, msks_list_final, mode=mode) # save files
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print('Datasets:',opt.img_folder)
|
||||
|
||||
data_prepare([os.path.join(opt.data_root,folder) for folder in opt.img_folder],opt.mode)
|
||||
@@ -0,0 +1,108 @@
|
||||
import os
|
||||
import cv2
|
||||
import numpy as np
|
||||
from scipy.io import loadmat
|
||||
import tensorflow as tf
|
||||
from .preprocess import align_for_lm
|
||||
from shutil import move
|
||||
|
||||
mean_face = np.loadtxt('util/test_mean_face.txt')
|
||||
mean_face = mean_face.reshape([68, 2])
|
||||
|
||||
def save_label(labels, save_path):
|
||||
np.savetxt(save_path, labels)
|
||||
|
||||
def draw_landmarks(img, landmark, save_name):
|
||||
landmark = landmark
|
||||
lm_img = np.zeros([img.shape[0], img.shape[1], 3])
|
||||
lm_img[:] = img.astype(np.float32)
|
||||
landmark = np.round(landmark).astype(np.int32)
|
||||
|
||||
for i in range(len(landmark)):
|
||||
for j in range(-1, 1):
|
||||
for k in range(-1, 1):
|
||||
if img.shape[0] - 1 - landmark[i, 1]+j > 0 and \
|
||||
img.shape[0] - 1 - landmark[i, 1]+j < img.shape[0] and \
|
||||
landmark[i, 0]+k > 0 and \
|
||||
landmark[i, 0]+k < img.shape[1]:
|
||||
lm_img[img.shape[0] - 1 - landmark[i, 1]+j, landmark[i, 0]+k,
|
||||
:] = np.array([0, 0, 255])
|
||||
lm_img = lm_img.astype(np.uint8)
|
||||
|
||||
cv2.imwrite(save_name, lm_img)
|
||||
|
||||
|
||||
def load_data(img_name, txt_name):
|
||||
return cv2.imread(img_name), np.loadtxt(txt_name)
|
||||
|
||||
# create tensorflow graph for landmark detector
|
||||
def load_lm_graph(graph_filename):
|
||||
with tf.gfile.GFile(graph_filename, 'rb') as f:
|
||||
graph_def = tf.GraphDef()
|
||||
graph_def.ParseFromString(f.read())
|
||||
|
||||
with tf.Graph().as_default() as graph:
|
||||
tf.import_graph_def(graph_def, name='net')
|
||||
img_224 = graph.get_tensor_by_name('net/input_imgs:0')
|
||||
output_lm = graph.get_tensor_by_name('net/lm:0')
|
||||
lm_sess = tf.Session(graph=graph)
|
||||
|
||||
return lm_sess,img_224,output_lm
|
||||
|
||||
|
||||
# landmark detection
|
||||
def detect_68p(img_path, sess, input_op, output_op):
|
||||
print('detecting landmarks......')
|
||||
names = [i for i in sorted(os.listdir(
|
||||
img_path)) if 'jpg' in i or 'png' in i or 'jpeg' in i or 'PNG' in i]
|
||||
|
||||
vis_path = os.path.join(img_path, 'vis')
|
||||
remove_path = os.path.join(img_path, 'remove')
|
||||
save_path = os.path.join(img_path, 'landmarks')
|
||||
|
||||
if not os.path.isdir(vis_path):
|
||||
os.makedirs(vis_path)
|
||||
if not os.path.isdir(remove_path):
|
||||
os.makedirs(remove_path)
|
||||
if not os.path.isdir(save_path):
|
||||
os.makedirs(save_path)
|
||||
|
||||
for i in range(0, len(names)):
|
||||
name = names[i]
|
||||
print('%05d' % (i), ' ', name)
|
||||
|
||||
full_image_name = os.path.join(img_path, name)
|
||||
txt_name = '.'.join(name.split('.')[:-1]) + '.txt'
|
||||
full_txt_name = os.path.join(img_path, 'detections', txt_name) # 5 facial landmark path for each image
|
||||
|
||||
# if an image does not have detected 5 facial landmarks,
|
||||
# remove it from the training list
|
||||
if not os.path.isfile(full_txt_name):
|
||||
move(full_image_name, os.path.join(remove_path, name))
|
||||
continue
|
||||
|
||||
# load data
|
||||
img, five_points = load_data(full_image_name, full_txt_name)
|
||||
input_img, scale, bbox = align_for_lm(img, five_points) # align for 68 landmark detection
|
||||
|
||||
# if the alignment fails, remove corresponding image from the training list
|
||||
if scale == 0:
|
||||
move(full_txt_name, os.path.join(remove_path, txt_name))
|
||||
move(full_image_name, os.path.join(remove_path, name))
|
||||
continue
|
||||
|
||||
# detect landmarks
|
||||
input_img = np.reshape(input_img, [1, 224, 224, 3]).astype(np.float32)
|
||||
landmark = sess.run(output_op, feed_dict={input_op: input_img})
|
||||
|
||||
# transform back to original image coordinate
|
||||
landmark = landmark.reshape([68, 2]) + mean_face
|
||||
landmark[:, 1] = 223 - landmark[:, 1]
|
||||
landmark = landmark / scale
|
||||
landmark[:, 0] = landmark[:, 0] + bbox[0]
|
||||
landmark[:, 1] = landmark[:, 1] + bbox[1]
|
||||
landmark[:, 1] = img.shape[0] - 1 - landmark[:, 1]
|
||||
|
||||
if i % 100 == 0:
|
||||
draw_landmarks(img, landmark, os.path.join(vis_path, name))
|
||||
save_label(landmark, os.path.join(save_path, txt_name))
|
||||
@@ -0,0 +1,34 @@
|
||||
"""This script is to generate training list files for Deep3DFaceRecon_pytorch
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
# save path to training data
|
||||
def write_list(lms_list, imgs_list, msks_list, mode='train',save_folder='datalist', save_name=''):
|
||||
save_path = os.path.join(save_folder, mode)
|
||||
if not os.path.isdir(save_path):
|
||||
os.makedirs(save_path)
|
||||
with open(os.path.join(save_path, save_name + 'landmarks.txt'), 'w') as fd:
|
||||
fd.writelines([i + '\n' for i in lms_list])
|
||||
|
||||
with open(os.path.join(save_path, save_name + 'images.txt'), 'w') as fd:
|
||||
fd.writelines([i + '\n' for i in imgs_list])
|
||||
|
||||
with open(os.path.join(save_path, save_name + 'masks.txt'), 'w') as fd:
|
||||
fd.writelines([i + '\n' for i in msks_list])
|
||||
|
||||
# check if the path is valid
|
||||
def check_list(rlms_list, rimgs_list, rmsks_list):
|
||||
lms_list, imgs_list, msks_list = [], [], []
|
||||
for i in range(len(rlms_list)):
|
||||
flag = 'false'
|
||||
lm_path = rlms_list[i]
|
||||
im_path = rimgs_list[i]
|
||||
msk_path = rmsks_list[i]
|
||||
if os.path.isfile(lm_path) and os.path.isfile(im_path) and os.path.isfile(msk_path):
|
||||
flag = 'true'
|
||||
lms_list.append(rlms_list[i])
|
||||
imgs_list.append(rimgs_list[i])
|
||||
msks_list.append(rmsks_list[i])
|
||||
print(i, rlms_list[i], flag)
|
||||
return lms_list, imgs_list, msks_list
|
||||
@@ -0,0 +1,237 @@
|
||||
"""This script contains the image preprocessing code for Deep3DFaceRecon_pytorch
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
from scipy.io import loadmat
|
||||
from PIL import Image
|
||||
import cv2
|
||||
import os
|
||||
from skimage import transform as trans
|
||||
import torch
|
||||
import warnings
|
||||
warnings.filterwarnings("ignore", category=np.VisibleDeprecationWarning)
|
||||
warnings.filterwarnings("ignore", category=FutureWarning)
|
||||
|
||||
|
||||
# calculating least square problem for image alignment
|
||||
def POS(xp, x):
|
||||
npts = xp.shape[1]
|
||||
|
||||
A = np.zeros([2*npts, 8])
|
||||
|
||||
A[0:2*npts-1:2, 0:3] = x.transpose()
|
||||
A[0:2*npts-1:2, 3] = 1
|
||||
|
||||
A[1:2*npts:2, 4:7] = x.transpose()
|
||||
A[1:2*npts:2, 7] = 1
|
||||
|
||||
b = np.reshape(xp.transpose(), [2*npts, 1])
|
||||
|
||||
k, _, _, _ = np.linalg.lstsq(A, b)
|
||||
|
||||
R1 = k[0:3]
|
||||
R2 = k[4:7]
|
||||
sTx = k[3]
|
||||
sTy = k[7]
|
||||
s = (np.linalg.norm(R1) + np.linalg.norm(R2))/2
|
||||
t = np.stack([sTx, sTy], axis=0)
|
||||
|
||||
return t, s
|
||||
|
||||
# bounding box for 68 landmark detection
|
||||
# to 224 x 224, rect bbox
|
||||
def BBRegression(points, params):
|
||||
|
||||
w1 = params['W1']
|
||||
b1 = params['B1']
|
||||
w2 = params['W2']
|
||||
b2 = params['B2']
|
||||
|
||||
data = points.copy().reshape([5, 2])
|
||||
|
||||
# data - data_mean
|
||||
data_mean = np.mean(data, axis=0) # (2,)
|
||||
x_mean,y_mean = data_mean[0], data_mean[1]
|
||||
data[:, 0] = data[:, 0] - x_mean
|
||||
data[:, 1] = data[:, 1] - y_mean
|
||||
|
||||
# (data - data_mean) / variance
|
||||
rms = np.sqrt(np.sum(data ** 2)/5)
|
||||
data = data / rms
|
||||
|
||||
data = data.reshape([1, 10])
|
||||
data = np.transpose(data)
|
||||
inputs = np.matmul(w1, data) + b1
|
||||
inputs = 2 / (1 + np.exp(-2 * inputs)) - 1
|
||||
inputs = np.matmul(w2, inputs) + b2
|
||||
inputs = np.transpose(inputs)
|
||||
x = inputs[:, 0] * rms + x_mean
|
||||
y = inputs[:, 1] * rms + y_mean
|
||||
w = 224/inputs[:, 2] * rms
|
||||
rects = [x, y, w, w]
|
||||
return np.array(rects).reshape([4])
|
||||
|
||||
# utils for landmark detection
|
||||
def img_padding(img, box):
|
||||
success = True
|
||||
bbox = box.copy()
|
||||
res = np.zeros([2*img.shape[0], 2*img.shape[1], 3])
|
||||
res[img.shape[0] // 2: img.shape[0] + img.shape[0] //
|
||||
2, img.shape[1] // 2: img.shape[1] + img.shape[1]//2] = img
|
||||
|
||||
bbox[0] = bbox[0] + img.shape[1] // 2
|
||||
bbox[1] = bbox[1] + img.shape[0] // 2
|
||||
if bbox[0] < 0 or bbox[1] < 0:
|
||||
success = False
|
||||
return res, bbox, success
|
||||
|
||||
# utils for landmark detection
|
||||
def crop(img, bbox):
|
||||
padded_img, padded_bbox, flag = img_padding(img, bbox)
|
||||
if flag:
|
||||
crop_img = padded_img[padded_bbox[1]: padded_bbox[1] +
|
||||
padded_bbox[3], padded_bbox[0]: padded_bbox[0] + padded_bbox[2]]
|
||||
crop_img = cv2.resize(crop_img.astype(np.uint8),
|
||||
(224, 224), interpolation=cv2.INTER_CUBIC)
|
||||
scale = 224 / padded_bbox[3]
|
||||
return crop_img, scale
|
||||
else:
|
||||
return padded_img, 0
|
||||
|
||||
# utils for landmark detection
|
||||
def scale_trans(img, lm, t, s):
|
||||
imgw = img.shape[1]
|
||||
imgh = img.shape[0]
|
||||
M_s = np.array([[1, 0, -t[0] + imgw//2 + 0.5], [0, 1, -imgh//2 + t[1]]],
|
||||
dtype=np.float32)
|
||||
img = cv2.warpAffine(img, M_s, (imgw, imgh))
|
||||
w = int(imgw / s * 100)
|
||||
h = int(imgh / s * 100)
|
||||
img = cv2.resize(img, (w, h))
|
||||
lm = np.stack([lm[:, 0] - t[0] + imgw // 2, lm[:, 1] -
|
||||
t[1] + imgh // 2], axis=1) / s * 100
|
||||
|
||||
left = w//2 - 112
|
||||
up = h//2 - 112
|
||||
bbox = [left, up, 224, 224]
|
||||
cropped_img, scale2 = crop(img, bbox)
|
||||
assert(scale2!=0)
|
||||
t1 = np.array([bbox[0], bbox[1]])
|
||||
|
||||
# back to raw img s * crop + s * t1 + t2
|
||||
t1 = np.array([w//2 - 112, h//2 - 112])
|
||||
scale = s / 100
|
||||
t2 = np.array([t[0] - imgw/2, t[1] - imgh / 2])
|
||||
inv = (scale/scale2, scale * t1 + t2.reshape([2]))
|
||||
return cropped_img, inv
|
||||
|
||||
# utils for landmark detection
|
||||
def align_for_lm(img, five_points):
|
||||
five_points = np.array(five_points).reshape([1, 10])
|
||||
params = loadmat('util/BBRegressorParam_r.mat')
|
||||
bbox = BBRegression(five_points, params)
|
||||
assert(bbox[2] != 0)
|
||||
|
||||
bbox = np.round(bbox).astype(np.int32)
|
||||
crop_img, scale = crop(img, bbox)
|
||||
|
||||
return crop_img, scale, bbox
|
||||
|
||||
|
||||
# resize and crop images for face reconstruction
|
||||
def resize_n_crop_img(img, lm, t, s, target_size=224., mask=None):
|
||||
w0, h0 = img.size
|
||||
w = (w0*s).astype(np.int32)
|
||||
h = (h0*s).astype(np.int32)
|
||||
left = (w/2 - target_size/2 + float((t[0] - w0/2)*s)).astype(np.int32)
|
||||
right = left + target_size
|
||||
up = (h/2 - target_size/2 + float((h0/2 - t[1])*s)).astype(np.int32)
|
||||
below = up + target_size
|
||||
|
||||
img = img.resize((w, h), resample=Image.BICUBIC)
|
||||
img = img.crop((left, up, right, below))
|
||||
|
||||
if mask is not None:
|
||||
mask = mask.resize((w, h), resample=Image.BICUBIC)
|
||||
mask = mask.crop((left, up, right, below))
|
||||
|
||||
lm = np.stack([lm[:, 0] - t[0] + w0/2, lm[:, 1] -
|
||||
t[1] + h0/2], axis=1)*s
|
||||
lm = lm - np.reshape(
|
||||
np.array([(w/2 - target_size/2), (h/2-target_size/2)]), [1, 2])
|
||||
|
||||
return img, lm, mask
|
||||
|
||||
# utils for face reconstruction
|
||||
def extract_5p(lm):
|
||||
lm_idx = np.array([31, 37, 40, 43, 46, 49, 55]) - 1
|
||||
lm5p = np.stack([lm[lm_idx[0], :], np.mean(lm[lm_idx[[1, 2]], :], 0), np.mean(
|
||||
lm[lm_idx[[3, 4]], :], 0), lm[lm_idx[5], :], lm[lm_idx[6], :]], axis=0)
|
||||
lm5p = lm5p[[1, 2, 0, 3, 4], :]
|
||||
return lm5p
|
||||
|
||||
# utils for face reconstruction
|
||||
def align_img(img, lm, lm3D, mask=None, target_size=224., rescale_factor=102.):
|
||||
"""
|
||||
Return:
|
||||
transparams --numpy.array (raw_W, raw_H, scale, tx, ty)
|
||||
img_new --PIL.Image (target_size, target_size, 3)
|
||||
lm_new --numpy.array (68, 2), y direction is opposite to v direction
|
||||
mask_new --PIL.Image (target_size, target_size)
|
||||
|
||||
Parameters:
|
||||
img --PIL.Image (raw_H, raw_W, 3)
|
||||
lm --numpy.array (68, 2), y direction is opposite to v direction
|
||||
lm3D --numpy.array (5, 3)
|
||||
mask --PIL.Image (raw_H, raw_W, 3)
|
||||
"""
|
||||
|
||||
w0, h0 = img.size
|
||||
if lm.shape[0] != 5:
|
||||
lm5p = extract_5p(lm)
|
||||
else:
|
||||
lm5p = lm
|
||||
|
||||
# calculate translation and scale factors using 5 facial landmarks
|
||||
# and standard landmarks of a 3D face
|
||||
t, s = POS(lm5p.transpose(), lm3D.transpose())
|
||||
s = rescale_factor/s
|
||||
|
||||
# processing the image
|
||||
img_new, lm_new, mask_new = resize_n_crop_img(img, lm, t, s, target_size=target_size, mask=mask)
|
||||
trans_params = np.array([w0, h0, s, t[0], t[1]])
|
||||
|
||||
return trans_params, img_new, lm_new, mask_new
|
||||
|
||||
# utils for face recognition model
|
||||
def estimate_norm(lm_68p, H):
|
||||
# from https://github.com/deepinsight/insightface/blob/c61d3cd208a603dfa4a338bd743b320ce3e94730/recognition/common/face_align.py#L68
|
||||
"""
|
||||
Return:
|
||||
trans_m --numpy.array (2, 3)
|
||||
Parameters:
|
||||
lm --numpy.array (68, 2), y direction is opposite to v direction
|
||||
H --int/float , image height
|
||||
"""
|
||||
lm = extract_5p(lm_68p)
|
||||
lm[:, -1] = H - 1 - lm[:, -1]
|
||||
|
||||
tform = trans.SimilarityTransform()
|
||||
src = np.array(
|
||||
[[38.2946, 51.6963], [73.5318, 51.5014], [56.0252, 71.7366],
|
||||
[41.5493, 92.3655], [70.7299, 92.2041]],
|
||||
dtype=np.float32)
|
||||
tform.estimate(lm, src)
|
||||
M = tform.params
|
||||
if np.linalg.det(M) == 0:
|
||||
M = np.eye(3)
|
||||
|
||||
return M[0:2, :]
|
||||
|
||||
def estimate_norm_torch(lm_68p, H):
|
||||
lm_68p_ = lm_68p.detach().cpu().numpy()
|
||||
M = []
|
||||
for i in range(lm_68p_.shape[0]):
|
||||
M.append(estimate_norm(lm_68p_[i], H))
|
||||
M = torch.tensor(np.array(M), dtype=torch.float32).to(lm_68p.device)
|
||||
return M
|
||||
@@ -0,0 +1,129 @@
|
||||
"""This script is to generate skin attention mask for Deep3DFaceRecon_pytorch
|
||||
"""
|
||||
|
||||
import math
|
||||
import numpy as np
|
||||
import os
|
||||
import cv2
|
||||
|
||||
class GMM:
|
||||
def __init__(self, dim, num, w, mu, cov, cov_det, cov_inv):
|
||||
self.dim = dim # feature dimension
|
||||
self.num = num # number of Gaussian components
|
||||
self.w = w # weights of Gaussian components (a list of scalars)
|
||||
self.mu= mu # mean of Gaussian components (a list of 1xdim vectors)
|
||||
self.cov = cov # covariance matrix of Gaussian components (a list of dimxdim matrices)
|
||||
self.cov_det = cov_det # pre-computed determinet of covariance matrices (a list of scalars)
|
||||
self.cov_inv = cov_inv # pre-computed inverse covariance matrices (a list of dimxdim matrices)
|
||||
|
||||
self.factor = [0]*num
|
||||
for i in range(self.num):
|
||||
self.factor[i] = (2*math.pi)**(self.dim/2) * self.cov_det[i]**0.5
|
||||
|
||||
def likelihood(self, data):
|
||||
assert(data.shape[1] == self.dim)
|
||||
N = data.shape[0]
|
||||
lh = np.zeros(N)
|
||||
|
||||
for i in range(self.num):
|
||||
data_ = data - self.mu[i]
|
||||
|
||||
tmp = np.matmul(data_,self.cov_inv[i]) * data_
|
||||
tmp = np.sum(tmp,axis=1)
|
||||
power = -0.5 * tmp
|
||||
|
||||
p = np.array([math.exp(power[j]) for j in range(N)])
|
||||
p = p/self.factor[i]
|
||||
lh += p*self.w[i]
|
||||
|
||||
return lh
|
||||
|
||||
|
||||
def _rgb2ycbcr(rgb):
|
||||
m = np.array([[65.481, 128.553, 24.966],
|
||||
[-37.797, -74.203, 112],
|
||||
[112, -93.786, -18.214]])
|
||||
shape = rgb.shape
|
||||
rgb = rgb.reshape((shape[0] * shape[1], 3))
|
||||
ycbcr = np.dot(rgb, m.transpose() / 255.)
|
||||
ycbcr[:, 0] += 16.
|
||||
ycbcr[:, 1:] += 128.
|
||||
return ycbcr.reshape(shape)
|
||||
|
||||
|
||||
def _bgr2ycbcr(bgr):
|
||||
rgb = bgr[..., ::-1]
|
||||
return _rgb2ycbcr(rgb)
|
||||
|
||||
|
||||
gmm_skin_w = [0.24063933, 0.16365987, 0.26034665, 0.33535415]
|
||||
gmm_skin_mu = [np.array([113.71862, 103.39613, 164.08226]),
|
||||
np.array([150.19858, 105.18467, 155.51428]),
|
||||
np.array([183.92976, 107.62468, 152.71820]),
|
||||
np.array([114.90524, 113.59782, 151.38217])]
|
||||
gmm_skin_cov_det = [5692842.5, 5851930.5, 2329131., 1585971.]
|
||||
gmm_skin_cov_inv = [np.array([[0.0019472069, 0.0020450759, -0.00060243998],[0.0020450759, 0.017700525, 0.0051420014],[-0.00060243998, 0.0051420014, 0.0081308950]]),
|
||||
np.array([[0.0027110141, 0.0011036990, 0.0023122299],[0.0011036990, 0.010707724, 0.010742856],[0.0023122299, 0.010742856, 0.017481629]]),
|
||||
np.array([[0.0048026871, 0.00022935172, 0.0077668377],[0.00022935172, 0.011729696, 0.0081661865],[0.0077668377, 0.0081661865, 0.025374353]]),
|
||||
np.array([[0.0011989699, 0.0022453172, -0.0010748957],[0.0022453172, 0.047758564, 0.020332102],[-0.0010748957, 0.020332102, 0.024502251]])]
|
||||
|
||||
gmm_skin = GMM(3, 4, gmm_skin_w, gmm_skin_mu, [], gmm_skin_cov_det, gmm_skin_cov_inv)
|
||||
|
||||
gmm_nonskin_w = [0.12791070, 0.31130761, 0.34245777, 0.21832393]
|
||||
gmm_nonskin_mu = [np.array([99.200851, 112.07533, 140.20602]),
|
||||
np.array([110.91392, 125.52969, 130.19237]),
|
||||
np.array([129.75864, 129.96107, 126.96808]),
|
||||
np.array([112.29587, 128.85121, 129.05431])]
|
||||
gmm_nonskin_cov_det = [458703648., 6466488., 90611376., 133097.63]
|
||||
gmm_nonskin_cov_inv = [np.array([[0.00085371657, 0.00071197288, 0.00023958916],[0.00071197288, 0.0025935620, 0.00076557708],[0.00023958916, 0.00076557708, 0.0015042332]]),
|
||||
np.array([[0.00024650150, 0.00045542428, 0.00015019422],[0.00045542428, 0.026412144, 0.018419769],[0.00015019422, 0.018419769, 0.037497383]]),
|
||||
np.array([[0.00037054974, 0.00038146760, 0.00040408765],[0.00038146760, 0.0085505722, 0.0079136286],[0.00040408765, 0.0079136286, 0.010982352]]),
|
||||
np.array([[0.00013709733, 0.00051228428, 0.00012777430],[0.00051228428, 0.28237113, 0.10528370],[0.00012777430, 0.10528370, 0.23468947]])]
|
||||
|
||||
gmm_nonskin = GMM(3, 4, gmm_nonskin_w, gmm_nonskin_mu, [], gmm_nonskin_cov_det, gmm_nonskin_cov_inv)
|
||||
|
||||
prior_skin = 0.8
|
||||
prior_nonskin = 1 - prior_skin
|
||||
|
||||
|
||||
# calculate skin attention mask
|
||||
def skinmask(imbgr):
|
||||
im = _bgr2ycbcr(imbgr)
|
||||
|
||||
data = im.reshape((-1,3))
|
||||
|
||||
lh_skin = gmm_skin.likelihood(data)
|
||||
lh_nonskin = gmm_nonskin.likelihood(data)
|
||||
|
||||
tmp1 = prior_skin * lh_skin
|
||||
tmp2 = prior_nonskin * lh_nonskin
|
||||
post_skin = tmp1 / (tmp1+tmp2) # posterior probability
|
||||
|
||||
post_skin = post_skin.reshape((im.shape[0],im.shape[1]))
|
||||
|
||||
post_skin = np.round(post_skin*255)
|
||||
post_skin = post_skin.astype(np.uint8)
|
||||
post_skin = np.tile(np.expand_dims(post_skin,2),[1,1,3]) # reshape to H*W*3
|
||||
|
||||
return post_skin
|
||||
|
||||
|
||||
def get_skin_mask(img_path):
|
||||
print('generating skin masks......')
|
||||
names = [i for i in sorted(os.listdir(
|
||||
img_path)) if 'jpg' in i or 'png' in i or 'jpeg' in i or 'PNG' in i]
|
||||
|
||||
save_path = os.path.join(img_path, 'mask')
|
||||
if not os.path.isdir(save_path):
|
||||
os.makedirs(save_path)
|
||||
|
||||
for i in range(0, len(names)):
|
||||
name = names[i]
|
||||
print('%05d' % (i), ' ', name)
|
||||
|
||||
full_image_name = os.path.join(img_path, name)
|
||||
|
||||
img = cv2.imread(full_image_name).astype(np.float32)
|
||||
skin_img = skinmask(img)
|
||||
|
||||
cv2.imwrite(os.path.join(save_path, name), skin_img.astype(np.uint8))
|
||||
@@ -0,0 +1,82 @@
|
||||
from torch.utils.data import Dataset, DataLoader
|
||||
|
||||
import torch
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
from pathlib2 import Path
|
||||
from face_alignment import FaceAlignment, LandmarksType
|
||||
from zmq import device
|
||||
|
||||
|
||||
class ImagesDataset(Dataset):
|
||||
def __init__(self, path_folder:Path):
|
||||
|
||||
self.path_folder = path_folder
|
||||
self.list_image = sorted(path_folder.glob("*.jpg"), reverse=False)
|
||||
print(f"Have {len(self.list_image)} images, like {self.list_image[:3]}")
|
||||
|
||||
|
||||
def __len__(self):
|
||||
return len(self.list_image)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
path_frame = self.list_image[idx]
|
||||
image = Image.open(str(path_frame)).convert('RGB') # (h, w, 3)
|
||||
image = np.asarray(image)
|
||||
return {"image_name": path_frame.stem, "image": image}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
|
||||
vpath_videos = sorted(path_data.glob("*"), reverse=True)
|
||||
print(f"Have {len(vpath_videos)} dir files")
|
||||
|
||||
device = "cuda:7"
|
||||
model = FaceAlignment(LandmarksType._2D, device=device, face_detector='sfd')
|
||||
print(f"load FaceAlignment model in {device}")
|
||||
|
||||
# IDs = ["2-23min"]
|
||||
# for each word
|
||||
for i, ipath_item in enumerate(vpath_videos[16:]):
|
||||
iname = ipath_item.stem
|
||||
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
|
||||
|
||||
# if iname not in IDs: continue
|
||||
|
||||
ipath_infor = ipath_item.joinpath("video/info.json")
|
||||
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
|
||||
ipath_frame = ipath_item.joinpath("frames")
|
||||
ipath_ldmks.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
# check
|
||||
num_frame = len(list(ipath_frame.glob("*.jpg")))
|
||||
num_ladmk = len(list(ipath_ldmks.glob("*.txt")))
|
||||
if num_frame == num_ladmk:
|
||||
print(f"\n Skip: have already done!")
|
||||
continue
|
||||
|
||||
|
||||
dataset = ImagesDataset(ipath_frame)
|
||||
dloader = DataLoader(dataset, batch_size=16, num_workers=8)
|
||||
|
||||
for k, ibatch in enumerate(dloader):
|
||||
ibatch_name = ibatch["image_name"]
|
||||
ibatch_data = ibatch["image"].to(device) # B x H x W x 3
|
||||
ibatch_data = ibatch_data.permute(0, 3, 1, 2) # B x H x W x 3
|
||||
# print(f"ibatch_data shape = {ibatch_data.shape}, path={ibatch_name[:3]}")
|
||||
if k%100 == 0:
|
||||
print(f"batching {k}/{len(dloader)} ... ")
|
||||
|
||||
pred = model.get_landmarks_from_batch(ibatch_data, return_landmark_score=False)
|
||||
# print(f"pred len = {len(pred)}, type= {type(pred)}, [0] shape={pred[0].shape}")
|
||||
|
||||
# save landmarks
|
||||
for jldmk, jname in zip(pred, ibatch_name):
|
||||
jpath_ldmk = ipath_ldmks.joinpath(jname + ".txt")
|
||||
np.savetxt(jpath_ldmk, jldmk, fmt=" %3d")
|
||||
|
||||
|
||||
|
||||
# break
|
||||
@@ -0,0 +1,175 @@
|
||||
import cv2
|
||||
import numpy as np
|
||||
from pathlib2 import Path
|
||||
from skimage.transform import estimate_transform, warp
|
||||
|
||||
from torch.utils.data import Dataset, DataLoader
|
||||
|
||||
class ImagesDataset(Dataset):
|
||||
def __init__(self, path_frames, path_landmk, suffix="jpg", crop_size=224, scale=1.25, roation_image=False):
|
||||
'''
|
||||
path_frames: folder, vpath_image, image path, video path
|
||||
'''
|
||||
|
||||
self.path_frames = Path(path_frames)
|
||||
self.path_landmk = Path(path_landmk)
|
||||
self.vpath_image = sorted(self.path_frames.glob(f"*.{suffix}"), key=lambda x: int(x.stem.split("-")[-1]), reverse=False)
|
||||
print(f'--> total have {len(self.vpath_image)} images, top: \n{self.vpath_image[:3]}')
|
||||
|
||||
self.scale = scale # 1.25
|
||||
self.crop_size = crop_size # 224
|
||||
self.roation_image =roation_image
|
||||
|
||||
def bbox2point(self, left, right, top, bottom, type='bbox'):
|
||||
''' bbox from detector and landmarks are different
|
||||
'''
|
||||
if type=='kpt68':
|
||||
old_size = (right - left + bottom - top) / 2 * 1.1
|
||||
center = np.array([right - (right - left) / 2.0,
|
||||
bottom - (bottom - top ) / 2.0 ])
|
||||
elif type=='bbox':
|
||||
old_size = (right - left + bottom - top)/2
|
||||
center = np.array([right - (right - left) / 2.0,
|
||||
bottom - (bottom - top ) / 2.0 + old_size*0.12])
|
||||
else:
|
||||
raise NotImplementedError
|
||||
|
||||
return old_size, center
|
||||
|
||||
|
||||
def __len__(self):
|
||||
return len(self.vpath_image)
|
||||
|
||||
def __getitem__(self, index):
|
||||
ipath_frame = self.vpath_image[index]
|
||||
image_name = ipath_frame.stem # (frame-0000)
|
||||
|
||||
# print(f"load ipath_frame --> {ipath_frame}")
|
||||
|
||||
ipath_ldmk = self.path_landmk.joinpath(image_name + ".txt")
|
||||
if not ipath_ldmk.exists():
|
||||
raise Exception(f"ipath_ldmk not exists --> {ipath_ldmk}")
|
||||
|
||||
# load orignal image & landmarks
|
||||
image = cv2.imread(str(ipath_frame)) # (H, W, 3), dtype=uint8
|
||||
kpt = np.loadtxt(ipath_ldmk) # (68, 2)
|
||||
|
||||
# reverse H&W
|
||||
if self.roation_image:
|
||||
image = image.transpose(1,0,2) # (H, W, 3)
|
||||
kpt = kpt[:, ::-1] # (68, 2)
|
||||
|
||||
left = np.min(kpt[:,0]); right = np.max(kpt[:,0])
|
||||
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1])
|
||||
old_size, center = self.bbox2point(left, right, top, bottom, type='kpt68')
|
||||
|
||||
# crop transform
|
||||
size = int(old_size * self.scale)
|
||||
src_pts = np.array([[center[0] - size/2, center[1] - size/2], # (left, top)
|
||||
[center[0] - size/2, center[1] + size/2], # (left, bottom)
|
||||
[center[0] + size/2, center[1] - size/2]]) # (right, top)
|
||||
|
||||
DST_PTS = np.array([[0, 0], # (left-top-corner)
|
||||
[0, self.crop_size - 1], # (left-botton corner)
|
||||
[self.crop_size - 1, 0]]) # (right-top corner)
|
||||
|
||||
# tform_params dytpe = float64, shape = (3, 3)
|
||||
tform = estimate_transform('similarity', src_pts, DST_PTS)
|
||||
|
||||
# image = image/255.
|
||||
# (crop_size, crop_size, 3) ,float64
|
||||
cropped_imag = warp(image, tform.inverse, output_shape=(self.crop_size, self.crop_size)) # scale to (0~1)
|
||||
cropped_ldmk = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # (68,3)
|
||||
cropped_ldmk = cropped_ldmk[:, :2]
|
||||
# cropped_ldmk[:,:2] = cropped_ldmk[:,:2] / self.crop_size * 2 - 1
|
||||
|
||||
if cropped_ldmk.shape[0] > 68:
|
||||
# raise Exception(f"cropped_ldmk = {cropped_ldmk.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}")
|
||||
cropped_ldmk = cropped_ldmk[:68, :]
|
||||
print(f"ERROR: > use first 68-kpts, cropped_ldmk = {cropped_ldmk.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}")
|
||||
|
||||
|
||||
# cropped_mask = warp(mask, tform.inverse, output_shape=(self.crop_size, self.crop_size)) # scale to (0~1)
|
||||
|
||||
# print(f"image dytpe = {image.dtype}, shape = {image.shape} ")
|
||||
# print(f"cropped_imag dytpe = {cropped_imag.dtype}, shape = {cropped_imag.shape} ")
|
||||
# print(f"tform_params dytpe = {tform.params.dtype}, shape = {tform.params.shape} ")
|
||||
# print(f"cropped_ldmk dytpe = {cropped_ldmk.dtype}, shape = {cropped_ldmk.shape}, max={cropped_ldmk.max()}, min={cropped_ldmk.min()} ")
|
||||
# # print(f"jbatch_ldmks ={cropped_ldmk}")
|
||||
|
||||
return {'image_name': ipath_frame.stem,
|
||||
'image': image,
|
||||
'cropped_imag': cropped_imag,
|
||||
'tform_params': tform.params,
|
||||
'cropped_ldmk': cropped_ldmk,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
sub_folder = "processing" # processing, body, smile
|
||||
path_data = Path(f"/ssdata1/lsen/DATA/Actor5/{sub_folder}")
|
||||
vpath_videos = sorted(path_data.glob("*"), reverse=False)
|
||||
print(f"Have {len(vpath_videos)} dir files")
|
||||
|
||||
# whole body need roation frame
|
||||
roation_image = True if sub_folder == "body" else False
|
||||
|
||||
# IDs = ["2-23min"]
|
||||
# for each word
|
||||
for i, ipath_item in enumerate(vpath_videos):
|
||||
iname = ipath_item.stem
|
||||
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
|
||||
|
||||
# if iname not in IDs: continue
|
||||
ipath_infor = ipath_item.joinpath("video/info.json")
|
||||
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
|
||||
ipath_frame = ipath_item.joinpath("frames")
|
||||
ipath_fcrop = ipath_item.joinpath("frames_crop_512")
|
||||
ipath_tfrom = ipath_item.joinpath("frames_crop_tform_512")
|
||||
ipath_lcrop = ipath_item.joinpath("frames_crop_ldmks_512")
|
||||
|
||||
ipath_fcrop.mkdir(parents=True, exist_ok=True)
|
||||
ipath_tfrom.mkdir(parents=True, exist_ok=True)
|
||||
ipath_lcrop.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# check
|
||||
num_frame = len(list(ipath_frame.glob("*.jpg")))
|
||||
num_fcrop = len(list(ipath_fcrop.glob("*.jpg")))
|
||||
if num_frame == num_fcrop:
|
||||
print(f"\n Skip: have already done!")
|
||||
continue
|
||||
|
||||
# only whole body image, need set roation_image=True
|
||||
dataset = ImagesDataset(ipath_frame, ipath_ldmks, suffix="jpg", crop_size=512, scale=1.5, roation_image=roation_image)
|
||||
dloader = DataLoader(dataset, batch_size=64, num_workers=4, shuffle=False)
|
||||
|
||||
for j, jbatch in enumerate(dloader):
|
||||
# print(f"jbatch_data shape = {jbatch_data.shape}, path={jbatch_name[:3]}")
|
||||
if j%100 == 0:
|
||||
print(f"batching {j}/{len(dloader)} ... ")
|
||||
|
||||
jbatch_name = jbatch["image_name"]
|
||||
jbatch_crop = (255*jbatch["cropped_imag"]).numpy().astype(np.uint8)
|
||||
jbatch_tfrom = jbatch["tform_params"].numpy()
|
||||
jbatch_ldmks = jbatch["cropped_ldmk"].numpy()
|
||||
|
||||
# print(f"jbatch_crop dytpe = {jbatch_crop.dtype}, shape = {jbatch_crop.shape} ")
|
||||
# print(f"jbatch_tfrom dytpe = {jbatch_tfrom.dtype}, shape = {jbatch_tfrom.shape} ")
|
||||
# print(f"jbatch_ldmks dytpe = {jbatch_ldmks.dtype}, shape = {jbatch_ldmks.shape}, max={jbatch_ldmks.max()}, min={jbatch_ldmks.min()} ")
|
||||
|
||||
# save data
|
||||
for k,kname in enumerate(jbatch_name):
|
||||
kpath_fcrop = ipath_fcrop.joinpath(kname + ".jpg")
|
||||
kpath_tfrom = ipath_tfrom.joinpath(kname + ".npy")
|
||||
kpath_lcrop = ipath_lcrop.joinpath(kname + ".txt")
|
||||
|
||||
if kpath_fcrop.exists() and kpath_tfrom.exists() and kpath_lcrop.exists():
|
||||
continue
|
||||
|
||||
np.save(kpath_tfrom, jbatch_tfrom[k])
|
||||
np.savetxt(kpath_lcrop, jbatch_ldmks[k], fmt=" %3d")
|
||||
cv2.imwrite(str(kpath_fcrop), jbatch_crop[k])
|
||||
|
||||
# cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_{vis_name}.jpg")), img)
|
||||
# break
|
||||
@@ -0,0 +1,81 @@
|
||||
from torch.utils.data import Dataset, DataLoader
|
||||
import cv2
|
||||
import torch
|
||||
import numpy as np
|
||||
from pathlib2 import Path
|
||||
from face_alignment import FaceAlignment, LandmarksType
|
||||
from zmq import device
|
||||
|
||||
|
||||
class ImagesDataset(Dataset):
|
||||
def __init__(self, path_folder:Path):
|
||||
|
||||
self.path_folder = path_folder
|
||||
self.list_image = sorted(path_folder.glob("*.jpg"), reverse=False)
|
||||
print(f"Have {len(self.list_image)} images, like {self.list_image[:3]}")
|
||||
|
||||
|
||||
def __len__(self):
|
||||
return len(self.list_image)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
path_frame = self.list_image[idx]
|
||||
# image = Image.open(str(path_frame)).convert('RGB') # (h, w, 3)
|
||||
# image = np.asarray(image)
|
||||
image = cv2.imread(str(path_frame)).astype(np.float32)
|
||||
return {"image_name": path_frame.stem, "image": image}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
|
||||
vpath_videos = sorted(path_data.glob("*"), reverse=True)
|
||||
print(f"Have {len(vpath_videos)} dir files")
|
||||
|
||||
device = "cuda:7"
|
||||
model = FaceAlignment(LandmarksType._2D, device=device, face_detector='sfd')
|
||||
print(f"load FaceAlignment model in {device}")
|
||||
|
||||
# IDs = ["2-23min"]
|
||||
# for each word
|
||||
for i, ipath_item in enumerate(vpath_videos[16:]):
|
||||
iname = ipath_item.stem
|
||||
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
|
||||
|
||||
# if iname not in IDs: continue
|
||||
|
||||
ipath_infor = ipath_item.joinpath("video/info.json")
|
||||
ipath_frame = ipath_item.joinpath("frames")
|
||||
ipath_mask = ipath_item.joinpath("skin_mask")
|
||||
ipath_mask.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# check
|
||||
num_frame = len(list(ipath_frame.glob("*.jpg")))
|
||||
num_mask = len(list(ipath_mask.glob("*.jpg")))
|
||||
if num_frame == num_mask:
|
||||
print(f"\n Skip: have already done!")
|
||||
continue
|
||||
|
||||
vframe_frame = list(ipath_frame.glob("*.jpg"))
|
||||
print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
|
||||
|
||||
|
||||
for k, kpath_ in enumerate(dloader):
|
||||
ibatch_name = ibatch["image_name"]
|
||||
ibatch_data = ibatch["image"].to(device) # B x H x W x 3
|
||||
ibatch_data = ibatch_data.permute(0, 3, 1, 2) # B x H x W x 3
|
||||
# print(f"ibatch_data shape = {ibatch_data.shape}, path={ibatch_name[:3]}")
|
||||
if k%100 == 0:
|
||||
print(f"batching {k}/{len(dloader)} ... ")
|
||||
|
||||
pred = model.get_landmarks_from_batch(ibatch_data, return_landmark_score=False)
|
||||
# print(f"pred len = {len(pred)}, type= {type(pred)}, [0] shape={pred[0].shape}")
|
||||
|
||||
# save landmarks
|
||||
for jldmk, jname in zip(pred, ibatch_name):
|
||||
jpath_ldmk = ipath_ldmks.joinpath(jname + ".txt")
|
||||
np.savetxt(jpath_ldmk, jldmk, fmt=" %3d")
|
||||
|
||||
|
||||
|
||||
# break
|
||||
@@ -0,0 +1,31 @@
|
||||
|
||||
import os
|
||||
from pathlib2 import Path
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
|
||||
vpath_videos = sorted(path_data.glob("*"), reverse=False)
|
||||
print(f"Have {len(vpath_videos)} dir files")
|
||||
|
||||
|
||||
# IDs = ["2-23min"]
|
||||
# for each word
|
||||
for i, ipath_item in enumerate(vpath_videos):
|
||||
iname = ipath_item.stem
|
||||
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
|
||||
|
||||
# if iname not in IDs: continue
|
||||
ipath_fcrop = ipath_item.joinpath("frames_crop")
|
||||
ipath_tfrom = ipath_item.joinpath("frames_crop_tform")
|
||||
|
||||
|
||||
if ipath_fcrop.exists():
|
||||
cmd = f"rm -rf {str(ipath_fcrop)}"
|
||||
print("RUN: ", cmd)
|
||||
os.system(cmd)
|
||||
|
||||
if ipath_tfrom.exists():
|
||||
cmd = f"rm -rf {str(ipath_tfrom)}"
|
||||
print("RUN: ", cmd)
|
||||
os.system(cmd)
|
||||
Executable
+683
@@ -0,0 +1,683 @@
|
||||
import torch.nn as nn
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from functools import reduce
|
||||
import torchvision.models as models
|
||||
import torchfile
|
||||
|
||||
def l2_distance(verts1, verts2):
|
||||
return torch.sqrt(((verts1 - verts2)**2).sum(2)).mean(1).mean()
|
||||
|
||||
### VAE
|
||||
def kl_loss(texcode):
|
||||
"""
|
||||
recon_x: generating images
|
||||
x: origin images
|
||||
mu: latent mean
|
||||
logvar: latent log variance
|
||||
"""
|
||||
mu, logvar = texcode[:,:128], texcode[:,128:]
|
||||
KLD_element = mu.pow(2).add_(logvar.exp()).mul_(-1).add_(1).add_(logvar)
|
||||
KLD = torch.sum(KLD_element).mul_(-0.5)
|
||||
# KL divergence
|
||||
return KLD
|
||||
|
||||
### ------------------------------------- Losses/Regularizations for shading
|
||||
# white shading
|
||||
# uv_mask_tf = tf.expand_dims(tf.expand_dims(tf.constant( self.uv_mask, dtype = tf.float32 ), 0), -1)
|
||||
# mean_shade = tf.reduce_mean( tf.multiply(shade_300W, uv_mask_tf) , axis=[0,1,2]) * 16384 / 10379
|
||||
# G_loss_white_shading = 10*norm_loss(mean_shade, 0.99*tf.ones([1, 3], dtype=tf.float32), loss_type = "l2")
|
||||
def shading_white_loss(shading):
|
||||
'''
|
||||
regularize lighting: assume lights close to white
|
||||
'''
|
||||
# rgb_diff = (shading[:,0] - shading[:,1])**2 + (shading[:,0] - shading[:,2])**2 + (shading[:,1] - shading[:,2])**2
|
||||
# rgb_diff = (shading[:,0].mean([1,2]) - shading[:,1].mean([1,2]))**2 + (shading[:,0].mean([1,2]) - shading[:,2].mean([1,2]))**2 + (shading[:,1].mean([1,2]) - shading[:,2].mean([1,2]))**2
|
||||
# rgb_diff = (shading.mean([2, 3]) - torch.ones((shading.shape[0], 3)).float().cuda())**2
|
||||
rgb_diff = (shading.mean([0, 2, 3]) - 0.99)**2
|
||||
return rgb_diff.mean()
|
||||
|
||||
def shading_smooth_loss(shading):
|
||||
'''
|
||||
assume: shading should be smooth
|
||||
ref: Lifting AutoEncoders: Unsupervised Learning of a Fully-Disentangled 3D Morphable Model using Deep Non-Rigid Structure from Motion
|
||||
'''
|
||||
dx = shading[:,:,1:-1,1:] - shading[:,:,1:-1,:-1]
|
||||
dy = shading[:,:,1:,1:-1] - shading[:,:,:-1,1:-1]
|
||||
gradient_image = (dx**2).mean() + (dy**2).mean()
|
||||
return gradient_image.mean()
|
||||
|
||||
### ------------------------------------- Losses/Regularizations for albedo
|
||||
# texture_300W_labels_chromaticity = (texture_300W_labels + 1.0)/2.0
|
||||
# texture_300W_labels_chromaticity = tf.divide(texture_300W_labels_chromaticity, tf.reduce_sum(texture_300W_labels_chromaticity, axis=[-1], keep_dims=True) + 1e-6)
|
||||
|
||||
|
||||
# w_u = tf.stop_gradient(tf.exp(-15*tf.norm( texture_300W_labels_chromaticity[:, :-1, :, :] - texture_300W_labels_chromaticity[:, 1:, :, :], ord='euclidean', axis=-1, keep_dims=True)) * texture_vis_mask[:, :-1, :, :] )
|
||||
# G_loss_local_albedo_const_u = tf.reduce_mean(norm_loss( albedo_300W[:, :-1, :, :], albedo_300W[:, 1:, :, :], loss_type = 'l2,1', reduce_mean=False, p=0.8) * w_u) / tf.reduce_sum(w_u+1e-6)
|
||||
|
||||
|
||||
# w_v = tf.stop_gradient(tf.exp(-15*tf.norm( texture_300W_labels_chromaticity[:, :, :-1, :] - texture_300W_labels_chromaticity[:, :, 1:, :], ord='euclidean', axis=-1, keep_dims=True)) * texture_vis_mask[:, :, :-1, :] )
|
||||
# G_loss_local_albedo_const_v = tf.reduce_mean(norm_loss( albedo_300W[:, :, :-1, :], albedo_300W[:, :, 1:, :], loss_type = 'l2,1', reduce_mean=False, p=0.8) * w_v) / tf.reduce_sum(w_v+1e-6)
|
||||
|
||||
# G_loss_local_albedo_const = (G_loss_local_albedo_const_u + G_loss_local_albedo_const_v)*10
|
||||
|
||||
def albedo_constancy_loss(albedo, alpha = 15, weight = 1.):
|
||||
'''
|
||||
for similarity of neighbors
|
||||
ref: Self-supervised Multi-level Face Model Learning for Monocular Reconstruction at over 250 Hz
|
||||
Towards High-fidelity Nonlinear 3D Face Morphable Model
|
||||
'''
|
||||
albedo_chromaticity = albedo/(torch.sum(albedo, dim=1, keepdim=True) + 1e-6)
|
||||
weight_x = torch.exp(-alpha*(albedo_chromaticity[:,:,1:,:] - albedo_chromaticity[:,:,:-1,:])**2).detach()
|
||||
weight_y = torch.exp(-alpha*(albedo_chromaticity[:,:,:,1:] - albedo_chromaticity[:,:,:,:-1])**2).detach()
|
||||
albedo_const_loss_x = ((albedo[:,:,1:,:] - albedo[:,:,:-1,:])**2)*weight_x
|
||||
albedo_const_loss_y = ((albedo[:,:,:,1:] - albedo[:,:,:,:-1])**2)*weight_y
|
||||
|
||||
albedo_constancy_loss = albedo_const_loss_x.mean() + albedo_const_loss_y.mean()
|
||||
return albedo_constancy_loss*weight
|
||||
|
||||
def albedo_ring_loss(texcode, ring_elements, margin, weight=1.):
|
||||
"""
|
||||
computes ring loss for ring_outputs before FLAME decoder
|
||||
Inputs:
|
||||
ring_outputs = a list containing N streams of the ring; len(ring_outputs) = N
|
||||
Each ring_outputs[i] is a tensor of (batch_size X shape_dim_num)
|
||||
Aim is to force each row (same subject) of each stream to produce same shape
|
||||
Each row of first N-1 strams are of the same subject and
|
||||
the Nth stream is the different subject
|
||||
"""
|
||||
tot_ring_loss = (texcode[0]-texcode[0]).sum()
|
||||
diff_stream = texcode[-1]
|
||||
count = 0.0
|
||||
for i in range(ring_elements - 1):
|
||||
for j in range(ring_elements - 1):
|
||||
pd = (texcode[i] - texcode[j]).pow(2).sum(1)
|
||||
nd = (texcode[i] - diff_stream).pow(2).sum(1)
|
||||
tot_ring_loss = torch.add(tot_ring_loss,
|
||||
(torch.nn.functional.relu(margin + pd - nd).mean()))
|
||||
count += 1.0
|
||||
|
||||
tot_ring_loss = (1.0/count) * tot_ring_loss
|
||||
return tot_ring_loss * weight
|
||||
|
||||
def albedo_same_loss(albedo, ring_elements, weight=1.):
|
||||
"""
|
||||
computes ring loss for ring_outputs before FLAME decoder
|
||||
Inputs:
|
||||
ring_outputs = a list containing N streams of the ring; len(ring_outputs) = N
|
||||
Each ring_outputs[i] is a tensor of (batch_size X shape_dim_num)
|
||||
Aim is to force each row (same subject) of each stream to produce same shape
|
||||
Each row of first N-1 strams are of the same subject and
|
||||
the Nth stream is the different subject
|
||||
"""
|
||||
loss = 0
|
||||
for i in range(ring_elements - 1):
|
||||
for j in range(ring_elements - 1):
|
||||
pd = (albedo[i] - albedo[j]).pow(2).mean()
|
||||
loss += pd
|
||||
loss = loss/ring_elements
|
||||
return loss * weight
|
||||
|
||||
### ------------------------------------- Losses/Regularizations for vertices
|
||||
def batch_kp_2d_l1_loss(real_2d_kp, predicted_2d_kp, weights=None):
|
||||
"""
|
||||
Computes the l1 loss between the ground truth keypoints and the predicted keypoints
|
||||
Inputs:
|
||||
kp_gt : N x K x 3
|
||||
kp_pred: N x K x 2
|
||||
"""
|
||||
if weights is not None:
|
||||
real_2d_kp[:,:,2] = weights[None,:]*real_2d_kp[:,:,2]
|
||||
kp_gt = real_2d_kp.view(-1, 3)
|
||||
|
||||
kp_pred = predicted_2d_kp.contiguous().view(-1, 2)
|
||||
vis = kp_gt[:, 2]
|
||||
k = torch.sum(vis) * 2.0 + 1e-8
|
||||
dif_abs = torch.abs(kp_gt[:, :2] - kp_pred).sum(1)
|
||||
|
||||
return torch.matmul(dif_abs, vis) * 1.0 / k
|
||||
|
||||
|
||||
def landmark_loss(predicted_landmarks, landmarks_gt, weight=1.):
|
||||
# (predicted_theta, predicted_verts, predicted_landmarks) = ringnet_outputs[-1]
|
||||
if torch.is_tensor(landmarks_gt) is not True:
|
||||
real_2d = torch.cat(landmarks_gt).cuda()
|
||||
else:
|
||||
real_2d = torch.cat([landmarks_gt, torch.ones((landmarks_gt.shape[0], 68, 1)).cuda()], dim=-1)
|
||||
# real_2d = torch.cat(landmarks_gt).cuda()
|
||||
|
||||
loss_lmk_2d = batch_kp_2d_l1_loss(real_2d, predicted_landmarks)
|
||||
return loss_lmk_2d * weight
|
||||
|
||||
|
||||
def eye_dis(landmarks):
|
||||
# left eye: [38,42], [39,41] - 1
|
||||
# right eye: [44,48], [45,47] -1
|
||||
eye_up = landmarks[:,[37, 38, 43, 44], :]
|
||||
eye_bottom = landmarks[:,[41, 40, 47, 46], :]
|
||||
dis = torch.sqrt(((eye_up - eye_bottom)**2).sum(2)) #[bz, 4]
|
||||
return dis
|
||||
|
||||
|
||||
def eyed_loss(predicted_landmarks, landmarks_gt, weight=1.):
|
||||
if torch.is_tensor(landmarks_gt) is not True:
|
||||
real_2d = torch.cat(landmarks_gt).cuda()
|
||||
else:
|
||||
real_2d = torch.cat([landmarks_gt, torch.ones((landmarks_gt.shape[0], 68, 1)).cuda()], dim=-1)
|
||||
|
||||
pred_eyed = eye_dis(predicted_landmarks[:,:,:2])
|
||||
gt_eyed = eye_dis(real_2d[:,:,:2])
|
||||
|
||||
loss = (pred_eyed - gt_eyed).abs().mean()
|
||||
return loss
|
||||
|
||||
|
||||
def lip_dis(landmarks):
|
||||
# up inner lip: [62, 63, 64] - 1
|
||||
# down innder lip: [68, 67, 66] -1
|
||||
lip_up = landmarks[:,[61, 62, 63], :]
|
||||
lip_down = landmarks[:,[67, 66, 65], :]
|
||||
dis = torch.sqrt(((lip_up - lip_down)**2).sum(2)) #[bz, 4]
|
||||
return dis
|
||||
|
||||
|
||||
def lipd_loss(predicted_landmarks, landmarks_gt, weight=1.):
|
||||
if torch.is_tensor(landmarks_gt) is not True:
|
||||
real_2d = torch.cat(landmarks_gt).cuda()
|
||||
else:
|
||||
real_2d = torch.cat([landmarks_gt, torch.ones((landmarks_gt.shape[0], 68, 1)).cuda()], dim=-1)
|
||||
|
||||
pred_lipd = lip_dis(predicted_landmarks[:,:,:2])
|
||||
gt_lipd = lip_dis(real_2d[:,:,:2])
|
||||
|
||||
loss = (pred_lipd - gt_lipd).abs().mean()
|
||||
return loss
|
||||
|
||||
|
||||
def weighted_landmark_loss(predicted_landmarks, landmarks_gt):
|
||||
# smaller inner landmark weights
|
||||
# (predicted_theta, predicted_verts, predicted_landmarks) = ringnet_outputs[-1]
|
||||
# import ipdb; ipdb.set_trace()
|
||||
real_2d = landmarks_gt
|
||||
|
||||
weights = torch.ones((68,)).cuda()
|
||||
weights[5:7] = 2
|
||||
weights[10:12] = 2
|
||||
# nose points
|
||||
weights[27:36] = 1.5
|
||||
weights[30] = 3
|
||||
weights[31] = 3
|
||||
weights[35] = 3
|
||||
# inner mouth
|
||||
weights[60:68] = 1.5
|
||||
weights[48:60] = 1.5
|
||||
weights[48] = 3
|
||||
weights[54] = 3
|
||||
|
||||
loss_lmk_2d = batch_kp_2d_l1_loss(real_2d, predicted_landmarks, weights)
|
||||
return loss_lmk_2d
|
||||
|
||||
|
||||
def landmark_loss_tensor(predicted_landmarks, landmarks_gt, weights=None):
|
||||
# (predicted_theta, predicted_verts, predicted_landmarks) = ringnet_outputs[-1]
|
||||
loss_lmk_2d = batch_kp_2d_l1_loss(landmarks_gt, predicted_landmarks, weights)
|
||||
|
||||
return loss_lmk_2d
|
||||
|
||||
|
||||
|
||||
def ring_loss(ring_outputs, ring_type, margin, weight=1.):
|
||||
"""
|
||||
computes ring loss for ring_outputs before FLAME decoder
|
||||
Inputs:
|
||||
ring_outputs = a list containing N streams of the ring; len(ring_outputs) = N
|
||||
Each ring_outputs[i] is a tensor of (batch_size X shape_dim_num)
|
||||
Aim is to force each row (same subject) of each stream to produce same shape
|
||||
Each row of first N-1 strams are of the same subject and
|
||||
the Nth stream is the different subject
|
||||
"""
|
||||
tot_ring_loss = (ring_outputs[0]-ring_outputs[0]).sum()
|
||||
if ring_type == '51':
|
||||
diff_stream = ring_outputs[-1]
|
||||
count = 0.0
|
||||
for i in range(6):
|
||||
for j in range(6):
|
||||
pd = (ring_outputs[i] - ring_outputs[j]).pow(2).sum(1)
|
||||
nd = (ring_outputs[i] - diff_stream).pow(2).sum(1)
|
||||
tot_ring_loss = torch.add(tot_ring_loss,
|
||||
(torch.nn.functional.relu(margin + pd - nd).mean()))
|
||||
count += 1.0
|
||||
|
||||
elif ring_type == '33':
|
||||
perm_code = [(0, 1, 3),
|
||||
(0, 1, 4),
|
||||
(0, 1, 5),
|
||||
(0, 2, 3),
|
||||
(0, 2, 4),
|
||||
(0, 2, 5),
|
||||
(1, 0, 3),
|
||||
(1, 0, 4),
|
||||
(1, 0, 5),
|
||||
(1, 2, 3),
|
||||
(1, 2, 4),
|
||||
(1, 2, 5),
|
||||
(2, 0, 3),
|
||||
(2, 0, 4),
|
||||
(2, 0, 5),
|
||||
(2, 1, 3),
|
||||
(2, 1, 4),
|
||||
(2, 1, 5)]
|
||||
count = 0.0
|
||||
for i in perm_code:
|
||||
pd = (ring_outputs[i[0]] - ring_outputs[i[1]]).pow(2).sum(1)
|
||||
nd = (ring_outputs[i[1]] - ring_outputs[i[2]]).pow(2).sum(1)
|
||||
tot_ring_loss = torch.add(tot_ring_loss,
|
||||
(torch.nn.functional.relu(margin + pd - nd).mean()))
|
||||
count += 1.0
|
||||
|
||||
tot_ring_loss = (1.0/count) * tot_ring_loss
|
||||
|
||||
return tot_ring_loss * weight
|
||||
|
||||
|
||||
######################################## images/features/perceptual
|
||||
def gradient_dif_loss(prediction, gt):
|
||||
prediction_diff_x = prediction[:,:,1:-1,1:] - prediction[:,:,1:-1,:-1]
|
||||
prediction_diff_y = prediction[:,:,1:,1:-1] - prediction[:,:,1:,1:-1]
|
||||
gt_x = gt[:,:,1:-1,1:] - gt[:,:,1:-1,:-1]
|
||||
gt_y = gt[:,:,1:,1:-1] - gt[:,:,:-1,1:-1]
|
||||
diff = torch.mean((prediction_diff_x-gt_x)**2) + torch.mean((prediction_diff_y-gt_y)**2)
|
||||
return diff.mean()
|
||||
|
||||
|
||||
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_hq_loss(prediction, gt):
|
||||
# https://torchgeometry.readthedocs.io/en/latest/_modules/kornia/filters/laplacian.html
|
||||
b, c, h, w = prediction.shape
|
||||
kernel_size = 3
|
||||
kernel = get_laplacian_kernel2d(kernel_size).to(prediction.device).to(prediction.dtype)
|
||||
kernel = kernel.repeat(c, 1, 1, 1)
|
||||
padding = (kernel_size - 1) // 2
|
||||
lap_pre = F.conv2d(prediction, kernel, padding=padding, stride=1, groups=c)
|
||||
lap_gt = F.conv2d(gt, kernel, padding=padding, stride=1, groups=c)
|
||||
|
||||
return ((lap_pre - lap_gt)**2).mean()
|
||||
|
||||
|
||||
##
|
||||
class VGG19FeatLayer(nn.Module):
|
||||
def __init__(self):
|
||||
super(VGG19FeatLayer, self).__init__()
|
||||
self.vgg19 = models.vgg19(pretrained=True).features.eval().cuda()
|
||||
self.mean = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).cuda()
|
||||
self.std = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).cuda()
|
||||
|
||||
def forward(self, x):
|
||||
out = {}
|
||||
x = x - self.mean
|
||||
x = x/self.std
|
||||
ci = 1
|
||||
ri = 0
|
||||
for layer in self.vgg19.children():
|
||||
if isinstance(layer, nn.Conv2d):
|
||||
ri += 1
|
||||
name = 'conv{}_{}'.format(ci, ri)
|
||||
elif isinstance(layer, nn.ReLU):
|
||||
ri += 1
|
||||
name = 'relu{}_{}'.format(ci, ri)
|
||||
layer = nn.ReLU(inplace=False)
|
||||
elif isinstance(layer, nn.MaxPool2d):
|
||||
ri = 0
|
||||
name = 'pool_{}'.format(ci)
|
||||
ci += 1
|
||||
elif isinstance(layer, nn.BatchNorm2d):
|
||||
name = 'bn_{}'.format(ci)
|
||||
else:
|
||||
raise RuntimeError('Unrecognized layer: {}'.format(layer.__class__.__name__))
|
||||
x = layer(x)
|
||||
out[name] = x
|
||||
# print([x for x in out])
|
||||
return out
|
||||
|
||||
|
||||
class IDMRFLoss(nn.Module):
|
||||
def __init__(self, featlayer=VGG19FeatLayer):
|
||||
super(IDMRFLoss, self).__init__()
|
||||
self.featlayer = featlayer()
|
||||
self.feat_style_layers = {'relu3_2': 1.0, 'relu4_2': 1.0}
|
||||
self.feat_content_layers = {'relu4_2': 1.0}
|
||||
self.bias = 1.0
|
||||
self.nn_stretch_sigma = 0.5
|
||||
self.lambda_style = 1.0
|
||||
self.lambda_content = 1.0
|
||||
|
||||
def sum_normalize(self, featmaps):
|
||||
reduce_sum = torch.sum(featmaps, dim=1, keepdim=True)
|
||||
return featmaps / reduce_sum
|
||||
|
||||
def patch_extraction(self, featmaps):
|
||||
patch_size = 1
|
||||
patch_stride = 1
|
||||
patches_as_depth_vectors = featmaps.unfold(2, patch_size, patch_stride).unfold(3, patch_size, patch_stride)
|
||||
self.patches_OIHW = patches_as_depth_vectors.permute(0, 2, 3, 1, 4, 5)
|
||||
dims = self.patches_OIHW.size()
|
||||
self.patches_OIHW = self.patches_OIHW.view(-1, dims[3], dims[4], dims[5])
|
||||
return self.patches_OIHW
|
||||
|
||||
def compute_relative_distances(self, cdist):
|
||||
epsilon = 1e-5
|
||||
div = torch.min(cdist, dim=1, keepdim=True)[0]
|
||||
relative_dist = cdist / (div + epsilon)
|
||||
return relative_dist
|
||||
|
||||
def exp_norm_relative_dist(self, relative_dist):
|
||||
scaled_dist = relative_dist
|
||||
dist_before_norm = torch.exp((self.bias - scaled_dist)/self.nn_stretch_sigma)
|
||||
self.cs_NCHW = self.sum_normalize(dist_before_norm)
|
||||
return self.cs_NCHW
|
||||
|
||||
def mrf_loss(self, gen, tar):
|
||||
meanT = torch.mean(tar, 1, keepdim=True)
|
||||
gen_feats, tar_feats = gen - meanT, tar - meanT
|
||||
|
||||
gen_feats_norm = torch.norm(gen_feats, p=2, dim=1, keepdim=True)
|
||||
tar_feats_norm = torch.norm(tar_feats, p=2, dim=1, keepdim=True)
|
||||
|
||||
gen_normalized = gen_feats / gen_feats_norm
|
||||
tar_normalized = tar_feats / tar_feats_norm
|
||||
|
||||
cosine_dist_l = []
|
||||
BatchSize = tar.size(0)
|
||||
|
||||
for i in range(BatchSize):
|
||||
tar_feat_i = tar_normalized[i:i+1, :, :, :]
|
||||
gen_feat_i = gen_normalized[i:i+1, :, :, :]
|
||||
patches_OIHW = self.patch_extraction(tar_feat_i)
|
||||
|
||||
cosine_dist_i = F.conv2d(gen_feat_i, patches_OIHW)
|
||||
cosine_dist_l.append(cosine_dist_i)
|
||||
cosine_dist = torch.cat(cosine_dist_l, dim=0)
|
||||
cosine_dist_zero_2_one = - (cosine_dist - 1) / 2
|
||||
relative_dist = self.compute_relative_distances(cosine_dist_zero_2_one)
|
||||
rela_dist = self.exp_norm_relative_dist(relative_dist)
|
||||
dims_div_mrf = rela_dist.size()
|
||||
k_max_nc = torch.max(rela_dist.view(dims_div_mrf[0], dims_div_mrf[1], -1), dim=2)[0]
|
||||
div_mrf = torch.mean(k_max_nc, dim=1)
|
||||
div_mrf_sum = -torch.log(div_mrf)
|
||||
div_mrf_sum = torch.sum(div_mrf_sum)
|
||||
return div_mrf_sum
|
||||
|
||||
def forward(self, gen, tar):
|
||||
## gen: [bz,3,h,w] rgb [0,1]
|
||||
gen_vgg_feats = self.featlayer(gen)
|
||||
tar_vgg_feats = self.featlayer(tar)
|
||||
style_loss_list = [self.feat_style_layers[layer] * self.mrf_loss(gen_vgg_feats[layer], tar_vgg_feats[layer]) for layer in self.feat_style_layers]
|
||||
self.style_loss = reduce(lambda x, y: x+y, style_loss_list) * self.lambda_style
|
||||
|
||||
content_loss_list = [self.feat_content_layers[layer] * self.mrf_loss(gen_vgg_feats[layer], tar_vgg_feats[layer]) for layer in self.feat_content_layers]
|
||||
self.content_loss = reduce(lambda x, y: x+y, content_loss_list) * self.lambda_content
|
||||
|
||||
return self.style_loss + self.content_loss
|
||||
|
||||
# loss = 0
|
||||
# for key in self.feat_style_layers.keys():
|
||||
# loss += torch.mean((gen_vgg_feats[key] - tar_vgg_feats[key])**2)
|
||||
# return loss
|
||||
|
||||
######################################################## vgg16 face
|
||||
|
||||
class VGG_16(nn.Module):
|
||||
"""
|
||||
Main Class
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
"""
|
||||
Constructor
|
||||
"""
|
||||
super().__init__()
|
||||
self.block_size = [2, 2, 3, 3, 3]
|
||||
self.conv_1_1 = nn.Conv2d(3, 64, 3, stride=1, padding=1)
|
||||
self.conv_1_2 = nn.Conv2d(64, 64, 3, stride=1, padding=1)
|
||||
self.conv_2_1 = nn.Conv2d(64, 128, 3, stride=1, padding=1)
|
||||
self.conv_2_2 = nn.Conv2d(128, 128, 3, stride=1, padding=1)
|
||||
self.conv_3_1 = nn.Conv2d(128, 256, 3, stride=1, padding=1)
|
||||
self.conv_3_2 = nn.Conv2d(256, 256, 3, stride=1, padding=1)
|
||||
self.conv_3_3 = nn.Conv2d(256, 256, 3, stride=1, padding=1)
|
||||
self.conv_4_1 = nn.Conv2d(256, 512, 3, stride=1, padding=1)
|
||||
self.conv_4_2 = nn.Conv2d(512, 512, 3, stride=1, padding=1)
|
||||
self.conv_4_3 = nn.Conv2d(512, 512, 3, stride=1, padding=1)
|
||||
self.conv_5_1 = nn.Conv2d(512, 512, 3, stride=1, padding=1)
|
||||
self.conv_5_2 = nn.Conv2d(512, 512, 3, stride=1, padding=1)
|
||||
self.conv_5_3 = nn.Conv2d(512, 512, 3, stride=1, padding=1)
|
||||
self.fc6 = nn.Linear(512 * 7 * 7, 4096)
|
||||
self.fc7 = nn.Linear(4096, 4096)
|
||||
self.fc8 = nn.Linear(4096, 2622)
|
||||
self.mean = torch.Tensor(np.array([129.1863, 104.7624, 93.5940])/255.).float().view(1, 3, 1, 1).cuda()
|
||||
# self.mean = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).cuda()
|
||||
|
||||
def load_weights(self, path="pretrained/VGG_FACE.t7"):
|
||||
""" Function to load luatorch pretrained
|
||||
Args:
|
||||
path: path for the luatorch pretrained
|
||||
"""
|
||||
model = torchfile.load(path)
|
||||
counter = 1
|
||||
block = 1
|
||||
for i, layer in enumerate(model.modules):
|
||||
if layer.weight is not None:
|
||||
if block <= 5:
|
||||
self_layer = getattr(self, "conv_%d_%d" % (block, counter))
|
||||
counter += 1
|
||||
if counter > self.block_size[block - 1]:
|
||||
counter = 1
|
||||
block += 1
|
||||
self_layer.weight.data[...] = torch.tensor(layer.weight).view_as(self_layer.weight)[...]
|
||||
self_layer.bias.data[...] = torch.tensor(layer.bias).view_as(self_layer.bias)[...]
|
||||
else:
|
||||
self_layer = getattr(self, "fc%d" % (block))
|
||||
block += 1
|
||||
self_layer.weight.data[...] = torch.tensor(layer.weight).view_as(self_layer.weight)[...]
|
||||
self_layer.bias.data[...] = torch.tensor(layer.bias).view_as(self_layer.bias)[...]
|
||||
|
||||
def forward(self, x):
|
||||
""" Pytorch forward
|
||||
Args:
|
||||
x: input image (224x224)
|
||||
Returns: class logits
|
||||
"""
|
||||
out = {}
|
||||
x = x - self.mean
|
||||
x = F.relu(self.conv_1_1(x))
|
||||
x = F.relu(self.conv_1_2(x))
|
||||
x = F.max_pool2d(x, 2, 2)
|
||||
x = F.relu(self.conv_2_1(x))
|
||||
x = F.relu(self.conv_2_2(x))
|
||||
x = F.max_pool2d(x, 2, 2)
|
||||
x = F.relu(self.conv_3_1(x))
|
||||
x = F.relu(self.conv_3_2(x))
|
||||
out['relu3_2'] = x
|
||||
x = F.relu(self.conv_3_3(x))
|
||||
x = F.max_pool2d(x, 2, 2)
|
||||
x = F.relu(self.conv_4_1(x))
|
||||
x = F.relu(self.conv_4_2(x))
|
||||
out['relu4_2'] = x
|
||||
x = F.relu(self.conv_4_3(x))
|
||||
x = F.max_pool2d(x, 2, 2)
|
||||
x = F.relu(self.conv_5_1(x))
|
||||
x = F.relu(self.conv_5_2(x))
|
||||
x = F.relu(self.conv_5_3(x))
|
||||
x = F.max_pool2d(x, 2, 2)
|
||||
x = x.view(x.size(0), -1)
|
||||
x = F.relu(self.fc6(x))
|
||||
x = F.dropout(x, 0.5, self.training)
|
||||
x = F.relu(self.fc7(x))
|
||||
x = F.dropout(x, 0.5, self.training)
|
||||
x = self.fc8(x)
|
||||
out['last'] = x
|
||||
return out
|
||||
|
||||
|
||||
class VGGLoss(nn.Module):
|
||||
def __init__(self):
|
||||
super(VGGLoss, self).__init__()
|
||||
self.featlayer = VGG_16().float()
|
||||
self.featlayer.load_weights(path="data/face_recognition_model/vgg_face_torch/VGG_FACE.t7")
|
||||
self.featlayer = self.featlayer.cuda().eval()
|
||||
self.feat_style_layers = {'relu3_2': 1.0, 'relu4_2': 1.0}
|
||||
self.feat_content_layers = {'relu4_2': 1.0}
|
||||
self.bias = 1.0
|
||||
self.nn_stretch_sigma = 0.5
|
||||
self.lambda_style = 1.0
|
||||
self.lambda_content = 1.0
|
||||
|
||||
def sum_normalize(self, featmaps):
|
||||
reduce_sum = torch.sum(featmaps, dim=1, keepdim=True)
|
||||
return featmaps / reduce_sum
|
||||
|
||||
def patch_extraction(self, featmaps):
|
||||
patch_size = 1
|
||||
patch_stride = 1
|
||||
patches_as_depth_vectors = featmaps.unfold(2, patch_size, patch_stride).unfold(3, patch_size, patch_stride)
|
||||
self.patches_OIHW = patches_as_depth_vectors.permute(0, 2, 3, 1, 4, 5)
|
||||
dims = self.patches_OIHW.size()
|
||||
self.patches_OIHW = self.patches_OIHW.view(-1, dims[3], dims[4], dims[5])
|
||||
return self.patches_OIHW
|
||||
|
||||
def compute_relative_distances(self, cdist):
|
||||
epsilon = 1e-5
|
||||
div = torch.min(cdist, dim=1, keepdim=True)[0]
|
||||
relative_dist = cdist / (div + epsilon)
|
||||
return relative_dist
|
||||
|
||||
def exp_norm_relative_dist(self, relative_dist):
|
||||
scaled_dist = relative_dist
|
||||
dist_before_norm = torch.exp((self.bias - scaled_dist)/self.nn_stretch_sigma)
|
||||
self.cs_NCHW = self.sum_normalize(dist_before_norm)
|
||||
return self.cs_NCHW
|
||||
|
||||
def mrf_loss(self, gen, tar):
|
||||
meanT = torch.mean(tar, 1, keepdim=True)
|
||||
gen_feats, tar_feats = gen - meanT, tar - meanT
|
||||
|
||||
gen_feats_norm = torch.norm(gen_feats, p=2, dim=1, keepdim=True)
|
||||
tar_feats_norm = torch.norm(tar_feats, p=2, dim=1, keepdim=True)
|
||||
|
||||
gen_normalized = gen_feats / gen_feats_norm
|
||||
tar_normalized = tar_feats / tar_feats_norm
|
||||
|
||||
cosine_dist_l = []
|
||||
BatchSize = tar.size(0)
|
||||
|
||||
for i in range(BatchSize):
|
||||
tar_feat_i = tar_normalized[i:i+1, :, :, :]
|
||||
gen_feat_i = gen_normalized[i:i+1, :, :, :]
|
||||
patches_OIHW = self.patch_extraction(tar_feat_i)
|
||||
|
||||
cosine_dist_i = F.conv2d(gen_feat_i, patches_OIHW)
|
||||
cosine_dist_l.append(cosine_dist_i)
|
||||
cosine_dist = torch.cat(cosine_dist_l, dim=0)
|
||||
cosine_dist_zero_2_one = - (cosine_dist - 1) / 2
|
||||
relative_dist = self.compute_relative_distances(cosine_dist_zero_2_one)
|
||||
rela_dist = self.exp_norm_relative_dist(relative_dist)
|
||||
dims_div_mrf = rela_dist.size()
|
||||
k_max_nc = torch.max(rela_dist.view(dims_div_mrf[0], dims_div_mrf[1], -1), dim=2)[0]
|
||||
div_mrf = torch.mean(k_max_nc, dim=1)
|
||||
div_mrf_sum = -torch.log(div_mrf)
|
||||
div_mrf_sum = torch.sum(div_mrf_sum)
|
||||
return div_mrf_sum
|
||||
|
||||
def forward(self, gen, tar):
|
||||
## gen: [bz,3,h,w] rgb [0,1]
|
||||
gen_vgg_feats = self.featlayer(gen)
|
||||
tar_vgg_feats = self.featlayer(tar)
|
||||
style_loss_list = [self.feat_style_layers[layer] * self.mrf_loss(gen_vgg_feats[layer], tar_vgg_feats[layer]) for layer in self.feat_style_layers]
|
||||
self.style_loss = reduce(lambda x, y: x+y, style_loss_list) * self.lambda_style
|
||||
|
||||
content_loss_list = [self.feat_content_layers[layer] * self.mrf_loss(gen_vgg_feats[layer], tar_vgg_feats[layer]) for layer in self.feat_content_layers]
|
||||
self.content_loss = reduce(lambda x, y: x+y, content_loss_list) * self.lambda_content
|
||||
|
||||
return self.style_loss + self.content_loss
|
||||
# loss = 0
|
||||
# for key in self.feat_style_layers.keys():
|
||||
# loss += torch.mean((gen_vgg_feats[key] - tar_vgg_feats[key])**2)
|
||||
# return loss
|
||||
|
||||
##############################################
|
||||
## ref: https://github.com/cydonia999/VGGFace2-pytorch
|
||||
from ..models.nn.frnet import resnet50, load_state_dict
|
||||
class VGGFace2Loss(nn.Module):
|
||||
def __init__(self, pretrained_model, pretrained_data='vggface2'):
|
||||
super(VGGFace2Loss, self).__init__()
|
||||
self.reg_model = resnet50(num_classes=8631, include_top=False).eval().cuda()
|
||||
load_state_dict(self.reg_model, pretrained_model)
|
||||
self.mean_bgr = torch.tensor([91.4953, 103.8827, 131.0912]).cuda()
|
||||
|
||||
def reg_features(self, x):
|
||||
# out = []
|
||||
margin=10
|
||||
x = x[:,:,margin:224-margin,margin:224-margin]
|
||||
# x = F.interpolate(x*2. - 1., [224,224], mode='nearest')
|
||||
x = F.interpolate(x*2. - 1., [224,224], mode='bilinear')
|
||||
# import ipdb; ipdb.set_trace()
|
||||
feature = self.reg_model(x)
|
||||
feature = feature.view(x.size(0), -1)
|
||||
return feature
|
||||
|
||||
def transform(self, img):
|
||||
# import ipdb;ipdb.set_trace()
|
||||
img = img[:, [2,1,0], :, :].permute(0,2,3,1) * 255 - self.mean_bgr
|
||||
img = img.permute(0,3,1,2)
|
||||
return img
|
||||
|
||||
def _cos_metric(self, x1, x2):
|
||||
return 1.0 - F.cosine_similarity(x1, x2, dim=1)
|
||||
|
||||
def forward(self, gen, tar, is_crop=True):
|
||||
gen = self.transform(gen)
|
||||
tar = self.transform(tar)
|
||||
|
||||
gen_out = self.reg_features(gen)
|
||||
tar_out = self.reg_features(tar)
|
||||
# loss = ((gen_out - tar_out)**2).mean()
|
||||
loss = self._cos_metric(gen_out, tar_out).mean()
|
||||
return loss
|
||||
File renamed without changes.
@@ -0,0 +1,72 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import logging
|
||||
|
||||
from .encoders import ResnetEncoder, VOCAEncoder
|
||||
from ..mesh.FLAME import FLAME, FLAMETex
|
||||
|
||||
|
||||
class Audio2Coeff(nn.Module):
|
||||
|
||||
def __init__(self, opt, opt_FLAME):
|
||||
super(Audio2Coeff, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.dim_motion = opt.dim_motion # 53
|
||||
self.dim_speech = opt.dim_speech # 29
|
||||
self.dim_hidden = opt.dim_hidden # 256
|
||||
|
||||
# creat model
|
||||
self.driven = VOCAEncoder(outsize=self.dim_motion)
|
||||
self.flame = FLAME(opt_FLAME)
|
||||
|
||||
# setup render
|
||||
|
||||
def _setup_renderer(self, model_cfg):
|
||||
set_rasterizer(self.cfg.rasterizer_type)
|
||||
self.render = SRenderY(self.image_size, obj_filename=model_cfg.topology_path, uv_size=model_cfg.uv_size, rasterizer_type=self.cfg.rasterizer_type).to(self.device)
|
||||
|
||||
# face mask for rendering details
|
||||
mask = imread(model_cfg.face_eye_mask_path).astype(np.float32)/255.; mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous()
|
||||
self.uv_face_eye_mask = F.interpolate(mask, [model_cfg.uv_size, model_cfg.uv_size]).to(self.device)
|
||||
mask = imread(model_cfg.face_mask_path).astype(np.float32)/255.; mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous()
|
||||
self.uv_face_mask = F.interpolate(mask, [model_cfg.uv_size, model_cfg.uv_size]).to(self.device)
|
||||
# displacement correction
|
||||
fixed_dis = np.load(model_cfg.fixed_displacement_path)
|
||||
self.fixed_uv_dis = torch.tensor(fixed_dis).float().to(self.device)
|
||||
# mean texture
|
||||
mean_texture = imread(model_cfg.mean_tex_path).astype(np.float32)/255.; mean_texture = torch.from_numpy(mean_texture.transpose(2,0,1))[None,:,:,:].contiguous()
|
||||
self.mean_texture = F.interpolate(mean_texture, [model_cfg.uv_size, model_cfg.uv_size]).to(self.device)
|
||||
# dense mesh template, for save detail mesh
|
||||
self.dense_template = np.load(model_cfg.dense_template_path, allow_pickle=True, encoding='latin1').item()
|
||||
|
||||
|
||||
|
||||
def forward(self, x):
|
||||
""" forward function
|
||||
Args:
|
||||
x: torch.Tensor, [nbatch x seqlen x nwind x dim_condit]
|
||||
return:
|
||||
pred: torch.Tensor, [nbatch x seqlen x dim_motion]
|
||||
"""
|
||||
(nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, 29)
|
||||
logging.debug(f"[forward] input x shape = {x.shape}")
|
||||
|
||||
# preprocessing data
|
||||
x = x.reshape(nbatch * nseqlen, 1, nwind, nfeat) # (B * nseq, 1, 16, 29)
|
||||
x = torch.transpose(x, 1, 3) # (B * nseq, 29, 16, 1)
|
||||
logging.debug(f"[forward] transpose x shape = {x.shape}")
|
||||
|
||||
feat = self.encoder(x) # (B * nseq, 50)
|
||||
logging.debug(f"[forward] encoder shape = {feat.shape}")
|
||||
|
||||
pred = self.decoder(feat) # (B * nseq, dim_motion)
|
||||
logging.debug(f"[forward] decoder shape = {pred.shape}")
|
||||
|
||||
pred = pred.reshape(nbatch, nseqlen, -1) # (B, nseq, dim_motion)
|
||||
logging.debug(f"[forward] reshape shape = {pred.shape}")
|
||||
|
||||
|
||||
return pred
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ class Audio2Mesh(nn.Module):
|
||||
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.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),
|
||||
@@ -32,13 +32,11 @@ class Audio2Mesh(nn.Module):
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
|
||||
nn.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
|
||||
|
||||
Executable
+100
@@ -0,0 +1,100 @@
|
||||
# -*- 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
|
||||
|
||||
from turtle import forward
|
||||
import numpy as np
|
||||
import torch.nn as nn
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from . import resnet
|
||||
|
||||
class ResnetEncoder(nn.Module):
|
||||
def __init__(self, dim_output, last_op=None):
|
||||
super(ResnetEncoder, self).__init__()
|
||||
feature_size = 2048
|
||||
self.encoder = resnet.load_ResNet50Model() #out: 2048
|
||||
### regressor
|
||||
self.layers = nn.Sequential(
|
||||
nn.Linear(feature_size, 1024),
|
||||
nn.ReLU(),
|
||||
nn.Linear(1024, dim_output)
|
||||
)
|
||||
self.last_op = last_op
|
||||
|
||||
def forward(self, inputs):
|
||||
features = self.encoder(inputs)
|
||||
parameters = self.layers(features)
|
||||
if self.last_op:
|
||||
parameters = self.last_op(parameters)
|
||||
return parameters
|
||||
|
||||
|
||||
class VOCAEncoder(nn.Module):
|
||||
def __init__(self, dim_output, last_op=None):
|
||||
super(VOCAEncoder, self).__init__()
|
||||
|
||||
# encoder
|
||||
self.encoder = nn.Sequential( # (nbatch, nchannel=29, H=16, W=1)
|
||||
nn.BatchNorm2d(self.dim_speech),
|
||||
|
||||
# block 1
|
||||
nn.Conv2d(self.dim_speech, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Flatten(), # 64,
|
||||
|
||||
nn.Linear(in_features=128, out_features=2048), # 128,
|
||||
nn.Tanh(),
|
||||
|
||||
nn.Linear(in_features=2048, out_features=128) # 50,
|
||||
)
|
||||
|
||||
# output
|
||||
self.layers = nn.Sequential(
|
||||
nn.Linear(in_features=128, out_features=self.dim_motion),
|
||||
)
|
||||
|
||||
self.last_op = last_op
|
||||
|
||||
|
||||
def forward(self, inputs):
|
||||
features = self.encoder(inputs)
|
||||
parameters = self.layers(features)
|
||||
if self.last_op:
|
||||
parameters = self.last_op(parameters)
|
||||
return parameters
|
||||
@@ -1,320 +0,0 @@
|
||||
# -*- 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
|
||||
Whitespace-only changes.
@@ -1,377 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,29 +0,0 @@
|
||||
## 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
|
||||
|
||||
Whitespace-only changes.
@@ -1,24 +0,0 @@
|
||||
# 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)}
|
||||
)
|
||||
@@ -1,48 +0,0 @@
|
||||
#include <torch/torch.h>
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
|
||||
std::vector<at::Tensor> 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<at::Tensor> 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<at::Tensor> 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<at::Tensor> 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
|
||||
@@ -1,319 +0,0 @@
|
||||
// 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 <ATen/ATen.h>
|
||||
|
||||
#include <cuda.h>
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
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 <typename scalar_t>
|
||||
__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 <typename scalar_t> struct point
|
||||
{
|
||||
public:
|
||||
scalar_t x;
|
||||
scalar_t y;
|
||||
|
||||
__host__ __device__ scalar_t dot(point<scalar_t> p)
|
||||
{
|
||||
return this->x * p.x + this->y * p.y;
|
||||
};
|
||||
|
||||
__host__ __device__ point<scalar_t> operator-(point<scalar_t>& p)
|
||||
{
|
||||
point<scalar_t> np;
|
||||
np.x = this->x - p.x;
|
||||
np.y = this->y - p.y;
|
||||
return np;
|
||||
};
|
||||
|
||||
__host__ __device__ point<scalar_t> operator+(point<scalar_t>& p)
|
||||
{
|
||||
point<scalar_t> np;
|
||||
np.x = this->x + p.x;
|
||||
np.y = this->y + p.y;
|
||||
return np;
|
||||
};
|
||||
|
||||
__host__ __device__ point<scalar_t> operator*(scalar_t s)
|
||||
{
|
||||
point<scalar_t> np;
|
||||
np.x = s * this->x;
|
||||
np.y = s * this->y;
|
||||
return np;
|
||||
};
|
||||
};
|
||||
|
||||
template <typename scalar_t>
|
||||
__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 <typename scalar_t>
|
||||
__device__ __forceinline__ void barycentric_weight(scalar_t *w, point<scalar_t> p, point<scalar_t> p0, point<scalar_t> p1, point<scalar_t> p2) {
|
||||
|
||||
// vectors
|
||||
point<scalar_t> 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 <typename scalar_t>
|
||||
__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<scalar_t> 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 <typename scalar_t>
|
||||
__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<scalar_t> 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<at::Tensor> 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<scalar_t><<<blocks_1, threads>>>(
|
||||
face_vertices.data<scalar_t>(),
|
||||
depth_buffer.data<scalar_t>(),
|
||||
triangle_buffer.data<int>(),
|
||||
baryw_buffer.data<scalar_t>(),
|
||||
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<scalar_t><<<blocks_1, threads>>>(
|
||||
face_vertices.data<scalar_t>(),
|
||||
depth_buffer.data<scalar_t>(),
|
||||
triangle_buffer.data<int>(),
|
||||
baryw_buffer.data<scalar_t>(),
|
||||
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<at::Tensor> 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<scalar_t><<<blocks_1, threads>>>(
|
||||
face_vertices.data<scalar_t>(),
|
||||
face_colors.data<scalar_t>(),
|
||||
depth_buffer.data<scalar_t>(),
|
||||
triangle_buffer.data<int>(),
|
||||
images.data<scalar_t>(),
|
||||
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<scalar_t><<<blocks_1, threads>>>(
|
||||
// face_vertices.data<scalar_t>(),
|
||||
// face_colors.data<scalar_t>(),
|
||||
// depth_buffer.data<scalar_t>(),
|
||||
// triangle_buffer.data<int>(),
|
||||
// images.data<scalar_t>(),
|
||||
// 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};
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,458 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,136 +0,0 @@
|
||||
'''
|
||||
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
|
||||
@@ -1,719 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,12 +1,16 @@
|
||||
from typing import Any, List
|
||||
from omegaconf import DictConfig
|
||||
import numpy as np
|
||||
from skimage.io import imread
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from pytorch_lightning import LightningModule
|
||||
from torchmetrics import MaxMetric, MeanMetric
|
||||
from torchmetrics import MaxMetric, MeanMetric, MinMetric
|
||||
import logging
|
||||
|
||||
from ..losses import lossfunc
|
||||
|
||||
|
||||
from src.losses import WingLoss
|
||||
from src.utils.debug import debug
|
||||
@@ -20,7 +24,7 @@ from src.mesh import util
|
||||
from src.utils.animation import write_video, write_video_with_gt
|
||||
|
||||
|
||||
class Audio2MeshModel(LightningModule):
|
||||
class Audio2CoeffModel(LightningModule):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -29,6 +33,7 @@ class Audio2MeshModel(LightningModule):
|
||||
opt: DictConfig = None,
|
||||
opt_LOSS: DictConfig = None,
|
||||
opt_netF: DictConfig = None,
|
||||
opt_netT: DictConfig = None,
|
||||
opt_netR: DictConfig = None,
|
||||
opt_netW: DictConfig = None,
|
||||
netG: torch.nn.Module = None,
|
||||
@@ -46,9 +51,10 @@ class Audio2MeshModel(LightningModule):
|
||||
self.opt = opt
|
||||
self.opt_LOSS = opt_LOSS
|
||||
|
||||
self.netG = netG # load Audio2mesh model
|
||||
self.netG = netG # load Audio2coeff model
|
||||
self.netF = self._load_netF(opt_netF) # load FLAME model
|
||||
self.netR = self._load_netR(opt_netR) # load Render model
|
||||
self.netT = self._load_netT(opt_netT) # load Texture model
|
||||
self.processor, self.netW = self._load_netW(opt_netW) # load wav2vec model
|
||||
|
||||
|
||||
@@ -80,6 +86,8 @@ class Audio2MeshModel(LightningModule):
|
||||
vertices_weight[:, :, flame_mouth_idx, :] = 10
|
||||
self.register_buffer("vertices_weight", vertices_weight)
|
||||
|
||||
landmarks_weight = self._set_landmark68_weight()
|
||||
self.register_buffer("landmarks_weight", landmarks_weight)
|
||||
|
||||
# loss function
|
||||
self.loss_func_wing = WingLoss(reduction="none") # return (B, )
|
||||
@@ -91,14 +99,52 @@ class Audio2MeshModel(LightningModule):
|
||||
self.test_rec, self.test_vel = MeanMetric(), MeanMetric()
|
||||
|
||||
# for logging best so far validation accuracy
|
||||
self.val_best = MaxMetric()
|
||||
self.val_best = MinMetric()
|
||||
|
||||
def _set_landmark68_weight(self,):
|
||||
# smaller inner landmark weights
|
||||
weights = torch.ones((68,))
|
||||
|
||||
weights[5:7] = 2
|
||||
weights[10:12] = 2
|
||||
# nose points
|
||||
weights[27:36] = 1.5
|
||||
weights[[30,31,35]] = 3
|
||||
# inner mouth
|
||||
weights[60:68] = 1.5
|
||||
weights[48:60] = 1.5
|
||||
weights[[48,54]] = 3
|
||||
|
||||
return weights
|
||||
|
||||
|
||||
def _load_netF(self, opt_netF):
|
||||
from src.mesh.FLAME import FLAME
|
||||
|
||||
logging.info("_load_netF, FLAME ...")
|
||||
return FLAME(opt_netF)
|
||||
|
||||
model = FLAME(opt_netF)
|
||||
|
||||
# set to freeze
|
||||
for param in model.parameters():
|
||||
param.requires_grad = False
|
||||
|
||||
return model.eval()
|
||||
|
||||
|
||||
def _load_netT(self, opt_netT):
|
||||
from ..mesh.FLAME import FLAMETex
|
||||
|
||||
logging.info("_load_netF, FLAME ...")
|
||||
|
||||
model = FLAMETex(opt_netT)
|
||||
|
||||
# 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
|
||||
@@ -109,11 +155,43 @@ class Audio2MeshModel(LightningModule):
|
||||
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
|
||||
)
|
||||
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
|
||||
|
||||
# face mask for rendering details
|
||||
mask = imread(opt_netR.face_eye_mask_path).astype(np.float32)/255.
|
||||
mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous()
|
||||
uv_face_eye_mask = F.interpolate(mask, [opt_netR.uv_size, opt_netR.uv_size])
|
||||
self.register_buffer("uv_face_eye_mask", uv_face_eye_mask)
|
||||
|
||||
mask = imread(opt_netR.face_mask_path).astype(np.float32)/255.
|
||||
mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous()
|
||||
uv_face_mask = F.interpolate(mask, [opt_netR.uv_size, opt_netR.uv_size])
|
||||
self.register_buffer("uv_face_mask", uv_face_mask)
|
||||
|
||||
# # displacement correction
|
||||
# fixed_dis = np.load(opt_netR.fixed_displacement_path)
|
||||
# fixed_uv_dis = torch.tensor(fixed_dis).float()
|
||||
# self.register_buffer("fixed_uv_dis", fixed_uv_dis)
|
||||
|
||||
# mean texture
|
||||
mean_texture = imread(opt_netR.mean_tex_path).astype(np.float32)/255.
|
||||
mean_texture = torch.from_numpy(mean_texture.transpose(2,0,1))[None,:,:,:].contiguous()
|
||||
mean_texture = F.interpolate(mean_texture, [opt_netR.uv_size, opt_netR.uv_size])
|
||||
self.register_buffer("mean_texture", mean_texture)
|
||||
|
||||
# # dense mesh template, for save detail mesh
|
||||
# self.dense_template = np.load(opt_netR.dense_template_path, allow_pickle=True, encoding='latin1').item()
|
||||
|
||||
return model.eval()
|
||||
|
||||
|
||||
def _load_netW(self, opt_netW):
|
||||
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
|
||||
@@ -124,15 +202,11 @@ class Audio2MeshModel(LightningModule):
|
||||
processor = Wav2Vec2FeatureExtractor.from_pretrained(opt_netW.path_ckpt_wav2vec)
|
||||
extractor = Wav2Vec2Model.from_pretrained(opt_netW.path_ckpt_wav2vec)
|
||||
|
||||
return processor, extractor
|
||||
# set to freeze
|
||||
for param in extractor.parameters():
|
||||
param.requires_grad = False
|
||||
|
||||
|
||||
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
|
||||
return processor, extractor.eval()
|
||||
|
||||
|
||||
def configure_optimizers(self):
|
||||
@@ -147,10 +221,16 @@ class Audio2MeshModel(LightningModule):
|
||||
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):
|
||||
|
||||
@@ -160,11 +240,22 @@ class Audio2MeshModel(LightningModule):
|
||||
data = batch["data"].float() # (B, nsteps, nc_motion)
|
||||
debug(f"data = {data.shape}, dtype={data.dtype}", verbose=False)
|
||||
|
||||
|
||||
images = batch['image'] # [B, nsteps, 3, size, size] ==> [BxK, 3, size, size]
|
||||
images = images.view(-1, images.shape[-3], images.shape[-2], images.shape[-1])
|
||||
lmk = batch['landmark'] # [B, nsteps, 3, size, size] ==> [BxK, 3, size, size]
|
||||
lmk = lmk.view(-1, lmk.shape[-2], lmk.shape[-1])
|
||||
masks = batch['mask'] # [B, nsteps, 3, size, size] ==> [BxK, 3, size, size]
|
||||
masks = masks.view(-1, images.shape[-2], images.shape[-1])
|
||||
|
||||
# batch information
|
||||
batch_info = {
|
||||
"vid": batch['vid'],
|
||||
"nframe": batch['nframe'],
|
||||
"interv": batch['frame_interval']
|
||||
"interv": batch['frame_interval'],
|
||||
"images": images,
|
||||
"lmk": lmk,
|
||||
"masks": masks
|
||||
}
|
||||
|
||||
# speech data
|
||||
@@ -208,34 +299,77 @@ class Audio2MeshModel(LightningModule):
|
||||
return self.netG(x)
|
||||
|
||||
|
||||
def step(self, batch:Any):
|
||||
def step(self, batch:Any, return_vis:bool=False):
|
||||
|
||||
batch_x, batch_tgt, batch_info = self.set_input(batch)
|
||||
B, N = batch_x.size(0), batch_x.size(1) # get batch_size
|
||||
|
||||
batch_pdt = self.forward(batch_x)
|
||||
batch_pdt += self.temp_verts
|
||||
# get exp + pos
|
||||
batch_pdt = self.netG(batch_x) # B*N x dim_motion
|
||||
|
||||
# prepare codedict for render
|
||||
codedict = {}
|
||||
codedict["exp"] = batch_pdt['exp'] # from predict
|
||||
codedict["pos"] = batch_pdt['pos'] # from predict
|
||||
|
||||
codedict["shape"] = batch_info['shape'] # from ** mean ** shape
|
||||
codedict["tex"] = batch_info['tex'] # from predict
|
||||
codedict["cam"] = batch_info['cam'] # from predict
|
||||
codedict["pose"] = batch_info['pose'] # from predict
|
||||
codedict["light"] = batch_info['light'] # from predict
|
||||
|
||||
#
|
||||
# get geometry vertice
|
||||
verts, landmarks2d, landmarks3d = self.netF(
|
||||
shape_params=codedict['shape'], expression_params=codedict['exp'], pose_params=codedict['pose'])
|
||||
|
||||
# get albedo texture
|
||||
albedo = self.netT(codedict['tex'])
|
||||
|
||||
## projection with camera (2D landmarks, 3D landmarks, verts)
|
||||
landmarks3d_world = landmarks3d.clone()
|
||||
landmarks2d = util.batch_orth_proj(landmarks2d, codedict['cam'])[:,:,:2]
|
||||
landmarks2d[:,:,1:] = -landmarks2d[:,:,1:]
|
||||
landmarks3d = util.batch_orth_proj(landmarks3d, codedict['cam'])
|
||||
landmarks3d[:,:,1:] = -landmarks3d[:,:,1:]
|
||||
trans_verts = util.batch_orth_proj(verts, codedict['cam'])
|
||||
trans_verts[:,:,1:] = -trans_verts[:,:,1:]
|
||||
|
||||
# render to image
|
||||
ops = self.netR(verts, trans_verts, albedo, codedict['light'])
|
||||
|
||||
## output
|
||||
opdict = {
|
||||
'images': batch_info['images'],
|
||||
'lmk': batch_info['lmk'],
|
||||
'albedo': albedo,
|
||||
'verts': verts,
|
||||
'trans_verts': trans_verts,
|
||||
'landmarks2d': landmarks2d,
|
||||
'landmarks3d': landmarks3d,
|
||||
'landmarks3d_world': landmarks3d_world,
|
||||
'grid': ops['grid'],
|
||||
'rendered_images': ops['images'],
|
||||
'alpha_images': ops['alpha_images'],
|
||||
'normal_images': ops['normal_images']
|
||||
}
|
||||
|
||||
# get mask predicted_images
|
||||
mask_face_eye = F.grid_sample(self.uv_face_eye_mask.expand(B,-1,-1,-1), opdict['grid'].detach(), align_corners=False)
|
||||
predicted_images = opdict['rendered_images'] * mask_face_eye * opdict['alpha_images']
|
||||
opdict['predicted_images'] = predicted_images
|
||||
|
||||
|
||||
# eval loss
|
||||
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}")
|
||||
@@ -250,13 +384,6 @@ class Audio2MeshModel(LightningModule):
|
||||
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)
|
||||
|
||||
@@ -276,7 +403,6 @@ class Audio2MeshModel(LightningModule):
|
||||
|
||||
# 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()`
|
||||
@@ -294,7 +420,6 @@ class Audio2MeshModel(LightningModule):
|
||||
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}
|
||||
|
||||
@@ -314,6 +439,54 @@ class Audio2MeshModel(LightningModule):
|
||||
self.test_rec.reset(), self.test_vel.reset()
|
||||
|
||||
|
||||
def eval_loss(self, lmk, mask_face_eye, images, predicted_images, opdict, codedict):
|
||||
|
||||
loss = 0
|
||||
loss_dict = {}
|
||||
|
||||
## base shape
|
||||
predicted_landmarks = opdict['landmarks2d']
|
||||
|
||||
# landmarks loss
|
||||
loss_lmk = lossfunc.landmark_loss(predicted_landmarks, lmk, self.landmak_weight)
|
||||
loss_dict['landmark'] = loss_lmk.detach()
|
||||
if self.opt_loss.lmk > 0.0:
|
||||
loss += loss_lmk * self.opt_loss.lmk
|
||||
|
||||
# eye closure loss
|
||||
loss_eye = lossfunc.eyed_loss(predicted_landmarks, lmk)
|
||||
loss_dict['eye_distance'] = loss_eye.detach()
|
||||
if self.opt_loss.eyed > 0.0:
|
||||
loss += loss_eye * self.opt_loss.eyed
|
||||
|
||||
# lip closure loss
|
||||
loss_lip = lossfunc.lipd_loss(predicted_landmarks, lmk)
|
||||
loss_dict['lip_distance'] = loss_lip.detach()
|
||||
if self.opt_loss.lipd > 0.0:
|
||||
loss += loss_lip * self.opt_loss.lipd
|
||||
|
||||
# photometric loss
|
||||
masks = masks[:,None,:,:] if self.opt_loss.useSeg else (mask_face_eye * opdict['alpha_images'])
|
||||
loss_pho = masks * (predicted_images - images).abs().mean()
|
||||
loss_dict['photometric_texture'] = loss_pho.detach()
|
||||
if self.opt_loss.photo > 0.0:
|
||||
loss += loss_pho * self.opt_loss.photo
|
||||
|
||||
# expression regularization
|
||||
loss_reg = torch.sum(codedict['exp']**2)/2
|
||||
loss_dict['expression_reg'] = loss_reg.detach()
|
||||
if self.opt_loss.reg > 0.0 :
|
||||
# import ipdb; ipdb.set_trace()
|
||||
loss += loss_reg * self.opt_loss.reg
|
||||
|
||||
|
||||
#########################################################
|
||||
loss_dict['all_loss'] = loss.detach()
|
||||
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
|
||||
def eval_losses(self, batch_pdt_geo, batch_tgt_geo):
|
||||
""" Computes the loss function.
|
||||
pramas:
|
||||
@@ -410,6 +583,8 @@ class Audio2MeshModel(LightningModule):
|
||||
return verts, ldmk2d, ldmk3d
|
||||
|
||||
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def get_vertices(self, batch_motion):
|
||||
"""
|
||||
@@ -441,17 +616,17 @@ class Audio2MeshModel(LightningModule):
|
||||
"""
|
||||
verts: [N x 5023 x 3]
|
||||
"""
|
||||
batch_size = verts.size(0)
|
||||
B = verts.size(0)
|
||||
|
||||
if cam is None:
|
||||
cam = torch.zeros(batch_size, 3).to(device) # (batch_size, 3)
|
||||
cam = torch.zeros(B, 3).to(device) # (B, 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)
|
||||
images = self.netR.render_shape(verts, verts_proj) # (B, 3, 512, 512)
|
||||
|
||||
return images
|
||||
|
||||
@@ -562,6 +737,17 @@ class Audio2MeshModel(LightningModule):
|
||||
write_video_with_gt(v_render_pt, v_render_gt, batch_speech[i], ipath_save, fps=50, sr=16000)
|
||||
|
||||
|
||||
|
||||
|
||||
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)
|
||||
# items["test"] = '{:.6f}'.format(items["loss"])
|
||||
return items
|
||||
|
||||
|
||||
def tensor2image(self, tensor):
|
||||
# image = tensor.detach().cpu().numpy()
|
||||
image = tensor.numpy()
|
||||
@@ -7,7 +7,6 @@ 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
|
||||
|
||||
Executable
+174
@@ -0,0 +1,174 @@
|
||||
import math
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
|
||||
def conv3x3(in_planes, out_planes, stride=1):
|
||||
"""3x3 convolution with padding"""
|
||||
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
|
||||
padding=1, bias=False)
|
||||
|
||||
class BasicBlock(nn.Module):
|
||||
expansion = 1
|
||||
|
||||
def __init__(self, inplanes, planes, stride=1, downsample=None):
|
||||
super(BasicBlock, self).__init__()
|
||||
self.conv1 = conv3x3(inplanes, planes, stride)
|
||||
self.bn1 = nn.BatchNorm2d(planes)
|
||||
self.relu = nn.ReLU(inplace=True)
|
||||
self.conv2 = conv3x3(planes, planes)
|
||||
self.bn2 = nn.BatchNorm2d(planes)
|
||||
self.downsample = downsample
|
||||
self.stride = stride
|
||||
|
||||
def forward(self, x):
|
||||
residual = x
|
||||
|
||||
out = self.conv1(x)
|
||||
out = self.bn1(out)
|
||||
out = self.relu(out)
|
||||
|
||||
out = self.conv2(out)
|
||||
out = self.bn2(out)
|
||||
|
||||
if self.downsample is not None:
|
||||
residual = self.downsample(x)
|
||||
|
||||
out += residual
|
||||
out = self.relu(out)
|
||||
|
||||
return out
|
||||
|
||||
|
||||
class Bottleneck(nn.Module):
|
||||
expansion = 4
|
||||
|
||||
def __init__(self, inplanes, planes, stride=1, downsample=None):
|
||||
super(Bottleneck, self).__init__()
|
||||
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, bias=False)
|
||||
self.bn1 = nn.BatchNorm2d(planes)
|
||||
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
|
||||
self.bn2 = nn.BatchNorm2d(planes)
|
||||
self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
|
||||
self.bn3 = nn.BatchNorm2d(planes * 4)
|
||||
self.relu = nn.ReLU(inplace=True)
|
||||
self.downsample = downsample
|
||||
self.stride = stride
|
||||
|
||||
def forward(self, x):
|
||||
residual = x
|
||||
|
||||
out = self.conv1(x)
|
||||
out = self.bn1(out)
|
||||
out = self.relu(out)
|
||||
|
||||
out = self.conv2(out)
|
||||
out = self.bn2(out)
|
||||
out = self.relu(out)
|
||||
|
||||
out = self.conv3(out)
|
||||
out = self.bn3(out)
|
||||
|
||||
if self.downsample is not None:
|
||||
residual = self.downsample(x)
|
||||
|
||||
out += residual
|
||||
out = self.relu(out)
|
||||
|
||||
return out
|
||||
|
||||
|
||||
class ResNet(nn.Module):
|
||||
|
||||
def __init__(self, block, layers, num_classes=1000, include_top=True):
|
||||
self.inplanes = 64
|
||||
super(ResNet, self).__init__()
|
||||
self.include_top = include_top
|
||||
|
||||
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
|
||||
self.bn1 = nn.BatchNorm2d(64)
|
||||
self.relu = nn.ReLU(inplace=True)
|
||||
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=0, ceil_mode=True)
|
||||
|
||||
self.layer1 = self._make_layer(block, 64, layers[0])
|
||||
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
|
||||
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
|
||||
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
|
||||
self.avgpool = nn.AvgPool2d(7, stride=1)
|
||||
self.fc = nn.Linear(512 * block.expansion, num_classes)
|
||||
|
||||
for m in self.modules():
|
||||
if isinstance(m, nn.Conv2d):
|
||||
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
|
||||
m.weight.data.normal_(0, math.sqrt(2. / n))
|
||||
|
||||
elif isinstance(m, nn.BatchNorm2d):
|
||||
m.weight.data.fill_(1)
|
||||
m.bias.data.zero_()
|
||||
|
||||
def _make_layer(self, block, planes, blocks, stride=1):
|
||||
downsample = None
|
||||
if stride != 1 or self.inplanes != planes * block.expansion:
|
||||
downsample = nn.Sequential(
|
||||
nn.Conv2d(self.inplanes, planes * block.expansion,
|
||||
kernel_size=1, stride=stride, bias=False),
|
||||
nn.BatchNorm2d(planes * block.expansion),
|
||||
)
|
||||
|
||||
layers = []
|
||||
layers.append(block(self.inplanes, planes, stride, downsample))
|
||||
self.inplanes = planes * block.expansion
|
||||
for i in range(1, blocks):
|
||||
layers.append(block(self.inplanes, planes))
|
||||
|
||||
return nn.Sequential(*layers)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.conv1(x)
|
||||
x = self.bn1(x)
|
||||
x = self.relu(x)
|
||||
x = self.maxpool(x)
|
||||
|
||||
x = self.layer1(x)
|
||||
x = self.layer2(x)
|
||||
x = self.layer3(x)
|
||||
x = self.layer4(x)
|
||||
|
||||
x = self.avgpool(x)
|
||||
|
||||
if not self.include_top:
|
||||
return x
|
||||
|
||||
x = x.view(x.size(0), -1)
|
||||
x = self.fc(x)
|
||||
return x
|
||||
|
||||
def resnet50(**kwargs):
|
||||
"""Constructs a ResNet-50 model.
|
||||
"""
|
||||
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
|
||||
return model
|
||||
|
||||
import pickle
|
||||
def load_state_dict(model, fname):
|
||||
"""
|
||||
Set parameters converted from Caffe models authors of VGGFace2 provide.
|
||||
See https://www.robots.ox.ac.uk/~vgg/data/vgg_face2/.
|
||||
Arguments:
|
||||
model: model
|
||||
fname: file name of parameters converted from a Caffe model, assuming the file format is Pickle.
|
||||
"""
|
||||
with open(fname, 'rb') as f:
|
||||
weights = pickle.load(f, encoding='latin1')
|
||||
|
||||
own_state = model.state_dict()
|
||||
for name, param in weights.items():
|
||||
if name in own_state:
|
||||
try:
|
||||
own_state[name].copy_(torch.from_numpy(param))
|
||||
except Exception:
|
||||
raise RuntimeError('While copying the parameter named {}, whose dimensions in the model are {} and whose '\
|
||||
'dimensions in the checkpoint are {}.'.format(name, own_state[name].size(), param.size()))
|
||||
else:
|
||||
raise KeyError('unexpected key "{}" in state_dict'.format(name))
|
||||
|
||||
Reference in new issue
Block a user