Showing preview only (329K chars total). Download the full file or copy to clipboard to get everything.
Repository: namepllet/HandOccNet
Branch: master
Commit: 65ba997c9ce8
Files: 55
Total size: 311.4 KB
Directory structure:
gitextract_dl_xba82/
├── .gitignore
├── README.md
├── common/
│ ├── base.py
│ ├── logger.py
│ ├── nets/
│ │ ├── backbone.py
│ │ ├── cbam.py
│ │ ├── hand_head.py
│ │ ├── mano_head.py
│ │ ├── regressor.py
│ │ └── transformer.py
│ ├── timer.py
│ └── utils/
│ ├── __init__.py
│ ├── camera.py
│ ├── dir.py
│ ├── fitting.py
│ ├── mano.py
│ ├── manopth/
│ │ ├── .gitignore
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── environment.yml
│ │ ├── examples/
│ │ │ ├── manopth_demo.py
│ │ │ └── manopth_mindemo.py
│ │ ├── mano/
│ │ │ ├── __init__.py
│ │ │ └── webuser/
│ │ │ ├── __init__.py
│ │ │ ├── lbs.py
│ │ │ ├── posemapper.py
│ │ │ ├── serialization.py
│ │ │ ├── smpl_handpca_wrapper_HAND_only.py
│ │ │ └── verts.py
│ │ ├── manopth/
│ │ │ ├── __init__.py
│ │ │ ├── argutils.py
│ │ │ ├── demo.py
│ │ │ ├── manolayer.py
│ │ │ ├── rodrigues_layer.py
│ │ │ ├── rot6d.py
│ │ │ ├── rotproj.py
│ │ │ └── tensutils.py
│ │ ├── setup.py
│ │ └── test/
│ │ └── test_demo.py
│ ├── optimizers/
│ │ ├── __init__.py
│ │ ├── lbfgs_ls.py
│ │ └── optim_factory.py
│ ├── preprocessing.py
│ ├── transforms.py
│ └── vis.py
├── data/
│ ├── DEX_YCB/
│ │ └── DEX_YCB.py
│ └── HO3D/
│ └── HO3D.py
├── demo/
│ ├── demo.py
│ ├── demo_fitting.py
│ └── output.obj
├── main/
│ ├── config.py
│ ├── model.py
│ ├── test.py
│ └── train.py
└── requiremets.sh
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Created by .ignore support plugin (hsz.mobi)
### Python template
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
*.npy
#*.png
*.jpg
*.out
output
data/*/data
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
### macOS template
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/dictionaries
.idea/**/shelf
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# CMake
cmake-build-debug/
cmake-build-release/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
================================================
FILE: README.md
================================================
# HandOccNet: Occlusion-Robust 3D Hand Mesh Estimation Network
## Introduction
This repository is the offical [Pytorch](https://pytorch.org/) implementation of **[HandOccNet: Occlusion-Robust 3D Hand Mesh Estimation Network (CVPR 2022)](https://arxiv.org/abs/2203.14564)**. Below is the overall pipeline of HandOccNet.

## Quick demo
* Install **[PyTorch](https://pytorch.org)** and Python >= 3.7.4 and run `sh requirements.sh`.
* Download `snapshot_demo.pth.tar` from [here](https://drive.google.com/drive/folders/1OlyV-qbzOmtQYdzV6dbQX4OtAU5ajBOa?usp=sharing) and place at `demo` folder.
* Prepare `input.jpg` at `demo` folder.
* Download `MANO_RIGHT.pkl` from [here](https://mano.is.tue.mpg.de/) and place at `common/utils/manopth/mano/models`.
* Go to `demo` folder and edit `bbox` in [here](https://github.com/namepllet/HandOccNet/blob/185492e0e5b08c47e37039c5d67e3f2b099a6f9e/demo/demo.py#L61).
* Run `python demo.py --gpu 0` if you want to run on gpu 0.
* You can see `hand_bbox.png`, `hand_image.png`, and `output.obj`.
* Run `python demo_fitting.py --gpu 0 --depth 0.5` if you want to get the hand mesh's translation from the camera. The depth argument is initialization for the optimization.
* You can see `fitting_input_3d_mesh.json` that contains the translation and MANO parameters, `fitting_input_3dmesh.obj`, `fitting_input_2d_prediction.png`, and `fitting_input_projection.png`.
## Directory
### Root
The `${ROOT}` is described as below.
```
${ROOT}
|-- data
|-- demo
|-- common
|-- main
|-- output
```
* `data` contains data loading codes and soft links to images and annotations directories.
* `demo` contains demo codes.
* `common` contains kernel codes for HandOccNet.
* `main` contains high-level codes for training or testing the network.
* `output` contains log, trained models, visualized outputs, and test result.
### Data
You need to follow directory structure of the `data` as below.
```
${ROOT}
|-- data
| |-- HO3D
| | |-- data
| | | |-- train
| | | | |-- ABF10
| | | | |-- ......
| | | |-- evaluation
| | | |-- annotations
| | | | |-- HO3D_train_data.json
| | | | |-- HO3D_evaluation_data.json
| |-- DEX_YCB
| | |-- data
| | | |-- 20200709-subject-01
| | | |-- ......
| | | |-- annotations
| | | | |--DEX_YCB_s0_train_data.json
| | | | |--DEX_YCB_s0_test_data.json
```
* Download HO3D(version 2) data and annotation files [[data](https://www.tugraz.at/institute/icg/research/team-lepetit/research-projects/hand-object-3d-pose-annotation/)][[annotation files](https://drive.google.com/drive/folders/1pmRpgv38PXvlLOODtoxpTYnIpYTkNV6b?usp=sharing)]
* Download DexYCB data and annotation files [[data](https://dex-ycb.github.io/)][[annotation files](https://drive.google.com/drive/folders/1pmRpgv38PXvlLOODtoxpTYnIpYTkNV6b?usp=sharing)]
### Pytorch MANO layer
* For the MANO layer, I used [manopth](https://github.com/hassony2/manopth). The repo is already included in `common/utils/manopth`.
* Download `MANO_RIGHT.pkl` from [here](https://mano.is.tue.mpg.de/) and place at `common/utils/manopth/mano/models`.
### Output
You need to follow the directory structure of the `output` folder as below.
```
${ROOT}
|-- output
| |-- log
| |-- model_dump
| |-- result
| |-- vis
```
* Creating `output` folder as soft link form is recommended instead of folder form because it would take large storage capacity.
* `log` folder contains training log file.
* `model_dump` folder contains saved checkpoints for each epoch.
* `result` folder contains final estimation files generated in the testing stage.
* `vis` folder contains visualized results.
## Running HandOccNet
### Start
* Install **[PyTorch](https://pytorch.org)** and Python >= 3.7.4 and run `sh requirements.sh`.
* In the `main/config.py`, you can change settings of the model including dataset to use and input size and so on.
### Train
In the `main` folder, set trainset in `config.py` (as 'HO3D' or 'DEX_YCB') and run
```bash
python train.py --gpu 0-3
```
to train HandOccNet on the GPU 0,1,2,3. `--gpu 0,1,2,3` can be used instead of `--gpu 0-3`.
### Test
Place trained model at the `output/model_dump/`.
In the `main` folder, set testset in `config.py` (as 'HO3D' or 'DEX_YCB') and run
```bash
python test.py --gpu 0-3 --test_epoch {test epoch}
```
to test HandOccNet on the GPU 0,1,2,3 with {test epoch}th epoch trained model. `--gpu 0,1,2,3` can be used instead of `--gpu 0-3`.
* For the HO3D dataset, pred{test epoch}.zip will be generated in `output/result` folder. You can upload it to the [codalab challenge](https://competitions.codalab.org/competitions/22485) and see the results.
* Our trained model can be downloaded from [here](https://drive.google.com/drive/folders/1OlyV-qbzOmtQYdzV6dbQX4OtAU5ajBOa?usp=sharing)
## Results
Here I report the performance of the HandOccNet.
<p align="center">
<img src="asset/comparison_sota_HO3D.png">
</p>
<p align="center">
<img src="asset/comparison_sota_DexYCB.png">
</p>
## Reference
```
@InProceedings{Park_2022_CVPR_HandOccNet,
author = {Park, JoonKyu and Oh, Yeonguk and Moon, Gyeongsik and Choi, Hongsuk and Lee, Kyoung Mu},
title = {HandOccNet: Occlusion-Robust 3D Hand Mesh Estimation Network},
booktitle = {Conference on Computer Vision and Pattern Recognition (CVPR)},
year = {2022}
}
```
## Acknowledgements
For this project, we relied on research codes from:
* [I2L-MeshNet_RELEASE](https://github.com/mks0601/I2L-MeshNet_RELEASE)
* [Semi-Hand-Object](https://github.com/stevenlsw/Semi-Hand-Object)
* [attention-module](https://github.com/Jongchan/attention-module)
================================================
FILE: common/base.py
================================================
import os
import os.path as osp
import math
import time
import glob
import abc
from torch.utils.data import DataLoader
import torch.optim
import torchvision.transforms as transforms
from timer import Timer
from logger import colorlogger
from torch.nn.parallel.data_parallel import DataParallel
from config import cfg
from model import get_model
# dynamic dataset import
exec('from ' + cfg.trainset + ' import ' + cfg.trainset)
exec('from ' + cfg.testset + ' import ' + cfg.testset)
class Base(object):
__metaclass__ = abc.ABCMeta
def __init__(self, log_name='logs.txt'):
self.cur_epoch = 0
# timer
self.tot_timer = Timer()
self.gpu_timer = Timer()
self.read_timer = Timer()
# logger
self.logger = colorlogger(cfg.log_dir, log_name=log_name)
@abc.abstractmethod
def _make_batch_generator(self):
return
@abc.abstractmethod
def _make_model(self):
return
class Trainer(Base):
def __init__(self):
super(Trainer, self).__init__(log_name = 'train_logs.txt')
def get_optimizer(self, model):
model_params = filter(lambda p: p.requires_grad, model.parameters())
optimizer = torch.optim.Adam(model_params, lr=cfg.lr)
return optimizer
def save_model(self, state, epoch):
file_path = osp.join(cfg.model_dir,'snapshot_{}.pth.tar'.format(str(epoch)))
torch.save(state, file_path)
self.logger.info("Write snapshot into {}".format(file_path))
def load_model(self, model, optimizer):
model_file_list = glob.glob(osp.join(cfg.model_dir,'*.pth.tar'))
cur_epoch = max([int(file_name[file_name.find('snapshot_') + 9 : file_name.find('.pth.tar')]) for file_name in model_file_list])
ckpt_path = osp.join(cfg.model_dir, 'snapshot_' + str(cur_epoch) + '.pth.tar')
ckpt = torch.load(ckpt_path)
start_epoch = ckpt['epoch'] + 1
model.load_state_dict(ckpt['network'], strict=False)
#optimizer.load_state_dict(ckpt['optimizer'])
self.logger.info('Load checkpoint from {}'.format(ckpt_path))
return start_epoch, model, optimizer
def set_lr(self, epoch):
for e in cfg.lr_dec_epoch:
if epoch < e:
break
if epoch < cfg.lr_dec_epoch[-1]:
idx = cfg.lr_dec_epoch.index(e)
for g in self.optimizer.param_groups:
g['lr'] = cfg.lr * (cfg.lr_dec_factor ** idx)
else:
for g in self.optimizer.param_groups:
g['lr'] = cfg.lr * (cfg.lr_dec_factor ** len(cfg.lr_dec_epoch))
def get_lr(self):
for g in self.optimizer.param_groups:
cur_lr = g['lr']
return cur_lr
def _make_batch_generator(self):
# data load and construct batch generator
self.logger.info("Creating dataset...")
train_dataset = eval(cfg.trainset)(transforms.ToTensor(), "train")
self.itr_per_epoch = math.ceil(len(train_dataset) / cfg.num_gpus / cfg.train_batch_size)
self.batch_generator = DataLoader(dataset=train_dataset, batch_size=cfg.num_gpus*cfg.train_batch_size, shuffle=True, num_workers=cfg.num_thread, pin_memory=True)
def _make_model(self):
# prepare network
self.logger.info("Creating graph and optimizer...")
model = get_model('train')
model = DataParallel(model).cuda()
optimizer = self.get_optimizer(model)
if cfg.continue_train:
start_epoch, model, optimizer = self.load_model(model, optimizer)
else:
start_epoch = 0
model.train()
self.start_epoch = start_epoch
self.model = model
self.optimizer = optimizer
class Tester(Base):
def __init__(self, test_epoch):
self.test_epoch = int(test_epoch)
super(Tester, self).__init__(log_name = 'test_logs.txt')
def _make_batch_generator(self):
# data load and construct batch generator
self.logger.info("Creating dataset...")
self.test_dataset = eval(cfg.testset)(transforms.ToTensor(), "test")
self.batch_generator = DataLoader(dataset=self.test_dataset, batch_size=cfg.num_gpus*cfg.test_batch_size, shuffle=False, num_workers=cfg.num_thread, pin_memory=True)
def _make_model(self):
model_path = os.path.join(cfg.model_dir, 'snapshot_%d.pth.tar' % self.test_epoch)
assert os.path.exists(model_path), 'Cannot find model at ' + model_path
self.logger.info('Load checkpoint from {}'.format(model_path))
# prepare network
self.logger.info("Creating graph...")
model = get_model('test')
model = DataParallel(model).cuda()
ckpt = torch.load(model_path)
model.load_state_dict(ckpt['network'], strict=False)
model.eval()
self.model = model
def _evaluate(self, outs, cur_sample_idx):
eval_result = self.test_dataset.evaluate(outs, cur_sample_idx)
return eval_result
def _print_eval_result(self, test_epoch):
self.test_dataset.print_eval_result(test_epoch)
================================================
FILE: common/logger.py
================================================
import logging
import os
OK = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
END = '\033[0m'
PINK = '\033[95m'
BLUE = '\033[94m'
GREEN = OK
RED = FAIL
WHITE = END
YELLOW = WARNING
class colorlogger():
def __init__(self, log_dir, log_name='train_logs.txt'):
# set log
self._logger = logging.getLogger(log_name)
self._logger.setLevel(logging.INFO)
log_file = os.path.join(log_dir, log_name)
if not os.path.exists(log_dir):
os.makedirs(log_dir)
file_log = logging.FileHandler(log_file, mode='a')
file_log.setLevel(logging.INFO)
console_log = logging.StreamHandler()
console_log.setLevel(logging.INFO)
formatter = logging.Formatter(
"{}%(asctime)s{} %(message)s".format(GREEN, END),
"%m-%d %H:%M:%S")
file_log.setFormatter(formatter)
console_log.setFormatter(formatter)
self._logger.addHandler(file_log)
self._logger.addHandler(console_log)
def debug(self, msg):
self._logger.debug(str(msg))
def info(self, msg):
self._logger.info(str(msg))
def warning(self, msg):
self._logger.warning(WARNING + 'WRN: ' + str(msg) + END)
def critical(self, msg):
self._logger.critical(RED + 'CRI: ' + str(msg) + END)
def error(self, msg):
self._logger.error(RED + 'ERR: ' + str(msg) + END)
================================================
FILE: common/nets/backbone.py
================================================
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from torchvision import ops
import torch
from nets.cbam import SpatialGate
class FPN(nn.Module):
def __init__(self, pretrained=True):
super(FPN, self).__init__()
self.in_planes = 64
resnet = resnet50(pretrained=pretrained)
self.toplayer = nn.Conv2d(2048, 256, kernel_size=1, stride=1, padding=0) # Reduce channels
self.layer0 = nn.Sequential(resnet.conv1, resnet.bn1, resnet.leakyrelu, resnet.maxpool)
self.layer1 = nn.Sequential(resnet.layer1)
self.layer2 = nn.Sequential(resnet.layer2)
self.layer3 = nn.Sequential(resnet.layer3)
self.layer4 = nn.Sequential(resnet.layer4)
# Smooth layers
#self.smooth1 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)
self.smooth2 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)
self.smooth3 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)
# Lateral layers
self.latlayer1 = nn.Conv2d(1024, 256, kernel_size=1, stride=1, padding=0)
self.latlayer2 = nn.Conv2d( 512, 256, kernel_size=1, stride=1, padding=0)
self.latlayer3 = nn.Conv2d( 256, 256, kernel_size=1, stride=1, padding=0)
# Attention Module
self.attention_module = SpatialGate()
self.pool = nn.AvgPool2d(2, stride=2)
def _upsample_add(self, x, y):
_, _, H, W = y.size()
return F.interpolate(x, size=(H,W), mode='bilinear', align_corners=False) + y
def forward(self, x):
# Bottom-up
c1 = self.layer0(x)
c2 = self.layer1(c1)
c3 = self.layer2(c2)
c4 = self.layer3(c3)
c5 = self.layer4(c4)
# Top-down
p5 = self.toplayer(c5)
p4 = self._upsample_add(p5, self.latlayer1(c4))
p3 = self._upsample_add(p4, self.latlayer2(c3))
p2 = self._upsample_add(p3, self.latlayer3(c2))
# Smooth
#p4 = self.smooth1(p4)
p3 = self.smooth2(p3)
p2 = self.smooth3(p2)
# Attention
p2 = self.pool(p2)
primary_feats, secondary_feats = self.attention_module(p2)
return primary_feats, secondary_feats
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000):
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.leakyrelu = nn.LeakyReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
self.avgpool = nn.AvgPool2d(7, stride=1)
self.fc = nn.Linear(512 * block.expansion, num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="leaky_relu")
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion))
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.leakyrelu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = x.mean(3).mean(2)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def resnet50(pretrained=False, **kwargs):
"""Constructs a ResNet-50 model Encoder"""
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url("https://download.pytorch.org/models/resnet50-19c8e357.pth"))
return model
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.leakyrelu = nn.LeakyReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.leakyrelu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.leakyrelu(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(
planes, planes, kernel_size=3, stride=stride, padding=1, bias=False
)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(
planes, planes * self.expansion, kernel_size=1, bias=False
)
self.bn3 = nn.BatchNorm2d(planes * self.expansion)
self.leakyrelu = nn.LeakyReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.leakyrelu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.leakyrelu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.leakyrelu(out)
return out
================================================
FILE: common/nets/cbam.py
================================================
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
class BasicConv(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, relu=True, bn=True, bias=False):
super(BasicConv, self).__init__()
self.out_channels = out_planes
self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias)
self.bn = nn.BatchNorm2d(out_planes,eps=1e-5, momentum=0.01, affine=True) if bn else None
self.relu = nn.ReLU() if relu else None
def forward(self, x):
x = self.conv(x)
if self.bn is not None:
x = self.bn(x)
if self.relu is not None:
x = self.relu(x)
return x
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size(0), -1)
class ChannelGate(nn.Module):
def __init__(self, gate_channels, reduction_ratio=16, pool_types=['avg', 'max']):
super(ChannelGate, self).__init__()
self.gate_channels = gate_channels
self.mlp = nn.Sequential(
Flatten(),
nn.Linear(gate_channels, gate_channels // reduction_ratio),
nn.ReLU(),
nn.Linear(gate_channels // reduction_ratio, gate_channels)
)
self.pool_types = pool_types
def forward(self, x):
channel_att_sum = None
for pool_type in self.pool_types:
if pool_type=='avg':
avg_pool = F.avg_pool2d( x, (x.size(2), x.size(3)), stride=(x.size(2), x.size(3)))
channel_att_raw = self.mlp( avg_pool )
elif pool_type=='max':
max_pool = F.max_pool2d( x, (x.size(2), x.size(3)), stride=(x.size(2), x.size(3)))
channel_att_raw = self.mlp( max_pool )
elif pool_type=='lp':
lp_pool = F.lp_pool2d( x, 2, (x.size(2), x.size(3)), stride=(x.size(2), x.size(3)))
channel_att_raw = self.mlp( lp_pool )
elif pool_type=='lse':
# LSE pool only
lse_pool = logsumexp_2d(x)
channel_att_raw = self.mlp( lse_pool )
if channel_att_sum is None:
channel_att_sum = channel_att_raw
else:
channel_att_sum = channel_att_sum + channel_att_raw
scale = F.sigmoid( channel_att_sum ).unsqueeze(2).unsqueeze(3).expand_as(x)
return x * scale
def logsumexp_2d(tensor):
tensor_flatten = tensor.view(tensor.size(0), tensor.size(1), -1)
s, _ = torch.max(tensor_flatten, dim=2, keepdim=True)
outputs = s + (tensor_flatten - s).exp().sum(dim=2, keepdim=True).log()
return outputs
class ChannelPool(nn.Module):
def forward(self, x):
return torch.cat( (torch.max(x,1)[0].unsqueeze(1), torch.mean(x,1).unsqueeze(1)), dim=1 )
class SpatialGate(nn.Module):
def __init__(self):
super(SpatialGate, self).__init__()
kernel_size = 7
self.compress = ChannelPool()
self.spatial = BasicConv(2, 1, kernel_size, stride=1, padding=(kernel_size-1) // 2, relu=False)
def forward(self, x):
x_compress = self.compress(x)
x_out = self.spatial(x_compress)
scale = F.sigmoid(x_out) # broadcasting
return x*scale, x*(1-scale)
class CBAM(nn.Module):
def __init__(self, gate_channels, reduction_ratio=16, pool_types=['avg', 'max'], no_spatial=False):
super(CBAM, self).__init__()
self.ChannelGate = ChannelGate(gate_channels, reduction_ratio, pool_types)
self.no_spatial=no_spatial
if not no_spatial:
self.SpatialGate = SpatialGate()
def forward(self, x):
x_out = self.ChannelGate(x)
if not self.no_spatial:
x_out = self.SpatialGate(x_out)
return x_out
================================================
FILE: common/nets/hand_head.py
================================================
import torch
from torch import nn
import torch.nn.functional as F
class hand_regHead(nn.Module):
def __init__(self, roi_res=32, joint_nb=21, stacks=1, channels=256, blocks=1):
"""
Args:
inr_res: input image size
joint_nb: hand joint num
"""
super(hand_regHead, self).__init__()
# hand head
self.out_res = roi_res
self.joint_nb = joint_nb
self.channels = channels
self.blocks = blocks
self.stacks = stacks
self.betas = nn.Parameter(torch.ones((self.joint_nb, 1), dtype=torch.float32))
center_offset = 0.5
vv, uu = torch.meshgrid(torch.arange(self.out_res).float(), torch.arange(self.out_res).float())
uu, vv = uu + center_offset, vv + center_offset
self.register_buffer("uu", uu / self.out_res)
self.register_buffer("vv", vv / self.out_res)
self.softmax = nn.Softmax(dim=2)
block = Bottleneck
self.features = self.channels // block.expansion
hg, res, fc, score, fc_, score_ = [], [], [], [], [], []
for i in range(self.stacks):
hg.append(Hourglass(block, self.blocks, self.features, 4))
res.append(self.make_residual(block, self.channels, self.features, self.blocks))
fc.append(BasicBlock(self.channels, self.channels, kernel_size=1))
score.append(nn.Conv2d(self.channels, self.joint_nb, kernel_size=1, bias=True))
if i < self.stacks - 1:
fc_.append(nn.Conv2d(self.channels, self.channels, kernel_size=1, bias=True))
score_.append(nn.Conv2d(self.joint_nb, self.channels, kernel_size=1, bias=True))
self.hg = nn.ModuleList(hg)
self.res = nn.ModuleList(res)
self.fc = nn.ModuleList(fc)
self.score = nn.ModuleList(score)
self.fc_ = nn.ModuleList(fc_)
self.score_ = nn.ModuleList(score_)
def make_residual(self, block, inplanes, planes, blocks, stride=1):
skip = None
if stride != 1 or inplanes != planes * block.expansion:
skip = nn.Sequential(
nn.Conv2d(inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=True))
layers = []
layers.append(block(inplanes, planes, stride, skip))
for i in range(1, blocks):
layers.append(block(inplanes, planes))
return nn.Sequential(*layers)
def spatial_softmax(self, latents):
latents = latents.view((-1, self.joint_nb, self.out_res ** 2))
latents = latents * self.betas
heatmaps = self.softmax(latents)
heatmaps = heatmaps.view(-1, self.joint_nb, self.out_res, self.out_res)
return heatmaps
def generate_output(self, heatmaps):
predictions = torch.stack((
torch.sum(torch.sum(heatmaps * self.uu, dim=2), dim=2),
torch.sum(torch.sum(heatmaps * self.vv, dim=2), dim=2)), dim=2)
return predictions
def forward(self, x):
out, encoding, preds = [], [], []
for i in range(self.stacks):
y = self.hg[i](x)
y = self.res[i](y)
y = self.fc[i](y)
latents = self.score[i](y)
heatmaps= self.spatial_softmax(latents)
out.append(heatmaps)
predictions = self.generate_output(heatmaps)
preds.append(predictions)
if i < self.stacks - 1:
fc_ = self.fc_[i](y)
score_ = self.score_[i](heatmaps)
x = x + fc_ + score_
encoding.append(x)
else:
encoding.append(y)
return out, encoding, preds
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size,groups=1):
super(BasicBlock, self).__init__()
self.block = nn.Sequential(
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size,
stride=1, padding=((kernel_size - 1) // 2),
groups=groups,bias=True),
nn.BatchNorm2d(out_planes),
nn.LeakyReLU(inplace=True)
)
def forward(self, x):
return self.block(x)
class Residual(nn.Module):
def __init__(self, numIn, numOut):
super(Residual, self).__init__()
self.numIn = numIn
self.numOut = numOut
self.bn = nn.BatchNorm2d(self.numIn)
self.leakyrelu = nn.LeakyReLU(inplace=True)
self.conv1 = nn.Conv2d(self.numIn, self.numOut // 2, bias=True, kernel_size=1)
self.bn1 = nn.BatchNorm2d(self.numOut // 2)
self.conv2 = nn.Conv2d(self.numOut // 2, self.numOut // 2, bias=True, kernel_size=3, stride=1, padding=1)
self.bn2 = nn.BatchNorm2d(self.numOut // 2)
self.conv3 = nn.Conv2d(self.numOut // 2, self.numOut, bias=True, kernel_size=1)
if self.numIn != self.numOut:
self.conv4 = nn.Conv2d(self.numIn, self.numOut, bias=True, kernel_size=1)
def forward(self, x):
residual = x
out = self.bn(x)
out = self.leakyrelu(out)
out = self.conv1(out)
out = self.bn1(out)
out = self.leakyrelu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.leakyrelu(out)
out = self.conv3(out)
if self.numIn != self.numOut:
residual = self.conv4(x)
return out + residual
class Bottleneck(nn.Module):
expansion = 2
def __init__(self, inplanes, planes, stride=1, skip=None, groups=1):
super(Bottleneck, self).__init__()
self.bn1 = nn.BatchNorm2d(inplanes)
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=True, groups=groups)
self.bn2 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
padding=1, bias=True, groups=groups)
self.bn3 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, planes * 2, kernel_size=1, bias=True, groups=groups)
self.leakyrelu = nn.LeakyReLU(inplace=True) # negative_slope=0.01
self.skip = skip
self.stride = stride
def forward(self, x):
residual = x
out = self.bn1(x)
out = self.leakyrelu(out)
out = self.conv1(out)
out = self.bn2(out)
out = self.leakyrelu(out)
out = self.conv2(out)
out = self.bn3(out)
out = self.leakyrelu(out)
out = self.conv3(out)
if self.skip is not None:
residual = self.skip(x)
out += residual
return out
class Hourglass(nn.Module):
def __init__(self, block, num_blocks, planes, depth):
super(Hourglass, self).__init__()
self.depth = depth
self.block = block
self.hg = self._make_hour_glass(block, num_blocks, planes, depth)
def _make_residual(self, block, num_blocks, planes):
layers = []
for i in range(0, num_blocks):
# channel changes: planes*block.expansion->planes->2*planes
layers.append(block(planes * block.expansion, planes))
return nn.Sequential(*layers)
def _make_hour_glass(self, block, num_blocks, planes, depth):
hg = []
for i in range(depth):
res = []
for j in range(3):
# 3 residual modules composed of a residual unit
# <2*planes><2*planes>
res.append(self._make_residual(block, num_blocks, planes))
if i == 0:
# i=0 in a recursive construction build the basic network path
# see: low2 = self.hg[n-1][3](low1)
# <2*planes><2*planes>
res.append(self._make_residual(block, num_blocks, planes))
hg.append(nn.ModuleList(res))
return nn.ModuleList(hg)
def _hour_glass_forward(self, n, x):
up1 = self.hg[n - 1][0](x) # skip branches
low1 = F.max_pool2d(x, 2, stride=2)
low1 = self.hg[n - 1][1](low1)
if n > 1:
low2 = self._hour_glass_forward(n - 1, low1)
else:
low2 = self.hg[n - 1][3](low1) # only for depth=1 basic path of the hourglass network
low3 = self.hg[n - 1][2](low2)
up2 = F.interpolate(low3, scale_factor=2) # scale_factor=2 should be consistent with F.max_pool2d(2,stride=2)
out = up1 + up2
return out
def forward(self, x):
# depth: order of the hourglass network
# do network forward recursively
return self._hour_glass_forward(self.depth, x)
class hand_Encoder(nn.Module):
def __init__(self, num_heatmap_chan=21, num_feat_chan=256, size_input_feature=(32, 32),
nRegBlock=4, nRegModules=2):
super(hand_Encoder, self).__init__()
self.num_heatmap_chan = num_heatmap_chan
self.num_feat_chan = num_feat_chan
self.size_input_feature = size_input_feature
self.nRegBlock = nRegBlock
self.nRegModules = nRegModules
self.heatmap_conv = nn.Conv2d(self.num_heatmap_chan, self.num_feat_chan,
bias=True, kernel_size=1, stride=1)
self.encoding_conv = nn.Conv2d(self.num_feat_chan, self.num_feat_chan,
bias=True, kernel_size=1, stride=1)
reg = []
for i in range(self.nRegBlock):
for j in range(self.nRegModules):
reg.append(Residual(self.num_feat_chan, self.num_feat_chan))
self.reg = nn.ModuleList(reg)
self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2)
self.downsample_scale = 2 ** self.nRegBlock
# fc layers
self.num_feat_out = self.num_feat_chan * (size_input_feature[0] * size_input_feature[1] // (self.downsample_scale ** 2))
def forward(self, hm_list, encoding_list):
x = self.heatmap_conv(hm_list[-1]) + self.encoding_conv(encoding_list[-1])
if len(encoding_list) > 1:
x = x + encoding_list[-2]
# x: B x num_feat_chan x 32 x 32
for i in range(self.nRegBlock):
for j in range(self.nRegModules):
x = self.reg[i * self.nRegModules + j](x)
x = self.maxpool(x)
# x: B x num_feat_chan x 2 x 2
out = x.view(x.size(0), -1)
return out
================================================
FILE: common/nets/mano_head.py
================================================
import torch
from torch import nn
from torch.nn import functional as F
from utils.mano import MANO
mano = MANO()
def batch_rodrigues(theta):
# theta N x 3
l1norm = torch.norm(theta + 1e-8, p=2, dim=1)
angle = torch.unsqueeze(l1norm, -1)
normalized = torch.div(theta, angle)
angle = angle * 0.5
v_cos = torch.cos(angle)
v_sin = torch.sin(angle)
quat = torch.cat([v_cos, v_sin * normalized], dim=1)
return quat2mat(quat)
def quat2mat(quat):
"""Convert quaternion coefficients to rotation matrix.
"""
norm_quat = quat
norm_quat = norm_quat / norm_quat.norm(p=2, dim=1, keepdim=True)
w, x, y, z = norm_quat[:, 0], norm_quat[:, 1], norm_quat[:, 2], norm_quat[:, 3]
B = quat.size(0)
w2, x2, y2, z2 = w.pow(2), x.pow(2), y.pow(2), z.pow(2)
wx, wy, wz = w * x, w * y, w * z
xy, xz, yz = x * y, x * z, y * z
rotMat = torch.stack([w2 + x2 - y2 - z2, 2 * xy - 2 * wz, 2 * wy + 2 * xz,
2 * wz + 2 * xy, w2 - x2 + y2 - z2, 2 * yz - 2 * wx,
2 * xz - 2 * wy, 2 * wx + 2 * yz, w2 - x2 - y2 + z2], dim=1).view(B, 3, 3)
return rotMat
def quat2aa(quaternion):
"""Convert quaternion vector to angle axis of rotation."""
if not torch.is_tensor(quaternion):
raise TypeError("Input type is not a torch.Tensor. Got {}".format(
type(quaternion)))
if not quaternion.shape[-1] == 4:
raise ValueError("Input must be a tensor of shape Nx4 or 4. Got {}"
.format(quaternion.shape))
# unpack input and compute conversion
q1 = quaternion[..., 1]
q2 = quaternion[..., 2]
q3 = quaternion[..., 3]
sin_squared_theta = q1 * q1 + q2 * q2 + q3 * q3
sin_theta = torch.sqrt(sin_squared_theta)
cos_theta = quaternion[..., 0]
two_theta = 2.0 * torch.where(
cos_theta < 0.0,
torch.atan2(-sin_theta, -cos_theta),
torch.atan2(sin_theta, cos_theta))
k_pos = two_theta / sin_theta
k_neg = 2.0 * torch.ones_like(sin_theta)
k = torch.where(sin_squared_theta > 0.0, k_pos, k_neg)
angle_axis = torch.zeros_like(quaternion)[..., :3]
angle_axis[..., 0] += q1 * k
angle_axis[..., 1] += q2 * k
angle_axis[..., 2] += q3 * k
return angle_axis
def mat2quat(rotation_matrix, eps=1e-6):
"""Convert 3x4 rotation matrix to 4d quaternion vector"""
if not torch.is_tensor(rotation_matrix):
raise TypeError("Input type is not a torch.Tensor. Got {}".format(
type(rotation_matrix)))
if len(rotation_matrix.shape) > 3:
raise ValueError(
"Input size must be a three dimensional tensor. Got {}".format(
rotation_matrix.shape))
if not rotation_matrix.shape[-2:] == (3, 4):
raise ValueError(
"Input size must be a N x 3 x 4 tensor. Got {}".format(
rotation_matrix.shape))
rmat_t = torch.transpose(rotation_matrix, 1, 2)
mask_d2 = rmat_t[:, 2, 2] < eps
mask_d0_d1 = rmat_t[:, 0, 0] > rmat_t[:, 1, 1]
mask_d0_nd1 = rmat_t[:, 0, 0] < -rmat_t[:, 1, 1]
t0 = 1 + rmat_t[:, 0, 0] - rmat_t[:, 1, 1] - rmat_t[:, 2, 2]
q0 = torch.stack([rmat_t[:, 1, 2] - rmat_t[:, 2, 1],
t0, rmat_t[:, 0, 1] + rmat_t[:, 1, 0],
rmat_t[:, 2, 0] + rmat_t[:, 0, 2]], -1)
t0_rep = t0.repeat(4, 1).t()
t1 = 1 - rmat_t[:, 0, 0] + rmat_t[:, 1, 1] - rmat_t[:, 2, 2]
q1 = torch.stack([rmat_t[:, 2, 0] - rmat_t[:, 0, 2],
rmat_t[:, 0, 1] + rmat_t[:, 1, 0],
t1, rmat_t[:, 1, 2] + rmat_t[:, 2, 1]], -1)
t1_rep = t1.repeat(4, 1).t()
t2 = 1 - rmat_t[:, 0, 0] - rmat_t[:, 1, 1] + rmat_t[:, 2, 2]
q2 = torch.stack([rmat_t[:, 0, 1] - rmat_t[:, 1, 0],
rmat_t[:, 2, 0] + rmat_t[:, 0, 2],
rmat_t[:, 1, 2] + rmat_t[:, 2, 1], t2], -1)
t2_rep = t2.repeat(4, 1).t()
t3 = 1 + rmat_t[:, 0, 0] + rmat_t[:, 1, 1] + rmat_t[:, 2, 2]
q3 = torch.stack([t3, rmat_t[:, 1, 2] - rmat_t[:, 2, 1],
rmat_t[:, 2, 0] - rmat_t[:, 0, 2],
rmat_t[:, 0, 1] - rmat_t[:, 1, 0]], -1)
t3_rep = t3.repeat(4, 1).t()
mask_c0 = mask_d2 * mask_d0_d1
mask_c1 = mask_d2 * ~mask_d0_d1
mask_c2 = ~mask_d2 * mask_d0_nd1
mask_c3 = ~mask_d2 * ~mask_d0_nd1
mask_c0 = mask_c0.view(-1, 1).type_as(q0)
mask_c1 = mask_c1.view(-1, 1).type_as(q1)
mask_c2 = mask_c2.view(-1, 1).type_as(q2)
mask_c3 = mask_c3.view(-1, 1).type_as(q3)
q = q0 * mask_c0 + q1 * mask_c1 + q2 * mask_c2 + q3 * mask_c3
q /= torch.sqrt(t0_rep * mask_c0 + t1_rep * mask_c1 + # noqa
t2_rep * mask_c2 + t3_rep * mask_c3) # noqa
q *= 0.5
return q
def rot6d2mat(x):
"""Convert 6D rotation representation to 3x3 rotation matrix.
Based on Zhou et al., "On the Continuity of Rotation Representations in Neural Networks", CVPR 2019
"""
a1 = x[:, 0:3]
a2 = x[:, 3:6]
b1 = F.normalize(a1)
b2 = F.normalize(a2 - torch.einsum('bi,bi->b', b1, a2).unsqueeze(-1) * b1)
b3 = torch.cross(b1, b2, dim=1)
return torch.stack((b1, b2, b3), dim=-1)
def mat2aa(rotation_matrix):
"""Convert 3x4 rotation matrix to Rodrigues vector"""
def convert_points_to_homogeneous(points):
if not torch.is_tensor(points):
raise TypeError("Input type is not a torch.Tensor. Got {}".format(
type(points)))
if len(points.shape) < 2:
raise ValueError("Input must be at least a 2D tensor. Got {}".format(
points.shape))
return F.pad(points, (0, 1), "constant", 1.0)
if rotation_matrix.shape[1:] == (3, 3):
rotation_matrix = convert_points_to_homogeneous(rotation_matrix)
quaternion = mat2quat(rotation_matrix)
aa = quat2aa(quaternion)
aa[torch.isnan(aa)] = 0.0
return aa
class mano_regHead(nn.Module):
def __init__(self, mano_layer=mano.layer, feature_size=1024, mano_neurons=[1024, 512]):
super(mano_regHead, self).__init__()
# 6D representation of rotation matrix
self.pose6d_size = 16 * 6
self.mano_pose_size = 16 * 3
# Base Regression Layers
mano_base_neurons = [feature_size] + mano_neurons
base_layers = []
for layer_idx, (inp_neurons, out_neurons) in enumerate(
zip(mano_base_neurons[:-1], mano_base_neurons[1:])):
base_layers.append(nn.Linear(inp_neurons, out_neurons))
base_layers.append(nn.LeakyReLU(inplace=True))
self.mano_base_layer = nn.Sequential(*base_layers)
# Pose layers
self.pose_reg = nn.Linear(mano_base_neurons[-1], self.pose6d_size)
# Shape layers
self.shape_reg = nn.Linear(mano_base_neurons[-1], 10)
self.mano_layer = mano_layer
def forward(self, features, gt_mano_params=None):
mano_features = self.mano_base_layer(features)
pred_mano_pose_6d = self.pose_reg(mano_features)
pred_mano_pose_rotmat = rot6d2mat(pred_mano_pose_6d.view(-1, 6)).view(-1, 16, 3, 3).contiguous()
pred_mano_shape = self.shape_reg(mano_features)
pred_mano_pose = mat2aa(pred_mano_pose_rotmat.view(-1, 3, 3)).contiguous().view(-1, self.mano_pose_size)
pred_verts, pred_joints, pred_manojoints2cam = self.mano_layer(th_pose_coeffs=pred_mano_pose, th_betas=pred_mano_shape)
pred_verts /= 1000
pred_joints /= 1000
pred_mano_results = {
"verts3d": pred_verts,
"joints3d": pred_joints,
"mano_shape": pred_mano_shape,
"mano_pose": pred_mano_pose_rotmat,
"mano_pose_aa": pred_mano_pose,
"manojoints2cam": pred_manojoints2cam
}
if gt_mano_params is not None:
gt_mano_shape = gt_mano_params[:, self.mano_pose_size:]
gt_mano_pose = gt_mano_params[:, :self.mano_pose_size].contiguous()
gt_mano_pose_rotmat = batch_rodrigues(gt_mano_pose.view(-1, 3)).view(-1, 16, 3, 3)
gt_verts, gt_joints = self.mano_layer(th_pose_coeffs=gt_mano_pose, th_betas=gt_mano_shape)
gt_verts /= 1000
gt_joints /= 1000
gt_mano_results = {
"verts3d": gt_verts,
"joints3d": gt_joints,
"mano_shape": gt_mano_shape,
"mano_pose": gt_mano_pose_rotmat}
else:
gt_mano_results = None
return pred_mano_results, gt_mano_results
================================================
FILE: common/nets/regressor.py
================================================
import torch
import torch.nn as nn
from torch.nn import functional as F
from utils.mano import MANO
from nets.hand_head import hand_regHead, hand_Encoder
from nets.mano_head import mano_regHead
class Regressor(nn.Module):
def __init__(self):
super(Regressor, self).__init__()
self.hand_regHead = hand_regHead()
self.hand_Encoder = hand_Encoder()
self.mano_regHead = mano_regHead()
def forward(self, feats, gt_mano_params=None):
out_hm, encoding, preds_joints_img = self.hand_regHead(feats)
mano_encoding = self.hand_Encoder(out_hm, encoding)
pred_mano_results, gt_mano_results = self.mano_regHead(mano_encoding, gt_mano_params)
return pred_mano_results, gt_mano_results, preds_joints_img
================================================
FILE: common/nets/transformer.py
================================================
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import repeat
class Transformer(nn.Module):
def __init__(self, inp_res=32, dim=256, depth=2, num_heads=4, mlp_ratio=4., injection=True):
super().__init__()
self.injection=injection
self.layers = nn.ModuleList([])
for _ in range(depth):
self.layers.append(Block(dim=dim, num_heads=num_heads, mlp_ratio=mlp_ratio, injection=injection))
if self.injection:
self.conv1 = nn.Sequential(
nn.Conv2d(dim*2, dim, 3, padding=1),
nn.ReLU(),
nn.Conv2d(dim, dim, 3, padding=1),
)
self.conv2 = nn.Sequential(
nn.Conv2d(dim*2, dim, 1, padding=0),
)
def forward(self, query, key):
output = query
for i, layer in enumerate(self.layers):
output = layer(query=output, key=key)
if self.injection:
output = torch.cat([key, output], dim=1)
output = self.conv1(output) + self.conv2(output)
return output
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
self._init_weights()
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
def _init_weights(self):
nn.init.xavier_uniform_(self.fc1.weight)
nn.init.xavier_uniform_(self.fc2.weight)
nn.init.normal_(self.fc1.bias, std=1e-6)
nn.init.normal_(self.fc2.bias, std=1e-6)
class Attention(nn.Module):
def __init__(self, dim, num_heads=1):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = head_dim ** -0.5
self.sigmoid = nn.Sigmoid()
def forward(self, query, key, value, query2, key2, use_sigmoid):
B, N, C = query.shape
query = query.reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
key = key.reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
value = value.reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
attn = torch.matmul(query, key.transpose(-2, -1)) * self.scale
attn = attn.softmax(dim=-1)
if use_sigmoid:
query2 = query2.reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
key2 = key2.reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
attn2 = torch.matmul(query2, key2.transpose(-2, -1)) * self.scale
attn2 = torch.sum(attn2, dim=-1)
attn2 = self.sigmoid(attn2)
attn = attn * attn2.unsqueeze(3)
x = torch.matmul(attn, value).transpose(1, 2).reshape(B, N, C)
return x
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., act_layer=nn.GELU, norm_layer=nn.LayerNorm, injection=True):
super().__init__()
self.injection = injection
self.channels = dim
self.encode_value = nn.Conv2d(in_channels=dim, out_channels=dim, kernel_size=1, stride=1, padding=0)
self.encode_query = nn.Conv2d(in_channels=dim, out_channels=dim, kernel_size=1, stride=1, padding=0)
self.encode_key = nn.Conv2d(in_channels=dim, out_channels=dim, kernel_size=1, stride=1, padding=0)
if self.injection:
self.encode_query2 = nn.Conv2d(in_channels=dim, out_channels=dim, kernel_size=1, stride=1, padding=0)
self.encode_key2 = nn.Conv2d(in_channels=dim, out_channels=dim, kernel_size=1, stride=1, padding=0)
self.attn = Attention(dim, num_heads=num_heads)
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer)
self.q_embedding = nn.Parameter(torch.randn(1, 256, 32, 32))
self.k_embedding = nn.Parameter(torch.randn(1, 256, 32, 32))
def with_pos_embed(self, tensor, pos):
return tensor if pos is None else tensor + pos
def forward(self, query, key, query_embed=None, key_embed=None):
b, c, h, w = query.shape
query_embed = repeat(self.q_embedding, '() n c d -> b n c d', b = b)
key_embed = repeat(self.k_embedding, '() n c d -> b n c d', b = b)
q_embed = self.with_pos_embed(query, query_embed)
k_embed = self.with_pos_embed(key, key_embed)
v = self.encode_value(key).view(b, self.channels, -1)
v = v.permute(0, 2, 1)
q = self.encode_query(q_embed).view(b, self.channels, -1)
q = q.permute(0, 2, 1)
k = self.encode_key(k_embed).view(b, self.channels, -1)
k = k.permute(0, 2, 1)
query = query.view(b, self.channels, -1).permute(0, 2, 1)
if self.injection:
q2 = self.encode_query2(q_embed).view(b, self.channels, -1)
q2 = q2.permute(0, 2, 1)
k2 = self.encode_key2(k_embed).view(b, self.channels, -1)
k2 = k2.permute(0, 2, 1)
query = self.attn(query=q, key=k, value=v,query2 = q2, key2 = k2, use_sigmoid=True)
else:
q2 = None
k2 = None
query = query + self.attn(query=q, key=k, value=v, query2 = q2, key2 = k2, use_sigmoid=False)
query = query + self.mlp(self.norm2(query))
query = query.permute(0, 2, 1).contiguous().view(b, self.channels, h, w)
return query
================================================
FILE: common/timer.py
================================================
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
import time
class Timer(object):
"""A simple timer."""
def __init__(self):
self.total_time = 0.
self.calls = 0
self.start_time = 0.
self.diff = 0.
self.average_time = 0.
self.warm_up = 0
def tic(self):
# using time.time instead of time.clock because time time.clock
# does not normalize for multithreading
self.start_time = time.time()
def toc(self, average=True):
self.diff = time.time() - self.start_time
if self.warm_up < 10:
self.warm_up += 1
return self.diff
else:
self.total_time += self.diff
self.calls += 1
self.average_time = self.total_time / self.calls
if average:
return self.average_time
else:
return self.diff
================================================
FILE: common/utils/__init__.py
================================================
================================================
FILE: common/utils/camera.py
================================================
# -*- coding: utf-8 -*-
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# You can only use this computer program if you have closed
# a license agreement with MPG or you get the right to use the computer
# program from someone who is authorized to grant you that right.
# Any use of the computer program without a valid license is prohibited and
# liable to prosecution.
#
# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
# for Intelligent Systems and the Max Planck Institute for Biological
# Cybernetics. All rights reserved.
#
# Contact: ps-license@tuebingen.mpg.de
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from collections import namedtuple
import torch
import torch.nn as nn
import torch.nn.functional as F
PerspParams = namedtuple('ModelOutput',
['rotation', 'translation', 'center',
'focal_length'])
def transform_mat(R: torch.tensor, t: torch.tensor) -> torch.Tensor:
''' Creates a batch of transformation matrices
Args:
- R: Bx3x3 array of a batch of rotation matrices
- t: Bx3x1 array of a batch of translation vectors
Returns:
- T: Bx4x4 Transformation matrix
'''
# No padding left or right, only add an extra row
return torch.cat([F.pad(R, [0, 0, 0, 1]),
F.pad(t, [0, 0, 0, 1], value=1)], dim=2)
def create_camera(camera_type='persp', **kwargs):
if camera_type.lower() == 'persp':
return PerspectiveCamera(**kwargs)
else:
raise ValueError('Uknown camera type: {}'.format(camera_type))
class PerspectiveCamera(nn.Module):
FOCAL_LENGTH = 500
def __init__(self, rotation=None, translation=None,
focal_length_x=None, focal_length_y=None,
batch_size=1,
center=None, dtype=torch.float32, **kwargs):
super(PerspectiveCamera, self).__init__()
self.name = ''
self.batch_size = batch_size
self.dtype = dtype
# Make a buffer so that PyTorch does not complain when creating
# the camera matrix
self.register_buffer('zero',
torch.zeros([batch_size], dtype=dtype))
if focal_length_x is None or type(focal_length_x) == float:
focal_length_x = torch.full(
[batch_size],
self.FOCAL_LENGTH if focal_length_x is None else
focal_length_x,
dtype=dtype)
if focal_length_y is None or type(focal_length_y) == float:
focal_length_y = torch.full(
[batch_size],
self.FOCAL_LENGTH if focal_length_y is None else
focal_length_y,
dtype=dtype)
self.register_buffer('focal_length_x', focal_length_x)
self.register_buffer('focal_length_y', focal_length_y)
if center is None:
center = torch.zeros([batch_size, 2], dtype=dtype)
self.register_buffer('center', center)
if rotation is None:
rotation = torch.eye(
3, dtype=dtype).unsqueeze(dim=0).repeat(batch_size, 1, 1)
rotation = nn.Parameter(rotation, requires_grad=True)
self.register_parameter('rotation', rotation)
if translation is None:
translation = torch.zeros([batch_size, 3], dtype=dtype)
translation = nn.Parameter(translation,
requires_grad=True)
self.register_parameter('translation', translation)
def forward(self, points):
device = points.device
with torch.no_grad():
camera_mat = torch.zeros([self.batch_size, 2, 2],
dtype=self.dtype, device=points.device)
camera_mat[:, 0, 0] = self.focal_length_x
camera_mat[:, 1, 1] = self.focal_length_y
camera_transform = transform_mat(self.rotation,
self.translation.unsqueeze(dim=-1))
homog_coord = torch.ones(list(points.shape)[:-1] + [1],
dtype=points.dtype,
device=device)
# Convert the points to homogeneous coordinates
points_h = torch.cat([points, homog_coord], dim=-1)
projected_points = torch.einsum('bki,bji->bjk',
[camera_transform, points_h])
img_points = torch.div(projected_points[:, :, :2],
projected_points[:, :, 2].unsqueeze(dim=-1))
img_points = torch.einsum('bki,bji->bjk', [camera_mat, img_points]) \
+ self.center.unsqueeze(dim=1)
return img_points
================================================
FILE: common/utils/dir.py
================================================
import os
import sys
def make_folder(folder_name):
if not os.path.exists(folder_name):
os.makedirs(folder_name)
def add_pypath(path):
if path not in sys.path:
sys.path.insert(0, path)
================================================
FILE: common/utils/fitting.py
================================================
import numpy as np
import torch
import torch.nn as nn
def to_tensor(tensor, dtype=torch.float32):
if torch.Tensor == type(tensor):
return tensor.clone().detach()
else:
return torch.tensor(tensor, dtype=dtype)
def rel_change(prev_val, curr_val):
return (prev_val - curr_val) / max([np.abs(prev_val), np.abs(curr_val), 1])
class FittingMonitor(object):
def __init__(self, summary_steps=1, visualize=False,
maxiters=300, ftol=1e-10, gtol=1e-09,
body_color=(1.0, 1.0, 0.9, 1.0),
model_type='mano',
**kwargs):
super(FittingMonitor, self).__init__()
self.maxiters = maxiters
self.ftol = ftol
self.gtol = gtol
self.visualize = visualize
self.summary_steps = summary_steps
self.body_color = body_color
self.model_type = model_type
def __enter__(self):
self.steps = 0
return self
def __exit__(self, exception_type, exception_value, traceback):
pass
def set_colors(self, vertex_color):
batch_size = self.colors.shape[0]
self.colors = np.tile(
np.array(vertex_color).reshape(1, 3),
[batch_size, 1])
def run_fitting(self, optimizer, closure, params,
**kwargs):
''' Helper function for running an optimization process
Parameters
----------
optimizer: torch.optim.Optimizer
The PyTorch optimizer object
closure: function
The function used to calculate the gradients
params: list
List containing the parameters that will be optimized
Returns
-------
loss: float
The final loss value
'''
prev_loss = None
for n in range(self.maxiters):
loss = optimizer.step(closure)
if torch.isnan(loss).sum() > 0:
print('NaN loss value, stopping!')
break
if torch.isinf(loss).sum() > 0:
print('Infinite loss value, stopping!')
break
if n > 0 and prev_loss is not None and self.ftol > 0:
loss_rel_change = rel_change(prev_loss, loss.item())
if loss_rel_change <= self.ftol:
break
if all([torch.abs(var.grad.view(-1).max()).item() < self.gtol
for var in params if var.grad is not None]):
break
prev_loss = loss.item()
return prev_loss
def create_fitting_closure(self,
optimizer,
camera=None,
joint_cam=None,
joint_img=None,
hand_translation=None,
hand_scale=None,
loss=None,
joints_conf=None,
joint_weights=None,
create_graph=False,
**kwargs):
def fitting_func(backward=True):
if backward:
optimizer.zero_grad()
total_loss = loss(camera=camera,
joint_cam=joint_cam,
joint_img=joint_img,
hand_translation=hand_translation,
hand_scale =hand_scale,
**kwargs)
if backward:
total_loss.backward(create_graph=create_graph)
self.steps += 1
return total_loss
return fitting_func
class ScaleTranslationLoss(nn.Module):
def __init__(self, init_joints_idxs, trans_estimation=None,
reduction='sum',
data_weight=1.0,
depth_loss_weight=1e3, dtype=torch.float32,
**kwargs):
super(ScaleTranslationLoss, self).__init__()
self.dtype = dtype
if trans_estimation is not None:
self.register_buffer(
'trans_estimation',
to_tensor(trans_estimation, dtype=dtype))
else:
self.trans_estimation = trans_estimation
self.register_buffer('data_weight',
torch.tensor(data_weight, dtype=dtype))
self.register_buffer(
'init_joints_idxs',
to_tensor(init_joints_idxs, dtype=torch.long))
self.register_buffer('depth_loss_weight',
torch.tensor(depth_loss_weight, dtype=dtype))
def reset_loss_weights(self, loss_weight_dict):
for key in loss_weight_dict:
if hasattr(self, key):
weight_tensor = getattr(self, key)
weight_tensor = torch.tensor(loss_weight_dict[key],
dtype=weight_tensor.dtype,
device=weight_tensor.device)
setattr(self, key, weight_tensor)
def forward(self, camera, joint_cam, joint_img, hand_translation, hand_scale, **kwargs):
projected_joints = camera(
hand_scale * joint_cam + hand_translation)
joint_error = \
torch.index_select(joint_img, 1, self.init_joints_idxs) - \
torch.index_select(projected_joints, 1, self.init_joints_idxs)
joint_loss = torch.sum(joint_error.abs()) * self.data_weight ** 2
depth_loss = 0.0
if (self.depth_loss_weight.item() > 0 and self.trans_estimation is not None):
depth_loss = self.depth_loss_weight * torch.sum((
hand_translation[2] - self.trans_estimation[2]).abs() ** 2)
return joint_loss + depth_loss
================================================
FILE: common/utils/mano.py
================================================
import numpy as np
import torch
import os.path as osp
import json
from config import cfg
import sys
sys.path.insert(0, cfg.mano_path)
import manopth
from manopth.manolayer import ManoLayer
class MANO(object):
def __init__(self):
# TEMP
self.left_layer = ManoLayer(mano_root=osp.join(cfg.mano_path, 'mano', 'models'), flat_hand_mean=False, use_pca=False, side='left') # load right hand MANO model
self.layer = self.get_layer()
self.vertex_num = 778
self.face = self.layer.th_faces.numpy()
self.joint_regressor = self.layer.th_J_regressor.numpy()
self.joint_num = 21
self.joints_name = ('Wrist', 'Thumb_1', 'Thumb_2', 'Thumb_3', 'Thumb_4', 'Index_1', 'Index_2', 'Index_3', 'Index_4', 'Middle_1', 'Middle_2', 'Middle_3', 'Middle_4', 'Ring_1', 'Ring_2', 'Ring_3', 'Ring_4', 'Pinky_1', 'Pinky_2', 'Pinky_3', 'Pinly_4')
self.skeleton = ( (0,1), (0,5), (0,9), (0,13), (0,17), (1,2), (2,3), (3,4), (5,6), (6,7), (7,8), (9,10), (10,11), (11,12), (13,14), (14,15), (15,16), (17,18), (18,19), (19,20) )
self.root_joint_idx = self.joints_name.index('Wrist')
# add fingertips to joint_regressor
self.fingertip_vertex_idx = [728, 353, 442, 576, 694] # mesh vertex idx
thumbtip_onehot = np.array([1 if i == 728 else 0 for i in range(self.joint_regressor.shape[1])], dtype=np.float32).reshape(1,-1)
indextip_onehot = np.array([1 if i == 353 else 0 for i in range(self.joint_regressor.shape[1])], dtype=np.float32).reshape(1,-1)
middletip_onehot = np.array([1 if i == 442 else 0 for i in range(self.joint_regressor.shape[1])], dtype=np.float32).reshape(1,-1)
ringtip_onehot = np.array([1 if i == 576 else 0 for i in range(self.joint_regressor.shape[1])], dtype=np.float32).reshape(1,-1)
pinkytip_onehot = np.array([1 if i == 694 else 0 for i in range(self.joint_regressor.shape[1])], dtype=np.float32).reshape(1,-1)
self.joint_regressor = np.concatenate((self.joint_regressor, thumbtip_onehot, indextip_onehot, middletip_onehot, ringtip_onehot, pinkytip_onehot))
self.joint_regressor = self.joint_regressor[[0, 13, 14, 15, 16, 1, 2, 3, 17, 4, 5, 6, 18, 10, 11, 12, 19, 7, 8, 9, 20],:]
def get_layer(self):
return ManoLayer(mano_root=osp.join(cfg.mano_path, 'mano', 'models'), flat_hand_mean=False, use_pca=False, side='right') # load right hand MANO model
================================================
FILE: common/utils/manopth/.gitignore
================================================
*.sw*
*.bak
*_bak.py
.cache/
__pycache__/
build/
dist/
manopth_hassony2.egg-info/
mano/models
assets/mano_layer.svg
================================================
FILE: common/utils/manopth/LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
================================================
FILE: common/utils/manopth/README.md
================================================
Manopth
=======
[MANO](http://mano.is.tue.mpg.de) layer for [PyTorch](https://pytorch.org/) (tested with v0.4 and v1.x)
ManoLayer is a differentiable PyTorch layer that deterministically maps from pose and shape parameters to hand joints and vertices.
It can be integrated into any architecture as a differentiable layer to predict hand meshes.

ManoLayer takes **batched** hand pose and shape vectors and outputs corresponding hand joints and vertices.
The code is mostly a PyTorch port of the original [MANO](http://mano.is.tue.mpg.de) model from [chumpy](https://github.com/mattloper/chumpy) to [PyTorch](https://pytorch.org/).
It therefore builds directly upon the work of Javier Romero, Dimitrios Tzionas and Michael J. Black.
This layer was developped and used for the paper *Learning joint reconstruction of hands and manipulated objects* for CVPR19.
See [project page](https://github.com/hassony2/obman) and [demo+training code](https://github.com/hassony2/obman_train).
It [reuses](https://github.com/hassony2/manopth/blob/master/manopth/rodrigues_layer.py) [part of the great code](https://github.com/MandyMo/pytorch_HMR/blob/master/src/util.py) from the [Pytorch layer for the SMPL body model](https://github.com/MandyMo/pytorch_HMR/blob/master/README.md) by Zhang Xiong ([MandyMo](https://github.com/MandyMo)) to compute the rotation utilities !
It also includes in `mano/webuser` partial content of files from the original [MANO](http://mano.is.tue.mpg.de) code ([posemapper.py](mano/webuser/posemapper.py), [serialization.py](mano/webuser/serialization.py), [lbs.py](mano/webuser/lbs.py), [verts.py](mano/webuser/verts.py), [smpl_handpca_wrapper_HAND_only.py](mano/webuser/smpl_handpca_wrapper_HAND_only.py)).
If you find this code useful for your research, consider citing:
- the original [MANO](http://mano.is.tue.mpg.de) publication:
```
@article{MANO:SIGGRAPHASIA:2017,
title = {Embodied Hands: Modeling and Capturing Hands and Bodies Together},
author = {Romero, Javier and Tzionas, Dimitrios and Black, Michael J.},
journal = {ACM Transactions on Graphics, (Proc. SIGGRAPH Asia)},
publisher = {ACM},
month = nov,
year = {2017},
url = {http://doi.acm.org/10.1145/3130800.3130883},
month_numeric = {11}
}
```
- the publication this PyTorch port was developped for:
```
@INPROCEEDINGS{hasson19_obman,
title = {Learning joint reconstruction of hands and manipulated objects},
author = {Hasson, Yana and Varol, G{\"u}l and Tzionas, Dimitris and Kalevatykh, Igor and Black, Michael J. and Laptev, Ivan and Schmid, Cordelia},
booktitle = {CVPR},
year = {2019}
}
```
The training code associated with this paper, compatible with manopth can be found [here](https://github.com/hassony2/obman_train). The release includes a model trained on a variety of hand datasets.
# Installation
## Get code and dependencies
- `git clone https://github.com/hassony2/manopth`
- `cd manopth`
- Install the dependencies listed in [environment.yml](environment.yml)
- In an existing conda environment, `conda env update -f environment.yml`
- In a new environment, `conda env create -f environment.yml`, will create a conda environment named `manopth`
## Download MANO pickle data-structures
- Go to [MANO website](http://mano.is.tue.mpg.de/)
- Create an account by clicking *Sign Up* and provide your information
- Download Models and Code (the downloaded file should have the format `mano_v*_*.zip`). Note that all code and data from this download falls under the [MANO license](http://mano.is.tue.mpg.de/license).
- unzip and copy the `models` folder into the `manopth/mano` folder
- Your folder structure should look like this:
```
manopth/
mano/
models/
MANO_LEFT.pkl
MANO_RIGHT.pkl
...
manopth/
__init__.py
...
```
To check that everything is going well, run `python examples/manopth_mindemo.py`, which should generate from a random hand using the MANO layer !
## Install `manopth` package
To be able to import and use `ManoLayer` in another project, go to your `manopth` folder and run `pip install .`
`cd /path/to/other/project`
You can now use `from manopth import ManoLayer` in this other project!
# Usage
## Minimal usage script
See [examples/manopth_mindemo.py](examples/manopth_mindemo.py)
Simple forward pass with random pose and shape parameters through MANO layer
```python
import torch
from manopth.manolayer import ManoLayer
from manopth import demo
batch_size = 10
# Select number of principal components for pose space
ncomps = 6
# Initialize MANO layer
mano_layer = ManoLayer(mano_root='mano/models', use_pca=True, ncomps=ncomps)
# Generate random shape parameters
random_shape = torch.rand(batch_size, 10)
# Generate random pose parameters, including 3 values for global axis-angle rotation
random_pose = torch.rand(batch_size, ncomps + 3)
# Forward pass through MANO layer
hand_verts, hand_joints = mano_layer(random_pose, random_shape)
demo.display_hand({'verts': hand_verts, 'joints': hand_joints}, mano_faces=mano_layer.th_faces)
```
Result :

## Demo
With more options, forward and backward pass, and a loop for quick profiling, look at [examples/manopth_demo.py](examples/manopth_demo.py).
You can run it locally with:
`python examples/manopth_demo.py`
================================================
FILE: common/utils/manopth/environment.yml
================================================
name: manopth
dependencies:
- opencv
- python=3.7
- matplotlib
- numpy
- pytorch
- tqdm
- git
- pip:
- git+https://github.com/hassony2/chumpy.git
================================================
FILE: common/utils/manopth/examples/manopth_demo.py
================================================
import argparse
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import torch
from tqdm import tqdm
from manopth import argutils
from manopth.manolayer import ManoLayer
from manopth.demo import display_hand
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', default=1, type=int)
parser.add_argument('--cuda', action='store_true')
parser.add_argument(
'--no_display',
action='store_true',
help="Disable display output of ManoLayer given random inputs")
parser.add_argument('--side', default='left', choices=['left', 'right'])
parser.add_argument('--random_shape', action='store_true', help="Random hand shape")
parser.add_argument('--rand_mag', type=float, default=1, help="Controls pose variability")
parser.add_argument(
'--flat_hand_mean',
action='store_true',
help="Use flat hand as mean instead of average hand pose")
parser.add_argument(
'--iters',
type=int,
default=1,
help=
"Use for quick profiling of forward and backward pass accross ManoLayer"
)
parser.add_argument('--mano_root', default='mano/models')
parser.add_argument('--root_rot_mode', default='axisang', choices=['rot6d', 'axisang'])
parser.add_argument('--no_pca', action='store_true', help="Give axis-angle or rotation matrix as inputs instead of PCA coefficients")
parser.add_argument('--joint_rot_mode', default='axisang', choices=['rotmat', 'axisang'], help="Joint rotation inputs")
parser.add_argument(
'--mano_ncomps', default=6, type=int, help="Number of PCA components")
args = parser.parse_args()
argutils.print_args(args)
layer = ManoLayer(
flat_hand_mean=args.flat_hand_mean,
side=args.side,
mano_root=args.mano_root,
ncomps=args.mano_ncomps,
use_pca=not args.no_pca,
root_rot_mode=args.root_rot_mode,
joint_rot_mode=args.joint_rot_mode)
if args.root_rot_mode == 'axisang':
rot = 3
else:
rot = 6
print(rot)
if args.no_pca:
args.mano_ncomps = 45
# Generate random pose coefficients
pose_params = args.rand_mag * torch.rand(args.batch_size, args.mano_ncomps + rot)
pose_params.requires_grad = True
if args.random_shape:
shape = torch.rand(args.batch_size, 10)
else:
shape = torch.zeros(1) # Hack to act like None for PyTorch JIT
if args.cuda:
pose_params = pose_params.cuda()
shape = shape.cuda()
layer.cuda()
# Loop for forward/backward quick profiling
for idx in tqdm(range(args.iters)):
# Forward pass
verts, Jtr = layer(pose_params, th_betas=shape)
# Backward pass
loss = torch.norm(verts)
loss.backward()
if not args.no_display:
verts, Jtr = layer(pose_params, th_betas=shape)
joints = Jtr.cpu().detach()
verts = verts.cpu().detach()
# Draw obtained vertices and joints
display_hand({
'verts': verts,
'joints': joints
},
mano_faces=layer.th_faces)
================================================
FILE: common/utils/manopth/examples/manopth_mindemo.py
================================================
import torch
from manopth.manolayer import ManoLayer
from manopth import demo
batch_size = 10
# Select number of principal components for pose space
ncomps = 6
# Initialize MANO layer
mano_layer = ManoLayer(
mano_root='mano/models', use_pca=True, ncomps=ncomps, flat_hand_mean=False)
# Generate random shape parameters
random_shape = torch.rand(batch_size, 10)
# Generate random pose parameters, including 3 values for global axis-angle rotation
random_pose = torch.rand(batch_size, ncomps + 3)
# Forward pass through MANO layer
hand_verts, hand_joints = mano_layer(random_pose, random_shape)
demo.display_hand({
'verts': hand_verts,
'joints': hand_joints
},
mano_faces=mano_layer.th_faces)
================================================
FILE: common/utils/manopth/mano/__init__.py
================================================
================================================
FILE: common/utils/manopth/mano/webuser/__init__.py
================================================
================================================
FILE: common/utils/manopth/mano/webuser/lbs.py
================================================
'''
Copyright 2017 Javier Romero, Dimitrios Tzionas, Michael J Black and the Max Planck Gesellschaft. All rights reserved.
This software is provided for research purposes only.
By using this software you agree to the terms of the MANO/SMPL+H Model license here http://mano.is.tue.mpg.de/license
More information about MANO/SMPL+H is available at http://mano.is.tue.mpg.de.
For comments or questions, please email us at: mano@tue.mpg.de
About this file:
================
This file defines a wrapper for the loading functions of the MANO model.
Modules included:
- load_model:
loads the MANO model from a given file location (i.e. a .pkl file location),
or a dictionary object.
'''
from mano.webuser.posemapper import posemap
import chumpy
import numpy as np
def global_rigid_transformation(pose, J, kintree_table, xp):
results = {}
pose = pose.reshape((-1, 3))
id_to_col = {kintree_table[1, i]: i for i in range(kintree_table.shape[1])}
parent = {
i: id_to_col[kintree_table[0, i]]
for i in range(1, kintree_table.shape[1])
}
if xp == chumpy:
from mano.webuser.posemapper import Rodrigues
rodrigues = lambda x: Rodrigues(x)
else:
import cv2
rodrigues = lambda x: cv2.Rodrigues(x)[0]
with_zeros = lambda x: xp.vstack((x, xp.array([[0.0, 0.0, 0.0, 1.0]])))
results[0] = with_zeros(
xp.hstack((rodrigues(pose[0, :]), J[0, :].reshape((3, 1)))))
for i in range(1, kintree_table.shape[1]):
results[i] = results[parent[i]].dot(
with_zeros(
xp.hstack((rodrigues(pose[i, :]), ((J[i, :] - J[parent[i], :]
).reshape((3, 1)))))))
pack = lambda x: xp.hstack([np.zeros((4, 3)), x.reshape((4, 1))])
results = [results[i] for i in sorted(results.keys())]
results_global = results
if True:
results2 = [
results[i] - (pack(results[i].dot(xp.concatenate(((J[i, :]), 0)))))
for i in range(len(results))
]
results = results2
result = xp.dstack(results)
return result, results_global
def verts_core(pose, v, J, weights, kintree_table, want_Jtr=False, xp=chumpy):
A, A_global = global_rigid_transformation(pose, J, kintree_table, xp)
T = A.dot(weights.T)
rest_shape_h = xp.vstack((v.T, np.ones((1, v.shape[0]))))
v = (T[:, 0, :] * rest_shape_h[0, :].reshape(
(1, -1)) + T[:, 1, :] * rest_shape_h[1, :].reshape(
(1, -1)) + T[:, 2, :] * rest_shape_h[2, :].reshape(
(1, -1)) + T[:, 3, :] * rest_shape_h[3, :].reshape((1, -1))).T
v = v[:, :3]
if not want_Jtr:
return v
Jtr = xp.vstack([g[:3, 3] for g in A_global])
return (v, Jtr)
================================================
FILE: common/utils/manopth/mano/webuser/posemapper.py
================================================
'''
Copyright 2017 Javier Romero, Dimitrios Tzionas, Michael J Black and the Max Planck Gesellschaft. All rights reserved.
This software is provided for research purposes only.
By using this software you agree to the terms of the MANO/SMPL+H Model license here http://mano.is.tue.mpg.de/license
More information about MANO/SMPL+H is available at http://mano.is.tue.mpg.de.
For comments or questions, please email us at: mano@tue.mpg.de
About this file:
================
This file defines a wrapper for the loading functions of the MANO model.
Modules included:
- load_model:
loads the MANO model from a given file location (i.e. a .pkl file location),
or a dictionary object.
'''
import chumpy as ch
import numpy as np
import cv2
class Rodrigues(ch.Ch):
dterms = 'rt'
def compute_r(self):
return cv2.Rodrigues(self.rt.r)[0]
def compute_dr_wrt(self, wrt):
if wrt is self.rt:
return cv2.Rodrigues(self.rt.r)[1].T
def lrotmin(p):
if isinstance(p, np.ndarray):
p = p.ravel()[3:]
return np.concatenate(
[(cv2.Rodrigues(np.array(pp))[0] - np.eye(3)).ravel()
for pp in p.reshape((-1, 3))]).ravel()
if p.ndim != 2 or p.shape[1] != 3:
p = p.reshape((-1, 3))
p = p[1:]
return ch.concatenate([(Rodrigues(pp) - ch.eye(3)).ravel()
for pp in p]).ravel()
def posemap(s):
if s == 'lrotmin':
return lrotmin
else:
raise Exception('Unknown posemapping: %s' % (str(s), ))
================================================
FILE: common/utils/manopth/mano/webuser/serialization.py
================================================
'''
Copyright 2017 Javier Romero, Dimitrios Tzionas, Michael J Black and the Max Planck Gesellschaft. All rights reserved.
This software is provided for research purposes only.
By using this software you agree to the terms of the MANO/SMPL+H Model license here http://mano.is.tue.mpg.de/license
More information about MANO/SMPL+H is available at http://mano.is.tue.mpg.de.
For comments or questions, please email us at: mano@tue.mpg.de
About this file:
================
This file defines a wrapper for the loading functions of the MANO model.
Modules included:
- load_model:
loads the MANO model from a given file location (i.e. a .pkl file location),
or a dictionary object.
'''
__all__ = ['load_model', 'save_model']
import numpy as np
import pickle
import chumpy as ch
from chumpy.ch import MatVecMult
from mano.webuser.posemapper import posemap
from mano.webuser.verts import verts_core
def ready_arguments(fname_or_dict):
if not isinstance(fname_or_dict, dict):
dd = pickle.load(open(fname_or_dict, 'rb'), encoding='latin1')
else:
dd = fname_or_dict
backwards_compatibility_replacements(dd)
want_shapemodel = 'shapedirs' in dd
nposeparms = dd['kintree_table'].shape[1] * 3
if 'trans' not in dd:
dd['trans'] = np.zeros(3)
if 'pose' not in dd:
dd['pose'] = np.zeros(nposeparms)
if 'shapedirs' in dd and 'betas' not in dd:
dd['betas'] = np.zeros(dd['shapedirs'].shape[-1])
for s in [
'v_template', 'weights', 'posedirs', 'pose', 'trans', 'shapedirs',
'betas', 'J'
]:
if (s in dd) and not hasattr(dd[s], 'dterms'):
dd[s] = ch.array(dd[s])
if want_shapemodel:
dd['v_shaped'] = dd['shapedirs'].dot(dd['betas']) + dd['v_template']
v_shaped = dd['v_shaped']
J_tmpx = MatVecMult(dd['J_regressor'], v_shaped[:, 0])
J_tmpy = MatVecMult(dd['J_regressor'], v_shaped[:, 1])
J_tmpz = MatVecMult(dd['J_regressor'], v_shaped[:, 2])
dd['J'] = ch.vstack((J_tmpx, J_tmpy, J_tmpz)).T
dd['v_posed'] = v_shaped + dd['posedirs'].dot(
posemap(dd['bs_type'])(dd['pose']))
else:
dd['v_posed'] = dd['v_template'] + dd['posedirs'].dot(
posemap(dd['bs_type'])(dd['pose']))
return dd
def load_model(fname_or_dict):
dd = ready_arguments(fname_or_dict)
args = {
'pose': dd['pose'],
'v': dd['v_posed'],
'J': dd['J'],
'weights': dd['weights'],
'kintree_table': dd['kintree_table'],
'xp': ch,
'want_Jtr': True,
'bs_style': dd['bs_style']
}
result, Jtr = verts_core(**args)
result = result + dd['trans'].reshape((1, 3))
result.J_transformed = Jtr + dd['trans'].reshape((1, 3))
for k, v in dd.items():
setattr(result, k, v)
return result
================================================
FILE: common/utils/manopth/mano/webuser/smpl_handpca_wrapper_HAND_only.py
================================================
'''
Copyright 2017 Javier Romero, Dimitrios Tzionas, Michael J Black and the Max Planck Gesellschaft. All rights reserved.
This software is provided for research purposes only.
By using this software you agree to the terms of the MANO/SMPL+H Model license here http://mano.is.tue.mpg.de/license
More information about MANO/SMPL+H is available at http://mano.is.tue.mpg.de.
For comments or questions, please email us at: mano@tue.mpg.de
About this file:
================
This file defines a wrapper for the loading functions of the MANO model.
Modules included:
- load_model:
loads the MANO model from a given file location (i.e. a .pkl file location),
or a dictionary object.
'''
def ready_arguments(fname_or_dict, posekey4vposed='pose'):
import numpy as np
import pickle
import chumpy as ch
from chumpy.ch import MatVecMult
from mano.webuser.posemapper import posemap
if not isinstance(fname_or_dict, dict):
dd = pickle.load(open(fname_or_dict, 'rb'), encoding='latin1')
# dd = pickle.load(open(fname_or_dict, 'rb'))
else:
dd = fname_or_dict
want_shapemodel = 'shapedirs' in dd
nposeparms = dd['kintree_table'].shape[1] * 3
if 'trans' not in dd:
dd['trans'] = np.zeros(3)
if 'pose' not in dd:
dd['pose'] = np.zeros(nposeparms)
if 'shapedirs' in dd and 'betas' not in dd:
dd['betas'] = np.zeros(dd['shapedirs'].shape[-1])
for s in [
'v_template', 'weights', 'posedirs', 'pose', 'trans', 'shapedirs',
'betas', 'J'
]:
if (s in dd) and not hasattr(dd[s], 'dterms'):
dd[s] = ch.array(dd[s])
assert (posekey4vposed in dd)
if want_shapemodel:
dd['v_shaped'] = dd['shapedirs'].dot(dd['betas']) + dd['v_template']
v_shaped = dd['v_shaped']
J_tmpx = MatVecMult(dd['J_regressor'], v_shaped[:, 0])
J_tmpy = MatVecMult(dd['J_regressor'], v_shaped[:, 1])
J_tmpz = MatVecMult(dd['J_regressor'], v_shaped[:, 2])
dd['J'] = ch.vstack((J_tmpx, J_tmpy, J_tmpz)).T
pose_map_res = posemap(dd['bs_type'])(dd[posekey4vposed])
dd['v_posed'] = v_shaped + dd['posedirs'].dot(pose_map_res)
else:
pose_map_res = posemap(dd['bs_type'])(dd[posekey4vposed])
dd_add = dd['posedirs'].dot(pose_map_res)
dd['v_posed'] = dd['v_template'] + dd_add
return dd
def load_model(fname_or_dict, ncomps=6, flat_hand_mean=False, v_template=None):
''' This model loads the fully articulable HAND SMPL model,
and replaces the pose DOFS by ncomps from PCA'''
from mano.webuser.verts import verts_core
import numpy as np
import chumpy as ch
import pickle
import scipy.sparse as sp
np.random.seed(1)
if not isinstance(fname_or_dict, dict):
smpl_data = pickle.load(open(fname_or_dict, 'rb'), encoding='latin1')
# smpl_data = pickle.load(open(fname_or_dict, 'rb'))
else:
smpl_data = fname_or_dict
rot = 3 # for global orientation!!!
hands_components = smpl_data['hands_components']
hands_mean = np.zeros(hands_components.shape[
1]) if flat_hand_mean else smpl_data['hands_mean']
hands_coeffs = smpl_data['hands_coeffs'][:, :ncomps]
selected_components = np.vstack((hands_components[:ncomps]))
hands_mean = hands_mean.copy()
pose_coeffs = ch.zeros(rot + selected_components.shape[0])
full_hand_pose = pose_coeffs[rot:(rot + ncomps)].dot(selected_components)
smpl_data['fullpose'] = ch.concatenate((pose_coeffs[:rot],
hands_mean + full_hand_pose))
smpl_data['pose'] = pose_coeffs
Jreg = smpl_data['J_regressor']
if not sp.issparse(Jreg):
smpl_data['J_regressor'] = (sp.csc_matrix(
(Jreg.data, (Jreg.row, Jreg.col)), shape=Jreg.shape))
# slightly modify ready_arguments to make sure that it uses the fullpose
# (which will NOT be pose) for the computation of posedirs
dd = ready_arguments(smpl_data, posekey4vposed='fullpose')
# create the smpl formula with the fullpose,
# but expose the PCA coefficients as smpl.pose for compatibility
args = {
'pose': dd['fullpose'],
'v': dd['v_posed'],
'J': dd['J'],
'weights': dd['weights'],
'kintree_table': dd['kintree_table'],
'xp': ch,
'want_Jtr': True,
'bs_style': dd['bs_style'],
}
result_previous, meta = verts_core(**args)
result = result_previous + dd['trans'].reshape((1, 3))
result.no_translation = result_previous
if meta is not None:
for field in ['Jtr', 'A', 'A_global', 'A_weighted']:
if (hasattr(meta, field)):
setattr(result, field, getattr(meta, field))
setattr(result, 'Jtr', meta)
if hasattr(result, 'Jtr'):
result.J_transformed = result.Jtr + dd['trans'].reshape((1, 3))
for k, v in dd.items():
setattr(result, k, v)
if v_template is not None:
result.v_template[:] = v_template
return result
if __name__ == '__main__':
load_model()
================================================
FILE: common/utils/manopth/mano/webuser/verts.py
================================================
'''
Copyright 2017 Javier Romero, Dimitrios Tzionas, Michael J Black and the Max Planck Gesellschaft. All rights reserved.
This software is provided for research purposes only.
By using this software you agree to the terms of the MANO/SMPL+H Model license here http://mano.is.tue.mpg.de/license
More information about MANO/SMPL+H is available at http://mano.is.tue.mpg.de.
For comments or questions, please email us at: mano@tue.mpg.de
About this file:
================
This file defines a wrapper for the loading functions of the MANO model.
Modules included:
- load_model:
loads the MANO model from a given file location (i.e. a .pkl file location),
or a dictionary object.
'''
import chumpy
import mano.webuser.lbs as lbs
from mano.webuser.posemapper import posemap
import scipy.sparse as sp
from chumpy.ch import MatVecMult
def ischumpy(x):
return hasattr(x, 'dterms')
def verts_decorated(trans,
pose,
v_template,
J_regressor,
weights,
kintree_table,
bs_style,
f,
bs_type=None,
posedirs=None,
betas=None,
shapedirs=None,
want_Jtr=False):
for which in [
trans, pose, v_template, weights, posedirs, betas, shapedirs
]:
if which is not None:
assert ischumpy(which)
v = v_template
if shapedirs is not None:
if betas is None:
betas = chumpy.zeros(shapedirs.shape[-1])
v_shaped = v + shapedirs.dot(betas)
else:
v_shaped = v
if posedirs is not None:
v_posed = v_shaped + posedirs.dot(posemap(bs_type)(pose))
else:
v_posed = v_shaped
v = v_posed
if sp.issparse(J_regressor):
J_tmpx = MatVecMult(J_regressor, v_shaped[:, 0])
J_tmpy = MatVecMult(J_regressor, v_shaped[:, 1])
J_tmpz = MatVecMult(J_regressor, v_shaped[:, 2])
J = chumpy.vstack((J_tmpx, J_tmpy, J_tmpz)).T
else:
assert (ischumpy(J))
assert (bs_style == 'lbs')
result, Jtr = lbs.verts_core(
pose, v, J, weights, kintree_table, want_Jtr=True, xp=chumpy)
tr = trans.reshape((1, 3))
result = result + tr
Jtr = Jtr + tr
result.trans = trans
result.f = f
result.pose = pose
result.v_template = v_template
result.J = J
result.J_regressor = J_regressor
result.weights = weights
result.kintree_table = kintree_table
result.bs_style = bs_style
result.bs_type = bs_type
if posedirs is not None:
result.posedirs = posedirs
result.v_posed = v_posed
if shapedirs is not None:
result.shapedirs = shapedirs
result.betas = betas
result.v_shaped = v_shaped
if want_Jtr:
result.J_transformed = Jtr
return result
def verts_core(pose,
v,
J,
weights,
kintree_table,
bs_style,
want_Jtr=False,
xp=chumpy):
if xp == chumpy:
assert (hasattr(pose, 'dterms'))
assert (hasattr(v, 'dterms'))
assert (hasattr(J, 'dterms'))
assert (hasattr(weights, 'dterms'))
assert (bs_style == 'lbs')
result = lbs.verts_core(pose, v, J, weights, kintree_table, want_Jtr, xp)
return result
================================================
FILE: common/utils/manopth/manopth/__init__.py
================================================
name = 'manopth'
================================================
FILE: common/utils/manopth/manopth/argutils.py
================================================
import datetime
import os
import pickle
import subprocess
import sys
def print_args(args):
opts = vars(args)
print('======= Options ========')
for k, v in sorted(opts.items()):
print('{}: {}'.format(k, v))
print('========================')
def save_args(args, save_folder, opt_prefix='opt', verbose=True):
opts = vars(args)
# Create checkpoint folder
if not os.path.exists(save_folder):
os.makedirs(save_folder, exist_ok=True)
# Save options
opt_filename = '{}.txt'.format(opt_prefix)
opt_path = os.path.join(save_folder, opt_filename)
with open(opt_path, 'a') as opt_file:
opt_file.write('====== Options ======\n')
for k, v in sorted(opts.items()):
opt_file.write(
'{option}: {value}\n'.format(option=str(k), value=str(v)))
opt_file.write('=====================\n')
opt_file.write('launched {} at {}\n'.format(
str(sys.argv[0]), str(datetime.datetime.now())))
# Add git info
label = subprocess.check_output(["git", "describe",
"--always"]).strip()
if subprocess.call(
["git", "branch"],
stderr=subprocess.STDOUT,
stdout=open(os.devnull, 'w')) == 0:
opt_file.write('=== Git info ====\n')
opt_file.write('{}\n'.format(label))
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'])
opt_file.write('commit : {}\n'.format(commit.strip()))
opt_picklename = '{}.pkl'.format(opt_prefix)
opt_picklepath = os.path.join(save_folder, opt_picklename)
with open(opt_picklepath, 'wb') as opt_file:
pickle.dump(opts, opt_file)
if verbose:
print('Saved options to {}'.format(opt_path))
================================================
FILE: common/utils/manopth/manopth/demo.py
================================================
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import numpy as np
import torch
from manopth.manolayer import ManoLayer
def generate_random_hand(batch_size=1, ncomps=6, mano_root='mano/models'):
nfull_comps = ncomps + 3 # Add global orientation dims to PCA
random_pcapose = torch.rand(batch_size, nfull_comps)
mano_layer = ManoLayer(mano_root=mano_root)
verts, joints = mano_layer(random_pcapose)
return {'verts': verts, 'joints': joints, 'faces': mano_layer.th_faces}
def display_hand(hand_info, mano_faces=None, ax=None, alpha=0.2, batch_idx=0, show=True):
"""
Displays hand batch_idx in batch of hand_info, hand_info as returned by
generate_random_hand
"""
if ax is None:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
verts, joints = hand_info['verts'][batch_idx], hand_info['joints'][
batch_idx]
if mano_faces is None:
ax.scatter(verts[:, 0], verts[:, 1], verts[:, 2], alpha=0.1)
else:
mesh = Poly3DCollection(verts[mano_faces], alpha=alpha)
face_color = (141 / 255, 184 / 255, 226 / 255)
edge_color = (50 / 255, 50 / 255, 50 / 255)
mesh.set_edgecolor(edge_color)
mesh.set_facecolor(face_color)
ax.add_collection3d(mesh)
ax.scatter(joints[:, 0], joints[:, 1], joints[:, 2], color='r')
cam_equal_aspect_3d(ax, verts.numpy())
if show:
plt.show()
def cam_equal_aspect_3d(ax, verts, flip_x=False):
"""
Centers view on cuboid containing hand and flips y and z axis
and fixes azimuth
"""
extents = np.stack([verts.min(0), verts.max(0)], axis=1)
sz = extents[:, 1] - extents[:, 0]
centers = np.mean(extents, axis=1)
maxsize = max(abs(sz))
r = maxsize / 2
if flip_x:
ax.set_xlim(centers[0] + r, centers[0] - r)
else:
ax.set_xlim(centers[0] - r, centers[0] + r)
# Invert y and z axis
ax.set_ylim(centers[1] + r, centers[1] - r)
ax.set_zlim(centers[2] + r, centers[2] - r)
================================================
FILE: common/utils/manopth/manopth/manolayer.py
================================================
import os
import numpy as np
import torch
from torch.nn import Module
from mano.webuser.smpl_handpca_wrapper_HAND_only import ready_arguments
from manopth import rodrigues_layer, rotproj, rot6d
from manopth.tensutils import (th_posemap_axisang, th_with_zeros, th_pack,
subtract_flat_id, make_list)
class ManoLayer(Module):
__constants__ = [
'use_pca', 'rot', 'ncomps', 'ncomps', 'kintree_parents', 'check',
'side', 'center_idx', 'joint_rot_mode'
]
def __init__(self,
center_idx=None,
flat_hand_mean=True,
ncomps=6,
side='right',
mano_root='mano/models',
use_pca=True,
root_rot_mode='axisang',
joint_rot_mode='axisang',
robust_rot=False):
"""
Args:
center_idx: index of center joint in our computations,
if -1 centers on estimate of palm as middle of base
of middle finger and wrist
flat_hand_mean: if True, (0, 0, 0, ...) pose coefficients match
flat hand, else match average hand pose
mano_root: path to MANO pkl files for left and right hand
ncomps: number of PCA components form pose space (<45)
side: 'right' or 'left'
use_pca: Use PCA decomposition for pose space.
joint_rot_mode: 'axisang' or 'rotmat', ignored if use_pca
"""
super().__init__()
self.center_idx = center_idx
self.robust_rot = robust_rot
if root_rot_mode == 'axisang':
self.rot = 3
else:
self.rot = 6
self.flat_hand_mean = flat_hand_mean
self.side = side
self.use_pca = use_pca
self.joint_rot_mode = joint_rot_mode
self.root_rot_mode = root_rot_mode
if use_pca:
self.ncomps = ncomps
else:
self.ncomps = 45
if side == 'right':
self.mano_path = os.path.join(mano_root, 'MANO_RIGHT.pkl')
elif side == 'left':
self.mano_path = os.path.join(mano_root, 'MANO_LEFT.pkl')
smpl_data = ready_arguments(self.mano_path)
hands_components = smpl_data['hands_components']
self.smpl_data = smpl_data
self.register_buffer('th_betas',
torch.Tensor(smpl_data['betas'].r).unsqueeze(0))
self.register_buffer('th_shapedirs',
torch.Tensor(smpl_data['shapedirs'].r))
self.register_buffer('th_posedirs',
torch.Tensor(smpl_data['posedirs'].r))
self.register_buffer(
'th_v_template',
torch.Tensor(smpl_data['v_template'].r).unsqueeze(0))
self.register_buffer(
'th_J_regressor',
torch.Tensor(np.array(smpl_data['J_regressor'].toarray())))
self.register_buffer('th_weights',
torch.Tensor(smpl_data['weights'].r))
self.register_buffer('th_faces',
torch.Tensor(smpl_data['f'].astype(np.int32)).long())
# Get hand mean
hands_mean = np.zeros(hands_components.shape[1]
) if flat_hand_mean else smpl_data['hands_mean']
hands_mean = hands_mean.copy()
th_hands_mean = torch.Tensor(hands_mean).unsqueeze(0)
if self.use_pca or self.joint_rot_mode == 'axisang':
# Save as axis-angle
self.register_buffer('th_hands_mean', th_hands_mean)
selected_components = hands_components[:ncomps]
self.register_buffer('th_selected_comps',
torch.Tensor(selected_components))
else:
th_hands_mean_rotmat = rodrigues_layer.batch_rodrigues(
th_hands_mean.view(15, 3)).reshape(15, 3, 3)
self.register_buffer('th_hands_mean_rotmat', th_hands_mean_rotmat)
# Kinematic chain params
self.kintree_table = smpl_data['kintree_table']
parents = list(self.kintree_table[0].tolist())
self.kintree_parents = parents
def forward(self,
th_pose_coeffs,
th_betas=torch.zeros(1),
th_trans=torch.zeros(1),
root_palm=torch.Tensor([0]),
share_betas=torch.Tensor([0]),
):
"""
Args:
th_trans (Tensor (batch_size x ncomps)): if provided, applies trans to joints and vertices
th_betas (Tensor (batch_size x 10)): if provided, uses given shape parameters for hand shape
else centers on root joint (9th joint)
root_palm: return palm as hand root instead of wrist
"""
# if len(th_pose_coeffs) == 0:
# return th_pose_coeffs.new_empty(0), th_pose_coeffs.new_empty(0)
batch_size = th_pose_coeffs.shape[0]
# Get axis angle from PCA components and coefficients
if self.use_pca or self.joint_rot_mode == 'axisang':
# Remove global rot coeffs
th_hand_pose_coeffs = th_pose_coeffs[:, self.rot:self.rot +
self.ncomps]
if self.use_pca:
# PCA components --> axis angles
th_full_hand_pose = th_hand_pose_coeffs.mm(self.th_selected_comps)
else:
th_full_hand_pose = th_hand_pose_coeffs
# Concatenate back global rot
th_full_pose = torch.cat([
th_pose_coeffs[:, :self.rot],
self.th_hands_mean + th_full_hand_pose
], 1)
if self.root_rot_mode == 'axisang':
# compute rotation matrixes from axis-angle while skipping global rotation
th_pose_map, th_rot_map = th_posemap_axisang(th_full_pose)
root_rot = th_rot_map[:, :9].view(batch_size, 3, 3)
th_rot_map = th_rot_map[:, 9:]
th_pose_map = th_pose_map[:, 9:]
else:
# th_posemap offsets by 3, so add offset or 3 to get to self.rot=6
th_pose_map, th_rot_map = th_posemap_axisang(th_full_pose[:, 6:])
if self.robust_rot:
root_rot = rot6d.robust_compute_rotation_matrix_from_ortho6d(th_full_pose[:, :6])
else:
root_rot = rot6d.compute_rotation_matrix_from_ortho6d(th_full_pose[:, :6])
else:
assert th_pose_coeffs.dim() == 4, (
'When not self.use_pca, '
'th_pose_coeffs should have 4 dims, got {}'.format(
th_pose_coeffs.dim()))
assert th_pose_coeffs.shape[2:4] == (3, 3), (
'When not self.use_pca, th_pose_coeffs have 3x3 matrix for two'
'last dims, got {}'.format(th_pose_coeffs.shape[2:4]))
th_pose_rots = rotproj.batch_rotprojs(th_pose_coeffs)
th_rot_map = th_pose_rots[:, 1:].view(batch_size, -1)
th_pose_map = subtract_flat_id(th_rot_map)
root_rot = th_pose_rots[:, 0]
# Full axis angle representation with root joint
if th_betas is None or th_betas.numel() == 1:
th_v_shaped = torch.matmul(self.th_shapedirs,
self.th_betas.transpose(1, 0)).permute(
2, 0, 1) + self.th_v_template
th_j = torch.matmul(self.th_J_regressor, th_v_shaped).repeat(
batch_size, 1, 1)
else:
if share_betas:
th_betas = th_betas.mean(0, keepdim=True).expand(th_betas.shape[0], 10)
th_v_shaped = torch.matmul(self.th_shapedirs,
th_betas.transpose(1, 0)).permute(
2, 0, 1) + self.th_v_template
th_j = torch.matmul(self.th_J_regressor, th_v_shaped)
# th_pose_map should have shape 20x135
th_v_posed = th_v_shaped + torch.matmul(
self.th_posedirs, th_pose_map.transpose(0, 1)).permute(2, 0, 1)
# Final T pose with transformation done !
# Global rigid transformation
root_j = th_j[:, 0, :].contiguous().view(batch_size, 3, 1)
root_trans = th_with_zeros(torch.cat([root_rot, root_j], 2))
all_rots = th_rot_map.view(th_rot_map.shape[0], 15, 3, 3)
lev1_idxs = [1, 4, 7, 10, 13]
lev2_idxs = [2, 5, 8, 11, 14]
lev3_idxs = [3, 6, 9, 12, 15]
lev1_rots = all_rots[:, [idx - 1 for idx in lev1_idxs]]
lev2_rots = all_rots[:, [idx - 1 for idx in lev2_idxs]]
lev3_rots = all_rots[:, [idx - 1 for idx in lev3_idxs]]
lev1_j = th_j[:, lev1_idxs]
lev2_j = th_j[:, lev2_idxs]
lev3_j = th_j[:, lev3_idxs]
# From base to tips
# Get lev1 results
all_transforms = [root_trans.unsqueeze(1)]
lev1_j_rel = lev1_j - root_j.transpose(1, 2)
lev1_rel_transform_flt = th_with_zeros(torch.cat([lev1_rots, lev1_j_rel.unsqueeze(3)], 3).view(-1, 3, 4))
root_trans_flt = root_trans.unsqueeze(1).repeat(1, 5, 1, 1).view(root_trans.shape[0] * 5, 4, 4)
lev1_flt = torch.matmul(root_trans_flt, lev1_rel_transform_flt)
all_transforms.append(lev1_flt.view(all_rots.shape[0], 5, 4, 4))
# Get lev2 results
lev2_j_rel = lev2_j - lev1_j
lev2_rel_transform_flt = th_with_zeros(torch.cat([lev2_rots, lev2_j_rel.unsqueeze(3)], 3).view(-1, 3, 4))
lev2_flt = torch.matmul(lev1_flt, lev2_rel_transform_flt)
all_transforms.append(lev2_flt.view(all_rots.shape[0], 5, 4, 4))
# Get lev3 results
lev3_j_rel = lev3_j - lev2_j
lev3_rel_transform_flt = th_with_zeros(torch.cat([lev3_rots, lev3_j_rel.unsqueeze(3)], 3).view(-1, 3, 4))
lev3_flt = torch.matmul(lev2_flt, lev3_rel_transform_flt)
all_transforms.append(lev3_flt.view(all_rots.shape[0], 5, 4, 4))
reorder_idxs = [0, 1, 6, 11, 2, 7, 12, 3, 8, 13, 4, 9, 14, 5, 10, 15]
th_results = torch.cat(all_transforms, 1)[:, reorder_idxs]
th_results_global = th_results
joint_js = torch.cat([th_j, th_j.new_zeros(th_j.shape[0], 16, 1)], 2)
tmp2 = torch.matmul(th_results, joint_js.unsqueeze(3))
th_results2 = (th_results - torch.cat([tmp2.new_zeros(*tmp2.shape[:2], 4, 3), tmp2], 3)).permute(0, 2, 3, 1)
th_T = torch.matmul(th_results2, self.th_weights.transpose(0, 1))
th_rest_shape_h = torch.cat([
th_v_posed.transpose(2, 1),
torch.ones((batch_size, 1, th_v_posed.shape[1]),
dtype=th_T.dtype,
device=th_T.device),
], 1)
th_verts = (th_T * th_rest_shape_h.unsqueeze(1)).sum(2).transpose(2, 1)
th_verts = th_verts[:, :, :3]
th_jtr = th_results_global[:, :, :3, 3]
# In addition to MANO reference joints we sample vertices on each finger
# to serve as finger tips
if self.side == 'right':
tips = th_verts[:, [745, 317, 444, 556, 673]]
else:
tips = th_verts[:, [745, 317, 445, 556, 673]]
if bool(root_palm):
palm = (th_verts[:, 95] + th_verts[:, 22]).unsqueeze(1) / 2
th_jtr = torch.cat([palm, th_jtr[:, 1:]], 1)
th_jtr = torch.cat([th_jtr, tips], 1)
# Reorder joints to match visualization utilities
th_jtr = th_jtr[:, [0, 13, 14, 15, 16, 1, 2, 3, 17, 4, 5, 6, 18, 10, 11, 12, 19, 7, 8, 9, 20]]
if th_trans is None or bool(torch.norm(th_trans) == 0):
if self.center_idx is not None:
center_joint = th_jtr[:, self.center_idx].unsqueeze(1)
th_jtr = th_jtr - center_joint
th_verts = th_verts - center_joint
else:
th_jtr = th_jtr + th_trans.unsqueeze(1)
th_verts = th_verts + th_trans.unsqueeze(1)
# Scale to milimeters
th_verts = th_verts * 1000
th_jtr = th_jtr * 1000
return th_verts, th_jtr, th_results_global
================================================
FILE: common/utils/manopth/manopth/rodrigues_layer.py
================================================
"""
This part reuses code from https://github.com/MandyMo/pytorch_HMR/blob/master/src/util.py
which is part of a PyTorch port of SMPL.
Thanks to Zhang Xiong (MandyMo) for making this great code available on github !
"""
import argparse
from torch.autograd import gradcheck
import torch
from torch.autograd import Variable
from manopth import argutils
def quat2mat(quat):
"""Convert quaternion coefficients to rotation matrix.
Args:
quat: size = [batch_size, 4] 4 <===>(w, x, y, z)
Returns:
Rotation matrix corresponding to the quaternion -- size = [batch_size, 3, 3]
"""
norm_quat = quat
norm_quat = norm_quat / norm_quat.norm(p=2, dim=1, keepdim=True)
w, x, y, z = norm_quat[:, 0], norm_quat[:, 1], norm_quat[:,
2], norm_quat[:,
3]
batch_size = quat.size(0)
w2, x2, y2, z2 = w.pow(2), x.pow(2), y.pow(2), z.pow(2)
wx, wy, wz = w * x, w * y, w * z
xy, xz, yz = x * y, x * z, y * z
rotMat = torch.stack([
w2 + x2 - y2 - z2, 2 * xy - 2 * wz, 2 * wy + 2 * xz, 2 * wz + 2 * xy,
w2 - x2 + y2 - z2, 2 * yz - 2 * wx, 2 * xz - 2 * wy, 2 * wx + 2 * yz,
w2 - x2 - y2 + z2
],
dim=1).view(batch_size, 3, 3)
return rotMat
def batch_rodrigues(axisang):
#axisang N x 3
axisang_norm = torch.norm(axisang + 1e-8, p=2, dim=1)
angle = torch.unsqueeze(axisang_norm, -1)
axisang_normalized = torch.div(axisang, angle)
angle = angle * 0.5
v_cos = torch.cos(angle)
v_sin = torch.sin(angle)
quat = torch.cat([v_cos, v_sin * axisang_normalized], dim=1)
rot_mat = quat2mat(quat)
rot_mat = rot_mat.view(rot_mat.shape[0], 9)
return rot_mat
def th_get_axis_angle(vector):
angle = torch.norm(vector, 2, 1)
axes = vector / angle.unsqueeze(1)
return axes, angle
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', default=1, type=int)
parser.add_argument('--cuda', action='store_true')
args = parser.parse_args()
argutils.print_args(args)
n_components = 6
rot = 3
inputs = torch.rand(args.batch_size, rot)
inputs_var = Variable(inputs.double(), requires_grad=True)
if args.cuda:
inputs = inputs.cuda()
# outputs = batch_rodrigues(inputs)
test_function = gradcheck(batch_rodrigues, (inputs_var, ))
print('batch test passed !')
inputs = torch.rand(rot)
inputs_var = Variable(inputs.double(), requires_grad=True)
test_function = gradcheck(th_cv2_rod_sub_id.apply, (inputs_var, ))
print('th_cv2_rod test passed')
inputs = torch.rand(rot)
inputs_var = Variable(inputs.double(), requires_grad=True)
test_th = gradcheck(th_cv2_rod.apply, (inputs_var, ))
print('th_cv2_rod_id test passed !')
================================================
FILE: common/utils/manopth/manopth/rot6d.py
================================================
import torch
def compute_rotation_matrix_from_ortho6d(poses):
"""
Code from
https://github.com/papagina/RotationContinuity
On the Continuity of Rotation Representations in Neural Networks
Zhou et al. CVPR19
https://zhouyisjtu.github.io/project_rotation/rotation.html
"""
x_raw = poses[:, 0:3] # batch*3
y_raw = poses[:, 3:6] # batch*3
x = normalize_vector(x_raw) # batch*3
z = cross_product(x, y_raw) # batch*3
z = normalize_vector(z) # batch*3
y = cross_product(z, x) # batch*3
x = x.view(-1, 3, 1)
y = y.view(-1, 3, 1)
z = z.view(-1, 3, 1)
matrix = torch.cat((x, y, z), 2) # batch*3*3
return matrix
def robust_compute_rotation_matrix_from_ortho6d(poses):
"""
Instead of making 2nd vector orthogonal to first
create a base that takes into account the two predicted
directions equally
"""
x_raw = poses[:, 0:3] # batch*3
y_raw = poses[:, 3:6] # batch*3
x = normalize_vector(x_raw) # batch*3
y = normalize_vector(y_raw) # batch*3
middle = normalize_vector(x + y)
orthmid = normalize_vector(x - y)
x = normalize_vector(middle + orthmid)
y = normalize_vector(middle - orthmid)
# Their scalar product should be small !
# assert torch.einsum("ij,ij->i", [x, y]).abs().max() < 0.00001
z = normalize_vector(cross_product(x, y))
x = x.view(-1, 3, 1)
y = y.view(-1, 3, 1)
z = z.view(-1, 3, 1)
matrix = torch.cat((x, y, z), 2) # batch*3*3
# Check for reflection in matrix ! If found, flip last vector TODO
assert (torch.stack([torch.det(mat) for mat in matrix ])< 0).sum() == 0
return matrix
def normalize_vector(v):
batch = v.shape[0]
v_mag = torch.sqrt(v.pow(2).sum(1)) # batch
v_mag = torch.max(v_mag, v.new([1e-8]))
v_mag = v_mag.view(batch, 1).expand(batch, v.shape[1])
v = v/v_mag
return v
def cross_product(u, v):
batch = u.shape[0]
i = u[:, 1] * v[:, 2] - u[:, 2] * v[:, 1]
j = u[:, 2] * v[:, 0] - u[:, 0] * v[:, 2]
k = u[:, 0] * v[:, 1] - u[:, 1] * v[:, 0]
out = torch.cat((i.view(batch, 1), j.view(batch, 1), k.view(batch, 1)), 1)
return out
================================================
FILE: common/utils/manopth/manopth/rotproj.py
================================================
import torch
def batch_rotprojs(batches_rotmats):
proj_rotmats = []
for batch_idx, batch_rotmats in enumerate(batches_rotmats):
proj_batch_rotmats = []
for rot_idx, rotmat in enumerate(batch_rotmats):
# GPU implementation of svd is VERY slow
# ~ 2 10^-3 per hit vs 5 10^-5 on cpu
U, S, V = rotmat.cpu().svd()
rotmat = torch.matmul(U, V.transpose(0, 1))
orth_det = rotmat.det()
# Remove reflection
if orth_det < 0:
rotmat[:, 2] = -1 * rotmat[:, 2]
rotmat = rotmat.cuda()
proj_batch_rotmats.append(rotmat)
proj_rotmats.append(torch.stack(proj_batch_rotmats))
return torch.stack(proj_rotmats)
================================================
FILE: common/utils/manopth/manopth/tensutils.py
================================================
import torch
from manopth import rodrigues_layer
def th_posemap_axisang(pose_vectors):
rot_nb = int(pose_vectors.shape[1] / 3)
pose_vec_reshaped = pose_vectors.contiguous().view(-1, 3)
rot_mats = rodrigues_layer.batch_rodrigues(pose_vec_reshaped)
rot_mats = rot_mats.view(pose_vectors.shape[0], rot_nb * 9)
pose_maps = subtract_flat_id(rot_mats)
return pose_maps, rot_mats
def th_with_zeros(tensor):
batch_size = tensor.shape[0]
padding = tensor.new([0.0, 0.0, 0.0, 1.0])
padding.requires_grad = False
concat_list = [tensor, padding.view(1, 1, 4).repeat(batch_size, 1, 1)]
cat_res = torch.cat(concat_list, 1)
return cat_res
def th_pack(tensor):
batch_size = tensor.shape[0]
padding = tensor.new_zeros((batch_size, 4, 3))
padding.requires_grad = False
pack_list = [padding, tensor]
pack_res = torch.cat(pack_list, 2)
return pack_res
def subtract_flat_id(rot_mats):
# Subtracts identity as a flattened tensor
rot_nb = int(rot_mats.shape[1] / 9)
id_flat = torch.eye(
3, dtype=rot_mats.dtype, device=rot_mats.device).view(1, 9).repeat(
rot_mats.shape[0], rot_nb)
# id_flat.requires_grad = False
results = rot_mats - id_flat
return results
def make_list(tensor):
# type: (List[int]) -> List[int]
return tensor
================================================
FILE: common/utils/manopth/setup.py
================================================
from setuptools import find_packages, setup
import warnings
DEPENDENCY_PACKAGE_NAMES = ["matplotlib", "torch", "tqdm", "numpy", "cv2",
"chumpy"]
def check_dependencies():
missing_dependencies = []
for package_name in DEPENDENCY_PACKAGE_NAMES:
try:
__import__(package_name)
except ImportError:
missing_dependencies.append(package_name)
if missing_dependencies:
warnings.warn(
'Missing dependencies: {}. We recommend you follow '
'the installation instructions at '
'https://github.com/hassony2/manopth#installation'.format(
missing_dependencies))
with open("README.md", "r") as fh:
long_description = fh.read()
check_dependencies()
setup(
name="manopth",
version="0.0.1",
author="Yana Hasson",
author_email="yana.hasson.inria@gmail.com",
packages=find_packages(exclude=('tests',)),
python_requires=">=3.5.0",
description="PyTorch mano layer",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/hassony2/manopth",
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: GNU GENERAL PUBLIC LICENSE",
"Operating System :: OS Independent",
],
)
================================================
FILE: common/utils/manopth/test/test_demo.py
================================================
import torch
from manopth.demo import generate_random_hand
def test_generate_random_hand():
batch_size = 3
hand_info = generate_random_hand(batch_size=batch_size, ncomps=6)
verts = hand_info['verts']
joints = hand_info['joints']
assert verts.shape == (batch_size, 778, 3)
assert joints.shape == (batch_size, 21, 3)
================================================
FILE: common/utils/optimizers/__init__.py
================================================
# -*- coding: utf-8 -*-
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# You can only use this computer program if you have closed
# a license agreement with MPG or you get the right to use the computer
# program from someone who is authorized to grant you that right.
# Any use of the computer program without a valid license is prohibited and
# liable to prosecution.
#
# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
# for Intelligent Systems and the Max Planck Institute for Biological
# Cybernetics. All rights reserved.
#
# Contact: ps-license@tuebingen.mpg.de
================================================
FILE: common/utils/optimizers/lbfgs_ls.py
================================================
# PyTorch implementation of L-BFGS with Strong Wolfe line search
# Will be removed once https://github.com/pytorch/pytorch/pull/8824
# is merged
import torch
from functools import reduce
from torch.optim import Optimizer
def _cubic_interpolate(x1, f1, g1, x2, f2, g2, bounds=None):
# ported from https://github.com/torch/optim/blob/master/polyinterp.lua
# Compute bounds of interpolation area
if bounds is not None:
xmin_bound, xmax_bound = bounds
else:
xmin_bound, xmax_bound = (x1, x2) if x1 <= x2 else (x2, x1)
# Code for most common case: cubic interpolation of 2 points
# w/ function and derivative values for both
# Solution in this case (where x2 is the farthest point):
# d1 = g1 + g2 - 3*(f1-f2)/(x1-x2);
# d2 = sqrt(d1^2 - g1*g2);
# min_pos = x2 - (x2 - x1)*((g2 + d2 - d1)/(g2 - g1 + 2*d2));
# t_new = min(max(min_pos,xmin_bound),xmax_bound);
d1 = g1 + g2 - 3 * (f1 - f2) / (x1 - x2)
d2_square = d1 ** 2 - g1 * g2
if d2_square >= 0:
d2 = d2_square.sqrt()
if x1 <= x2:
min_pos = x2 - (x2 - x1) * ((g2 + d2 - d1) / (g2 - g1 + 2 * d2))
else:
min_pos = x1 - (x1 - x2) * ((g1 + d2 - d1) / (g1 - g2 + 2 * d2))
return min(max(min_pos, xmin_bound), xmax_bound)
else:
return (xmin_bound + xmax_bound) / 2.
def _strong_Wolfe(obj_func, x, t, d, f, g, gtd, c1=1e-4, c2=0.9, tolerance_change=1e-9,
max_iter=20,
max_ls=25):
# ported from https://github.com/torch/optim/blob/master/lswolfe.lua
d_norm = d.abs().max()
g = g.clone()
# evaluate objective and gradient using initial step
f_new, g_new = obj_func(x, t, d)
ls_func_evals = 1
gtd_new = g_new.dot(d)
# bracket an interval containing a point satisfying the Wolfe criteria
t_prev, f_prev, g_prev, gtd_prev = 0, f, g, gtd
done = False
ls_iter = 0
while ls_iter < max_ls:
# check conditions
if f_new > (f + c1 * t * gtd) or (ls_iter > 1 and f_new >= f_prev):
bracket = [t_prev, t]
bracket_f = [f_prev, f_new]
bracket_g = [g_prev, g_new.clone()]
bracket_gtd = [gtd_prev, gtd_new]
break
if abs(gtd_new) <= -c2 * gtd:
bracket = [t]
bracket_f = [f_new]
bracket_g = [g_new]
bracket_gtd = [gtd_new]
done = True
break
if gtd_new >= 0:
bracket = [t_prev, t]
bracket_f = [f_prev, f_new]
bracket_g = [g_prev, g_new.clone()]
bracket_gtd = [gtd_prev, gtd_new]
break
# interpolate
min_step = t + 0.01 * (t - t_prev)
max_step = t * 10
tmp = t
t = _cubic_interpolate(t_prev, f_prev, gtd_prev, t, f_new, gtd_new,
bounds=(min_step, max_step))
# next step
t_prev = tmp
f_prev = f_new
g_prev = g_new.clone()
gtd_prev = gtd_new
f_new, g_new = obj_func(x, t, d)
ls_func_evals += 1
gtd_new = g_new.dot(d)
ls_iter += 1
# reached max number of iterations?
if ls_iter == max_ls:
bracket = [0, t]
bracket_f = [f, f_new]
bracket_g = [g, g_new]
bracket_gtd = [gtd, gtd_new]
# zoom phase: we now have a point satisfying the criteria, or
# a bracket around it. We refine the bracket until we find the
# exact point satisfying the criteria
insuf_progress = False
# find high and low points in bracket
low_pos, high_pos = (0, 1) if bracket_f[0] <= bracket_f[-1] else (1, 0)
while not done and ls_iter < max_iter:
# compute new trial value
t = _cubic_interpolate(bracket[0], bracket_f[0], bracket_gtd[0],
bracket[1], bracket_f[1], bracket_gtd[1])
# test what we are making sufficient progress
eps = 0.1 * (max(bracket) - min(bracket))
if min(max(bracket) - t, t - min(bracket)) < eps:
# interpolation close to boundary
if insuf_progress or t >= max(bracket) or t <= min(bracket):
# evaluate at 0.1 away from boundary
if abs(t - max(bracket)) < abs(t - min(bracket)):
t = max(bracket) - eps
else:
t = min(bracket) + eps
insuf_progress = False
else:
insuf_progress = True
else:
insuf_progress = False
# Evaluate new point
f_new, g_new = obj_func(x, t, d)
ls_func_evals += 1
gtd_new = g_new.dot(d)
ls_iter += 1
if f_new > (f + c1 * t * gtd) or f_new >= bracket_f[low_pos]:
# Armijo condition not satisfied or not lower than lowest point
bracket[high_pos] = t
bracket_f[high_pos] = f_new
bracket_g[high_pos] = g_new.clone()
bracket_gtd[high_pos] = gtd_new
low_pos, high_pos = (0, 1) if bracket_f[0] <= bracket_f[1] else (1, 0)
else:
if abs(gtd_new) <= -c2 * gtd:
# Wolfe conditions satisfied
done = True
elif gtd_new * (bracket[high_pos] - bracket[low_pos]) >= 0:
# old high becomes new low
bracket[high_pos] = bracket[low_pos]
bracket_f[high_pos] = bracket_f[low_pos]
bracket_g[high_pos] = bracket_g[low_pos]
bracket_gtd[high_pos] = bracket_gtd[low_pos]
# new point becomes new low
bracket[low_pos] = t
bracket_f[low_pos] = f_new
bracket_g[low_pos] = g_new.clone()
bracket_gtd[low_pos] = gtd_new
# line-search bracket is so small
if abs(bracket[1] - bracket[0]) * d_norm < tolerance_change:
break
# return stuff
t = bracket[low_pos]
f_new = bracket_f[low_pos]
g_new = bracket_g[low_pos]
return f_new, g_new, t, ls_func_evals
# LBFGS with strong Wolfe line search introduces in PR #8824
# Will be removed once merged with master
class LBFGS(Optimizer):
"""Implements L-BFGS algorithm, heavily inspired by `minFunc
<https://www.cs.ubc.ca/~schmidtm/Software/minFunc.html>`.
.. warning::
This optimizer doesn't support per-parameter options and parameter
groups (there can be only one).
.. warning::
Right now all parameters have to be on a single device. This will be
improved in the future.
.. note::
This is a very memory intensive optimizer (it requires additional
``param_bytes * (history_size + 1)`` bytes). If it doesn't fit in memory
try reducing the history size, or use a different algorithm.
Arguments:
lr (float): learning rate (default: 1)
max_iter (int): maximal number of iterations per optimization step
(default: 20)
max_eval (int): maximal number of function evaluations per optimization
step (default: max_iter * 1.25).
tolerance_grad (float): termination tolerance on first order optimality
(default: 1e-5).
tolerance_change (float): termination tolerance on function
value/parameter changes (default: 1e-9).
history_size (int): update history size (default: 100).
line_search_fn (str): either 'strong_Wolfe' or None (default: None).
"""
def __init__(self, params, lr=1, max_iter=20, max_eval=None,
tolerance_grad=1e-5, tolerance_change=1e-9, history_size=100,
line_search_fn=None):
if max_eval is None:
max_eval = max_iter * 5 // 4
defaults = dict(lr=lr, max_iter=max_iter, max_eval=max_eval,
tolerance_grad=tolerance_grad, tolerance_change=tolerance_change,
history_size=history_size, line_search_fn=line_search_fn)
super(LBFGS, self).__init__(params, defaults)
if len(self.param_groups) != 1:
raise ValueError("LBFGS doesn't support per-parameter options "
"(parameter groups)")
self._params = self.param_groups[0]['params']
self._numel_cache = None
def _numel(self):
if self._numel_cache is None:
self._numel_cache = reduce(lambda total, p: total + p.numel(), self._params, 0)
return self._numel_cache
def _gather_flat_grad(self):
views = []
for p in self._params:
if p.grad is None:
view = p.new(p.numel()).zero_()
elif p.grad.is_sparse:
view = p.grad.to_dense().view(-1)
else:
view = p.grad.view(-1)
views.append(view)
return torch.cat(views, 0)
def _add_grad(self, step_size, update):
offset = 0
for p in self._params:
numel = p.numel()
# view as to avoid deprecated pointwise semantics
p.data.add_(step_size, update[offset:offset + numel].view_as(p.data))
offset += numel
assert offset == self._numel()
def _clone_param(self):
return [p.clone() for p in self._params]
def _set_param(self, params_data):
for p, pdata in zip(self._params, params_data):
p.data.copy_(pdata)
def _directional_evaluate(self, closure, x, t, d):
self._add_grad(t, d)
loss = float(closure())
flat_grad = self._gather_flat_grad()
self._set_param(x)
return loss, flat_grad
def step(self, closure):
"""Performs a single optimization step.
Arguments:
closure (callable): A closure that reevaluates the model
and returns the loss.
"""
assert len(self.param_groups) == 1
group = self.param_groups[0]
lr = group['lr']
max_iter = group['max_iter']
max_eval = group['max_eval']
tolerance_grad = group['tolerance_grad']
tolerance_change = group['tolerance_change']
line_search_fn = group['line_search_fn']
history_size = group['history_size']
# NOTE: LBFGS has only global state, but we register it as state for
# the first param, because this helps with casting in load_state_dict
state = self.state[self._params[0]]
state.setdefault('func_evals', 0)
state.setdefault('n_iter', 0)
# evaluate initial f(x) and df/dx
orig_loss = closure()
loss = float(orig_loss)
current_evals = 1
state['func_evals'] += 1
flat_grad = self._gather_flat_grad()
opt_cond = flat_grad.abs().max() <= tolerance_grad
# optimal condition
if opt_cond:
return orig_loss
# tensors cached in state (for tracing)
d = state.get('d')
t = state.get('t')
old_dirs = state.get('old_dirs')
old_stps = state.get('old_stps')
ro = state.get('ro')
H_diag = state.get('H_diag')
prev_flat_grad = state.get('prev_flat_grad')
prev_loss = state.get('prev_loss')
n_iter = 0
# optimize for a max of max_iter iterations
while n_iter < max_iter:
# keep track of nb of iterations
n_iter += 1
state['n_iter'] += 1
############################################################
# compute gradient descent direction
############################################################
if state['n_iter'] == 1:
d = flat_grad.neg()
old_dirs = []
old_stps = []
ro = []
H_diag = 1
else:
# do lbfgs update (update memory)
y = flat_grad.sub(prev_flat_grad)
s = d.mul(t)
ys = y.dot(s) # y*s
if ys > 1e-10:
# updating memory
if len(old_dirs) == history_size:
# shift history by one (limited-memory)
old_dirs.pop(0)
old_stps.pop(0)
ro.pop(0)
# store new direction/step
old_dirs.append(y)
old_stps.append(s)
ro.append(1. / ys)
# update scale of initial Hessian approximation
H_diag = ys / y.dot(y) # (y*y)
# compute the approximate (L-BFGS) inverse Hessian
# multiplied by the gradient
num_old = len(old_dirs)
if 'al' not in state:
state['al'] = [None] * history_size
al = state['al']
# iteration in L-BFGS loop collapsed to use just one buffer
q = flat_grad.neg()
for i in range(num_old - 1, -1, -1):
al[i] = old_stps[i].dot(q) * ro[i]
q.add_(-al[i], old_dirs[i])
# multiply by initial Hessian
# r/d is the final direction
d = r = torch.mul(q, H_diag)
for i in range(num_old):
be_i = old_dirs[i].dot(r) * ro[i]
r.add_(al[i] - be_i, old_stps[i])
if prev_flat_grad is None:
prev_flat_grad = flat_grad.clone()
else:
prev_flat_grad.copy_(flat_grad)
prev_loss = loss
############################################################
# compute step length
############################################################
# reset initial guess for step size
if state['n_iter'] == 1:
t = min(1., 1. / flat_grad.abs().sum()) * lr
else:
t = lr
# directional derivative
gtd = flat_grad.dot(d) # g * d
# directional derivative is below tolerance
if gtd > -tolerance_change:
break
# optional line search: user function
ls_func_evals = 0
if line_search_fn is not None:
# perform line search, using user function
if line_search_fn != "strong_Wolfe":
raise RuntimeError("only 'strong_Wolfe' is supported")
else:
x_init = self._clone_param()
def obj_func(x, t, d):
return self._directional_evaluate(closure, x, t, d)
loss, flat_grad, t, ls_func_evals = _strong_Wolfe(obj_func, x_init, t, d,
loss,
flat_grad,
gtd,
max_iter=max_iter)
self._add_grad(t, d)
opt_cond = flat_grad.abs().max() <= tolerance_grad
else:
# no line search, simply move with fixed-step
self._add_grad(t, d)
if n_iter != max_iter:
# re-evaluate function only if not in last iteration
# the reason we do this: in a stochastic setting,
# no use to re-evaluate that function here
loss = float(closure())
flat_grad = self._gather_flat_grad()
opt_cond = flat_grad.abs().max() <= tolerance_grad
ls_func_evals = 1
# update func eval
current_evals += ls_func_evals
state['func_evals'] += ls_func_evals
############################################################
# check conditions
############################################################
if n_iter == max_iter:
break
if current_evals >= max_eval:
break
# optimal condition
if opt_cond:
break
# lack of progress
if d.mul(t).abs().max() <= tolerance_change:
break
if abs(loss - prev_loss) < tolerance_change:
break
state['d'] = d
state['t'] = t
state['old_dirs'] = old_dirs
state['old_stps'] = old_stps
state['ro'] = ro
state['H_diag'] = H_diag
state['prev_flat_grad'] = prev_flat_grad
state['prev_loss'] = prev_loss
return orig_loss
================================================
FILE: common/utils/optimizers/optim_factory.py
================================================
# -*- coding: utf-8 -*-
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# You can only use this computer program if you have closed
# a license agreement with MPG or you get the right to use the computer
# program from someone who is authorized to grant you that right.
# Any use of the computer program without a valid license is prohibited and
# liable to prosecution.
#
# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
# for Intelligent Systems and the Max Planck Institute for Biological
# Cybernetics. All rights reserved.
#
# Contact: ps-license@tuebingen.mpg.de
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import torch.optim as optim
from .lbfgs_ls import LBFGS as LBFGSLs
def create_optimizer(parameters, optim_type='lbfgs',
lr=1e-3,
momentum=0.9,
use_nesterov=True,
beta1=0.9,
beta2=0.999,
epsilon=1e-8,
use_locking=False,
weight_decay=0.0,
centered=False,
rmsprop_alpha=0.99,
maxiters=20,
gtol=1e-6,
ftol=1e-9,
**kwargs):
''' Creates the optimizer
'''
if optim_type == 'adam':
return (optim.Adam(parameters, lr=lr, betas=(beta1, beta2),
weight_decay=weight_decay),
False)
elif optim_type == 'lbfgs':
return (optim.LBFGS(parameters, lr=lr, max_iter=maxiters), False)
elif optim_type == 'lbfgsls':
return LBFGSLs(parameters, lr=lr, max_iter=maxiters,
line_search_fn='strong_Wolfe'), False
elif optim_type == 'rmsprop':
return (optim.RMSprop(parameters, lr=lr, epsilon=epsilon,
alpha=rmsprop_alpha,
weight_decay=weight_decay,
momentum=momentum, centered=centered),
False)
elif optim_type == 'sgd':
return (optim.SGD(parameters, lr=lr, momentum=momentum,
weight_decay=weight_decay,
nesterov=use_nesterov),
False)
else:
raise ValueError('Optimizer {} not supported!'.format(optim_type))
================================================
FILE: common/utils/preprocessing.py
================================================
import numpy as np
import cv2
import random
from config import cfg
import math
import torchvision
def load_img(path, order='RGB'):
img = cv2.imread(path, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)
if not isinstance(img, np.ndarray):
raise IOError("Fail to read %s" % path)
if order=='RGB':
img = img[:,:,::-1].copy()
img = img.astype(np.float32)
return img
def get_bbox(joint_img, joint_valid, expansion_factor=1.0):
x_img, y_img = joint_img[:,0], joint_img[:,1]
x_img = x_img[joint_valid==1]; y_img = y_img[joint_valid==1];
xmin = min(x_img); ymin = min(y_img); xmax = max(x_img); ymax = max(y_img);
x_center = (xmin+xmax)/2.; width = (xmax-xmin)*expansion_factor;
xmin = x_center - 0.5*width
xmax = x_center + 0.5*width
y_center = (ymin+ymax)/2.; height = (ymax-ymin)*expansion_factor;
ymin = y_center - 0.5*height
ymax = y_center + 0.5*height
bbox = np.array([xmin, ymin, xmax - xmin, ymax - ymin]).astype(np.float32)
return bbox
def process_bbox(bbox, img_width, img_height, expansion_factor=1.25):
# sanitize bboxes
x, y, w, h = bbox
x1 = np.max((0, x))
y1 = np.max((0, y))
x2 = np.min((img_width - 1, x1 + np.max((0, w - 1))))
y2 = np.min((img_height - 1, y1 + np.max((0, h - 1))))
if w*h > 0 and x2 >= x1 and y2 >= y1:
bbox = np.array([x1, y1, x2-x1, y2-y1])
else:
return None
# aspect ratio preserving bbox
w = bbox[2]
h = bbox[3]
c_x = bbox[0] + w/2.
c_y = bbox[1] + h/2.
aspect_ratio = cfg.input_img_shape[1]/cfg.input_img_shape[0]
if w > aspect_ratio * h:
h = w / aspect_ratio
elif w < aspect_ratio * h:
w = h * aspect_ratio
bbox[2] = w*expansion_factor
bbox[3] = h*expansion_factor
bbox[0] = c_x - bbox[2]/2.
bbox[1] = c_y - bbox[3]/2.
return bbox
def get_aug_config():
scale_factor = 0.25
rot_factor = 30
color_factor = 0.2
scale = np.clip(np.random.randn(), -1.0, 1.0) * scale_factor + 1.0
rot = np.clip(np.random.randn(), -2.0,
2.0) * rot_factor if random.random() <= 0.6 else 0
c_up = 1.0 + color_factor
c_low = 1.0 - color_factor
color_scale = np.array([random.uniform(c_low, c_up), random.uniform(c_low, c_up), random.uniform(c_low, c_up)])
return scale, rot, color_scale
def augmentation(img, bbox, data_split, do_flip=False):
if data_split == 'train':
scale, rot, color_scale = get_aug_config()
else:
scale, rot, color_scale = 1.0, 0.0, np.array([1,1,1])
img, trans, inv_trans = generate_patch_image(img, bbox, scale, rot, do_flip, cfg.input_img_shape)
img = np.clip(img * color_scale[None,None,:], 0, 255)
return img, trans, inv_trans, rot, scale
def generate_patch_image(cvimg, bbox, scale, rot, do_flip, out_shape):
img = cvimg.copy()
img_height, img_width, img_channels = img.shape
bb_c_x = float(bbox[0] + 0.5*bbox[2])
bb_c_y = float(bbox[1] + 0.5*bbox[3])
bb_width = float(bbox[2])
bb_height = float(bbox[3])
if do_flip:
img = img[:, ::-1, :]
bb_c_x = img_width - bb_c_x - 1
trans = gen_trans_from_patch_cv(bb_c_x, bb_c_y, bb_width, bb_height, out_shape[1], out_shape[0], scale, rot)
img_patch = cv2.warpAffine(img, trans, (int(out_shape[1]), int(out_shape[0])), flags=cv2.INTER_LINEAR)
img_patch = img_patch.astype(np.float32)
inv_trans = gen_trans_from_patch_cv(bb_c_x, bb_c_y, bb_width, bb_height, out_shape[1], out_shape[0], scale, rot, inv=True)
return img_patch, trans, inv_trans
def rotate_2d(pt_2d, rot_rad):
x = pt_2d[0]
y = pt_2d[1]
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
xx = x * cs - y * sn
yy = x * sn + y * cs
return np.array([xx, yy], dtype=np.float32)
def gen_trans_from_patch_cv(c_x, c_y, src_width, src_height, dst_width, dst_height, scale, rot, inv=False):
# augment size with scale
src_w = src_width * scale
src_h = src_height * scale
src_center = np.array([c_x, c_y], dtype=np.float32)
# augment rotation
rot_rad = np.pi * rot / 180
src_downdir = rotate_2d(np.array([0, src_h * 0.5], dtype=np.float32), rot_rad)
src_rightdir = rotate_2d(np.array([src_w * 0.5, 0], dtype=np.float32), rot_rad)
dst_w = dst_width
dst_h = dst_height
dst_center = np.array([dst_w * 0.5, dst_h * 0.5], dtype=np.float32)
dst_downdir = np.array([0, dst_h * 0.5], dtype=np.float32)
dst_rightdir = np.array([dst_w * 0.5, 0], dtype=np.float32)
src = np.zeros((3, 2), dtype=np.float32)
src[0, :] = src_center
src[1, :] = src_center + src_downdir
src[2, :] = src_center + src_rightdir
dst = np.zeros((3, 2), dtype=np.float32)
dst[0, :] = dst_center
dst[1, :] = dst_center + dst_downdir
dst[2, :] = dst_center + dst_rightdir
if inv:
trans = cv2.getAffineTransform(np.float32(dst), np.float32(src))
else:
trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))
trans = trans.astype(np.float32)
return trans
================================================
FILE: common/utils/transforms.py
================================================
import torch
import numpy as np
from config import cfg
def cam2pixel(cam_coord, f, c):
x = cam_coord[:,0] / cam_coord[:,2] * f[0] + c[0]
y = cam_coord[:,1] / cam_coord[:,2] * f[1] + c[1]
z = cam_coord[:,2]
return np.stack((x,y,z),1)
def pixel2cam(pixel_coord, f, c):
x = (pixel_coord[:,0] - c[0]) / f[0] * pixel_coord[:,2]
y = (pixel_coord[:,1] - c[1]) / f[1] * pixel_coord[:,2]
z = pixel_coord[:,2]
return np.stack((x,y,z),1)
def world2cam(world_coord, R, t):
cam_coord = np.dot(R, world_coord.transpose(1,0)).transpose(1,0) + t.reshape(1,3)
return cam_coord
def cam2world(cam_coord, R, t):
world_coord = np.dot(np.linalg.inv(R), (cam_coord - t.reshape(1,3)).transpose(1,0)).transpose(1,0)
return world_coord
def rigid_transform_3D(A, B):
n, dim = A.shape
centroid_A = np.mean(A, axis = 0)
centroid_B = np.mean(B, axis = 0)
H = np.dot(np.transpose(A - centroid_A), B - centroid_B) / n
U, s, V = np.linalg.svd(H)
R = np.dot(np.transpose(V), np.transpose(U))
if np.linalg.det(R) < 0:
s[-1] = -s[-1]
V[2] = -V[2]
R = np.dot(np.transpose(V), np.transpose(U))
varP = np.var(A, axis=0).sum()
c = 1/varP * np.sum(s)
t = -np.dot(c*R, np.transpose(centroid_A)) + np.transpose(centroid_B)
return c, R, t
def rigid_align(A, B):
c, R, t = rigid_transform_3D(A, B)
A2 = np.transpose(np.dot(c*R, np.transpose(A))) + t
return A2
def transform_joint_to_other_db(src_joint, src_name, dst_name):
src_joint_num = len(src_name)
dst_joint_num = len(dst_name)
new_joint = np.zeros(((dst_joint_num,) + src_joint.shape[1:]), dtype=np.float32)
for src_idx in range(len(src_name)):
name = src_name[src_idx]
if name in dst_name:
dst_idx = dst_name.index(name)
new_joint[dst_idx] = src_joint[src_idx]
return new_joint
================================================
FILE: common/utils/vis.py
================================================
import os
import cv2
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib as mpl
os.environ["PYOPENGL_PLATFORM"] = "egl"
import pyrender
import trimesh
def vis_keypoints_with_skeleton(img, kps, kps_lines, kp_thresh=0.4, alpha=1):
# Convert from plt 0-1 RGBA colors to 0-255 BGR colors for opencv.
cmap = plt.get_cmap('rainbow')
colors = [cmap(i) for i in np.linspace(0, 1, len(kps_lines) + 2)]
colors = [(c[2] * 255, c[1] * 255, c[0] * 255) for c in colors]
# Perform the drawing on a copy of the image, to allow for blending.
kp_mask = np.copy(img)
# Draw the keypoints.
for l in range(len(kps_lines)):
i1 = kps_lines[l][0]
i2 = kps_lines[l][1]
p1 = kps[0, i1].astype(np.int32), kps[1, i1].astype(np.int32)
p2 = kps[0, i2].astype(np.int32), kps[1, i2].astype(np.int32)
if kps[2, i1] > kp_thresh and kps[2, i2] > kp_thresh:
cv2.line(
kp_mask, p1, p2,
color=colors[l], thickness=2, lineType=cv2.LINE_AA)
if kps[2, i1] > kp_thresh:
cv2.circle(
kp_mask, p1,
radius=3, color=colors[l], thickness=-1, lineType=cv2.LINE_AA)
if kps[2, i2] > kp_thresh:
cv2.circle(
kp_mask, p2,
radius=3, color=colors[l], thickness=-1, lineType=cv2.LINE_AA)
# Blend the keypoints.
return cv2.addWeighted(img, 1.0 - alpha, kp_mask, alpha, 0)
def vis_keypoints(img, kps, alpha=1):
# Convert from plt 0-1 RGBA colors to 0-255 BGR colors for opencv.
cmap = plt.get_cmap('rainbow')
colors = [cmap(i) for i in np.linspace(0, 1, len(kps) + 2)]
colors = [(c[2] * 255, c[1] * 255, c[0] * 255) for c in colors]
# Perform the drawing on a copy of the image, to allow for blending.
kp_mask = np.copy(img)
# Draw the keypoints.
for i in range(len(kps)):
p = kps[i][0].astype(np.int32), kps[i][1].astype(np.int32)
cv2.circle(kp_mask, p, radius=3, color=colors[i], thickness=-1, lineType=cv2.LINE_AA)
# Blend the keypoints.
return cv2.addWeighted(img, 1.0 - alpha, kp_mask, alpha, 0)
def vis_mesh(img, mesh_vertex, alpha=0.5):
# Convert from plt 0-1 RGBA colors to 0-255 BGR colors for opencv.
cmap = plt.get_cmap('rainbow')
colors = [cmap(i) for i in np.linspace(0, 1, len(mesh_vertex))]
colors = [(c[2] * 255, c[1] * 255, c[0] * 255) for c in colors]
# Perform the drawing on a copy of the image, to allow for blending.
mask = np.copy(img)
# Draw the mesh
for i in range(len(mesh_vertex)):
p = mesh_vertex[i][0].astype(np.int32), mesh_vertex[i][1].astype(np.int32)
cv2.circle(mask, p, radius=1, color=colors[i], thickness=-1, lineType=cv2.LINE_AA)
# Blend the keypoints.
return cv2.addWeighted(img, 1.0 - alpha, mask, alpha, 0)
def vis_3d_skeleton(kpt_3d, kpt_3d_vis, kps_lines, filename=None):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Convert from plt 0-1 RGBA colors to 0-255 BGR colors for opencv.
cmap = plt.get_cmap('rainbow')
colors = [cmap(i) for i in np.linspace(0, 1, len(kps_lines) + 2)]
colors = [np.array((c[2], c[1], c[0])) for c in colors]
for l in range(len(kps_lines)):
i1 = kps_lines[l][0]
i2 = kps_lines[l][1]
x = np.array([kpt_3d[i1,0], kpt_3d[i2,0]])
y = np.array([kpt_3d[i1,1], kpt_3d[i2,1]])
z = np.array([kpt_3d[i1,2], kpt_3d[i2,2]])
if kpt_3d_vis[i1,0] > 0 and kpt_3d_vis[i2,0] > 0:
ax.plot(x, z, -y, c=colors[l], linewidth=2)
if kpt_3d_vis[i1,0] > 0:
ax.scatter(kpt_3d[i1,0], kpt_3d[i1,2], -kpt_3d[i1,1], c=colors[l], marker='o')
if kpt_3d_vis[i2,0] > 0:
ax.scatter(kpt_3d[i2,0], kpt_3d[i2,2], -kpt_3d[i2,1], c=colors[l], marker='o')
if filename is None:
ax.set_title('3D vis')
else:
ax.set_title(filename)
ax.set_xlabel('X Label')
ax.set_ylabel('Z Label')
ax.set_zlabel('Y Label')
ax.legend()
#plt.show()
#cv2.waitKey(0)
plt.savefig(filename)
def save_obj(v, f, file_name='output.obj'):
obj_file = open(file_name, 'w')
for i in range(len(v)):
obj_file.write('v ' + str(v[i][0]) + ' ' + str(v[i][1]) + ' ' + str(v[i][2]) + '\n')
for i in range(len(f)):
obj_file.write('f ' + str(f[i][0]+1) + '/' + str(f[i][0]+1) + ' ' + str(f[i][1]+1) + '/' + str(f[i][1]+1) + ' ' + str(f[i][2]+1) + '/' + str(f[i][2]+1) + '\n')
obj_file.close()
def render_mesh(img, mesh, face, cam_param):
# mesh
mesh = trimesh.Trimesh(mesh, face)
rot = trimesh.transformations.rotation_matrix(
np.radians(180), [1, 0, 0])
mesh.apply_transform(rot)
material = pyrender.MetallicRoughnessMaterial(metallicFactor=0.0, alphaMode='OPAQUE', baseColorFactor=(1.0, 1.0, 0.9, 1.0))
mesh = pyrender.Mesh.from_trimesh(mesh, material=material, smooth=False)
scene = pyrender.Scene(ambient_light=(0.3, 0.3, 0.3))
scene.add(mesh, 'mesh')
focal, princpt = cam_param['focal'], cam_param['princpt']
camera = pyrender.IntrinsicsCamera(fx=focal[0], fy=focal[1], cx=princpt[0], cy=princpt[1])
scene.add(camera)
# renderer
renderer = pyrender.OffscreenRenderer(viewport_width=img.shape[1], viewport_height=img.shape[0], point_size=1.0)
# light
light = pyrender.DirectionalLight(color=[1.0, 1.0, 1.0], intensity=0.8)
light_pose = np.eye(4)
light_pose[:3, 3] = np.array([0, -1, 1])
scene.add(light, pose=light_pose)
light_pose[:3, 3] = np.array([0, 1, 1])
scene.add(light, pose=light_pose)
light_pose[:3, 3] = np.array([1, 1, 2])
scene.add(light, pose=light_pose)
# render
rgb, depth = renderer.render(scene, flags=pyrender.RenderFlags.RGBA)
rgb = rgb[:,:,:3].astype(np.float32)
valid_mask = (depth > 0)[:,:,None]
# save to image
img = rgb * valid_mask*0.5 + img #* (1-valid_mask)
return img
================================================
FILE: data/DEX_YCB/DEX_YCB.py
================================================
import os
import os.path as osp
import numpy as np
import torch
import cv2
import random
import json
import math
import copy
from pycocotools.coco import COCO
from config import cfg
from utils.preprocessing import load_img, get_bbox, process_bbox, generate_patch_image, augmentation
from utils.transforms import world2cam, cam2pixel, pixel2cam, rigid_align, transform_joint_to_other_db
from utils.vis import vis_keypoints, vis_mesh, save_obj, vis_keypoints_with_skeleton, render_mesh, vis_3d_skeleton
from utils.mano import MANO
mano = MANO()
# # TEMP; test set
# target_img_list = {
# 1: ['20200820-subject-03/20200820_135508/836212060125/color_000030.jpg', '20200820-subject-03/20200820_135508/836212060125/color_000060.jpg', '20200903-subject-04/20200903_103828/836212060125/color_000030.jpg', '20200903-subject-04/20200903_103828/836212060125/color_000060.jpg', '20200908-subject-05/20200908_143535/836212060125/color_000060.jpg', '20200908-subject-05/20200908_143535/932122060857/color_000030.jpg', '20200918-subject-06/20200918_113137/836212060125/color_000030.jpg', '20200918-subject-06/20200918_113137/836212060125/color_000060.jpg',
# '20200928-subject-07/20200928_143500/836212060125/color_000060.jpg', '20200928-subject-07/20200928_143500/932122060857/color_000030.jpg', '20201002-subject-08/20201002_104827/836212060125/color_000060.jpg', '20201002-subject-08/20201002_104827/932122060861/color_000030.jpg', '20201015-subject-09/20201015_142844/836212060125/color_000030.jpg', '20201015-subject-09/20201015_142844/836212060125/color_000060.jpg', '20201015-subject-09/20201015_142844/841412060263/color_000000.jpg', '20201022-subject-10/20201022_110947/840412060917/color_000060.jpg', '20201022-subject-10/20201022_110947/932122060857/color_000030.jpg'],
# 2: ['20200820-subject-03/20200820_135810/836212060125/color_000060.jpg', '20200820-subject-03/20200820_135810/839512060362/color_000030.jpg', '20200903-subject-04/20200903_104115/836212060125/color_000030.jpg', '20200903-subject-04/20200903_104115/839512060362/color_000060.jpg', '20200908-subject-05/20200908_143832/836212060125/color_000030.jpg', '20200908-subject-05/20200908_143832/836212060125/color_000060.jpg', '20200918-subject-06/20200918_113405/839512060362/color_000060.jpg', '20200918-subject-06/20200918_113405/840412060917/color_000030.jpg', '20200928-subject-07/20200928_143727/839512060362/color_000060.jpg', '20200928-subject-07/20200928_143727/840412060917/color_000030.jpg', '20201002-subject-08/20201002_105058/836212060125/color_000060.jpg', '20201002-subject-08/20201002_105058/840412060917/color_000030.jpg', '20201015-subject-09/20201015_143113/836212060125/color_000030.jpg', '20201015-subject-09/20201015_143113/836212060125/color_000060.jpg', '20201015-subject-09/20201015_143113/840412060917/color_000000.jpg', '20201022-subject-10/20201022_111144/840412060917/color_000030.jpg', '20201022-subject-10/20201022_111144/840412060917/color_000060.jpg'],
# 10: ['20200820-subject-03/20200820_142158/932122060861/color_000030.jpg', '20200820-subject-03/20200820_142158/932122060861/color_000060.jpg', '20200903-subject-04/20200903_110342/836212060125/color_000060.jpg', '20200908-subject-05/20200908_145938/836212060125/color_000060.jpg', '20200908-subject-05/20200908_145938/839512060362/color_000030.jpg', '20200918-subject-06/20200918_115139/839512060362/color_000060.jpg', '20200918-subject-06/20200918_115139/840412060917/color_000030.jpg', '20200928-subject-07/20200928_153732/836212060125/color_000030.jpg', '20200928-subject-07/20200928_153732/932122060857/color_000060.jpg', '20201002-subject-08/20201002_110854/836212060125/color_000060.jpg', '20201015-subject-09/20201015_145212/836212060125/color_000030.jpg', '20201015-subject-09/20201015_145212/839512060362/color_000060.jpg'],
# 15: ['20200820-subject-03/20200820_143802/836212060125/color_000060.jpg', '20200820-subject-03/20200820_143802/840412060917/color_000030.jpg', '20200903-subject-04/20200903_112724/836212060125/color_000060.jpg', '20200903-subject-04/20200903_112724/841412060263/color_000030.jpg', '20200908-subject-05/20200908_151328/836212060125/color_000060.jpg', '20200908-subject-05/20200908_151328/840412060917/color_000030.jpg', '20200918-subject-06/20200918_120310/836212060125/color_000030.jpg', '20200918-subject-06/20200918_120310/836212060125/color_000060.jpg', '20200928-subject-07/20200928_154943/836212060125/color_000030.jpg', '20200928-subject-07/20200928_154943/836212060125/color_000060.jpg', '20201002-subject-08/20201002_112045/836212060125/color_000030.jpg', '20201002-subject-08/20201002_112045/836212060125/color_000060.jpg', '20201015-subject-09/20201015_150413/836212060125/color_000030.jpg', '20201015-subject-09/20201015_150413/836212060125/color_000060.jpg', '20201022-subject-10/20201022_113909/836212060125/color_000060.jpg']
# }
# # TEMP; val set
# # target_img_list = {
# # 1: ['20200709-subject-01/20200709_142123/836212060125/color_000030.jpg', '20200709-subject-01/20200709_142123/836212060125/color_000060.jpg', '20200813-subject-02/20200813_145612/836212060125/color_000030.jpg', '20200813-subject-02/20200813_145612/836212060125/color_000060.jpg'],
# # 2: ['20200709-subject-01/20200709_142446/840412060917/color_000030.jpg', '20200709-subject-01/20200709_142446/840412060917/color_000060.jpg', '20200813-subject-02/20200813_145920/836212060125/color_000030.jpg', '20200813-subject-02/20200813_145920/836212060125/color_000060.jpg'],
# # 10: ['20200709-subject-01/20200709_145743/839512060362/color_000060.jpg', '20200709-subject-01/20200709_145743/932122061900/color_000030.jpg', '20200813-subject-02/20200813_152842/836212060125/color_000060.jpg', '20200813-subject-02/20200813_152842/841412060263/color_000030.jpg'],
# # 15: ['20200709-subject-01/20200709_151632/836212060125/color_000060.jpg', '20200709-subject-01/20200709_151632/840412060917/color_000030.jpg', '20200813-subject-02/20200813_154408/836212060125/color_000030.jpg', '20200813-subject-02/20200813_154408/836212060125/color_000060.jpg'],
# # }
# target_img_list_sum = []
# for key, val in target_img_list.items():
# target_img_list_sum.extend(val)
#with open('/home/hongsuk.c/Projects/HandOccNet/main/novel_object_test_list.json', 'r') as f:
# target_img_list_sum = json.load(f)
#print("TARGET LENGTH: ", len(target_img_list_sum))
class DEX_YCB(torch.utils.data.Dataset):
def __init__(self, transform, data_split):
self.transform = transform
self.data_split = data_split if data_split == 'train' else 'val'
self.root_dir = osp.join('..', 'data', 'DEX_YCB', 'data')
self.annot_path = osp.join(self.root_dir, 'annotations')
self.root_joint_idx = 0
self.datalist = self.load_data()
if self.data_split != 'train':
self.eval_result = [[],[]] #[mpjpe_list, pa-mpjpe_list]
print("TEST DATA LEN: ", len(self.datalist))
def load_data(self):
db = COCO(osp.join(self.annot_path, "DEX_YCB_s0_{}_data.json".format(self.data_split)))
datalist = []
for aid in db.anns.keys():
ann = db.anns[aid]
image_id = ann['image_id']
img = db.loadImgs(image_id)[0]
img_path = osp.join(self.root_dir, img['file_name'])
img_shape = (img['height'], img['width'])
if self.data_split == 'train':
joints_coord_cam = np.array(ann['joints_coord_cam'], dtype=np.float32) # meter
cam_param = {k:np.array(v, dtype=np.float32) for k,v in ann['cam_param'].items()}
joints_coord_img = np.array(ann['joints_img'], dtype=np.float32)
hand_type = ann['hand_type']
bbox = get_bbox(joints_coord_img[:,:2], np.ones_like(joints_coord_img[:,0]), expansion_factor=1.5)
bbox = process_bbox(bbox, img['width'], img['height'], expansion_factor=1.0)
if bbox is None:
continue
mano_pose = np.array(ann['mano_param']['pose'], dtype=np.float32)
mano_shape = np.array(ann['mano_param']['shape'], dtype=np.float32)
data = {"img_path": img_path, "img_shape": img_shape, "joints_coord_cam": joints_coord_cam, "joints_coord_img": joints_coord_img,
"bbox": bbox, "cam_param": cam_param, "mano_pose": mano_pose, "mano_shape": mano_shape, "hand_type": hand_type}
else:
# if '/'.join(img_path.split('/')[-4:]) not in target_img_list_sum:
# continue
joints_coord_cam = np.array(ann['joints_coord_cam'], dtype=np.float32)
root_joint_cam = copy.deepcopy(joints_coord_cam[0])
joints_coord_img = np.array(ann['joints_img'], dtype=np.float32)
hand_type = ann['hand_type']
if False and hand_type == 'left':
# mano_pose = np.array(ann['mano_param']['pose'], dtype=np.float32)
# mano_shape = np.array(ann['mano_param']['shape'], dtype=np.float32)
# vertices, joints, manojoints2cam = mano.left_layer(torch.from_numpy(mano_pose)[None, :], torch.from_numpy(mano_shape)[None, :])
# vertices = vertices[0].numpy()
# # save_obj(vertices, mano.left_layer.th_faces.numpy(), 'org_left.obj')
# joints = joints[0].numpy()
gitextract_dl_xba82/ ├── .gitignore ├── README.md ├── common/ │ ├── base.py │ ├── logger.py │ ├── nets/ │ │ ├── backbone.py │ │ ├── cbam.py │ │ ├── hand_head.py │ │ ├── mano_head.py │ │ ├── regressor.py │ │ └── transformer.py │ ├── timer.py │ └── utils/ │ ├── __init__.py │ ├── camera.py │ ├── dir.py │ ├── fitting.py │ ├── mano.py │ ├── manopth/ │ │ ├── .gitignore │ │ ├── LICENSE │ │ ├── README.md │ │ ├── environment.yml │ │ ├── examples/ │ │ │ ├── manopth_demo.py │ │ │ └── manopth_mindemo.py │ │ ├── mano/ │ │ │ ├── __init__.py │ │ │ └── webuser/ │ │ │ ├── __init__.py │ │ │ ├── lbs.py │ │ │ ├── posemapper.py │ │ │ ├── serialization.py │ │ │ ├── smpl_handpca_wrapper_HAND_only.py │ │ │ └── verts.py │ │ ├── manopth/ │ │ │ ├── __init__.py │ │ │ ├── argutils.py │ │ │ ├── demo.py │ │ │ ├── manolayer.py │ │ │ ├── rodrigues_layer.py │ │ │ ├── rot6d.py │ │ │ ├── rotproj.py │ │ │ └── tensutils.py │ │ ├── setup.py │ │ └── test/ │ │ └── test_demo.py │ ├── optimizers/ │ │ ├── __init__.py │ │ ├── lbfgs_ls.py │ │ └── optim_factory.py │ ├── preprocessing.py │ ├── transforms.py │ └── vis.py ├── data/ │ ├── DEX_YCB/ │ │ └── DEX_YCB.py │ └── HO3D/ │ └── HO3D.py ├── demo/ │ ├── demo.py │ ├── demo_fitting.py │ └── output.obj ├── main/ │ ├── config.py │ ├── model.py │ ├── test.py │ └── train.py └── requiremets.sh
SYMBOL INDEX (235 symbols across 40 files)
FILE: common/base.py
class Base (line 20) | class Base(object):
method __init__ (line 23) | def __init__(self, log_name='logs.txt'):
method _make_batch_generator (line 36) | def _make_batch_generator(self):
method _make_model (line 40) | def _make_model(self):
class Trainer (line 43) | class Trainer(Base):
method __init__ (line 44) | def __init__(self):
method get_optimizer (line 47) | def get_optimizer(self, model):
method save_model (line 52) | def save_model(self, state, epoch):
method load_model (line 57) | def load_model(self, model, optimizer):
method set_lr (line 69) | def set_lr(self, epoch):
method get_lr (line 81) | def get_lr(self):
method _make_batch_generator (line 86) | def _make_batch_generator(self):
method _make_model (line 94) | def _make_model(self):
class Tester (line 111) | class Tester(Base):
method __init__ (line 112) | def __init__(self, test_epoch):
method _make_batch_generator (line 116) | def _make_batch_generator(self):
method _make_model (line 122) | def _make_model(self):
method _evaluate (line 137) | def _evaluate(self, outs, cur_sample_idx):
method _print_eval_result (line 141) | def _print_eval_result(self, test_epoch):
FILE: common/logger.py
class colorlogger (line 16) | class colorlogger():
method __init__ (line 17) | def __init__(self, log_dir, log_name='train_logs.txt'):
method debug (line 36) | def debug(self, msg):
method info (line 39) | def info(self, msg):
method warning (line 42) | def warning(self, msg):
method critical (line 45) | def critical(self, msg):
method error (line 48) | def error(self, msg):
FILE: common/nets/backbone.py
class FPN (line 10) | class FPN(nn.Module):
method __init__ (line 11) | def __init__(self, pretrained=True):
method _upsample_add (line 40) | def _upsample_add(self, x, y):
method forward (line 44) | def forward(self, x):
class ResNet (line 68) | class ResNet(nn.Module):
method __init__ (line 69) | def __init__(self, block, layers, num_classes=1000):
method _make_layer (line 90) | def _make_layer(self, block, planes, blocks, stride=1):
method forward (line 105) | def forward(self, x):
function resnet50 (line 122) | def resnet50(pretrained=False, **kwargs):
function conv3x3 (line 130) | def conv3x3(in_planes, out_planes, stride=1):
class BasicBlock (line 134) | class BasicBlock(nn.Module):
method __init__ (line 137) | def __init__(self, inplanes, planes, stride=1, downsample=None):
method forward (line 147) | def forward(self, x):
class Bottleneck (line 166) | class Bottleneck(nn.Module):
method __init__ (line 169) | def __init__(self, inplanes, planes, stride=1, downsample=None):
method forward (line 185) | def forward(self, x):
FILE: common/nets/cbam.py
class BasicConv (line 6) | class BasicConv(nn.Module):
method __init__ (line 7) | def __init__(self, in_planes, out_planes, kernel_size, stride=1, paddi...
method forward (line 14) | def forward(self, x):
class Flatten (line 22) | class Flatten(nn.Module):
method forward (line 23) | def forward(self, x):
class ChannelGate (line 26) | class ChannelGate(nn.Module):
method __init__ (line 27) | def __init__(self, gate_channels, reduction_ratio=16, pool_types=['avg...
method forward (line 37) | def forward(self, x):
function logsumexp_2d (line 62) | def logsumexp_2d(tensor):
class ChannelPool (line 68) | class ChannelPool(nn.Module):
method forward (line 69) | def forward(self, x):
class SpatialGate (line 72) | class SpatialGate(nn.Module):
method __init__ (line 73) | def __init__(self):
method forward (line 78) | def forward(self, x):
class CBAM (line 84) | class CBAM(nn.Module):
method __init__ (line 85) | def __init__(self, gate_channels, reduction_ratio=16, pool_types=['avg...
method forward (line 91) | def forward(self, x):
FILE: common/nets/hand_head.py
class hand_regHead (line 5) | class hand_regHead(nn.Module):
method __init__ (line 6) | def __init__(self, roi_res=32, joint_nb=21, stacks=1, channels=256, bl...
method make_residual (line 51) | def make_residual(self, block, inplanes, planes, blocks, stride=1):
method spatial_softmax (line 62) | def spatial_softmax(self, latents):
method generate_output (line 69) | def generate_output(self, heatmaps):
method forward (line 75) | def forward(self, x):
class BasicBlock (line 96) | class BasicBlock(nn.Module):
method __init__ (line 97) | def __init__(self, in_planes, out_planes, kernel_size,groups=1):
method forward (line 107) | def forward(self, x):
class Residual (line 111) | class Residual(nn.Module):
method __init__ (line 112) | def __init__(self, numIn, numOut):
method forward (line 127) | def forward(self, x):
class Bottleneck (line 145) | class Bottleneck(nn.Module):
method __init__ (line 148) | def __init__(self, inplanes, planes, stride=1, skip=None, groups=1):
method forward (line 162) | def forward(self, x):
class Hourglass (line 185) | class Hourglass(nn.Module):
method __init__ (line 186) | def __init__(self, block, num_blocks, planes, depth):
method _make_residual (line 193) | def _make_residual(self, block, num_blocks, planes):
method _make_hour_glass (line 201) | def _make_hour_glass(self, block, num_blocks, planes, depth):
method _hour_glass_forward (line 217) | def _hour_glass_forward(self, n, x):
method forward (line 231) | def forward(self, x):
class hand_Encoder (line 237) | class hand_Encoder(nn.Module):
method __init__ (line 238) | def __init__(self, num_heatmap_chan=21, num_feat_chan=256, size_input_...
method forward (line 266) | def forward(self, hm_list, encoding_list):
FILE: common/nets/mano_head.py
function batch_rodrigues (line 7) | def batch_rodrigues(theta):
function quat2mat (line 20) | def quat2mat(quat):
function quat2aa (line 39) | def quat2aa(quaternion):
function mat2quat (line 72) | def mat2quat(rotation_matrix, eps=1e-6):
function rot6d2mat (line 134) | def rot6d2mat(x):
function mat2aa (line 146) | def mat2aa(rotation_matrix):
class mano_regHead (line 167) | class mano_regHead(nn.Module):
method __init__ (line 168) | def __init__(self, mano_layer=mano.layer, feature_size=1024, mano_neur...
method forward (line 190) | def forward(self, features, gt_mano_params=None):
FILE: common/nets/regressor.py
class Regressor (line 8) | class Regressor(nn.Module):
method __init__ (line 9) | def __init__(self):
method forward (line 15) | def forward(self, feats, gt_mano_params=None):
FILE: common/nets/transformer.py
class Transformer (line 6) | class Transformer(nn.Module):
method __init__ (line 7) | def __init__(self, inp_res=32, dim=256, depth=2, num_heads=4, mlp_rati...
method forward (line 26) | def forward(self, query, key):
class Mlp (line 37) | class Mlp(nn.Module):
method __init__ (line 38) | def __init__(self, in_features, hidden_features=None, out_features=Non...
method forward (line 48) | def forward(self, x):
method _init_weights (line 56) | def _init_weights(self):
class Attention (line 63) | class Attention(nn.Module):
method __init__ (line 64) | def __init__(self, dim, num_heads=1):
method forward (line 71) | def forward(self, query, key, value, query2, key2, use_sigmoid):
class Block (line 90) | class Block(nn.Module):
method __init__ (line 92) | def __init__(self, dim, num_heads, mlp_ratio=4., act_layer=nn.GELU, no...
method with_pos_embed (line 114) | def with_pos_embed(self, tensor, pos):
method forward (line 117) | def forward(self, query, key, query_embed=None, key_embed=None):
FILE: common/timer.py
class Timer (line 10) | class Timer(object):
method __init__ (line 12) | def __init__(self):
method tic (line 20) | def tic(self):
method toc (line 25) | def toc(self, average=True):
FILE: common/utils/camera.py
function transform_mat (line 33) | def transform_mat(R: torch.tensor, t: torch.tensor) -> torch.Tensor:
function create_camera (line 47) | def create_camera(camera_type='persp', **kwargs):
class PerspectiveCamera (line 54) | class PerspectiveCamera(nn.Module):
method __init__ (line 58) | def __init__(self, rotation=None, translation=None,
method forward (line 106) | def forward(self, points):
FILE: common/utils/dir.py
function make_folder (line 4) | def make_folder(folder_name):
function add_pypath (line 8) | def add_pypath(path):
FILE: common/utils/fitting.py
function to_tensor (line 7) | def to_tensor(tensor, dtype=torch.float32):
function rel_change (line 14) | def rel_change(prev_val, curr_val):
class FittingMonitor (line 17) | class FittingMonitor(object):
method __init__ (line 18) | def __init__(self, summary_steps=1, visualize=False,
method __enter__ (line 34) | def __enter__(self):
method __exit__ (line 39) | def __exit__(self, exception_type, exception_value, traceback):
method set_colors (line 42) | def set_colors(self, vertex_color):
method run_fitting (line 49) | def run_fitting(self, optimizer, closure, params,
method create_fitting_closure (line 92) | def create_fitting_closure(self,
class ScaleTranslationLoss (line 128) | class ScaleTranslationLoss(nn.Module):
method __init__ (line 130) | def __init__(self, init_joints_idxs, trans_estimation=None,
method reset_loss_weights (line 153) | def reset_loss_weights(self, loss_weight_dict):
method forward (line 162) | def forward(self, camera, joint_cam, joint_img, hand_translation, hand...
FILE: common/utils/mano.py
class MANO (line 12) | class MANO(object):
method __init__ (line 13) | def __init__(self):
method get_layer (line 38) | def get_layer(self):
FILE: common/utils/manopth/mano/webuser/lbs.py
function global_rigid_transformation (line 27) | def global_rigid_transformation(pose, J, kintree_table, xp):
function verts_core (line 68) | def verts_core(pose, v, J, weights, kintree_table, want_Jtr=False, xp=ch...
FILE: common/utils/manopth/mano/webuser/posemapper.py
class Rodrigues (line 27) | class Rodrigues(ch.Ch):
method compute_r (line 30) | def compute_r(self):
method compute_dr_wrt (line 33) | def compute_dr_wrt(self, wrt):
function lrotmin (line 38) | def lrotmin(p):
function posemap (line 51) | def posemap(s):
FILE: common/utils/manopth/mano/webuser/serialization.py
function ready_arguments (line 31) | def ready_arguments(fname_or_dict):
function load_model (line 73) | def load_model(fname_or_dict):
FILE: common/utils/manopth/mano/webuser/smpl_handpca_wrapper_HAND_only.py
function ready_arguments (line 22) | def ready_arguments(fname_or_dict, posekey4vposed='pose'):
function load_model (line 70) | def load_model(fname_or_dict, ncomps=6, flat_hand_mean=False, v_template...
FILE: common/utils/manopth/mano/webuser/verts.py
function ischumpy (line 29) | def ischumpy(x):
function verts_decorated (line 33) | def verts_decorated(trans,
function verts_core (line 107) | def verts_core(pose,
FILE: common/utils/manopth/manopth/argutils.py
function print_args (line 8) | def print_args(args):
function save_args (line 16) | def save_args(args, save_folder, opt_prefix='opt', verbose=True):
FILE: common/utils/manopth/manopth/demo.py
function generate_random_hand (line 10) | def generate_random_hand(batch_size=1, ncomps=6, mano_root='mano/models'):
function display_hand (line 18) | def display_hand(hand_info, mano_faces=None, ax=None, alpha=0.2, batch_i...
function cam_equal_aspect_3d (line 43) | def cam_equal_aspect_3d(ax, verts, flip_x=False):
FILE: common/utils/manopth/manopth/manolayer.py
class ManoLayer (line 13) | class ManoLayer(Module):
method __init__ (line 19) | def __init__(self,
method forward (line 110) | def forward(self,
FILE: common/utils/manopth/manopth/rodrigues_layer.py
function quat2mat (line 15) | def quat2mat(quat):
function batch_rodrigues (line 43) | def batch_rodrigues(axisang):
function th_get_axis_angle (line 57) | def th_get_axis_angle(vector):
FILE: common/utils/manopth/manopth/rot6d.py
function compute_rotation_matrix_from_ortho6d (line 4) | def compute_rotation_matrix_from_ortho6d(poses):
function robust_compute_rotation_matrix_from_ortho6d (line 26) | def robust_compute_rotation_matrix_from_ortho6d(poses):
function normalize_vector (line 54) | def normalize_vector(v):
function cross_product (line 63) | def cross_product(u, v):
FILE: common/utils/manopth/manopth/rotproj.py
function batch_rotprojs (line 4) | def batch_rotprojs(batches_rotmats):
FILE: common/utils/manopth/manopth/tensutils.py
function th_posemap_axisang (line 6) | def th_posemap_axisang(pose_vectors):
function th_with_zeros (line 15) | def th_with_zeros(tensor):
function th_pack (line 25) | def th_pack(tensor):
function subtract_flat_id (line 34) | def subtract_flat_id(rot_mats):
function make_list (line 45) | def make_list(tensor):
FILE: common/utils/manopth/setup.py
function check_dependencies (line 8) | def check_dependencies():
FILE: common/utils/manopth/test/test_demo.py
function test_generate_random_hand (line 6) | def test_generate_random_hand():
FILE: common/utils/optimizers/lbfgs_ls.py
function _cubic_interpolate (line 11) | def _cubic_interpolate(x1, f1, g1, x2, f2, g2, bounds=None):
function _strong_Wolfe (line 39) | def _strong_Wolfe(obj_func, x, t, d, f, g, gtd, c1=1e-4, c2=0.9, toleran...
class LBFGS (line 172) | class LBFGS(Optimizer):
method __init__ (line 199) | def __init__(self, params, lr=1, max_iter=20, max_eval=None,
method _numel (line 216) | def _numel(self):
method _gather_flat_grad (line 221) | def _gather_flat_grad(self):
method _add_grad (line 233) | def _add_grad(self, step_size, update):
method _clone_param (line 242) | def _clone_param(self):
method _set_param (line 245) | def _set_param(self, params_data):
method _directional_evaluate (line 249) | def _directional_evaluate(self, closure, x, t, d):
method step (line 256) | def step(self, closure):
FILE: common/utils/optimizers/optim_factory.py
function create_optimizer (line 27) | def create_optimizer(parameters, optim_type='lbfgs',
FILE: common/utils/preprocessing.py
function load_img (line 8) | def load_img(path, order='RGB'):
function get_bbox (line 19) | def get_bbox(joint_img, joint_valid, expansion_factor=1.0):
function process_bbox (line 36) | def process_bbox(bbox, img_width, img_height, expansion_factor=1.25):
function get_aug_config (line 65) | def get_aug_config():
function augmentation (line 79) | def augmentation(img, bbox, data_split, do_flip=False):
function generate_patch_image (line 89) | def generate_patch_image(cvimg, bbox, scale, rot, do_flip, out_shape):
function rotate_2d (line 109) | def rotate_2d(pt_2d, rot_rad):
function gen_trans_from_patch_cv (line 117) | def gen_trans_from_patch_cv(c_x, c_y, src_width, src_height, dst_width, ...
FILE: common/utils/transforms.py
function cam2pixel (line 5) | def cam2pixel(cam_coord, f, c):
function pixel2cam (line 11) | def pixel2cam(pixel_coord, f, c):
function world2cam (line 17) | def world2cam(world_coord, R, t):
function cam2world (line 21) | def cam2world(cam_coord, R, t):
function rigid_transform_3D (line 25) | def rigid_transform_3D(A, B):
function rigid_align (line 43) | def rigid_align(A, B):
function transform_joint_to_other_db (line 48) | def transform_joint_to_other_db(src_joint, src_name, dst_name):
FILE: common/utils/vis.py
function vis_keypoints_with_skeleton (line 11) | def vis_keypoints_with_skeleton(img, kps, kps_lines, kp_thresh=0.4, alph...
function vis_keypoints (line 42) | def vis_keypoints(img, kps, alpha=1):
function vis_mesh (line 59) | def vis_mesh(img, mesh_vertex, alpha=0.5):
function vis_3d_skeleton (line 76) | def vis_3d_skeleton(kpt_3d, kpt_3d_vis, kps_lines, filename=None):
function save_obj (line 115) | def save_obj(v, f, file_name='output.obj'):
function render_mesh (line 123) | def render_mesh(img, mesh, face, cam_param):
FILE: data/DEX_YCB/DEX_YCB.py
class DEX_YCB (line 43) | class DEX_YCB(torch.utils.data.Dataset):
method __init__ (line 44) | def __init__(self, transform, data_split):
method load_data (line 55) | def load_data(self):
method __len__ (line 148) | def __len__(self):
method __getitem__ (line 151) | def __getitem__(self, idx):
method evaluate (line 212) | def evaluate(self, outs, cur_sample_idx):
method print_eval_result (line 245) | def print_eval_result(self, test_epoch):
FILE: data/HO3D/HO3D.py
class HO3D (line 18) | class HO3D(torch.utils.data.Dataset):
method __init__ (line 19) | def __init__(self, transform, data_split):
method load_data (line 31) | def load_data(self):
method __len__ (line 75) | def __len__(self):
method __getitem__ (line 78) | def __getitem__(self, idx):
method evaluate (line 129) | def evaluate(self, outs, cur_sample_idx):
method print_eval_result (line 155) | def print_eval_result(self, test_epoch):
FILE: demo/demo.py
function parse_args (line 21) | def parse_args():
FILE: demo/demo_fitting.py
function parse_args (line 26) | def parse_args():
function load_camera (line 45) | def load_camera(cam_path, cam_idx='0'):
FILE: main/config.py
class Config (line 6) | class Config:
method set_args (line 55) | def set_args(self, gpu_ids, continue_train=False):
FILE: main/model.py
class Model (line 14) | class Model(nn.Module):
method __init__ (line 15) | def __init__(self, backbone, FIT, SET, regressor):
method forward (line 25) | def forward(self, inputs, targets, meta_info, mode):
method get_mesh_scale_trans (line 59) | def get_mesh_scale_trans(self, pred_joint_img, pred_joint_cam, init_sc...
function init_weights (line 107) | def init_weights(m):
function get_model (line 120) | def get_model(mode):
FILE: main/test.py
function parse_args (line 9) | def parse_args():
function main (line 27) | def main():
FILE: main/train.py
function parse_args (line 7) | def parse_args():
function main (line 24) | def main():
Condensed preview — 55 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (331K chars).
[
{
"path": ".gitignore",
"chars": 2794,
"preview": "# Created by .ignore support plugin (hsz.mobi)\n### Python template\n# Byte-compiled / optimized / DLL files\n__pycache__/\n"
},
{
"path": "README.md",
"chars": 5774,
"preview": "# HandOccNet: Occlusion-Robust 3D Hand Mesh Estimation Network\n\n## Introduction\nThis repository is the offical [Pytorch]"
},
{
"path": "common/base.py",
"chars": 5124,
"preview": "import os\nimport os.path as osp\nimport math\nimport time\nimport glob\nimport abc\nfrom torch.utils.data import DataLoader\ni"
},
{
"path": "common/logger.py",
"chars": 1392,
"preview": "import logging\nimport os\n\nOK = '\\033[92m'\nWARNING = '\\033[93m'\nFAIL = '\\033[91m'\nEND = '\\033[0m'\n\nPINK = '\\033[95m'\nBLUE"
},
{
"path": "common/nets/backbone.py",
"chars": 6810,
"preview": "import torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.model_zoo as model_zoo\n\nfrom torchvision import"
},
{
"path": "common/nets/cbam.py",
"chars": 3870,
"preview": "import torch\nimport math\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass BasicConv(nn.Module):\n def __in"
},
{
"path": "common/nets/hand_head.py",
"chars": 10308,
"preview": "import torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nclass hand_regHead(nn.Module):\n def __init__(self,"
},
{
"path": "common/nets/mano_head.py",
"chars": 8550,
"preview": "import torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom utils.mano import MANO\nmano = MANO()\n\ndef ba"
},
{
"path": "common/nets/regressor.py",
"chars": 767,
"preview": "import torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom utils.mano import MANO\nfrom nets.hand_head "
},
{
"path": "common/nets/transformer.py",
"chars": 5938,
"preview": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom einops import repeat\n\nclass Transformer(nn.Modul"
},
{
"path": "common/timer.py",
"chars": 1088,
"preview": "# --------------------------------------------------------\n# Fast R-CNN\n# Copyright (c) 2015 Microsoft\n# Licensed under "
},
{
"path": "common/utils/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "common/utils/camera.py",
"chars": 4906,
"preview": "# -*- coding: utf-8 -*-\n\n# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is\n# holder of all propri"
},
{
"path": "common/utils/dir.py",
"chars": 209,
"preview": "import os\nimport sys\n\ndef make_folder(folder_name):\n if not os.path.exists(folder_name):\n os.makedirs(folder_n"
},
{
"path": "common/utils/fitting.py",
"chars": 5925,
"preview": "import numpy as np\nimport torch\nimport torch.nn as nn\n\n\n\ndef to_tensor(tensor, dtype=torch.float32):\n if torch.Tensor"
},
{
"path": "common/utils/mano.py",
"chars": 2413,
"preview": "import numpy as np\nimport torch\nimport os.path as osp\nimport json\nfrom config import cfg\n\nimport sys\nsys.path.insert(0, "
},
{
"path": "common/utils/manopth/.gitignore",
"chars": 118,
"preview": "*.sw*\n*.bak\n*_bak.py\n\n.cache/\n__pycache__/\nbuild/\ndist/\nmanopth_hassony2.egg-info/\n\nmano/models\nassets/mano_layer.svg\n"
},
{
"path": "common/utils/manopth/LICENSE",
"chars": 35149,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "common/utils/manopth/README.md",
"chars": 5362,
"preview": "Manopth\n=======\n\n[MANO](http://mano.is.tue.mpg.de) layer for [PyTorch](https://pytorch.org/) (tested with v0.4 and v1.x)"
},
{
"path": "common/utils/manopth/environment.yml",
"chars": 167,
"preview": "name: manopth\n\ndependencies:\n - opencv\n - python=3.7\n - matplotlib\n - numpy\n - pytorch\n - tqdm\n - git\n - pip:\n "
},
{
"path": "common/utils/manopth/examples/manopth_demo.py",
"chars": 3190,
"preview": "import argparse\n\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport torch\nfrom tqdm imp"
},
{
"path": "common/utils/manopth/examples/manopth_mindemo.py",
"chars": 725,
"preview": "import torch\nfrom manopth.manolayer import ManoLayer\nfrom manopth import demo\n\nbatch_size = 10\n# Select number of princi"
},
{
"path": "common/utils/manopth/mano/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "common/utils/manopth/mano/webuser/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "common/utils/manopth/mano/webuser/lbs.py",
"chars": 2761,
"preview": "'''\nCopyright 2017 Javier Romero, Dimitrios Tzionas, Michael J Black and the Max Planck Gesellschaft. All rights reserv"
},
{
"path": "common/utils/manopth/mano/webuser/posemapper.py",
"chars": 1528,
"preview": "'''\nCopyright 2017 Javier Romero, Dimitrios Tzionas, Michael J Black and the Max Planck Gesellschaft. All rights reserv"
},
{
"path": "common/utils/manopth/mano/webuser/serialization.py",
"chars": 2860,
"preview": "'''\nCopyright 2017 Javier Romero, Dimitrios Tzionas, Michael J Black and the Max Planck Gesellschaft. All rights reserv"
},
{
"path": "common/utils/manopth/mano/webuser/smpl_handpca_wrapper_HAND_only.py",
"chars": 5103,
"preview": "'''\nCopyright 2017 Javier Romero, Dimitrios Tzionas, Michael J Black and the Max Planck Gesellschaft. All rights reserv"
},
{
"path": "common/utils/manopth/mano/webuser/verts.py",
"chars": 3423,
"preview": "'''\nCopyright 2017 Javier Romero, Dimitrios Tzionas, Michael J Black and the Max Planck Gesellschaft. All rights reserv"
},
{
"path": "common/utils/manopth/manopth/__init__.py",
"chars": 17,
"preview": "name = 'manopth'\n"
},
{
"path": "common/utils/manopth/manopth/argutils.py",
"chars": 1806,
"preview": "import datetime\nimport os\nimport pickle\nimport subprocess\nimport sys\n\n\ndef print_args(args):\n opts = vars(args)\n p"
},
{
"path": "common/utils/manopth/manopth/demo.py",
"chars": 2100,
"preview": "from matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d.art3d import Poly"
},
{
"path": "common/utils/manopth/manopth/manolayer.py",
"chars": 12161,
"preview": "import os\n\nimport numpy as np\nimport torch\nfrom torch.nn import Module\n\nfrom mano.webuser.smpl_handpca_wrapper_HAND_only"
},
{
"path": "common/utils/manopth/manopth/rodrigues_layer.py",
"chars": 2920,
"preview": "\"\"\"\nThis part reuses code from https://github.com/MandyMo/pytorch_HMR/blob/master/src/util.py\nwhich is part of a PyTorch"
},
{
"path": "common/utils/manopth/manopth/rot6d.py",
"chars": 2212,
"preview": "import torch\n\n\ndef compute_rotation_matrix_from_ortho6d(poses):\n \"\"\"\n Code from\n https://github.com/papagina/Ro"
},
{
"path": "common/utils/manopth/manopth/rotproj.py",
"chars": 753,
"preview": "import torch\n\n\ndef batch_rotprojs(batches_rotmats):\n proj_rotmats = []\n for batch_idx, batch_rotmats in enumerate("
},
{
"path": "common/utils/manopth/manopth/tensutils.py",
"chars": 1341,
"preview": "import torch\n\nfrom manopth import rodrigues_layer\n\n\ndef th_posemap_axisang(pose_vectors):\n rot_nb = int(pose_vectors."
},
{
"path": "common/utils/manopth/setup.py",
"chars": 1344,
"preview": "from setuptools import find_packages, setup\nimport warnings\n\nDEPENDENCY_PACKAGE_NAMES = [\"matplotlib\", \"torch\", \"tqdm\", "
},
{
"path": "common/utils/manopth/test/test_demo.py",
"chars": 342,
"preview": "import torch\n\nfrom manopth.demo import generate_random_hand\n\n\ndef test_generate_random_hand():\n batch_size = 3\n ha"
},
{
"path": "common/utils/optimizers/__init__.py",
"chars": 739,
"preview": "# -*- coding: utf-8 -*-\n\n# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is\n# holder of all propri"
},
{
"path": "common/utils/optimizers/lbfgs_ls.py",
"chars": 16686,
"preview": "# PyTorch implementation of L-BFGS with Strong Wolfe line search\n# Will be removed once https://github.com/pytorch/pytor"
},
{
"path": "common/utils/optimizers/optim_factory.py",
"chars": 2546,
"preview": "# -*- coding: utf-8 -*-\n\n# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is\n# holder of all propri"
},
{
"path": "common/utils/preprocessing.py",
"chars": 5078,
"preview": "import numpy as np\nimport cv2\nimport random\nfrom config import cfg\nimport math\nimport torchvision\n\ndef load_img(path, or"
},
{
"path": "common/utils/transforms.py",
"chars": 1890,
"preview": "import torch\nimport numpy as np\nfrom config import cfg\n\ndef cam2pixel(cam_coord, f, c):\n x = cam_coord[:,0] / cam_coo"
},
{
"path": "common/utils/vis.py",
"chars": 6008,
"preview": "import os\nimport cv2\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport m"
},
{
"path": "data/DEX_YCB/DEX_YCB.py",
"chars": 17454,
"preview": "import os\nimport os.path as osp\nimport numpy as np\nimport torch\nimport cv2\nimport random\nimport json\nimport math\nimport "
},
{
"path": "data/HO3D/HO3D.py",
"chars": 7833,
"preview": "import os\nimport os.path as osp\nimport numpy as np\nimport torch\nimport cv2\nimport random\nimport json\nimport math\nimport "
},
{
"path": "demo/demo.py",
"chars": 2611,
"preview": "import sys\nimport os\nimport os.path as osp\nimport argparse\nimport numpy as np\nimport cv2\nimport torch\nimport torchvision"
},
{
"path": "demo/demo_fitting.py",
"chars": 6985,
"preview": "import sys\nimport glob\nimport os\nimport os.path as osp\nimport argparse\nimport json\nimport numpy as np\nimport cv2\nimport "
},
{
"path": "demo/output.obj",
"chars": 87833,
"preview": "v 0.09704167395830154 0.0123032471165061 0.039412785321474075\nv 0.09976062923669815 0.010310064069926739 0.0295864623039"
},
{
"path": "main/config.py",
"chars": 1990,
"preview": "import os\nimport os.path as osp\nimport sys\nimport numpy as np\n\nclass Config:\n \n ## dataset\n # HO3D, DEX_YCB\n "
},
{
"path": "main/model.py",
"chars": 5686,
"preview": "import torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom nets.backbone import FPN\nfrom nets.transfor"
},
{
"path": "main/test.py",
"chars": 1597,
"preview": "import torch\nimport argparse\nfrom tqdm import tqdm\nimport numpy as np\nimport torch.backends.cudnn as cudnn\nfrom config i"
},
{
"path": "main/train.py",
"chars": 2592,
"preview": "import argparse\nfrom config import cfg\nimport torch\nfrom base import Trainer\nimport torch.backends.cudnn as cudnn\n\ndef p"
},
{
"path": "requiremets.sh",
"chars": 115,
"preview": "pip install numpy==1.17.4 torch==1.9.1 torchvision==0.10.1 einops chumpy opencv-python pycocotools pyrender tqdm\n\n\n"
}
]
About this extraction
This page contains the full source code of the namepllet/HandOccNet GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 55 files (311.4 KB), approximately 106.2k tokens, and a symbol index with 235 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.