Spaces:
Running
on
L40S
Running
on
L40S
File size: 10,782 Bytes
2252f3d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 |
from collections import namedtuple
import numpy as np
import torch
import torch.nn as nn
from .lbs import lbs, hybrik, rotmat_to_quat, quat_to_rotmat, rotation_matrix_to_angle_axis
try:
import cPickle as pk
except ImportError:
import pickle as pk
ModelOutput = namedtuple(
'ModelOutput', ['vertices', 'joints', 'joints_from_verts', 'rot_mats'])
ModelOutput.__new__.__defaults__ = (None, ) * len(ModelOutput._fields)
def to_tensor(array, dtype=torch.float32):
if 'torch.tensor' not in str(type(array)):
return torch.tensor(array, dtype=dtype)
class Struct(object):
def __init__(self, **kwargs):
for key, val in kwargs.items():
setattr(self, key, val)
def to_np(array, dtype=np.float32):
if 'scipy.sparse' in str(type(array)):
array = array.todense()
return np.array(array, dtype=dtype)
class SMPL_layer(nn.Module):
NUM_JOINTS = 23
NUM_BODY_JOINTS = 23
NUM_BETAS = 10
JOINT_NAMES = [
'pelvis',
'left_hip',
'right_hip', # 2
'spine1',
'left_knee',
'right_knee', # 5
'spine2',
'left_ankle',
'right_ankle', # 8
'spine3',
'left_foot',
'right_foot', # 11
'neck',
'left_collar',
'right_collar', # 14
'jaw', # 15
'left_shoulder',
'right_shoulder', # 17
'left_elbow',
'right_elbow', # 19
'left_wrist',
'right_wrist', # 21
'left_thumb',
'right_thumb', # 23
'head',
'left_middle',
'right_middle', # 26
'left_bigtoe',
'right_bigtoe' # 28
]
LEAF_NAMES = [
'head', 'left_middle', 'right_middle', 'left_bigtoe', 'right_bigtoe'
]
root_idx_17 = 0
root_idx_smpl = 0
def __init__(self,
model_path,
h36m_jregressor,
gender='neutral',
dtype=torch.float32,
num_joints=29):
''' SMPL model layers
Parameters:
----------
model_path: str
The path to the folder or to the file where the model
parameters are stored
gender: str, optional
Which gender to load
'''
super(SMPL_layer, self).__init__()
self.ROOT_IDX = self.JOINT_NAMES.index('pelvis')
self.LEAF_IDX = [
self.JOINT_NAMES.index(name) for name in self.LEAF_NAMES
]
self.SPINE3_IDX = 9
with open(model_path, 'rb') as smpl_file:
self.smpl_data = Struct(**pk.load(smpl_file, encoding='latin1'))
self.gender = gender
self.dtype = dtype
self.faces = self.smpl_data.f
''' Register Buffer '''
# Faces
self.register_buffer(
'faces_tensor',
to_tensor(to_np(self.smpl_data.f, dtype=np.int64),
dtype=torch.long))
# The vertices of the template model, (6890, 3)
self.register_buffer(
'v_template',
to_tensor(to_np(self.smpl_data.v_template), dtype=dtype))
# The shape components
# Shape blend shapes basis, (6890, 3, 10)
self.register_buffer(
'shapedirs', to_tensor(to_np(self.smpl_data.shapedirs),
dtype=dtype))
# Pose blend shape basis: 6890 x 3 x 23*9, reshaped to 6890*3 x 23*9
num_pose_basis = self.smpl_data.posedirs.shape[-1]
# 23*9 x 6890*3
posedirs = np.reshape(self.smpl_data.posedirs, [-1, num_pose_basis]).T
self.register_buffer('posedirs', to_tensor(to_np(posedirs),
dtype=dtype))
# Vertices to Joints location (23 + 1, 6890)
self.register_buffer(
'J_regressor',
to_tensor(to_np(self.smpl_data.J_regressor), dtype=dtype))
# Vertices to Human3.6M Joints location (17, 6890)
self.register_buffer('J_regressor_h36m',
to_tensor(to_np(h36m_jregressor), dtype=dtype))
self.num_joints = num_joints
# indices of parents for each joints
parents = torch.zeros(len(self.JOINT_NAMES), dtype=torch.long)
parents[:(self.NUM_JOINTS + 1)] = to_tensor(
to_np(self.smpl_data.kintree_table[0])).long()
parents[0] = -1
# extend kinematic tree
parents[24] = 15
parents[25] = 22
parents[26] = 23
parents[27] = 10
parents[28] = 11
if parents.shape[0] > self.num_joints:
parents = parents[:24]
self.register_buffer('children_map',
self._parents_to_children(parents))
# (24,)
self.register_buffer('parents', parents)
# (6890, 23 + 1)
self.register_buffer(
'lbs_weights', to_tensor(to_np(self.smpl_data.weights),
dtype=dtype))
def _parents_to_children(self, parents):
children = torch.ones_like(parents) * -1
for i in range(self.num_joints):
if children[parents[i]] < 0:
children[parents[i]] = i
for i in self.LEAF_IDX:
if i < children.shape[0]:
children[i] = -1
children[self.SPINE3_IDX] = -3
children[0] = 3
children[self.SPINE3_IDX] = self.JOINT_NAMES.index('neck')
return children
def forward(self,
pose_axis_angle,
betas,
global_orient,
transl=None,
return_verts=True):
''' Forward pass for the SMPL model
Parameters
----------
pose_axis_angle: torch.tensor, optional, shape Bx(J*3)
It should be a tensor that contains joint rotations in
axis-angle format. (default=None)
betas: torch.tensor, optional, shape Bx10
It can used if shape parameters
`betas` are predicted from some external model.
(default=None)
global_orient: torch.tensor, optional, shape Bx3
Global Orientations.
transl: torch.tensor, optional, shape Bx3
Global Translations.
return_verts: bool, optional
Return the vertices. (default=True)
Returns
-------
'''
# batch_size = pose_axis_angle.shape[0]
# concate root orientation with thetas
if global_orient is not None:
full_pose = torch.cat([global_orient, pose_axis_angle], dim=1)
else:
full_pose = pose_axis_angle
# Translate thetas to rotation matrics
pose2rot = True
# vertices: (B, N, 3), joints: (B, K, 3)
vertices, joints, rot_mats, joints_from_verts_h36m = lbs(
betas,
full_pose,
self.v_template,
self.shapedirs,
self.posedirs,
self.J_regressor,
self.J_regressor_h36m,
self.parents,
self.lbs_weights,
pose2rot=pose2rot,
dtype=self.dtype)
if transl is not None:
# apply translations
joints += transl.unsqueeze(dim=1)
vertices += transl.unsqueeze(dim=1)
joints_from_verts_h36m += transl.unsqueeze(dim=1)
else:
vertices = vertices - \
joints_from_verts_h36m[:, self.root_idx_17, :].unsqueeze(
1).detach()
joints = joints - \
joints[:, self.root_idx_smpl, :].unsqueeze(1).detach()
joints_from_verts_h36m = joints_from_verts_h36m - \
joints_from_verts_h36m[:, self.root_idx_17, :].unsqueeze(
1).detach()
output = ModelOutput(vertices=vertices,
joints=joints,
rot_mats=rot_mats,
joints_from_verts=joints_from_verts_h36m)
return output
def hybrik(self,
pose_skeleton,
betas,
phis,
global_orient,
transl=None,
return_verts=True,
leaf_thetas=None):
''' Inverse pass for the SMPL model
Parameters
----------
pose_skeleton: torch.tensor, optional, shape Bx(J*3)
It should be a tensor that contains joint locations in
(X, Y, Z) format. (default=None)
betas: torch.tensor, optional, shape Bx10
It can used if shape parameters
`betas` are predicted from some external model.
(default=None)
global_orient: torch.tensor, optional, shape Bx3
Global Orientations.
transl: torch.tensor, optional, shape Bx3
Global Translations.
return_verts: bool, optional
Return the vertices. (default=True)
Returns
-------
'''
batch_size = pose_skeleton.shape[0]
if leaf_thetas is not None:
leaf_thetas = leaf_thetas.reshape(batch_size * 5, 4)
leaf_thetas = quat_to_rotmat(leaf_thetas)
vertices, new_joints, rot_mats, joints_from_verts = hybrik(
betas,
global_orient,
pose_skeleton,
phis,
self.v_template,
self.shapedirs,
self.posedirs,
self.J_regressor,
self.J_regressor_h36m,
self.parents,
self.children_map,
self.lbs_weights,
dtype=self.dtype,
train=self.training,
leaf_thetas=leaf_thetas)
rot_mats = rot_mats.reshape(batch_size, 24, 3, 3)
# rot_aa = rotation_matrix_to_angle_axis(rot_mats)
# rot_mats = rotmat_to_quat(rot_mats).reshape(batch_size, 24 * 4)
if transl is not None:
new_joints += transl.unsqueeze(dim=1)
vertices += transl.unsqueeze(dim=1)
# joints_from_verts += transl.unsqueeze(dim=1)
else:
vertices = vertices - \
joints_from_verts[:, self.root_idx_17, :].unsqueeze(1).detach()
new_joints = new_joints - \
new_joints[:, self.root_idx_smpl, :].unsqueeze(1).detach()
# joints_from_verts = joints_from_verts - joints_from_verts[:, self.root_idx_17, :].unsqueeze(1).detach()
output = ModelOutput(vertices=vertices,
joints=new_joints,
rot_mats=rot_mats,
joints_from_verts=joints_from_verts)
return output
|