File size: 2,189 Bytes
38b191e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from scipy.spatial.transform import Rotation as R
import torch, numpy as np

BOF_body = np.array([
    [-120.0, -130.0,  -80.0, # left shoulder
     -120.0,   0.0,  -80.0, # right shoulder
     -180.0, -160.0, -180.0, # left elbow
     -180.0,  0.0,  -180.0, # right elbow
     -120.0,  -50.0,  -90.0, # left wrist
     -120.0,  -50.0,  -90.0, # right wrist
     ],
     [90.0,    0.0,   80.0, # left shoulder
      90.0, 130.0,   80.0, # right shoulder
      180.0,    0.0,   180.0, # left elbow
      180.0,  160.0,    180.0, # right elbow
      90.0,   50.0,   90.0, # left wrist
      90.0,   50.0,   90.0]]) / 180 * np.pi


def _to_numpy_flat_last3(x: torch.Tensor):
    dev, dt = x.device, x.dtype
    x_np = x.detach().cpu().numpy().reshape(-1, 3)
    return x_np, x.shape, dev, dt

def _from_numpy(x_np: np.ndarray, shape, dev, dt):
    y = torch.from_numpy(x_np.reshape(*shape))
    if dt in (torch.float32, torch.float64): y = y.to(dt)
    return y.to(dev)



def euler_XYZ_to_axis_angle_scipy(e: torch.Tensor, degrees: bool = False) -> torch.Tensor:
    e_np, shape, dev, dt = _to_numpy_flat_last3(e)
    aa_np = R.from_euler('XYZ', e_np, degrees=degrees).as_rotvec()
    return _from_numpy(aa_np, shape, dev, dt)

def axis_angle_to_euler_XYZ_scipy(aa: torch.Tensor):
    aa_np, shape, dev, dt = _to_numpy_flat_last3(aa)
    e_np  = R.from_rotvec(aa_np).as_euler('XYZ', degrees=False)
    return _from_numpy(e_np, shape, dev, dt)




def apply_angular_constraints(body_pose):  # body_pose: (B, 63) axis-angle for 21 joints
    device = body_pose.device
    B = body_pose.shape[0]
    body_pose = body_pose.view(B, 21, 3)

    # your bounds (6×3) in radians, defined for joints [15..20] in intrinsic 'XYZ'
    minC = torch.tensor(BOF_body[0], dtype=body_pose.dtype, device=device).view(6,3)
    maxC = torch.tensor(BOF_body[1], dtype=body_pose.dtype, device=device).view(6,3)

    aa_arms = body_pose[:, 15:, :]
    
    e_arms  = axis_angle_to_euler_XYZ_scipy(aa_arms)       # (B,6,3) intrinsic 'XYZ'

    e_clamp = torch.clamp(e_arms, minC, maxC)

    aa_new = euler_XYZ_to_axis_angle_scipy(e_clamp)

    body_pose[:, 15:, :] = aa_new
    
    return body_pose.view(B, -1)