├── data └── README.md ├── models └── README.md ├── demo_data └── README.md ├── saved_model └── README.md ├── route_data.py ├── sub_data.py ├── train_route.py ├── train_pose.py ├── README.md ├── route.py ├── pose_after_route.py ├── sub_goal.py ├── train_subgoal.py ├── net_layers.py ├── LICENSE ├── utils.py ├── generate_routepose_data.ipynb ├── generate_sub_data.ipynb ├── utils_optimize.py └── demo.ipynb /data/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /models/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /demo_data/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /saved_model/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /route_data.py: -------------------------------------------------------------------------------- 1 | import torch.utils.data as data 2 | import torch 3 | import numpy as np 4 | 5 | class ROUTEDATA(data.Dataset): 6 | def __init__(self): 7 | self.data=np.load('./data/routepose_training_data.npy',allow_pickle=True) 8 | self.len=(len(self.data)//8)*8 9 | def __getitem__(self, index): 10 | return self.data[index][0],self.data[index][1],self.data[index][2],self.data[index][3],\ 11 | self.data[index][4],self.data[index][5],self.data[index][6],self.data[index][7],self.data[index][8] 12 | def __len__(self): 13 | return self.len -------------------------------------------------------------------------------- /sub_data.py: -------------------------------------------------------------------------------- 1 | import torch.utils.data as data 2 | import torch 3 | import numpy as np 4 | import random 5 | import os 6 | import json 7 | import pickle 8 | 9 | class SUBDATA(data.Dataset): 10 | def __init__(self): 11 | self.data=np.load('./data/sub_data_training.npy',allow_pickle=True) 12 | 13 | def __getitem__(self, index): 14 | return self.data[index][0],self.data[index][1],self.data[index][2],self.data[index][3],\ 15 | self.data[index][4],self.data[index][5],self.data[index][6],self.data[index][7] 16 | def __len__(self): 17 | return (len(self.data)//8)*8 18 | -------------------------------------------------------------------------------- /train_route.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | from torch.nn import init 6 | import torch.optim as optim 7 | from torch.optim import lr_scheduler 8 | from route import ROUTENET 9 | from route_data import ROUTEDATA 10 | from utils import GeometryTransformer 11 | 12 | batch_size = 16 13 | 14 | dataset = ROUTEDATA() 15 | dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True) 16 | 17 | model = ROUTENET(input_dim=9,hid_dim=64) 18 | model = model.cuda() 19 | 20 | lrate = 0.001 21 | optimizer = optim.Adam(model.parameters(), lr=lrate) 22 | 23 | for epoch in range(20): 24 | model.train() 25 | total_loss=0 26 | 27 | for j,data in enumerate(dataloader,0): 28 | optimizer.zero_grad() 29 | 30 | input_list,middle_list,frame_name,scene_name,sdf,scene_points,cam_extrinsic,s_grid_min,s_grid_max = data 31 | 32 | input_list = input_list[:,[0,-1],:] 33 | 34 | body = middle_list[:,0:1,6:16].cuda() 35 | input_list = torch.cat([input_list[:,:,:6],input_list[:,:,16:]],dim=2) 36 | middle_list = torch.cat([middle_list[:,:,:6],middle_list[:,:,16:]],dim=2) 37 | 38 | scene_points = scene_points.cuda() 39 | 40 | input_list = input_list.view(-1,62) 41 | six_d_input_list = GeometryTransformer.convert_to_6D_rot(input_list) 42 | six_d_input_list = six_d_input_list.view(-1,2,65) 43 | x = six_d_input_list.cuda() 44 | x1 = six_d_input_list[:,:,:9].cuda() 45 | 46 | middle_list = middle_list.view(-1,62) 47 | six_d_middle_list = GeometryTransformer.convert_to_6D_rot(middle_list) 48 | six_d_middle_list = six_d_middle_list.view(-1,60,65) #60: 2s 30fps 49 | 50 | y = six_d_middle_list[:,:,:9].cuda() 51 | 52 | out = model(x1,scene_points.transpose(1,2)) 53 | 54 | loss = torch.mean(torch.abs(out-y)) 55 | 56 | loss.backward() 57 | optimizer.step() 58 | 59 | total_loss = total_loss+loss 60 | 61 | print('loss:',total_loss/(j+1)) 62 | 63 | save_path = './saved_model/route_'+str(epoch)+'.model' 64 | torch.save(model.state_dict(),save_path) 65 | 66 | -------------------------------------------------------------------------------- /train_pose.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | from torch.nn import init 6 | import torch.optim as optim 7 | from torch.optim import lr_scheduler 8 | from route_data import ROUTEDATA 9 | from route import ROUTENET 10 | from pose_after_route import POSEAFTERROUTE 11 | from utils import GeometryTransformer 12 | 13 | batch_size=16 14 | 15 | dataset = ROUTEDATA() 16 | dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True) 17 | 18 | routenet = ROUTENET(input_dim=9,hid_dim=64).cuda() 19 | 20 | print('use pretrained routenet') 21 | routenet.load_state_dict(torch.load('saved_model/route.model')) 22 | 23 | model = POSEAFTERROUTE(input_dim=65-9,hid_dim=256) 24 | model = model.cuda() 25 | 26 | lrate = 0.001 27 | optimizer = optim.Adam(model.parameters(), lr=lrate) 28 | 29 | for epoch in range(20): 30 | model.train() 31 | total_loss = 0 32 | total_loss_rec = 0 33 | total_loss_motion = 0 34 | total_rec_orient_loss = 0 35 | total_rec_transl_loss = 0 36 | 37 | 38 | for j,data in enumerate(dataloader,0): 39 | 40 | optimizer.zero_grad() 41 | 42 | input_list,middle_list,frame_name,scene_name,sdf,scene_points,cam_extrinsic,s_grid_min,s_grid_max = data 43 | 44 | 45 | input_list = input_list[:,[0,-1],:] 46 | 47 | body = middle_list[:,0:1,6:16].cuda() 48 | input_list = torch.cat([input_list[:,:,:6],input_list[:,:,16:]],dim=2) 49 | middle_list = torch.cat([middle_list[:,:,:6],middle_list[:,:,16:]],dim=2) 50 | 51 | scene_points = scene_points.cuda() 52 | 53 | input_list = input_list.view(-1,62) 54 | six_d_input_list = GeometryTransformer.convert_to_6D_rot(input_list) 55 | six_d_input_list = six_d_input_list.view(-1,2,65) 56 | x = six_d_input_list.cuda() 57 | x1 = six_d_input_list[:,:,:9].cuda() 58 | 59 | route_predict = routenet(x1,scene_points.transpose(1,2)).detach() 60 | route_predict = route_predict.view(x1.shape[0],-1) 61 | 62 | middle_list = middle_list.view(-1,62) 63 | six_d_middle_list = GeometryTransformer.convert_to_6D_rot(middle_list) 64 | six_d_middle_list = six_d_middle_list.view(-1,60,65) 65 | 66 | y = six_d_middle_list[:,:,9:].cuda() 67 | 68 | out = model(x[:,:,9:],scene_points.transpose(1,2),route_predict) 69 | 70 | loss = torch.mean(torch.abs(out-y)) 71 | 72 | loss.backward() 73 | optimizer.step() 74 | 75 | total_loss = total_loss+loss 76 | 77 | print('loss:',total_loss/(j+1)) 78 | 79 | save_path = './saved_model/poseafterroute_'+str(epoch)+'.model' 80 | torch.save(model.state_dict(),save_path) 81 | 82 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Long-term-Motion-in-3D-Scenes 2 | 3 | This is an implementation of the CVPR'21 paper "Synthesizing Long-Term 3D Human Motion and Interaction in 3D". 4 | 5 | Please check our [paper](https://arxiv.org/pdf/2012.05522.pdf) and the [project webpage](https://jiashunwang.github.io/Long-term-Motion-in-3D-Scenes/) for more details. 6 | 7 | ## Citation 8 | 9 | If you use our code or paper, please consider citing: 10 | ``` 11 | @article{wang2020synthesizing, 12 | title={Synthesizing Long-Term 3D Human Motion and Interaction in 3D Scenes}, 13 | author={Wang, Jiashun and Xu, Huazhe and Xu, Jingwei and Liu, Sifei and Wang, Xiaolong}, 14 | journal={arXiv preprint arXiv:2012.05522}, 15 | year={2020} 16 | } 17 | ``` 18 | 19 | ## Dependencies 20 | 21 | Requirements: 22 | - python3.6 23 | - pytorch==1.1.0 24 | - trimesh 25 | - open3d 26 | - [Chamfer Pytorch](https://github.com/ThibaultGROUEIX/ChamferDistancePytorch/tree/719b0f1ca5ba370616cb837c03ab88d9a88173ff) 27 | - [Human Body Prior](https://github.com/nghorbani/human_body_prior) 28 | - [SMPL-X](https://github.com/vchoutas/smplify-x) 29 | 30 | ## Datasets 31 | We use [PROX](https://prox.is.tue.mpg.de/) and [PROXE](https://github.com/yz-cnsdqz/PSI-release) datasets as our training data. After downloading them, please put them in './data/'. We provide `generate_routepose_data.ipynb` and `generate_sub_data.ipynb` for data generation. Note in PROX, the human meshes and the scene meshes are not in the same area in the world coordinates. Different from PROX and PROXE, we apply the inverse of the camera extrinsics to the scene mesh. Since the scene is the input and we need it to be aligned with the human bodies. This is done in the data generation code. Thus for contact calculating, you do not need to apply transformation to them. While for collision calculating, you still need to apply the transformation to the human bodies similar to [PROXE](https://github.com/yz-cnsdqz/PSI-release) to make it be aligned with SDF. Please be careful with this during training or testing, especially if you want to test on other scenes such as [Matterport3D](https://github.com/niessner/Matterport). Please put body_segments data in './data/' as well. 32 | 33 | ## Demo 34 | We provide `demo.ipynb` to help you play with our method. Before running, please put a downsampled `MPH16.ply` mesh and the SDF data of this scene in './demo_data/'. You can download them from [PROX](https://prox.is.tue.mpg.de/) and [PROXE](https://github.com/yz-cnsdqz/PSI-release). Still, please be careful with the camera extrinsics when you want to test other scenes, make sure the human body is in the scene. This code will also show you how to optimize the whole motion. 35 | 36 | ## Models 37 | We use [SMPL-X](https://github.com/vchoutas/smplify-x) to represent human bodies. Please download the SMPL-X models and put them in './models/' and it may look like './models/smplx/SMPLX_NEUTRAL.npz'. Please download [vposer](https://github.com/nghorbani/human_body_prior) model and put it in './' ('./vposer_v1_0/'). 38 | 39 | We also provide our pretrained model [here](https://drive.google.com/file/d/1QyUWmvepAXKk_WYd2C-ZB6CEnl4zpjBS/view?usp=sharing) 40 | 41 | 42 | ## Training 43 | After you generate the data. You can train the networks directly, 44 | ``` 45 | python train_subgoal.py 46 | ``` 47 | ``` 48 | python train_route.py 49 | ``` 50 | Please train the posenet after you finished training routenet with your own pretrained routenet model, 51 | ``` 52 | python train_pose.py 53 | ``` 54 | 55 | 56 | 57 | ## Acknowledgement 58 | This work was supported, in part, by grants from DARPA LwLL, NSF 1730158 CI-New: Cognitive Hardware and Software Ecosystem Community Infrastructure (CHASE-CI), NSF ACI-1541349 CC\*DNI Pacific Research Platform, and gifts from Qualcomm and TuSimple. 59 | Part of our code is based on [PROXE](https://github.com/yz-cnsdqz/PSI-release) and it may help you with the dependencies and dataset parts as well. Many thanks! 60 | 61 | ## License 62 | Apache-2.0 License 63 | -------------------------------------------------------------------------------- /route.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | 6 | class PointNetfeat(nn.Module): 7 | def __init__(self, global_feat = True, feature_transform = False): 8 | super(PointNetfeat, self).__init__() 9 | 10 | self.conv1 = torch.nn.Conv1d(3, 64, 1) 11 | self.conv2 = torch.nn.Conv1d(64, 128, 1) 12 | self.conv3 = torch.nn.Conv1d(128, 256, 1) 13 | self.bn1 = nn.InstanceNorm1d(64) 14 | self.bn2 = nn.InstanceNorm1d(128) 15 | self.bn3 = nn.InstanceNorm1d(256) 16 | self.global_feat = global_feat 17 | self.feature_transform = feature_transform 18 | 19 | 20 | def forward(self, x): 21 | n_pts = x.size()[2] 22 | 23 | x = F.relu(self.bn1(self.conv1(x))) 24 | pointfeat = x 25 | x = F.relu(self.bn2(self.conv2(x))) 26 | x = self.bn3(self.conv3(x)) 27 | x = torch.max(x, 2, keepdim=True)[0] 28 | x = x.view(-1, 256) 29 | 30 | return x 31 | if self.global_feat: 32 | return x, trans, trans_feat 33 | else: 34 | x = x.view(-1, 256, 1).repeat(1, 1, n_pts) 35 | return torch.cat([x, pointfeat], 1)#, trans, trans_feat 36 | 37 | 38 | 39 | 40 | class PointNetDenseCls(nn.Module): 41 | def __init__(self, k = 13, feature_transform=False): 42 | super(PointNetDenseCls, self).__init__() 43 | self.k = k 44 | 45 | self.feat = PointNetfeat(global_feat=False, feature_transform=feature_transform) 46 | self.conv1 = torch.nn.Conv1d(256+64, 256, 1) 47 | self.conv2 = torch.nn.Conv1d(256, 128, 1) 48 | self.conv3 = torch.nn.Conv1d(128, 64, 1) 49 | self.conv4 = torch.nn.Conv1d(64, self.k, 1) 50 | self.bn1 = nn.BatchNorm1d(256) 51 | self.bn2 = nn.BatchNorm1d(128) 52 | self.bn3 = nn.BatchNorm1d(64) 53 | 54 | def forward(self, x): 55 | batchsize = x.size()[0] 56 | n_pts = x.size()[2] 57 | x = self.feat(x) 58 | x = F.relu(self.bn1(self.conv1(x))) 59 | x = F.relu(self.bn2(self.conv2(x))) 60 | x = F.relu(self.bn3(self.conv3(x))) 61 | x = self.conv4(x) 62 | x = x.transpose(2,1).contiguous() 63 | x = F.log_softmax(x.view(-1,self.k), dim=-1) 64 | x = x.view(batchsize, n_pts, self.k) 65 | return x 66 | 67 | 68 | 69 | class ROUTENET(nn.Module): 70 | def __init__(self, input_dim=9, hid_dim=64, n_layers=1, dropout=0,bidirectional=True,scene_model_ckpt=True,device='cuda'): 71 | super().__init__() 72 | self.input_dim = input_dim 73 | self.hid_dim = hid_dim 74 | self.n_layers = n_layers 75 | 76 | 77 | self.lstm = nn.LSTM(input_dim, hid_dim, n_layers, dropout=dropout,bidirectional=bidirectional,batch_first=True) 78 | self.fc_scene = nn.Linear(256,32) 79 | self.fc = nn.Linear(hid_dim*2*2+32,hid_dim*2*2) 80 | self.fc2 = nn.Linear(hid_dim*2*2,60*input_dim) 81 | 82 | pointnet = PointNetDenseCls().to(device)#.cuda() 83 | if scene_model_ckpt is True: 84 | pointnet.load_state_dict(torch.load('./saved_model/point.model')) 85 | removed = list(pointnet.children())[0:1] 86 | self.pointfeature = nn.Sequential(*removed) 87 | 88 | def forward(self, x,scene_points): 89 | 90 | batch_size = x.shape[0] 91 | 92 | outputs, (hidden, cell) = self.lstm(x) 93 | 94 | outputs = outputs.reshape(batch_size,-1) 95 | 96 | pointfea = self.pointfeature(scene_points)#.detach() 97 | 98 | pointfea = self.fc_scene(pointfea) 99 | outputs = torch.cat([outputs,pointfea],dim=1) 100 | 101 | outputs = F.relu(self.fc(outputs)) 102 | outputs = self.fc2(outputs) 103 | 104 | outputs = outputs.reshape(batch_size,60,self.input_dim) 105 | 106 | return outputs 107 | -------------------------------------------------------------------------------- /pose_after_route.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | 6 | class PointNetfeat(nn.Module): 7 | def __init__(self, global_feat = True, feature_transform = False): 8 | super(PointNetfeat, self).__init__() 9 | 10 | self.conv1 = torch.nn.Conv1d(3, 64, 1) 11 | self.conv2 = torch.nn.Conv1d(64, 128, 1) 12 | self.conv3 = torch.nn.Conv1d(128, 256, 1) 13 | self.bn1 = nn.InstanceNorm1d(64) 14 | self.bn2 = nn.InstanceNorm1d(128) 15 | self.bn3 = nn.InstanceNorm1d(256) 16 | self.global_feat = global_feat 17 | self.feature_transform = feature_transform 18 | 19 | 20 | def forward(self, x): 21 | n_pts = x.size()[2] 22 | 23 | x = F.relu(self.bn1(self.conv1(x))) 24 | pointfeat = x 25 | x = F.relu(self.bn2(self.conv2(x))) 26 | x = self.bn3(self.conv3(x)) 27 | x = torch.max(x, 2, keepdim=True)[0] 28 | x = x.view(-1, 256) 29 | 30 | return x 31 | if self.global_feat: 32 | return x, trans, trans_feat 33 | else: 34 | x = x.view(-1, 256, 1).repeat(1, 1, n_pts) 35 | return torch.cat([x, pointfeat], 1)#, trans, trans_feat 36 | 37 | class PointNetDenseCls(nn.Module): 38 | def __init__(self, k = 13, feature_transform=False): 39 | super(PointNetDenseCls, self).__init__() 40 | self.k = k 41 | #self.feature_transform=feature_transform 42 | self.feat = PointNetfeat(global_feat=False, feature_transform=feature_transform) 43 | self.conv1 = torch.nn.Conv1d(256+64, 256, 1) 44 | self.conv2 = torch.nn.Conv1d(256, 128, 1) 45 | self.conv3 = torch.nn.Conv1d(128, 64, 1) 46 | self.conv4 = torch.nn.Conv1d(64, self.k, 1) 47 | self.bn1 = nn.BatchNorm1d(256) 48 | self.bn2 = nn.BatchNorm1d(128) 49 | self.bn3 = nn.BatchNorm1d(64) 50 | 51 | def forward(self, x): 52 | batchsize = x.size()[0] 53 | n_pts = x.size()[2] 54 | x = self.feat(x) 55 | x = F.relu(self.bn1(self.conv1(x))) 56 | x = F.relu(self.bn2(self.conv2(x))) 57 | x = F.relu(self.bn3(self.conv3(x))) 58 | x = self.conv4(x) 59 | x = x.transpose(2,1).contiguous() 60 | x = F.log_softmax(x.view(-1,self.k), dim=-1) 61 | x = x.view(batchsize, n_pts, self.k) 62 | return x 63 | 64 | 65 | class POSEAFTERROUTE(nn.Module): 66 | def __init__(self, input_dim=65, hid_dim=256, n_layers=1, dropout=0,bidirectional=True,scene_model_ckpt=True,device='cuda'): 67 | super().__init__() 68 | self.input_dim = input_dim 69 | self.hid_dim = hid_dim 70 | self.n_layers = n_layers 71 | 72 | self.lstm = nn.LSTM(input_dim, hid_dim, n_layers, dropout=dropout,bidirectional=bidirectional,batch_first=True) 73 | self.fc_scene = nn.Linear(256,32) 74 | self.fc_path = nn.Linear(60*9,64) 75 | self.fc = nn.Linear(hid_dim*2*2+32+64,hid_dim*2*2) 76 | self.fc2 = nn.Linear(hid_dim*2*2,60*input_dim) 77 | 78 | pointnet = PointNetDenseCls().to(device) 79 | if scene_model_ckpt is True: 80 | pointnet.load_state_dict(torch.load('./saved_model/point.model')) 81 | removed = list(pointnet.children())[0:1] 82 | self.pointfeature = nn.Sequential(*removed) 83 | 84 | def forward(self, x,scene_points,path): 85 | 86 | batch_size=x.shape[0] 87 | 88 | outputs, (hidden, cell) = self.lstm(x) 89 | 90 | outputs=outputs.reshape(batch_size,-1) 91 | pointfea=self.pointfeature(scene_points)#.detach() 92 | 93 | pointfea=self.fc_scene(pointfea) 94 | path=self.fc_path(path) 95 | outputs=torch.cat([outputs,pointfea,path],dim=1) 96 | 97 | outputs=F.relu(self.fc(outputs)) 98 | outputs=self.fc2(outputs) 99 | 100 | outputs=outputs.reshape(batch_size,60,self.input_dim) 101 | 102 | return outputs 103 | -------------------------------------------------------------------------------- /sub_goal.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | import torchvision 4 | 5 | import torch.nn as nn 6 | import torch.nn.functional as F 7 | import torchgeometry as tgm 8 | 9 | import random 10 | from torch.nn import init 11 | import functools 12 | from torch.optim import lr_scheduler 13 | 14 | import sys, os 15 | import json 16 | 17 | from net_layers import BodyGlobalPoseVAE, BodyLocalPoseVAE, ResBlock 18 | 19 | class PointNetfeat(nn.Module): 20 | def __init__(self, global_feat = True, feature_transform = False): 21 | super(PointNetfeat, self).__init__() 22 | #self.stn = STN3d() 23 | self.conv1 = torch.nn.Conv1d(3, 64, 1) 24 | self.conv2 = torch.nn.Conv1d(64, 128, 1) 25 | self.conv3 = torch.nn.Conv1d(128, 256, 1) 26 | self.bn1 = nn.InstanceNorm1d(64) 27 | self.bn2 = nn.InstanceNorm1d(128) 28 | self.bn3 = nn.InstanceNorm1d(256) 29 | self.global_feat = global_feat 30 | self.feature_transform = feature_transform 31 | #if self.feature_transform: 32 | # self.fstn = STNkd(k=64) 33 | 34 | def forward(self, x): 35 | n_pts = x.size()[2] 36 | # trans = self.stn(x) 37 | # x = x.transpose(2, 1) 38 | # x = torch.bmm(x, trans) 39 | # x = x.transpose(2, 1) 40 | x = F.relu(self.bn1(self.conv1(x))) 41 | 42 | pointfeat = x 43 | x = F.relu(self.bn2(self.conv2(x))) 44 | x = self.bn3(self.conv3(x)) 45 | x = torch.max(x, 2, keepdim=True)[0] 46 | x = x.view(-1, 256) 47 | 48 | return x 49 | if self.global_feat: 50 | return x, trans, trans_feat 51 | else: 52 | x = x.view(-1, 256, 1).repeat(1, 1, n_pts) 53 | return torch.cat([x, pointfeat], 1)#, trans, trans_feat 54 | 55 | 56 | class PointNetDenseCls(nn.Module): 57 | def __init__(self, k = 13, feature_transform=False): 58 | super(PointNetDenseCls, self).__init__() 59 | self.k = k 60 | #self.feature_transform=feature_transform 61 | self.feat = PointNetfeat(global_feat=False, feature_transform=feature_transform) 62 | self.conv1 = torch.nn.Conv1d(256+64, 256, 1) 63 | self.conv2 = torch.nn.Conv1d(256, 128, 1) 64 | self.conv3 = torch.nn.Conv1d(128, 64, 1) 65 | self.conv4 = torch.nn.Conv1d(64, self.k, 1) 66 | self.bn1 = nn.BatchNorm1d(256) 67 | self.bn2 = nn.BatchNorm1d(128) 68 | self.bn3 = nn.BatchNorm1d(64) 69 | 70 | def forward(self, x): 71 | batchsize = x.size()[0] 72 | n_pts = x.size()[2] 73 | x = self.feat(x) 74 | x = F.relu(self.bn1(self.conv1(x))) 75 | x = F.relu(self.bn2(self.conv2(x))) 76 | x = F.relu(self.bn3(self.conv3(x))) 77 | x = self.conv4(x) 78 | x = x.transpose(2,1).contiguous() 79 | x = F.log_softmax(x.view(-1,self.k), dim=-1) 80 | x = x.view(batchsize, n_pts, self.k) 81 | return x 82 | 83 | 84 | 85 | 86 | 87 | 88 | class Pointnet(nn.Module): 89 | def __init__(self): 90 | super().__init__() 91 | 92 | self.conv1 = torch.nn.Conv1d(3, 64, 1) 93 | self.conv2 = torch.nn.Conv1d(64, 128, 1) 94 | self.conv3 = torch.nn.Conv1d(128, 256, 1) 95 | 96 | self.norm1 = torch.nn.InstanceNorm1d(64) 97 | self.norm2 = torch.nn.InstanceNorm1d(128) 98 | self.norm3 = torch.nn.InstanceNorm1d(256) 99 | 100 | def forward(self, x): 101 | 102 | x = F.relu(self.norm1(self.conv1(x))) 103 | 104 | x = F.relu(self.norm2(self.conv2(x))) 105 | x = F.relu(self.norm3(self.conv3(x))) 106 | x,_ = torch.max(x, 2) 107 | x = x.view(-1, 256) 108 | 109 | return x 110 | 111 | 112 | class SUBGOAL(nn.Module): 113 | 114 | def __init__(self, 115 | latentD=512, 116 | n_dim_body=62, 117 | scene_model_ckpt=True, 118 | device='cuda' 119 | ): 120 | 121 | super(SUBGOAL, self).__init__() 122 | 123 | self.device=device 124 | self.eps_d = 32 125 | 126 | 127 | pointnet = PointNetDenseCls().to(self.device) 128 | if scene_model_ckpt is True: 129 | pointnet.load_state_dict(torch.load('0811_in_256_4.model')) 130 | removed=list(pointnet.children())[0:1] 131 | self.pointfeature=nn.Sequential(*removed) 132 | self.fc=nn.Linear(1024,256) 133 | self.condition_encoder=nn.Linear(256+9+10,latentD)#256+3+6+6 134 | 135 | self.linear_in = nn.Linear(n_dim_body, latentD) 136 | self.human_encoder = nn.Sequential(ResBlock(2*latentD), 137 | ResBlock(2*latentD)) 138 | 139 | self.mu_enc = nn.Linear(2*latentD, self.eps_d) 140 | self.logvar_enc = nn.Linear(2*latentD, self.eps_d) 141 | 142 | self.linear_latent = nn.Linear(self.eps_d, latentD) 143 | self.human_decoder = nn.Sequential(ResBlock(2*latentD), 144 | ResBlock(2*latentD)) 145 | 146 | self.linear_out = nn.Linear(2*latentD, n_dim_body) 147 | 148 | 149 | 150 | def _sampler(self, mu, logvar): 151 | var = logvar.mul(0.5).exp_() 152 | eps = torch.FloatTensor(var.size()).normal_() 153 | eps = eps.to(self.device) 154 | return eps.mul(var).add_(mu) 155 | 156 | 157 | def forward(self, x_body, x_s, z_loc, body): 158 | ''' 159 | x_body: body representation, [batch, 65] 160 | x_s: point of scene, [batch, 3, N] 161 | loc: target_loc, [batch, 3] 162 | body: body, [batch,10] 163 | ''' 164 | 165 | b_ = x_s.shape[0] 166 | 167 | z_s = self.pointfeature(x_s) #z_s, [batch,1024] 168 | 169 | z_input = torch.cat([z_s,z_loc,body],dim=1) 170 | 171 | z_input = self.condition_encoder(z_input) #[batch,latentD] 172 | 173 | 174 | z_h = self.linear_in(x_body) 175 | 176 | z_ = torch.cat([z_h, z_input], dim=1) 177 | z_ = self.human_encoder(z_) 178 | 179 | mu = self.mu_enc(z_) 180 | logvar = self.logvar_enc(z_) 181 | 182 | z_ = self._sampler(mu, logvar) 183 | z_ = self.linear_latent(z_) 184 | z_hs = torch.cat([z_, z_input], dim=1) 185 | 186 | z_hs = self.human_decoder(z_hs) 187 | 188 | x_body_rec = self.linear_out(z_hs) 189 | 190 | 191 | return x_body_rec, mu, logvar 192 | 193 | 194 | 195 | def sample(self, x_body, x_s, loc, body): 196 | 197 | b_ = x_s.shape[0] 198 | 199 | z_s = self.pointfeature(x_s) #z_s, [batch,1024] 200 | 201 | z_loc = loc 202 | 203 | z_input=torch.cat([z_s,z_loc,body],dim=1) 204 | 205 | 206 | z_input=self.condition_encoder(z_input) #[batch,latentD] 207 | 208 | 209 | eps = torch.randn([b_, self.eps_d],dtype=torch.float32).to(self.device) 210 | 211 | z_h = self.linear_latent(eps) 212 | z_hs = torch.cat([z_h, z_input], dim=1) 213 | z_hs = self.human_decoder(z_hs) 214 | x_body_gen = self.linear_out(z_hs) 215 | 216 | return x_body_gen 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | -------------------------------------------------------------------------------- /train_subgoal.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.optim as optim 3 | import numpy as np 4 | from sub_data import SUBDATA 5 | import time 6 | import torch.nn.functional as F 7 | from human_body_prior.tools.model_loader import load_vposer 8 | from utils import BodyParamParser, ContinousRotReprDecoder, GeometryTransformer 9 | import smplx 10 | import chamfer_pytorch.dist_chamfer as ext 11 | from sub_goal import Pointnet,SUBGOAL 12 | 13 | start = time.time() 14 | batch_size = 8 15 | dataset = SUBDATA() 16 | dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True) 17 | 18 | contact_id_folder = './data/body_segments' 19 | contact_part = ['back','gluteus','L_Hand','R_Hand','L_Leg','R_Leg','thighs'] 20 | 21 | vposer, _ = load_vposer('./vposer_v1_0', vp_model='snapshot') 22 | vposer = vposer.cuda() 23 | 24 | body_mesh_model = smplx.create('./models', 25 | model_type='smplx', 26 | gender='neutral', ext='npz', 27 | num_pca_comps=12, 28 | create_global_orient=True, 29 | create_body_pose=True, 30 | create_betas=True, 31 | create_left_hand_pose=True, 32 | create_right_hand_pose=True, 33 | create_expression=True, 34 | create_jaw_pose=True, 35 | create_leye_pose=True, 36 | create_reye_pose=True, 37 | create_transl=True, 38 | batch_size=batch_size 39 | ) 40 | 41 | body_mesh_model = body_mesh_model.cuda() 42 | print('finish data loading time:',time.time()-start) 43 | 44 | model = SUBGOAL(n_dim_body=65) 45 | model = model.cuda() 46 | lrate = 0.0005 47 | optimizer = optim.Adam(model.parameters(), lr=lrate) 48 | 49 | for epoch in range(50): 50 | 51 | start_time = time.time() 52 | 53 | 54 | total_loss = 0 55 | total_collision_loss = 0 56 | total_contact_loss = 0 57 | total_kl_loss = 0 58 | total_rec_loss = 0 59 | total_rec_orient_loss = 0 60 | total_rec_transl_loss = 0 61 | 62 | for j,data in enumerate(dataloader,0): 63 | optimizer.zero_grad() 64 | 65 | 66 | middle_list,_,scene_name,sdf,scene_points,cam_extrinsic,s_grid_min_batch,s_grid_max_batch = data 67 | 68 | body = middle_list[:,0,6:16].cuda() 69 | 70 | middle_list = torch.cat([middle_list[:,:,:6],middle_list[:,:,16:]],dim=2) 71 | 72 | middle = middle_list[:,0,:].cuda() 73 | scene_points = scene_points.cuda() 74 | sdf = sdf.cuda() 75 | s_grid_max_batch = s_grid_max_batch.cuda() 76 | s_grid_min_batch = s_grid_min_batch.cuda() 77 | 78 | middle = GeometryTransformer.convert_to_6D_rot(middle) 79 | 80 | rec, mu, logsigma2 = model(middle,scene_points.transpose(1,2),middle[:,:9],body) 81 | 82 | 83 | loss_rec_transl = 0.5*(F.l1_loss(rec[:,:3], middle[:,:3])) 84 | loss_rec_orient = (F.l1_loss(rec[:,3:9], middle[:,3:9])) 85 | loss_rec = (F.l1_loss(rec[:,9:41], middle[:,9:41]))+loss_rec_transl+loss_rec_orient+0.1*F.l1_loss(rec[:,41:], middle[:,41:]) 86 | 87 | fca = 1.0 88 | fca = min(1.0, max(float(epoch) / (10*0.75),0) ) 89 | loss_KL = (fca**2 * 0.1*torch.mean(torch.exp(logsigma2) +mu**2 -1.0 -logsigma2)) 90 | 91 | #body mesh 92 | 93 | rec = GeometryTransformer.convert_to_3D_rot(rec) 94 | body_param_rec = BodyParamParser.body_params_encapsulate_batch_nobody_hand(rec) 95 | body_param_rec['body_pose'] = vposer.decode(body_param_rec['body_pose'], 96 | output_type='aa').view(rec.shape[0], -1) 97 | body_param_rec['betas'] = body 98 | 99 | smplx_output = body_mesh_model(return_verts=True, **body_param_rec) 100 | 101 | #body_verts_batch is with scene pointcloud 102 | #body_verts_batch_ is with scene sdf 103 | 104 | body_verts_batch = smplx_output.vertices #[b, 10475,3] 105 | body_verts_batch_ = GeometryTransformer.verts_transform(body_verts_batch, torch.tensor(cam_extrinsic,dtype=torch.float32).cuda()) 106 | 107 | 108 | #contact loss 109 | vid, fid = GeometryTransformer.get_contact_id(body_segments_folder=contact_id_folder, 110 | contact_body_parts=contact_part) 111 | 112 | body_verts_contact_batch = body_verts_batch[:, vid, :] 113 | dist_chamfer_contact = ext.chamferDist() 114 | 115 | contact_dist, _ = dist_chamfer_contact( 116 | body_verts_contact_batch.contiguous(), 117 | scene_points.contiguous() 118 | ) 119 | 120 | loss_contact = (1 * torch.mean( torch.sqrt(contact_dist+1e-4) 121 | /(torch.sqrt(contact_dist+1e-4)+1.0) ) ) 122 | 123 | #collision loss 124 | norm_verts_batch = ((body_verts_batch_ - s_grid_min_batch.unsqueeze(1)) 125 | / (s_grid_max_batch.unsqueeze(1) - s_grid_min_batch.unsqueeze(1)) *2 -1) 126 | 127 | n_verts = norm_verts_batch.shape[1] 128 | 129 | body_sdf_batch = F.grid_sample(sdf.unsqueeze(1), 130 | norm_verts_batch[:,:,[2,1,0]].view(-1, n_verts,1,1,3), 131 | padding_mode='border') 132 | 133 | if body_sdf_batch.lt(0).sum().item() < 1: 134 | loss_sdf_pene = torch.tensor(0.0, dtype=torch.float32).cuda() 135 | 136 | else: 137 | loss_sdf_pene = body_sdf_batch[body_sdf_batch < 0].abs().mean() 138 | 139 | loss_KL = loss_KL 140 | loss_rec = 0.1*loss_rec 141 | loss_sdf_pene = 0.01*loss_sdf_pene 142 | loss_contact = 0.01*loss_contact 143 | 144 | loss = loss_KL+loss_rec+loss_sdf_pene+loss_contact 145 | 146 | loss.backward() 147 | optimizer.step() 148 | 149 | total_collision_loss = total_collision_loss+loss_sdf_pene 150 | total_loss = total_loss+loss 151 | 152 | total_contact_loss = total_contact_loss+loss_contact 153 | total_kl_loss = total_kl_loss+loss_KL 154 | total_rec_loss = total_rec_loss+loss_rec 155 | total_rec_orient_loss = total_rec_orient_loss+0.1*loss_rec_orient 156 | total_rec_transl_loss = total_rec_transl_loss+0.1*loss_rec_transl 157 | 158 | print('##################################') 159 | print('##################################') 160 | print('epoch:',epoch) 161 | end_time=time.time() 162 | print('time:',end_time-start_time) 163 | print('total:',total_loss/((j+1))) 164 | print('collison:',total_collision_loss/(j+1)) 165 | print('contact:',total_contact_loss/((j+1))) 166 | print('kl:',total_kl_loss/(j+1)) 167 | print('rec_orient:',total_rec_orient_loss/(j+1)) 168 | print('rec_transl:',total_rec_transl_loss/(j+1)) 169 | print('rec:',total_rec_loss/(j+1)) 170 | 171 | print('##################################') 172 | print('##################################') 173 | 174 | if (epoch+1) % 5 == 0: 175 | save_path = './saved_model/subgoal_'+str(epoch)+'.model' 176 | print(save_path) 177 | torch.save(model.state_dict(),save_path) 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | -------------------------------------------------------------------------------- /net_layers.py: -------------------------------------------------------------------------------- 1 | import copy 2 | import torch 3 | import torchvision 4 | import torch.nn as nn 5 | import sys, os 6 | 7 | 8 | class Swish(nn.Module): 9 | 10 | def __init__(self): 11 | ''' 12 | Init method. 13 | ''' 14 | super().__init__() # init the base class 15 | 16 | def forward(self, x): 17 | ''' 18 | Forward pass of the function. 19 | ''' 20 | return x * torch.sigmoid(x) 21 | 22 | 23 | 24 | class ResBlock(nn.Module): 25 | def __init__(self, n_dim): 26 | super(ResBlock, self).__init__() 27 | 28 | self.n_dim = n_dim 29 | 30 | self.fc1 = nn.Linear(n_dim, n_dim) 31 | self.fc2 = nn.Linear(n_dim, n_dim) 32 | self.acfun = nn.LeakyReLU() 33 | 34 | def forward(self, x0): 35 | 36 | x = self.acfun(self.fc1(x0)) 37 | x = self.acfun(self.fc2(x)) 38 | x = x+x0 39 | return x 40 | 41 | 42 | 43 | class BodyGlobalPoseVAE(nn.Module): 44 | def __init__(self,zdim,num_hidden=512,f_dim=32,test=False,in_dim=3, 45 | pretrained_resnet='resnet18.pth'): 46 | super(BodyGlobalPoseVAE, self).__init__() 47 | 48 | 49 | self.test = test 50 | self.zdim = zdim 51 | 52 | resnet = torchvision.models.resnet18() 53 | if pretrained_resnet is not None: 54 | print('[INFO][%s] Using pretrained resnet18 weights.'.format(self.__class__.__name__)) 55 | resnet.load_state_dict(torch.load(pretrained_resnet)) 56 | removed = list(resnet.children())[1:6] 57 | self.resnet = nn.Sequential(nn.Conv2d(in_dim, 64, kernel_size=7, 58 | stride=2, padding=3,bias=False), 59 | *removed) 60 | self.conv = nn.Conv2d(128,f_dim,3,1,1) # b x f_dim x 28 x 28 61 | self.fc = nn.Linear(f_dim*16*16,num_hidden) 62 | 63 | 64 | ############ encoder torso ############ 65 | self.torso_linear = nn.Linear(3,num_hidden) 66 | 67 | ############ mix all conditions ############ 68 | self.encode = nn.Sequential(ResBlock(n_dim=2*num_hidden), 69 | ResBlock(n_dim=2*num_hidden)) 70 | 71 | 72 | self.mean_linear = nn.Linear(2*num_hidden,zdim) 73 | self.log_var_linear = nn.Linear(2*num_hidden,zdim) 74 | 75 | 76 | 77 | ############ decoder for the scene+torso feature ####### 78 | self.decode = nn.Sequential(nn.Linear(num_hidden+zdim, f_dim), 79 | ResBlock(n_dim=f_dim), 80 | ResBlock(n_dim=f_dim), 81 | nn.Linear(f_dim, 3)) 82 | 83 | 84 | def sampler(self, mu, logvar): 85 | var = logvar.mul(0.5).exp_() 86 | eps = torch.FloatTensor(var.size()).normal_() 87 | eps = eps.cuda() 88 | return eps.mul(var).add_(mu) 89 | 90 | 91 | def forward(self,scene,torso=None): 92 | if self.test: 93 | b = scene.size(0) 94 | z = torch.Tensor(b,self.zdim).cuda() 95 | z.normal_(0,1) 96 | 97 | fscene_ = self.conv(self.resnet(scene)) 98 | z_s = self.fc(fscene_.view(b,-1)) # bxnum_hidden 99 | z_sg = torch.cat([z, z_s],dim=1) 100 | x_g_gen = self.decode(z_sg) 101 | 102 | return x_g_gen 103 | 104 | else: 105 | b = scene.size(0) 106 | 107 | ############# encoder #################### 108 | fscene_ = self.conv(self.resnet(scene)) 109 | z_s = self.fc(fscene_.view(b,-1)) # bxnum_hidden 110 | 111 | ###### torso ###### 112 | ftorso = self.torso_linear(torso) 113 | 114 | fc_cls_torso = torch.cat((z_s,ftorso),dim=1) 115 | # fc_cls_torso = z_s+ftorso 116 | feature = self.encode(fc_cls_torso) 117 | 118 | mean = self.mean_linear(feature) 119 | log_var = self.log_var_linear(feature) 120 | 121 | 122 | ############# sampling ################# 123 | z = self.sampler(mean, log_var) 124 | 125 | 126 | ############# decoder ################## 127 | z_sg = torch.cat([z, z_s],dim=1) 128 | x_g_rec = self.decode(z_sg) 129 | 130 | return x_g_rec, mean, log_var 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | class BodyLocalPoseVAE(nn.Module): 141 | def __init__(self,zdim,num_hidden=512,f_dim=128,test=False,in_dim=3, 142 | pretrained_resnet='resnet18.pth'): 143 | super(BodyLocalPoseVAE, self).__init__() 144 | 145 | self.test = test 146 | self.zdim = zdim 147 | 148 | resnet = torchvision.models.resnet18() 149 | if pretrained_resnet is not None: 150 | print('[INFO][%s] Using pretrained resnet18 weights.'.format(self.__class__.__name__)) 151 | resnet.load_state_dict(torch.load(pretrained_resnet)) 152 | removed = list(resnet.children())[1:6] 153 | self.resnet = nn.Sequential(nn.Conv2d(in_dim, 64, kernel_size=7, 154 | stride=2, padding=3, 155 | bias=False), 156 | *removed) 157 | self.conv = nn.Conv2d(128,f_dim,3,1,1) # b x f_dim x 28 x 28 158 | self.fc = nn.Linear(f_dim*16*16,num_hidden) 159 | 160 | 161 | 162 | ############ encoder torso & body branch ############ 163 | self.torso_linear = nn.Linear(3,num_hidden) 164 | self.pose_linear = nn.Linear(72,num_hidden) 165 | 166 | ############ mix all conditions ############ 167 | self.encode = nn.Sequential(ResBlock(n_dim=3*num_hidden), 168 | ResBlock(n_dim=3*num_hidden)) 169 | 170 | 171 | self.mean_linear = nn.Linear(3*num_hidden,zdim) 172 | self.log_var_linear = nn.Linear(3*num_hidden,zdim) 173 | 174 | 175 | 176 | ############ decoder for the scene+torso feature ####### 177 | self.decode = nn.Sequential(nn.Linear(2*num_hidden+zdim, f_dim), 178 | ResBlock(n_dim=f_dim), 179 | ResBlock(n_dim=f_dim), 180 | nn.Linear(f_dim, 72)) 181 | 182 | 183 | 184 | def sampler(self, mu, logvar): 185 | var = logvar.mul(0.5).exp_() 186 | eps = torch.FloatTensor(var.size()).normal_() 187 | eps = eps.cuda() 188 | return eps.mul(var).add_(mu) 189 | 190 | 191 | def forward(self,scene, torso=None, pose=None): 192 | if self.test: 193 | b = scene.size(0) 194 | z = torch.Tensor(b,self.zdim).cuda() 195 | z.normal_(0,1) 196 | 197 | fscene_ = self.conv(self.resnet(scene)) 198 | z_s = self.fc(fscene_.view(b,-1)) # bxnum_hidden 199 | z_g = self.torso_linear(torso) 200 | 201 | z_sgl = torch.cat([z, z_g, z_s],dim=1) 202 | x_g_gen = self.decode(z_sgl) 203 | 204 | return x_g_gen 205 | else: 206 | 207 | b = scene.size(0) 208 | 209 | ############# encoder #################### 210 | fscene_ = self.conv(self.resnet(scene)) 211 | z_s = self.fc(fscene_.view(b,-1)) # bxnum_hidden 212 | 213 | z_g = self.torso_linear(torso) 214 | z_l = self.pose_linear(pose) 215 | 216 | z_sgl = torch.cat([z_l, z_g, z_s] ,dim=1) 217 | 218 | feature = self.encode(z_sgl) 219 | 220 | mean = self.mean_linear(feature) 221 | log_var = self.log_var_linear(feature) 222 | 223 | ############# sampling ################# 224 | z = self.sampler(mean, log_var) 225 | 226 | ############# decoder ################## 227 | z_sgl = torch.cat([z, z_g, z_s],dim=1) 228 | x_l_rec = self.decode(z_sgl) 229 | 230 | return x_l_rec, mean, log_var 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import open3d as o3d 2 | import numpy as np 3 | import torch 4 | import torchvision 5 | 6 | import torch.nn as nn 7 | import torch.nn.functional as F 8 | import torchgeometry as tgm 9 | 10 | import random 11 | from torch.nn import init 12 | import functools 13 | from torch.optim import lr_scheduler 14 | 15 | import sys, os 16 | import json 17 | 18 | 19 | class ContinousRotReprDecoder(nn.Module): 20 | ''' 21 | - this class encodes/decodes rotations with the 6D continuous representation 22 | - Zhou et al., On the continuity of rotation representations in neural networks 23 | - also used in the VPoser (see smplx) 24 | ''' 25 | 26 | def __init__(self): 27 | super(ContinousRotReprDecoder, self).__init__() 28 | 29 | def forward(self, module_input): 30 | reshaped_input = module_input.view(-1, 3, 2) 31 | 32 | b1 = F.normalize(reshaped_input[:, :, 0], dim=1) 33 | 34 | dot_prod = torch.sum(b1 * reshaped_input[:, :, 1], dim=1, keepdim=True) 35 | b2 = F.normalize(reshaped_input[:, :, 1] - dot_prod * b1, dim=-1) 36 | b3 = torch.cross(b1, b2, dim=1) 37 | 38 | return torch.stack([b1, b2, b3], dim=-1) 39 | 40 | 41 | @staticmethod 42 | def decode(module_input): 43 | reshaped_input = module_input.view(-1, 3, 2) 44 | 45 | b1 = F.normalize(reshaped_input[:, :, 0], dim=1) 46 | 47 | dot_prod = torch.sum(b1 * reshaped_input[:, :, 1], dim=1, keepdim=True) 48 | b2 = F.normalize(reshaped_input[:, :, 1] - dot_prod * b1, dim=-1) 49 | b3 = torch.cross(b1, b2, dim=1) 50 | 51 | return torch.stack([b1, b2, b3], dim=-1) 52 | 53 | 54 | @staticmethod 55 | def matrot2aa(pose_matrot): 56 | ''' 57 | :param pose_matrot: Nx1xnum_jointsx9 58 | :return: Nx1xnum_jointsx3 59 | ''' 60 | 61 | homogen_matrot = F.pad(pose_matrot.view(-1, 3, 3), [0,1]) 62 | pose = tgm.rotation_matrix_to_angle_axis(homogen_matrot).view(-1, 3).contiguous() 63 | return pose 64 | 65 | @staticmethod 66 | def aa2matrot(pose): 67 | ''' 68 | :param Nx1xnum_jointsx3 69 | :return: pose_matrot: Nx1xnum_jointsx9 70 | ''' 71 | pose_body_matrot = tgm.angle_axis_to_rotation_matrix(pose.reshape(-1, 3))[:, :3, :3].contiguous() 72 | return pose_body_matrot 73 | 74 | 75 | class GeometryTransformer(): 76 | 77 | @staticmethod 78 | def get_contact_id(body_segments_folder, contact_body_parts=['L_Hand', 'R_Hand']): 79 | 80 | contact_verts_ids = [] 81 | contact_faces_ids = [] 82 | 83 | for part in contact_body_parts: 84 | with open(os.path.join(body_segments_folder, part + '.json'), 'r') as f: 85 | data = json.load(f) 86 | contact_verts_ids.append(list(set(data["verts_ind"]))) 87 | contact_faces_ids.append(list(set(data["faces_ind"]))) 88 | 89 | contact_verts_ids = np.concatenate(contact_verts_ids) 90 | contact_faces_ids = np.concatenate(contact_faces_ids) 91 | 92 | 93 | return contact_verts_ids, contact_faces_ids 94 | 95 | @staticmethod 96 | def convert_to_6D_rot(x_batch): 97 | xt = x_batch[:,:3] 98 | xr = x_batch[:,3:6] 99 | xb = x_batch[:, 6:] 100 | 101 | xr_mat = ContinousRotReprDecoder.aa2matrot(xr) # return [:,3,3] 102 | xr_repr = xr_mat[:,:,:-1].reshape([-1,6]) 103 | 104 | return torch.cat([xt, xr_repr, xb], dim=-1) 105 | 106 | @staticmethod 107 | def convert_to_3D_rot(x_batch): 108 | xt = x_batch[:,:3] 109 | xr = x_batch[:,3:9] 110 | xb = x_batch[:,9:] 111 | 112 | xr_mat = ContinousRotReprDecoder.decode(xr) # return [:,3,3] 113 | xr_aa = ContinousRotReprDecoder.matrot2aa(xr_mat) # return [:,3] 114 | 115 | return torch.cat([xt, xr_aa, xb], dim=-1) 116 | 117 | 118 | 119 | @staticmethod 120 | def verts_transform(verts_batch, cam_ext_batch): 121 | verts_batch_homo = F.pad(verts_batch, (0,1), mode='constant', value=1) 122 | verts_batch_homo_transformed = torch.matmul(verts_batch_homo, 123 | cam_ext_batch.permute(0,2,1)) 124 | 125 | verts_batch_transformed = verts_batch_homo_transformed[:,:,:-1] 126 | 127 | return verts_batch_transformed 128 | 129 | 130 | @staticmethod 131 | def recover_global_T(x_batch, cam_intrisic, max_depth): 132 | xt_batch = x_batch[:,:3] 133 | xr_batch = x_batch[:,3:] 134 | 135 | fx_batch = cam_intrisic[:,0,0] 136 | fy_batch = cam_intrisic[:,1,1] 137 | # fx_batch = 1000 138 | # fy_batch = 1000 139 | px_batch = cam_intrisic[:,0,2] 140 | py_batch = cam_intrisic[:,1,2] 141 | s_ = 1.0 / torch.max(px_batch, py_batch) 142 | 143 | z = (xt_batch[:, 2]+1.0)/2.0 * max_depth 144 | 145 | x = xt_batch[:,0] * z / s_ / fx_batch 146 | y = xt_batch[:,1] * z / s_ / fy_batch 147 | 148 | xt_batch_recoverd = torch.stack([x,y,z],dim=-1) 149 | 150 | return torch.cat([xt_batch_recoverd, xr_batch],dim=-1) 151 | 152 | 153 | @staticmethod 154 | def normalize_global_T(x_batch, cam_intrisic, max_depth): 155 | ''' 156 | according to the camera intrisics and maximal depth, 157 | normalize the global translate to [-1, 1] for X, Y and Z. 158 | input: [transl, rotation, local params] 159 | ''' 160 | 161 | xt_batch = x_batch[:,:3] 162 | xr_batch = x_batch[:,3:] 163 | 164 | fx_batch = cam_intrisic[:,0,0] 165 | fy_batch = cam_intrisic[:,1,1] 166 | px_batch = cam_intrisic[:,0,2] 167 | py_batch = cam_intrisic[:,1,2] 168 | s_ = 1.0 / torch.max(px_batch, py_batch) 169 | x = s_* xt_batch[:,0]*fx_batch / (xt_batch[:,2] + 1e-6) 170 | y = s_* xt_batch[:,1]*fy_batch / (xt_batch[:,2] + 1e-6) 171 | 172 | z = 2.0*xt_batch[:,2] / max_depth - 1.0 173 | 174 | xt_batch_normalized = torch.stack([x,y,z],dim=-1) 175 | 176 | 177 | return torch.cat([xt_batch_normalized, xr_batch],dim=-1) 178 | 179 | 180 | 181 | 182 | class BodyParamParser(): 183 | 184 | @staticmethod 185 | def body_params_encapsulate(x_body_rec): 186 | x_body_rec_np = x_body_rec.detach().cpu().numpy() 187 | n_batch = x_body_rec_np.shape[0] 188 | rec_list = [] 189 | 190 | for b in range(n_batch): 191 | body_params_batch_rec={} 192 | body_params_batch_rec['transl'] = x_body_rec_np[b:b+1,:3] 193 | body_params_batch_rec['global_orient'] = x_body_rec_np[b:b+1,3:6] 194 | body_params_batch_rec['betas'] = x_body_rec_np[b:b+1,6:16] 195 | body_params_batch_rec['body_pose'] = x_body_rec_np[b:b+1,16:48] 196 | body_params_batch_rec['left_hand_pose'] = x_body_rec_np[b:b+1,48:60] 197 | body_params_batch_rec['right_hand_pose'] = x_body_rec_np[b:b+1,60:] 198 | rec_list.append(body_params_batch_rec) 199 | 200 | return rec_list 201 | 202 | 203 | @staticmethod 204 | def body_params_encapsulate_batch(x_body_rec): 205 | 206 | body_params_batch_rec={} 207 | body_params_batch_rec['transl'] = x_body_rec[:,:3] 208 | body_params_batch_rec['global_orient'] = x_body_rec[:,3:6] 209 | body_params_batch_rec['betas'] = x_body_rec[:,6:16] 210 | body_params_batch_rec['body_pose'] = x_body_rec[:,16:48] 211 | #body_params_batch_rec['left_hand_pose'] = x_body_rec[:,48:60] 212 | #body_params_batch_rec['right_hand_pose'] = x_body_rec[:,60:] 213 | return body_params_batch_rec 214 | 215 | def body_params_encapsulate_batch_nobody(x_body_rec): 216 | 217 | body_params_batch_rec={} 218 | body_params_batch_rec['transl'] = x_body_rec[:,:3] 219 | body_params_batch_rec['global_orient'] = x_body_rec[:,3:6] 220 | #body_params_batch_rec['betas'] = x_body_rec[:,6:16] 221 | body_params_batch_rec['body_pose'] = x_body_rec[:,6:38] 222 | #body_params_batch_rec['left_hand_pose'] = x_body_rec[:,48:60] 223 | #body_params_batch_rec['right_hand_pose'] = x_body_rec[:,60:] 224 | return body_params_batch_rec 225 | 226 | 227 | def body_params_encapsulate_batch_hand(x_body_rec): 228 | 229 | body_params_batch_rec={} 230 | body_params_batch_rec['transl'] = x_body_rec[:,:3] 231 | body_params_batch_rec['global_orient'] = x_body_rec[:,3:6] 232 | body_params_batch_rec['betas'] = x_body_rec[:,6:16] 233 | body_params_batch_rec['body_pose'] = x_body_rec[:,16:48] 234 | body_params_batch_rec['left_hand_pose'] = x_body_rec[:,48:60] 235 | body_params_batch_rec['right_hand_pose'] = x_body_rec[:,60:] 236 | 237 | 238 | return body_params_batch_rec 239 | 240 | @staticmethod 241 | def body_params_encapsulate_batch_nobody_hand(x_body_rec): 242 | 243 | body_params_batch_rec={} 244 | body_params_batch_rec['transl'] = x_body_rec[:,:3] 245 | body_params_batch_rec['global_orient'] = x_body_rec[:,3:6] 246 | #body_params_batch_rec['betas'] = x_body_rec[:,6:16] 247 | body_params_batch_rec['body_pose'] = x_body_rec[:,6:38] 248 | body_params_batch_rec['left_hand_pose'] = x_body_rec[:,38:50] 249 | body_params_batch_rec['right_hand_pose'] = x_body_rec[:,50:] 250 | 251 | 252 | return body_params_batch_rec 253 | 254 | @staticmethod 255 | def body_params_encapsulate_latent(x_body_rec, eps=None): 256 | 257 | x_body_rec_np = x_body_rec.detach().cpu().numpy() 258 | eps_np = eps.detach().cpu().numpy() 259 | 260 | n_batch = x_body_rec_np.shape[0] 261 | rec_list = [] 262 | 263 | for b in range(n_batch): 264 | body_params_batch_rec={} 265 | body_params_batch_rec['transl'] = x_body_rec_np[b:b+1,:3] 266 | body_params_batch_rec['global_orient'] = x_body_rec_np[b:b+1,3:6] 267 | body_params_batch_rec['betas'] = x_body_rec_np[b:b+1,6:16] 268 | body_params_batch_rec['body_pose'] = x_body_rec_np[b:b+1,16:48] 269 | body_params_batch_rec['left_hand_pose'] = x_body_rec_np[b:b+1,48:60] 270 | body_params_batch_rec['right_hand_pose'] = x_body_rec_np[b:b+1,60:] 271 | body_params_batch_rec['z'] = eps_np[b:b+1, :] 272 | rec_list.append(body_params_batch_rec) 273 | 274 | return rec_list 275 | 276 | @staticmethod 277 | def body_params_parse(body_params_batch): 278 | ''' 279 | input: body_params 280 | |-- transl: global translation, [1, 3D] 281 | |-- global_orient: global rotation, [1, 3D] 282 | |-- betas: body shape, [1, 10D] 283 | |-- body_pose: in Vposer latent space, [1, 32D] 284 | |-- left_hand_pose: [1, 12] 285 | |-- right_hand_pose: [1, 12] 286 | |-- camera_translation: [1, 3D] 287 | |-- camera_rotation: [1, 3x3 mat] 288 | z_s: scene representation [1, 128D] 289 | ''' 290 | 291 | ## parse body_params_batch 292 | x_body_T = body_params_batch['transl'] 293 | x_body_R = body_params_batch['global_orient'] 294 | x_body_beta = body_params_batch['betas'] 295 | x_body_pose = body_params_batch['body_pose'] 296 | x_body_lh = body_params_batch['left_hand_pose'] 297 | x_body_rh = body_params_batch['right_hand_pose'] 298 | 299 | x_body = np.concatenate([x_body_T, x_body_R, 300 | x_body_beta, x_body_pose, 301 | x_body_lh, x_body_rh], axis=-1) 302 | x_body_gpu = torch.tensor(x_body, dtype=torch.float32).cuda() 303 | 304 | return x_body_gpu 305 | 306 | 307 | @staticmethod 308 | def body_params_parse_fitting(body_params_batch): 309 | ''' 310 | input: body_params 311 | |-- transl: global translation, [1, 3D] 312 | |-- global_orient: global rotation, [1, 3D] 313 | |-- betas: body shape, [1, 10D] 314 | |-- body_pose: in Vposer latent space, [1, 32D] 315 | |-- left_hand_pose: [1, 12] 316 | |-- right_hand_pose: [1, 12] 317 | |-- camera_translation: [1, 3D] 318 | |-- camera_rotation: [1, 3x3 mat] 319 | z_s: scene representation [1, 128D] 320 | ''' 321 | 322 | ## parse body_params_batch 323 | x_body_T = body_params_batch['transl'] 324 | x_body_R = body_params_batch['global_orient'] 325 | x_body_beta = body_params_batch['betas'] 326 | x_body_pose = body_params_batch['body_pose'] 327 | x_body_lh = body_params_batch['left_hand_pose'] 328 | x_body_rh = body_params_batch['right_hand_pose'] 329 | cam_ext = torch.tensor(body_params_batch['cam_ext'], dtype=torch.float32).cuda() 330 | cam_int = torch.tensor(body_params_batch['cam_int'], dtype=torch.float32).cuda() 331 | 332 | x_body = np.concatenate([x_body_T, x_body_R, 333 | x_body_beta, x_body_pose, 334 | x_body_lh, x_body_rh], axis=-1) 335 | x_body_gpu = torch.tensor(x_body, dtype=torch.float32).cuda() 336 | 337 | return x_body_gpu, cam_ext, cam_int 338 | -------------------------------------------------------------------------------- /generate_routepose_data.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import sys, os, glob\n", 10 | "import json\n", 11 | "import argparse\n", 12 | "import numpy as np\n", 13 | "import scipy.io as sio\n", 14 | "import torch\n", 15 | "import time\n", 16 | "import os\n", 17 | "import pickle\n", 18 | "import random\n", 19 | "device=\"cpu\"" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": 2, 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "def recover_global_T(x_batch, cam_intrisic, max_depth):\n", 29 | " xt_batch = x_batch[:,:3]\n", 30 | " xr_batch = x_batch[:,3:]\n", 31 | "\n", 32 | " fx_batch = cam_intrisic[:,0,0]\n", 33 | " fy_batch = cam_intrisic[:,1,1]\n", 34 | " px_batch = cam_intrisic[:,0,2]\n", 35 | " py_batch = cam_intrisic[:,1,2]\n", 36 | " s_ = 1.0 / torch.max(px_batch, py_batch)\n", 37 | "\n", 38 | " z = (xt_batch[:, 2]+1.0)/2.0 * max_depth\n", 39 | "\n", 40 | " x = xt_batch[:,0] * z / s_ / fx_batch\n", 41 | " y = xt_batch[:,1] * z / s_ / fy_batch\n", 42 | " \n", 43 | " xt_batch_recoverd = torch.stack([x,y,z],dim=-1)\n", 44 | "\n", 45 | " return torch.cat([xt_batch_recoverd, xr_batch],dim=-1)\n", 46 | "\n", 47 | "\n", 48 | "\n", 49 | "def convert_to_3D_rot(x_batch):\n", 50 | " xt = x_batch[:,:3]\n", 51 | " xr = x_batch[:,3:9]\n", 52 | " xb = x_batch[:,9:]\n", 53 | "\n", 54 | " xr_mat = ContinousRotReprDecoder.decode(xr) # return [:,3,3]\n", 55 | " xr_aa = ContinousRotReprDecoder.matrot2aa(xr_mat) # return [:,3]\n", 56 | "\n", 57 | " return torch.cat([xt, xr_aa, xb], dim=-1)\n", 58 | "\n", 59 | "\n", 60 | "def body_params_encapsulate(x_body_rec, to_numpy=True, batched=False):\n", 61 | " \n", 62 | " if to_numpy:\n", 63 | " x_body_rec_np = x_body_rec.detach().cpu().numpy()\n", 64 | " else:\n", 65 | " x_body_rec_np = x_body_rec\n", 66 | " \n", 67 | " \n", 68 | " if batched:\n", 69 | " body_params_batch_rec={}\n", 70 | " body_params_batch_rec['transl'] = x_body_rec_np[:,:3]\n", 71 | " body_params_batch_rec['global_orient'] = x_body_rec_np[:,3:6]\n", 72 | " body_params_batch_rec['betas'] = x_body_rec_np[:,6:16]\n", 73 | " body_params_batch_rec['body_pose'] = x_body_rec_np[:,16:48]\n", 74 | " body_params_batch_rec['left_hand_pose'] = x_body_rec_np[:,48:60]\n", 75 | " body_params_batch_rec['right_hand_pose'] = x_body_rec_np[:,60:]\n", 76 | " \n", 77 | " return body_params_batch_rec\n", 78 | " \n", 79 | " else:\n", 80 | " n_batch = x_body_rec_np.shape[0]\n", 81 | " rec_list = []\n", 82 | "\n", 83 | " for b in range(n_batch):\n", 84 | " body_params_batch_rec={}\n", 85 | " body_params_batch_rec['transl'] = x_body_rec_np[b:b+1,:3]\n", 86 | " body_params_batch_rec['global_orient'] = x_body_rec_np[b:b+1,3:6]\n", 87 | " body_params_batch_rec['betas'] = x_body_rec_np[b:b+1,6:16]\n", 88 | " body_params_batch_rec['body_pose'] = x_body_rec_np[b:b+1,16:48]\n", 89 | " #body_params_batch_rec['left_hand_pose'] = x_body_rec_np[b:b+1,48:60]\n", 90 | " #body_params_batch_rec['right_hand_pose'] = x_body_rec_np[b:b+1,60:]\n", 91 | " rec_list.append(body_params_batch_rec)\n", 92 | "\n", 93 | " return rec_list\n", 94 | "\n", 95 | "\n", 96 | "def data_preprocessing(img, modality, target_domain_size=[128, 128]):\n", 97 | "\n", 98 | " \"\"\"\n", 99 | " input:\n", 100 | " - img (depthmap or semantic map): [height, width].\n", 101 | " - modality: 'depth' or 'seg'\n", 102 | " output:\n", 103 | " canvas: with shape of target_domain_size, where the input is in the\n", 104 | " center tightly, with shape target_domain_size\n", 105 | " factor: the resizing factor\n", 106 | " \"\"\"\n", 107 | "\n", 108 | " # prepare the canvas\n", 109 | " img_shape_o = img.shape\n", 110 | " canvas = torch.zeros([1,1]+target_domain_size, dtype=torch.float32,\n", 111 | " device=torch.device(device))\n", 112 | "\n", 113 | "\n", 114 | " # filter out unavailable values\n", 115 | " if modality == 'depth':\n", 116 | " img[img>6.0]=6.0\n", 117 | "\n", 118 | " if modality == 'seg':\n", 119 | " img[img>41] = 41\n", 120 | "\n", 121 | "\n", 122 | "\n", 123 | " ## rescale to [-1,1]\n", 124 | " max_val = torch.max(img)\n", 125 | " _img = 2* img / max_val - 1.0\n", 126 | "\n", 127 | " ## put _img to the canvas\n", 128 | " if img_shape_o[0]>= img_shape_o[1]:\n", 129 | " factor = float(target_domain_size[0]) / img_shape_o[0]\n", 130 | " target_height = target_domain_size[0]\n", 131 | " target_width = int(img_shape_o[1] * factor) //2 *2 \n", 132 | "\n", 133 | " # for depth map we use bilinear interpolation in resizing\n", 134 | " # for segmentation map we use bilinear interpolation as well.\n", 135 | " # note that float semantic label is not real in practice, but\n", 136 | " # helpful in our work\n", 137 | " target_size = [target_height, target_width]\n", 138 | "\n", 139 | " _img = _img.view(1,1,img_shape_o[0],img_shape_o[1])\n", 140 | " img_resize = F.interpolate(_img, size=target_size, mode='bilinear',\n", 141 | " align_corners=False)\n", 142 | "\n", 143 | " na = target_width\n", 144 | " nb = target_domain_size[1]\n", 145 | " lower = (nb //2) - (na //2)\n", 146 | " upper = (nb //2) + (na //2)\n", 147 | "\n", 148 | " canvas[:,:,:, lower:upper] = img_resize\n", 149 | "\n", 150 | "\n", 151 | " else:\n", 152 | " factor = float(target_domain_size[1]) / img_shape_o[1]\n", 153 | "\n", 154 | " target_height = int(factor*img_shape_o[0]) //2 *2\n", 155 | " target_width = target_domain_size[1]\n", 156 | "\n", 157 | " target_size = [target_height, target_width]\n", 158 | " _img = _img.view(1,1,img_shape_o[0],img_shape_o[1])\n", 159 | " img_resize = F.interpolate(_img, size=target_size, mode='bilinear',\n", 160 | " align_corners=False)\n", 161 | "\n", 162 | " na = target_height\n", 163 | " nb = target_domain_size[0]\n", 164 | " lower = (nb //2) - (na //2)\n", 165 | " upper = (nb //2) + (na //2)\n", 166 | "\n", 167 | " canvas[:,:,lower:upper, :] = img_resize\n", 168 | "\n", 169 | " return canvas, factor, max_val\n", 170 | "\n", 171 | "\n", 172 | "\n", 173 | "\n", 174 | "def scipy_matfile_parse(filename):\n", 175 | " '''\n", 176 | " parse data from files and put them to GPU\n", 177 | " Note that this function is for demo, and is different from the ones used in other places.\n", 178 | " '''\n", 179 | " data = sio.loadmat(filename)\n", 180 | " depth0_np = data['depth']\n", 181 | " seg0_np = data['seg']\n", 182 | "\n", 183 | " ## change them to torch tensor\n", 184 | " depth0 = torch.tensor(depth0_np, dtype=torch.float32, device=torch.device(device))\n", 185 | " seg0 = torch.tensor(seg0_np, dtype=torch.float32, device=torch.device(device))\n", 186 | "\n", 187 | " ## pre_processing\n", 188 | " depth, factor_d,max_d = data_preprocessing(depth0, 'depth', target_domain_size=[128, 128])\n", 189 | " seg, factor_s,_ = data_preprocessing(seg0, 'seg', target_domain_size=[128, 128])\n", 190 | "\n", 191 | "\n", 192 | " cam_intrinsic_np = data['cam'][0][0]['intrinsic']\n", 193 | " cam_intrinsic = torch.tensor(cam_intrinsic_np, dtype=torch.float32, device=torch.device(device)).unsqueeze(0)\n", 194 | " cam_extrinsic_np = data['cam'][0][0]['extrinsic']\n", 195 | " cam_extrinsic_np = np.linalg.inv(cam_extrinsic_np)\n", 196 | " cam_extrinsic = torch.tensor(cam_extrinsic_np, dtype=torch.float32, device=torch.device(device)).unsqueeze(0)\n", 197 | "\n", 198 | " return depth, seg, max_d.view(1), cam_intrinsic, cam_extrinsic" 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": 3, 204 | "metadata": {}, 205 | "outputs": [], 206 | "source": [ 207 | "def create_dataset(data,seq):\n", 208 | " dataset=[]\n", 209 | " for i in range(len(data)):\n", 210 | " body_t = data[i]['transl']\n", 211 | " body_r = data[i]['global_orient']\n", 212 | " body_shape=data[i]['betas']\n", 213 | " body_pose = data[i]['pose_embedding']\n", 214 | " body_lhp = data[i]['left_hand_pose']\n", 215 | " body_rhp = data[i]['right_hand_pose']\n", 216 | " body = np.concatenate([body_t, body_r, body_shape, \n", 217 | " body_pose, body_lhp, body_rhp\n", 218 | " ],\n", 219 | " axis=-1)\n", 220 | " \n", 221 | " dataset.append(body)\n", 222 | " \n", 223 | " input_list=[]\n", 224 | " gt_list=[]\n", 225 | " seq=seq\n", 226 | " for i in range(len(dataset)):\n", 227 | " \n", 228 | " try:\n", 229 | " input_=torch.tensor(np.concatenate([dataset[i],dataset[i+seq*61]]), dtype=torch.float32)\n", 230 | " t_list=[]\n", 231 | " for temp_i in range(60):\n", 232 | " t_list.append(dataset[i+seq*temp_i+1]) \n", 233 | " gt=torch.tensor(np.concatenate(t_list),dtype=torch.float32)\n", 234 | " \n", 235 | "\n", 236 | " if torch.max(np.isnan(input_))==0 and torch.max(np.isnan(gt))==0:\n", 237 | " input_list.append(input_)\n", 238 | " gt_list.append(gt)\n", 239 | " \n", 240 | " except:\n", 241 | " pass\n", 242 | " \n", 243 | " return input_list,gt_list" 244 | ] 245 | }, 246 | { 247 | "cell_type": "code", 248 | "execution_count": 54, 249 | "metadata": {}, 250 | "outputs": [ 251 | { 252 | "name": "stdout", 253 | "output_type": "stream", 254 | "text": [ 255 | "training BasementSittingBooth_00142_01 1395\n", 256 | "training BasementSittingBooth_00145_01 1590\n", 257 | "training BasementSittingBooth_03452_01 1366\n", 258 | "training MPH112_00034_01 1775\n", 259 | "training MPH112_00150_01 1503\n", 260 | "training MPH112_00151_01 746\n", 261 | "training MPH112_00157_01 1179\n", 262 | "training MPH112_00169_01 1184\n", 263 | "training MPH112_03515_01 1018\n", 264 | "training MPH11_00034_01 2112\n", 265 | "training MPH11_00150_01 2125\n", 266 | "training MPH11_00151_01 1396\n", 267 | "training MPH11_03515_01 1852\n", 268 | "testing MPH16_00157_01 1723\n", 269 | "testing MPH16_03301_01 899\n", 270 | "testing MPH1Library_00034_01 2149\n", 271 | "training MPH8_00168_01 2669\n", 272 | "training MPH8_03301_01 1587\n", 273 | "testing N0SittingBooth_00162_01 1117\n", 274 | "testing N0SittingBooth_00169_01 900\n", 275 | "testing N0SittingBooth_00169_02 768\n", 276 | "testing N0SittingBooth_03301_01 1026\n", 277 | "testing N0SittingBooth_03403_01 1167\n", 278 | "training N0Sofa_00034_01 2583\n", 279 | "training N0Sofa_00034_02 1384\n", 280 | "training N0Sofa_00141_01 2204\n", 281 | "training N0Sofa_00145_01 1980\n", 282 | "training N3Library_00157_01 905\n", 283 | "training N3Library_00157_02 652\n", 284 | "training N3Library_03301_01 765\n", 285 | "training N3Library_03301_02 590\n", 286 | "training N3Library_03375_01 1038\n", 287 | "training N3Library_03375_02 402\n", 288 | "training N3Library_03403_01 608\n", 289 | "training N3Library_03403_02 922\n", 290 | "training N3Office_00034_01 2090\n", 291 | "training N3Office_00139_01 1275\n", 292 | "training N3Office_00139_02 1701\n", 293 | "training N3Office_00150_01 2442\n", 294 | "training N3Office_00153_01 2921\n", 295 | "training N3Office_00159_01 1975\n", 296 | "training N3Office_03301_01 1982\n", 297 | "testing N3OpenArea_00157_01 934\n", 298 | "testing N3OpenArea_00157_02 1263\n", 299 | "testing N3OpenArea_00158_01 824\n", 300 | "testing N3OpenArea_00158_02 1287\n", 301 | "testing N3OpenArea_03301_01 994\n", 302 | "testing N3OpenArea_03403_01 603\n", 303 | "training Werkraum_03301_01 690\n", 304 | "training Werkraum_03403_01 673\n", 305 | "training Werkraum_03516_01 1397\n", 306 | "training Werkraum_03516_02 1159\n" 307 | ] 308 | } 309 | ], 310 | "source": [ 311 | "np.random.seed(2020)\n", 312 | "s1_data_training=[]\n", 313 | "s1_data_testing=[]\n", 314 | "testing_scene= ['MPH16','MPH1Library', 'N0SittingBooth','N3OpenArea']\n", 315 | "sdf_path = scene_sdf_path = './data/prox/sdf' \n", 316 | "total_file_list=sorted(os.listdir('./data/prox/PROXD/'))\n", 317 | "\n", 318 | "for each in total_file_list:\n", 319 | " scene_name=each[:-9]\n", 320 | " with open(os.path.join(scene_sdf_path, scene_name+'.json')) as f:\n", 321 | " sdf_data = json.load(f)\n", 322 | " grid_min = np.array(sdf_data['min'])\n", 323 | " grid_max = np.array(sdf_data['max'])\n", 324 | " grid_dim = sdf_data['dim']\n", 325 | " sdf = np.load(os.path.join(scene_sdf_path, scene_name + '_sdf.npy')).reshape(grid_dim, grid_dim, grid_dim)\n", 326 | " \n", 327 | " scene_name=each[:-9]\n", 328 | " \n", 329 | " filelist=os.listdir('./data/prox/PROXD/'+each+'/results')\n", 330 | " filelist=sorted(filelist)\n", 331 | " temp_data_file=filelist\n", 332 | " data=[]\n", 333 | " for i in range(len(temp_data_file)):\n", 334 | " f=open('./data/prox/PROXD/'+each+'/results/'+temp_data_file[i]+'/000.pkl','rb')\n", 335 | " temp=pickle.load(f)\n", 336 | " data.append(temp)\n", 337 | " sample_data=[]\n", 338 | "\n", 339 | " for i in range(0,len(data),1):\n", 340 | " sample_data.append(data[i])\n", 341 | " \n", 342 | " input_list,middle_list=create_dataset(sample_data,1)\n", 343 | " \n", 344 | " scene_mesh = o3d.io.read_triangle_mesh('./data/Proxe/scenes_downsampled/'+scene_name+'.ply')\n", 345 | " \n", 346 | " cam_ext_path='./data/prox/cam2world/'+scene_name+'.json'\n", 347 | " f=open(cam_ext_path,'r')\n", 348 | " contents = f.read();\n", 349 | " cam_ext = json.loads(contents)\n", 350 | " cam_= np.linalg.inv(cam_ext)\n", 351 | " \n", 352 | " \n", 353 | " scene_verts = torch.tensor(np.asarray(scene_mesh.transform(cam_).vertices),dtype=torch.float32)\n", 354 | " \n", 355 | " grid_min = torch.tensor(np.array(sdf_data['min']),dtype=torch.float32)\n", 356 | " grid_max = torch.tensor(np.array(sdf_data['max']),dtype=torch.float32)\n", 357 | " if scene_name in testing_scene:\n", 358 | " for i in range(len(input_list)):\n", 359 | " s1_data_testing.append([input_list[i],middle_list[i],each,scene_name,sdf,scene_verts,np.array(cam_ext),grid_min,grid_max])\n", 360 | " print('testing',each,i)\n", 361 | " else:\n", 362 | " for i in range(len(input_list)):\n", 363 | " s1_data_training.append([input_list[i],middle_list[i],each,scene_name,sdf,scene_verts,np.array(cam_ext),grid_min,grid_max])\n", 364 | " print('training',each,i)\n", 365 | " " 366 | ] 367 | }, 368 | { 369 | "cell_type": "code", 370 | "execution_count": 60, 371 | "metadata": {}, 372 | "outputs": [], 373 | "source": [ 374 | "s1_data_=[]\n", 375 | "s1_data=s1_data_training\n", 376 | "for i in range(len(s1_data)):\n", 377 | " if torch.sqrt(((s1_data[i][0][0][:3]-s1_data[i][0][1][:3]) ** 2).sum(dim=-1)).mean()>=0.5:\n", 378 | " s1_data_.append(s1_data[i])" 379 | ] 380 | }, 381 | { 382 | "cell_type": "code", 383 | "execution_count": 62, 384 | "metadata": {}, 385 | "outputs": [], 386 | "source": [ 387 | "np.save('./data/routepose_training_data.npy',np.array(s1_data_))" 388 | ] 389 | }, 390 | { 391 | "cell_type": "code", 392 | "execution_count": null, 393 | "metadata": {}, 394 | "outputs": [], 395 | "source": [ 396 | "s1_data_=[]\n", 397 | "s1_data=s1_data_testing\n", 398 | "for i in range(len(s1_data)):\n", 399 | " if torch.sqrt(((s1_data[i][0][0][:3]-s1_data[i][0][1][:3]) ** 2).sum(dim=-1)).mean()>=0.5:\n", 400 | " s1_data_.append(s1_data[i])" 401 | ] 402 | }, 403 | { 404 | "cell_type": "code", 405 | "execution_count": null, 406 | "metadata": {}, 407 | "outputs": [], 408 | "source": [ 409 | "np.save('./data/routepose_testing_data.npy',np.array(s1_data_))" 410 | ] 411 | } 412 | ], 413 | "metadata": { 414 | "kernelspec": { 415 | "display_name": "Python 3", 416 | "language": "python", 417 | "name": "python3" 418 | }, 419 | "language_info": { 420 | "codemirror_mode": { 421 | "name": "ipython", 422 | "version": 3 423 | }, 424 | "file_extension": ".py", 425 | "mimetype": "text/x-python", 426 | "name": "python", 427 | "nbconvert_exporter": "python", 428 | "pygments_lexer": "ipython3", 429 | "version": "3.7.0" 430 | } 431 | }, 432 | "nbformat": 4, 433 | "nbformat_minor": 2 434 | } 435 | -------------------------------------------------------------------------------- /generate_sub_data.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import sys, os, glob\n", 10 | "import json\n", 11 | "import argparse\n", 12 | "import numpy as np\n", 13 | "import scipy.io as sio\n", 14 | "import torch\n", 15 | "import torch.nn as nn\n", 16 | "import torch.nn.functional as F\n", 17 | "from torch.nn import init\n", 18 | "import torch.optim as optim\n", 19 | "from torch.optim import lr_scheduler\n", 20 | "\n", 21 | "import smplx\n", 22 | "from human_body_prior.tools.model_loader import load_vposer\n", 23 | "\n", 24 | "from utils import ContinousRotReprDecoder, GeometryTransformer, BodyParamParser\n", 25 | "\n", 26 | "import time\n", 27 | "\n", 28 | "import os\n", 29 | "import pickle\n", 30 | "import random" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": 2, 36 | "metadata": {}, 37 | "outputs": [], 38 | "source": [ 39 | "def recover_global_T(x_batch, cam_intrisic, max_depth):\n", 40 | " xt_batch = x_batch[:,:3]\n", 41 | " xr_batch = x_batch[:,3:]\n", 42 | "\n", 43 | " fx_batch = cam_intrisic[:,0,0]\n", 44 | " fy_batch = cam_intrisic[:,1,1]\n", 45 | " px_batch = cam_intrisic[:,0,2]\n", 46 | " py_batch = cam_intrisic[:,1,2]\n", 47 | " s_ = 1.0 / torch.max(px_batch, py_batch)\n", 48 | "\n", 49 | " z = (xt_batch[:, 2]+1.0)/2.0 * max_depth\n", 50 | "\n", 51 | " x = xt_batch[:,0] * z / s_ / fx_batch\n", 52 | " y = xt_batch[:,1] * z / s_ / fy_batch\n", 53 | " \n", 54 | " xt_batch_recoverd = torch.stack([x,y,z],dim=-1)\n", 55 | "\n", 56 | " return torch.cat([xt_batch_recoverd, xr_batch],dim=-1)\n", 57 | "\n", 58 | "\n", 59 | "\n", 60 | "def convert_to_3D_rot(x_batch):\n", 61 | " xt = x_batch[:,:3]\n", 62 | " xr = x_batch[:,3:9]\n", 63 | " xb = x_batch[:,9:]\n", 64 | "\n", 65 | " xr_mat = ContinousRotReprDecoder.decode(xr) # return [:,3,3]\n", 66 | " xr_aa = ContinousRotReprDecoder.matrot2aa(xr_mat) # return [:,3]\n", 67 | "\n", 68 | " return torch.cat([xt, xr_aa, xb], dim=-1)\n", 69 | "\n", 70 | "\n", 71 | "def body_params_encapsulate(x_body_rec, to_numpy=True, batched=False):\n", 72 | " \n", 73 | " if to_numpy:\n", 74 | " x_body_rec_np = x_body_rec.detach().cpu().numpy()\n", 75 | " else:\n", 76 | " x_body_rec_np = x_body_rec\n", 77 | " \n", 78 | " \n", 79 | " if batched:\n", 80 | " body_params_batch_rec={}\n", 81 | " body_params_batch_rec['transl'] = x_body_rec_np[:,:3]\n", 82 | " body_params_batch_rec['global_orient'] = x_body_rec_np[:,3:6]\n", 83 | " body_params_batch_rec['betas'] = x_body_rec_np[:,6:16]\n", 84 | " body_params_batch_rec['body_pose'] = x_body_rec_np[:,16:48]\n", 85 | " #body_params_batch_rec['left_hand_pose'] = x_body_rec_np[:,48:60]\n", 86 | " #body_params_batch_rec['right_hand_pose'] = x_body_rec_np[:,60:]\n", 87 | " \n", 88 | " return body_params_batch_rec\n", 89 | " \n", 90 | " else:\n", 91 | " n_batch = x_body_rec_np.shape[0]\n", 92 | " rec_list = []\n", 93 | "\n", 94 | " for b in range(n_batch):\n", 95 | " body_params_batch_rec={}\n", 96 | " body_params_batch_rec['transl'] = x_body_rec_np[b:b+1,:3]\n", 97 | " body_params_batch_rec['global_orient'] = x_body_rec_np[b:b+1,3:6]\n", 98 | " body_params_batch_rec['betas'] = x_body_rec_np[b:b+1,6:16]\n", 99 | " body_params_batch_rec['body_pose'] = x_body_rec_np[b:b+1,16:48]\n", 100 | " #body_params_batch_rec['left_hand_pose'] = x_body_rec_np[b:b+1,48:60]\n", 101 | " #body_params_batch_rec['right_hand_pose'] = x_body_rec_np[b:b+1,60:]\n", 102 | " rec_list.append(body_params_batch_rec)\n", 103 | "\n", 104 | " return rec_list\n", 105 | "\n", 106 | "\n", 107 | "\n", 108 | "\n", 109 | "def data_preprocessing(img, modality, target_domain_size=[128, 128]):\n", 110 | "\n", 111 | " \"\"\"\n", 112 | " input:\n", 113 | " - img (depthmap or semantic map): [height, width].\n", 114 | " - modality: 'depth' or 'seg'\n", 115 | " output:\n", 116 | " canvas: with shape of target_domain_size, where the input is in the\n", 117 | " center tightly, with shape target_domain_size\n", 118 | " factor: the resizing factor\n", 119 | " \"\"\"\n", 120 | "\n", 121 | " # prepare the canvas\n", 122 | " img_shape_o = img.shape\n", 123 | " canvas = torch.zeros([1,1]+target_domain_size, dtype=torch.float32,\n", 124 | " device=torch.device(device))\n", 125 | "\n", 126 | "\n", 127 | " # filter out unavailable values\n", 128 | " if modality == 'depth':\n", 129 | " img[img>6.0]=6.0\n", 130 | "\n", 131 | " if modality == 'seg':\n", 132 | " img[img>41] = 41\n", 133 | "\n", 134 | "\n", 135 | "\n", 136 | " ## rescale to [-1,1]\n", 137 | " max_val = torch.max(img)\n", 138 | " _img = 2* img / max_val - 1.0\n", 139 | "\n", 140 | " ## put _img to the canvas\n", 141 | " if img_shape_o[0]>= img_shape_o[1]:\n", 142 | " factor = float(target_domain_size[0]) / img_shape_o[0]\n", 143 | " target_height = target_domain_size[0]\n", 144 | " target_width = int(img_shape_o[1] * factor) //2 *2 \n", 145 | "\n", 146 | " # for depth map we use bilinear interpolation in resizing\n", 147 | " # for segmentation map we use bilinear interpolation as well.\n", 148 | " # note that float semantic label is not real in practice, but\n", 149 | " # helpful in our work\n", 150 | " target_size = [target_height, target_width]\n", 151 | "\n", 152 | " _img = _img.view(1,1,img_shape_o[0],img_shape_o[1])\n", 153 | " img_resize = F.interpolate(_img, size=target_size, mode='bilinear',\n", 154 | " align_corners=False)\n", 155 | "\n", 156 | " na = target_width\n", 157 | " nb = target_domain_size[1]\n", 158 | " lower = (nb //2) - (na //2)\n", 159 | " upper = (nb //2) + (na //2)\n", 160 | "\n", 161 | " canvas[:,:,:, lower:upper] = img_resize\n", 162 | "\n", 163 | "\n", 164 | " else:\n", 165 | " factor = float(target_domain_size[1]) / img_shape_o[1]\n", 166 | "\n", 167 | " target_height = int(factor*img_shape_o[0]) //2 *2\n", 168 | " target_width = target_domain_size[1]\n", 169 | "\n", 170 | " target_size = [target_height, target_width]\n", 171 | " _img = _img.view(1,1,img_shape_o[0],img_shape_o[1])\n", 172 | " img_resize = F.interpolate(_img, size=target_size, mode='bilinear',\n", 173 | " align_corners=False)\n", 174 | "\n", 175 | " na = target_height\n", 176 | " nb = target_domain_size[0]\n", 177 | " lower = (nb //2) - (na //2)\n", 178 | " upper = (nb //2) + (na //2)\n", 179 | "\n", 180 | " canvas[:,:,lower:upper, :] = img_resize\n", 181 | "\n", 182 | " return canvas, factor, max_val\n", 183 | "\n", 184 | "\n", 185 | "device=\"cpu\"\n", 186 | "\n", 187 | "def scipy_matfile_parse(filename):\n", 188 | " '''\n", 189 | " parse data from files and put them to GPU\n", 190 | " Note that this function is for demo, and is different from the ones used in other places.\n", 191 | " '''\n", 192 | " data = sio.loadmat(filename)\n", 193 | " depth0_np = data['depth']\n", 194 | " seg0_np = data['seg']\n", 195 | "\n", 196 | " ## change them to torch tensor\n", 197 | " depth0 = torch.tensor(depth0_np, dtype=torch.float32, device=torch.device(device))\n", 198 | " seg0 = torch.tensor(seg0_np, dtype=torch.float32, device=torch.device(device))\n", 199 | "\n", 200 | " ## pre_processing\n", 201 | " depth, factor_d,max_d = data_preprocessing(depth0, 'depth', target_domain_size=[128, 128])\n", 202 | " seg, factor_s,_ = data_preprocessing(seg0, 'seg', target_domain_size=[128, 128])\n", 203 | "\n", 204 | "\n", 205 | " cam_intrinsic_np = data['cam'][0][0]['intrinsic']\n", 206 | " cam_intrinsic = torch.tensor(cam_intrinsic_np, dtype=torch.float32, device=torch.device(device)).unsqueeze(0)\n", 207 | " cam_extrinsic_np = data['cam'][0][0]['extrinsic']\n", 208 | " cam_extrinsic_np = np.linalg.inv(cam_extrinsic_np)\n", 209 | " cam_extrinsic = torch.tensor(cam_extrinsic_np, dtype=torch.float32, device=torch.device(device)).unsqueeze(0)\n", 210 | "\n", 211 | " return depth, seg, max_d.view(1), cam_intrinsic, cam_extrinsic" 212 | ] 213 | }, 214 | { 215 | "cell_type": "code", 216 | "execution_count": 4, 217 | "metadata": {}, 218 | "outputs": [], 219 | "source": [ 220 | "def create_dataset(data):\n", 221 | " dataset=[]\n", 222 | " for i in range(len(data)):\n", 223 | " body_t = data[i]['transl']\n", 224 | " body_r = data[i]['global_orient']\n", 225 | " body_shape=data[i]['betas']\n", 226 | " body_pose = data[i]['pose_embedding']\n", 227 | " body_lhp = data[i]['left_hand_pose']\n", 228 | " body_rhp = data[i]['right_hand_pose']\n", 229 | " body = np.concatenate([body_t, body_r, body_shape, \n", 230 | " body_pose, body_lhp, body_rhp\n", 231 | " ],\n", 232 | " axis=-1)\n", 233 | " \n", 234 | " dataset.append(body)\n", 235 | " #train_input=[]\n", 236 | " #train_gt=[]\n", 237 | " #test_input=[]\n", 238 | " #test_gt=[]\n", 239 | " #np.random.seed(2020)\n", 240 | " #sample=np.random.choice(len(data),int(len(data)*0.8),replace=False)\n", 241 | " input_list=[]\n", 242 | " gt_list=[]\n", 243 | " \n", 244 | " for i in range(len(dataset)):\n", 245 | " \n", 246 | " \n", 247 | " \n", 248 | " try:\n", 249 | " exist1=0\n", 250 | " exist2=0\n", 251 | " input1_list=[]\n", 252 | " for j in range(i,i-40,-1):\n", 253 | " if 0.2right_avg_distance: 148 | # temp_list.append('left') 149 | #foot_list.append(left_foot_verts_batch[iii]) 150 | #else: 151 | # temp_list.append('right') 152 | #foot_list.append(right_foot_verts_batch[iii]) 153 | #threshold=threshold 154 | if threshold*right_joint_distance1.1*body_joints_batch[iii,4,1]: 156 | temp_list.append('right') 157 | #foot_list.append(right_foot_verts_batch[iii]) 158 | elif right_joint_distance>threshold*left_joint_distance and right_joint_longer_distance>threshold*left_joint_longer_distance: 159 | #elif 1.1*body_joints_batch[iii,5,1]" 204 | ] 205 | }, 206 | "execution_count": 6, 207 | "metadata": {}, 208 | "output_type": "execute_result" 209 | } 210 | ], 211 | "source": [ 212 | "from sub_goal import SUBGOAL\n", 213 | "ndim=65\n", 214 | "cvae=SUBGOAL(n_dim_body=ndim,scene_model_ckpt=False,device=device)\n", 215 | "cvae=cvae.to(device)\n", 216 | "cvae.load_state_dict(torch.load('saved_model/subgoal.model',map_location=device))" 217 | ] 218 | }, 219 | { 220 | "cell_type": "code", 221 | "execution_count": 7, 222 | "metadata": {}, 223 | "outputs": [], 224 | "source": [ 225 | "#MPH16.ply is a downsampled scene from PROXE dataset\n", 226 | "scene_mesh=o3d.io.read_triangle_mesh('demo_data/MPH16.ply')\n", 227 | "\n", 228 | "#camera_ext of MPH16\n", 229 | "camera_ext=np.array([[-0.40142276, 0.34250608, -0.84944061, 2.16673488],\n", 230 | " [ 0.91529181, 0.11642218, -0.38559925, 1.88633201],\n", 231 | " [-0.03317636, -0.93227435, -0.36022753, 0.736902 ],\n", 232 | " [ 0. , 0. , 0. , 1. ]])\n", 233 | "camera_ext_inv=np.linalg.inv(camera_ext)\n", 234 | "\n", 235 | "# apply transformation to the scene pointcloud, let the scene and human body in the same area\n", 236 | "scene_points=torch.tensor(np.asarray(scene_mesh.transform(camera_ext_inv).vertices),dtype=torch.float32).to(device)\n", 237 | "\n", 238 | "#scene_points=torch.tensor(scene_points,dtype=torch.float32).to(device)\n", 239 | "#you can randomly sample the positions or get them from the dataset\n", 240 | "\n", 241 | "start=GeometryTransformer.convert_to_6D_rot(\n", 242 | " torch.tensor([[-0.6111, -0.0384, 2.8900, -2.8275, -0.0543, -0.2241]])).to(device)\n", 243 | "sub=GeometryTransformer.convert_to_6D_rot(\n", 244 | " torch.tensor([[-0.3502, 0.1911, 2.1834, -2.8251, 0.0991, -0.7367]])).to(device)\n", 245 | "end=GeometryTransformer.convert_to_6D_rot(\n", 246 | " torch.tensor([[-0.6594, 0.2947, 1.2586, -2.8201, -0.1839, 0.5844]])).to(device)\n", 247 | "\n", 248 | "#you can set the body shape parameters\n", 249 | "body=torch.zeros([1,10]).to(device)\n", 250 | "\n" 251 | ] 252 | }, 253 | { 254 | "cell_type": "code", 255 | "execution_count": 8, 256 | "metadata": {}, 257 | "outputs": [ 258 | { 259 | "name": "stdout", 260 | "output_type": "stream", 261 | "text": [ 262 | "finish\n" 263 | ] 264 | } 265 | ], 266 | "source": [ 267 | "start_body = cvae.sample(None,scene_points.unsqueeze(0).transpose(1,2),start,body)\n", 268 | "start_body_ = GeometryTransformer.convert_to_3D_rot(start_body)\n", 269 | "body_param_rec = BodyParamParser.body_params_encapsulate_batch_nobody_hand(start_body_)\n", 270 | "body_param_rec['body_pose'] = vposer.decode(body_param_rec['body_pose'], \n", 271 | " output_type='aa').view(start_body.shape[0], -1)\n", 272 | "body_param_rec['betas']=body.repeat(start_body.shape[0],1)\n", 273 | "smplx_output = body_mesh_model(return_verts=True, \n", 274 | " **body_param_rec\n", 275 | " )\n", 276 | "body_verts_batch = smplx_output.vertices\n", 277 | "smplx_faces = body_mesh_model.faces\n", 278 | "out_mesh =trimesh.Trimesh(body_verts_batch[0].detach().cpu().numpy(),smplx_faces,process=False)\n", 279 | "out_mesh.apply_transform(camera_ext)\n", 280 | "out_mesh.export('./demo_data/start.obj')\n", 281 | "print('finish')" 282 | ] 283 | }, 284 | { 285 | "cell_type": "code", 286 | "execution_count": 9, 287 | "metadata": {}, 288 | "outputs": [ 289 | { 290 | "name": "stdout", 291 | "output_type": "stream", 292 | "text": [ 293 | "finish\n" 294 | ] 295 | } 296 | ], 297 | "source": [ 298 | "middle_body = cvae.sample(None,scene_points.unsqueeze(0).transpose(1,2),sub,body)\n", 299 | "middle_body_ = GeometryTransformer.convert_to_3D_rot(middle_body)\n", 300 | "\n", 301 | "body_param_rec = BodyParamParser.body_params_encapsulate_batch_nobody_hand(middle_body_)\n", 302 | "body_param_rec['body_pose'] = vposer.decode(body_param_rec['body_pose'], \n", 303 | " output_type='aa').view(start_body.shape[0], -1)\n", 304 | "body_param_rec['betas']=body.repeat(start_body.shape[0],1)\n", 305 | "smplx_output = body_mesh_model(return_verts=True, \n", 306 | " **body_param_rec\n", 307 | " )\n", 308 | "body_verts_batch = smplx_output.vertices\n", 309 | "smplx_faces = body_mesh_model.faces\n", 310 | "out_mesh =trimesh.Trimesh(body_verts_batch[0].detach().cpu().numpy(),smplx_faces,process=False)\n", 311 | "out_mesh.apply_transform(camera_ext)\n", 312 | "out_mesh.export('./demo_data/middle.obj')\n", 313 | "print('finish')" 314 | ] 315 | }, 316 | { 317 | "cell_type": "code", 318 | "execution_count": 10, 319 | "metadata": {}, 320 | "outputs": [ 321 | { 322 | "name": "stdout", 323 | "output_type": "stream", 324 | "text": [ 325 | "finish\n" 326 | ] 327 | } 328 | ], 329 | "source": [ 330 | "end_body = cvae.sample(None,scene_points.unsqueeze(0).transpose(1,2),end,body)\n", 331 | "end_body_ = GeometryTransformer.convert_to_3D_rot(end_body)\n", 332 | "\n", 333 | "body_param_rec = BodyParamParser.body_params_encapsulate_batch_nobody_hand(end_body_)\n", 334 | "body_param_rec['body_pose'] = vposer.decode(body_param_rec['body_pose'], \n", 335 | " output_type='aa').view(start_body.shape[0], -1)\n", 336 | "body_param_rec['betas']=body.repeat(start_body.shape[0],1)\n", 337 | "smplx_output = body_mesh_model(return_verts=True, \n", 338 | " **body_param_rec\n", 339 | " )\n", 340 | "body_verts_batch = smplx_output.vertices\n", 341 | "smplx_faces = body_mesh_model.faces\n", 342 | "out_mesh=trimesh.Trimesh(body_verts_batch[0].detach().cpu().numpy(),smplx_faces,process=False)\n", 343 | "out_mesh.apply_transform(camera_ext)\n", 344 | "out_mesh.export('./demo_data/end.obj')\n", 345 | "print('finish')" 346 | ] 347 | }, 348 | { 349 | "cell_type": "code", 350 | "execution_count": 11, 351 | "metadata": {}, 352 | "outputs": [ 353 | { 354 | "name": "stdout", 355 | "output_type": "stream", 356 | "text": [ 357 | "finish\n" 358 | ] 359 | }, 360 | { 361 | "name": "stderr", 362 | "output_type": "stream", 363 | "text": [ 364 | "C:\\Users\\jiash\\Anaconda3\\lib\\site-packages\\torch\\nn\\modules\\rnn.py:51: UserWarning: dropout option adds dropout after all but last recurrent layer, so non-zero dropout expects num_layers greater than 1, but got dropout=0.4 and num_layers=1\n", 365 | " \"num_layers={}\".format(dropout, num_layers))\n" 366 | ] 367 | } 368 | ], 369 | "source": [ 370 | "from route import ROUTENET\n", 371 | "from pose_after_route import POSEAFTERROUTE\n", 372 | "\n", 373 | "routenet = ROUTENET(input_dim=9,hid_dim=64,scene_model_ckpt=False,device=device).to(device)\n", 374 | "posenet = POSEAFTERROUTE(input_dim=65-9,hid_dim=256,scene_model_ckpt=False,device=device).to(device)\n", 375 | "\n", 376 | "routenet.load_state_dict(torch.load('saved_model/route.model',map_location=device))\n", 377 | "posenet.load_state_dict(torch.load('saved_model/pose_after_route.model',map_location=device))\n", 378 | "print('finish')" 379 | ] 380 | }, 381 | { 382 | "cell_type": "markdown", 383 | "metadata": {}, 384 | "source": [ 385 | "Motion" 386 | ] 387 | }, 388 | { 389 | "cell_type": "code", 390 | "execution_count": 12, 391 | "metadata": {}, 392 | "outputs": [], 393 | "source": [ 394 | "x1=torch.cat([start_body,middle_body]).unsqueeze(0)\n", 395 | "route=routenet(x1[:,:,:9],scene_points.unsqueeze(0).transpose(1,2))\n", 396 | "pose=posenet(x1[:,:,9:],scene_points.unsqueeze(0).transpose(1,2),route.view(route.shape[0],-1))\n", 397 | "\n", 398 | "y1=torch.cat([route,pose],dim=2).view(-1,65)\n", 399 | "y1_ = GeometryTransformer.convert_to_3D_rot(y1)\n", 400 | "\n", 401 | "body_param_rec = BodyParamParser.body_params_encapsulate_batch_nobody_hand(y1_)\n", 402 | "body_param_rec['body_pose'] = vposer.decode(body_param_rec['body_pose'], \n", 403 | " output_type='aa').view(y1.shape[0], -1)\n", 404 | "body_param_rec['betas']=body.repeat(y1.shape[0],1)\n", 405 | "smplx_output = body_mesh_model_batch(return_verts=True, \n", 406 | " **body_param_rec\n", 407 | " )\n", 408 | "body_verts_batch = smplx_output.vertices\n", 409 | "for i in range(60):\n", 410 | " out_mesh =trimesh.Trimesh(body_verts_batch[i].detach().cpu().numpy(),smplx_faces,process=False)\n", 411 | " out_mesh.apply_transform(camera_ext)\n", 412 | " out_mesh.export('./demo_data/'+str(i)+'.obj')" 413 | ] 414 | }, 415 | { 416 | "cell_type": "code", 417 | "execution_count": 13, 418 | "metadata": {}, 419 | "outputs": [], 420 | "source": [ 421 | "x2=torch.cat([middle_body,end_body]).unsqueeze(0)\n", 422 | "route=routenet(x2[:,:,:9],scene_points.unsqueeze(0).transpose(1,2))\n", 423 | "pose=posenet(x2[:,:,9:],scene_points.unsqueeze(0).transpose(1,2),route.view(route.shape[0],-1))\n", 424 | "\n", 425 | "y2=torch.cat([route,pose],dim=2).view(-1,65)\n", 426 | "y2_ = GeometryTransformer.convert_to_3D_rot(y2)\n", 427 | "\n", 428 | "body_param_rec = BodyParamParser.body_params_encapsulate_batch_nobody_hand(y2_)\n", 429 | "body_param_rec['body_pose'] = vposer.decode(body_param_rec['body_pose'], \n", 430 | " output_type='aa').view(y2.shape[0], -1)\n", 431 | "body_param_rec['betas']=body.repeat(y2.shape[0],1)\n", 432 | "smplx_output = body_mesh_model_batch(return_verts=True, \n", 433 | " **body_param_rec\n", 434 | " )\n", 435 | "body_verts_batch = smplx_output.vertices\n", 436 | "for i in range(60):\n", 437 | " out_mesh =trimesh.Trimesh(body_verts_batch[i].detach().cpu().numpy(),smplx_faces,process=False)\n", 438 | " out_mesh.apply_transform(camera_ext)\n", 439 | " out_mesh.export('./demo_data/'+str(i+60)+'.obj')" 440 | ] 441 | }, 442 | { 443 | "cell_type": "markdown", 444 | "metadata": {}, 445 | "source": [ 446 | "Optimization" 447 | ] 448 | }, 449 | { 450 | "cell_type": "code", 451 | "execution_count": 14, 452 | "metadata": {}, 453 | "outputs": [], 454 | "source": [ 455 | "with open('./demo_data/MPH16.json') as f:\n", 456 | " sdf_data = json.load(f)\n", 457 | " grid_min = np.array(sdf_data['min'])\n", 458 | " grid_max = np.array(sdf_data['max'])\n", 459 | " grid_dim = sdf_data['dim']\n", 460 | "sdf = np.load('./demo_data/MPH16_sdf.npy').reshape(grid_dim, grid_dim, grid_dim)" 461 | ] 462 | }, 463 | { 464 | "cell_type": "code", 465 | "execution_count": 15, 466 | "metadata": {}, 467 | "outputs": [], 468 | "source": [ 469 | "s_grid_min = torch.tensor(grid_min, dtype=torch.float32).unsqueeze(0).to(device)\n", 470 | "s_grid_max = torch.tensor(grid_max, dtype=torch.float32).unsqueeze(0).to(device)\n", 471 | "s_sdf = torch.tensor(sdf, dtype=torch.float32).unsqueeze(0).to(device) \n", 472 | "cam_ext=torch.tensor(camera_ext,dtype=torch.float32).unsqueeze(0).to(device)" 473 | ] 474 | }, 475 | { 476 | "cell_type": "code", 477 | "execution_count": 20, 478 | "metadata": {}, 479 | "outputs": [ 480 | { 481 | "name": "stdout", 482 | "output_type": "stream", 483 | "text": [ 484 | "torch.Size([1, 10])\n", 485 | "torch.Size([120, 62])\n", 486 | "['right', 'right', 'right', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'right', 'right', 'right', 'right', 'right', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'right', 'right', 'right', 'right', 'left', 'left', 'left', 'left', 'left', 'left', 'right', 'right', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'left', 'left', 'left', 'right', 'right', 'right', 'right']\n" 487 | ] 488 | }, 489 | { 490 | "name": "stderr", 491 | "output_type": "stream", 492 | "text": [ 493 | "C:\\Users\\jiash\\Anaconda3\\lib\\site-packages\\torch\\nn\\functional.py:2693: UserWarning: Default grid_sample and affine_grid behavior will be changed to align_corners=False from 1.4.0. See the documentation of grid_sample for details.\n", 494 | " warnings.warn(\"Default grid_sample and affine_grid behavior will be changed \"\n" 495 | ] 496 | }, 497 | { 498 | "name": "stdout", 499 | "output_type": "stream", 500 | "text": [ 501 | "torch.Size([1, 10])\n", 502 | "torch.Size([120, 62])\n", 503 | "torch.Size([1, 10])\n", 504 | "torch.Size([120, 62])\n", 505 | "torch.Size([1, 10])\n", 506 | "torch.Size([120, 62])\n", 507 | "torch.Size([1, 10])\n", 508 | "torch.Size([120, 62])\n", 509 | "torch.Size([1, 10])\n", 510 | "torch.Size([120, 62])\n", 511 | "torch.Size([1, 10])\n", 512 | "torch.Size([120, 62])\n", 513 | "torch.Size([1, 10])\n", 514 | "torch.Size([120, 62])\n", 515 | "torch.Size([1, 10])\n", 516 | "torch.Size([120, 62])\n", 517 | "torch.Size([1, 10])\n", 518 | "torch.Size([120, 62])\n", 519 | "torch.Size([1, 10])\n", 520 | "torch.Size([120, 62])\n", 521 | "torch.Size([1, 10])\n", 522 | "torch.Size([120, 62])\n", 523 | "torch.Size([1, 10])\n", 524 | "torch.Size([120, 62])\n", 525 | "torch.Size([1, 10])\n", 526 | "torch.Size([120, 62])\n", 527 | "torch.Size([1, 10])\n", 528 | "torch.Size([120, 62])\n", 529 | "torch.Size([1, 10])\n", 530 | "torch.Size([120, 62])\n", 531 | "torch.Size([1, 10])\n", 532 | "torch.Size([120, 62])\n", 533 | "torch.Size([1, 10])\n", 534 | "torch.Size([120, 62])\n", 535 | "torch.Size([1, 10])\n", 536 | "torch.Size([120, 62])\n", 537 | "torch.Size([1, 10])\n", 538 | "torch.Size([120, 62])\n", 539 | "torch.Size([1, 10])\n", 540 | "torch.Size([120, 62])\n", 541 | "['left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left', 'left']\n", 542 | "torch.Size([1, 10])\n", 543 | "torch.Size([120, 62])\n", 544 | "torch.Size([1, 10])\n", 545 | "torch.Size([120, 62])\n", 546 | "torch.Size([1, 10])\n", 547 | "torch.Size([120, 62])\n", 548 | "torch.Size([1, 10])\n", 549 | "torch.Size([120, 62])\n", 550 | "torch.Size([1, 10])\n", 551 | "torch.Size([120, 62])\n", 552 | "torch.Size([1, 10])\n", 553 | "torch.Size([120, 62])\n", 554 | "torch.Size([1, 10])\n", 555 | "torch.Size([120, 62])\n", 556 | "torch.Size([1, 10])\n", 557 | "torch.Size([120, 62])\n", 558 | "torch.Size([1, 10])\n", 559 | "torch.Size([120, 62])\n", 560 | "torch.Size([1, 10])\n", 561 | "torch.Size([120, 62])\n", 562 | "torch.Size([1, 10])\n", 563 | "torch.Size([120, 62])\n", 564 | "torch.Size([1, 10])\n", 565 | "torch.Size([120, 62])\n", 566 | "torch.Size([1, 10])\n", 567 | "torch.Size([120, 62])\n", 568 | "torch.Size([1, 10])\n", 569 | "torch.Size([120, 62])\n", 570 | "torch.Size([1, 10])\n", 571 | "torch.Size([120, 62])\n", 572 | "torch.Size([1, 10])\n", 573 | "torch.Size([120, 62])\n", 574 | "torch.Size([1, 10])\n", 575 | "torch.Size([120, 62])\n", 576 | "torch.Size([1, 10])\n", 577 | "torch.Size([120, 62])\n", 578 | "torch.Size([1, 10])\n", 579 | "torch.Size([120, 62])\n", 580 | "torch.Size([1, 10])\n", 581 | "torch.Size([120, 62])\n", 582 | "torch.Size([1, 10])\n", 583 | "torch.Size([120, 62])\n", 584 | "torch.Size([1, 10])\n", 585 | "torch.Size([120, 62])\n", 586 | "torch.Size([1, 10])\n", 587 | "torch.Size([120, 62])\n", 588 | "torch.Size([1, 10])\n", 589 | "torch.Size([120, 62])\n", 590 | "torch.Size([1, 10])\n", 591 | "torch.Size([120, 62])\n", 592 | "torch.Size([1, 10])\n", 593 | "torch.Size([120, 62])\n", 594 | "torch.Size([1, 10])\n", 595 | "torch.Size([120, 62])\n", 596 | "torch.Size([1, 10])\n", 597 | "torch.Size([120, 62])\n", 598 | "torch.Size([1, 10])\n", 599 | "torch.Size([120, 62])\n", 600 | "torch.Size([1, 10])\n", 601 | "torch.Size([120, 62])\n", 602 | "torch.Size([1, 10])\n", 603 | "torch.Size([120, 62])\n", 604 | "torch.Size([1, 10])\n", 605 | "torch.Size([120, 62])\n", 606 | "torch.Size([1, 10])\n", 607 | "torch.Size([120, 62])\n", 608 | "torch.Size([1, 10])\n", 609 | "torch.Size([120, 62])\n", 610 | "torch.Size([1, 10])\n", 611 | "torch.Size([120, 62])\n", 612 | "torch.Size([1, 10])\n", 613 | "torch.Size([120, 62])\n", 614 | "torch.Size([1, 10])\n", 615 | "torch.Size([120, 62])\n", 616 | "torch.Size([1, 10])\n", 617 | "torch.Size([120, 62])\n", 618 | "torch.Size([1, 10])\n", 619 | "torch.Size([120, 62])\n", 620 | "torch.Size([1, 10])\n", 621 | "torch.Size([120, 62])\n", 622 | "torch.Size([1, 10])\n", 623 | "torch.Size([120, 62])\n", 624 | "torch.Size([1, 10])\n", 625 | "torch.Size([120, 62])\n", 626 | "torch.Size([1, 10])\n", 627 | "torch.Size([120, 62])\n", 628 | "torch.Size([1, 10])\n", 629 | "torch.Size([120, 62])\n", 630 | "torch.Size([1, 10])\n", 631 | "torch.Size([120, 62])\n", 632 | "torch.Size([1, 10])\n", 633 | "torch.Size([120, 62])\n", 634 | "torch.Size([1, 10])\n", 635 | "torch.Size([120, 62])\n", 636 | "torch.Size([1, 10])\n", 637 | "torch.Size([120, 62])\n", 638 | "torch.Size([1, 10])\n", 639 | "torch.Size([120, 62])\n" 640 | ] 641 | } 642 | ], 643 | "source": [ 644 | "from utils_optimize import fitting\n", 645 | "\n", 646 | "\n", 647 | "contact_id_folder='./data/body_segments'\n", 648 | "\n", 649 | "#connect two short-term motion\n", 650 | "x_whole=torch.cat([y1_.detach(),y2_.detach()]) #_,62\n", 651 | "start_end=torch.cat([start_body_.detach(),end_body_.detach()]) #_,62\n", 652 | "\n", 653 | "\n", 654 | "body_mesh_model_batch = smplx.create('./models', \n", 655 | " model_type='smplx',\n", 656 | " gender='neutral', ext='npz',\n", 657 | " num_pca_comps=12,\n", 658 | " create_global_orient=True,\n", 659 | " create_body_pose=True,\n", 660 | " create_betas=True,\n", 661 | " create_left_hand_pose=True,\n", 662 | " create_right_hand_pose=True,\n", 663 | " create_expression=True,\n", 664 | " create_jaw_pose=True,\n", 665 | " create_leye_pose=True,\n", 666 | " create_reye_pose=True,\n", 667 | " create_transl=True,\n", 668 | " batch_size=x_whole.shape[0]\n", 669 | " )\n", 670 | "body_mesh_model_batch=body_mesh_model_batch.to(device)\n", 671 | "\n", 672 | "\n", 673 | "#first state of the optimization\n", 674 | "fittingconfig={'init_lr_h': 0.02,\n", 675 | " 'num_iter':20, \n", 676 | " 'contact_part':['back','butt','L_Hand','R_Hand','L_Leg','R_Leg','thighs'],\n", 677 | " }\n", 678 | "lossconfig={\n", 679 | " 'weight_loss_rec': 0,\n", 680 | " 'weight_loss_vposer':0,\n", 681 | " 'weight_contact': 2,\n", 682 | " 'weight_collision' : 2,\n", 683 | " 'weight_motion':0.5,\n", 684 | " 'weight_skating':0\n", 685 | " }\n", 686 | "\n", 687 | "\n", 688 | "y_after = fitting(x_whole, body, cam_ext, \n", 689 | " scene_points, s_sdf, s_grid_min, s_grid_max,\n", 690 | " fittingconfig, lossconfig,start_end,vposer, body_mesh_model_batch, threshold=1.6, contact_id_folder=contact_id_folder, device=device)\n", 691 | "\n", 692 | "fittingconfig={'init_lr_h': 0.02,\n", 693 | " 'num_iter':50, \n", 694 | " 'contact_part':['back','butt','L_Hand','R_Hand','L_Leg','R_Leg','thighs'],\n", 695 | " }\n", 696 | "\n", 697 | "lossconfig={\n", 698 | " 'weight_loss_rec': 0,\n", 699 | " 'weight_loss_vposer':0,\n", 700 | " 'weight_contact': 1,\n", 701 | " 'weight_collision' : 1,\n", 702 | " 'weight_motion':0.5,\n", 703 | " 'weight_skating':1\n", 704 | " }\n", 705 | " \n", 706 | "y_after = fitting(y_after.detach(), body, cam_ext, \n", 707 | " scene_points, s_sdf, s_grid_min, s_grid_max,\n", 708 | " fittingconfig, lossconfig,start_end,vposer, body_mesh_model_batch, threshold=1.6, contact_id_folder=contact_id_folder, device=device)" 709 | ] 710 | }, 711 | { 712 | "cell_type": "code", 713 | "execution_count": 24, 714 | "metadata": {}, 715 | "outputs": [], 716 | "source": [ 717 | "body_param_rec = BodyParamParser.body_params_encapsulate_batch_nobody_hand(y_after)\n", 718 | "body_param_rec['body_pose'] = vposer.decode(body_param_rec['body_pose'], \n", 719 | " output_type='aa').view(y_after.shape[0], -1)\n", 720 | "body_param_rec['betas']=body.repeat(y_after.shape[0],1)\n", 721 | "smplx_output = body_mesh_model_batch(return_verts=True, \n", 722 | " **body_param_rec\n", 723 | " )\n", 724 | "body_verts_batch = smplx_output.vertices\n", 725 | "for i in range(120):\n", 726 | " out_mesh =trimesh.Trimesh(body_verts_batch[i].detach().cpu().numpy(),smplx_faces,process=False)\n", 727 | " out_mesh.apply_transform(camera_ext)\n", 728 | " out_mesh.export('./demo_data/after'+str(i)+'.obj')" 729 | ] 730 | } 731 | ], 732 | "metadata": { 733 | "kernelspec": { 734 | "display_name": "Python 3", 735 | "language": "python", 736 | "name": "python3" 737 | }, 738 | "language_info": { 739 | "codemirror_mode": { 740 | "name": "ipython", 741 | "version": 3 742 | }, 743 | "file_extension": ".py", 744 | "mimetype": "text/x-python", 745 | "name": "python", 746 | "nbconvert_exporter": "python", 747 | "pygments_lexer": "ipython3", 748 | "version": "3.7.0" 749 | } 750 | }, 751 | "nbformat": 4, 752 | "nbformat_minor": 4 753 | } 754 | --------------------------------------------------------------------------------