File size: 3,132 Bytes
d378823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Minimal licensed-MANO runtime. Model files are discovered locally and never copied."""
import os
from pathlib import Path
from types import SimpleNamespace
import numpy as np
import torch
import smplx
from freihand_common import DATASET_ROOT, RestrictedUnpickler

class StoredState:
    def __setstate__(self, state): self.__dict__.update(state)

class ManoReader(RestrictedUnpickler):
    def find_class(self, module, name):
        if (module, name) in [("chumpy.ch", "Ch"), ("chumpy.reordering", "Select"), ("scipy.sparse.csc", "csc_matrix")]:
            return StoredState
        if (module, name) == ("__builtin__", "set"): return set
        return super().find_class(module, name)

def model_dir():
    candidates = []
    if os.environ.get("MANO_MODEL_DIR"): candidates.append(Path(os.environ["MANO_MODEL_DIR"]))
    candidates += [DATASET_ROOT / "tmp/models/mano", DATASET_ROOT / "tmp/pilot-models", Path.home() / ".mano/models"]
    for path in candidates:
        if (path / "MANO_RIGHT.pkl").is_file(): return path
    raise FileNotFoundError("MANO_RIGHT.pkl not found. Set MANO_MODEL_DIR or place it in <dataset>/tmp/models/mano.")

def model_data(path):
    with path.open("rb") as stream: data = ManoReader(stream, encoding="latin1").load()
    shapedirs = data["shapedirs"]
    if isinstance(shapedirs, StoredState):
        data["shapedirs"] = shapedirs.a.x.reshape(-1)[shapedirs.idxs].reshape(shapedirs.preferred_shape)
    sparse = data["J_regressor"]
    if isinstance(sparse, StoredState):
        dense = np.zeros(sparse._shape)
        for col in range(sparse._shape[1]):
            begin, end = sparse.indptr[col:col + 2]; dense[sparse.indices[begin:end], col] = sparse.data[begin:end]
        data["J_regressor"] = dense
    return data

class Mano:
    def __init__(self):
        directory = model_dir(); self.data = model_data(directory / "MANO_RIGHT.pkl")
        self.layer = smplx.MANO(model_path=str(directory), data_struct=SimpleNamespace(**self.data),
                               is_rhand=True, use_pca=False, flat_hand_mean=True)
    def geometry(self, pose, betas, translation=None):
        pose = torch.as_tensor(np.asarray(pose).copy(), dtype=torch.float32).reshape(-1, 48)
        betas = torch.as_tensor(np.asarray(betas).copy(), dtype=torch.float32).reshape(-1, 10)
        with torch.no_grad(): output = self.layer(global_orient=pose[:, :3], hand_pose=pose[:, 3:], betas=betas)
        vertices = output.vertices.numpy(); joints = output.joints.numpy()[:, :16]
        if translation is not None:
            delta = np.asarray(translation).reshape(-1, 1, 3); vertices += delta; joints += delta
        keypoints = np.stack([joints[:,0],joints[:,13],joints[:,14],joints[:,15],vertices[:,744],
                              joints[:,1],joints[:,2],joints[:,3],vertices[:,320],
                              joints[:,4],joints[:,5],joints[:,6],vertices[:,443],
                              joints[:,10],joints[:,11],joints[:,12],vertices[:,555],
                              joints[:,7],joints[:,8],joints[:,9],vertices[:,672]], axis=1)
        return vertices, keypoints, joints