Spaces:
Running
Running
Sapphire-356
commited on
Commit
•
95f8bbc
1
Parent(s):
561c4ea
add: Video2MC
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitignore +200 -0
- HPE2keyframes.py +323 -0
- LICENSE +674 -0
- common/arguments.py +102 -0
- common/camera.py +107 -0
- common/generators.py +425 -0
- common/h36m_dataset.py +258 -0
- common/humaneva_dataset.py +122 -0
- common/inference_3d.py +107 -0
- common/jpt_arguments.py +92 -0
- common/loss.py +94 -0
- common/mocap_dataset.py +40 -0
- common/model.py +200 -0
- common/quaternion.py +36 -0
- common/skeleton.py +88 -0
- common/utils.py +202 -0
- common/visualization.py +251 -0
- data/data_utils.py +110 -0
- data/prepare_2d_kpt.py +45 -0
- data/prepare_data_2d_h36m_generic.py +108 -0
- data/prepare_data_2d_h36m_sh.py +112 -0
- data/prepare_data_h36m.py +142 -0
- data/prepare_data_humaneva.py +242 -0
- joints_detectors/Alphapose/.gitignore +29 -0
- joints_detectors/Alphapose/LICENSE +515 -0
- joints_detectors/Alphapose/README.md +112 -0
- joints_detectors/Alphapose/SPPE/.gitattributes +2 -0
- joints_detectors/Alphapose/SPPE/.gitignore +114 -0
- joints_detectors/Alphapose/SPPE/LICENSE +21 -0
- joints_detectors/Alphapose/SPPE/README.md +1 -0
- joints_detectors/Alphapose/SPPE/__init__.py +0 -0
- joints_detectors/Alphapose/SPPE/src/__init__.py +0 -0
- joints_detectors/Alphapose/SPPE/src/main_fast_inference.py +67 -0
- joints_detectors/Alphapose/SPPE/src/models/FastPose.py +35 -0
- joints_detectors/Alphapose/SPPE/src/models/__init__.py +1 -0
- joints_detectors/Alphapose/SPPE/src/models/hg-prm.py +126 -0
- joints_detectors/Alphapose/SPPE/src/models/hgPRM.py +236 -0
- joints_detectors/Alphapose/SPPE/src/models/layers/DUC.py +23 -0
- joints_detectors/Alphapose/SPPE/src/models/layers/PRM.py +135 -0
- joints_detectors/Alphapose/SPPE/src/models/layers/Residual.py +54 -0
- joints_detectors/Alphapose/SPPE/src/models/layers/Resnet.py +82 -0
- joints_detectors/Alphapose/SPPE/src/models/layers/SE_Resnet.py +99 -0
- joints_detectors/Alphapose/SPPE/src/models/layers/SE_module.py +19 -0
- joints_detectors/Alphapose/SPPE/src/models/layers/__init__.py +1 -0
- joints_detectors/Alphapose/SPPE/src/models/layers/util_models.py +37 -0
- joints_detectors/Alphapose/SPPE/src/opt.py +102 -0
- joints_detectors/Alphapose/SPPE/src/utils/__init__.py +1 -0
- joints_detectors/Alphapose/SPPE/src/utils/dataset/.coco.py.swp +0 -0
- joints_detectors/Alphapose/SPPE/src/utils/dataset/__init__.py +0 -0
- joints_detectors/Alphapose/SPPE/src/utils/dataset/coco.py +85 -0
.gitignore
ADDED
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
|
2 |
+
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
3 |
+
|
4 |
+
# User-specific stuff
|
5 |
+
.idea/**/workspace.xml
|
6 |
+
.idea/**/tasks.xml
|
7 |
+
.idea/**/usage.statistics.xml
|
8 |
+
.idea/**/dictionaries
|
9 |
+
.idea/**/shelf
|
10 |
+
|
11 |
+
# Generated files
|
12 |
+
.idea/**/contentModel.xml
|
13 |
+
|
14 |
+
# Sensitive or high-churn files
|
15 |
+
.idea/**/dataSources/
|
16 |
+
.idea/**/dataSources.ids
|
17 |
+
.idea/**/dataSources.local.xml
|
18 |
+
.idea/**/sqlDataSources.xml
|
19 |
+
.idea/**/dynamic.xml
|
20 |
+
.idea/**/uiDesigner.xml
|
21 |
+
.idea/**/dbnavigator.xml
|
22 |
+
|
23 |
+
# Gradle
|
24 |
+
.idea/**/gradle.xml
|
25 |
+
.idea/**/libraries
|
26 |
+
|
27 |
+
# Secret
|
28 |
+
.idea/**/deployment.xml
|
29 |
+
.idea/**/remote-mappings.xml
|
30 |
+
|
31 |
+
# Gradle and Maven with auto-import
|
32 |
+
# When using Gradle or Maven with auto-import, you should exclude module files,
|
33 |
+
# since they will be recreated, and may cause churn. Uncomment if using
|
34 |
+
# auto-import.
|
35 |
+
# .idea/modules.xml
|
36 |
+
# .idea/*.iml
|
37 |
+
# .idea/modules
|
38 |
+
# *.iml
|
39 |
+
# *.ipr
|
40 |
+
|
41 |
+
# CMake
|
42 |
+
cmake-build-*/
|
43 |
+
|
44 |
+
# Mongo Explorer plugin
|
45 |
+
.idea/**/mongoSettings.xml
|
46 |
+
|
47 |
+
# File-based project format
|
48 |
+
*.iws
|
49 |
+
|
50 |
+
# IntelliJ
|
51 |
+
out/
|
52 |
+
|
53 |
+
# mpeltonen/sbt-idea plugin
|
54 |
+
.idea_modules/
|
55 |
+
|
56 |
+
# JIRA plugin
|
57 |
+
atlassian-ide-plugin.xml
|
58 |
+
|
59 |
+
# Cursive Clojure plugin
|
60 |
+
.idea/replstate.xml
|
61 |
+
|
62 |
+
# Crashlytics plugin (for Android Studio and IntelliJ)
|
63 |
+
com_crashlytics_export_strings.xml
|
64 |
+
crashlytics.properties
|
65 |
+
crashlytics-build.properties
|
66 |
+
fabric.properties
|
67 |
+
|
68 |
+
# Editor-based Rest Client
|
69 |
+
.idea/httpRequests
|
70 |
+
|
71 |
+
# Android studio 3.1+ serialized cache file
|
72 |
+
.idea/caches/build_file_checksums.ser
|
73 |
+
|
74 |
+
checkpoint/*
|
75 |
+
outputs/*
|
76 |
+
data/data_3d_h36m.npz
|
77 |
+
data/own2DFiles/*
|
78 |
+
|
79 |
+
|
80 |
+
|
81 |
+
__pycache__/
|
82 |
+
*.py[cod]
|
83 |
+
|
84 |
+
|
85 |
+
*.pyc
|
86 |
+
.ipynb_checkpoints/
|
87 |
+
*.gif
|
88 |
+
*.jpg
|
89 |
+
*.png
|
90 |
+
*.npz
|
91 |
+
*.zip
|
92 |
+
*.json
|
93 |
+
*.mp4
|
94 |
+
*.tar
|
95 |
+
*.pth
|
96 |
+
*.weights
|
97 |
+
*.avi
|
98 |
+
*.caffemodel
|
99 |
+
*.npy
|
100 |
+
|
101 |
+
|
102 |
+
/st_gcn
|
103 |
+
/outputs
|
104 |
+
/nohub*
|
105 |
+
/VideoSave
|
106 |
+
/ActionRecognition
|
107 |
+
/work_dir
|
108 |
+
|
109 |
+
|
110 |
+
|
111 |
+
|
112 |
+
|
113 |
+
|
114 |
+
__pycache__/
|
115 |
+
*.py[cod]
|
116 |
+
*$py.class
|
117 |
+
*.so
|
118 |
+
|
119 |
+
eggs/
|
120 |
+
.eggs/
|
121 |
+
*.egg-info/
|
122 |
+
.installed.cfg
|
123 |
+
*.egg
|
124 |
+
|
125 |
+
# PyInstaller
|
126 |
+
# Usually these files are written by a python script from a template
|
127 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
128 |
+
*.manifest
|
129 |
+
*.spec
|
130 |
+
|
131 |
+
# Unit test / coverage reports
|
132 |
+
htmlcov/
|
133 |
+
.tox/
|
134 |
+
.coverage
|
135 |
+
.coverage.*
|
136 |
+
.cache
|
137 |
+
nosetests.xml
|
138 |
+
coverage.xml
|
139 |
+
*.cover
|
140 |
+
.hypothesis/
|
141 |
+
|
142 |
+
# Translations
|
143 |
+
*.mo
|
144 |
+
*.pot
|
145 |
+
|
146 |
+
# Django stuff:
|
147 |
+
*.log
|
148 |
+
|
149 |
+
# Flask stuff:
|
150 |
+
instance/
|
151 |
+
.webassets-cache
|
152 |
+
|
153 |
+
# Scrapy stuff:
|
154 |
+
.scrapy
|
155 |
+
|
156 |
+
# Sphinx documentation
|
157 |
+
|
158 |
+
# PyBuilder
|
159 |
+
target/
|
160 |
+
|
161 |
+
# Jupyter Notebook
|
162 |
+
.ipynb_checkpoints
|
163 |
+
|
164 |
+
# pyenv
|
165 |
+
.python-version
|
166 |
+
|
167 |
+
# celery beat schedule file
|
168 |
+
celerybeat-schedule
|
169 |
+
|
170 |
+
# SageMath parsed files
|
171 |
+
*.sage.py
|
172 |
+
|
173 |
+
# dotenv
|
174 |
+
.env
|
175 |
+
|
176 |
+
# virtualenv
|
177 |
+
.venv
|
178 |
+
venv/
|
179 |
+
ENV/
|
180 |
+
|
181 |
+
# Spyder project settings
|
182 |
+
.spyderproject
|
183 |
+
.spyproject
|
184 |
+
|
185 |
+
# Rope project settings
|
186 |
+
.ropeproject
|
187 |
+
|
188 |
+
# mkdocs documentation
|
189 |
+
/site
|
190 |
+
|
191 |
+
# mypy
|
192 |
+
.mypy_cache/
|
193 |
+
|
194 |
+
# Self-defined files
|
195 |
+
/local_test/
|
196 |
+
/lab_processing/
|
197 |
+
|
198 |
+
|
199 |
+
inputs/
|
200 |
+
*.miframes
|
HPE2keyframes.py
ADDED
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import matplotlib.pyplot as plt
|
3 |
+
import pickle
|
4 |
+
import torch
|
5 |
+
import torch.nn.functional as F
|
6 |
+
from scipy.spatial.transform import Rotation
|
7 |
+
from scipy.ndimage import binary_erosion, binary_dilation
|
8 |
+
|
9 |
+
import os
|
10 |
+
import json
|
11 |
+
|
12 |
+
|
13 |
+
|
14 |
+
def euler_angles_smooth(XYZ_euler_angles):
|
15 |
+
|
16 |
+
if XYZ_euler_angles.ndim == 1:
|
17 |
+
XYZ_euler_angles = XYZ_euler_angles[:, np.newaxis]
|
18 |
+
|
19 |
+
for i in range(XYZ_euler_angles.shape[0]-1):
|
20 |
+
for j in range(XYZ_euler_angles.shape[1]):
|
21 |
+
# smooth
|
22 |
+
if XYZ_euler_angles[i+1, j] - XYZ_euler_angles[i, j] > 180:
|
23 |
+
XYZ_euler_angles[i+1:, j] = XYZ_euler_angles[i+1:, j] - 360
|
24 |
+
elif XYZ_euler_angles[i+1, j] - XYZ_euler_angles[i, j] < -180:
|
25 |
+
XYZ_euler_angles[i+1:, j] = XYZ_euler_angles[i+1:, j] + 360
|
26 |
+
|
27 |
+
return np.squeeze(XYZ_euler_angles)
|
28 |
+
|
29 |
+
|
30 |
+
|
31 |
+
def xyz2euler_body(xyz, xyz_body_frame, X_dir=1.0, Y_dir=1.0):
|
32 |
+
'''
|
33 |
+
xyz: Coordinates from 3D human pose estimation. Each dimension: (frame, 3, xyz)
|
34 |
+
xyz_body_frame: Coordinates of body frame. Used to calculate the Y direction rotation of body.
|
35 |
+
X_dir: -1.0 for arm and body.
|
36 |
+
Y_dir: -1.0 for body and head.
|
37 |
+
'''
|
38 |
+
|
39 |
+
# swap y and z to align the coordinate in the mine-imator
|
40 |
+
xyz[:, :, [1, 2]] = xyz[:, :, [2, 1]]
|
41 |
+
xyz[:, :, 0] = -xyz[:, :, 0]
|
42 |
+
xyz_body_frame[:, :, [1, 2]] = xyz_body_frame[:, :, [2, 1]]
|
43 |
+
xyz_body_frame[:, :, 0] = -xyz_body_frame[:, :, 0]
|
44 |
+
|
45 |
+
p0, p1, p2 = torch.unbind(xyz, dim=1)
|
46 |
+
p1_, p4_, p14_, p11_ = torch.unbind(xyz_body_frame, dim=1)
|
47 |
+
|
48 |
+
# solve the cosine pose matrix
|
49 |
+
Y = (p0 - p1) * Y_dir
|
50 |
+
arm = p2 - p1
|
51 |
+
|
52 |
+
Y = F.normalize(Y, dim=1)
|
53 |
+
X = F.normalize(p11_ + p4_ - p1_ - p14_, dim=1)
|
54 |
+
# X = F.normalize(torch.cross(X_dir*arm, Y), dim=1) # TODO smooth
|
55 |
+
Z = F.normalize(torch.cross(X, Y), dim=1)
|
56 |
+
|
57 |
+
cos_pose_matrix = torch.stack([X, Y, Z], dim=2)
|
58 |
+
r = Rotation.from_matrix(cos_pose_matrix)
|
59 |
+
YXZ_euler_angles = r.as_euler("YXZ", degrees=True)
|
60 |
+
|
61 |
+
# bend
|
62 |
+
bend = -(Y * F.normalize(arm, dim=1)).sum(dim=1) * Y_dir
|
63 |
+
bend = torch.rad2deg(torch.acos(bend))
|
64 |
+
|
65 |
+
# swap xyz
|
66 |
+
YXZ_euler_angles[:, [0, 1, 2]] = YXZ_euler_angles[:, [1, 0, 2]]
|
67 |
+
XYZ_euler_angles = YXZ_euler_angles
|
68 |
+
|
69 |
+
# arm cos_pose_matrix
|
70 |
+
Y_arm = F.normalize(arm, dim=1)
|
71 |
+
X_arm = X
|
72 |
+
Z_arm = F.normalize(torch.cross(X_arm, Y_arm), dim=1)
|
73 |
+
cos_pose_matrix_arm = torch.stack([X_arm, Y_arm, Z_arm], dim=2)
|
74 |
+
|
75 |
+
# avoid abrupt changes in angle
|
76 |
+
XYZ_euler_angles = euler_angles_smooth(XYZ_euler_angles)
|
77 |
+
bend = euler_angles_smooth(bend.numpy())
|
78 |
+
|
79 |
+
return XYZ_euler_angles, bend, cos_pose_matrix_arm
|
80 |
+
|
81 |
+
|
82 |
+
def xyz2euler_relative(xyz, cos_body, X_dir=1.0, Y_dir=1.0, head=False, leg=False, euler_body=None):
|
83 |
+
'''
|
84 |
+
xyz: Coordinates from 3D human pose estimation. Each dimension: (frame, 3, xyz)
|
85 |
+
X_dir: -1.0 for arm and body.
|
86 |
+
Y_dir: -1.0 for body and head.
|
87 |
+
'''
|
88 |
+
|
89 |
+
# swap y and z to align the coordinate in the mine-imator
|
90 |
+
xyz[:, :, [1, 2]] = xyz[:, :, [2, 1]]
|
91 |
+
xyz[:, :, 0] = -xyz[:, :, 0]
|
92 |
+
p0, p1, p2 = torch.unbind(xyz, dim=1)
|
93 |
+
|
94 |
+
# solve the cosine pose matrix
|
95 |
+
Y = (p0 - p1) * Y_dir
|
96 |
+
arm = p2 - p1
|
97 |
+
|
98 |
+
Y = F.normalize(Y, dim=1)
|
99 |
+
X = F.normalize(torch.cross(X_dir*arm, Y), dim=1) # TODO smooth
|
100 |
+
Z = F.normalize(torch.cross(X, Y), dim=1)
|
101 |
+
|
102 |
+
cos_pose_matrix = torch.stack([X, Y, Z], dim=2)
|
103 |
+
|
104 |
+
if head == True:
|
105 |
+
Y_arm = F.normalize(arm, dim=1)
|
106 |
+
X_arm = X
|
107 |
+
Z_arm = F.normalize(torch.cross(X_arm, Y_arm), dim=1)
|
108 |
+
cos_pose_matrix = torch.stack([X_arm, Y_arm, Z_arm], dim=2)
|
109 |
+
|
110 |
+
# relative to the body rotation Y
|
111 |
+
if leg == True:
|
112 |
+
euler_body_Y = euler_body * 0
|
113 |
+
euler_body_Y[:, 0:1] = euler_body[:, 1:2]
|
114 |
+
r_body_Y = Rotation.from_euler("YXZ", euler_body_Y, degrees=True)
|
115 |
+
cos_body_Y = torch.from_numpy(r_body_Y.as_matrix())
|
116 |
+
|
117 |
+
# relative to the body
|
118 |
+
cos_relative = cos_body if leg == False else cos_body_Y.float()
|
119 |
+
cos_pose_matrix = cos_relative.permute(0, 2, 1) @ cos_pose_matrix
|
120 |
+
r = Rotation.from_matrix(cos_pose_matrix)
|
121 |
+
YXZ_euler_angles = r.as_euler("YXZ", degrees=True)
|
122 |
+
|
123 |
+
# bend
|
124 |
+
bend = -(Y * F.normalize(arm, dim=1)).sum(dim=1) * Y_dir
|
125 |
+
bend = torch.rad2deg(torch.acos(bend))
|
126 |
+
# if head == True:
|
127 |
+
# bend = bend * 0.5
|
128 |
+
|
129 |
+
# swap xyz
|
130 |
+
YXZ_euler_angles[:, [0, 1, 2]] = YXZ_euler_angles[:, [1, 0, 2]]
|
131 |
+
XYZ_euler_angles = YXZ_euler_angles
|
132 |
+
|
133 |
+
# avoid abrupt changes in angle
|
134 |
+
XYZ_euler_angles = euler_angles_smooth(XYZ_euler_angles)
|
135 |
+
bend = euler_angles_smooth(bend.numpy())
|
136 |
+
|
137 |
+
return XYZ_euler_angles, bend
|
138 |
+
|
139 |
+
|
140 |
+
def calculate_body_offset(euler_body, euler_right_leg, bend_right_leg, euler_left_leg, bend_left_leg, length_leg=[6, 6], prior=False):
|
141 |
+
'''
|
142 |
+
Calculate the offset of the body to make the movement more realistic.
|
143 |
+
First, determine the foot positions of both legs based on the actual
|
144 |
+
effect of Euler angle rotation in Mine-imator. Then, determine which
|
145 |
+
leg is currently touching the ground and fix the grounded leg. This
|
146 |
+
allows the calculation of the body offset.
|
147 |
+
|
148 |
+
'''
|
149 |
+
|
150 |
+
def calculate_leg_coordinates(r_body_Y, euler_leg, bend_leg, length_leg, right=True):
|
151 |
+
YXZ_euler_leg = euler_leg[:, [1, 0, 2]]
|
152 |
+
r1 = Rotation.from_euler("YXZ", YXZ_euler_leg, degrees=True)
|
153 |
+
m1 = r1.as_matrix()
|
154 |
+
X1 = m1[:, :, 0] # direction
|
155 |
+
Y1 = m1[:, :, 1] # vector to be rotated
|
156 |
+
r2 = Rotation.from_rotvec(X1*bend_leg[:, np.newaxis], degrees=True)
|
157 |
+
Y2 = r2.apply(Y1) # reconstruct the arm vector
|
158 |
+
coordinates = -(Y1 * length_leg[0] + Y2 * length_leg[1])
|
159 |
+
coordinates[:, 0] = coordinates[:, 0] - 2
|
160 |
+
coordinates = r_body_Y.apply(coordinates)
|
161 |
+
return coordinates
|
162 |
+
|
163 |
+
# calculate the endpoint coordinates of two legs
|
164 |
+
euler_body_Y = euler_body * 0
|
165 |
+
euler_body_Y[:, 0:1] = euler_body[:, 1:2]
|
166 |
+
r_body_Y = Rotation.from_euler("YXZ", euler_body_Y, degrees=True)
|
167 |
+
right_coordinates = calculate_leg_coordinates(r_body_Y, euler_right_leg, bend_right_leg, length_leg)
|
168 |
+
left_coordinates = calculate_leg_coordinates(r_body_Y, euler_left_leg, bend_left_leg, length_leg)
|
169 |
+
# stack, 0: right, 1: left
|
170 |
+
coordinates = np.stack([right_coordinates, left_coordinates], axis=1)
|
171 |
+
|
172 |
+
# determine which leg grounded, 0: right, 1: left
|
173 |
+
grounded_flag = (right_coordinates[:, 1] > left_coordinates[:, 1])*1
|
174 |
+
# prior knowledge: The more bended legs are not grounded
|
175 |
+
if prior == True:
|
176 |
+
grounded_flag_left = (bend_right_leg - bend_left_leg) > 30
|
177 |
+
grounded_flag_right = (bend_left_leg - bend_right_leg) > 30
|
178 |
+
grounded_flag += grounded_flag_left*1
|
179 |
+
grounded_flag *= (1 - grounded_flag_right)*1
|
180 |
+
# smoothing
|
181 |
+
grounded_flag = binary_erosion(grounded_flag, structure=np.ones(7))*1
|
182 |
+
grounded_flag = binary_dilation(grounded_flag, structure=np.ones(7))*1
|
183 |
+
|
184 |
+
body_POS = np.zeros_like(right_coordinates)
|
185 |
+
|
186 |
+
# POS_Y
|
187 |
+
ind = np.array(range(right_coordinates.shape[0]))
|
188 |
+
body_POS[:, 1] = -coordinates[ind, grounded_flag, 1]
|
189 |
+
|
190 |
+
# extract the X, Z coordinates of grounded leg in time t_1
|
191 |
+
X_t1 = coordinates[ind[:-1], grounded_flag[:-1], 0]
|
192 |
+
Z_t1 = coordinates[ind[:-1], grounded_flag[:-1], 2]
|
193 |
+
# extract the X, Z coordinates of grounded leg in time t_2
|
194 |
+
# note that the split of grounded_flag not changed
|
195 |
+
X_t2 = coordinates[ind[1:], grounded_flag[:-1], 0]
|
196 |
+
Z_t2 = coordinates[ind[1:], grounded_flag[:-1], 2]
|
197 |
+
|
198 |
+
# calculate the relative displacement between two frames
|
199 |
+
X_relative = X_t2 - X_t1
|
200 |
+
Z_relative = Z_t2 - Z_t1
|
201 |
+
|
202 |
+
# calculate the absolute displacement
|
203 |
+
X_abs = np.cumsum(X_relative)
|
204 |
+
Z_abs = np.cumsum(Z_relative)
|
205 |
+
|
206 |
+
body_POS[1:, 0] = -X_abs
|
207 |
+
body_POS[1:, 2] = -Z_abs
|
208 |
+
|
209 |
+
return body_POS
|
210 |
+
|
211 |
+
|
212 |
+
def add_keyframes(data, length, part_name, euler, bend, not_body=True, not_head=True, body_steve=False, body_POS=None):
|
213 |
+
for i in range(length):
|
214 |
+
if not_head:
|
215 |
+
keyframes_dict = {
|
216 |
+
"position": i,
|
217 |
+
"part_name": part_name,
|
218 |
+
"values": {
|
219 |
+
"ROT_X": float(euler[i][0]),
|
220 |
+
"ROT_Y": float(euler[i][2]), # Y, Z args in mine-imator miframes is exchanged. Maybe a bug.
|
221 |
+
"ROT_Z": float(euler[i][1]*not_body),
|
222 |
+
"BEND_ANGLE_X": float(bend[i])
|
223 |
+
}
|
224 |
+
}
|
225 |
+
else: # no bend
|
226 |
+
keyframes_dict = {
|
227 |
+
"position": i,
|
228 |
+
"part_name": part_name,
|
229 |
+
"values": {
|
230 |
+
"ROT_X": float(euler[i][0]),
|
231 |
+
"ROT_Y": float(euler[i][2]),
|
232 |
+
"ROT_Z": float(euler[i][1]),
|
233 |
+
}
|
234 |
+
}
|
235 |
+
if body_steve == True:
|
236 |
+
keyframes_dict = {
|
237 |
+
"position": i,
|
238 |
+
"values": {
|
239 |
+
"POS_X": float(body_POS[i][0]),
|
240 |
+
"POS_Y": float(body_POS[i][2]),
|
241 |
+
"POS_Z": float(body_POS[i][1]),
|
242 |
+
"ROT_Z": float(euler[i][1])
|
243 |
+
}
|
244 |
+
}
|
245 |
+
data["keyframes"].append(keyframes_dict)
|
246 |
+
|
247 |
+
print(f"add_key_frames: {part_name}")
|
248 |
+
|
249 |
+
|
250 |
+
def hpe2keyframes(HPE_filename, FPS_mine_imator, keyframes_filename, prior=True):
|
251 |
+
|
252 |
+
# read data
|
253 |
+
with open(HPE_filename, 'rb') as file:
|
254 |
+
data = np.load(file)
|
255 |
+
print(f"open file: {HPE_filename}")
|
256 |
+
xyz = data.copy()
|
257 |
+
length = xyz.shape[0]
|
258 |
+
|
259 |
+
# extract data from each body part
|
260 |
+
xyz_right_leg = torch.from_numpy(xyz[:, 1:4, :])
|
261 |
+
xyz_right_arm = torch.from_numpy(xyz[:, 14:17, :])
|
262 |
+
xyz_left_leg = torch.from_numpy(xyz[:, 4:7, :])
|
263 |
+
xyz_left_arm = torch.from_numpy(xyz[:, 11:14, :])
|
264 |
+
xyz_body = torch.from_numpy(xyz[:, [0, 7, 8], :])
|
265 |
+
xyz_body_frame = torch.from_numpy(xyz[:, [1, 4, 14, 11], :])
|
266 |
+
xyz_head = torch.from_numpy(xyz[:, [8, 9, 10], :])
|
267 |
+
|
268 |
+
# calculate the absolute euler angles of body
|
269 |
+
euler_body, bend_body, cos_pos_matrix = xyz2euler_body(xyz_body, xyz_body_frame, X_dir=-1, Y_dir=-1)
|
270 |
+
|
271 |
+
# calculate the relative euler angles of arm and head with respect to the body ROT_Y
|
272 |
+
euler_right_leg, bend_right_leg = xyz2euler_relative(xyz_right_leg, cos_pos_matrix, leg=True, euler_body=euler_body)
|
273 |
+
euler_left_leg, bend_left_leg = xyz2euler_relative(xyz_left_leg, cos_pos_matrix, leg=True, euler_body=euler_body)
|
274 |
+
|
275 |
+
# calculate the relative euler angles of arm and head with respect to the upper body
|
276 |
+
euler_right_arm, bend_right_arm = xyz2euler_relative(xyz_right_arm, cos_pos_matrix, X_dir=-1)
|
277 |
+
euler_left_arm, bend_left_arm = xyz2euler_relative(xyz_left_arm, cos_pos_matrix, X_dir=-1)
|
278 |
+
euler_head, bend_head = xyz2euler_relative(xyz_head, cos_pos_matrix, Y_dir=-1, head=True)
|
279 |
+
|
280 |
+
# create json format data
|
281 |
+
data = {
|
282 |
+
"format": 34,
|
283 |
+
"created_in": "2.0.0", # mine-imator version
|
284 |
+
"is_model": True,
|
285 |
+
"tempo": FPS_mine_imator, # FPS
|
286 |
+
"length": length, # keyframes length
|
287 |
+
"keyframes": [
|
288 |
+
],
|
289 |
+
"templates": [],
|
290 |
+
"timelines": [],
|
291 |
+
"resources": []
|
292 |
+
}
|
293 |
+
|
294 |
+
# relative offset makes the model more realistic
|
295 |
+
# caculate the relative offset based on Euler angle and bending angle
|
296 |
+
body_POS = calculate_body_offset(euler_body, euler_right_leg, bend_right_leg, euler_left_leg, bend_left_leg, prior=prior)
|
297 |
+
|
298 |
+
|
299 |
+
add_keyframes(data, length, "left_leg", euler_left_leg, bend_left_leg)
|
300 |
+
add_keyframes(data, length, "right_leg", euler_right_leg, bend_right_leg)
|
301 |
+
add_keyframes(data, length, "left_arm", euler_left_arm, bend_left_arm)
|
302 |
+
add_keyframes(data, length, "right_arm", euler_right_arm, bend_right_arm)
|
303 |
+
add_keyframes(data, length, "body", euler_body, bend_body, not_body=False)
|
304 |
+
add_keyframes(data, length, "head", euler_head, bend_head, not_head=False)
|
305 |
+
add_keyframes(data, length, "abc", euler_body, bend_body, body_steve=True, body_POS=body_POS) # TODO
|
306 |
+
|
307 |
+
# save json
|
308 |
+
with open(keyframes_filename, "w") as file:
|
309 |
+
json.dump(data, file, indent=4)
|
310 |
+
|
311 |
+
print(f"keyframes file saves successfully, file path: {os.path.abspath(keyframes_filename)}")
|
312 |
+
|
313 |
+
|
314 |
+
|
315 |
+
if __name__ == '__main__':
|
316 |
+
# config
|
317 |
+
HPE_filename = "outputs/test_3d_output_malaoshi_2-00_2-30_postprocess.npy"
|
318 |
+
FPS_mine_imator = 30
|
319 |
+
keyframes_filename = "steve_malaoshi2.miframes"
|
320 |
+
prior = True
|
321 |
+
hpe2keyframes(HPE_filename, FPS_mine_imator, keyframes_filename, prior=prior)
|
322 |
+
|
323 |
+
print("Done!")
|
LICENSE
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
635 |
+
Copyright (C) <year> <name of author>
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) <year> <name of author>
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<https://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
common/arguments.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
|
8 |
+
import argparse
|
9 |
+
|
10 |
+
|
11 |
+
def parse_args():
|
12 |
+
parser = argparse.ArgumentParser(description='Training script')
|
13 |
+
|
14 |
+
# General arguments
|
15 |
+
parser.add_argument('-d', '--dataset', default='h36m', type=str, metavar='NAME', help='target dataset') # h36m or humaneva
|
16 |
+
parser.add_argument('-k', '--keypoints', default='cpn_ft_h36m_dbb', type=str, metavar='NAME', help='2D detections to use')
|
17 |
+
parser.add_argument('-str', '--subjects-train', default='S1,S5,S6,S7,S8', type=str, metavar='LIST',
|
18 |
+
help='training subjects separated by comma')
|
19 |
+
parser.add_argument('-ste', '--subjects-test', default='S9,S11', type=str, metavar='LIST', help='test subjects separated by comma')
|
20 |
+
parser.add_argument('-sun', '--subjects-unlabeled', default='', type=str, metavar='LIST',
|
21 |
+
help='unlabeled subjects separated by comma for self-supervision')
|
22 |
+
parser.add_argument('-a', '--actions', default='*', type=str, metavar='LIST',
|
23 |
+
help='actions to train/test on, separated by comma, or * for all')
|
24 |
+
parser.add_argument('-c', '--checkpoint', default='checkpoint', type=str, metavar='PATH',
|
25 |
+
help='checkpoint directory')
|
26 |
+
parser.add_argument('--checkpoint-frequency', default=10, type=int, metavar='N',
|
27 |
+
help='create a checkpoint every N epochs')
|
28 |
+
parser.add_argument('-r', '--resume', default='', type=str, metavar='FILENAME',
|
29 |
+
help='checkpoint to resume (file name)')
|
30 |
+
parser.add_argument('--evaluate', default='pretrained_h36m_detectron_coco.bin', type=str, metavar='FILENAME', help='checkpoint to evaluate (file name)')
|
31 |
+
parser.add_argument('--render', action='store_true', help='visualize a particular video')
|
32 |
+
parser.add_argument('--by-subject', action='store_true', help='break down error by subject (on evaluation)')
|
33 |
+
parser.add_argument('--export-training-curves', action='store_true', help='save training curves as .png images')
|
34 |
+
|
35 |
+
# Model arguments
|
36 |
+
parser.add_argument('-s', '--stride', default=1, type=int, metavar='N', help='chunk size to use during training')
|
37 |
+
parser.add_argument('-e', '--epochs', default=60, type=int, metavar='N', help='number of training epochs')
|
38 |
+
parser.add_argument('-b', '--batch-size', default=1024, type=int, metavar='N', help='batch size in terms of predicted frames')
|
39 |
+
parser.add_argument('-drop', '--dropout', default=0.25, type=float, metavar='P', help='dropout probability')
|
40 |
+
parser.add_argument('-lr', '--learning-rate', default=0.001, type=float, metavar='LR', help='initial learning rate')
|
41 |
+
parser.add_argument('-lrd', '--lr-decay', default=0.95, type=float, metavar='LR', help='learning rate decay per epoch')
|
42 |
+
parser.add_argument('-no-da', '--no-data-augmentation', dest='data_augmentation', action='store_false',
|
43 |
+
help='disable train-time flipping')
|
44 |
+
parser.add_argument('-no-tta', '--no-test-time-augmentation', dest='test_time_augmentation', action='store_false',
|
45 |
+
help='disable test-time flipping')
|
46 |
+
parser.add_argument('-arc', '--architecture', default='3,3,3,3,3', type=str, metavar='LAYERS', help='filter widths separated by comma')
|
47 |
+
parser.add_argument('--causal', action='store_true', help='use causal convolutions for real-time processing')
|
48 |
+
parser.add_argument('-ch', '--channels', default=1024, type=int, metavar='N', help='number of channels in convolution layers')
|
49 |
+
|
50 |
+
# Experimental
|
51 |
+
parser.add_argument('--subset', default=1, type=float, metavar='FRACTION', help='reduce dataset size by fraction')
|
52 |
+
parser.add_argument('--downsample', default=1, type=int, metavar='FACTOR', help='downsample frame rate by factor (semi-supervised)')
|
53 |
+
parser.add_argument('--warmup', default=1, type=int, metavar='N', help='warm-up epochs for semi-supervision')
|
54 |
+
parser.add_argument('--no-eval', action='store_true', help='disable epoch evaluation while training (small speed-up)')
|
55 |
+
parser.add_argument('--dense', action='store_true', help='use dense convolutions instead of dilated convolutions')
|
56 |
+
parser.add_argument('--disable-optimizations', action='store_true', help='disable optimized model for single-frame predictions')
|
57 |
+
parser.add_argument('--linear-projection', action='store_true', help='use only linear coefficients for semi-supervised projection')
|
58 |
+
parser.add_argument('--no-bone-length', action='store_false', dest='bone_length_term',
|
59 |
+
help='disable bone length term in semi-supervised settings')
|
60 |
+
parser.add_argument('--no-proj', action='store_true', help='disable projection for semi-supervised setting')
|
61 |
+
|
62 |
+
# Visualization
|
63 |
+
parser.add_argument('--viz-subject', type=str, metavar='STR', help='subject to render')
|
64 |
+
parser.add_argument('--viz-action', type=str, metavar='STR', help='action to render')
|
65 |
+
parser.add_argument('--viz-camera', type=int, default=0, metavar='N', help='camera to render')
|
66 |
+
parser.add_argument('--viz-video', type=str, metavar='PATH', help='path to input video')
|
67 |
+
parser.add_argument('--viz-skip', type=int, default=0, metavar='N', help='skip first N frames of input video')
|
68 |
+
parser.add_argument('--viz-output', type=str, metavar='PATH', help='output file name (.gif or .mp4)')
|
69 |
+
parser.add_argument('--viz-bitrate', type=int, default=30000, metavar='N', help='bitrate for mp4 videos')
|
70 |
+
parser.add_argument('--viz-no-ground-truth', action='store_true', help='do not show ground-truth poses')
|
71 |
+
parser.add_argument('--viz-limit', type=int, default=-1, metavar='N', help='only render first N frames')
|
72 |
+
parser.add_argument('--viz-downsample', type=int, default=1, metavar='N', help='downsample FPS by a factor N')
|
73 |
+
parser.add_argument('--viz-size', type=int, default=5, metavar='N', help='image size')
|
74 |
+
# self add
|
75 |
+
parser.add_argument('-in2d','--input_npz', type=str, default='', help='input 2d numpy file')
|
76 |
+
parser.add_argument('--video', dest='input_video', type=str, default='', help='input video name')
|
77 |
+
|
78 |
+
parser.add_argument('--layers', default=3, type=int)
|
79 |
+
parser.add_argument('--channel', default=256, type=int)
|
80 |
+
parser.add_argument('--d_hid', default=512, type=int)
|
81 |
+
parser.add_argument('-f', '--frames', type=int, default=243)
|
82 |
+
parser.add_argument('--n_joints', type=int, default=17)
|
83 |
+
parser.add_argument('--out_joints', type=int, default=17)
|
84 |
+
parser.add_argument('--in_channels', type=int, default=2)
|
85 |
+
parser.add_argument('--out_channels', type=int, default=3)
|
86 |
+
parser.add_argument('--stride_num', type=list, default=[3, 3, 3, 3, 3])
|
87 |
+
|
88 |
+
parser.set_defaults(bone_length_term=True)
|
89 |
+
parser.set_defaults(data_augmentation=True)
|
90 |
+
parser.set_defaults(test_time_augmentation=True)
|
91 |
+
|
92 |
+
args = parser.parse_args()
|
93 |
+
# Check invalid configuration
|
94 |
+
if args.resume and args.evaluate:
|
95 |
+
print('Invalid flags: --resume and --evaluate cannot be set at the same time')
|
96 |
+
exit()
|
97 |
+
|
98 |
+
if args.export_training_curves and args.no_eval:
|
99 |
+
print('Invalid flags: --export-training-curves and --no-eval cannot be set at the same time')
|
100 |
+
exit()
|
101 |
+
|
102 |
+
return args
|
common/camera.py
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
|
8 |
+
import numpy as np
|
9 |
+
import torch
|
10 |
+
|
11 |
+
from common.quaternion import qrot, qinverse
|
12 |
+
from common.utils import wrap
|
13 |
+
|
14 |
+
|
15 |
+
def normalize_screen_coordinates(X, w, h):
|
16 |
+
assert X.shape[-1] == 2
|
17 |
+
|
18 |
+
# Normalize so that [0, w] is mapped to [-1, 1], while preserving the aspect ratio
|
19 |
+
return X / w * 2 - [1, h / w]
|
20 |
+
|
21 |
+
|
22 |
+
def normalize_screen_coordinates_new(X, w, h):
|
23 |
+
assert X.shape[-1] == 2
|
24 |
+
|
25 |
+
return (X - (w / 2, h / 2)) / (w / 2, h / 2)
|
26 |
+
|
27 |
+
|
28 |
+
def image_coordinates_new(X, w, h):
|
29 |
+
assert X.shape[-1] == 2
|
30 |
+
|
31 |
+
# Reverse camera frame normalization
|
32 |
+
return (X * (w / 2, h / 2)) + (w / 2, h / 2)
|
33 |
+
|
34 |
+
|
35 |
+
def image_coordinates(X, w, h):
|
36 |
+
assert X.shape[-1] == 2
|
37 |
+
|
38 |
+
# Reverse camera frame normalization
|
39 |
+
return (X + [1, h / w]) * w / 2
|
40 |
+
|
41 |
+
|
42 |
+
def world_to_camera(X, R, t):
|
43 |
+
Rt = wrap(qinverse, R) # Invert rotation
|
44 |
+
return wrap(qrot, np.tile(Rt, (*X.shape[:-1], 1)), X - t) # Rotate and translate
|
45 |
+
|
46 |
+
|
47 |
+
def camera_to_world(X, R, t):
|
48 |
+
return wrap(qrot, np.tile(R, (*X.shape[:-1], 1)), X) + t
|
49 |
+
|
50 |
+
|
51 |
+
def project_to_2d(X, camera_params):
|
52 |
+
"""
|
53 |
+
Project 3D points to 2D using the Human3.6M camera projection function.
|
54 |
+
This is a differentiable and batched reimplementation of the original MATLAB script.
|
55 |
+
|
56 |
+
Arguments:
|
57 |
+
X -- 3D points in *camera space* to transform (N, *, 3)
|
58 |
+
camera_params -- intrinsic parameteres (N, 2+2+3+2=9)
|
59 |
+
focal length / principal point / radial_distortion / tangential_distortion
|
60 |
+
"""
|
61 |
+
assert X.shape[-1] == 3
|
62 |
+
assert len(camera_params.shape) == 2
|
63 |
+
assert camera_params.shape[-1] == 9
|
64 |
+
assert X.shape[0] == camera_params.shape[0]
|
65 |
+
|
66 |
+
while len(camera_params.shape) < len(X.shape):
|
67 |
+
camera_params = camera_params.unsqueeze(1)
|
68 |
+
|
69 |
+
f = camera_params[..., :2] # focal lendgth
|
70 |
+
c = camera_params[..., 2:4] # center principal point
|
71 |
+
k = camera_params[..., 4:7]
|
72 |
+
p = camera_params[..., 7:]
|
73 |
+
|
74 |
+
XX = torch.clamp(X[..., :2] / X[..., 2:], min=-1, max=1)
|
75 |
+
r2 = torch.sum(XX[..., :2] ** 2, dim=len(XX.shape) - 1, keepdim=True)
|
76 |
+
|
77 |
+
radial = 1 + torch.sum(k * torch.cat((r2, r2 ** 2, r2 ** 3), dim=len(r2.shape) - 1), dim=len(r2.shape) - 1, keepdim=True)
|
78 |
+
tan = torch.sum(p * XX, dim=len(XX.shape) - 1, keepdim=True)
|
79 |
+
|
80 |
+
XXX = XX * (radial + tan) + p * r2
|
81 |
+
|
82 |
+
return f * XXX + c
|
83 |
+
|
84 |
+
|
85 |
+
def project_to_2d_linear(X, camera_params):
|
86 |
+
"""
|
87 |
+
使用linear parameters is a little difference for use linear and no-linear parameters
|
88 |
+
Project 3D points to 2D using only linear parameters (focal length and principal point).
|
89 |
+
|
90 |
+
Arguments:
|
91 |
+
X -- 3D points in *camera space* to transform (N, *, 3)
|
92 |
+
camera_params -- intrinsic parameteres (N, 2+2+3+2=9)
|
93 |
+
"""
|
94 |
+
assert X.shape[-1] == 3
|
95 |
+
assert len(camera_params.shape) == 2
|
96 |
+
assert camera_params.shape[-1] == 9
|
97 |
+
assert X.shape[0] == camera_params.shape[0]
|
98 |
+
|
99 |
+
while len(camera_params.shape) < len(X.shape):
|
100 |
+
camera_params = camera_params.unsqueeze(1)
|
101 |
+
|
102 |
+
f = camera_params[..., :2]
|
103 |
+
c = camera_params[..., 2:4]
|
104 |
+
|
105 |
+
XX = torch.clamp(X[..., :2] / X[..., 2:], min=-1, max=1)
|
106 |
+
|
107 |
+
return f * XX + c
|
common/generators.py
ADDED
@@ -0,0 +1,425 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
|
8 |
+
from itertools import zip_longest
|
9 |
+
|
10 |
+
import numpy as np
|
11 |
+
|
12 |
+
|
13 |
+
class ChunkedGenerator:
|
14 |
+
"""
|
15 |
+
Batched data generator, used for training.
|
16 |
+
The sequences are split into equal-length chunks and padded as necessary.
|
17 |
+
|
18 |
+
Arguments:
|
19 |
+
batch_size -- the batch size to use for training
|
20 |
+
cameras -- list of cameras, one element for each video (optional, used for semi-supervised training)
|
21 |
+
poses_3d -- list of ground-truth 3D poses, one element for each video (optional, used for supervised training)
|
22 |
+
poses_2d -- list of input 2D keypoints, one element for each video
|
23 |
+
chunk_length -- number of output frames to predict for each training example (usually 1)
|
24 |
+
pad -- 2D input padding to compensate for valid convolutions, per side (depends on the receptive field)
|
25 |
+
causal_shift -- asymmetric padding offset when causal convolutions are used (usually 0 or "pad")
|
26 |
+
shuffle -- randomly shuffle the dataset before each epoch
|
27 |
+
random_seed -- initial seed to use for the random generator
|
28 |
+
augment -- augment the dataset by flipping poses horizontally
|
29 |
+
kps_left and kps_right -- list of left/right 2D keypoints if flipping is enabled
|
30 |
+
joints_left and joints_right -- list of left/right 3D joints if flipping is enabled
|
31 |
+
"""
|
32 |
+
|
33 |
+
def __init__(self, batch_size, cameras, poses_3d, poses_2d,
|
34 |
+
chunk_length, pad=0, causal_shift=0,
|
35 |
+
shuffle=True, random_seed=1234,
|
36 |
+
augment=False, kps_left=None, kps_right=None, joints_left=None, joints_right=None,
|
37 |
+
endless=False):
|
38 |
+
assert poses_3d is None or len(poses_3d) == len(poses_2d), (len(poses_3d), len(poses_2d))
|
39 |
+
assert cameras is None or len(cameras) == len(poses_2d)
|
40 |
+
|
41 |
+
# Build lineage info
|
42 |
+
pairs = [] # (seq_idx, start_frame, end_frame, flip) tuples
|
43 |
+
for i in range(len(poses_2d)):
|
44 |
+
assert poses_3d is None or poses_3d[i].shape[0] == poses_3d[i].shape[0]
|
45 |
+
n_chunks = (poses_2d[i].shape[0] + chunk_length - 1) // chunk_length
|
46 |
+
offset = (n_chunks * chunk_length - poses_2d[i].shape[0]) // 2
|
47 |
+
bounds = np.arange(n_chunks + 1) * chunk_length - offset
|
48 |
+
augment_vector = np.full(len(bounds - 1), False, dtype=bool)
|
49 |
+
pairs += zip(np.repeat(i, len(bounds - 1)), bounds[:-1], bounds[1:], augment_vector)
|
50 |
+
if augment:
|
51 |
+
pairs += zip(np.repeat(i, len(bounds - 1)), bounds[:-1], bounds[1:], ~augment_vector)
|
52 |
+
|
53 |
+
# Initialize buffers
|
54 |
+
if cameras is not None:
|
55 |
+
self.batch_cam = np.empty((batch_size, cameras[0].shape[-1]))
|
56 |
+
if poses_3d is not None:
|
57 |
+
self.batch_3d = np.empty((batch_size, chunk_length, poses_3d[0].shape[-2], poses_3d[0].shape[-1]))
|
58 |
+
self.batch_2d = np.empty((batch_size, chunk_length + 2 * pad, poses_2d[0].shape[-2], poses_2d[0].shape[-1]))
|
59 |
+
|
60 |
+
self.num_batches = (len(pairs) + batch_size - 1) // batch_size
|
61 |
+
self.batch_size = batch_size
|
62 |
+
self.random = np.random.RandomState(random_seed)
|
63 |
+
self.pairs = pairs
|
64 |
+
self.shuffle = shuffle
|
65 |
+
self.pad = pad
|
66 |
+
self.causal_shift = causal_shift
|
67 |
+
self.endless = endless
|
68 |
+
self.state = None
|
69 |
+
|
70 |
+
self.cameras = cameras
|
71 |
+
self.poses_3d = poses_3d
|
72 |
+
self.poses_2d = poses_2d
|
73 |
+
|
74 |
+
self.augment = augment
|
75 |
+
self.kps_left = kps_left
|
76 |
+
self.kps_right = kps_right
|
77 |
+
self.joints_left = joints_left
|
78 |
+
self.joints_right = joints_right
|
79 |
+
|
80 |
+
def num_frames(self):
|
81 |
+
return self.num_batches * self.batch_size
|
82 |
+
|
83 |
+
def random_state(self):
|
84 |
+
return self.random
|
85 |
+
|
86 |
+
def set_random_state(self, random):
|
87 |
+
self.random = random
|
88 |
+
|
89 |
+
def augment_enabled(self):
|
90 |
+
return self.augment
|
91 |
+
|
92 |
+
def next_pairs(self):
|
93 |
+
if self.state is None:
|
94 |
+
if self.shuffle:
|
95 |
+
pairs = self.random.permutation(self.pairs)
|
96 |
+
else:
|
97 |
+
pairs = self.pairs
|
98 |
+
return 0, pairs
|
99 |
+
else:
|
100 |
+
return self.state
|
101 |
+
|
102 |
+
def next_epoch(self):
|
103 |
+
enabled = True
|
104 |
+
while enabled:
|
105 |
+
start_idx, pairs = self.next_pairs()
|
106 |
+
for b_i in range(start_idx, self.num_batches):
|
107 |
+
chunks = pairs[b_i * self.batch_size: (b_i + 1) * self.batch_size]
|
108 |
+
for i, (seq_i, start_3d, end_3d, flip) in enumerate(chunks):
|
109 |
+
start_2d = start_3d - self.pad - self.causal_shift
|
110 |
+
end_2d = end_3d + self.pad - self.causal_shift
|
111 |
+
|
112 |
+
# 2D poses
|
113 |
+
seq_2d = self.poses_2d[seq_i]
|
114 |
+
low_2d = max(start_2d, 0)
|
115 |
+
high_2d = min(end_2d, seq_2d.shape[0])
|
116 |
+
pad_left_2d = low_2d - start_2d
|
117 |
+
pad_right_2d = end_2d - high_2d
|
118 |
+
if pad_left_2d != 0 or pad_right_2d != 0:
|
119 |
+
self.batch_2d[i] = np.pad(seq_2d[low_2d:high_2d], ((pad_left_2d, pad_right_2d), (0, 0), (0, 0)), 'edge')
|
120 |
+
else:
|
121 |
+
self.batch_2d[i] = seq_2d[low_2d:high_2d]
|
122 |
+
|
123 |
+
if flip:
|
124 |
+
# Flip 2D keypoints
|
125 |
+
self.batch_2d[i, :, :, 0] *= -1
|
126 |
+
self.batch_2d[i, :, self.kps_left + self.kps_right] = self.batch_2d[i, :, self.kps_right + self.kps_left]
|
127 |
+
|
128 |
+
# 3D poses
|
129 |
+
if self.poses_3d is not None:
|
130 |
+
seq_3d = self.poses_3d[seq_i]
|
131 |
+
low_3d = max(start_3d, 0)
|
132 |
+
high_3d = min(end_3d, seq_3d.shape[0])
|
133 |
+
pad_left_3d = low_3d - start_3d
|
134 |
+
pad_right_3d = end_3d - high_3d
|
135 |
+
if pad_left_3d != 0 or pad_right_3d != 0:
|
136 |
+
self.batch_3d[i] = np.pad(seq_3d[low_3d:high_3d], ((pad_left_3d, pad_right_3d), (0, 0), (0, 0)), 'edge')
|
137 |
+
else:
|
138 |
+
self.batch_3d[i] = seq_3d[low_3d:high_3d]
|
139 |
+
|
140 |
+
if flip:
|
141 |
+
# Flip 3D joints
|
142 |
+
self.batch_3d[i, :, :, 0] *= -1
|
143 |
+
self.batch_3d[i, :, self.joints_left + self.joints_right] = \
|
144 |
+
self.batch_3d[i, :, self.joints_right + self.joints_left]
|
145 |
+
|
146 |
+
# Cameras
|
147 |
+
if self.cameras is not None:
|
148 |
+
self.batch_cam[i] = self.cameras[seq_i]
|
149 |
+
if flip:
|
150 |
+
# Flip horizontal distortion coefficients
|
151 |
+
self.batch_cam[i, 2] *= -1
|
152 |
+
self.batch_cam[i, 7] *= -1
|
153 |
+
|
154 |
+
if self.endless:
|
155 |
+
self.state = (b_i + 1, pairs)
|
156 |
+
if self.poses_3d is None and self.cameras is None:
|
157 |
+
yield None, None, self.batch_2d[:len(chunks)]
|
158 |
+
elif self.poses_3d is not None and self.cameras is None:
|
159 |
+
yield None, self.batch_3d[:len(chunks)], self.batch_2d[:len(chunks)]
|
160 |
+
elif self.poses_3d is None:
|
161 |
+
yield self.batch_cam[:len(chunks)], None, self.batch_2d[:len(chunks)]
|
162 |
+
else:
|
163 |
+
yield self.batch_cam[:len(chunks)], self.batch_3d[:len(chunks)], self.batch_2d[:len(chunks)]
|
164 |
+
|
165 |
+
if self.endless:
|
166 |
+
self.state = None
|
167 |
+
else:
|
168 |
+
enabled = False
|
169 |
+
|
170 |
+
|
171 |
+
class UnchunkedGenerator:
|
172 |
+
"""
|
173 |
+
Non-batched data generator, used for testing.
|
174 |
+
Sequences are returned one at a time (i.e. batch size = 1), without chunking.
|
175 |
+
|
176 |
+
If data augmentation is enabled, the batches contain two sequences (i.e. batch size = 2),
|
177 |
+
the second of which is a mirrored version of the first.
|
178 |
+
|
179 |
+
Arguments:
|
180 |
+
cameras -- list of cameras, one element for each video (optional, used for semi-supervised training)
|
181 |
+
poses_3d -- list of ground-truth 3D poses, one element for each video (optional, used for supervised training)
|
182 |
+
poses_2d -- list of input 2D keypoints, one element for each video
|
183 |
+
pad -- 2D input padding to compensate for valid convolutions, per side (depends on the receptive field)
|
184 |
+
causal_shift -- asymmetric padding offset when causal convolutions are used (usually 0 or "pad")
|
185 |
+
augment -- augment the dataset by flipping poses horizontally
|
186 |
+
kps_left and kps_right -- list of left/right 2D keypoints if flipping is enabled
|
187 |
+
joints_left and joints_right -- list of left/right 3D joints if flipping is enabled
|
188 |
+
"""
|
189 |
+
|
190 |
+
def __init__(self, cameras, poses_3d, poses_2d, pad=0, causal_shift=0,
|
191 |
+
augment=False, kps_left=None, kps_right=None, joints_left=None, joints_right=None):
|
192 |
+
assert poses_3d is None or len(poses_3d) == len(poses_2d)
|
193 |
+
assert cameras is None or len(cameras) == len(poses_2d)
|
194 |
+
|
195 |
+
self.augment = augment
|
196 |
+
self.kps_left = kps_left
|
197 |
+
self.kps_right = kps_right
|
198 |
+
self.joints_left = joints_left
|
199 |
+
self.joints_right = joints_right
|
200 |
+
|
201 |
+
self.pad = pad
|
202 |
+
self.causal_shift = causal_shift
|
203 |
+
self.cameras = [] if cameras is None else cameras
|
204 |
+
self.poses_3d = [] if poses_3d is None else poses_3d
|
205 |
+
self.poses_2d = poses_2d
|
206 |
+
|
207 |
+
def num_frames(self):
|
208 |
+
count = 0
|
209 |
+
for p in self.poses_2d:
|
210 |
+
count += p.shape[0]
|
211 |
+
return count
|
212 |
+
|
213 |
+
def augment_enabled(self):
|
214 |
+
return self.augment
|
215 |
+
|
216 |
+
def set_augment(self, augment):
|
217 |
+
self.augment = augment
|
218 |
+
|
219 |
+
def next_epoch(self):
|
220 |
+
for seq_cam, seq_3d, seq_2d in zip_longest(self.cameras, self.poses_3d, self.poses_2d):
|
221 |
+
batch_cam = None if seq_cam is None else np.expand_dims(seq_cam, axis=0)
|
222 |
+
batch_3d = None if seq_3d is None else np.expand_dims(seq_3d, axis=0)
|
223 |
+
# 2D input padding to compensate for valid convolutions, per side (depends on the receptive field)
|
224 |
+
batch_2d = np.expand_dims(np.pad(seq_2d,
|
225 |
+
((self.pad + self.causal_shift, self.pad - self.causal_shift), (0, 0), (0, 0)),
|
226 |
+
'edge'), axis=0)
|
227 |
+
if self.augment:
|
228 |
+
# Append flipped version
|
229 |
+
if batch_cam is not None:
|
230 |
+
batch_cam = np.concatenate((batch_cam, batch_cam), axis=0)
|
231 |
+
batch_cam[1, 2] *= -1
|
232 |
+
batch_cam[1, 7] *= -1
|
233 |
+
|
234 |
+
if batch_3d is not None:
|
235 |
+
batch_3d = np.concatenate((batch_3d, batch_3d), axis=0)
|
236 |
+
batch_3d[1, :, :, 0] *= -1
|
237 |
+
batch_3d[1, :, self.joints_left + self.joints_right] = batch_3d[1, :, self.joints_right + self.joints_left]
|
238 |
+
|
239 |
+
batch_2d = np.concatenate((batch_2d, batch_2d), axis=0)
|
240 |
+
batch_2d[1, :, :, 0] *= -1
|
241 |
+
batch_2d[1, :, self.kps_left + self.kps_right] = batch_2d[1, :, self.kps_right + self.kps_left]
|
242 |
+
|
243 |
+
yield batch_cam, batch_3d, batch_2d
|
244 |
+
|
245 |
+
class Evaluate_Generator:
|
246 |
+
"""
|
247 |
+
Batched data generator, used for training.
|
248 |
+
The sequences are split into equal-length chunks and padded as necessary.
|
249 |
+
Arguments:
|
250 |
+
batch_size -- the batch size to use for training
|
251 |
+
cameras -- list of cameras, one element for each video (optional, used for semi-supervised training)
|
252 |
+
poses_3d -- list of ground-truth 3D poses, one element for each video (optional, used for supervised training)
|
253 |
+
poses_2d -- list of input 2D keypoints, one element for each video
|
254 |
+
chunk_length -- number of output frames to predict for each training example (usually 1)
|
255 |
+
pad -- 2D input padding to compensate for valid convolutions, per side (depends on the receptive field)
|
256 |
+
causal_shift -- asymmetric padding offset when causal convolutions are used (usually 0 or "pad")
|
257 |
+
shuffle -- randomly shuffle the dataset before each epoch
|
258 |
+
random_seed -- initial seed to use for the random generator
|
259 |
+
augment -- augment the dataset by flipping poses horizontally
|
260 |
+
kps_left and kps_right -- list of left/right 2D keypoints if flipping is enabled
|
261 |
+
joints_left and joints_right -- list of left/right 3D joints if flipping is enabled
|
262 |
+
"""
|
263 |
+
|
264 |
+
def __init__(self, batch_size, cameras, poses_3d, poses_2d,
|
265 |
+
chunk_length, pad=0, causal_shift=0,
|
266 |
+
shuffle=True, random_seed=1234,
|
267 |
+
augment=False, kps_left=None, kps_right=None, joints_left=None, joints_right=None,
|
268 |
+
endless=False):
|
269 |
+
assert poses_3d is None or len(poses_3d) == len(poses_2d), (len(poses_3d), len(poses_2d))
|
270 |
+
assert cameras is None or len(cameras) == len(poses_2d)
|
271 |
+
|
272 |
+
# Build lineage info
|
273 |
+
pairs = [] # (seq_idx, start_frame, end_frame, flip) tuples
|
274 |
+
for i in range(len(poses_2d)):
|
275 |
+
assert poses_3d is None or poses_3d[i].shape[0] == poses_3d[i].shape[0]
|
276 |
+
n_chunks = (poses_2d[i].shape[0] + chunk_length - 1) // chunk_length
|
277 |
+
offset = (n_chunks * chunk_length - poses_2d[i].shape[0]) // 2
|
278 |
+
bounds = np.arange(n_chunks + 1) * chunk_length - offset
|
279 |
+
augment_vector = np.full(len(bounds - 1), False, dtype=bool)
|
280 |
+
pairs += zip(np.repeat(i, len(bounds - 1)), bounds[:-1], bounds[1:], augment_vector)
|
281 |
+
|
282 |
+
# Initialize buffers
|
283 |
+
if cameras is not None:
|
284 |
+
self.batch_cam = np.empty((batch_size, cameras[0].shape[-1]))
|
285 |
+
if poses_3d is not None:
|
286 |
+
self.batch_3d = np.empty((batch_size, chunk_length, poses_3d[0].shape[-2], poses_3d[0].shape[-1]))
|
287 |
+
|
288 |
+
if augment:
|
289 |
+
self.batch_2d_flip = np.empty(
|
290 |
+
(batch_size, chunk_length + 2 * pad, poses_2d[0].shape[-2], poses_2d[0].shape[-1]))
|
291 |
+
self.batch_2d = np.empty((batch_size, chunk_length + 2 * pad, poses_2d[0].shape[-2], poses_2d[0].shape[-1]))
|
292 |
+
else:
|
293 |
+
self.batch_2d = np.empty((batch_size, chunk_length + 2 * pad, poses_2d[0].shape[-2], poses_2d[0].shape[-1]))
|
294 |
+
|
295 |
+
self.num_batches = (len(pairs) + batch_size - 1) // batch_size
|
296 |
+
self.batch_size = batch_size
|
297 |
+
self.random = np.random.RandomState(random_seed)
|
298 |
+
self.pairs = pairs
|
299 |
+
self.shuffle = shuffle
|
300 |
+
self.pad = pad
|
301 |
+
self.causal_shift = causal_shift
|
302 |
+
self.endless = endless
|
303 |
+
self.state = None
|
304 |
+
|
305 |
+
self.cameras = cameras
|
306 |
+
self.poses_3d = poses_3d
|
307 |
+
self.poses_2d = poses_2d
|
308 |
+
|
309 |
+
self.augment = augment
|
310 |
+
self.kps_left = kps_left
|
311 |
+
self.kps_right = kps_right
|
312 |
+
self.joints_left = joints_left
|
313 |
+
self.joints_right = joints_right
|
314 |
+
|
315 |
+
def num_frames(self):
|
316 |
+
return self.num_batches * self.batch_size
|
317 |
+
|
318 |
+
def random_state(self):
|
319 |
+
return self.random
|
320 |
+
|
321 |
+
def set_random_state(self, random):
|
322 |
+
self.random = random
|
323 |
+
|
324 |
+
def augment_enabled(self):
|
325 |
+
return self.augment
|
326 |
+
|
327 |
+
def next_pairs(self):
|
328 |
+
if self.state is None:
|
329 |
+
if self.shuffle:
|
330 |
+
pairs = self.random.permutation(self.pairs)
|
331 |
+
else:
|
332 |
+
pairs = self.pairs
|
333 |
+
return 0, pairs
|
334 |
+
else:
|
335 |
+
return self.state
|
336 |
+
|
337 |
+
def next_epoch(self):
|
338 |
+
enabled = True
|
339 |
+
while enabled:
|
340 |
+
start_idx, pairs = self.next_pairs()
|
341 |
+
for b_i in range(start_idx, self.num_batches):
|
342 |
+
chunks = pairs[b_i * self.batch_size: (b_i + 1) * self.batch_size]
|
343 |
+
for i, (seq_i, start_3d, end_3d, flip) in enumerate(chunks):
|
344 |
+
start_2d = start_3d - self.pad - self.causal_shift
|
345 |
+
end_2d = end_3d + self.pad - self.causal_shift
|
346 |
+
|
347 |
+
# 2D poses
|
348 |
+
seq_2d = self.poses_2d[seq_i]
|
349 |
+
low_2d = max(start_2d, 0)
|
350 |
+
high_2d = min(end_2d, seq_2d.shape[0])
|
351 |
+
pad_left_2d = low_2d - start_2d
|
352 |
+
pad_right_2d = end_2d - high_2d
|
353 |
+
if pad_left_2d != 0 or pad_right_2d != 0:
|
354 |
+
self.batch_2d[i] = np.pad(seq_2d[low_2d:high_2d], ((pad_left_2d, pad_right_2d), (0, 0), (0, 0)),
|
355 |
+
'edge')
|
356 |
+
if self.augment:
|
357 |
+
self.batch_2d_flip[i] = np.pad(seq_2d[low_2d:high_2d],
|
358 |
+
((pad_left_2d, pad_right_2d), (0, 0), (0, 0)),
|
359 |
+
'edge')
|
360 |
+
|
361 |
+
else:
|
362 |
+
self.batch_2d[i] = seq_2d[low_2d:high_2d]
|
363 |
+
if self.augment:
|
364 |
+
self.batch_2d_flip[i] = seq_2d[low_2d:high_2d]
|
365 |
+
|
366 |
+
if self.augment:
|
367 |
+
self.batch_2d_flip[i, :, :, 0] *= -1
|
368 |
+
self.batch_2d_flip[i, :, self.kps_left + self.kps_right] = self.batch_2d_flip[i, :,
|
369 |
+
self.kps_right + self.kps_left]
|
370 |
+
|
371 |
+
# 3D poses
|
372 |
+
if self.poses_3d is not None:
|
373 |
+
seq_3d = self.poses_3d[seq_i]
|
374 |
+
low_3d = max(start_3d, 0)
|
375 |
+
high_3d = min(end_3d, seq_3d.shape[0])
|
376 |
+
pad_left_3d = low_3d - start_3d
|
377 |
+
pad_right_3d = end_3d - high_3d
|
378 |
+
if pad_left_3d != 0 or pad_right_3d != 0:
|
379 |
+
self.batch_3d[i] = np.pad(seq_3d[low_3d:high_3d],
|
380 |
+
((pad_left_3d, pad_right_3d), (0, 0), (0, 0)), 'edge')
|
381 |
+
else:
|
382 |
+
self.batch_3d[i] = seq_3d[low_3d:high_3d]
|
383 |
+
|
384 |
+
if flip:
|
385 |
+
self.batch_3d[i, :, :, 0] *= -1
|
386 |
+
self.batch_3d[i, :, self.joints_left + self.joints_right] = \
|
387 |
+
self.batch_3d[i, :, self.joints_right + self.joints_left]
|
388 |
+
|
389 |
+
# Cameras
|
390 |
+
if self.cameras is not None:
|
391 |
+
self.batch_cam[i] = self.cameras[seq_i]
|
392 |
+
if flip:
|
393 |
+
# Flip horizontal distortion coefficients
|
394 |
+
self.batch_cam[i, 2] *= -1
|
395 |
+
self.batch_cam[i, 7] *= -1
|
396 |
+
|
397 |
+
if self.endless:
|
398 |
+
self.state = (b_i + 1, pairs)
|
399 |
+
|
400 |
+
if self.augment:
|
401 |
+
if self.poses_3d is None and self.cameras is None:
|
402 |
+
yield None, None, self.batch_2d[:len(chunks)], self.batch_2d_flip[:len(chunks)]
|
403 |
+
elif self.poses_3d is not None and self.cameras is None:
|
404 |
+
yield None, self.batch_3d[:len(chunks)], self.batch_2d[:len(chunks)], self.batch_2d_flip[
|
405 |
+
:len(chunks)]
|
406 |
+
elif self.poses_3d is None:
|
407 |
+
yield self.batch_cam[:len(chunks)], None, self.batch_2d[:len(chunks)], self.batch_2d_flip[
|
408 |
+
:len(chunks)]
|
409 |
+
else:
|
410 |
+
yield self.batch_cam[:len(chunks)], self.batch_3d[:len(chunks)], self.batch_2d[:len(
|
411 |
+
chunks)], self.batch_2d_flip[:len(chunks)]
|
412 |
+
else:
|
413 |
+
if self.poses_3d is None and self.cameras is None:
|
414 |
+
yield None, None, self.batch_2d[:len(chunks)]
|
415 |
+
elif self.poses_3d is not None and self.cameras is None:
|
416 |
+
yield None, self.batch_3d[:len(chunks)], self.batch_2d[:len(chunks)]
|
417 |
+
elif self.poses_3d is None:
|
418 |
+
yield self.batch_cam[:len(chunks)], None, self.batch_2d[:len(chunks)]
|
419 |
+
else:
|
420 |
+
yield self.batch_cam[:len(chunks)], self.batch_3d[:len(chunks)], self.batch_2d[:len(chunks)]
|
421 |
+
|
422 |
+
if self.endless:
|
423 |
+
self.state = None
|
424 |
+
else:
|
425 |
+
enabled = False
|
common/h36m_dataset.py
ADDED
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
|
8 |
+
import copy
|
9 |
+
|
10 |
+
import numpy as np
|
11 |
+
|
12 |
+
from common.camera import normalize_screen_coordinates
|
13 |
+
from common.mocap_dataset import MocapDataset
|
14 |
+
from common.skeleton import Skeleton
|
15 |
+
|
16 |
+
h36m_skeleton = Skeleton(parents=[-1, 0, 1, 2, 3, 4, 0, 6, 7, 8, 9, 0, 11, 12, 13, 14, 12,
|
17 |
+
16, 17, 18, 19, 20, 19, 22, 12, 24, 25, 26, 27, 28, 27, 30],
|
18 |
+
joints_left=[6, 7, 8, 9, 10, 16, 17, 18, 19, 20, 21, 22, 23],
|
19 |
+
joints_right=[1, 2, 3, 4, 5, 24, 25, 26, 27, 28, 29, 30, 31])
|
20 |
+
|
21 |
+
h36m_cameras_intrinsic_params = [
|
22 |
+
{
|
23 |
+
'id': '54138969',
|
24 |
+
'center': [512.54150390625, 515.4514770507812],
|
25 |
+
'focal_length': [1145.0494384765625, 1143.7811279296875],
|
26 |
+
'radial_distortion': [-0.20709891617298126, 0.24777518212795258, -0.0030751503072679043],
|
27 |
+
'tangential_distortion': [-0.0009756988729350269, -0.00142447161488235],
|
28 |
+
'res_w': 1000,
|
29 |
+
'res_h': 1002,
|
30 |
+
'azimuth': 70, # Only used for visualization
|
31 |
+
},
|
32 |
+
{
|
33 |
+
'id': '55011271',
|
34 |
+
'center': [508.8486328125, 508.0649108886719],
|
35 |
+
'focal_length': [1149.6756591796875, 1147.5916748046875],
|
36 |
+
'radial_distortion': [-0.1942136287689209, 0.2404085397720337, 0.006819975562393665],
|
37 |
+
'tangential_distortion': [-0.0016190266469493508, -0.0027408944442868233],
|
38 |
+
'res_w': 1000,
|
39 |
+
'res_h': 1000,
|
40 |
+
'azimuth': -70, # Only used for visualization
|
41 |
+
},
|
42 |
+
{
|
43 |
+
'id': '58860488',
|
44 |
+
'center': [519.8158569335938, 501.40264892578125],
|
45 |
+
'focal_length': [1149.1407470703125, 1148.7989501953125],
|
46 |
+
'radial_distortion': [-0.2083381861448288, 0.25548800826072693, -0.0024604974314570427],
|
47 |
+
'tangential_distortion': [0.0014843869721516967, -0.0007599993259645998],
|
48 |
+
'res_w': 1000,
|
49 |
+
'res_h': 1000,
|
50 |
+
'azimuth': 110, # Only used for visualization
|
51 |
+
},
|
52 |
+
{
|
53 |
+
'id': '60457274',
|
54 |
+
'center': [514.9682006835938, 501.88201904296875],
|
55 |
+
'focal_length': [1145.5113525390625, 1144.77392578125],
|
56 |
+
'radial_distortion': [-0.198384091258049, 0.21832367777824402, -0.008947807364165783],
|
57 |
+
'tangential_distortion': [-0.0005872055771760643, -0.0018133620033040643],
|
58 |
+
'res_w': 1000,
|
59 |
+
'res_h': 1002,
|
60 |
+
'azimuth': -110, # Only used for visualization
|
61 |
+
},
|
62 |
+
]
|
63 |
+
|
64 |
+
h36m_cameras_extrinsic_params = {
|
65 |
+
'S1': [
|
66 |
+
{
|
67 |
+
'orientation': [0.1407056450843811, -0.1500701755285263, -0.755240797996521, 0.6223280429840088],
|
68 |
+
'translation': [1841.1070556640625, 4955.28466796875, 1563.4454345703125],
|
69 |
+
},
|
70 |
+
{
|
71 |
+
'orientation': [0.6157187819480896, -0.764836311340332, -0.14833825826644897, 0.11794740706682205],
|
72 |
+
'translation': [1761.278564453125, -5078.0068359375, 1606.2650146484375],
|
73 |
+
},
|
74 |
+
{
|
75 |
+
'orientation': [0.14651472866535187, -0.14647851884365082, 0.7653023600578308, -0.6094175577163696],
|
76 |
+
'translation': [-1846.7777099609375, 5215.04638671875, 1491.972412109375],
|
77 |
+
},
|
78 |
+
{
|
79 |
+
'orientation': [0.5834008455276489, -0.7853162288665771, 0.14548823237419128, -0.14749594032764435],
|
80 |
+
'translation': [-1794.7896728515625, -3722.698974609375, 1574.8927001953125],
|
81 |
+
},
|
82 |
+
],
|
83 |
+
'S2': [
|
84 |
+
{},
|
85 |
+
{},
|
86 |
+
{},
|
87 |
+
{},
|
88 |
+
],
|
89 |
+
'S3': [
|
90 |
+
{},
|
91 |
+
{},
|
92 |
+
{},
|
93 |
+
{},
|
94 |
+
],
|
95 |
+
'S4': [
|
96 |
+
{},
|
97 |
+
{},
|
98 |
+
{},
|
99 |
+
{},
|
100 |
+
],
|
101 |
+
'S5': [
|
102 |
+
{
|
103 |
+
'orientation': [0.1467377245426178, -0.162370964884758, -0.7551892995834351, 0.6178938746452332],
|
104 |
+
'translation': [2097.3916015625, 4880.94482421875, 1605.732421875],
|
105 |
+
},
|
106 |
+
{
|
107 |
+
'orientation': [0.6159758567810059, -0.7626792192459106, -0.15728192031383514, 0.1189815029501915],
|
108 |
+
'translation': [2031.7008056640625, -5167.93310546875, 1612.923095703125],
|
109 |
+
},
|
110 |
+
{
|
111 |
+
'orientation': [0.14291371405124664, -0.12907841801643372, 0.7678384780883789, -0.6110143065452576],
|
112 |
+
'translation': [-1620.5948486328125, 5171.65869140625, 1496.43701171875],
|
113 |
+
},
|
114 |
+
{
|
115 |
+
'orientation': [0.5920479893684387, -0.7814217805862427, 0.1274748593568802, -0.15036417543888092],
|
116 |
+
'translation': [-1637.1737060546875, -3867.3173828125, 1547.033203125],
|
117 |
+
},
|
118 |
+
],
|
119 |
+
'S6': [
|
120 |
+
{
|
121 |
+
'orientation': [0.1337897777557373, -0.15692396461963654, -0.7571090459823608, 0.6198879480361938],
|
122 |
+
'translation': [1935.4517822265625, 4950.24560546875, 1618.0838623046875],
|
123 |
+
},
|
124 |
+
{
|
125 |
+
'orientation': [0.6147197484970093, -0.7628812789916992, -0.16174767911434174, 0.11819244921207428],
|
126 |
+
'translation': [1969.803955078125, -5128.73876953125, 1632.77880859375],
|
127 |
+
},
|
128 |
+
{
|
129 |
+
'orientation': [0.1529948115348816, -0.13529130816459656, 0.7646096348762512, -0.6112781167030334],
|
130 |
+
'translation': [-1769.596435546875, 5185.361328125, 1476.993408203125],
|
131 |
+
},
|
132 |
+
{
|
133 |
+
'orientation': [0.5916101336479187, -0.7804774045944214, 0.12832270562648773, -0.1561593860387802],
|
134 |
+
'translation': [-1721.668701171875, -3884.13134765625, 1540.4879150390625],
|
135 |
+
},
|
136 |
+
],
|
137 |
+
'S7': [
|
138 |
+
{
|
139 |
+
'orientation': [0.1435241848230362, -0.1631336808204651, -0.7548328638076782, 0.6188824772834778],
|
140 |
+
'translation': [1974.512939453125, 4926.3544921875, 1597.8326416015625],
|
141 |
+
},
|
142 |
+
{
|
143 |
+
'orientation': [0.6141672730445862, -0.7638262510299683, -0.1596645563840866, 0.1177929937839508],
|
144 |
+
'translation': [1937.0584716796875, -5119.7900390625, 1631.5665283203125],
|
145 |
+
},
|
146 |
+
{
|
147 |
+
'orientation': [0.14550060033798218, -0.12874816358089447, 0.7660516500473022, -0.6127139329910278],
|
148 |
+
'translation': [-1741.8111572265625, 5208.24951171875, 1464.8245849609375],
|
149 |
+
},
|
150 |
+
{
|
151 |
+
'orientation': [0.5912848114967346, -0.7821764349937439, 0.12445473670959473, -0.15196487307548523],
|
152 |
+
'translation': [-1734.7105712890625, -3832.42138671875, 1548.5830078125],
|
153 |
+
},
|
154 |
+
],
|
155 |
+
'S8': [
|
156 |
+
{
|
157 |
+
'orientation': [0.14110587537288666, -0.15589867532253265, -0.7561917304992676, 0.619644045829773],
|
158 |
+
'translation': [2150.65185546875, 4896.1611328125, 1611.9046630859375],
|
159 |
+
},
|
160 |
+
{
|
161 |
+
'orientation': [0.6169601678848267, -0.7647668123245239, -0.14846350252628326, 0.11158157885074615],
|
162 |
+
'translation': [2219.965576171875, -5148.453125, 1613.0440673828125],
|
163 |
+
},
|
164 |
+
{
|
165 |
+
'orientation': [0.1471444070339203, -0.13377119600772858, 0.7670128345489502, -0.6100369691848755],
|
166 |
+
'translation': [-1571.2215576171875, 5137.0185546875, 1498.1761474609375],
|
167 |
+
},
|
168 |
+
{
|
169 |
+
'orientation': [0.5927824378013611, -0.7825870513916016, 0.12147816270589828, -0.14631995558738708],
|
170 |
+
'translation': [-1476.913330078125, -3896.7412109375, 1547.97216796875],
|
171 |
+
},
|
172 |
+
],
|
173 |
+
'S9': [
|
174 |
+
{
|
175 |
+
'orientation': [0.15540587902069092, -0.15548215806484222, -0.7532095313072205, 0.6199594736099243],
|
176 |
+
'translation': [2044.45849609375, 4935.1171875, 1481.2275390625],
|
177 |
+
},
|
178 |
+
{
|
179 |
+
'orientation': [0.618784487247467, -0.7634735107421875, -0.14132238924503326, 0.11933968216180801],
|
180 |
+
'translation': [1990.959716796875, -5123.810546875, 1568.8048095703125],
|
181 |
+
},
|
182 |
+
{
|
183 |
+
'orientation': [0.13357827067375183, -0.1367100477218628, 0.7689454555511475, -0.6100738644599915],
|
184 |
+
'translation': [-1670.9921875, 5211.98583984375, 1528.387939453125],
|
185 |
+
},
|
186 |
+
{
|
187 |
+
'orientation': [0.5879399180412292, -0.7823407053947449, 0.1427614390850067, -0.14794869720935822],
|
188 |
+
'translation': [-1696.04345703125, -3827.099853515625, 1591.4127197265625],
|
189 |
+
},
|
190 |
+
],
|
191 |
+
'S11': [
|
192 |
+
{
|
193 |
+
'orientation': [0.15232472121715546, -0.15442320704460144, -0.7547563314437866, 0.6191070079803467],
|
194 |
+
'translation': [2098.440185546875, 4926.5546875, 1500.278564453125],
|
195 |
+
},
|
196 |
+
{
|
197 |
+
'orientation': [0.6189449429512024, -0.7600917220115662, -0.15300633013248444, 0.1255258321762085],
|
198 |
+
'translation': [2083.182373046875, -4912.1728515625, 1561.07861328125],
|
199 |
+
},
|
200 |
+
{
|
201 |
+
'orientation': [0.14943228662014008, -0.15650227665901184, 0.7681233882904053, -0.6026304364204407],
|
202 |
+
'translation': [-1609.8153076171875, 5177.3359375, 1537.896728515625],
|
203 |
+
},
|
204 |
+
{
|
205 |
+
'orientation': [0.5894251465797424, -0.7818877100944519, 0.13991211354732513, -0.14715361595153809],
|
206 |
+
'translation': [-1590.738037109375, -3854.1689453125, 1578.017578125],
|
207 |
+
},
|
208 |
+
],
|
209 |
+
}
|
210 |
+
|
211 |
+
|
212 |
+
class Human36mDataset(MocapDataset):
|
213 |
+
def __init__(self, path, remove_static_joints=True):
|
214 |
+
super().__init__(fps=50, skeleton=h36m_skeleton)
|
215 |
+
|
216 |
+
self._cameras = copy.deepcopy(h36m_cameras_extrinsic_params)
|
217 |
+
for cameras in self._cameras.values():
|
218 |
+
for i, cam in enumerate(cameras):
|
219 |
+
cam.update(h36m_cameras_intrinsic_params[i])
|
220 |
+
for k, v in cam.items():
|
221 |
+
if k not in ['id', 'res_w', 'res_h']:
|
222 |
+
cam[k] = np.array(v, dtype='float32')
|
223 |
+
|
224 |
+
# Normalize camera frame
|
225 |
+
cam['center'] = normalize_screen_coordinates(cam['center'], w=cam['res_w'], h=cam['res_h']).astype('float32')
|
226 |
+
cam['focal_length'] = cam['focal_length'] / cam['res_w'] * 2
|
227 |
+
if 'translation' in cam:
|
228 |
+
cam['translation'] = cam['translation'] / 1000 # mm to meters
|
229 |
+
|
230 |
+
# Add intrinsic parameters vector
|
231 |
+
cam['intrinsic'] = np.concatenate((cam['focal_length'],
|
232 |
+
cam['center'],
|
233 |
+
cam['radial_distortion'],
|
234 |
+
cam['tangential_distortion']))
|
235 |
+
|
236 |
+
# Load serialized dataset
|
237 |
+
data = np.load(path)['positions_3d'].item()
|
238 |
+
|
239 |
+
self._data = {}
|
240 |
+
for subject, actions in data.items():
|
241 |
+
self._data[subject] = {}
|
242 |
+
for action_name, positions in actions.items():
|
243 |
+
self._data[subject][action_name] = {
|
244 |
+
'positions': positions,
|
245 |
+
'cameras': self._cameras[subject],
|
246 |
+
}
|
247 |
+
|
248 |
+
# import ipdb;ipdb.set_trace()
|
249 |
+
if remove_static_joints:
|
250 |
+
# Bring the skeleton to 17 joints instead of the original 32
|
251 |
+
self.remove_joints([4, 5, 9, 10, 11, 16, 20, 21, 22, 23, 24, 28, 29, 30, 31])
|
252 |
+
|
253 |
+
# Rewire shoulders to the correct parents
|
254 |
+
self._skeleton._parents[11] = 8
|
255 |
+
self._skeleton._parents[14] = 8
|
256 |
+
|
257 |
+
def supports_semi_supervised(self):
|
258 |
+
return True
|
common/humaneva_dataset.py
ADDED
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
|
8 |
+
import copy
|
9 |
+
|
10 |
+
import numpy as np
|
11 |
+
|
12 |
+
from common.mocap_dataset import MocapDataset
|
13 |
+
from common.skeleton import Skeleton
|
14 |
+
|
15 |
+
humaneva_skeleton = Skeleton(parents=[-1, 0, 1, 2, 3, 1, 5, 6, 0, 8, 9, 0, 11, 12, 1],
|
16 |
+
joints_left=[2, 3, 4, 8, 9, 10],
|
17 |
+
joints_right=[5, 6, 7, 11, 12, 13])
|
18 |
+
|
19 |
+
humaneva_cameras_intrinsic_params = [
|
20 |
+
{
|
21 |
+
'id': 'C1',
|
22 |
+
'res_w': 640,
|
23 |
+
'res_h': 480,
|
24 |
+
'azimuth': 0, # Only used for visualization
|
25 |
+
},
|
26 |
+
{
|
27 |
+
'id': 'C2',
|
28 |
+
'res_w': 640,
|
29 |
+
'res_h': 480,
|
30 |
+
'azimuth': -90, # Only used for visualization
|
31 |
+
},
|
32 |
+
{
|
33 |
+
'id': 'C3',
|
34 |
+
'res_w': 640,
|
35 |
+
'res_h': 480,
|
36 |
+
'azimuth': 90, # Only used for visualization
|
37 |
+
},
|
38 |
+
]
|
39 |
+
|
40 |
+
humaneva_cameras_extrinsic_params = {
|
41 |
+
'S1': [
|
42 |
+
{
|
43 |
+
'orientation': [0.424207, -0.4983646, -0.5802981, 0.4847012],
|
44 |
+
'translation': [4062.227, 663.2477, 1528.397],
|
45 |
+
},
|
46 |
+
{
|
47 |
+
'orientation': [0.6503354, -0.7481602, -0.0919284, 0.0941766],
|
48 |
+
'translation': [844.8131, -3805.2092, 1504.9929],
|
49 |
+
},
|
50 |
+
{
|
51 |
+
'orientation': [0.0664734, -0.0690535, 0.7416416, -0.6639132],
|
52 |
+
'translation': [-797.67377, 3916.3174, 1433.6602],
|
53 |
+
},
|
54 |
+
],
|
55 |
+
'S2': [
|
56 |
+
{
|
57 |
+
'orientation': [0.4214752, -0.4961493, -0.5838273, 0.4851187],
|
58 |
+
'translation': [4112.9121, 626.4929, 1545.2988],
|
59 |
+
},
|
60 |
+
{
|
61 |
+
'orientation': [0.6501393, -0.7476588, -0.0954617, 0.0959808],
|
62 |
+
'translation': [923.5740, -3877.9243, 1504.5518],
|
63 |
+
},
|
64 |
+
{
|
65 |
+
'orientation': [0.0699353, -0.0712403, 0.7421637, -0.662742],
|
66 |
+
'translation': [-781.4915, 3838.8853, 1444.9929],
|
67 |
+
},
|
68 |
+
],
|
69 |
+
'S3': [
|
70 |
+
{
|
71 |
+
'orientation': [0.424207, -0.4983646, -0.5802981, 0.4847012],
|
72 |
+
'translation': [4062.2271, 663.2477, 1528.3970],
|
73 |
+
},
|
74 |
+
{
|
75 |
+
'orientation': [0.6503354, -0.7481602, -0.0919284, 0.0941766],
|
76 |
+
'translation': [844.8131, -3805.2092, 1504.9929],
|
77 |
+
},
|
78 |
+
{
|
79 |
+
'orientation': [0.0664734, -0.0690535, 0.7416416, -0.6639132],
|
80 |
+
'translation': [-797.6738, 3916.3174, 1433.6602],
|
81 |
+
},
|
82 |
+
],
|
83 |
+
'S4': [
|
84 |
+
{},
|
85 |
+
{},
|
86 |
+
{},
|
87 |
+
],
|
88 |
+
|
89 |
+
}
|
90 |
+
|
91 |
+
|
92 |
+
class HumanEvaDataset(MocapDataset):
|
93 |
+
def __init__(self, path):
|
94 |
+
super().__init__(fps=60, skeleton=humaneva_skeleton)
|
95 |
+
|
96 |
+
self._cameras = copy.deepcopy(humaneva_cameras_extrinsic_params)
|
97 |
+
for cameras in self._cameras.values():
|
98 |
+
for i, cam in enumerate(cameras):
|
99 |
+
cam.update(humaneva_cameras_intrinsic_params[i])
|
100 |
+
for k, v in cam.items():
|
101 |
+
if k not in ['id', 'res_w', 'res_h']:
|
102 |
+
cam[k] = np.array(v, dtype='float32')
|
103 |
+
if 'translation' in cam:
|
104 |
+
cam['translation'] = cam['translation'] / 1000 # mm to meters
|
105 |
+
|
106 |
+
for subject in list(self._cameras.keys()):
|
107 |
+
data = self._cameras[subject]
|
108 |
+
del self._cameras[subject]
|
109 |
+
for prefix in ['Train/', 'Validate/', 'Unlabeled/Train/', 'Unlabeled/Validate/', 'Unlabeled/']:
|
110 |
+
self._cameras[prefix + subject] = data
|
111 |
+
|
112 |
+
# Load serialized dataset
|
113 |
+
data = np.load(path)['positions_3d'].item()
|
114 |
+
|
115 |
+
self._data = {}
|
116 |
+
for subject, actions in data.items():
|
117 |
+
self._data[subject] = {}
|
118 |
+
for action_name, positions in actions.items():
|
119 |
+
self._data[subject][action_name] = {
|
120 |
+
'positions': positions,
|
121 |
+
'cameras': self._cameras[subject],
|
122 |
+
}
|
common/inference_3d.py
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
import hashlib
|
8 |
+
import os
|
9 |
+
import pathlib
|
10 |
+
import shutil
|
11 |
+
import sys
|
12 |
+
import time
|
13 |
+
|
14 |
+
import cv2
|
15 |
+
import numpy as np
|
16 |
+
import torch
|
17 |
+
from torch.autograd import Variable
|
18 |
+
|
19 |
+
def get_varialbe(target):
|
20 |
+
num = len(target)
|
21 |
+
var = []
|
22 |
+
|
23 |
+
for i in range(num):
|
24 |
+
temp = Variable(target[i]).contiguous().cuda().type(torch.cuda.FloatTensor)
|
25 |
+
var.append(temp)
|
26 |
+
|
27 |
+
return var
|
28 |
+
def input_augmentation(input_2D, input_2D_flip, model_trans, joints_left, joints_right):
|
29 |
+
B, T, J, C = input_2D.shape
|
30 |
+
|
31 |
+
input_2D_flip = input_2D_flip.view(B, T, J, C, 1).permute(0, 3, 1, 2, 4)
|
32 |
+
input_2D_non_flip = input_2D.view(B, T, J, C, 1).permute(0, 3, 1, 2, 4)
|
33 |
+
|
34 |
+
output_3D_flip, output_3D_flip_VTE = model_trans(input_2D_flip)
|
35 |
+
|
36 |
+
output_3D_flip_VTE[:, 0] *= -1
|
37 |
+
output_3D_flip[:, 0] *= -1
|
38 |
+
|
39 |
+
output_3D_flip_VTE[:, :, :, joints_left + joints_right] = output_3D_flip_VTE[:, :, :, joints_right + joints_left]
|
40 |
+
output_3D_flip[:, :, :, joints_left + joints_right] = output_3D_flip[:, :, :, joints_right + joints_left]
|
41 |
+
|
42 |
+
output_3D_non_flip, output_3D_non_flip_VTE = model_trans(input_2D_non_flip)
|
43 |
+
|
44 |
+
output_3D_VTE = (output_3D_non_flip_VTE + output_3D_flip_VTE) / 2
|
45 |
+
output_3D = (output_3D_non_flip + output_3D_flip) / 2
|
46 |
+
|
47 |
+
input_2D = input_2D_non_flip
|
48 |
+
|
49 |
+
return input_2D, output_3D, output_3D_VTE
|
50 |
+
|
51 |
+
def step(opt, dataLoader, model, optimizer=None, epoch=None):
|
52 |
+
model_trans = model['trans']
|
53 |
+
|
54 |
+
model_trans.eval()
|
55 |
+
|
56 |
+
joints_left = [4, 5, 6, 11, 12, 13]
|
57 |
+
joints_right = [1, 2, 3, 14, 15, 16]
|
58 |
+
epoch_cnt=0
|
59 |
+
out = []
|
60 |
+
for _, batch, batch_2d, batch_2d_flip in dataLoader.next_epoch():
|
61 |
+
#[gt_3D, input_2D] = get_varialbe([batch, batch_2d])
|
62 |
+
#input_2D = Variable(batch_2d).contiguous().cuda().type(torch.cuda.FloatTensor)
|
63 |
+
input_2D = torch.from_numpy(batch_2d.astype('float32'))
|
64 |
+
input_2D_flip = torch.from_numpy(batch_2d_flip.astype('float32'))
|
65 |
+
if torch.cuda.is_available():
|
66 |
+
input_2D = input_2D.cuda()
|
67 |
+
input_2D_flip = input_2D_flip.cuda()
|
68 |
+
|
69 |
+
N = input_2D.size(0)
|
70 |
+
|
71 |
+
# out_target = gt_3D.clone().view(N, -1, opt.out_joints, opt.out_channels)
|
72 |
+
# out_target[:, :, 0] = 0
|
73 |
+
# gt_3D = gt_3D.view(N, -1, opt.out_joints, opt.out_channels).type(torch.cuda.FloatTensor)
|
74 |
+
#
|
75 |
+
# if out_target.size(1) > 1:
|
76 |
+
# out_target_single = out_target[:, opt.pad].unsqueeze(1)
|
77 |
+
# gt_3D_single = gt_3D[:, opt.pad].unsqueeze(1)
|
78 |
+
# else:
|
79 |
+
# out_target_single = out_target
|
80 |
+
# gt_3D_single = gt_3D
|
81 |
+
|
82 |
+
|
83 |
+
input_2D, output_3D, output_3D_VTE = input_augmentation(input_2D, input_2D_flip, model_trans, joints_left, joints_right)
|
84 |
+
|
85 |
+
|
86 |
+
output_3D_VTE = output_3D_VTE.permute(0, 2, 3, 4, 1).contiguous().view(N, -1, opt.out_joints, opt.out_channels)
|
87 |
+
output_3D = output_3D.permute(0, 2, 3, 4, 1).contiguous().view(N, -1, opt.out_joints, opt.out_channels)
|
88 |
+
|
89 |
+
output_3D_single = output_3D
|
90 |
+
|
91 |
+
|
92 |
+
pred_out = output_3D_single
|
93 |
+
|
94 |
+
input_2D = input_2D.permute(0, 2, 3, 1, 4).view(N, -1, opt.n_joints, 2)
|
95 |
+
|
96 |
+
pred_out[:, :, 0, :] = 0
|
97 |
+
|
98 |
+
if epoch_cnt == 0:
|
99 |
+
out = pred_out.squeeze(1).cpu()
|
100 |
+
else:
|
101 |
+
out = torch.cat((out, pred_out.squeeze(1).cpu()), dim=0)
|
102 |
+
epoch_cnt +=1
|
103 |
+
return out.numpy()
|
104 |
+
|
105 |
+
def val(opt, val_loader, model):
|
106 |
+
with torch.no_grad():
|
107 |
+
return step(opt, val_loader, model)
|
common/jpt_arguments.py
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
|
8 |
+
import argparse
|
9 |
+
|
10 |
+
|
11 |
+
def parse_args():
|
12 |
+
parser = argparse.ArgumentParser(description='Training script')
|
13 |
+
|
14 |
+
# General arguments
|
15 |
+
parser.add_argument('-d', '--dataset', default='h36m', type=str, metavar='NAME', help='target dataset') # h36m or humaneva
|
16 |
+
parser.add_argument('-k', '--keypoints', default='cpn_ft_h36m_dbb', type=str, metavar='NAME', help='2D detections to use')
|
17 |
+
parser.add_argument('-str', '--subjects-train', default='S1,S5,S6,S7,S8', type=str, metavar='LIST',
|
18 |
+
help='training subjects separated by comma')
|
19 |
+
parser.add_argument('-ste', '--subjects-test', default='S9,S11', type=str, metavar='LIST', help='test subjects separated by comma')
|
20 |
+
parser.add_argument('-sun', '--subjects-unlabeled', default='', type=str, metavar='LIST',
|
21 |
+
help='unlabeled subjects separated by comma for self-supervision')
|
22 |
+
parser.add_argument('-a', '--actions', default='*', type=str, metavar='LIST',
|
23 |
+
help='actions to train/test on, separated by comma, or * for all')
|
24 |
+
parser.add_argument('-c', '--checkpoint', default='checkpoint', type=str, metavar='PATH',
|
25 |
+
help='checkpoint directory')
|
26 |
+
parser.add_argument('--checkpoint-frequency', default=10, type=int, metavar='N',
|
27 |
+
help='create a checkpoint every N epochs')
|
28 |
+
parser.add_argument('-r', '--resume', default='', type=str, metavar='FILENAME',
|
29 |
+
help='checkpoint to resume (file name)')
|
30 |
+
parser.add_argument('--evaluate', default='pretrained_h36m_detectron_coco.bin', type=str, metavar='FILENAME', help='checkpoint to evaluate (file name)')
|
31 |
+
parser.add_argument('--render', action='store_true', help='visualize a particular video')
|
32 |
+
parser.add_argument('--by-subject', action='store_true', help='break down error by subject (on evaluation)')
|
33 |
+
parser.add_argument('--export-training-curves', action='store_true', help='save training curves as .png images')
|
34 |
+
|
35 |
+
# Model arguments
|
36 |
+
parser.add_argument('-s', '--stride', default=1, type=int, metavar='N', help='chunk size to use during training')
|
37 |
+
parser.add_argument('-e', '--epochs', default=60, type=int, metavar='N', help='number of training epochs')
|
38 |
+
parser.add_argument('-b', '--batch-size', default=1024, type=int, metavar='N', help='batch size in terms of predicted frames')
|
39 |
+
parser.add_argument('-drop', '--dropout', default=0.25, type=float, metavar='P', help='dropout probability')
|
40 |
+
parser.add_argument('-lr', '--learning-rate', default=0.001, type=float, metavar='LR', help='initial learning rate')
|
41 |
+
parser.add_argument('-lrd', '--lr-decay', default=0.95, type=float, metavar='LR', help='learning rate decay per epoch')
|
42 |
+
parser.add_argument('-no-da', '--no-data-augmentation', dest='data_augmentation', action='store_false',
|
43 |
+
help='disable train-time flipping')
|
44 |
+
parser.add_argument('-no-tta', '--no-test-time-augmentation', dest='test_time_augmentation', action='store_false',
|
45 |
+
help='disable test-time flipping')
|
46 |
+
parser.add_argument('-arc', '--architecture', default='3,3,3,3,3', type=str, metavar='LAYERS', help='filter widths separated by comma')
|
47 |
+
parser.add_argument('--causal', action='store_true', help='use causal convolutions for real-time processing')
|
48 |
+
parser.add_argument('-ch', '--channels', default=1024, type=int, metavar='N', help='number of channels in convolution layers')
|
49 |
+
|
50 |
+
# Experimental
|
51 |
+
parser.add_argument('--subset', default=1, type=float, metavar='FRACTION', help='reduce dataset size by fraction')
|
52 |
+
parser.add_argument('--downsample', default=1, type=int, metavar='FACTOR', help='downsample frame rate by factor (semi-supervised)')
|
53 |
+
parser.add_argument('--warmup', default=1, type=int, metavar='N', help='warm-up epochs for semi-supervision')
|
54 |
+
parser.add_argument('--no-eval', action='store_true', help='disable epoch evaluation while training (small speed-up)')
|
55 |
+
parser.add_argument('--dense', action='store_true', help='use dense convolutions instead of dilated convolutions')
|
56 |
+
parser.add_argument('--disable-optimizations', action='store_true', help='disable optimized model for single-frame predictions')
|
57 |
+
parser.add_argument('--linear-projection', action='store_true', help='use only linear coefficients for semi-supervised projection')
|
58 |
+
parser.add_argument('--no-bone-length', action='store_false', dest='bone_length_term',
|
59 |
+
help='disable bone length term in semi-supervised settings')
|
60 |
+
parser.add_argument('--no-proj', action='store_true', help='disable projection for semi-supervised setting')
|
61 |
+
|
62 |
+
# Visualization
|
63 |
+
parser.add_argument('--viz-subject', type=str, metavar='STR', help='subject to render')
|
64 |
+
parser.add_argument('--viz-action', type=str, metavar='STR', help='action to render')
|
65 |
+
parser.add_argument('--viz-camera', type=int, default=0, metavar='N', help='camera to render')
|
66 |
+
parser.add_argument('--viz-video', type=str, metavar='PATH', help='path to input video')
|
67 |
+
parser.add_argument('--viz-skip', type=int, default=0, metavar='N', help='skip first N frames of input video')
|
68 |
+
parser.add_argument('--viz-output', type=str, metavar='PATH', help='output file name (.gif or .mp4)')
|
69 |
+
parser.add_argument('--viz-bitrate', type=int, default=30000, metavar='N', help='bitrate for mp4 videos')
|
70 |
+
parser.add_argument('--viz-no-ground-truth', action='store_true', help='do not show ground-truth poses')
|
71 |
+
parser.add_argument('--viz-limit', type=int, default=-1, metavar='N', help='only render first N frames')
|
72 |
+
parser.add_argument('--viz-downsample', type=int, default=1, metavar='N', help='downsample FPS by a factor N')
|
73 |
+
parser.add_argument('--viz-size', type=int, default=5, metavar='N', help='image size')
|
74 |
+
# self add
|
75 |
+
parser.add_argument('--input-npz', dest='input_npz', type=str, default='', help='input 2d numpy file')
|
76 |
+
|
77 |
+
parser.set_defaults(bone_length_term=True)
|
78 |
+
parser.set_defaults(data_augmentation=True)
|
79 |
+
parser.set_defaults(test_time_augmentation=True)
|
80 |
+
|
81 |
+
args = parser.parse_args(args=[])
|
82 |
+
# Check invalid configuration
|
83 |
+
if args.resume and args.evaluate:
|
84 |
+
print('Invalid flags: --resume and --evaluate cannot be set at the same time')
|
85 |
+
exit()
|
86 |
+
|
87 |
+
if args.export_training_curves and args.no_eval:
|
88 |
+
print('Invalid flags: --export-training-curves and --no-eval cannot be set at the same time')
|
89 |
+
exit()
|
90 |
+
|
91 |
+
# opt = parser.parse_args(args=[])
|
92 |
+
return args
|
common/loss.py
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
|
8 |
+
import numpy as np
|
9 |
+
import torch
|
10 |
+
|
11 |
+
|
12 |
+
def mpjpe(predicted, target):
|
13 |
+
"""
|
14 |
+
Mean per-joint position error (i.e. mean Euclidean distance),
|
15 |
+
often referred to as "Protocol #1" in many papers.
|
16 |
+
"""
|
17 |
+
assert predicted.shape == target.shape
|
18 |
+
return torch.mean(torch.norm(predicted - target, dim=len(target.shape) - 1))
|
19 |
+
|
20 |
+
|
21 |
+
def weighted_mpjpe(predicted, target, w):
|
22 |
+
"""
|
23 |
+
Weighted mean per-joint position error (i.e. mean Euclidean distance)
|
24 |
+
"""
|
25 |
+
assert predicted.shape == target.shape
|
26 |
+
assert w.shape[0] == predicted.shape[0]
|
27 |
+
return torch.mean(w * torch.norm(predicted - target, dim=len(target.shape) - 1))
|
28 |
+
|
29 |
+
|
30 |
+
def p_mpjpe(predicted, target):
|
31 |
+
"""
|
32 |
+
Pose error: MPJPE after rigid alignment (scale, rotation, and translation),
|
33 |
+
often referred to as "Protocol #2" in many papers.
|
34 |
+
"""
|
35 |
+
assert predicted.shape == target.shape
|
36 |
+
|
37 |
+
muX = np.mean(target, axis=1, keepdims=True)
|
38 |
+
muY = np.mean(predicted, axis=1, keepdims=True)
|
39 |
+
|
40 |
+
X0 = target - muX
|
41 |
+
Y0 = predicted - muY
|
42 |
+
|
43 |
+
normX = np.sqrt(np.sum(X0 ** 2, axis=(1, 2), keepdims=True))
|
44 |
+
normY = np.sqrt(np.sum(Y0 ** 2, axis=(1, 2), keepdims=True))
|
45 |
+
|
46 |
+
X0 /= normX
|
47 |
+
Y0 /= normY
|
48 |
+
|
49 |
+
H = np.matmul(X0.transpose(0, 2, 1), Y0)
|
50 |
+
U, s, Vt = np.linalg.svd(H)
|
51 |
+
V = Vt.transpose(0, 2, 1)
|
52 |
+
R = np.matmul(V, U.transpose(0, 2, 1))
|
53 |
+
|
54 |
+
# Avoid improper rotations (reflections), i.e. rotations with det(R) = -1
|
55 |
+
sign_detR = np.sign(np.expand_dims(np.linalg.det(R), axis=1))
|
56 |
+
V[:, :, -1] *= sign_detR
|
57 |
+
s[:, -1] *= sign_detR.flatten()
|
58 |
+
R = np.matmul(V, U.transpose(0, 2, 1)) # Rotation
|
59 |
+
|
60 |
+
tr = np.expand_dims(np.sum(s, axis=1, keepdims=True), axis=2)
|
61 |
+
|
62 |
+
a = tr * normX / normY # Scale
|
63 |
+
t = muX - a * np.matmul(muY, R) # Translation
|
64 |
+
|
65 |
+
# Perform rigid transformation on the input
|
66 |
+
predicted_aligned = a * np.matmul(predicted, R) + t
|
67 |
+
|
68 |
+
# Return MPJPE
|
69 |
+
return np.mean(np.linalg.norm(predicted_aligned - target, axis=len(target.shape) - 1))
|
70 |
+
|
71 |
+
|
72 |
+
def n_mpjpe(predicted, target):
|
73 |
+
"""
|
74 |
+
Normalized MPJPE (scale only), adapted from:
|
75 |
+
https://github.com/hrhodin/UnsupervisedGeometryAwareRepresentationLearning/blob/master/losses/poses.py
|
76 |
+
"""
|
77 |
+
assert predicted.shape == target.shape
|
78 |
+
|
79 |
+
norm_predicted = torch.mean(torch.sum(predicted ** 2, dim=3, keepdim=True), dim=2, keepdim=True)
|
80 |
+
norm_target = torch.mean(torch.sum(target * predicted, dim=3, keepdim=True), dim=2, keepdim=True)
|
81 |
+
scale = norm_target / norm_predicted
|
82 |
+
return mpjpe(scale * predicted, target)
|
83 |
+
|
84 |
+
|
85 |
+
def mean_velocity_error(predicted, target):
|
86 |
+
"""
|
87 |
+
Mean per-joint velocity error (i.e. mean Euclidean distance of the 1st derivative)
|
88 |
+
"""
|
89 |
+
assert predicted.shape == target.shape
|
90 |
+
|
91 |
+
velocity_predicted = np.diff(predicted, axis=0)
|
92 |
+
velocity_target = np.diff(target, axis=0)
|
93 |
+
|
94 |
+
return np.mean(np.linalg.norm(velocity_predicted - velocity_target, axis=len(target.shape) - 1))
|
common/mocap_dataset.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
|
8 |
+
|
9 |
+
class MocapDataset:
|
10 |
+
def __init__(self, fps, skeleton):
|
11 |
+
self._skeleton = skeleton
|
12 |
+
self._fps = fps
|
13 |
+
self._data = None # Must be filled by subclass
|
14 |
+
self._cameras = None # Must be filled by subclass
|
15 |
+
|
16 |
+
def remove_joints(self, joints_to_remove):
|
17 |
+
kept_joints = self._skeleton.remove_joints(joints_to_remove)
|
18 |
+
for subject in self._data.keys():
|
19 |
+
for action in self._data[subject].keys():
|
20 |
+
s = self._data[subject][action]
|
21 |
+
s['positions'] = s['positions'][:, kept_joints]
|
22 |
+
|
23 |
+
def __getitem__(self, key):
|
24 |
+
return self._data[key]
|
25 |
+
|
26 |
+
def subjects(self):
|
27 |
+
return self._data.keys()
|
28 |
+
|
29 |
+
def fps(self):
|
30 |
+
return self._fps
|
31 |
+
|
32 |
+
def skeleton(self):
|
33 |
+
return self._skeleton
|
34 |
+
|
35 |
+
def cameras(self):
|
36 |
+
return self._cameras
|
37 |
+
|
38 |
+
def supports_semi_supervised(self):
|
39 |
+
# This method can be overridden
|
40 |
+
return False
|
common/model.py
ADDED
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
|
8 |
+
import torch.nn as nn
|
9 |
+
|
10 |
+
|
11 |
+
class TemporalModelBase(nn.Module):
|
12 |
+
"""
|
13 |
+
Do not instantiate this class.
|
14 |
+
"""
|
15 |
+
|
16 |
+
def __init__(self, num_joints_in, in_features, num_joints_out,
|
17 |
+
filter_widths, causal, dropout, channels):
|
18 |
+
super().__init__()
|
19 |
+
|
20 |
+
# Validate input
|
21 |
+
for fw in filter_widths:
|
22 |
+
assert fw % 2 != 0, 'Only odd filter widths are supported'
|
23 |
+
|
24 |
+
self.num_joints_in = num_joints_in
|
25 |
+
self.in_features = in_features
|
26 |
+
self.num_joints_out = num_joints_out
|
27 |
+
self.filter_widths = filter_widths
|
28 |
+
|
29 |
+
self.drop = nn.Dropout(dropout)
|
30 |
+
self.relu = nn.ReLU(inplace=True)
|
31 |
+
|
32 |
+
self.pad = [filter_widths[0] // 2]
|
33 |
+
self.expand_bn = nn.BatchNorm1d(channels, momentum=0.1)
|
34 |
+
self.shrink = nn.Conv1d(channels, num_joints_out * 3, 1)
|
35 |
+
|
36 |
+
def set_bn_momentum(self, momentum):
|
37 |
+
self.expand_bn.momentum = momentum
|
38 |
+
for bn in self.layers_bn:
|
39 |
+
bn.momentum = momentum
|
40 |
+
|
41 |
+
def receptive_field(self):
|
42 |
+
"""
|
43 |
+
Return the total receptive field of this model as # of frames.
|
44 |
+
"""
|
45 |
+
frames = 0
|
46 |
+
for f in self.pad:
|
47 |
+
frames += f
|
48 |
+
return 1 + 2 * frames
|
49 |
+
|
50 |
+
def total_causal_shift(self):
|
51 |
+
"""
|
52 |
+
Return the asymmetric offset for sequence padding.
|
53 |
+
The returned value is typically 0 if causal convolutions are disabled,
|
54 |
+
otherwise it is half the receptive field.
|
55 |
+
"""
|
56 |
+
frames = self.causal_shift[0]
|
57 |
+
next_dilation = self.filter_widths[0]
|
58 |
+
for i in range(1, len(self.filter_widths)):
|
59 |
+
frames += self.causal_shift[i] * next_dilation
|
60 |
+
next_dilation *= self.filter_widths[i]
|
61 |
+
return frames
|
62 |
+
|
63 |
+
def forward(self, x):
|
64 |
+
assert len(x.shape) == 4
|
65 |
+
assert x.shape[-2] == self.num_joints_in
|
66 |
+
assert x.shape[-1] == self.in_features
|
67 |
+
|
68 |
+
sz = x.shape[:3]
|
69 |
+
x = x.view(x.shape[0], x.shape[1], -1)
|
70 |
+
x = x.permute(0, 2, 1)
|
71 |
+
|
72 |
+
x = self._forward_blocks(x)
|
73 |
+
|
74 |
+
x = x.permute(0, 2, 1)
|
75 |
+
x = x.view(sz[0], -1, self.num_joints_out, 3)
|
76 |
+
|
77 |
+
return x
|
78 |
+
|
79 |
+
|
80 |
+
class TemporalModel(TemporalModelBase):
|
81 |
+
"""
|
82 |
+
Reference 3D pose estimation model with temporal convolutions.
|
83 |
+
This implementation can be used for all use-cases.
|
84 |
+
"""
|
85 |
+
|
86 |
+
def __init__(self, num_joints_in, in_features, num_joints_out,
|
87 |
+
filter_widths, causal=False, dropout=0.25, channels=1024, dense=False):
|
88 |
+
"""
|
89 |
+
Initialize this model.
|
90 |
+
|
91 |
+
Arguments:
|
92 |
+
num_joints_in -- number of input joints (e.g. 17 for Human3.6M)
|
93 |
+
in_features -- number of input features for each joint (typically 2 for 2D input)
|
94 |
+
num_joints_out -- number of output joints (can be different than input)
|
95 |
+
filter_widths -- list of convolution widths, which also determines the # of blocks and receptive field
|
96 |
+
causal -- use causal convolutions instead of symmetric convolutions (for real-time applications)
|
97 |
+
dropout -- dropout probability
|
98 |
+
channels -- number of convolution channels
|
99 |
+
dense -- use regular dense convolutions instead of dilated convolutions (ablation experiment)
|
100 |
+
"""
|
101 |
+
super().__init__(num_joints_in, in_features, num_joints_out, filter_widths, causal, dropout, channels)
|
102 |
+
|
103 |
+
self.expand_conv = nn.Conv1d(num_joints_in * in_features, channels, filter_widths[0], bias=False)
|
104 |
+
|
105 |
+
layers_conv = []
|
106 |
+
layers_bn = []
|
107 |
+
|
108 |
+
self.causal_shift = [(filter_widths[0]) // 2 if causal else 0]
|
109 |
+
next_dilation = filter_widths[0]
|
110 |
+
for i in range(1, len(filter_widths)):
|
111 |
+
self.pad.append((filter_widths[i] - 1) * next_dilation // 2)
|
112 |
+
self.causal_shift.append((filter_widths[i] // 2 * next_dilation) if causal else 0)
|
113 |
+
|
114 |
+
layers_conv.append(nn.Conv1d(channels, channels,
|
115 |
+
filter_widths[i] if not dense else (2 * self.pad[-1] + 1),
|
116 |
+
dilation=next_dilation if not dense else 1,
|
117 |
+
bias=False))
|
118 |
+
layers_bn.append(nn.BatchNorm1d(channels, momentum=0.1))
|
119 |
+
layers_conv.append(nn.Conv1d(channels, channels, 1, dilation=1, bias=False))
|
120 |
+
layers_bn.append(nn.BatchNorm1d(channels, momentum=0.1))
|
121 |
+
|
122 |
+
next_dilation *= filter_widths[i]
|
123 |
+
|
124 |
+
self.layers_conv = nn.ModuleList(layers_conv)
|
125 |
+
self.layers_bn = nn.ModuleList(layers_bn)
|
126 |
+
|
127 |
+
def _forward_blocks(self, x):
|
128 |
+
x = self.drop(self.relu(self.expand_bn(self.expand_conv(x))))
|
129 |
+
|
130 |
+
for i in range(len(self.pad) - 1):
|
131 |
+
pad = self.pad[i + 1]
|
132 |
+
shift = self.causal_shift[i + 1]
|
133 |
+
# clip
|
134 |
+
res = x[:, :, pad + shift: x.shape[2] - pad + shift]
|
135 |
+
|
136 |
+
x = self.drop(self.relu(self.layers_bn[2 * i](self.layers_conv[2 * i](x))))
|
137 |
+
x = res + self.drop(self.relu(self.layers_bn[2 * i + 1](self.layers_conv[2 * i + 1](x))))
|
138 |
+
|
139 |
+
x = self.shrink(x)
|
140 |
+
return x
|
141 |
+
|
142 |
+
|
143 |
+
class TemporalModelOptimized1f(TemporalModelBase):
|
144 |
+
"""
|
145 |
+
3D pose estimation model optimized for single-frame batching, i.e.
|
146 |
+
where batches have input length = receptive field, and output length = 1.
|
147 |
+
This scenario is only used for training when stride == 1.
|
148 |
+
|
149 |
+
This implementation replaces dilated convolutions with strided convolutions
|
150 |
+
to avoid generating unused intermediate results. The weights are interchangeable
|
151 |
+
with the reference implementation.
|
152 |
+
"""
|
153 |
+
|
154 |
+
def __init__(self, num_joints_in, in_features, num_joints_out,
|
155 |
+
filter_widths, causal=False, dropout=0.25, channels=1024):
|
156 |
+
"""
|
157 |
+
Initialize this model.
|
158 |
+
|
159 |
+
Arguments:
|
160 |
+
num_joints_in -- number of input joints (e.g. 17 for Human3.6M)
|
161 |
+
in_features -- number of input features for each joint (typically 2 for 2D input)
|
162 |
+
num_joints_out -- number of output joints (can be different than input)
|
163 |
+
filter_widths -- list of convolution widths, which also determines the # of blocks and receptive field
|
164 |
+
causal -- use causal convolutions instead of symmetric convolutions (for real-time applications)
|
165 |
+
dropout -- dropout probability
|
166 |
+
channels -- number of convolution channels
|
167 |
+
"""
|
168 |
+
super().__init__(num_joints_in, in_features, num_joints_out, filter_widths, causal, dropout, channels)
|
169 |
+
|
170 |
+
self.expand_conv = nn.Conv1d(num_joints_in * in_features, channels, filter_widths[0], stride=filter_widths[0], bias=False)
|
171 |
+
|
172 |
+
layers_conv = []
|
173 |
+
layers_bn = []
|
174 |
+
|
175 |
+
self.causal_shift = [(filter_widths[0] // 2) if causal else 0]
|
176 |
+
next_dilation = filter_widths[0]
|
177 |
+
for i in range(1, len(filter_widths)):
|
178 |
+
self.pad.append((filter_widths[i] - 1) * next_dilation // 2)
|
179 |
+
self.causal_shift.append((filter_widths[i] // 2) if causal else 0)
|
180 |
+
|
181 |
+
layers_conv.append(nn.Conv1d(channels, channels, filter_widths[i], stride=filter_widths[i], bias=False))
|
182 |
+
layers_bn.append(nn.BatchNorm1d(channels, momentum=0.1))
|
183 |
+
layers_conv.append(nn.Conv1d(channels, channels, 1, dilation=1, bias=False))
|
184 |
+
layers_bn.append(nn.BatchNorm1d(channels, momentum=0.1))
|
185 |
+
next_dilation *= filter_widths[i]
|
186 |
+
|
187 |
+
self.layers_conv = nn.ModuleList(layers_conv)
|
188 |
+
self.layers_bn = nn.ModuleList(layers_bn)
|
189 |
+
|
190 |
+
def _forward_blocks(self, x):
|
191 |
+
x = self.drop(self.relu(self.expand_bn(self.expand_conv(x))))
|
192 |
+
|
193 |
+
for i in range(len(self.pad) - 1):
|
194 |
+
res = x[:, :, self.causal_shift[i + 1] + self.filter_widths[i + 1] // 2:: self.filter_widths[i + 1]]
|
195 |
+
|
196 |
+
x = self.drop(self.relu(self.layers_bn[2 * i](self.layers_conv[2 * i](x))))
|
197 |
+
x = res + self.drop(self.relu(self.layers_bn[2 * i + 1](self.layers_conv[2 * i + 1](x))))
|
198 |
+
|
199 |
+
x = self.shrink(x)
|
200 |
+
return x
|
common/quaternion.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
|
8 |
+
import torch
|
9 |
+
|
10 |
+
|
11 |
+
def qrot(q, v):
|
12 |
+
"""
|
13 |
+
Rotate vector(s) v about the rotation described by 四元数quaternion(s) q.
|
14 |
+
Expects a tensor of shape (*, 4) for q and a tensor of shape (*, 3) for v,
|
15 |
+
where * denotes any number of dimensions.
|
16 |
+
Returns a tensor of shape (*, 3).
|
17 |
+
"""
|
18 |
+
assert q.shape[-1] == 4
|
19 |
+
assert v.shape[-1] == 3
|
20 |
+
assert q.shape[:-1] == v.shape[:-1]
|
21 |
+
|
22 |
+
qvec = q[..., 1:]
|
23 |
+
uv = torch.cross(qvec, v, dim=len(q.shape) - 1)
|
24 |
+
uuv = torch.cross(qvec, uv, dim=len(q.shape) - 1)
|
25 |
+
return (v + 2 * (q[..., :1] * uv + uuv))
|
26 |
+
|
27 |
+
|
28 |
+
def qinverse(q, inplace=False):
|
29 |
+
# We assume the quaternion to be normalized
|
30 |
+
if inplace:
|
31 |
+
q[..., 1:] *= -1
|
32 |
+
return q
|
33 |
+
else:
|
34 |
+
w = q[..., :1]
|
35 |
+
xyz = q[..., 1:]
|
36 |
+
return torch.cat((w, -xyz), dim=len(q.shape) - 1)
|
common/skeleton.py
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
|
8 |
+
import numpy as np
|
9 |
+
|
10 |
+
|
11 |
+
class Skeleton:
|
12 |
+
def __init__(self, parents, joints_left, joints_right):
|
13 |
+
assert len(joints_left) == len(joints_right)
|
14 |
+
|
15 |
+
self._parents = np.array(parents)
|
16 |
+
self._joints_left = joints_left
|
17 |
+
self._joints_right = joints_right
|
18 |
+
self._compute_metadata()
|
19 |
+
|
20 |
+
def num_joints(self):
|
21 |
+
return len(self._parents)
|
22 |
+
|
23 |
+
def parents(self):
|
24 |
+
return self._parents
|
25 |
+
|
26 |
+
def has_children(self):
|
27 |
+
return self._has_children
|
28 |
+
|
29 |
+
def children(self):
|
30 |
+
return self._children
|
31 |
+
|
32 |
+
def remove_joints(self, joints_to_remove):
|
33 |
+
"""
|
34 |
+
Remove the joints specified in 'joints_to_remove'.
|
35 |
+
"""
|
36 |
+
valid_joints = []
|
37 |
+
for joint in range(len(self._parents)):
|
38 |
+
if joint not in joints_to_remove:
|
39 |
+
valid_joints.append(joint)
|
40 |
+
|
41 |
+
for i in range(len(self._parents)):
|
42 |
+
while self._parents[i] in joints_to_remove:
|
43 |
+
self._parents[i] = self._parents[self._parents[i]]
|
44 |
+
|
45 |
+
index_offsets = np.zeros(len(self._parents), dtype=int)
|
46 |
+
new_parents = []
|
47 |
+
for i, parent in enumerate(self._parents):
|
48 |
+
if i not in joints_to_remove:
|
49 |
+
new_parents.append(parent - index_offsets[parent])
|
50 |
+
else:
|
51 |
+
index_offsets[i:] += 1
|
52 |
+
self._parents = np.array(new_parents)
|
53 |
+
|
54 |
+
if self._joints_left is not None:
|
55 |
+
new_joints_left = []
|
56 |
+
for joint in self._joints_left:
|
57 |
+
if joint in valid_joints:
|
58 |
+
new_joints_left.append(joint - index_offsets[joint])
|
59 |
+
self._joints_left = new_joints_left
|
60 |
+
if self._joints_right is not None:
|
61 |
+
new_joints_right = []
|
62 |
+
for joint in self._joints_right:
|
63 |
+
if joint in valid_joints:
|
64 |
+
new_joints_right.append(joint - index_offsets[joint])
|
65 |
+
self._joints_right = new_joints_right
|
66 |
+
|
67 |
+
self._compute_metadata()
|
68 |
+
|
69 |
+
return valid_joints
|
70 |
+
|
71 |
+
def joints_left(self):
|
72 |
+
return self._joints_left
|
73 |
+
|
74 |
+
def joints_right(self):
|
75 |
+
return self._joints_right
|
76 |
+
|
77 |
+
def _compute_metadata(self):
|
78 |
+
self._has_children = np.zeros(len(self._parents)).astype(bool)
|
79 |
+
for i, parent in enumerate(self._parents):
|
80 |
+
if parent != -1:
|
81 |
+
self._has_children[parent] = True
|
82 |
+
|
83 |
+
self._children = []
|
84 |
+
for i, parent in enumerate(self._parents):
|
85 |
+
self._children.append([])
|
86 |
+
for i, parent in enumerate(self._parents):
|
87 |
+
if parent != -1:
|
88 |
+
self._children[parent].append(i)
|
common/utils.py
ADDED
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
import hashlib
|
8 |
+
import os
|
9 |
+
import pathlib
|
10 |
+
import shutil
|
11 |
+
import sys
|
12 |
+
import time
|
13 |
+
|
14 |
+
import cv2
|
15 |
+
import numpy as np
|
16 |
+
import torch
|
17 |
+
|
18 |
+
|
19 |
+
def add_path():
|
20 |
+
Alphapose_path = os.path.abspath('joints_detectors/Alphapose')
|
21 |
+
hrnet_path = os.path.abspath('joints_detectors/hrnet')
|
22 |
+
trackers_path = os.path.abspath('pose_trackers')
|
23 |
+
paths = filter(lambda p: p not in sys.path, [Alphapose_path, hrnet_path, trackers_path])
|
24 |
+
|
25 |
+
sys.path.extend(paths)
|
26 |
+
|
27 |
+
|
28 |
+
def wrap(func, *args, unsqueeze=False):
|
29 |
+
"""
|
30 |
+
Wrap a torch function so it can be called with NumPy arrays.
|
31 |
+
Input and return types are seamlessly converted.
|
32 |
+
"""
|
33 |
+
|
34 |
+
# Convert input types where applicable
|
35 |
+
args = list(args)
|
36 |
+
for i, arg in enumerate(args):
|
37 |
+
if type(arg) == np.ndarray:
|
38 |
+
args[i] = torch.from_numpy(arg)
|
39 |
+
if unsqueeze:
|
40 |
+
args[i] = args[i].unsqueeze(0)
|
41 |
+
|
42 |
+
result = func(*args)
|
43 |
+
|
44 |
+
# Convert output types where applicable
|
45 |
+
if isinstance(result, tuple):
|
46 |
+
result = list(result)
|
47 |
+
for i, res in enumerate(result):
|
48 |
+
if type(res) == torch.Tensor:
|
49 |
+
if unsqueeze:
|
50 |
+
res = res.squeeze(0)
|
51 |
+
result[i] = res.numpy()
|
52 |
+
return tuple(result)
|
53 |
+
elif type(result) == torch.Tensor:
|
54 |
+
if unsqueeze:
|
55 |
+
result = result.squeeze(0)
|
56 |
+
return result.numpy()
|
57 |
+
else:
|
58 |
+
return result
|
59 |
+
|
60 |
+
|
61 |
+
def deterministic_random(min_value, max_value, data):
|
62 |
+
digest = hashlib.sha256(data.encode()).digest()
|
63 |
+
raw_value = int.from_bytes(digest[:4], byteorder='little', signed=False)
|
64 |
+
return int(raw_value / (2 ** 32 - 1) * (max_value - min_value)) + min_value
|
65 |
+
|
66 |
+
|
67 |
+
def alpha_map(prediction):
|
68 |
+
p_min, p_max = prediction.min(), prediction.max()
|
69 |
+
|
70 |
+
k = 1.6 / (p_max - p_min)
|
71 |
+
b = 0.8 - k * p_max
|
72 |
+
|
73 |
+
prediction = k * prediction + b
|
74 |
+
|
75 |
+
return prediction
|
76 |
+
|
77 |
+
|
78 |
+
def change_score(prediction, detectron_detection_path):
|
79 |
+
detectron_predictions = np.load(detectron_detection_path, allow_pickle=True)['positions_2d'].item()
|
80 |
+
pose = detectron_predictions['S1']['Directions 1']
|
81 |
+
prediction[..., 2] = pose[..., 2]
|
82 |
+
|
83 |
+
return prediction
|
84 |
+
|
85 |
+
|
86 |
+
class Timer:
|
87 |
+
def __init__(self, message, show=True):
|
88 |
+
self.message = message
|
89 |
+
self.elapsed = 0
|
90 |
+
self.show = show
|
91 |
+
|
92 |
+
def __enter__(self):
|
93 |
+
self.start = time.perf_counter()
|
94 |
+
|
95 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
96 |
+
if self.show:
|
97 |
+
print(f'{self.message} --- elapsed time: {time.perf_counter() - self.start} s')
|
98 |
+
|
99 |
+
|
100 |
+
def calculate_area(data):
|
101 |
+
"""
|
102 |
+
Get the rectangle area of keypoints.
|
103 |
+
:param data: AlphaPose json keypoint format([x, y, score, ... , x, y, score]) or AlphaPose result keypoint format([[x, y], ..., [x, y]])
|
104 |
+
:return: area
|
105 |
+
"""
|
106 |
+
data = np.array(data)
|
107 |
+
|
108 |
+
if len(data.shape) == 1:
|
109 |
+
data = np.reshape(data, (-1, 3))
|
110 |
+
|
111 |
+
width = min(data[:, 0]) - max(data[:, 0])
|
112 |
+
height = min(data[:, 1]) - max(data[:, 1])
|
113 |
+
|
114 |
+
return np.abs(width * height)
|
115 |
+
|
116 |
+
|
117 |
+
def read_video(filename, fps=None, skip=0, limit=-1):
|
118 |
+
stream = cv2.VideoCapture(filename)
|
119 |
+
|
120 |
+
i = 0
|
121 |
+
while True:
|
122 |
+
grabbed, frame = stream.read()
|
123 |
+
# if the `grabbed` boolean is `False`, then we have
|
124 |
+
# reached the end of the video file
|
125 |
+
if not grabbed:
|
126 |
+
print('===========================> This video get ' + str(i) + ' frames in total.')
|
127 |
+
sys.stdout.flush()
|
128 |
+
break
|
129 |
+
|
130 |
+
i += 1
|
131 |
+
if i > skip:
|
132 |
+
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
133 |
+
yield np.array(frame)
|
134 |
+
if i == limit:
|
135 |
+
break
|
136 |
+
|
137 |
+
|
138 |
+
def split_video(video_path):
|
139 |
+
stream = cv2.VideoCapture(video_path)
|
140 |
+
|
141 |
+
output_dir = os.path.dirname(video_path)
|
142 |
+
video_name = os.path.basename(video_path)
|
143 |
+
video_name = video_name[:video_name.rfind('.')]
|
144 |
+
|
145 |
+
save_folder = pathlib.Path(f'./{output_dir}/alpha_pose_{video_name}/split_image/')
|
146 |
+
shutil.rmtree(str(save_folder), ignore_errors=True)
|
147 |
+
save_folder.mkdir(parents=True, exist_ok=True)
|
148 |
+
|
149 |
+
total_frames = int(stream.get(cv2.CAP_PROP_FRAME_COUNT))
|
150 |
+
length = len(str(total_frames)) + 1
|
151 |
+
|
152 |
+
i = 1
|
153 |
+
while True:
|
154 |
+
grabbed, frame = stream.read()
|
155 |
+
|
156 |
+
if not grabbed:
|
157 |
+
print(f'Split totally {i + 1} images from video.')
|
158 |
+
break
|
159 |
+
|
160 |
+
save_path = f'{save_folder}/output{str(i).zfill(length)}.png'
|
161 |
+
cv2.imwrite(save_path, frame)
|
162 |
+
|
163 |
+
i += 1
|
164 |
+
|
165 |
+
saved_path = os.path.dirname(save_path)
|
166 |
+
print(f'Split images saved in {saved_path}')
|
167 |
+
|
168 |
+
return saved_path
|
169 |
+
|
170 |
+
|
171 |
+
def evaluate(test_generator, model_pos, action=None, return_predictions=False):
|
172 |
+
"""
|
173 |
+
Inference the 3d positions from 2d position.
|
174 |
+
:type test_generator: UnchunkedGenerator
|
175 |
+
:param test_generator:
|
176 |
+
:param model_pos: 3d pose model
|
177 |
+
:param return_predictions: return predictions if true
|
178 |
+
:return:
|
179 |
+
"""
|
180 |
+
joints_left, joints_right = list([4, 5, 6, 11, 12, 13]), list([1, 2, 3, 14, 15, 16])
|
181 |
+
with torch.no_grad():
|
182 |
+
model_pos.eval()
|
183 |
+
N = 0
|
184 |
+
for _, batch, batch_2d in test_generator.next_epoch():
|
185 |
+
inputs_2d = torch.from_numpy(batch_2d.astype('float32'))
|
186 |
+
if torch.cuda.is_available():
|
187 |
+
inputs_2d = inputs_2d.cuda()
|
188 |
+
# Positional model
|
189 |
+
predicted_3d_pos = model_pos(inputs_2d)
|
190 |
+
if test_generator.augment_enabled():
|
191 |
+
# Undo flipping and take average with non-flipped version
|
192 |
+
predicted_3d_pos[1, :, :, 0] *= -1
|
193 |
+
predicted_3d_pos[1, :, joints_left + joints_right] = predicted_3d_pos[1, :, joints_right + joints_left]
|
194 |
+
predicted_3d_pos = torch.mean(predicted_3d_pos, dim=0, keepdim=True)
|
195 |
+
if return_predictions:
|
196 |
+
return predicted_3d_pos.squeeze(0).cpu().numpy()
|
197 |
+
|
198 |
+
|
199 |
+
if __name__ == '__main__':
|
200 |
+
os.chdir('..')
|
201 |
+
|
202 |
+
split_video('outputs/kobe.mp4')
|
common/visualization.py
ADDED
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
|
8 |
+
import time
|
9 |
+
|
10 |
+
import cv2
|
11 |
+
import matplotlib.pyplot as plt
|
12 |
+
import numpy as np
|
13 |
+
from matplotlib.animation import FuncAnimation, writers
|
14 |
+
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
|
15 |
+
from mpl_toolkits.mplot3d import Axes3D
|
16 |
+
from tqdm import tqdm
|
17 |
+
|
18 |
+
from common.utils import read_video
|
19 |
+
|
20 |
+
|
21 |
+
def ckpt_time(ckpt=None, display=0, desc=''):
|
22 |
+
if not ckpt:
|
23 |
+
return time.time()
|
24 |
+
else:
|
25 |
+
if display:
|
26 |
+
print(desc + ' consume time {:0.4f}'.format(time.time() - float(ckpt)))
|
27 |
+
return time.time() - float(ckpt), time.time()
|
28 |
+
|
29 |
+
|
30 |
+
def set_equal_aspect(ax, data):
|
31 |
+
"""
|
32 |
+
Create white cubic bounding box to make sure that 3d axis is in equal aspect.
|
33 |
+
:param ax: 3D axis
|
34 |
+
:param data: shape of(frames, 3), generated from BVH using convert_bvh2dataset.py
|
35 |
+
"""
|
36 |
+
X, Y, Z = data[..., 0], data[..., 1], data[..., 2]
|
37 |
+
|
38 |
+
# Create cubic bounding box to simulate equal aspect ratio
|
39 |
+
max_range = np.array([X.max() - X.min(), Y.max() - Y.min(), Z.max() - Z.min()]).max()
|
40 |
+
Xb = 0.5 * max_range * np.mgrid[-1:2:2, -1:2:2, -1:2:2][0].flatten() + 0.5 * (X.max() + X.min())
|
41 |
+
Yb = 0.5 * max_range * np.mgrid[-1:2:2, -1:2:2, -1:2:2][1].flatten() + 0.5 * (Y.max() + Y.min())
|
42 |
+
Zb = 0.5 * max_range * np.mgrid[-1:2:2, -1:2:2, -1:2:2][2].flatten() + 0.5 * (Z.max() + Z.min())
|
43 |
+
|
44 |
+
for xb, yb, zb in zip(Xb, Yb, Zb):
|
45 |
+
ax.plot([xb], [yb], [zb], 'w')
|
46 |
+
|
47 |
+
|
48 |
+
def downsample_tensor(X, factor):
|
49 |
+
length = X.shape[0] // factor * factor
|
50 |
+
return np.mean(X[:length].reshape(-1, factor, *X.shape[1:]), axis=1)
|
51 |
+
|
52 |
+
|
53 |
+
def render_animation(keypoints, poses, skeleton, fps, bitrate, azim, output, viewport,
|
54 |
+
limit=-1, downsample=1, size=6, input_video_path=None, input_video_skip=0):
|
55 |
+
"""
|
56 |
+
TODO
|
57 |
+
Render an animation. The supported output modes are:
|
58 |
+
-- 'interactive': display an interactive figure
|
59 |
+
(also works on notebooks if associated with %matplotlib inline)
|
60 |
+
-- 'html': render the animation as HTML5 video. Can be displayed in a notebook using HTML(...).
|
61 |
+
-- 'filename.mp4': render and export the animation as an h264 video (requires ffmpeg).
|
62 |
+
-- 'filename.gif': render and export the animation a gif file (requires imagemagick).
|
63 |
+
"""
|
64 |
+
plt.ioff()
|
65 |
+
fig = plt.figure(figsize=(size * (1 + len(poses)), size))
|
66 |
+
ax_in = fig.add_subplot(1, 1 + len(poses), 1)
|
67 |
+
ax_in.get_xaxis().set_visible(False)
|
68 |
+
ax_in.get_yaxis().set_visible(False)
|
69 |
+
ax_in.set_axis_off()
|
70 |
+
ax_in.set_title('Input')
|
71 |
+
|
72 |
+
# prevent wired error
|
73 |
+
_ = Axes3D.__class__.__name__
|
74 |
+
|
75 |
+
ax_3d = []
|
76 |
+
lines_3d = []
|
77 |
+
trajectories = []
|
78 |
+
radius = 1.7
|
79 |
+
for index, (title, data) in enumerate(poses.items()):
|
80 |
+
ax = fig.add_subplot(1, 1 + len(poses), index + 2, projection='3d')
|
81 |
+
ax.view_init(elev=15., azim=azim)
|
82 |
+
ax.set_xlim3d([-radius / 2, radius / 2])
|
83 |
+
ax.set_zlim3d([0, radius])
|
84 |
+
ax.set_ylim3d([-radius / 2, radius / 2])
|
85 |
+
# ax.set_aspect('equal')
|
86 |
+
ax.set_xticklabels([])
|
87 |
+
ax.set_yticklabels([])
|
88 |
+
ax.set_zticklabels([])
|
89 |
+
ax.dist = 12.5
|
90 |
+
ax.set_title(title) # , pad=35
|
91 |
+
ax_3d.append(ax)
|
92 |
+
lines_3d.append([])
|
93 |
+
trajectories.append(data[:, 0, [0, 1]])
|
94 |
+
poses = list(poses.values())
|
95 |
+
|
96 |
+
# Decode video
|
97 |
+
if input_video_path is None:
|
98 |
+
# Black background
|
99 |
+
all_frames = np.zeros((keypoints.shape[0], viewport[1], viewport[0]), dtype='uint8')
|
100 |
+
else:
|
101 |
+
# Load video using ffmpeg
|
102 |
+
all_frames = []
|
103 |
+
for f in read_video(input_video_path, fps=None, skip=input_video_skip):
|
104 |
+
all_frames.append(f)
|
105 |
+
|
106 |
+
effective_length = min(keypoints.shape[0], len(all_frames))
|
107 |
+
all_frames = all_frames[:effective_length]
|
108 |
+
|
109 |
+
if downsample > 1:
|
110 |
+
keypoints = downsample_tensor(keypoints, downsample)
|
111 |
+
all_frames = downsample_tensor(np.array(all_frames), downsample).astype('uint8')
|
112 |
+
for idx in range(len(poses)):
|
113 |
+
poses[idx] = downsample_tensor(poses[idx], downsample)
|
114 |
+
trajectories[idx] = downsample_tensor(trajectories[idx], downsample)
|
115 |
+
fps /= downsample
|
116 |
+
|
117 |
+
initialized = False
|
118 |
+
image = None
|
119 |
+
lines = []
|
120 |
+
points = None
|
121 |
+
|
122 |
+
if limit < 1:
|
123 |
+
limit = len(all_frames)
|
124 |
+
else:
|
125 |
+
limit = min(limit, len(all_frames))
|
126 |
+
|
127 |
+
parents = skeleton.parents()
|
128 |
+
pbar = tqdm(total=limit)
|
129 |
+
|
130 |
+
def update_video(i):
|
131 |
+
nonlocal initialized, image, lines, points
|
132 |
+
|
133 |
+
for n, ax in enumerate(ax_3d):
|
134 |
+
ax.set_xlim3d([-radius / 2 + trajectories[n][i, 0], radius / 2 + trajectories[n][i, 0]])
|
135 |
+
ax.set_ylim3d([-radius / 2 + trajectories[n][i, 1], radius / 2 + trajectories[n][i, 1]])
|
136 |
+
|
137 |
+
# Update 2D poses
|
138 |
+
if not initialized:
|
139 |
+
image = ax_in.imshow(all_frames[i], aspect='equal')
|
140 |
+
|
141 |
+
for j, j_parent in enumerate(parents):
|
142 |
+
if j_parent == -1:
|
143 |
+
continue
|
144 |
+
|
145 |
+
# if len(parents) == keypoints.shape[1] and 1 == 2:
|
146 |
+
# # Draw skeleton only if keypoints match (otherwise we don't have the parents definition)
|
147 |
+
# lines.append(ax_in.plot([keypoints[i, j, 0], keypoints[i, j_parent, 0]],
|
148 |
+
# [keypoints[i, j, 1], keypoints[i, j_parent, 1]], color='pink'))
|
149 |
+
|
150 |
+
col = 'red' if j in skeleton.joints_right() else 'black'
|
151 |
+
for n, ax in enumerate(ax_3d):
|
152 |
+
pos = poses[n][i]
|
153 |
+
lines_3d[n].append(ax.plot([pos[j, 0], pos[j_parent, 0]],
|
154 |
+
[pos[j, 1], pos[j_parent, 1]],
|
155 |
+
[pos[j, 2], pos[j_parent, 2]], zdir='z', c=col))
|
156 |
+
|
157 |
+
points = ax_in.scatter(*keypoints[i].T, 5, color='red', edgecolors='white', zorder=10)
|
158 |
+
|
159 |
+
initialized = True
|
160 |
+
else:
|
161 |
+
image.set_data(all_frames[i])
|
162 |
+
|
163 |
+
for j, j_parent in enumerate(parents):
|
164 |
+
if j_parent == -1:
|
165 |
+
continue
|
166 |
+
|
167 |
+
# if len(parents) == keypoints.shape[1] and 1 == 2:
|
168 |
+
# lines[j - 1][0].set_data([keypoints[i, j, 0], keypoints[i, j_parent, 0]],
|
169 |
+
# [keypoints[i, j, 1], keypoints[i, j_parent, 1]])
|
170 |
+
|
171 |
+
for n, ax in enumerate(ax_3d):
|
172 |
+
pos = poses[n][i]
|
173 |
+
lines_3d[n][j - 1][0].set_xdata(np.array([pos[j, 0], pos[j_parent, 0]])) # Hotfix matplotlib's bug. https://github.com/matplotlib/matplotlib/pull/20555
|
174 |
+
lines_3d[n][j - 1][0].set_ydata([pos[j, 1], pos[j_parent, 1]])
|
175 |
+
lines_3d[n][j - 1][0].set_3d_properties([pos[j, 2], pos[j_parent, 2]], zdir='z')
|
176 |
+
|
177 |
+
points.set_offsets(keypoints[i])
|
178 |
+
|
179 |
+
pbar.update()
|
180 |
+
|
181 |
+
fig.tight_layout()
|
182 |
+
|
183 |
+
anim = FuncAnimation(fig, update_video, frames=limit, interval=1000.0 / fps, repeat=False)
|
184 |
+
if output.endswith('.mp4'):
|
185 |
+
Writer = writers['ffmpeg']
|
186 |
+
writer = Writer(fps=fps, metadata={}, bitrate=bitrate)
|
187 |
+
anim.save(output, writer=writer)
|
188 |
+
elif output.endswith('.gif'):
|
189 |
+
anim.save(output, dpi=60, writer='imagemagick')
|
190 |
+
else:
|
191 |
+
raise ValueError('Unsupported output format (only .mp4 and .gif are supported)')
|
192 |
+
pbar.close()
|
193 |
+
plt.close()
|
194 |
+
|
195 |
+
|
196 |
+
def render_animation_test(keypoints, poses, skeleton, fps, bitrate, azim, output, viewport, limit=-1, downsample=1, size=6, input_video_frame=None,
|
197 |
+
input_video_skip=0, num=None):
|
198 |
+
t0 = ckpt_time()
|
199 |
+
fig = plt.figure(figsize=(12, 6))
|
200 |
+
canvas = FigureCanvas(fig)
|
201 |
+
fig.add_subplot(121)
|
202 |
+
plt.imshow(input_video_frame)
|
203 |
+
# 3D
|
204 |
+
ax = fig.add_subplot(122, projection='3d')
|
205 |
+
ax.view_init(elev=15., azim=azim)
|
206 |
+
# set 长度范围
|
207 |
+
radius = 1.7
|
208 |
+
ax.set_xlim3d([-radius / 2, radius / 2])
|
209 |
+
ax.set_zlim3d([0, radius])
|
210 |
+
ax.set_ylim3d([-radius / 2, radius / 2])
|
211 |
+
ax.set_aspect('equal')
|
212 |
+
# 坐标轴刻度
|
213 |
+
ax.set_xticklabels([])
|
214 |
+
ax.set_yticklabels([])
|
215 |
+
ax.set_zticklabels([])
|
216 |
+
ax.dist = 7.5
|
217 |
+
|
218 |
+
# lxy add
|
219 |
+
ax.set_xlabel('X Label')
|
220 |
+
ax.set_ylabel('Y Label')
|
221 |
+
ax.set_zlabel('Z Label')
|
222 |
+
|
223 |
+
# array([-1, 0, 1, 2, 0, 4, 5, 0, 7, 8, 9, 8, 11, 12, 8, 14, 15])
|
224 |
+
parents = skeleton.parents()
|
225 |
+
|
226 |
+
pos = poses['Reconstruction'][-1]
|
227 |
+
_, t1 = ckpt_time(t0, desc='1 ')
|
228 |
+
for j, j_parent in enumerate(parents):
|
229 |
+
if j_parent == -1:
|
230 |
+
continue
|
231 |
+
|
232 |
+
if len(parents) == keypoints.shape[1]:
|
233 |
+
color_pink = 'pink'
|
234 |
+
if j == 1 or j == 2:
|
235 |
+
color_pink = 'black'
|
236 |
+
|
237 |
+
col = 'red' if j in skeleton.joints_right() else 'black'
|
238 |
+
# 画图3D
|
239 |
+
ax.plot([pos[j, 0], pos[j_parent, 0]],
|
240 |
+
[pos[j, 1], pos[j_parent, 1]],
|
241 |
+
[pos[j, 2], pos[j_parent, 2]], zdir='z', c=col)
|
242 |
+
|
243 |
+
# plt.savefig('test/3Dimage_{}.png'.format(1000+num))
|
244 |
+
width, height = fig.get_size_inches() * fig.get_dpi()
|
245 |
+
_, t2 = ckpt_time(t1, desc='2 ')
|
246 |
+
canvas.draw() # draw the canvas, cache the renderer
|
247 |
+
image = np.fromstring(canvas.tostring_rgb(), dtype='uint8').reshape(int(height), int(width), 3)
|
248 |
+
cv2.imshow('im', image)
|
249 |
+
cv2.waitKey(5)
|
250 |
+
_, t3 = ckpt_time(t2, desc='3 ')
|
251 |
+
return image
|
data/data_utils.py
ADDED
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
|
8 |
+
import h5py
|
9 |
+
import numpy as np
|
10 |
+
|
11 |
+
mpii_metadata = {
|
12 |
+
'layout_name': 'mpii',
|
13 |
+
'num_joints': 16,
|
14 |
+
'keypoints_symmetry': [
|
15 |
+
[3, 4, 5, 13, 14, 15],
|
16 |
+
[0, 1, 2, 10, 11, 12],
|
17 |
+
]
|
18 |
+
}
|
19 |
+
|
20 |
+
coco_metadata = {
|
21 |
+
'layout_name': 'coco',
|
22 |
+
'num_joints': 17,
|
23 |
+
'keypoints_symmetry': [
|
24 |
+
[1, 3, 5, 7, 9, 11, 13, 15],
|
25 |
+
[2, 4, 6, 8, 10, 12, 14, 16],
|
26 |
+
]
|
27 |
+
}
|
28 |
+
|
29 |
+
h36m_metadata = {
|
30 |
+
'layout_name': 'h36m',
|
31 |
+
'num_joints': 17,
|
32 |
+
'keypoints_symmetry': [
|
33 |
+
[4, 5, 6, 11, 12, 13],
|
34 |
+
[1, 2, 3, 14, 15, 16],
|
35 |
+
]
|
36 |
+
}
|
37 |
+
|
38 |
+
humaneva15_metadata = {
|
39 |
+
'layout_name': 'humaneva15',
|
40 |
+
'num_joints': 15,
|
41 |
+
'keypoints_symmetry': [
|
42 |
+
[2, 3, 4, 8, 9, 10],
|
43 |
+
[5, 6, 7, 11, 12, 13]
|
44 |
+
]
|
45 |
+
}
|
46 |
+
|
47 |
+
humaneva20_metadata = {
|
48 |
+
'layout_name': 'humaneva20',
|
49 |
+
'num_joints': 20,
|
50 |
+
'keypoints_symmetry': [
|
51 |
+
[3, 4, 5, 6, 11, 12, 13, 14],
|
52 |
+
[7, 8, 9, 10, 15, 16, 17, 18]
|
53 |
+
]
|
54 |
+
}
|
55 |
+
|
56 |
+
|
57 |
+
def suggest_metadata(name):
|
58 |
+
names = []
|
59 |
+
for metadata in [mpii_metadata, coco_metadata, h36m_metadata, humaneva15_metadata, humaneva20_metadata]:
|
60 |
+
if metadata['layout_name'] in name:
|
61 |
+
return metadata
|
62 |
+
names.append(metadata['layout_name'])
|
63 |
+
raise KeyError('Cannot infer keypoint layout from name "{}". Tried {}.'.format(name, names))
|
64 |
+
|
65 |
+
|
66 |
+
def import_detectron_poses(path):
|
67 |
+
# Latin1 encoding because Detectron runs on Python 2.7
|
68 |
+
data = np.load(path, encoding='latin1')
|
69 |
+
kp = data['keypoints']
|
70 |
+
bb = data['boxes']
|
71 |
+
results = []
|
72 |
+
for i in range(len(bb)):
|
73 |
+
if len(bb[i][1]) == 0:
|
74 |
+
assert i > 0
|
75 |
+
# Use last pose in case of detection failure
|
76 |
+
results.append(results[-1])
|
77 |
+
continue
|
78 |
+
best_match = np.argmax(bb[i][1][:, 4])
|
79 |
+
# import ipdb;ipdb.set_trace()
|
80 |
+
keypoints = kp[i][1][best_match].T.copy()
|
81 |
+
results.append(keypoints)
|
82 |
+
results = np.array(results)
|
83 |
+
# return results[:, :, 4:6] # Soft-argmax
|
84 |
+
return results[:, :, [0, 1, 3]] # Argmax + score
|
85 |
+
|
86 |
+
|
87 |
+
def my_pose(path):
|
88 |
+
data = np.load(path, encoding='latin1')
|
89 |
+
|
90 |
+
|
91 |
+
def import_cpn_poses(path):
|
92 |
+
data = np.load(path)
|
93 |
+
kp = data['keypoints']
|
94 |
+
return kp[:, :, :2]
|
95 |
+
|
96 |
+
|
97 |
+
def import_sh_poses(path):
|
98 |
+
with h5py.File(path) as hf:
|
99 |
+
positions = hf['poses'].value
|
100 |
+
return positions.astype('float32')
|
101 |
+
|
102 |
+
|
103 |
+
def suggest_pose_importer(name):
|
104 |
+
if 'detectron' in name:
|
105 |
+
return import_detectron_poses
|
106 |
+
if 'cpn' in name:
|
107 |
+
return import_cpn_poses
|
108 |
+
if 'sh' in name:
|
109 |
+
return import_sh_poses
|
110 |
+
raise KeyError('Cannot infer keypoint format from name "{}". Tried detectron, cpn, sh.'.format(name))
|
data/prepare_2d_kpt.py
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
import sys
|
4 |
+
|
5 |
+
import numpy as np
|
6 |
+
from data_utils import suggest_metadata, suggest_pose_importer
|
7 |
+
|
8 |
+
sys.path.append('../')
|
9 |
+
|
10 |
+
output_prefix_2d = 'data_2d_h36m_'
|
11 |
+
cam_map = {
|
12 |
+
'54138969': 0,
|
13 |
+
'55011271': 1,
|
14 |
+
'58860488': 2,
|
15 |
+
'60457274': 3,
|
16 |
+
}
|
17 |
+
|
18 |
+
if __name__ == '__main__':
|
19 |
+
if os.path.basename(os.getcwd()) != 'data':
|
20 |
+
print('This script must be launched from the "data" directory')
|
21 |
+
exit(0)
|
22 |
+
|
23 |
+
parser = argparse.ArgumentParser(description='Human3.6M dataset converter')
|
24 |
+
|
25 |
+
parser.add_argument('-i', '--input', default='', type=str, metavar='PATH', help='input path to 2D detections')
|
26 |
+
parser.add_argument('-o', '--output', default='detectron_pt_coco', type=str, metavar='PATH',
|
27 |
+
help='output suffix for 2D detections (e.g. detectron_pt_coco)')
|
28 |
+
|
29 |
+
args = parser.parse_args()
|
30 |
+
|
31 |
+
if not args.input:
|
32 |
+
print('Please specify the input directory')
|
33 |
+
exit(0)
|
34 |
+
|
35 |
+
# according to output name,generate some format. we use detectron
|
36 |
+
import_func = suggest_pose_importer('detectron_pt_coco')
|
37 |
+
metadata = suggest_metadata('detectron_pt_coco')
|
38 |
+
|
39 |
+
print('Parsing 2D detections from', args.input)
|
40 |
+
keypoints = import_func(args.input)
|
41 |
+
|
42 |
+
output = keypoints.astype(np.float32)
|
43 |
+
# 生成的数据用于后面的3D检测
|
44 |
+
np.savez_compressed(output_prefix_2d + 'test' + args.output, positions_2d=output, metadata=metadata)
|
45 |
+
print('npz name is ', output_prefix_2d + 'test' + args.output)
|
data/prepare_data_2d_h36m_generic.py
ADDED
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
|
8 |
+
import argparse
|
9 |
+
import os
|
10 |
+
import re
|
11 |
+
import sys
|
12 |
+
from glob import glob
|
13 |
+
|
14 |
+
import ipdb
|
15 |
+
import numpy as np
|
16 |
+
from data_utils import suggest_metadata, suggest_pose_importer
|
17 |
+
|
18 |
+
sys.path.append('../')
|
19 |
+
|
20 |
+
output_prefix_2d = 'data_2d_h36m_'
|
21 |
+
cam_map = {
|
22 |
+
'54138969': 0,
|
23 |
+
'55011271': 1,
|
24 |
+
'58860488': 2,
|
25 |
+
'60457274': 3,
|
26 |
+
}
|
27 |
+
|
28 |
+
if __name__ == '__main__':
|
29 |
+
if os.path.basename(os.getcwd()) != 'data':
|
30 |
+
print('This script must be launched from the "data" directory')
|
31 |
+
exit(0)
|
32 |
+
|
33 |
+
parser = argparse.ArgumentParser(description='Human3.6M dataset converter')
|
34 |
+
|
35 |
+
parser.add_argument('-i', '--input', default='', type=str, metavar='PATH', help='input path to 2D detections')
|
36 |
+
parser.add_argument('-o', '--output', default='', type=str, metavar='PATH', help='output suffix for 2D detections (e.g. detectron_pt_coco)')
|
37 |
+
|
38 |
+
args = parser.parse_args()
|
39 |
+
|
40 |
+
if not args.input:
|
41 |
+
print('Please specify the input directory')
|
42 |
+
exit(0)
|
43 |
+
|
44 |
+
if not args.output:
|
45 |
+
print('Please specify an output suffix (e.g. detectron_pt_coco)')
|
46 |
+
exit(0)
|
47 |
+
|
48 |
+
import_func = suggest_pose_importer(args.output)
|
49 |
+
metadata = suggest_metadata(args.output)
|
50 |
+
|
51 |
+
print('Parsing 2D detections from', args.input)
|
52 |
+
|
53 |
+
output = {}
|
54 |
+
|
55 |
+
# lxy add
|
56 |
+
keypoints = import_func(args.input)
|
57 |
+
output['S1'] = {}
|
58 |
+
output['S1']['Walking'] = [None, None, None, None]
|
59 |
+
output['S1']['Walking'][0] = keypoints.astype(np.float32)
|
60 |
+
np.savez_compressed(output_prefix_2d + '00' + args.output, positions_2d=output, metadata=metadata)
|
61 |
+
data = np.load('data_2d_h36m_detectron_pt_coco.npz')
|
62 |
+
data1 = np.load('data_2d_h36m_00detectron_pt_coco.npz')
|
63 |
+
actions = data['positions_2d'].item()
|
64 |
+
actions1 = data1['positions_2d'].item()
|
65 |
+
meta = data['metadata']
|
66 |
+
|
67 |
+
actions['S1']['Walking'][0] = actions1['S1']['Walking'][0][:, :, :]
|
68 |
+
np.savez_compressed('data_2d_h36m_lxy_cpn_ft_h36m_dbb.npz', positions_2d=actions, metadata=meta)
|
69 |
+
|
70 |
+
os.exit()
|
71 |
+
ipdb.set_trace()
|
72 |
+
|
73 |
+
# match all file with the format
|
74 |
+
file_list = glob(args.input + '/S*/*.mp4.npz')
|
75 |
+
for f in file_list:
|
76 |
+
path, fname = os.path.split(f)
|
77 |
+
subject = os.path.basename(path)
|
78 |
+
assert subject.startswith('S'), subject + ' does not look like a subject directory'
|
79 |
+
|
80 |
+
if '_ALL' in fname:
|
81 |
+
continue
|
82 |
+
|
83 |
+
m = re.search('(.*)\\.([0-9]+)\\.mp4\\.npz', fname)
|
84 |
+
# first parentheses
|
85 |
+
action = m.group(1)
|
86 |
+
# second parentheses
|
87 |
+
camera = m.group(2)
|
88 |
+
camera_idx = cam_map[camera]
|
89 |
+
|
90 |
+
if subject == 'S11' and action == 'Directions':
|
91 |
+
continue # Discard corrupted video
|
92 |
+
|
93 |
+
# Use consistent naming convention
|
94 |
+
canonical_name = action.replace('TakingPhoto', 'Photo') \
|
95 |
+
.replace('WalkingDog', 'WalkDog')
|
96 |
+
|
97 |
+
keypoints = import_func(f)
|
98 |
+
assert keypoints.shape[1] == metadata['num_joints']
|
99 |
+
|
100 |
+
if subject not in output:
|
101 |
+
output[subject] = {}
|
102 |
+
if canonical_name not in output[subject]:
|
103 |
+
output[subject][canonical_name] = [None, None, None, None]
|
104 |
+
output[subject][canonical_name][camera_idx] = keypoints.astype('float32')
|
105 |
+
|
106 |
+
print('Saving...')
|
107 |
+
np.savez_compressed(output_prefix_2d + args.output, positions_2d=output, metadata=metadata)
|
108 |
+
print('Done.')
|
data/prepare_data_2d_h36m_sh.py
ADDED
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
|
8 |
+
import argparse
|
9 |
+
import os
|
10 |
+
import sys
|
11 |
+
import tarfile
|
12 |
+
import zipfile
|
13 |
+
from glob import glob
|
14 |
+
from shutil import rmtree
|
15 |
+
|
16 |
+
import h5py
|
17 |
+
import numpy as np
|
18 |
+
|
19 |
+
sys.path.append('../')
|
20 |
+
|
21 |
+
output_filename_pt = 'data_2d_h36m_sh_pt_mpii'
|
22 |
+
output_filename_ft = 'data_2d_h36m_sh_ft_h36m'
|
23 |
+
subjects = ['S1', 'S5', 'S6', 'S7', 'S8', 'S9', 'S11']
|
24 |
+
cam_map = {
|
25 |
+
'54138969': 0,
|
26 |
+
'55011271': 1,
|
27 |
+
'58860488': 2,
|
28 |
+
'60457274': 3,
|
29 |
+
}
|
30 |
+
|
31 |
+
metadata = {
|
32 |
+
'num_joints': 16,
|
33 |
+
'keypoints_symmetry': [
|
34 |
+
[3, 4, 5, 13, 14, 15],
|
35 |
+
[0, 1, 2, 10, 11, 12],
|
36 |
+
]
|
37 |
+
}
|
38 |
+
|
39 |
+
|
40 |
+
def process_subject(subject, file_list, output):
|
41 |
+
if subject == 'S11':
|
42 |
+
assert len(file_list) == 119, "Expected 119 files for subject " + subject + ", got " + str(len(file_list))
|
43 |
+
else:
|
44 |
+
assert len(file_list) == 120, "Expected 120 files for subject " + subject + ", got " + str(len(file_list))
|
45 |
+
|
46 |
+
for f in file_list:
|
47 |
+
action, cam = os.path.splitext(os.path.basename(f))[0].replace('_', ' ').split('.')
|
48 |
+
|
49 |
+
if subject == 'S11' and action == 'Directions':
|
50 |
+
continue # Discard corrupted video
|
51 |
+
|
52 |
+
if action not in output[subject]:
|
53 |
+
output[subject][action] = [None, None, None, None]
|
54 |
+
|
55 |
+
with h5py.File(f) as hf:
|
56 |
+
positions = hf['poses'].value
|
57 |
+
output[subject][action][cam_map[cam]] = positions.astype('float32')
|
58 |
+
|
59 |
+
|
60 |
+
if __name__ == '__main__':
|
61 |
+
if os.path.basename(os.getcwd()) != 'data':
|
62 |
+
print('This script must be launched from the "data" directory')
|
63 |
+
exit(0)
|
64 |
+
|
65 |
+
parser = argparse.ArgumentParser(description='Human3.6M dataset downloader/converter')
|
66 |
+
|
67 |
+
parser.add_argument('-pt', '--pretrained', default='', type=str, metavar='PATH', help='convert pretrained dataset')
|
68 |
+
parser.add_argument('-ft', '--fine-tuned', default='', type=str, metavar='PATH', help='convert fine-tuned dataset')
|
69 |
+
|
70 |
+
args = parser.parse_args()
|
71 |
+
|
72 |
+
if args.pretrained:
|
73 |
+
print('Converting pretrained dataset from', args.pretrained)
|
74 |
+
print('Extracting...')
|
75 |
+
with zipfile.ZipFile(args.pretrained, 'r') as archive:
|
76 |
+
archive.extractall('sh_pt')
|
77 |
+
|
78 |
+
print('Converting...')
|
79 |
+
output = {}
|
80 |
+
for subject in subjects:
|
81 |
+
output[subject] = {}
|
82 |
+
file_list = glob('sh_pt/h36m/' + subject + '/StackedHourglass/*.h5')
|
83 |
+
process_subject(subject, file_list, output)
|
84 |
+
|
85 |
+
print('Saving...')
|
86 |
+
np.savez_compressed(output_filename_pt, positions_2d=output, metadata=metadata)
|
87 |
+
|
88 |
+
print('Cleaning up...')
|
89 |
+
rmtree('sh_pt')
|
90 |
+
|
91 |
+
print('Done.')
|
92 |
+
|
93 |
+
if args.fine_tuned:
|
94 |
+
print('Converting fine-tuned dataset from', args.fine_tuned)
|
95 |
+
print('Extracting...')
|
96 |
+
with tarfile.open(args.fine_tuned, 'r:gz') as archive:
|
97 |
+
archive.extractall('sh_ft')
|
98 |
+
|
99 |
+
print('Converting...')
|
100 |
+
output = {}
|
101 |
+
for subject in subjects:
|
102 |
+
output[subject] = {}
|
103 |
+
file_list = glob('sh_ft/' + subject + '/StackedHourglassFineTuned240/*.h5')
|
104 |
+
process_subject(subject, file_list, output)
|
105 |
+
|
106 |
+
print('Saving...')
|
107 |
+
np.savez_compressed(output_filename_ft, positions_2d=output, metadata=metadata)
|
108 |
+
|
109 |
+
print('Cleaning up...')
|
110 |
+
rmtree('sh_ft')
|
111 |
+
|
112 |
+
print('Done.')
|
data/prepare_data_h36m.py
ADDED
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
|
8 |
+
import argparse
|
9 |
+
import os
|
10 |
+
import sys
|
11 |
+
import zipfile
|
12 |
+
from glob import glob
|
13 |
+
from shutil import rmtree
|
14 |
+
|
15 |
+
import h5py
|
16 |
+
import numpy as np
|
17 |
+
|
18 |
+
sys.path.append('../')
|
19 |
+
from common.h36m_dataset import Human36mDataset
|
20 |
+
from common.camera import world_to_camera, project_to_2d, image_coordinates
|
21 |
+
from common.utils import wrap
|
22 |
+
|
23 |
+
output_filename = 'data_3d_h36m'
|
24 |
+
output_filename_2d = 'data_2d_h36m_gt'
|
25 |
+
subjects = ['S1', 'S5', 'S6', 'S7', 'S8', 'S9', 'S11']
|
26 |
+
|
27 |
+
if __name__ == '__main__':
|
28 |
+
if os.path.basename(os.getcwd()) != 'data':
|
29 |
+
print('This script must be launched from the "data" directory')
|
30 |
+
exit(0)
|
31 |
+
|
32 |
+
parser = argparse.ArgumentParser(description='Human3.6M dataset downloader/converter')
|
33 |
+
|
34 |
+
# Default: convert dataset preprocessed by Martinez et al. in https://github.com/una-dinosauria/3d-pose-baseline
|
35 |
+
parser.add_argument('--from-archive', default='', type=str, metavar='PATH', help='convert preprocessed dataset')
|
36 |
+
|
37 |
+
# Alternatively, convert dataset from original source (the Human3.6M dataset path must be specified manually)
|
38 |
+
parser.add_argument('--from-source', default='', type=str, metavar='PATH', help='convert original dataset')
|
39 |
+
|
40 |
+
args = parser.parse_args()
|
41 |
+
|
42 |
+
if args.from_archive and args.from_source:
|
43 |
+
print('Please specify only one argument')
|
44 |
+
exit(0)
|
45 |
+
|
46 |
+
if os.path.exists(output_filename + '.npz'):
|
47 |
+
print('The dataset already exists at', output_filename + '.npz')
|
48 |
+
exit(0)
|
49 |
+
|
50 |
+
if args.from_archive:
|
51 |
+
print('Extracting Human3.6M dataset from', args.from_archive)
|
52 |
+
with zipfile.ZipFile(args.from_archive, 'r') as archive:
|
53 |
+
archive.extractall()
|
54 |
+
|
55 |
+
print('Converting...')
|
56 |
+
output = {}
|
57 |
+
for subject in subjects:
|
58 |
+
output[subject] = {}
|
59 |
+
file_list = glob('h36m/' + subject + '/MyPoses/3D_positions/*.h5')
|
60 |
+
assert len(file_list) == 30, "Expected 30 files for subject " + subject + ", got " + str(len(file_list))
|
61 |
+
for f in file_list:
|
62 |
+
action = os.path.splitext(os.path.basename(f))[0]
|
63 |
+
|
64 |
+
if subject == 'S11' and action == 'Directions':
|
65 |
+
continue # Discard corrupted video
|
66 |
+
|
67 |
+
with h5py.File(f) as hf:
|
68 |
+
positions = hf['3D_positions'].value.reshape(32, 3, -1).transpose(2, 0, 1)
|
69 |
+
positions /= 1000 # Meters instead of millimeters
|
70 |
+
output[subject][action] = positions.astype('float32')
|
71 |
+
|
72 |
+
print('Saving...')
|
73 |
+
np.savez_compressed(output_filename, positions_3d=output)
|
74 |
+
|
75 |
+
print('Cleaning up...')
|
76 |
+
rmtree('h36m')
|
77 |
+
|
78 |
+
print('Done.')
|
79 |
+
|
80 |
+
elif args.from_source:
|
81 |
+
print('Converting original Human3.6M dataset from', args.from_source)
|
82 |
+
output = {}
|
83 |
+
|
84 |
+
from scipy.io import loadmat
|
85 |
+
|
86 |
+
import ipdb;
|
87 |
+
|
88 |
+
ipdb.set_trace()
|
89 |
+
for subject in subjects:
|
90 |
+
output[subject] = {}
|
91 |
+
file_list = glob(args.from_source + '/' + subject + '/MyPoseFeatures/D3_Positions/*.cdf.mat')
|
92 |
+
assert len(file_list) == 30, "Expected 30 files for subject " + subject + ", got " + str(len(file_list))
|
93 |
+
for f in file_list:
|
94 |
+
action = os.path.splitext(os.path.splitext(os.path.basename(f))[0])[0]
|
95 |
+
|
96 |
+
if subject == 'S11' and action == 'Directions':
|
97 |
+
continue # Discard corrupted video
|
98 |
+
|
99 |
+
# Use consistent naming convention
|
100 |
+
canonical_name = action.replace('TakingPhoto', 'Photo') \
|
101 |
+
.replace('WalkingDog', 'WalkDog')
|
102 |
+
|
103 |
+
hf = loadmat(f)
|
104 |
+
positions = hf['data'][0, 0].reshape(-1, 32, 3)
|
105 |
+
positions /= 1000 # Meters instead of millimeters
|
106 |
+
output[subject][canonical_name] = positions.astype('float32')
|
107 |
+
|
108 |
+
print('Saving...')
|
109 |
+
np.savez_compressed(output_filename, positions_3d=output)
|
110 |
+
|
111 |
+
print('Done.')
|
112 |
+
|
113 |
+
else:
|
114 |
+
print('Please specify the dataset source')
|
115 |
+
exit(0)
|
116 |
+
|
117 |
+
# Create 2D pose file
|
118 |
+
print('')
|
119 |
+
print('Computing ground-truth 2D poses...')
|
120 |
+
dataset = Human36mDataset(output_filename + '.npz')
|
121 |
+
output_2d_poses = {}
|
122 |
+
for subject in dataset.subjects():
|
123 |
+
output_2d_poses[subject] = {}
|
124 |
+
for action in dataset[subject].keys():
|
125 |
+
anim = dataset[subject][action]
|
126 |
+
|
127 |
+
positions_2d = []
|
128 |
+
for cam in anim['cameras']:
|
129 |
+
pos_3d = world_to_camera(anim['positions'], R=cam['orientation'], t=cam['translation'])
|
130 |
+
pos_2d = wrap(project_to_2d, pos_3d, cam['intrinsic'], unsqueeze=True)
|
131 |
+
pos_2d_pixel_space = image_coordinates(pos_2d, w=cam['res_w'], h=cam['res_h'])
|
132 |
+
positions_2d.append(pos_2d_pixel_space.astype('float32'))
|
133 |
+
output_2d_poses[subject][action] = positions_2d
|
134 |
+
|
135 |
+
print('Saving...')
|
136 |
+
metadata = {
|
137 |
+
'num_joints': dataset.skeleton().num_joints(),
|
138 |
+
'keypoints_symmetry': [dataset.skeleton().joints_left(), dataset.skeleton().joints_right()]
|
139 |
+
}
|
140 |
+
np.savez_compressed(output_filename_2d, positions_2d=output_2d_poses, metadata=metadata)
|
141 |
+
|
142 |
+
print('Done.')
|
data/prepare_data_humaneva.py
ADDED
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2018-present, Facebook, Inc.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
#
|
7 |
+
|
8 |
+
import argparse
|
9 |
+
import os
|
10 |
+
import re
|
11 |
+
import sys
|
12 |
+
from glob import glob
|
13 |
+
|
14 |
+
import numpy as np
|
15 |
+
from data_utils import suggest_metadata, suggest_pose_importer
|
16 |
+
|
17 |
+
sys.path.append('../')
|
18 |
+
from itertools import groupby
|
19 |
+
|
20 |
+
subjects = ['Train/S1', 'Train/S2', 'Train/S3', 'Validate/S1', 'Validate/S2', 'Validate/S3']
|
21 |
+
|
22 |
+
cam_map = {
|
23 |
+
'C1': 0,
|
24 |
+
'C2': 1,
|
25 |
+
'C3': 2,
|
26 |
+
}
|
27 |
+
|
28 |
+
# Frame numbers for train/test split
|
29 |
+
# format: [start_frame, end_frame[ (inclusive, exclusive)
|
30 |
+
index = {
|
31 |
+
'Train/S1': {
|
32 |
+
'Walking 1': (590, 1203),
|
33 |
+
'Jog 1': (367, 740),
|
34 |
+
'ThrowCatch 1': (473, 945),
|
35 |
+
'Gestures 1': (395, 801),
|
36 |
+
'Box 1': (385, 789),
|
37 |
+
},
|
38 |
+
'Train/S2': {
|
39 |
+
'Walking 1': (438, 876),
|
40 |
+
'Jog 1': (398, 795),
|
41 |
+
'ThrowCatch 1': (550, 1128),
|
42 |
+
'Gestures 1': (500, 901),
|
43 |
+
'Box 1': (382, 734),
|
44 |
+
},
|
45 |
+
'Train/S3': {
|
46 |
+
'Walking 1': (448, 939),
|
47 |
+
'Jog 1': (401, 842),
|
48 |
+
'ThrowCatch 1': (493, 1027),
|
49 |
+
'Gestures 1': (533, 1102),
|
50 |
+
'Box 1': (512, 1021),
|
51 |
+
},
|
52 |
+
'Validate/S1': {
|
53 |
+
'Walking 1': (5, 590),
|
54 |
+
'Jog 1': (5, 367),
|
55 |
+
'ThrowCatch 1': (5, 473),
|
56 |
+
'Gestures 1': (5, 395),
|
57 |
+
'Box 1': (5, 385),
|
58 |
+
},
|
59 |
+
'Validate/S2': {
|
60 |
+
'Walking 1': (5, 438),
|
61 |
+
'Jog 1': (5, 398),
|
62 |
+
'ThrowCatch 1': (5, 550),
|
63 |
+
'Gestures 1': (5, 500),
|
64 |
+
'Box 1': (5, 382),
|
65 |
+
},
|
66 |
+
'Validate/S3': {
|
67 |
+
'Walking 1': (5, 448),
|
68 |
+
'Jog 1': (5, 401),
|
69 |
+
'ThrowCatch 1': (5, 493),
|
70 |
+
'Gestures 1': (5, 533),
|
71 |
+
'Box 1': (5, 512),
|
72 |
+
},
|
73 |
+
}
|
74 |
+
|
75 |
+
# Frames to skip for each video (synchronization)
|
76 |
+
sync_data = {
|
77 |
+
'S1': {
|
78 |
+
'Walking 1': (82, 81, 82),
|
79 |
+
'Jog 1': (51, 51, 50),
|
80 |
+
'ThrowCatch 1': (61, 61, 60),
|
81 |
+
'Gestures 1': (45, 45, 44),
|
82 |
+
'Box 1': (57, 57, 56),
|
83 |
+
},
|
84 |
+
'S2': {
|
85 |
+
'Walking 1': (115, 115, 114),
|
86 |
+
'Jog 1': (100, 100, 99),
|
87 |
+
'ThrowCatch 1': (127, 127, 127),
|
88 |
+
'Gestures 1': (122, 122, 121),
|
89 |
+
'Box 1': (119, 119, 117),
|
90 |
+
},
|
91 |
+
'S3': {
|
92 |
+
'Walking 1': (80, 80, 80),
|
93 |
+
'Jog 1': (65, 65, 65),
|
94 |
+
'ThrowCatch 1': (79, 79, 79),
|
95 |
+
'Gestures 1': (83, 83, 82),
|
96 |
+
'Box 1': (1, 1, 1),
|
97 |
+
},
|
98 |
+
'S4': {}
|
99 |
+
}
|
100 |
+
|
101 |
+
if __name__ == '__main__':
|
102 |
+
if os.path.basename(os.getcwd()) != 'data':
|
103 |
+
print('This script must be launched from the "data" directory')
|
104 |
+
exit(0)
|
105 |
+
|
106 |
+
parser = argparse.ArgumentParser(description='HumanEva dataset converter')
|
107 |
+
|
108 |
+
parser.add_argument('-p', '--path', default='', type=str, metavar='PATH', help='path to the processed HumanEva dataset')
|
109 |
+
parser.add_argument('--convert-3d', action='store_true', help='convert 3D mocap data')
|
110 |
+
parser.add_argument('--convert-2d', default='', type=str, metavar='PATH', help='convert user-supplied 2D detections')
|
111 |
+
parser.add_argument('-o', '--output', default='', type=str, metavar='PATH', help='output suffix for 2D detections (e.g. detectron_pt_coco)')
|
112 |
+
|
113 |
+
args = parser.parse_args()
|
114 |
+
|
115 |
+
if not args.convert_2d and not args.convert_3d:
|
116 |
+
print('Please specify one conversion mode')
|
117 |
+
exit(0)
|
118 |
+
|
119 |
+
if args.path:
|
120 |
+
print('Parsing HumanEva dataset from', args.path)
|
121 |
+
output = {}
|
122 |
+
output_2d = {}
|
123 |
+
frame_mapping = {}
|
124 |
+
|
125 |
+
from scipy.io import loadmat
|
126 |
+
|
127 |
+
num_joints = None
|
128 |
+
|
129 |
+
for subject in subjects:
|
130 |
+
output[subject] = {}
|
131 |
+
output_2d[subject] = {}
|
132 |
+
split, subject_name = subject.split('/')
|
133 |
+
if subject_name not in frame_mapping:
|
134 |
+
frame_mapping[subject_name] = {}
|
135 |
+
|
136 |
+
file_list = glob(args.path + '/' + subject + '/*.mat')
|
137 |
+
for f in file_list:
|
138 |
+
action = os.path.splitext(os.path.basename(f))[0]
|
139 |
+
|
140 |
+
# Use consistent naming convention
|
141 |
+
canonical_name = action.replace('_', ' ')
|
142 |
+
|
143 |
+
hf = loadmat(f)
|
144 |
+
positions = hf['poses_3d']
|
145 |
+
positions_2d = hf['poses_2d'].transpose(1, 0, 2, 3) # Ground-truth 2D poses
|
146 |
+
assert positions.shape[0] == positions_2d.shape[0] and positions.shape[1] == positions_2d.shape[2]
|
147 |
+
assert num_joints is None or num_joints == positions.shape[1], "Joint number inconsistency among files"
|
148 |
+
num_joints = positions.shape[1]
|
149 |
+
|
150 |
+
# Sanity check for the sequence length
|
151 |
+
assert positions.shape[0] == index[subject][canonical_name][1] - index[subject][canonical_name][0]
|
152 |
+
|
153 |
+
# Split corrupted motion capture streams into contiguous chunks
|
154 |
+
# e.g. 012XX567X9 is split into "012", "567", and "9".
|
155 |
+
all_chunks = [list(v) for k, v in groupby(positions, lambda x: np.isfinite(x).all())]
|
156 |
+
all_chunks_2d = [list(v) for k, v in groupby(positions_2d, lambda x: np.isfinite(x).all())]
|
157 |
+
assert len(all_chunks) == len(all_chunks_2d)
|
158 |
+
current_index = index[subject][canonical_name][0]
|
159 |
+
chunk_indices = []
|
160 |
+
for i, chunk in enumerate(all_chunks):
|
161 |
+
next_index = current_index + len(chunk)
|
162 |
+
name = canonical_name + ' chunk' + str(i)
|
163 |
+
if np.isfinite(chunk).all():
|
164 |
+
output[subject][name] = np.array(chunk, dtype='float32') / 1000
|
165 |
+
output_2d[subject][name] = list(np.array(all_chunks_2d[i], dtype='float32').transpose(1, 0, 2, 3))
|
166 |
+
chunk_indices.append((current_index, next_index, np.isfinite(chunk).all(), split, name))
|
167 |
+
current_index = next_index
|
168 |
+
assert current_index == index[subject][canonical_name][1]
|
169 |
+
if canonical_name not in frame_mapping[subject_name]:
|
170 |
+
frame_mapping[subject_name][canonical_name] = []
|
171 |
+
frame_mapping[subject_name][canonical_name] += chunk_indices
|
172 |
+
|
173 |
+
metadata = suggest_metadata('humaneva' + str(num_joints))
|
174 |
+
output_filename = 'data_3d_' + metadata['layout_name']
|
175 |
+
output_prefix_2d = 'data_2d_' + metadata['layout_name'] + '_'
|
176 |
+
|
177 |
+
if args.convert_3d:
|
178 |
+
print('Saving...')
|
179 |
+
np.savez_compressed(output_filename, positions_3d=output)
|
180 |
+
np.savez_compressed(output_prefix_2d + 'gt', positions_2d=output_2d, metadata=metadata)
|
181 |
+
print('Done.')
|
182 |
+
|
183 |
+
else:
|
184 |
+
print('Please specify the dataset source')
|
185 |
+
exit(0)
|
186 |
+
|
187 |
+
if args.convert_2d:
|
188 |
+
if not args.output:
|
189 |
+
print('Please specify an output suffix (e.g. detectron_pt_coco)')
|
190 |
+
exit(0)
|
191 |
+
|
192 |
+
import_func = suggest_pose_importer(args.output)
|
193 |
+
metadata = suggest_metadata(args.output)
|
194 |
+
|
195 |
+
print('Parsing 2D detections from', args.convert_2d)
|
196 |
+
|
197 |
+
output = {}
|
198 |
+
file_list = glob(args.convert_2d + '/S*/*.avi.npz')
|
199 |
+
for f in file_list:
|
200 |
+
path, fname = os.path.split(f)
|
201 |
+
subject = os.path.basename(path)
|
202 |
+
assert subject.startswith('S'), subject + ' does not look like a subject directory'
|
203 |
+
|
204 |
+
m = re.search('(.*) \\((.*)\\)', fname.replace('_', ' '))
|
205 |
+
action = m.group(1)
|
206 |
+
camera = m.group(2)
|
207 |
+
camera_idx = cam_map[camera]
|
208 |
+
|
209 |
+
keypoints = import_func(f)
|
210 |
+
assert keypoints.shape[1] == metadata['num_joints']
|
211 |
+
|
212 |
+
if action in sync_data[subject]:
|
213 |
+
sync_offset = sync_data[subject][action][camera_idx] - 1
|
214 |
+
else:
|
215 |
+
sync_offset = 0
|
216 |
+
|
217 |
+
if subject in frame_mapping and action in frame_mapping[subject]:
|
218 |
+
chunks = frame_mapping[subject][action]
|
219 |
+
for (start_idx, end_idx, labeled, split, name) in chunks:
|
220 |
+
canonical_subject = split + '/' + subject
|
221 |
+
if not labeled:
|
222 |
+
canonical_subject = 'Unlabeled/' + canonical_subject
|
223 |
+
if canonical_subject not in output:
|
224 |
+
output[canonical_subject] = {}
|
225 |
+
kps = keypoints[start_idx + sync_offset:end_idx + sync_offset]
|
226 |
+
assert len(kps) == end_idx - start_idx, "Got len {}, expected {}".format(len(kps), end_idx - start_idx)
|
227 |
+
|
228 |
+
if name not in output[canonical_subject]:
|
229 |
+
output[canonical_subject][name] = [None, None, None]
|
230 |
+
|
231 |
+
output[canonical_subject][name][camera_idx] = kps.astype('float32')
|
232 |
+
else:
|
233 |
+
canonical_subject = 'Unlabeled/' + subject
|
234 |
+
if canonical_subject not in output:
|
235 |
+
output[canonical_subject] = {}
|
236 |
+
if action not in output[canonical_subject]:
|
237 |
+
output[canonical_subject][action] = [None, None, None]
|
238 |
+
output[canonical_subject][action][camera_idx] = keypoints.astype('float32')
|
239 |
+
|
240 |
+
print('Saving...')
|
241 |
+
np.savez_compressed(output_prefix_2d + args.output, positions_2d=output, metadata=metadata)
|
242 |
+
print('Done.')
|
joints_detectors/Alphapose/.gitignore
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
human_detection/output
|
2 |
+
examples/results
|
3 |
+
examples/res
|
4 |
+
PoseFlow/__pycache__
|
5 |
+
PoseFlow/*.npy
|
6 |
+
PoseFlow/alpha-pose-results-test.json
|
7 |
+
PoseFlow/alpha-pose-results-val.json
|
8 |
+
PoseFlow/test-predict
|
9 |
+
PoseFlow/val-predict
|
10 |
+
train_sppe/coco-minival500_images.txt
|
11 |
+
train_sppe/person_keypoints_val2014.json
|
12 |
+
|
13 |
+
ssd/examples
|
14 |
+
images
|
15 |
+
|
16 |
+
*.npy
|
17 |
+
*.so
|
18 |
+
*.pyc
|
19 |
+
.ipynb_checkpoints
|
20 |
+
*/.ipynb_checkpoints/
|
21 |
+
*/.tensorboard/*
|
22 |
+
*/exp
|
23 |
+
|
24 |
+
*.pth
|
25 |
+
*.h5
|
26 |
+
*.zip
|
27 |
+
*.weights
|
28 |
+
|
29 |
+
coco-minival/
|
joints_detectors/Alphapose/LICENSE
ADDED
@@ -0,0 +1,515 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
ALPHAPOSE: MULTIPERSON KEYPOINT DETECTION
|
2 |
+
SOFTWARE LICENSE AGREEMENT
|
3 |
+
ACADEMIC OR NON-PROFIT ORGANIZATION NONCOMMERCIAL RESEARCH USE ONLY
|
4 |
+
|
5 |
+
BY USING OR DOWNLOADING THE SOFTWARE, YOU ARE AGREEING TO THE TERMS OF THIS LICENSE AGREEMENT. IF YOU DO NOT AGREE WITH THESE TERMS, YOU MAY NOT USE OR DOWNLOAD THE SOFTWARE.
|
6 |
+
|
7 |
+
This is a license agreement ("Agreement") between your academic institution or non-profit organization or self (called "Licensee" or "You" in this Agreement) and Shanghai Jiao Tong University (called "Licensor" in this Agreement). All rights not specifically granted to you in this Agreement are reserved for Licensor.
|
8 |
+
|
9 |
+
RESERVATION OF OWNERSHIP AND GRANT OF LICENSE:
|
10 |
+
Licensor retains exclusive ownership of any copy of the Software (as defined below) licensed under this Agreement and hereby grants to Licensee a personal, non-exclusive,
|
11 |
+
non-transferable license to use the Software for noncommercial research purposes, without the right to sublicense, pursuant to the terms and conditions of this Agreement. As used in this Agreement, the term "Software" means (i) the actual copy of all or any portion of code for program routines made accessible to Licensee by Licensor pursuant to this Agreement, inclusive of backups, updates, and/or merged copies permitted hereunder or subsequently supplied by Licensor, including all or any file structures, programming instructions, user interfaces and screen formats and sequences as well as any and all documentation and instructions related to it, and (ii) all or any derivatives and/or modifications created or made by You to any of the items specified in (i).
|
12 |
+
|
13 |
+
CONFIDENTIALITY: Licensee acknowledges that the Software is proprietary to Licensor, and as such, Licensee agrees to receive all such materials in confidence and use the Software only in accordance with the terms of this Agreement. Licensee agrees to use reasonable effort to protect the Software from unauthorized use, reproduction, distribution, or publication.
|
14 |
+
|
15 |
+
PERMITTED USES: The Software may be used for your own noncommercial internal research purposes. You understand and agree that Licensor is not obligated to implement any suggestions and/or feedback you might provide regarding the Software, but to the extent Licensor does so, you are not entitled to any compensation related thereto.
|
16 |
+
|
17 |
+
DERIVATIVES: You may create derivatives of or make modifications to the Software, however, You agree that all and any such derivatives and modifications will be owned by Licensor and become a part of the Software licensed to You under this Agreement. You may only use such derivatives and modifications for your own noncommercial internal research purposes, and you may not otherwise use, distribute or copy such derivatives and modifications in violation of this Agreement.
|
18 |
+
|
19 |
+
BACKUPS: If Licensee is an organization, it may make that number of copies of the Software necessary for internal noncommercial use at a single site within its organization provided that all information appearing in or on the original labels, including the copyright and trademark notices are copied onto the labels of the copies.
|
20 |
+
|
21 |
+
USES NOT PERMITTED: You may not distribute, copy or use the Software except as explicitly permitted herein. Licensee has not been granted any trademark license as part of this Agreement and may not use the name or mark “AlphaPose", "Shanghai Jiao Tong" or any renditions thereof without the prior written permission of Licensor.
|
22 |
+
|
23 |
+
You may not sell, rent, lease, sublicense, lend, time-share or transfer, in whole or in part, or provide third parties access to prior or present versions (or any parts thereof) of the Software.
|
24 |
+
|
25 |
+
ASSIGNMENT: You may not assign this Agreement or your rights hereunder without the prior written consent of Licensor. Any attempted assignment without such consent shall be null and void.
|
26 |
+
|
27 |
+
TERM: The term of the license granted by this Agreement is from Licensee's acceptance of this Agreement by downloading the Software or by using the Software until terminated as provided below.
|
28 |
+
|
29 |
+
The Agreement automatically terminates without notice if you fail to comply with any provision of this Agreement. Licensee may terminate this Agreement by ceasing using the Software. Upon any termination of this Agreement, Licensee will delete any and all copies of the Software. You agree that all provisions which operate to protect the proprietary rights of Licensor shall remain in force should breach occur and that the obligation of confidentiality described in this Agreement is binding in perpetuity and, as such, survives the term of the Agreement.
|
30 |
+
|
31 |
+
FEE: Provided Licensee abides completely by the terms and conditions of this Agreement, there is no fee due to Licensor for Licensee's use of the Software in accordance with this Agreement.
|
32 |
+
|
33 |
+
DISCLAIMER OF WARRANTIES: THE SOFTWARE IS PROVIDED "AS-IS" WITHOUT WARRANTY OF ANY KIND INCLUDING ANY WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE OR PURPOSE OR OF NON-INFRINGEMENT. LICENSEE BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE SOFTWARE AND RELATED MATERIALS.
|
34 |
+
|
35 |
+
SUPPORT AND MAINTENANCE: No Software support or training by the Licensor is provided as part of this Agreement.
|
36 |
+
|
37 |
+
EXCLUSIVE REMEDY AND LIMITATION OF LIABILITY: To the maximum extent permitted under applicable law, Licensor shall not be liable for direct, indirect, special, incidental, or consequential damages or lost profits related to Licensee's use of and/or inability to use the Software, even if Licensor is advised of the possibility of such damage.
|
38 |
+
|
39 |
+
EXPORT REGULATION: Licensee agrees to comply with any and all applicable
|
40 |
+
U.S. export control laws, regulations, and/or other laws related to embargoes and sanction programs administered by the Office of Foreign Assets Control.
|
41 |
+
|
42 |
+
SEVERABILITY: If any provision(s) of this Agreement shall be held to be invalid, illegal, or unenforceable by a court or other tribunal of competent jurisdiction, the validity, legality and enforceability of the remaining provisions shall not in any way be affected or impaired thereby.
|
43 |
+
|
44 |
+
NO IMPLIED WAIVERS: No failure or delay by Licensor in enforcing any right or remedy under this Agreement shall be construed as a waiver of any future or other exercise of such right or remedy by Licensor.
|
45 |
+
|
46 |
+
ENTIRE AGREEMENT AND AMENDMENTS: This Agreement constitutes the sole and entire agreement between Licensee and Licensor as to the matter set forth herein and supersedes any previous agreements, understandings, and arrangements between the parties relating hereto.
|
47 |
+
|
48 |
+
|
49 |
+
|
50 |
+
************************************************************************
|
51 |
+
|
52 |
+
THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
|
53 |
+
|
54 |
+
This project incorporates material from the project(s) listed below (collectively, "Third Party Code"). This Third Party Code is licensed to you under their original license terms set forth below. We reserves all other rights not expressly granted, whether by implication, estoppel or otherwise.
|
55 |
+
|
56 |
+
1. Torch, (https://github.com/torch/distro)
|
57 |
+
|
58 |
+
Copyright (c) 2016, Soumith Chintala, Ronan Collobert, Koray Kavukcuoglu, Clement Farabet All rights reserved.
|
59 |
+
|
60 |
+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
61 |
+
|
62 |
+
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
63 |
+
|
64 |
+
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
65 |
+
|
66 |
+
Neither the name of distro nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
67 |
+
|
68 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
69 |
+
|
70 |
+
2. TensorFlow (https://github.com/tensorflow/tensorflow)
|
71 |
+
Copyright 2018 The TensorFlow Authors. All rights reserved.
|
72 |
+
|
73 |
+
Apache License
|
74 |
+
Version 2.0, January 2004
|
75 |
+
http://www.apache.org/licenses/
|
76 |
+
|
77 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
78 |
+
|
79 |
+
1. Definitions.
|
80 |
+
|
81 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
82 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
83 |
+
|
84 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
85 |
+
the copyright owner that is granting the License.
|
86 |
+
|
87 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
88 |
+
other entities that control, are controlled by, or are under common
|
89 |
+
control with that entity. For the purposes of this definition,
|
90 |
+
"control" means (i) the power, direct or indirect, to cause the
|
91 |
+
direction or management of such entity, whether by contract or
|
92 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
93 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
94 |
+
|
95 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
96 |
+
exercising permissions granted by this License.
|
97 |
+
|
98 |
+
"Source" form shall mean the preferred form for making modifications,
|
99 |
+
including but not limited to software source code, documentation
|
100 |
+
source, and configuration files.
|
101 |
+
|
102 |
+
"Object" form shall mean any form resulting from mechanical
|
103 |
+
transformation or translation of a Source form, including but
|
104 |
+
not limited to compiled object code, generated documentation,
|
105 |
+
and conversions to other media types.
|
106 |
+
|
107 |
+
"Work" shall mean the work of authorship, whether in Source or
|
108 |
+
Object form, made available under the License, as indicated by a
|
109 |
+
copyright notice that is included in or attached to the work
|
110 |
+
(an example is provided in the Appendix below).
|
111 |
+
|
112 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
113 |
+
form, that is based on (or derived from) the Work and for which the
|
114 |
+
editorial revisions, annotations, elaborations, or other modifications
|
115 |
+
represent, as a whole, an original work of authorship. For the purposes
|
116 |
+
of this License, Derivative Works shall not include works that remain
|
117 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
118 |
+
the Work and Derivative Works thereof.
|
119 |
+
|
120 |
+
"Contribution" shall mean any work of authorship, including
|
121 |
+
the original version of the Work and any modifications or additions
|
122 |
+
to that Work or Derivative Works thereof, that is intentionally
|
123 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
124 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
125 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
126 |
+
means any form of electronic, verbal, or written communication sent
|
127 |
+
to the Licensor or its representatives, including but not limited to
|
128 |
+
communication on electronic mailing lists, source code control systems,
|
129 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
130 |
+
Licensor for the purpose of discussing and improving the Work, but
|
131 |
+
excluding communication that is conspicuously marked or otherwise
|
132 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
133 |
+
|
134 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
135 |
+
on behalf of whom a Contribution has been received by Licensor and
|
136 |
+
subsequently incorporated within the Work.
|
137 |
+
|
138 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
139 |
+
this License, each Contributor hereby grants to You a perpetual,
|
140 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
141 |
+
copyright license to reproduce, prepare Derivative Works of,
|
142 |
+
publicly display, publicly perform, sublicense, and distribute the
|
143 |
+
Work and such Derivative Works in Source or Object form.
|
144 |
+
|
145 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
146 |
+
this License, each Contributor hereby grants to You a perpetual,
|
147 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
148 |
+
(except as stated in this section) patent license to make, have made,
|
149 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
150 |
+
where such license applies only to those patent claims licensable
|
151 |
+
by such Contributor that are necessarily infringed by their
|
152 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
153 |
+
with the Work to which such Contribution(s) was submitted. If You
|
154 |
+
institute patent litigation against any entity (including a
|
155 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
156 |
+
or a Contribution incorporated within the Work constitutes direct
|
157 |
+
or contributory patent infringement, then any patent licenses
|
158 |
+
granted to You under this License for that Work shall terminate
|
159 |
+
as of the date such litigation is filed.
|
160 |
+
|
161 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
162 |
+
Work or Derivative Works thereof in any medium, with or without
|
163 |
+
modifications, and in Source or Object form, provided that You
|
164 |
+
meet the following conditions:
|
165 |
+
|
166 |
+
(a) You must give any other recipients of the Work or
|
167 |
+
Derivative Works a copy of this License; and
|
168 |
+
|
169 |
+
(b) You must cause any modified files to carry prominent notices
|
170 |
+
stating that You changed the files; and
|
171 |
+
|
172 |
+
(c) You must retain, in the Source form of any Derivative Works
|
173 |
+
that You distribute, all copyright, patent, trademark, and
|
174 |
+
attribution notices from the Source form of the Work,
|
175 |
+
excluding those notices that do not pertain to any part of
|
176 |
+
the Derivative Works; and
|
177 |
+
|
178 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
179 |
+
distribution, then any Derivative Works that You distribute must
|
180 |
+
include a readable copy of the attribution notices contained
|
181 |
+
within such NOTICE file, excluding those notices that do not
|
182 |
+
pertain to any part of the Derivative Works, in at least one
|
183 |
+
of the following places: within a NOTICE text file distributed
|
184 |
+
as part of the Derivative Works; within the Source form or
|
185 |
+
documentation, if provided along with the Derivative Works; or,
|
186 |
+
within a display generated by the Derivative Works, if and
|
187 |
+
wherever such third-party notices normally appear. The contents
|
188 |
+
of the NOTICE file are for informational purposes only and
|
189 |
+
do not modify the License. You may add Your own attribution
|
190 |
+
notices within Derivative Works that You distribute, alongside
|
191 |
+
or as an addendum to the NOTICE text from the Work, provided
|
192 |
+
that such additional attribution notices cannot be construed
|
193 |
+
as modifying the License.
|
194 |
+
|
195 |
+
You may add Your own copyright statement to Your modifications and
|
196 |
+
may provide additional or different license terms and conditions
|
197 |
+
for use, reproduction, or distribution of Your modifications, or
|
198 |
+
for any such Derivative Works as a whole, provided Your use,
|
199 |
+
reproduction, and distribution of the Work otherwise complies with
|
200 |
+
the conditions stated in this License.
|
201 |
+
|
202 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
203 |
+
any Contribution intentionally submitted for inclusion in the Work
|
204 |
+
by You to the Licensor shall be under the terms and conditions of
|
205 |
+
this License, without any additional terms or conditions.
|
206 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
207 |
+
the terms of any separate license agreement you may have executed
|
208 |
+
with Licensor regarding such Contributions.
|
209 |
+
|
210 |
+
6. Trademarks. This License does not grant permission to use the trade
|
211 |
+
names, trademarks, service marks, or product names of the Licensor,
|
212 |
+
except as required for reasonable and customary use in describing the
|
213 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
214 |
+
|
215 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
216 |
+
agreed to in writing, Licensor provides the Work (and each
|
217 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
218 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
219 |
+
implied, including, without limitation, any warranties or conditions
|
220 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
221 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
222 |
+
appropriateness of using or redistributing the Work and assume any
|
223 |
+
risks associated with Your exercise of permissions under this License.
|
224 |
+
|
225 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
226 |
+
whether in tort (including negligence), contract, or otherwise,
|
227 |
+
unless required by applicable law (such as deliberate and grossly
|
228 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
229 |
+
liable to You for damages, including any direct, indirect, special,
|
230 |
+
incidental, or consequential damages of any character arising as a
|
231 |
+
result of this License or out of the use or inability to use the
|
232 |
+
Work (including but not limited to damages for loss of goodwill,
|
233 |
+
work stoppage, computer failure or malfunction, or any and all
|
234 |
+
other commercial damages or losses), even if such Contributor
|
235 |
+
has been advised of the possibility of such damages.
|
236 |
+
|
237 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
238 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
239 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
240 |
+
or other liability obligations and/or rights consistent with this
|
241 |
+
License. However, in accepting such obligations, You may act only
|
242 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
243 |
+
of any other Contributor, and only if You agree to indemnify,
|
244 |
+
defend, and hold each Contributor harmless for any liability
|
245 |
+
incurred by, or claims asserted against, such Contributor by reason
|
246 |
+
of your accepting any such warranty or additional liability.
|
247 |
+
|
248 |
+
END OF TERMS AND CONDITIONS
|
249 |
+
|
250 |
+
APPENDIX: How to apply the Apache License to your work.
|
251 |
+
|
252 |
+
To apply the Apache License to your work, attach the following
|
253 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
254 |
+
replaced with your own identifying information. (Don't include
|
255 |
+
the brackets!) The text should be enclosed in the appropriate
|
256 |
+
comment syntax for the file format. We also recommend that a
|
257 |
+
file or class name and description of purpose be included on the
|
258 |
+
same "printed page" as the copyright notice for easier
|
259 |
+
identification within third-party archives.
|
260 |
+
|
261 |
+
Copyright 2017, The TensorFlow Authors.
|
262 |
+
|
263 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
264 |
+
you may not use this file except in compliance with the License.
|
265 |
+
You may obtain a copy of the License at
|
266 |
+
|
267 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
268 |
+
|
269 |
+
Unless required by applicable law or agreed to in writing, software
|
270 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
271 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
272 |
+
See the License for the specific language governing permissions and
|
273 |
+
limitations under the License.
|
274 |
+
|
275 |
+
3. tf-faster-rcnn (https://github.com/endernewton/tf-faster-rcnn)
|
276 |
+
MIT License
|
277 |
+
|
278 |
+
Copyright (c) 2017 Xinlei Chen
|
279 |
+
|
280 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
281 |
+
of this software and associated documentation files (the "Software"), to deal
|
282 |
+
in the Software without restriction, including without limitation the rights
|
283 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
284 |
+
copies of the Software, and to permit persons to whom the Software is
|
285 |
+
furnished to do so, subject to the following conditions:
|
286 |
+
|
287 |
+
The above copyright notice and this permission notice shall be included in all
|
288 |
+
copies or substantial portions of the Software.
|
289 |
+
|
290 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
291 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
292 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
293 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
294 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
295 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
296 |
+
SOFTWARE.
|
297 |
+
|
298 |
+
4.PyraNet (https://github.com/bearpaw/PyraNet)
|
299 |
+
Apache License
|
300 |
+
Version 2.0, January 2004
|
301 |
+
http://www.apache.org/licenses/
|
302 |
+
|
303 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
304 |
+
|
305 |
+
1. Definitions.
|
306 |
+
|
307 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
308 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
309 |
+
|
310 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
311 |
+
the copyright owner that is granting the License.
|
312 |
+
|
313 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
314 |
+
other entities that control, are controlled by, or are under common
|
315 |
+
control with that entity. For the purposes of this definition,
|
316 |
+
"control" means (i) the power, direct or indirect, to cause the
|
317 |
+
direction or management of such entity, whether by contract or
|
318 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
319 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
320 |
+
|
321 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
322 |
+
exercising permissions granted by this License.
|
323 |
+
|
324 |
+
"Source" form shall mean the preferred form for making modifications,
|
325 |
+
including but not limited to software source code, documentation
|
326 |
+
source, and configuration files.
|
327 |
+
|
328 |
+
"Object" form shall mean any form resulting from mechanical
|
329 |
+
transformation or translation of a Source form, including but
|
330 |
+
not limited to compiled object code, generated documentation,
|
331 |
+
and conversions to other media types.
|
332 |
+
|
333 |
+
"Work" shall mean the work of authorship, whether in Source or
|
334 |
+
Object form, made available under the License, as indicated by a
|
335 |
+
copyright notice that is included in or attached to the work
|
336 |
+
(an example is provided in the Appendix below).
|
337 |
+
|
338 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
339 |
+
form, that is based on (or derived from) the Work and for which the
|
340 |
+
editorial revisions, annotations, elaborations, or other modifications
|
341 |
+
represent, as a whole, an original work of authorship. For the purposes
|
342 |
+
of this License, Derivative Works shall not include works that remain
|
343 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
344 |
+
the Work and Derivative Works thereof.
|
345 |
+
|
346 |
+
"Contribution" shall mean any work of authorship, including
|
347 |
+
the original version of the Work and any modifications or additions
|
348 |
+
to that Work or Derivative Works thereof, that is intentionally
|
349 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
350 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
351 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
352 |
+
means any form of electronic, verbal, or written communication sent
|
353 |
+
to the Licensor or its representatives, including but not limited to
|
354 |
+
communication on electronic mailing lists, source code control systems,
|
355 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
356 |
+
Licensor for the purpose of discussing and improving the Work, but
|
357 |
+
excluding communication that is conspicuously marked or otherwise
|
358 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
359 |
+
|
360 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
361 |
+
on behalf of whom a Contribution has been received by Licensor and
|
362 |
+
subsequently incorporated within the Work.
|
363 |
+
|
364 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
365 |
+
this License, each Contributor hereby grants to You a perpetual,
|
366 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
367 |
+
copyright license to reproduce, prepare Derivative Works of,
|
368 |
+
publicly display, publicly perform, sublicense, and distribute the
|
369 |
+
Work and such Derivative Works in Source or Object form.
|
370 |
+
|
371 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
372 |
+
this License, each Contributor hereby grants to You a perpetual,
|
373 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
374 |
+
(except as stated in this section) patent license to make, have made,
|
375 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
376 |
+
where such license applies only to those patent claims licensable
|
377 |
+
by such Contributor that are necessarily infringed by their
|
378 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
379 |
+
with the Work to which such Contribution(s) was submitted. If You
|
380 |
+
institute patent litigation against any entity (including a
|
381 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
382 |
+
or a Contribution incorporated within the Work constitutes direct
|
383 |
+
or contributory patent infringement, then any patent licenses
|
384 |
+
granted to You under this License for that Work shall terminate
|
385 |
+
as of the date such litigation is filed.
|
386 |
+
|
387 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
388 |
+
Work or Derivative Works thereof in any medium, with or without
|
389 |
+
modifications, and in Source or Object form, provided that You
|
390 |
+
meet the following conditions:
|
391 |
+
|
392 |
+
(a) You must give any other recipients of the Work or
|
393 |
+
Derivative Works a copy of this License; and
|
394 |
+
|
395 |
+
(b) You must cause any modified files to carry prominent notices
|
396 |
+
stating that You changed the files; and
|
397 |
+
|
398 |
+
(c) You must retain, in the Source form of any Derivative Works
|
399 |
+
that You distribute, all copyright, patent, trademark, and
|
400 |
+
attribution notices from the Source form of the Work,
|
401 |
+
excluding those notices that do not pertain to any part of
|
402 |
+
the Derivative Works; and
|
403 |
+
|
404 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
405 |
+
distribution, then any Derivative Works that You distribute must
|
406 |
+
include a readable copy of the attribution notices contained
|
407 |
+
within such NOTICE file, excluding those notices that do not
|
408 |
+
pertain to any part of the Derivative Works, in at least one
|
409 |
+
of the following places: within a NOTICE text file distributed
|
410 |
+
as part of the Derivative Works; within the Source form or
|
411 |
+
documentation, if provided along with the Derivative Works; or,
|
412 |
+
within a display generated by the Derivative Works, if and
|
413 |
+
wherever such third-party notices normally appear. The contents
|
414 |
+
of the NOTICE file are for informational purposes only and
|
415 |
+
do not modify the License. You may add Your own attribution
|
416 |
+
notices within Derivative Works that You distribute, alongside
|
417 |
+
or as an addendum to the NOTICE text from the Work, provided
|
418 |
+
that such additional attribution notices cannot be construed
|
419 |
+
as modifying the License.
|
420 |
+
|
421 |
+
You may add Your own copyright statement to Your modifications and
|
422 |
+
may provide additional or different license terms and conditions
|
423 |
+
for use, reproduction, or distribution of Your modifications, or
|
424 |
+
for any such Derivative Works as a whole, provided Your use,
|
425 |
+
reproduction, and distribution of the Work otherwise complies with
|
426 |
+
the conditions stated in this License.
|
427 |
+
|
428 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
429 |
+
any Contribution intentionally submitted for inclusion in the Work
|
430 |
+
by You to the Licensor shall be under the terms and conditions of
|
431 |
+
this License, without any additional terms or conditions.
|
432 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
433 |
+
the terms of any separate license agreement you may have executed
|
434 |
+
with Licensor regarding such Contributions.
|
435 |
+
|
436 |
+
6. Trademarks. This License does not grant permission to use the trade
|
437 |
+
names, trademarks, service marks, or product names of the Licensor,
|
438 |
+
except as required for reasonable and customary use in describing the
|
439 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
440 |
+
|
441 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
442 |
+
agreed to in writing, Licensor provides the Work (and each
|
443 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
444 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
445 |
+
implied, including, without limitation, any warranties or conditions
|
446 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
447 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
448 |
+
appropriateness of using or redistributing the Work and assume any
|
449 |
+
risks associated with Your exercise of permissions under this License.
|
450 |
+
|
451 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
452 |
+
whether in tort (including negligence), contract, or otherwise,
|
453 |
+
unless required by applicable law (such as deliberate and grossly
|
454 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
455 |
+
liable to You for damages, including any direct, indirect, special,
|
456 |
+
incidental, or consequential damages of any character arising as a
|
457 |
+
result of this License or out of the use or inability to use the
|
458 |
+
Work (including but not limited to damages for loss of goodwill,
|
459 |
+
work stoppage, computer failure or malfunction, or any and all
|
460 |
+
other commercial damages or losses), even if such Contributor
|
461 |
+
has been advised of the possibility of such damages.
|
462 |
+
|
463 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
464 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
465 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
466 |
+
or other liability obligations and/or rights consistent with this
|
467 |
+
License. However, in accepting such obligations, You may act only
|
468 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
469 |
+
of any other Contributor, and only if You agree to indemnify,
|
470 |
+
defend, and hold each Contributor harmless for any liability
|
471 |
+
incurred by, or claims asserted against, such Contributor by reason
|
472 |
+
of your accepting any such warranty or additional liability.
|
473 |
+
|
474 |
+
END OF TERMS AND CONDITIONS
|
475 |
+
|
476 |
+
APPENDIX: How to apply the Apache License to your work.
|
477 |
+
|
478 |
+
To apply the Apache License to your work, attach the following
|
479 |
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
480 |
+
replaced with your own identifying information. (Don't include
|
481 |
+
the brackets!) The text should be enclosed in the appropriate
|
482 |
+
comment syntax for the file format. We also recommend that a
|
483 |
+
file or class name and description of purpose be included on the
|
484 |
+
same "printed page" as the copyright notice for easier
|
485 |
+
identification within third-party archives.
|
486 |
+
|
487 |
+
Copyright {yyyy} {name of copyright owner}
|
488 |
+
|
489 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
490 |
+
you may not use this file except in compliance with the License.
|
491 |
+
You may obtain a copy of the License at
|
492 |
+
|
493 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
494 |
+
|
495 |
+
Unless required by applicable law or agreed to in writing, software
|
496 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
497 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
498 |
+
See the License for the specific language governing permissions and
|
499 |
+
limitations under the License.
|
500 |
+
|
501 |
+
5. pose-hg-demo (https://github.com/umich-vl/pose-hg-demo)
|
502 |
+
Copyright (c) 2016, University of Michigan
|
503 |
+
All rights reserved.
|
504 |
+
|
505 |
+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
506 |
+
|
507 |
+
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
508 |
+
|
509 |
+
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
510 |
+
|
511 |
+
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
512 |
+
|
513 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
514 |
+
|
515 |
+
************END OF THIRD-PARTY SOFTWARE NOTICES AND INFORMATION**********
|
joints_detectors/Alphapose/README.md
ADDED
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
<div align="center">
|
3 |
+
<img src="doc/logo.jpg", width="400">
|
4 |
+
</div>
|
5 |
+
|
6 |
+
|
7 |
+
## News!
|
8 |
+
- Apr 2019: [**MXNet** version](https://github.com/MVIG-SJTU/AlphaPose/tree/mxnet) of AlphaPose is released! It runs at **23 fps** on COCO validation set.
|
9 |
+
- Feb 2019: [CrowdPose](https://github.com/MVIG-SJTU/AlphaPose/blob/pytorch/doc/CrowdPose.md) is integrated into AlphaPose Now!
|
10 |
+
- Dec 2018: [General version](https://github.com/MVIG-SJTU/AlphaPose/tree/pytorch/PoseFlow) of PoseFlow is released! 3X Faster and support pose tracking results visualization!
|
11 |
+
- Sep 2018: [**PyTorch** version](https://github.com/MVIG-SJTU/AlphaPose/tree/pytorch) of AlphaPose is released! It runs at **20 fps** on COCO validation set (4.6 people per image on average) and achieves 71 mAP!
|
12 |
+
|
13 |
+
## AlphaPose
|
14 |
+
[Alpha Pose](http://www.mvig.org/research/alphapose.html) is an accurate multi-person pose estimator, which is the **first open-source system that achieves 70+ mAP (72.3 mAP) on COCO dataset and 80+ mAP (82.1 mAP) on MPII dataset.**
|
15 |
+
To match poses that correspond to the same person across frames, we also provide an efficient online pose tracker called Pose Flow. It is the **first open-source online pose tracker that achieves both 60+ mAP (66.5 mAP) and 50+ MOTA (58.3 MOTA) on PoseTrack Challenge dataset.**
|
16 |
+
|
17 |
+
AlphaPose supports both Linux and **Windows!**
|
18 |
+
|
19 |
+
<div align="center">
|
20 |
+
<img src="doc/alphapose.gif", width="400">
|
21 |
+
</div>
|
22 |
+
|
23 |
+
|
24 |
+
## Installation
|
25 |
+
**Windows Version** please check out [doc/win_install.md](doc/win_install.md)
|
26 |
+
|
27 |
+
1. Get the code.
|
28 |
+
```Shell
|
29 |
+
git clone -b pytorch https://github.com/MVIG-SJTU/AlphaPose.git
|
30 |
+
```
|
31 |
+
|
32 |
+
2. Install [pytorch 0.4.0](https://github.com/pytorch/pytorch) and other dependencies.
|
33 |
+
```Shell
|
34 |
+
pip install -r requirements.txt
|
35 |
+
```
|
36 |
+
|
37 |
+
3. Download the models manually: **duc_se.pth** (2018/08/30) ([Google Drive]( https://drive.google.com/open?id=1OPORTWB2cwd5YTVBX-NE8fsauZJWsrtW) | [Baidu pan](https://pan.baidu.com/s/15jbRNKuslzm5wRSgUVytrA)), **yolov3-spp.weights**([Google Drive](https://drive.google.com/open?id=1D47msNOOiJKvPOXlnpyzdKA3k6E97NTC) | [Baidu pan](https://pan.baidu.com/s/1Zb2REEIk8tcahDa8KacPNA)). Place them into `./models/sppe` and `./models/yolo` respectively.
|
38 |
+
|
39 |
+
|
40 |
+
## Quick Start
|
41 |
+
- **Input dir**: Run AlphaPose for all images in a folder with:
|
42 |
+
```
|
43 |
+
python3 demo.py --indir ${img_directory} --outdir examples/res
|
44 |
+
```
|
45 |
+
- **Video**: Run AlphaPose for a video and save the rendered video with:
|
46 |
+
```
|
47 |
+
python3 video_demo.py --video ${path to video} --outdir examples/res --save_video
|
48 |
+
```
|
49 |
+
- **Webcam**: Run AlphaPose using webcam and visualize the results with:
|
50 |
+
```
|
51 |
+
python3 webcam_demo.py --webcam 0 --outdir examples/res --vis
|
52 |
+
```
|
53 |
+
- **Input list**: Run AlphaPose for images in a list and save the rendered images with:
|
54 |
+
```
|
55 |
+
python3 demo.py --list examples/list-coco-demo.txt --indir ${img_directory} --outdir examples/res --save_img
|
56 |
+
```
|
57 |
+
- **Note**: If you meet OOM(out of memory) problem, decreasing the pose estimation batch until the program can run on your computer:
|
58 |
+
```
|
59 |
+
python3 demo.py --indir ${img_directory} --outdir examples/res --posebatch 30
|
60 |
+
```
|
61 |
+
- **Getting more accurate**: You can enable flip testing to get more accurate results by disable fast_inference, e.g.:
|
62 |
+
```
|
63 |
+
python3 demo.py --indir ${img_directory} --outdir examples/res --fast_inference False
|
64 |
+
```
|
65 |
+
- **Speeding up**: Checkout the [speed_up.md](doc/speed_up.md) for more details.
|
66 |
+
- **Output format**: Checkout the [output.md](doc/output.md) for more details.
|
67 |
+
- **For more**: Checkout the [run.md](doc/run.md) for more options
|
68 |
+
|
69 |
+
## Pose Tracking
|
70 |
+
|
71 |
+
<p align='center'>
|
72 |
+
<img src="doc/posetrack.gif", width="360">
|
73 |
+
<img src="doc/posetrack2.gif", width="344">
|
74 |
+
</p>
|
75 |
+
|
76 |
+
Please read [PoseFlow/README.md](PoseFlow/) for details.
|
77 |
+
|
78 |
+
### CrowdPose
|
79 |
+
<p align='center'>
|
80 |
+
<img src="doc/crowdpose.gif", width="360">
|
81 |
+
</p>
|
82 |
+
|
83 |
+
Please read [doc/CrowdPose.md](doc/CrowdPose.md) for details.
|
84 |
+
|
85 |
+
|
86 |
+
## FAQ
|
87 |
+
Check out [faq.md](doc/faq.md) for faq.
|
88 |
+
|
89 |
+
## Contributors
|
90 |
+
Pytorch version of AlphaPose is developed and maintained by [Jiefeng Li](http://jeff-leaf.site/), [Hao-Shu Fang](https://fang-haoshu.github.io/), [Yuliang Xiu](http://xiuyuliang.cn) and [Cewu Lu](http://www.mvig.org/).
|
91 |
+
|
92 |
+
## Citation
|
93 |
+
Please cite these papers in your publications if it helps your research:
|
94 |
+
|
95 |
+
@inproceedings{fang2017rmpe,
|
96 |
+
title={{RMPE}: Regional Multi-person Pose Estimation},
|
97 |
+
author={Fang, Hao-Shu and Xie, Shuqin and Tai, Yu-Wing and Lu, Cewu},
|
98 |
+
booktitle={ICCV},
|
99 |
+
year={2017}
|
100 |
+
}
|
101 |
+
|
102 |
+
@inproceedings{xiu2018poseflow,
|
103 |
+
author = {Xiu, Yuliang and Li, Jiefeng and Wang, Haoyu and Fang, Yinghong and Lu, Cewu},
|
104 |
+
title = {{Pose Flow}: Efficient Online Pose Tracking},
|
105 |
+
booktitle={BMVC},
|
106 |
+
year = {2018}
|
107 |
+
}
|
108 |
+
|
109 |
+
|
110 |
+
|
111 |
+
## License
|
112 |
+
AlphaPose is freely available for free non-commercial use, and may be redistributed under these conditions. For commercial queries, please drop an e-mail at mvig.alphapose[at]gmail[dot]com and cc lucewu[[at]sjtu[dot]edu[dot]cn. We will send the detail agreement to you.
|
joints_detectors/Alphapose/SPPE/.gitattributes
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
# Auto detect text files and perform LF normalization
|
2 |
+
* text=auto
|
joints_detectors/Alphapose/SPPE/.gitignore
ADDED
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Byte-compiled / optimized / DLL files
|
2 |
+
__pycache__/
|
3 |
+
*.py[cod]
|
4 |
+
*$py.class
|
5 |
+
|
6 |
+
# C extensions
|
7 |
+
*.so
|
8 |
+
|
9 |
+
# Distribution / packaging
|
10 |
+
.Python
|
11 |
+
build/
|
12 |
+
develop-eggs/
|
13 |
+
dist/
|
14 |
+
downloads/
|
15 |
+
eggs/
|
16 |
+
.eggs/
|
17 |
+
lib/
|
18 |
+
lib64/
|
19 |
+
parts/
|
20 |
+
sdist/
|
21 |
+
var/
|
22 |
+
wheels/
|
23 |
+
*.egg-info/
|
24 |
+
.installed.cfg
|
25 |
+
*.egg
|
26 |
+
|
27 |
+
# PyInstaller
|
28 |
+
# Usually these files are written by a python script from a template
|
29 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
30 |
+
*.manifest
|
31 |
+
*.spec
|
32 |
+
|
33 |
+
# Installer logs
|
34 |
+
pip-log.txt
|
35 |
+
pip-delete-this-directory.txt
|
36 |
+
|
37 |
+
# Unit test / coverage reports
|
38 |
+
htmlcov/
|
39 |
+
.tox/
|
40 |
+
.coverage
|
41 |
+
.coverage.*
|
42 |
+
.cache
|
43 |
+
nosetests.xml
|
44 |
+
coverage.xml
|
45 |
+
*.cover
|
46 |
+
.hypothesis/
|
47 |
+
|
48 |
+
# Translations
|
49 |
+
*.mo
|
50 |
+
*.pot
|
51 |
+
|
52 |
+
# Django stuff:
|
53 |
+
*.log
|
54 |
+
local_settings.py
|
55 |
+
|
56 |
+
# Flask stuff:
|
57 |
+
instance/
|
58 |
+
.webassets-cache
|
59 |
+
|
60 |
+
# Scrapy stuff:
|
61 |
+
.scrapy
|
62 |
+
|
63 |
+
# Sphinx documentation
|
64 |
+
docs/_build/
|
65 |
+
|
66 |
+
# PyBuilder
|
67 |
+
target/
|
68 |
+
|
69 |
+
# Jupyter Notebook
|
70 |
+
.ipynb_checkpoints
|
71 |
+
|
72 |
+
# pyenv
|
73 |
+
.python-version
|
74 |
+
|
75 |
+
# celery beat schedule file
|
76 |
+
celerybeat-schedule
|
77 |
+
|
78 |
+
# SageMath parsed files
|
79 |
+
*.sage.py
|
80 |
+
|
81 |
+
# Environments
|
82 |
+
.env
|
83 |
+
.venv
|
84 |
+
env/
|
85 |
+
venv/
|
86 |
+
ENV/
|
87 |
+
|
88 |
+
# Spyder project settings
|
89 |
+
.spyderproject
|
90 |
+
.spyproject
|
91 |
+
|
92 |
+
# Rope project settings
|
93 |
+
.ropeproject
|
94 |
+
|
95 |
+
# mkdocs documentation
|
96 |
+
/site
|
97 |
+
|
98 |
+
# mypy
|
99 |
+
.mypy_cache/
|
100 |
+
|
101 |
+
.vscode/
|
102 |
+
*.pkl
|
103 |
+
exp
|
104 |
+
exp/*
|
105 |
+
data
|
106 |
+
data/*
|
107 |
+
model
|
108 |
+
model/*
|
109 |
+
*/images
|
110 |
+
*/images/*
|
111 |
+
|
112 |
+
*.h5
|
113 |
+
*.pth
|
114 |
+
|
joints_detectors/Alphapose/SPPE/LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2018 Jeff-sjtu
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
joints_detectors/Alphapose/SPPE/README.md
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
# pytorch-AlphaPose
|
joints_detectors/Alphapose/SPPE/__init__.py
ADDED
File without changes
|
joints_detectors/Alphapose/SPPE/src/__init__.py
ADDED
File without changes
|
joints_detectors/Alphapose/SPPE/src/main_fast_inference.py
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import torch._utils
|
5 |
+
import torch.nn as nn
|
6 |
+
import torch.utils.data
|
7 |
+
import torch.utils.data.distributed
|
8 |
+
|
9 |
+
from SPPE.src.models.FastPose import createModel
|
10 |
+
from SPPE.src.utils.img import flip, shuffleLR
|
11 |
+
|
12 |
+
try:
|
13 |
+
torch._utils._rebuild_tensor_v2
|
14 |
+
except AttributeError:
|
15 |
+
def _rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks):
|
16 |
+
tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride)
|
17 |
+
tensor.requires_grad = requires_grad
|
18 |
+
tensor._backward_hooks = backward_hooks
|
19 |
+
return tensor
|
20 |
+
torch._utils._rebuild_tensor_v2 = _rebuild_tensor_v2
|
21 |
+
|
22 |
+
|
23 |
+
class InferenNet(nn.Module):
|
24 |
+
def __init__(self, kernel_size, dataset):
|
25 |
+
super(InferenNet, self).__init__()
|
26 |
+
|
27 |
+
model = createModel().cuda()
|
28 |
+
print('Loading pose model from {}'.format('joints_detectors/Alphapose/models/sppe/duc_se.pth'))
|
29 |
+
sys.stdout.flush()
|
30 |
+
model.load_state_dict(torch.load('joints_detectors/Alphapose/models/sppe/duc_se.pth'))
|
31 |
+
model.eval()
|
32 |
+
self.pyranet = model
|
33 |
+
|
34 |
+
self.dataset = dataset
|
35 |
+
|
36 |
+
def forward(self, x):
|
37 |
+
out = self.pyranet(x)
|
38 |
+
out = out.narrow(1, 0, 17)
|
39 |
+
|
40 |
+
flip_out = self.pyranet(flip(x))
|
41 |
+
flip_out = flip_out.narrow(1, 0, 17)
|
42 |
+
|
43 |
+
flip_out = flip(shuffleLR(
|
44 |
+
flip_out, self.dataset))
|
45 |
+
|
46 |
+
out = (flip_out + out) / 2
|
47 |
+
|
48 |
+
return out
|
49 |
+
|
50 |
+
|
51 |
+
class InferenNet_fast(nn.Module):
|
52 |
+
def __init__(self, kernel_size, dataset):
|
53 |
+
super(InferenNet_fast, self).__init__()
|
54 |
+
|
55 |
+
model = createModel().cuda()
|
56 |
+
print('Loading pose model from {}'.format('models/sppe/duc_se.pth'))
|
57 |
+
model.load_state_dict(torch.load('models/sppe/duc_se.pth'))
|
58 |
+
model.eval()
|
59 |
+
self.pyranet = model
|
60 |
+
|
61 |
+
self.dataset = dataset
|
62 |
+
|
63 |
+
def forward(self, x):
|
64 |
+
out = self.pyranet(x)
|
65 |
+
out = out.narrow(1, 0, 17)
|
66 |
+
|
67 |
+
return out
|
joints_detectors/Alphapose/SPPE/src/models/FastPose.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
from torch.autograd import Variable
|
3 |
+
|
4 |
+
from .layers.SE_Resnet import SEResnet
|
5 |
+
from .layers.DUC import DUC
|
6 |
+
from opt import opt
|
7 |
+
|
8 |
+
|
9 |
+
def createModel():
|
10 |
+
return FastPose()
|
11 |
+
|
12 |
+
|
13 |
+
class FastPose(nn.Module):
|
14 |
+
DIM = 128
|
15 |
+
|
16 |
+
def __init__(self):
|
17 |
+
super(FastPose, self).__init__()
|
18 |
+
|
19 |
+
self.preact = SEResnet('resnet101')
|
20 |
+
|
21 |
+
self.suffle1 = nn.PixelShuffle(2)
|
22 |
+
self.duc1 = DUC(512, 1024, upscale_factor=2)
|
23 |
+
self.duc2 = DUC(256, 512, upscale_factor=2)
|
24 |
+
|
25 |
+
self.conv_out = nn.Conv2d(
|
26 |
+
self.DIM, opt.nClasses, kernel_size=3, stride=1, padding=1)
|
27 |
+
|
28 |
+
def forward(self, x: Variable):
|
29 |
+
out = self.preact(x)
|
30 |
+
out = self.suffle1(out)
|
31 |
+
out = self.duc1(out)
|
32 |
+
out = self.duc2(out)
|
33 |
+
|
34 |
+
out = self.conv_out(out)
|
35 |
+
return out
|
joints_detectors/Alphapose/SPPE/src/models/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from . import *
|
joints_detectors/Alphapose/SPPE/src/models/hg-prm.py
ADDED
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
from .layers.PRM import Residual as ResidualPyramid
|
3 |
+
from .layers.Residual import Residual as Residual
|
4 |
+
from torch.autograd import Variable
|
5 |
+
from opt import opt
|
6 |
+
from collections import defaultdict
|
7 |
+
|
8 |
+
|
9 |
+
class Hourglass(nn.Module):
|
10 |
+
def __init__(self, n, nFeats, nModules, inputResH, inputResW, net_type, B, C):
|
11 |
+
super(Hourglass, self).__init__()
|
12 |
+
|
13 |
+
self.ResidualUp = ResidualPyramid if n >= 2 else Residual
|
14 |
+
self.ResidualDown = ResidualPyramid if n >= 3 else Residual
|
15 |
+
|
16 |
+
self.depth = n
|
17 |
+
self.nModules = nModules
|
18 |
+
self.nFeats = nFeats
|
19 |
+
self.net_type = net_type
|
20 |
+
self.B = B
|
21 |
+
self.C = C
|
22 |
+
self.inputResH = inputResH
|
23 |
+
self.inputResW = inputResW
|
24 |
+
|
25 |
+
self.up1 = self._make_residual(self.ResidualUp, False, inputResH, inputResW)
|
26 |
+
self.low1 = nn.Sequential(
|
27 |
+
nn.MaxPool2d(2),
|
28 |
+
self._make_residual(self.ResidualDown, False, inputResH / 2, inputResW / 2)
|
29 |
+
)
|
30 |
+
if n > 1:
|
31 |
+
self.low2 = Hourglass(n - 1, nFeats, nModules, inputResH / 2, inputResW / 2, net_type, B, C)
|
32 |
+
else:
|
33 |
+
self.low2 = self._make_residual(self.ResidualDown, False, inputResH / 2, inputResW / 2)
|
34 |
+
|
35 |
+
self.low3 = self._make_residual(self.ResidualDown, True, inputResH / 2, inputResW / 2)
|
36 |
+
self.up2 = nn.UpsamplingNearest2d(scale_factor=2)
|
37 |
+
|
38 |
+
self.upperBranch = self.up1
|
39 |
+
self.lowerBranch = nn.Sequential(
|
40 |
+
self.low1,
|
41 |
+
self.low2,
|
42 |
+
self.low3,
|
43 |
+
self.up2
|
44 |
+
)
|
45 |
+
|
46 |
+
def _make_residual(self, resBlock, useConv, inputResH, inputResW):
|
47 |
+
layer_list = []
|
48 |
+
for i in range(self.nModules):
|
49 |
+
layer_list.append(resBlock(self.nFeats, self.nFeats, inputResH, inputResW,
|
50 |
+
stride=1, net_type=self.net_type, useConv=useConv,
|
51 |
+
baseWidth=self.B, cardinality=self.C))
|
52 |
+
return nn.Sequential(*layer_list)
|
53 |
+
|
54 |
+
def forward(self, x: Variable):
|
55 |
+
up1 = self.upperBranch(x)
|
56 |
+
up2 = self.lowerBranch(x)
|
57 |
+
out = up1 + up2
|
58 |
+
return out
|
59 |
+
|
60 |
+
|
61 |
+
class PyraNet(nn.Module):
|
62 |
+
def __init__(self):
|
63 |
+
super(PyraNet, self).__init__()
|
64 |
+
|
65 |
+
B, C = opt.baseWidth, opt.cardinality
|
66 |
+
self.inputResH = opt.inputResH / 4
|
67 |
+
self.inputResW = opt.inputResW / 4
|
68 |
+
self.nStack = opt.nStack
|
69 |
+
|
70 |
+
self.cnv1 = nn.Sequential(
|
71 |
+
nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3),
|
72 |
+
nn.BatchNorm2d(64),
|
73 |
+
nn.ReLU(True)
|
74 |
+
)
|
75 |
+
self.r1 = nn.Sequential(
|
76 |
+
ResidualPyramid(64, 128, opt.inputResH / 2, opt.inputResW / 2,
|
77 |
+
stride=1, net_type='no_preact', useConv=False, baseWidth=B, cardinality=C),
|
78 |
+
nn.MaxPool2d(2)
|
79 |
+
)
|
80 |
+
self.r4 = ResidualPyramid(128, 128, self.inputResH, self.inputResW,
|
81 |
+
stride=1, net_type='preact', useConv=False, baseWidth=B, cardinality=C)
|
82 |
+
self.r5 = ResidualPyramid(128, opt.nFeats, self.inputResH, self.inputResW,
|
83 |
+
stride=1, net_type='preact', useConv=False, baseWidth=B, cardinality=C)
|
84 |
+
self.preact = nn.Sequential(
|
85 |
+
self.cnv1,
|
86 |
+
self.r1,
|
87 |
+
self.r4,
|
88 |
+
self.r5
|
89 |
+
)
|
90 |
+
self.stack_layers = defaultdict(list)
|
91 |
+
for i in range(self.nStack):
|
92 |
+
hg = Hourglass(4, opt.nFeats, opt.nResidual, self.inputResH, self.inputResW, 'preact', B, C)
|
93 |
+
lin = nn.Sequential(
|
94 |
+
hg,
|
95 |
+
nn.BatchNorm2d(opt.nFeats),
|
96 |
+
nn.ReLU(True),
|
97 |
+
nn.Conv2d(opt.nFeats, opt.nFeats, kernel_size=1, stride=1, padding=0),
|
98 |
+
nn.BatchNorm2d(opt.nFeats),
|
99 |
+
nn.ReLU(True)
|
100 |
+
)
|
101 |
+
tmpOut = nn.Conv2d(opt.nFeats, opt.nClasses, kernel_size=1, stride=1, padding=0)
|
102 |
+
self.stack_layers['lin'].append(lin)
|
103 |
+
self.stack_layers['out'].append(tmpOut)
|
104 |
+
if i < self.nStack - 1:
|
105 |
+
lin_ = nn.Conv2d(opt.nFeats, opt.nFeats, kernel_size=1, stride=1, padding=0)
|
106 |
+
tmpOut_ = nn.Conv2d(opt.nClasses, opt.nFeats, kernel_size=1, stride=1, padding=0)
|
107 |
+
self.stack_layers['lin_'].append(lin_)
|
108 |
+
self.stack_layers['out_'].append(tmpOut_)
|
109 |
+
|
110 |
+
def forward(self, x: Variable):
|
111 |
+
out = []
|
112 |
+
inter = self.preact(x)
|
113 |
+
for i in range(self.nStack):
|
114 |
+
lin = self.stack_layers['lin'][i](inter)
|
115 |
+
tmpOut = self.stack_layers['out'][i](lin)
|
116 |
+
out.append(tmpOut)
|
117 |
+
if i < self.nStack - 1:
|
118 |
+
lin_ = self.stack_layers['lin_'][i](lin)
|
119 |
+
tmpOut_ = self.stack_layers['out_'][i](tmpOut)
|
120 |
+
inter = inter + lin_ + tmpOut_
|
121 |
+
return out
|
122 |
+
|
123 |
+
|
124 |
+
def createModel(**kw):
|
125 |
+
model = PyraNet()
|
126 |
+
return model
|
joints_detectors/Alphapose/SPPE/src/models/hgPRM.py
ADDED
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
from .layers.PRM import Residual as ResidualPyramid
|
3 |
+
from .layers.Residual import Residual as Residual
|
4 |
+
from torch.autograd import Variable
|
5 |
+
import torch
|
6 |
+
from opt import opt
|
7 |
+
import math
|
8 |
+
|
9 |
+
|
10 |
+
class Hourglass(nn.Module):
|
11 |
+
def __init__(self, n, nFeats, nModules, inputResH, inputResW, net_type, B, C):
|
12 |
+
super(Hourglass, self).__init__()
|
13 |
+
|
14 |
+
self.ResidualUp = ResidualPyramid if n >= 2 else Residual
|
15 |
+
self.ResidualDown = ResidualPyramid if n >= 3 else Residual
|
16 |
+
|
17 |
+
self.depth = n
|
18 |
+
self.nModules = nModules
|
19 |
+
self.nFeats = nFeats
|
20 |
+
self.net_type = net_type
|
21 |
+
self.B = B
|
22 |
+
self.C = C
|
23 |
+
self.inputResH = inputResH
|
24 |
+
self.inputResW = inputResW
|
25 |
+
|
26 |
+
up1 = self._make_residual(self.ResidualUp, False, inputResH, inputResW)
|
27 |
+
low1 = nn.Sequential(
|
28 |
+
nn.MaxPool2d(2),
|
29 |
+
self._make_residual(self.ResidualDown, False, inputResH / 2, inputResW / 2)
|
30 |
+
)
|
31 |
+
if n > 1:
|
32 |
+
low2 = Hourglass(n - 1, nFeats, nModules, inputResH / 2, inputResW / 2, net_type, B, C)
|
33 |
+
else:
|
34 |
+
low2 = self._make_residual(self.ResidualDown, False, inputResH / 2, inputResW / 2)
|
35 |
+
|
36 |
+
low3 = self._make_residual(self.ResidualDown, True, inputResH / 2, inputResW / 2)
|
37 |
+
up2 = nn.UpsamplingNearest2d(scale_factor=2)
|
38 |
+
|
39 |
+
self.upperBranch = up1
|
40 |
+
self.lowerBranch = nn.Sequential(
|
41 |
+
low1,
|
42 |
+
low2,
|
43 |
+
low3,
|
44 |
+
up2
|
45 |
+
)
|
46 |
+
|
47 |
+
def _make_residual(self, resBlock, useConv, inputResH, inputResW):
|
48 |
+
layer_list = []
|
49 |
+
for i in range(self.nModules):
|
50 |
+
layer_list.append(resBlock(self.nFeats, self.nFeats, inputResH, inputResW,
|
51 |
+
stride=1, net_type=self.net_type, useConv=useConv,
|
52 |
+
baseWidth=self.B, cardinality=self.C))
|
53 |
+
return nn.Sequential(*layer_list)
|
54 |
+
|
55 |
+
def forward(self, x: Variable):
|
56 |
+
up1 = self.upperBranch(x)
|
57 |
+
up2 = self.lowerBranch(x)
|
58 |
+
# out = up1 + up2
|
59 |
+
out = torch.add(up1, up2)
|
60 |
+
return out
|
61 |
+
|
62 |
+
|
63 |
+
class PyraNet(nn.Module):
|
64 |
+
def __init__(self):
|
65 |
+
super(PyraNet, self).__init__()
|
66 |
+
|
67 |
+
B, C = opt.baseWidth, opt.cardinality
|
68 |
+
self.inputResH = opt.inputResH / 4
|
69 |
+
self.inputResW = opt.inputResW / 4
|
70 |
+
self.nStack = opt.nStack
|
71 |
+
|
72 |
+
conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3)
|
73 |
+
if opt.init:
|
74 |
+
nn.init.xavier_normal(conv1.weight, gain=math.sqrt(1 / 3))
|
75 |
+
|
76 |
+
cnv1 = nn.Sequential(
|
77 |
+
conv1,
|
78 |
+
nn.BatchNorm2d(64),
|
79 |
+
nn.ReLU(True)
|
80 |
+
)
|
81 |
+
|
82 |
+
r1 = nn.Sequential(
|
83 |
+
ResidualPyramid(64, 128, opt.inputResH / 2, opt.inputResW / 2,
|
84 |
+
stride=1, net_type='no_preact', useConv=False, baseWidth=B, cardinality=C),
|
85 |
+
nn.MaxPool2d(2)
|
86 |
+
)
|
87 |
+
r4 = ResidualPyramid(128, 128, self.inputResH, self.inputResW,
|
88 |
+
stride=1, net_type='preact', useConv=False, baseWidth=B, cardinality=C)
|
89 |
+
r5 = ResidualPyramid(128, opt.nFeats, self.inputResH, self.inputResW,
|
90 |
+
stride=1, net_type='preact', useConv=False, baseWidth=B, cardinality=C)
|
91 |
+
self.preact = nn.Sequential(
|
92 |
+
cnv1,
|
93 |
+
r1,
|
94 |
+
r4,
|
95 |
+
r5
|
96 |
+
)
|
97 |
+
|
98 |
+
self.stack_lin = nn.ModuleList()
|
99 |
+
self.stack_out = nn.ModuleList()
|
100 |
+
self.stack_lin_ = nn.ModuleList()
|
101 |
+
self.stack_out_ = nn.ModuleList()
|
102 |
+
|
103 |
+
for i in range(self.nStack):
|
104 |
+
hg = Hourglass(4, opt.nFeats, opt.nResidual, self.inputResH, self.inputResW, 'preact', B, C)
|
105 |
+
conv1 = nn.Conv2d(opt.nFeats, opt.nFeats, kernel_size=1, stride=1, padding=0)
|
106 |
+
if opt.init:
|
107 |
+
nn.init.xavier_normal(conv1.weight, gain=math.sqrt(1 / 2))
|
108 |
+
lin = nn.Sequential(
|
109 |
+
hg,
|
110 |
+
nn.BatchNorm2d(opt.nFeats),
|
111 |
+
nn.ReLU(True),
|
112 |
+
conv1,
|
113 |
+
nn.BatchNorm2d(opt.nFeats),
|
114 |
+
nn.ReLU(True)
|
115 |
+
)
|
116 |
+
tmpOut = nn.Conv2d(opt.nFeats, opt.nClasses, kernel_size=1, stride=1, padding=0)
|
117 |
+
if opt.init:
|
118 |
+
nn.init.xavier_normal(tmpOut.weight)
|
119 |
+
self.stack_lin.append(lin)
|
120 |
+
self.stack_out.append(tmpOut)
|
121 |
+
if i < self.nStack - 1:
|
122 |
+
lin_ = nn.Conv2d(opt.nFeats, opt.nFeats, kernel_size=1, stride=1, padding=0)
|
123 |
+
tmpOut_ = nn.Conv2d(opt.nClasses, opt.nFeats, kernel_size=1, stride=1, padding=0)
|
124 |
+
if opt.init:
|
125 |
+
nn.init.xavier_normal(lin_.weight)
|
126 |
+
nn.init.xavier_normal(tmpOut_.weight)
|
127 |
+
self.stack_lin_.append(lin_)
|
128 |
+
self.stack_out_.append(tmpOut_)
|
129 |
+
|
130 |
+
def forward(self, x: Variable):
|
131 |
+
out = []
|
132 |
+
inter = self.preact(x)
|
133 |
+
for i in range(self.nStack):
|
134 |
+
lin = self.stack_lin[i](inter)
|
135 |
+
tmpOut = self.stack_out[i](lin)
|
136 |
+
out.append(tmpOut)
|
137 |
+
if i < self.nStack - 1:
|
138 |
+
lin_ = self.stack_lin_[i](lin)
|
139 |
+
tmpOut_ = self.stack_out_[i](tmpOut)
|
140 |
+
inter = inter + lin_ + tmpOut_
|
141 |
+
return out
|
142 |
+
|
143 |
+
|
144 |
+
class PyraNet_Inference(nn.Module):
|
145 |
+
def __init__(self):
|
146 |
+
super(PyraNet_Inference, self).__init__()
|
147 |
+
|
148 |
+
B, C = opt.baseWidth, opt.cardinality
|
149 |
+
self.inputResH = opt.inputResH / 4
|
150 |
+
self.inputResW = opt.inputResW / 4
|
151 |
+
self.nStack = opt.nStack
|
152 |
+
|
153 |
+
conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3)
|
154 |
+
if opt.init:
|
155 |
+
nn.init.xavier_normal(conv1.weight, gain=math.sqrt(1 / 3))
|
156 |
+
|
157 |
+
cnv1 = nn.Sequential(
|
158 |
+
conv1,
|
159 |
+
nn.BatchNorm2d(64),
|
160 |
+
nn.ReLU(True)
|
161 |
+
)
|
162 |
+
|
163 |
+
r1 = nn.Sequential(
|
164 |
+
ResidualPyramid(64, 128, opt.inputResH / 2, opt.inputResW / 2,
|
165 |
+
stride=1, net_type='no_preact', useConv=False, baseWidth=B, cardinality=C),
|
166 |
+
nn.MaxPool2d(2)
|
167 |
+
)
|
168 |
+
r4 = ResidualPyramid(128, 128, self.inputResH, self.inputResW,
|
169 |
+
stride=1, net_type='preact', useConv=False, baseWidth=B, cardinality=C)
|
170 |
+
r5 = ResidualPyramid(128, opt.nFeats, self.inputResH, self.inputResW,
|
171 |
+
stride=1, net_type='preact', useConv=False, baseWidth=B, cardinality=C)
|
172 |
+
self.preact = nn.Sequential(
|
173 |
+
cnv1,
|
174 |
+
r1,
|
175 |
+
r4,
|
176 |
+
r5
|
177 |
+
)
|
178 |
+
|
179 |
+
self.stack_lin = nn.ModuleList()
|
180 |
+
self.stack_out = nn.ModuleList()
|
181 |
+
self.stack_lin_ = nn.ModuleList()
|
182 |
+
self.stack_out_ = nn.ModuleList()
|
183 |
+
|
184 |
+
for i in range(self.nStack):
|
185 |
+
hg = Hourglass(4, opt.nFeats, opt.nResidual,
|
186 |
+
self.inputResH, self.inputResW, 'preact', B, C)
|
187 |
+
conv1 = nn.Conv2d(opt.nFeats, opt.nFeats,
|
188 |
+
kernel_size=1, stride=1, padding=0)
|
189 |
+
if opt.init:
|
190 |
+
nn.init.xavier_normal(conv1.weight, gain=math.sqrt(1 / 2))
|
191 |
+
lin = nn.Sequential(
|
192 |
+
hg,
|
193 |
+
nn.BatchNorm2d(opt.nFeats),
|
194 |
+
nn.ReLU(True),
|
195 |
+
conv1,
|
196 |
+
nn.BatchNorm2d(opt.nFeats),
|
197 |
+
nn.ReLU(True)
|
198 |
+
)
|
199 |
+
tmpOut = nn.Conv2d(opt.nFeats, opt.nClasses,
|
200 |
+
kernel_size=1, stride=1, padding=0)
|
201 |
+
if opt.init:
|
202 |
+
nn.init.xavier_normal(tmpOut.weight)
|
203 |
+
self.stack_lin.append(lin)
|
204 |
+
self.stack_out.append(tmpOut)
|
205 |
+
if i < self.nStack - 1:
|
206 |
+
lin_ = nn.Conv2d(opt.nFeats, opt.nFeats,
|
207 |
+
kernel_size=1, stride=1, padding=0)
|
208 |
+
tmpOut_ = nn.Conv2d(opt.nClasses, opt.nFeats,
|
209 |
+
kernel_size=1, stride=1, padding=0)
|
210 |
+
if opt.init:
|
211 |
+
nn.init.xavier_normal(lin_.weight)
|
212 |
+
nn.init.xavier_normal(tmpOut_.weight)
|
213 |
+
self.stack_lin_.append(lin_)
|
214 |
+
self.stack_out_.append(tmpOut_)
|
215 |
+
|
216 |
+
def forward(self, x: Variable):
|
217 |
+
inter = self.preact(x)
|
218 |
+
for i in range(self.nStack):
|
219 |
+
lin = self.stack_lin[i](inter)
|
220 |
+
tmpOut = self.stack_out[i](lin)
|
221 |
+
out = tmpOut
|
222 |
+
if i < self.nStack - 1:
|
223 |
+
lin_ = self.stack_lin_[i](lin)
|
224 |
+
tmpOut_ = self.stack_out_[i](tmpOut)
|
225 |
+
inter = inter + lin_ + tmpOut_
|
226 |
+
return out
|
227 |
+
|
228 |
+
|
229 |
+
def createModel(**kw):
|
230 |
+
model = PyraNet()
|
231 |
+
return model
|
232 |
+
|
233 |
+
|
234 |
+
def createModel_Inference(**kw):
|
235 |
+
model = PyraNet_Inference()
|
236 |
+
return model
|
joints_detectors/Alphapose/SPPE/src/models/layers/DUC.py
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
import torch.nn.functional as F
|
3 |
+
|
4 |
+
|
5 |
+
class DUC(nn.Module):
|
6 |
+
'''
|
7 |
+
INPUT: inplanes, planes, upscale_factor
|
8 |
+
OUTPUT: (planes // 4)* ht * wd
|
9 |
+
'''
|
10 |
+
def __init__(self, inplanes, planes, upscale_factor=2):
|
11 |
+
super(DUC, self).__init__()
|
12 |
+
self.conv = nn.Conv2d(inplanes, planes, kernel_size=3, padding=1, bias=False)
|
13 |
+
self.bn = nn.BatchNorm2d(planes)
|
14 |
+
self.relu = nn.ReLU()
|
15 |
+
|
16 |
+
self.pixel_shuffle = nn.PixelShuffle(upscale_factor)
|
17 |
+
|
18 |
+
def forward(self, x):
|
19 |
+
x = self.conv(x)
|
20 |
+
x = self.bn(x)
|
21 |
+
x = self.relu(x)
|
22 |
+
x = self.pixel_shuffle(x)
|
23 |
+
return x
|
joints_detectors/Alphapose/SPPE/src/models/layers/PRM.py
ADDED
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
from .util_models import ConcatTable, CaddTable, Identity
|
3 |
+
import math
|
4 |
+
from opt import opt
|
5 |
+
|
6 |
+
|
7 |
+
class Residual(nn.Module):
|
8 |
+
def __init__(self, numIn, numOut, inputResH, inputResW, stride=1,
|
9 |
+
net_type='preact', useConv=False, baseWidth=9, cardinality=4):
|
10 |
+
super(Residual, self).__init__()
|
11 |
+
|
12 |
+
self.con = ConcatTable([convBlock(numIn, numOut, inputResH,
|
13 |
+
inputResW, net_type, baseWidth, cardinality, stride),
|
14 |
+
skipLayer(numIn, numOut, stride, useConv)])
|
15 |
+
self.cadd = CaddTable(True)
|
16 |
+
|
17 |
+
def forward(self, x):
|
18 |
+
out = self.con(x)
|
19 |
+
out = self.cadd(out)
|
20 |
+
return out
|
21 |
+
|
22 |
+
|
23 |
+
def convBlock(numIn, numOut, inputResH, inputResW, net_type, baseWidth, cardinality, stride):
|
24 |
+
numIn = int(numIn)
|
25 |
+
numOut = int(numOut)
|
26 |
+
|
27 |
+
addTable = ConcatTable()
|
28 |
+
s_list = []
|
29 |
+
if net_type != 'no_preact':
|
30 |
+
s_list.append(nn.BatchNorm2d(numIn))
|
31 |
+
s_list.append(nn.ReLU(True))
|
32 |
+
|
33 |
+
conv1 = nn.Conv2d(numIn, numOut // 2, kernel_size=1)
|
34 |
+
if opt.init:
|
35 |
+
nn.init.xavier_normal(conv1.weight, gain=math.sqrt(1 / 2))
|
36 |
+
s_list.append(conv1)
|
37 |
+
|
38 |
+
s_list.append(nn.BatchNorm2d(numOut // 2))
|
39 |
+
s_list.append(nn.ReLU(True))
|
40 |
+
|
41 |
+
conv2 = nn.Conv2d(numOut // 2, numOut // 2,
|
42 |
+
kernel_size=3, stride=stride, padding=1)
|
43 |
+
if opt.init:
|
44 |
+
nn.init.xavier_normal(conv2.weight)
|
45 |
+
s_list.append(conv2)
|
46 |
+
|
47 |
+
s = nn.Sequential(*s_list)
|
48 |
+
addTable.add(s)
|
49 |
+
|
50 |
+
D = math.floor(numOut // baseWidth)
|
51 |
+
C = cardinality
|
52 |
+
s_list = []
|
53 |
+
|
54 |
+
if net_type != 'no_preact':
|
55 |
+
s_list.append(nn.BatchNorm2d(numIn))
|
56 |
+
s_list.append(nn.ReLU(True))
|
57 |
+
|
58 |
+
conv1 = nn.Conv2d(numIn, D, kernel_size=1, stride=stride)
|
59 |
+
if opt.init:
|
60 |
+
nn.init.xavier_normal(conv1.weight, gain=math.sqrt(1 / C))
|
61 |
+
|
62 |
+
s_list.append(conv1)
|
63 |
+
s_list.append(nn.BatchNorm2d(D))
|
64 |
+
s_list.append(nn.ReLU(True))
|
65 |
+
s_list.append(pyramid(D, C, inputResH, inputResW))
|
66 |
+
s_list.append(nn.BatchNorm2d(D))
|
67 |
+
s_list.append(nn.ReLU(True))
|
68 |
+
|
69 |
+
a = nn.Conv2d(D, numOut // 2, kernel_size=1)
|
70 |
+
a.nBranchIn = C
|
71 |
+
if opt.init:
|
72 |
+
nn.init.xavier_normal(a.weight, gain=math.sqrt(1 / C))
|
73 |
+
s_list.append(a)
|
74 |
+
|
75 |
+
s = nn.Sequential(*s_list)
|
76 |
+
addTable.add(s)
|
77 |
+
|
78 |
+
elewiswAdd = nn.Sequential(
|
79 |
+
addTable,
|
80 |
+
CaddTable(False)
|
81 |
+
)
|
82 |
+
conv2 = nn.Conv2d(numOut // 2, numOut, kernel_size=1)
|
83 |
+
if opt.init:
|
84 |
+
nn.init.xavier_normal(conv2.weight, gain=math.sqrt(1 / 2))
|
85 |
+
model = nn.Sequential(
|
86 |
+
elewiswAdd,
|
87 |
+
nn.BatchNorm2d(numOut // 2),
|
88 |
+
nn.ReLU(True),
|
89 |
+
conv2
|
90 |
+
)
|
91 |
+
return model
|
92 |
+
|
93 |
+
|
94 |
+
def pyramid(D, C, inputResH, inputResW):
|
95 |
+
pyraTable = ConcatTable()
|
96 |
+
sc = math.pow(2, 1 / C)
|
97 |
+
for i in range(C):
|
98 |
+
scaled = 1 / math.pow(sc, i + 1)
|
99 |
+
conv1 = nn.Conv2d(D, D, kernel_size=3, stride=1, padding=1)
|
100 |
+
if opt.init:
|
101 |
+
nn.init.xavier_normal(conv1.weight)
|
102 |
+
s = nn.Sequential(
|
103 |
+
nn.FractionalMaxPool2d(2, output_ratio=(scaled, scaled)),
|
104 |
+
conv1,
|
105 |
+
nn.UpsamplingBilinear2d(size=(int(inputResH), int(inputResW))))
|
106 |
+
pyraTable.add(s)
|
107 |
+
pyra = nn.Sequential(
|
108 |
+
pyraTable,
|
109 |
+
CaddTable(False)
|
110 |
+
)
|
111 |
+
return pyra
|
112 |
+
|
113 |
+
|
114 |
+
class skipLayer(nn.Module):
|
115 |
+
def __init__(self, numIn, numOut, stride, useConv):
|
116 |
+
super(skipLayer, self).__init__()
|
117 |
+
self.identity = False
|
118 |
+
|
119 |
+
if numIn == numOut and stride == 1 and not useConv:
|
120 |
+
self.identity = True
|
121 |
+
else:
|
122 |
+
conv1 = nn.Conv2d(numIn, numOut, kernel_size=1, stride=stride)
|
123 |
+
if opt.init:
|
124 |
+
nn.init.xavier_normal(conv1.weight, gain=math.sqrt(1 / 2))
|
125 |
+
self.m = nn.Sequential(
|
126 |
+
nn.BatchNorm2d(numIn),
|
127 |
+
nn.ReLU(True),
|
128 |
+
conv1
|
129 |
+
)
|
130 |
+
|
131 |
+
def forward(self, x):
|
132 |
+
if self.identity:
|
133 |
+
return x
|
134 |
+
else:
|
135 |
+
return self.m(x)
|
joints_detectors/Alphapose/SPPE/src/models/layers/Residual.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
import math
|
3 |
+
from .util_models import ConcatTable, CaddTable, Identity
|
4 |
+
from opt import opt
|
5 |
+
|
6 |
+
|
7 |
+
def Residual(numIn, numOut, *arg, stride=1, net_type='preact', useConv=False, **kw):
|
8 |
+
con = ConcatTable([convBlock(numIn, numOut, stride, net_type),
|
9 |
+
skipLayer(numIn, numOut, stride, useConv)])
|
10 |
+
cadd = CaddTable(True)
|
11 |
+
return nn.Sequential(con, cadd)
|
12 |
+
|
13 |
+
|
14 |
+
def convBlock(numIn, numOut, stride, net_type):
|
15 |
+
s_list = []
|
16 |
+
if net_type != 'no_preact':
|
17 |
+
s_list.append(nn.BatchNorm2d(numIn))
|
18 |
+
s_list.append(nn.ReLU(True))
|
19 |
+
|
20 |
+
conv1 = nn.Conv2d(numIn, numOut // 2, kernel_size=1)
|
21 |
+
if opt.init:
|
22 |
+
nn.init.xavier_normal(conv1.weight, gain=math.sqrt(1 / 2))
|
23 |
+
s_list.append(conv1)
|
24 |
+
|
25 |
+
s_list.append(nn.BatchNorm2d(numOut // 2))
|
26 |
+
s_list.append(nn.ReLU(True))
|
27 |
+
|
28 |
+
conv2 = nn.Conv2d(numOut // 2, numOut // 2, kernel_size=3, stride=stride, padding=1)
|
29 |
+
if opt.init:
|
30 |
+
nn.init.xavier_normal(conv2.weight)
|
31 |
+
s_list.append(conv2)
|
32 |
+
s_list.append(nn.BatchNorm2d(numOut // 2))
|
33 |
+
s_list.append(nn.ReLU(True))
|
34 |
+
|
35 |
+
conv3 = nn.Conv2d(numOut // 2, numOut, kernel_size=1)
|
36 |
+
if opt.init:
|
37 |
+
nn.init.xavier_normal(conv3.weight)
|
38 |
+
s_list.append(conv3)
|
39 |
+
|
40 |
+
return nn.Sequential(*s_list)
|
41 |
+
|
42 |
+
|
43 |
+
def skipLayer(numIn, numOut, stride, useConv):
|
44 |
+
if numIn == numOut and stride == 1 and not useConv:
|
45 |
+
return Identity()
|
46 |
+
else:
|
47 |
+
conv1 = nn.Conv2d(numIn, numOut, kernel_size=1, stride=stride)
|
48 |
+
if opt.init:
|
49 |
+
nn.init.xavier_normal(conv1.weight, gain=math.sqrt(1 / 2))
|
50 |
+
return nn.Sequential(
|
51 |
+
nn.BatchNorm2d(numIn),
|
52 |
+
nn.ReLU(True),
|
53 |
+
conv1
|
54 |
+
)
|
joints_detectors/Alphapose/SPPE/src/models/layers/Resnet.py
ADDED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
import torch.nn.functional as F
|
3 |
+
|
4 |
+
|
5 |
+
class Bottleneck(nn.Module):
|
6 |
+
expansion = 4
|
7 |
+
|
8 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None):
|
9 |
+
super(Bottleneck, self).__init__()
|
10 |
+
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, stride=1, bias=False)
|
11 |
+
self.bn1 = nn.BatchNorm2d(planes)
|
12 |
+
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
|
13 |
+
self.bn2 = nn.BatchNorm2d(planes)
|
14 |
+
self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, stride=1, bias=False)
|
15 |
+
self.bn3 = nn.BatchNorm2d(planes * 4)
|
16 |
+
self.downsample = downsample
|
17 |
+
self.stride = stride
|
18 |
+
|
19 |
+
def forward(self, x):
|
20 |
+
residual = x
|
21 |
+
|
22 |
+
out = F.relu(self.bn1(self.conv1(x)), inplace=True)
|
23 |
+
out = F.relu(self.bn2(self.conv2(out)), inplace=True)
|
24 |
+
out = self.bn3(self.conv3(out))
|
25 |
+
|
26 |
+
if self.downsample is not None:
|
27 |
+
residual = self.downsample(x)
|
28 |
+
|
29 |
+
out += residual
|
30 |
+
out = F.relu(out, inplace=True)
|
31 |
+
|
32 |
+
return out
|
33 |
+
|
34 |
+
|
35 |
+
class ResNet(nn.Module):
|
36 |
+
""" Resnet """
|
37 |
+
def __init__(self, architecture):
|
38 |
+
super(ResNet, self).__init__()
|
39 |
+
assert architecture in ["resnet50", "resnet101"]
|
40 |
+
self.inplanes = 64
|
41 |
+
self.layers = [3, 4, {"resnet50": 6, "resnet101": 23}[architecture], 3]
|
42 |
+
self.block = Bottleneck
|
43 |
+
|
44 |
+
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
|
45 |
+
self.bn1 = nn.BatchNorm2d(64, eps=1e-5, momentum=0.01, affine=True)
|
46 |
+
self.relu = nn.ReLU(inplace=True)
|
47 |
+
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2)
|
48 |
+
|
49 |
+
self.layer1 = self.make_layer(self.block, 64, self.layers[0])
|
50 |
+
self.layer2 = self.make_layer(self.block, 128, self.layers[1], stride=2)
|
51 |
+
self.layer3 = self.make_layer(self.block, 256, self.layers[2], stride=2)
|
52 |
+
|
53 |
+
self.layer4 = self.make_layer(
|
54 |
+
self.block, 512, self.layers[3], stride=2)
|
55 |
+
|
56 |
+
def forward(self, x):
|
57 |
+
x = self.maxpool(self.relu(self.bn1(self.conv1(x))))
|
58 |
+
x = self.layer1(x)
|
59 |
+
x = self.layer2(x)
|
60 |
+
x = self.layer3(x)
|
61 |
+
x = self.layer4(x)
|
62 |
+
return x
|
63 |
+
|
64 |
+
def stages(self):
|
65 |
+
return [self.layer1, self.layer2, self.layer3, self.layer4]
|
66 |
+
|
67 |
+
def make_layer(self, block, planes, blocks, stride=1):
|
68 |
+
downsample = None
|
69 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
70 |
+
downsample = nn.Sequential(
|
71 |
+
nn.Conv2d(self.inplanes, planes * block.expansion,
|
72 |
+
kernel_size=1, stride=stride, bias=False),
|
73 |
+
nn.BatchNorm2d(planes * block.expansion),
|
74 |
+
)
|
75 |
+
|
76 |
+
layers = []
|
77 |
+
layers.append(block(self.inplanes, planes, stride, downsample))
|
78 |
+
self.inplanes = planes * block.expansion
|
79 |
+
for i in range(1, blocks):
|
80 |
+
layers.append(block(self.inplanes, planes))
|
81 |
+
|
82 |
+
return nn.Sequential(*layers)
|
joints_detectors/Alphapose/SPPE/src/models/layers/SE_Resnet.py
ADDED
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
from .SE_module import SELayer
|
3 |
+
import torch.nn.functional as F
|
4 |
+
|
5 |
+
|
6 |
+
class Bottleneck(nn.Module):
|
7 |
+
expansion = 4
|
8 |
+
|
9 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None, reduction=False):
|
10 |
+
super(Bottleneck, self).__init__()
|
11 |
+
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
|
12 |
+
self.bn1 = nn.BatchNorm2d(planes)
|
13 |
+
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
|
14 |
+
padding=1, bias=False)
|
15 |
+
self.bn2 = nn.BatchNorm2d(planes)
|
16 |
+
self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
|
17 |
+
self.bn3 = nn.BatchNorm2d(planes * 4)
|
18 |
+
if reduction:
|
19 |
+
self.se = SELayer(planes * 4)
|
20 |
+
|
21 |
+
self.reduc = reduction
|
22 |
+
self.downsample = downsample
|
23 |
+
self.stride = stride
|
24 |
+
|
25 |
+
def forward(self, x):
|
26 |
+
residual = x
|
27 |
+
|
28 |
+
out = F.relu(self.bn1(self.conv1(x)), inplace=True)
|
29 |
+
out = F.relu(self.bn2(self.conv2(out)), inplace=True)
|
30 |
+
|
31 |
+
out = self.conv3(out)
|
32 |
+
out = self.bn3(out)
|
33 |
+
if self.reduc:
|
34 |
+
out = self.se(out)
|
35 |
+
|
36 |
+
if self.downsample is not None:
|
37 |
+
residual = self.downsample(x)
|
38 |
+
|
39 |
+
out += residual
|
40 |
+
out = F.relu(out)
|
41 |
+
|
42 |
+
return out
|
43 |
+
|
44 |
+
|
45 |
+
class SEResnet(nn.Module):
|
46 |
+
""" SEResnet """
|
47 |
+
|
48 |
+
def __init__(self, architecture):
|
49 |
+
super(SEResnet, self).__init__()
|
50 |
+
assert architecture in ["resnet50", "resnet101"]
|
51 |
+
self.inplanes = 64
|
52 |
+
self.layers = [3, 4, {"resnet50": 6, "resnet101": 23}[architecture], 3]
|
53 |
+
self.block = Bottleneck
|
54 |
+
|
55 |
+
self.conv1 = nn.Conv2d(3, 64, kernel_size=7,
|
56 |
+
stride=2, padding=3, bias=False)
|
57 |
+
self.bn1 = nn.BatchNorm2d(64, eps=1e-5, momentum=0.01, affine=True)
|
58 |
+
self.relu = nn.ReLU(inplace=True)
|
59 |
+
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
|
60 |
+
|
61 |
+
self.layer1 = self.make_layer(self.block, 64, self.layers[0])
|
62 |
+
self.layer2 = self.make_layer(
|
63 |
+
self.block, 128, self.layers[1], stride=2)
|
64 |
+
self.layer3 = self.make_layer(
|
65 |
+
self.block, 256, self.layers[2], stride=2)
|
66 |
+
|
67 |
+
self.layer4 = self.make_layer(
|
68 |
+
self.block, 512, self.layers[3], stride=2)
|
69 |
+
|
70 |
+
def forward(self, x):
|
71 |
+
x = self.maxpool(self.relu(self.bn1(self.conv1(x)))) # 64 * h/4 * w/4
|
72 |
+
x = self.layer1(x) # 256 * h/4 * w/4
|
73 |
+
x = self.layer2(x) # 512 * h/8 * w/8
|
74 |
+
x = self.layer3(x) # 1024 * h/16 * w/16
|
75 |
+
x = self.layer4(x) # 2048 * h/32 * w/32
|
76 |
+
return x
|
77 |
+
|
78 |
+
def stages(self):
|
79 |
+
return [self.layer1, self.layer2, self.layer3, self.layer4]
|
80 |
+
|
81 |
+
def make_layer(self, block, planes, blocks, stride=1):
|
82 |
+
downsample = None
|
83 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
84 |
+
downsample = nn.Sequential(
|
85 |
+
nn.Conv2d(self.inplanes, planes * block.expansion,
|
86 |
+
kernel_size=1, stride=stride, bias=False),
|
87 |
+
nn.BatchNorm2d(planes * block.expansion),
|
88 |
+
)
|
89 |
+
|
90 |
+
layers = []
|
91 |
+
if downsample is not None:
|
92 |
+
layers.append(block(self.inplanes, planes, stride, downsample, reduction=True))
|
93 |
+
else:
|
94 |
+
layers.append(block(self.inplanes, planes, stride, downsample))
|
95 |
+
self.inplanes = planes * block.expansion
|
96 |
+
for i in range(1, blocks):
|
97 |
+
layers.append(block(self.inplanes, planes))
|
98 |
+
|
99 |
+
return nn.Sequential(*layers)
|
joints_detectors/Alphapose/SPPE/src/models/layers/SE_module.py
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from torch import nn
|
2 |
+
|
3 |
+
|
4 |
+
class SELayer(nn.Module):
|
5 |
+
def __init__(self, channel, reduction=1):
|
6 |
+
super(SELayer, self).__init__()
|
7 |
+
self.avg_pool = nn.AdaptiveAvgPool2d(1)
|
8 |
+
self.fc = nn.Sequential(
|
9 |
+
nn.Linear(channel, channel // reduction),
|
10 |
+
nn.ReLU(inplace=True),
|
11 |
+
nn.Linear(channel // reduction, channel),
|
12 |
+
nn.Sigmoid()
|
13 |
+
)
|
14 |
+
|
15 |
+
def forward(self, x):
|
16 |
+
b, c, _, _ = x.size()
|
17 |
+
y = self.avg_pool(x).view(b, c)
|
18 |
+
y = self.fc(y).view(b, c, 1, 1)
|
19 |
+
return x * y
|
joints_detectors/Alphapose/SPPE/src/models/layers/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from . import *
|
joints_detectors/Alphapose/SPPE/src/models/layers/util_models.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
from torch.autograd import Variable
|
4 |
+
|
5 |
+
|
6 |
+
class ConcatTable(nn.Module):
|
7 |
+
def __init__(self, module_list=None):
|
8 |
+
super(ConcatTable, self).__init__()
|
9 |
+
|
10 |
+
self.modules_list = nn.ModuleList(module_list)
|
11 |
+
|
12 |
+
def forward(self, x: Variable):
|
13 |
+
y = []
|
14 |
+
for i in range(len(self.modules_list)):
|
15 |
+
y.append(self.modules_list[i](x))
|
16 |
+
return y
|
17 |
+
|
18 |
+
def add(self, module):
|
19 |
+
self.modules_list.append(module)
|
20 |
+
|
21 |
+
|
22 |
+
class CaddTable(nn.Module):
|
23 |
+
def __init__(self, inplace=False):
|
24 |
+
super(CaddTable, self).__init__()
|
25 |
+
self.inplace = inplace
|
26 |
+
|
27 |
+
def forward(self, x: Variable or list):
|
28 |
+
return torch.stack(x, 0).sum(0)
|
29 |
+
|
30 |
+
|
31 |
+
class Identity(nn.Module):
|
32 |
+
def __init__(self, params=None):
|
33 |
+
super(Identity, self).__init__()
|
34 |
+
self.params = nn.ParameterList(params)
|
35 |
+
|
36 |
+
def forward(self, x: Variable or list):
|
37 |
+
return x
|
joints_detectors/Alphapose/SPPE/src/opt.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import torch
|
3 |
+
|
4 |
+
parser = argparse.ArgumentParser(description='PyTorch AlphaPose Training')
|
5 |
+
|
6 |
+
"----------------------------- General options -----------------------------"
|
7 |
+
parser.add_argument('--expID', default='default', type=str,
|
8 |
+
help='Experiment ID')
|
9 |
+
parser.add_argument('--dataset', default='coco', type=str,
|
10 |
+
help='Dataset choice: mpii | coco')
|
11 |
+
parser.add_argument('--nThreads', default=30, type=int,
|
12 |
+
help='Number of data loading threads')
|
13 |
+
parser.add_argument('--debug', default=False, type=bool,
|
14 |
+
help='Print the debug information')
|
15 |
+
parser.add_argument('--snapshot', default=1, type=int,
|
16 |
+
help='How often to take a snapshot of the model (0 = never)')
|
17 |
+
|
18 |
+
"----------------------------- AlphaPose options -----------------------------"
|
19 |
+
parser.add_argument('--addDPG', default=False, type=bool,
|
20 |
+
help='Train with data augmentation')
|
21 |
+
|
22 |
+
"----------------------------- Model options -----------------------------"
|
23 |
+
parser.add_argument('--netType', default='hgPRM', type=str,
|
24 |
+
help='Options: hgPRM | resnext')
|
25 |
+
parser.add_argument('--loadModel', default=None, type=str,
|
26 |
+
help='Provide full path to a previously trained model')
|
27 |
+
parser.add_argument('--Continue', default=False, type=bool,
|
28 |
+
help='Pick up where an experiment left off')
|
29 |
+
parser.add_argument('--nFeats', default=256, type=int,
|
30 |
+
help='Number of features in the hourglass')
|
31 |
+
parser.add_argument('--nClasses', default=17, type=int,
|
32 |
+
help='Number of output channel')
|
33 |
+
parser.add_argument('--nStack', default=8, type=int,
|
34 |
+
help='Number of hourglasses to stack')
|
35 |
+
|
36 |
+
"----------------------------- Hyperparameter options -----------------------------"
|
37 |
+
parser.add_argument('--LR', default=2.5e-4, type=float,
|
38 |
+
help='Learning rate')
|
39 |
+
parser.add_argument('--momentum', default=0, type=float,
|
40 |
+
help='Momentum')
|
41 |
+
parser.add_argument('--weightDecay', default=0, type=float,
|
42 |
+
help='Weight decay')
|
43 |
+
parser.add_argument('--crit', default='MSE', type=str,
|
44 |
+
help='Criterion type')
|
45 |
+
parser.add_argument('--optMethod', default='rmsprop', type=str,
|
46 |
+
help='Optimization method: rmsprop | sgd | nag | adadelta')
|
47 |
+
|
48 |
+
|
49 |
+
"----------------------------- Training options -----------------------------"
|
50 |
+
parser.add_argument('--nEpochs', default=50, type=int,
|
51 |
+
help='Number of hourglasses to stack')
|
52 |
+
parser.add_argument('--epoch', default=0, type=int,
|
53 |
+
help='Current epoch')
|
54 |
+
parser.add_argument('--trainBatch', default=40, type=int,
|
55 |
+
help='Train-batch size')
|
56 |
+
parser.add_argument('--validBatch', default=20, type=int,
|
57 |
+
help='Valid-batch size')
|
58 |
+
parser.add_argument('--trainIters', default=0, type=int,
|
59 |
+
help='Total train iters')
|
60 |
+
parser.add_argument('--valIters', default=0, type=int,
|
61 |
+
help='Total valid iters')
|
62 |
+
parser.add_argument('--init', default=None, type=str,
|
63 |
+
help='Initialization')
|
64 |
+
"----------------------------- Data options -----------------------------"
|
65 |
+
parser.add_argument('--inputResH', default=384, type=int,
|
66 |
+
help='Input image height')
|
67 |
+
parser.add_argument('--inputResW', default=320, type=int,
|
68 |
+
help='Input image width')
|
69 |
+
parser.add_argument('--outputResH', default=96, type=int,
|
70 |
+
help='Output heatmap height')
|
71 |
+
parser.add_argument('--outputResW', default=80, type=int,
|
72 |
+
help='Output heatmap width')
|
73 |
+
parser.add_argument('--scale', default=0.25, type=float,
|
74 |
+
help='Degree of scale augmentation')
|
75 |
+
parser.add_argument('--rotate', default=30, type=float,
|
76 |
+
help='Degree of rotation augmentation')
|
77 |
+
parser.add_argument('--hmGauss', default=1, type=int,
|
78 |
+
help='Heatmap gaussian size')
|
79 |
+
|
80 |
+
"----------------------------- PyraNet options -----------------------------"
|
81 |
+
parser.add_argument('--baseWidth', default=9, type=int,
|
82 |
+
help='Heatmap gaussian size')
|
83 |
+
parser.add_argument('--cardinality', default=5, type=int,
|
84 |
+
help='Heatmap gaussian size')
|
85 |
+
parser.add_argument('--nResidual', default=1, type=int,
|
86 |
+
help='Number of residual modules at each location in the pyranet')
|
87 |
+
|
88 |
+
"----------------------------- Distribution options -----------------------------"
|
89 |
+
parser.add_argument('--dist', dest='dist', type=int, default=1,
|
90 |
+
help='distributed training or not')
|
91 |
+
parser.add_argument('--backend', dest='backend', type=str, default='gloo',
|
92 |
+
help='backend for distributed training')
|
93 |
+
parser.add_argument('--port', dest='port',
|
94 |
+
help='port of server')
|
95 |
+
|
96 |
+
|
97 |
+
opt = parser.parse_args()
|
98 |
+
if opt.Continue:
|
99 |
+
opt = torch.load("../exp/{}/{}/option.pkl".format(opt.dataset, opt.expID))
|
100 |
+
opt.Continue = True
|
101 |
+
opt.nEpochs = 50
|
102 |
+
print("--- Continue ---")
|
joints_detectors/Alphapose/SPPE/src/utils/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from . import *
|
joints_detectors/Alphapose/SPPE/src/utils/dataset/.coco.py.swp
ADDED
Binary file (4.1 kB). View file
|
|
joints_detectors/Alphapose/SPPE/src/utils/dataset/__init__.py
ADDED
File without changes
|
joints_detectors/Alphapose/SPPE/src/utils/dataset/coco.py
ADDED
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import h5py
|
3 |
+
from functools import reduce
|
4 |
+
|
5 |
+
import torch.utils.data as data
|
6 |
+
from ..pose import generateSampleBox
|
7 |
+
from opt import opt
|
8 |
+
|
9 |
+
|
10 |
+
class Mscoco(data.Dataset):
|
11 |
+
def __init__(self, train=True, sigma=1,
|
12 |
+
scale_factor=(0.2, 0.3), rot_factor=40, label_type='Gaussian'):
|
13 |
+
self.img_folder = '../data/coco/images' # root image folders
|
14 |
+
self.is_train = train # training set or test set
|
15 |
+
self.inputResH = opt.inputResH
|
16 |
+
self.inputResW = opt.inputResW
|
17 |
+
self.outputResH = opt.outputResH
|
18 |
+
self.outputResW = opt.outputResW
|
19 |
+
self.sigma = sigma
|
20 |
+
self.scale_factor = scale_factor
|
21 |
+
self.rot_factor = rot_factor
|
22 |
+
self.label_type = label_type
|
23 |
+
|
24 |
+
self.nJoints_coco = 17
|
25 |
+
self.nJoints_mpii = 16
|
26 |
+
self.nJoints = 33
|
27 |
+
|
28 |
+
self.accIdxs = (1, 2, 3, 4, 5, 6, 7, 8,
|
29 |
+
9, 10, 11, 12, 13, 14, 15, 16, 17)
|
30 |
+
self.flipRef = ((2, 3), (4, 5), (6, 7),
|
31 |
+
(8, 9), (10, 11), (12, 13),
|
32 |
+
(14, 15), (16, 17))
|
33 |
+
|
34 |
+
# create train/val split
|
35 |
+
with h5py.File('../data/coco/annot_clean.h5', 'r') as annot:
|
36 |
+
# train
|
37 |
+
self.imgname_coco_train = annot['imgname'][:-5887]
|
38 |
+
self.bndbox_coco_train = annot['bndbox'][:-5887]
|
39 |
+
self.part_coco_train = annot['part'][:-5887]
|
40 |
+
# val
|
41 |
+
self.imgname_coco_val = annot['imgname'][-5887:]
|
42 |
+
self.bndbox_coco_val = annot['bndbox'][-5887:]
|
43 |
+
self.part_coco_val = annot['part'][-5887:]
|
44 |
+
|
45 |
+
self.size_train = self.imgname_coco_train.shape[0]
|
46 |
+
self.size_val = self.imgname_coco_val.shape[0]
|
47 |
+
|
48 |
+
def __getitem__(self, index):
|
49 |
+
sf = self.scale_factor
|
50 |
+
|
51 |
+
if self.is_train:
|
52 |
+
part = self.part_coco_train[index]
|
53 |
+
bndbox = self.bndbox_coco_train[index]
|
54 |
+
imgname = self.imgname_coco_train[index]
|
55 |
+
else:
|
56 |
+
part = self.part_coco_val[index]
|
57 |
+
bndbox = self.bndbox_coco_val[index]
|
58 |
+
imgname = self.imgname_coco_val[index]
|
59 |
+
|
60 |
+
imgname = reduce(lambda x, y: x + y, map(lambda x: chr(int(x)), imgname))
|
61 |
+
img_path = os.path.join(self.img_folder, imgname)
|
62 |
+
|
63 |
+
metaData = generateSampleBox(img_path, bndbox, part, self.nJoints,
|
64 |
+
'coco', sf, self, train=self.is_train)
|
65 |
+
|
66 |
+
inp, out_bigcircle, out_smallcircle, out, setMask = metaData
|
67 |
+
|
68 |
+
label = []
|
69 |
+
for i in range(opt.nStack):
|
70 |
+
if i < 2:
|
71 |
+
# label.append(out_bigcircle.clone())
|
72 |
+
label.append(out.clone())
|
73 |
+
elif i < 4:
|
74 |
+
# label.append(out_smallcircle.clone())
|
75 |
+
label.append(out.clone())
|
76 |
+
else:
|
77 |
+
label.append(out.clone())
|
78 |
+
|
79 |
+
return inp, label, setMask, 'coco'
|
80 |
+
|
81 |
+
def __len__(self):
|
82 |
+
if self.is_train:
|
83 |
+
return self.size_train
|
84 |
+
else:
|
85 |
+
return self.size_val
|