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
@@ -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,374 +0,0 @@
|
||||
import torch
|
||||
|
||||
''' Rotation Converter
|
||||
Repre: euler angle(3), angle axis(3), rotation matrix(3x3), quaternion(4)
|
||||
ref: https://kornia.readthedocs.io/en/v0.1.2/_modules/torchgeometry/core/conversions.html#
|
||||
"pi",
|
||||
"rad2deg",
|
||||
"deg2rad",
|
||||
# "angle_axis_to_rotation_matrix", batch_rodrigues
|
||||
"rotation_matrix_to_angle_axis",
|
||||
"rotation_matrix_to_quaternion",
|
||||
"quaternion_to_angle_axis",
|
||||
# "angle_axis_to_quaternion",
|
||||
|
||||
euler2quat_conversion_sanity_batch
|
||||
|
||||
ref: smplx/lbs
|
||||
batch_rodrigues: axis angle -> matrix
|
||||
#
|
||||
'''
|
||||
pi = torch.Tensor([3.14159265358979323846])
|
||||
|
||||
def rad2deg(tensor):
|
||||
"""Function that converts angles from radians to degrees.
|
||||
|
||||
See :class:`~torchgeometry.RadToDeg` for details.
|
||||
|
||||
Args:
|
||||
tensor (Tensor): Tensor of arbitrary shape.
|
||||
|
||||
Returns:
|
||||
Tensor: Tensor with same shape as input.
|
||||
|
||||
Example:
|
||||
>>> input = tgm.pi * torch.rand(1, 3, 3)
|
||||
>>> output = tgm.rad2deg(input)
|
||||
"""
|
||||
if not torch.is_tensor(tensor):
|
||||
raise TypeError("Input type is not a torch.Tensor. Got {}"
|
||||
.format(type(tensor)))
|
||||
|
||||
return 180. * tensor / pi.to(tensor.device).type(tensor.dtype)
|
||||
|
||||
def deg2rad(tensor):
|
||||
"""Function that converts angles from degrees to radians.
|
||||
|
||||
See :class:`~torchgeometry.DegToRad` for details.
|
||||
|
||||
Args:
|
||||
tensor (Tensor): Tensor of arbitrary shape.
|
||||
|
||||
Returns:
|
||||
Tensor: Tensor with same shape as input.
|
||||
|
||||
Examples::
|
||||
|
||||
>>> input = 360. * torch.rand(1, 3, 3)
|
||||
>>> output = tgm.deg2rad(input)
|
||||
"""
|
||||
if not torch.is_tensor(tensor):
|
||||
raise TypeError("Input type is not a torch.Tensor. Got {}"
|
||||
.format(type(tensor)))
|
||||
|
||||
return tensor * pi.to(tensor.device).type(tensor.dtype) / 180.
|
||||
|
||||
######### to quaternion
|
||||
def euler_to_quaternion(r):
|
||||
x = r[..., 0]
|
||||
y = r[..., 1]
|
||||
z = r[..., 2]
|
||||
|
||||
z = z/2.0
|
||||
y = y/2.0
|
||||
x = x/2.0
|
||||
cz = torch.cos(z)
|
||||
sz = torch.sin(z)
|
||||
cy = torch.cos(y)
|
||||
sy = torch.sin(y)
|
||||
cx = torch.cos(x)
|
||||
sx = torch.sin(x)
|
||||
quaternion = torch.zeros_like(r.repeat(1,2))[..., :4].to(r.device)
|
||||
quaternion[..., 0] += cx*cy*cz - sx*sy*sz
|
||||
quaternion[..., 1] += cx*sy*sz + cy*cz*sx
|
||||
quaternion[..., 2] += cx*cz*sy - sx*cy*sz
|
||||
quaternion[..., 3] += cx*cy*sz + sx*cz*sy
|
||||
return quaternion
|
||||
|
||||
def rotation_matrix_to_quaternion(rotation_matrix, eps=1e-6):
|
||||
"""Convert 3x4 rotation matrix to 4d quaternion vector
|
||||
|
||||
This algorithm is based on algorithm described in
|
||||
https://github.com/KieranWynn/pyquaternion/blob/master/pyquaternion/quaternion.py#L201
|
||||
|
||||
Args:
|
||||
rotation_matrix (Tensor): the rotation matrix to convert.
|
||||
|
||||
Return:
|
||||
Tensor: the rotation in quaternion
|
||||
|
||||
Shape:
|
||||
- Input: :math:`(N, 3, 4)`
|
||||
- Output: :math:`(N, 4)`
|
||||
|
||||
Example:
|
||||
>>> input = torch.rand(4, 3, 4) # Nx3x4
|
||||
>>> output = tgm.rotation_matrix_to_quaternion(input) # Nx4
|
||||
"""
|
||||
if not torch.is_tensor(rotation_matrix):
|
||||
raise TypeError("Input type is not a torch.Tensor. Got {}".format(
|
||||
type(rotation_matrix)))
|
||||
|
||||
if len(rotation_matrix.shape) > 3:
|
||||
raise ValueError(
|
||||
"Input size must be a three dimensional tensor. Got {}".format(
|
||||
rotation_matrix.shape))
|
||||
# if not rotation_matrix.shape[-2:] == (3, 4):
|
||||
# raise ValueError(
|
||||
# "Input size must be a N x 3 x 4 tensor. Got {}".format(
|
||||
# rotation_matrix.shape))
|
||||
|
||||
rmat_t = torch.transpose(rotation_matrix, 1, 2)
|
||||
|
||||
mask_d2 = rmat_t[:, 2, 2] < eps
|
||||
|
||||
mask_d0_d1 = rmat_t[:, 0, 0] > rmat_t[:, 1, 1]
|
||||
mask_d0_nd1 = rmat_t[:, 0, 0] < -rmat_t[:, 1, 1]
|
||||
|
||||
t0 = 1 + rmat_t[:, 0, 0] - rmat_t[:, 1, 1] - rmat_t[:, 2, 2]
|
||||
q0 = torch.stack([rmat_t[:, 1, 2] - rmat_t[:, 2, 1],
|
||||
t0, rmat_t[:, 0, 1] + rmat_t[:, 1, 0],
|
||||
rmat_t[:, 2, 0] + rmat_t[:, 0, 2]], -1)
|
||||
t0_rep = t0.repeat(4, 1).t()
|
||||
|
||||
t1 = 1 - rmat_t[:, 0, 0] + rmat_t[:, 1, 1] - rmat_t[:, 2, 2]
|
||||
q1 = torch.stack([rmat_t[:, 2, 0] - rmat_t[:, 0, 2],
|
||||
rmat_t[:, 0, 1] + rmat_t[:, 1, 0],
|
||||
t1, rmat_t[:, 1, 2] + rmat_t[:, 2, 1]], -1)
|
||||
t1_rep = t1.repeat(4, 1).t()
|
||||
|
||||
t2 = 1 - rmat_t[:, 0, 0] - rmat_t[:, 1, 1] + rmat_t[:, 2, 2]
|
||||
q2 = torch.stack([rmat_t[:, 0, 1] - rmat_t[:, 1, 0],
|
||||
rmat_t[:, 2, 0] + rmat_t[:, 0, 2],
|
||||
rmat_t[:, 1, 2] + rmat_t[:, 2, 1], t2], -1)
|
||||
t2_rep = t2.repeat(4, 1).t()
|
||||
|
||||
t3 = 1 + rmat_t[:, 0, 0] + rmat_t[:, 1, 1] + rmat_t[:, 2, 2]
|
||||
q3 = torch.stack([t3, rmat_t[:, 1, 2] - rmat_t[:, 2, 1],
|
||||
rmat_t[:, 2, 0] - rmat_t[:, 0, 2],
|
||||
rmat_t[:, 0, 1] - rmat_t[:, 1, 0]], -1)
|
||||
t3_rep = t3.repeat(4, 1).t()
|
||||
|
||||
mask_c0 = mask_d2 * mask_d0_d1.float()
|
||||
mask_c1 = mask_d2 * (1 - mask_d0_d1.float())
|
||||
mask_c2 = (1 - mask_d2.float()) * mask_d0_nd1
|
||||
mask_c3 = (1 - mask_d2.float()) * (1 - mask_d0_nd1.float())
|
||||
mask_c0 = mask_c0.view(-1, 1).type_as(q0)
|
||||
mask_c1 = mask_c1.view(-1, 1).type_as(q1)
|
||||
mask_c2 = mask_c2.view(-1, 1).type_as(q2)
|
||||
mask_c3 = mask_c3.view(-1, 1).type_as(q3)
|
||||
|
||||
q = q0 * mask_c0 + q1 * mask_c1 + q2 * mask_c2 + q3 * mask_c3
|
||||
q /= torch.sqrt(t0_rep * mask_c0 + t1_rep * mask_c1 + # noqa
|
||||
t2_rep * mask_c2 + t3_rep * mask_c3) # noqa
|
||||
q *= 0.5
|
||||
return q
|
||||
|
||||
# def angle_axis_to_quaternion(theta):
|
||||
# batch_size = theta.shape[0]
|
||||
# l1norm = torch.norm(theta + 1e-8, p=2, dim=1)
|
||||
# angle = torch.unsqueeze(l1norm, -1)
|
||||
# normalized = torch.div(theta, angle)
|
||||
# angle = angle * 0.5
|
||||
# v_cos = torch.cos(angle)
|
||||
# v_sin = torch.sin(angle)
|
||||
# quat = torch.cat([v_cos, v_sin * normalized], dim=1)
|
||||
# return quat
|
||||
|
||||
def angle_axis_to_quaternion(angle_axis: torch.Tensor) -> torch.Tensor:
|
||||
"""Convert an angle axis to a quaternion.
|
||||
|
||||
Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h
|
||||
|
||||
Args:
|
||||
angle_axis (torch.Tensor): tensor with angle axis.
|
||||
|
||||
Return:
|
||||
torch.Tensor: tensor with quaternion.
|
||||
|
||||
Shape:
|
||||
- Input: :math:`(*, 3)` where `*` means, any number of dimensions
|
||||
- Output: :math:`(*, 4)`
|
||||
|
||||
Example:
|
||||
>>> angle_axis = torch.rand(2, 4) # Nx4
|
||||
>>> quaternion = tgm.angle_axis_to_quaternion(angle_axis) # Nx3
|
||||
"""
|
||||
if not torch.is_tensor(angle_axis):
|
||||
raise TypeError("Input type is not a torch.Tensor. Got {}".format(
|
||||
type(angle_axis)))
|
||||
|
||||
if not angle_axis.shape[-1] == 3:
|
||||
raise ValueError("Input must be a tensor of shape Nx3 or 3. Got {}"
|
||||
.format(angle_axis.shape))
|
||||
# unpack input and compute conversion
|
||||
a0: torch.Tensor = angle_axis[..., 0:1]
|
||||
a1: torch.Tensor = angle_axis[..., 1:2]
|
||||
a2: torch.Tensor = angle_axis[..., 2:3]
|
||||
theta_squared: torch.Tensor = a0 * a0 + a1 * a1 + a2 * a2
|
||||
|
||||
theta: torch.Tensor = torch.sqrt(theta_squared)
|
||||
half_theta: torch.Tensor = theta * 0.5
|
||||
|
||||
mask: torch.Tensor = theta_squared > 0.0
|
||||
ones: torch.Tensor = torch.ones_like(half_theta)
|
||||
|
||||
k_neg: torch.Tensor = 0.5 * ones
|
||||
k_pos: torch.Tensor = torch.sin(half_theta) / theta
|
||||
k: torch.Tensor = torch.where(mask, k_pos, k_neg)
|
||||
w: torch.Tensor = torch.where(mask, torch.cos(half_theta), ones)
|
||||
|
||||
quaternion: torch.Tensor = torch.zeros_like(angle_axis)
|
||||
quaternion[..., 0:1] += a0 * k
|
||||
quaternion[..., 1:2] += a1 * k
|
||||
quaternion[..., 2:3] += a2 * k
|
||||
return torch.cat([w, quaternion], dim=-1)
|
||||
|
||||
#### quaternion to
|
||||
def quaternion_to_rotation_matrix(quat):
|
||||
"""Convert quaternion coefficients to rotation matrix.
|
||||
Args:
|
||||
quat: size = [B, 4] 4 <===>(w, x, y, z)
|
||||
Returns:
|
||||
Rotation matrix corresponding to the quaternion -- size = [B, 3, 3]
|
||||
"""
|
||||
norm_quat = quat
|
||||
norm_quat = norm_quat / norm_quat.norm(p=2, dim=1, keepdim=True)
|
||||
w, x, y, z = norm_quat[:, 0], norm_quat[:, 1], norm_quat[:, 2], norm_quat[:, 3]
|
||||
|
||||
B = quat.size(0)
|
||||
|
||||
w2, x2, y2, z2 = w.pow(2), x.pow(2), y.pow(2), z.pow(2)
|
||||
wx, wy, wz = w * x, w * y, w * z
|
||||
xy, xz, yz = x * y, x * z, y * z
|
||||
|
||||
rotMat = torch.stack([w2 + x2 - y2 - z2, 2 * xy - 2 * wz, 2 * wy + 2 * xz,
|
||||
2 * wz + 2 * xy, w2 - x2 + y2 - z2, 2 * yz - 2 * wx,
|
||||
2 * xz - 2 * wy, 2 * wx + 2 * yz, w2 - x2 - y2 + z2], dim=1).view(B, 3, 3)
|
||||
return rotMat
|
||||
|
||||
def quaternion_to_angle_axis(quaternion: torch.Tensor):
|
||||
"""Convert quaternion vector to angle axis of rotation. TODO: CORRECT
|
||||
|
||||
Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h
|
||||
|
||||
Args:
|
||||
quaternion (torch.Tensor): tensor with quaternions.
|
||||
|
||||
Return:
|
||||
torch.Tensor: tensor with angle axis of rotation.
|
||||
|
||||
Shape:
|
||||
- Input: :math:`(*, 4)` where `*` means, any number of dimensions
|
||||
- Output: :math:`(*, 3)`
|
||||
|
||||
Example:
|
||||
>>> quaternion = torch.rand(2, 4) # Nx4
|
||||
>>> angle_axis = tgm.quaternion_to_angle_axis(quaternion) # Nx3
|
||||
"""
|
||||
if not torch.is_tensor(quaternion):
|
||||
raise TypeError("Input type is not a torch.Tensor. Got {}".format(
|
||||
type(quaternion)))
|
||||
|
||||
if not quaternion.shape[-1] == 4:
|
||||
raise ValueError("Input must be a tensor of shape Nx4 or 4. Got {}"
|
||||
.format(quaternion.shape))
|
||||
# unpack input and compute conversion
|
||||
q1: torch.Tensor = quaternion[..., 1]
|
||||
q2: torch.Tensor = quaternion[..., 2]
|
||||
q3: torch.Tensor = quaternion[..., 3]
|
||||
sin_squared_theta: torch.Tensor = q1 * q1 + q2 * q2 + q3 * q3
|
||||
|
||||
sin_theta: torch.Tensor = torch.sqrt(sin_squared_theta)
|
||||
cos_theta: torch.Tensor = quaternion[..., 0]
|
||||
two_theta: torch.Tensor = 2.0 * torch.where(
|
||||
cos_theta < 0.0,
|
||||
torch.atan2(-sin_theta, -cos_theta),
|
||||
torch.atan2(sin_theta, cos_theta))
|
||||
|
||||
k_pos: torch.Tensor = two_theta / sin_theta
|
||||
k_neg: torch.Tensor = 2.0 * torch.ones_like(sin_theta).to(quaternion.device)
|
||||
k: torch.Tensor = torch.where(sin_squared_theta > 0.0, k_pos, k_neg)
|
||||
|
||||
angle_axis: torch.Tensor = torch.zeros_like(quaternion).to(quaternion.device)[..., :3]
|
||||
angle_axis[..., 0] += q1 * k
|
||||
angle_axis[..., 1] += q2 * k
|
||||
angle_axis[..., 2] += q3 * k
|
||||
return angle_axis
|
||||
|
||||
#### batch converter
|
||||
def batch_euler2axis(r):
|
||||
return quaternion_to_angle_axis(euler_to_quaternion(r))
|
||||
|
||||
def batch_euler2matrix(r):
|
||||
return quaternion_to_rotation_matrix(euler_to_quaternion(r))
|
||||
|
||||
def batch_matrix2euler(rot_mats):
|
||||
# Calculates rotation matrix to euler angles
|
||||
# Careful for extreme cases of eular angles like [0.0, pi, 0.0]
|
||||
### only y?
|
||||
# TODO:
|
||||
sy = torch.sqrt(rot_mats[:, 0, 0] * rot_mats[:, 0, 0] +
|
||||
rot_mats[:, 1, 0] * rot_mats[:, 1, 0])
|
||||
return torch.atan2(-rot_mats[:, 2, 0], sy)
|
||||
|
||||
def batch_matrix2axis(rot_mats):
|
||||
return quaternion_to_angle_axis(rotation_matrix_to_quaternion(rot_mats))
|
||||
|
||||
def batch_axis2matrix(theta):
|
||||
# angle axis to rotation matrix
|
||||
# theta N x 3
|
||||
# return quat2mat(quat)
|
||||
# batch_rodrigues
|
||||
return quaternion_to_rotation_matrix(angle_axis_to_quaternion(theta))
|
||||
|
||||
def batch_axis2euler(theta):
|
||||
return batch_matrix2euler(batch_axis2matrix(theta))
|
||||
|
||||
def batch_axis2euler(r):
|
||||
return rot_mat_to_euler(batch_rodrigues(r))
|
||||
|
||||
|
||||
def batch_orth_proj(X, camera):
|
||||
'''
|
||||
X is N x num_pquaternion_to_angle_axisoints x 3
|
||||
'''
|
||||
camera = camera.clone().view(-1, 1, 3)
|
||||
X_trans = X[:, :, :2] + camera[:, :, 1:]
|
||||
X_trans = torch.cat([X_trans, X[:,:,2:]], 2)
|
||||
Xn = (camera[:, :, 0:1] * X_trans)
|
||||
return Xn
|
||||
|
||||
def batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32):
|
||||
''' same as batch_matrix2axis
|
||||
Calculates the rotation matrices for a batch of rotation vectors
|
||||
Parameters
|
||||
----------
|
||||
rot_vecs: torch.tensor Nx3
|
||||
array of N axis-angle vectors
|
||||
Returns
|
||||
-------
|
||||
R: torch.tensor Nx3x3
|
||||
The rotation matrices for the given axis-angle parameters
|
||||
'''
|
||||
|
||||
batch_size = rot_vecs.shape[0]
|
||||
device = rot_vecs.device
|
||||
|
||||
angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True)
|
||||
rot_dir = rot_vecs / angle
|
||||
|
||||
cos = torch.unsqueeze(torch.cos(angle), dim=1)
|
||||
sin = torch.unsqueeze(torch.sin(angle), dim=1)
|
||||
|
||||
# Bx1 arrays
|
||||
rx, ry, rz = torch.split(rot_dir, 1, dim=1)
|
||||
K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device)
|
||||
|
||||
zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device)
|
||||
K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \
|
||||
.view((batch_size, 3, 3))
|
||||
|
||||
ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0)
|
||||
rot_mat = ident + sin * K + (1 - cos) * torch.bmm(K, K)
|
||||
return rot_mat
|
||||
@@ -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