Commit 0e6b7d37 authored by PUJADES ROCAMORA Sergi's avatar PUJADES ROCAMORA Sergi
Browse files

update readme + licence + add code

parent 288faa62
## Installation
Back to the main [README](README.md).
### Installing on a virtual environment
#### PyEnv
It is recommended to use a virtual environment to install this package - but not mandatory.
We recommend using [pyenv](https://github.com/pyenv/pyenv) and [pyenv-virtualenv](https://github.com/pyenv/pyenv-virtualenv).
The instructions are well detailed [here](https://realpython.com/intro-to-pyenv/#installing-pyenv).
Then go to the base repository folder and
```
pyenv install -v 2.7.16
pyenv virtualenv 2.7.16 spine_model
pyenv local spine_model
```
#### Other Requirements
Then install the basic requirements.txt
```
pip install -r requirements.txt
```
#### Mesh Package
Now install an **old** [PS Body Mesh package](https://github.com/MPI-IS/mesh) from the given
[precompiled sources](https://github.com/MPI-IS/mesh/releases/tag/v0.1):
Mac Osx:
```
pip install https://github.com/MPI-IS/mesh/releases/download/v0.1/psbody_mesh-0.1-cp27-cp27m-macosx_10_11_intel.whl
```
or Linux:
```
pip install https://github.com/MPI-IS/mesh/releases/download/v0.1/psbody_mesh-0.1-cp27-cp27mu-linux_x86_64.whl
```
#### SMPL load function
The last needed code is the SMPL load function (serialization).
To get it:
* [Register](https://smpl.is.tue.mpg.de)
* [Login](https://smpl.is.tue.mpg.de/en/sign_in)
* Download the "Download version 1.0.0 for Python 2.7 (10 shape PCs)"
* Copy the `smpl_webuser` folder into the `code` folder of the repository
That's it! You should be setup and ready to run the code!
Check out the [QuickStart](QuickStart.md) file.
\ No newline at end of file
Back to the main [README](README.md).
# Licence
The Spine Model is released under the
[CC BY-NC-SA 2.0](https://creativecommons.org/licenses/by-nc-sa/2.0/legalcode) licence.
It is derived data from the [Verse19 Challenge Dataset](https://verse2019.grand-challenge.org/Data/)
released under the [CC BY-SA 2.0]( https://creativecommons.org/licenses/by-sa/2.0/legalcode) licence.
The full text of the CC BY-NC-SA 2.0 licence is reproduced here.
---
License
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.
1. Definitions
"Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License.
"Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License.
"Licensor" means the individual or entity that offers the Work under the terms of this License.
"Original Author" means the individual or entity who created the Work.
"Work" means the copyrightable work of authorship offered under the terms of this License.
"You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
"License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, Noncommercial, ShareAlike.
2. Fair Use Rights. Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws.
3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:
to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works;
to create and reproduce Derivative Works;
to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works;
to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works;
The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved, including but not limited to the rights set forth in Sections 4(e) and 4(f).
4. Restrictions.The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:
You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any reference to such Licensor or the Original Author, as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any reference to such Licensor or the Original Author, as requested.
You may distribute, publicly display, publicly perform, or publicly digitally perform a Derivative Work only under the terms of this License, a later version of this License with the same License Elements as this License, or a Creative Commons iCommons license that contains the same License Elements as this License (e.g. Attribution-NonCommercial-ShareAlike 2.0 Japan). You must include a copy of, or the Uniform Resource Identifier for, this License or other license specified in the previous sentence with every copy or phonorecord of each Derivative Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Derivative Works that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder, and You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Derivative Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Derivative Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Derivative Work itself to be made subject to the terms of this License.
You may not exercise any of the rights granted to You in Section 3 above in any manner that is primarily intended for or directed toward commercial advantage or private monetary compensation. The exchange of the Work for other copyrighted works by means of digital file-sharing or otherwise shall not be considered to be intended for or directed toward commercial advantage or private monetary compensation, provided there is no payment of any monetary compensation in connection with the exchange of copyrighted works.
If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and give the Original Author credit reasonable to the medium or means You are utilizing by conveying the name (or pseudonym if applicable) of the Original Author if supplied; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit.
For the avoidance of doubt, where the Work is a musical composition:
Performance Royalties Under Blanket Licenses. Licensor reserves the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work if that performance is primarily intended for or directed toward commercial advantage or private monetary compensation.
Mechanical Rights and Statutory Royalties. Licensor reserves the exclusive right to collect, whether individually or via a music rights agency or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions), if Your distribution of such cover version is primarily intended for or directed toward commercial advantage or private monetary compensation.
Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor reserves the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions), if Your public digital performance is primarily intended for or directed toward commercial advantage or private monetary compensation.
5. Representations, Warranties and Disclaimer
UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
7. Termination
This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.
8. Miscellaneous
Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent.
This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.
# Quick Start Guide
Please make sure you followed the [Install](Install.md) instructions.
Then come back to run the demo.
Back to the main [README](README.md).
## Running the Spine Model demo
To run the demo code, go to the code folder:
```
cd code
```
Then, for the Global rotation demo run:
```
python spine_model_demo.py -R
```
The full demo includes the global and local rotations, the shape space,
the individual joint locations and all joints at the same time.
```
python spine_model_demo.py -R -r -B -I -J
```
## Running the reconstruction demo
The model can also reconstruct a full spine from a partially observed spine.
In this demo we progressively mask the cervicals and reconstruct them.
Test first that the reconstruction with the PPCA mean works.
Reconstructions should be perfect (zero error)
```
python spine_completion_demo.py -M
```
Then you can test reconstructions from the model.
```
python spine_completion_demo.py
```
You can modify the beta parameter (line 204) of the model to obtain
different meshes and reconstruction settings.
\ No newline at end of file
......@@ -4,7 +4,7 @@ Welcome to the repository containing the spine statistical model learned from in
at the ShapeMi 2020 MICCAI Workshop.
# Mailing list and Contact
# Contact and Mailing list
If you are interested in the model and want to be updated with news,
please subscribe to the spine_model@inria.fr mailing list.
......@@ -15,6 +15,18 @@ For any questions related to the paper and the model release, please contact
[Di Meng](mailto:di.meng@inria.fr) or [Sergi Pujades](mailto:sergi.pujades-rocamora@inria.fr).
# Model Licence
The Spine Model is released under the
[CC BY-NC-SA 2.0](https://creativecommons.org/licenses/by-nc-sa/2.0/legalcode) licence.
Please check the [Licence](Licence.md) page with the full licence text.
# Model Release
We provide [Install](Install.md) instructions and a [QuickStart](QuickStart.md) guide to
learn how to use the model and reconstruct a full spine from partial data.
# Citing the work
......
#
# Derived work Spine Model, Di Meng, Marilyn Keller, Edmond Boyer, Michael J. Black, Sergi Pujades,
# Copyright © Inria and Max Planck Institute, CC BY-NC v2.0 license, 2019-2020 v1.0
# Based on Verse19 Challenge Dataset, Jan S. Kirschke, Anjany Sekuboyina, Maximilian Löffler , CC BY v2.0 license, 2019-2020 v3
#
def proj_ppca(Y, M, C, nb_latent=10):
'''
Y is input with missing data
M, C are the ppca values :
M : Mean
C : the reconstruction matrix
'''
from numpy import shape, isnan
from numpy import matmul as mm
from numpy.linalg import inv
assert(nb_latent == 10)
N = shape(Y)[0]
hidden = isnan(Y)
missing = hidden.sum()
print("\tReconstruction from {0:.2f}% missing data".format(100. * missing / N))
Ye = Y - M
Ye[hidden] = 0
CtC = mm(C.T, C)
X = mm(mm(Ye, C), inv(CtC))
X[nb_latent:] = 0
proj = mm(X, C.T)
Ye[hidden] = proj[hidden]
return Ye + M
def Y_from_model_mesh(m, M, v_smpl, v_smpl_metadata):
''' This function converts "the vertices of a model mesh" into the "ppca representation"
which includes the local translations.
The difference between them is:
- the computation of the local translations from the vertebrae centers
- the "rigid" registration to the mean positions (as the translation is already factored out)
-> the ppca was computed with the individual vertebrae unposed to the template shape
@param: m: a mesh given by the model (v_smpl.r, v_smpl.f)
@param: M: the mean of the ppca
extracts the individual vertebrae
and the translation between them
translates the vertebrae vertices to be in the same center as the mean vertebrae
constructs the Y matrix to be used in the reconstruction process
'''
from psbody.mesh import Mesh
from spine_model_utils import get_bone_mesh, get_bone_joint, get_translation_index
# Create the Y matrix: first the mesh vertices
import numpy as np
# Allocate the Y vector
Y = np.zeros_like(M)
bone_id_list = v_smpl_metadata['bone_id_list']
mesh_joints = dict()
for bone_id in bone_id_list:
v_start, v_end = v_smpl_metadata[bone_id]['indices']
mesh_verts = m.v[v_start:v_end]
mesh_joint = get_bone_joint(v_smpl.J_regressor,
v_smpl_metadata,
bone_id, Mesh(v=mesh_verts, f=[]))
ppca_verts = M[3*v_start:3*v_end].reshape(-1, 3)
ppca_joint = get_bone_joint(v_smpl.J_regressor,
v_smpl_metadata,
bone_id, Mesh(v=ppca_verts, f=[]))
offset = ppca_joint - mesh_joint
new_verts = mesh_verts + offset
Y[3*v_start:3*v_end] = new_verts.ravel()
mesh_joints[bone_id] = mesh_joint
# Then the local translations
# The are computed using the joint locations from one vertebra and the consecutive "above"
# L4 to L5, L4 to L3 and so on until C1 to C2
for c_bone_id in bone_id_list:
if c_bone_id == 1:
# C1 does not have a translation
continue
trans = mesh_joints[c_bone_id - 1] - mesh_joints[c_bone_id]
trans_index = get_translation_index(c_bone_id)
Y[trans_index:trans_index+3] = trans
return Y
def cervical_reconstruction_example(Y, v_smpl_metadata,
M, C):
import numpy as np
from spine_model_utils import get_translation_index
nb_bones = 5
for nb_bone_excluded in range(1, nb_bones+1):
print ("Excluding {} vertebrae".format(nb_bone_excluded))
Y_masked = Y.copy()
for excluded_bone_id in range(1, nb_bone_excluded+1):
# Mask mesh
v_start, v_end = v_smpl_metadata[excluded_bone_id]['indices']
# these indices refer to the vertices, each one is 3D
# In Y the coordinates are flattened, so we multiply the indices by 3
Y_start = v_start * 3
Y_end = v_end * 3
Y_masked[Y_start:Y_end] = np.nan
# Mask local translation - which is associated with the next bone_id
trans_index = get_translation_index(excluded_bone_id + 1)
Y_masked[trans_index:trans_index+3] = np.nan
# Complete the masked spine data using the ppca model (M, C,X)
Y_pred = proj_ppca(Y_masked, M, C)
# Get the original vertices and the predicted ones
for excluded_bone_id in range(1, nb_bone_excluded + 1):
v_start, v_end = v_smpl_metadata[excluded_bone_id]['indices']
Y_start = v_start * 3
Y_end = v_end * 3
# Get first "element"
orig_data = Y[Y_start:Y_end]
pred_data = Y_pred[Y_start:Y_end]
# Compare the ground truth test_vol spine and the extrapolated one
imputation_abs_err_norm = np.linalg.norm(orig_data.reshape(-1, 3) - pred_data.reshape(-1, 3), axis=1)
trans_index = get_translation_index(excluded_bone_id + 1)
orig_trans = Y[trans_index:trans_index+3]
pred_trans = Y_pred[trans_index:trans_index + 3]
imputation_abs_err_trans = np.linalg.norm(orig_trans.reshape(-1, 3) - pred_trans.reshape(-1, 3), axis=1)[0]
# Show some statistics
print("\tExcluded Bone {} Inputation Error Norm:".format(excluded_bone_id))
print("\tMax Shape Error in mm: {0:.2f}".format(np.max(imputation_abs_err_norm) * 1000))
print("\tMean Shape Error in mm: {0:.2f}".format(np.mean(imputation_abs_err_norm) * 1000))
print("\tTrans Error in mm: {0:.2f}".format(imputation_abs_err_trans * 1000))
print("")
return
if __name__ == '__main__':
from smpl_webuser.serialization import load_model
from psbody.mesh import Mesh
from spine_model_utils import current_model_filename, load_model_metadata, load_ppca_metadata
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-M", "--mean_check", action='store_true', help="Demo that starting with the mean all errors are zero")
args = parser.parse_args()
print "Reconstruction Demo"
print "Loading models and metadata ... "
v_smpl_metadata = load_model_metadata()
ppca_metadata = load_ppca_metadata()
M = ppca_metadata['M_pp']
C = ppca_metadata['C']
print "\tLoading done"
if args.mean_check:
# Use the mean of the ppca as the starting point
# Predictions will be perfect
Y = M.copy()
print "Using the PPCA mean: predictions should be perfect (zero error)."
else:
print "Using the Mean Model mesh: predictions should have small errors (approx 0.1 mm max, 0.05-0.07 mm mean)."
model_filename = current_model_filename
v_smpl = load_model(model_filename)
# Example with betas
v_smpl.betas[0] = 0
# Create mean mesh
m = Mesh(v=v_smpl.r, f=v_smpl.f)
Y = Y_from_model_mesh(m, M, v_smpl, v_smpl_metadata)
cervical_reconstruction_example(Y, v_smpl_metadata,
M, C)
#
# Derived work Spine Model, Di Meng, Marilyn Keller, Edmond Boyer, Michael J. Black, Sergi Pujades,
# Copyright © Inria and Max Planck Institute, CC BY-NC v2.0 license, 2019-2020 v1.0
# Based on Verse19 Challenge Dataset, Jan S. Kirschke, Anjany Sekuboyina, Maximilian Löffler , CC BY v2.0 license, 2019-2020 v3
#
def _create_cage(vs, radius=1e-2):
''' Given an array of 3d vertices, it creates a *cage* containing all given vertices inside.
The output are a set of spheres with the "corners" of the bounding box of the points.
:param vs: an array of 3d points
:returns: an array of eight spheres, creating a *cage*
'''
from itertools import product
from numpy import asarray
from psbody.mesh.sphere import Sphere
return([Sphere(asarray(corner), radius=radius).to_mesh()
for corner in product(*zip(vs.min(axis=0), vs.max(axis=0)))])
def _create_cage_from_meshes(meshes, radius=1e-2):
''' Given an iterable with meshes, their vertices are concatenated
and a cage is created using :func:`create_cage`.
:param meshes: an iterable with meshes
:type meshes: Mesh
:returns: an array of eight spheres, creating a *cage*
.. seealso:: :func:`create_cage`
'''
from numpy import zeros, vstack
cage_v = zeros([0, 3])
for m in meshes:
cage_v = vstack((cage_v, m.v))
return _create_cage(cage_v, radius=radius)
def create_cage(model):
from psbody.mesh import Mesh
model.betas[0] = 3
m1 = Mesh(v=v_smpl.r, f=v_smpl.f)
model.betas[0] = 0
model.trans[0] = 0.25
m2 = Mesh(v=v_smpl.r, f=v_smpl.f)
model.trans[0] = -0.25
m3 = Mesh(v=v_smpl.r, f=v_smpl.f)
model.trans[0] = 0
return _create_cage_from_meshes([m1, m2, m3], radius=0.0005)
def spheres_from_joints(model):
from psbody.mesh.sphere import Sphere
from numpy import asarray
from verse_colors import vertebrae_colormap
radius = 0.02
spheres = []
for i, center in enumerate(model.J.r):
sphere = Sphere(asarray(center), radius=radius).to_mesh()
sphere.set_vertex_colors(vertebrae_colormap(24- i))
spheres.append(sphere)
return spheres
if __name__ == '__main__':
from smpl_webuser.serialization import load_model
from psbody.mesh import Mesh, MeshViewer
from psbody.mesh.colors import name_to_rgb
from psbody.mesh.sphere import Sphere
import numpy as np
from time import sleep
from spine_model_utils import current_model_filename, load_model_metadata,\
get_bone_mesh, get_bone_joint, rotate
from verse_colors import vertebrae_colormap
# Parser for the input options
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-R", "--global_rot", action='store_true', help="Demos global rotation parameter")
parser.add_argument("-r", "--local_rot", action='store_true', help="Demos local rotation parameter")
parser.add_argument("-B", "--shape_space", action='store_true', help="Demos shape space parameter")
parser.add_argument("-I", "--individual_joints", action='store_true', help="Demos individual joint centers")
parser.add_argument("-J", "--jointlocation", action='store_true', help="Demos all joint centers")
args = parser.parse_args()
#
model_filename = current_model_filename
model_version = model_filename[-6: -4]
v_smpl_metadata = load_model_metadata()
show_global_rot = args.global_rot
show_local_rot = args.local_rot
show_shape_space = args.shape_space
show_individual_joints = args.individual_joints
show_jointlocation = args.jointlocation
print "Demoing model ", model_version, "(", model_filename, ")"
v_smpl = load_model(model_filename)
mv = MeshViewer()
m = Mesh(v=v_smpl.r, f=v_smpl.f)
mv.static_meshes = create_cage(v_smpl)
mv.set_dynamic_meshes([m])
mv.set_background_color(np.array([0.75, 0.75, 0.75]))
sleep(0.5)
sleep_time = 0.3
radius = 0.02
camera_orientations = {
'front': [0, 0, 0],
'side': [0., np.pi / 2, 0.]
}
bone_id_list = v_smpl_metadata['bone_id_list']
if show_global_rot:
# rotate global around y
for y_angle in np.linspace(0, 2 * np.pi, num=int(360/20)):
v_smpl.pose[1] = y_angle
m.v = v_smpl.r
mv.set_dynamic_meshes([m])
sleep(sleep_time)
v_smpl.pose[1] = 0
if show_local_rot:
# rotate around y axis the different parts
for i in range(4, v_smpl.pose.shape[0], 3):
for angle in np.linspace(0, 2 * np.pi, num=int(360/45)):
v_smpl.pose[i] = angle
m.v = v_smpl.r
mv.set_dynamic_meshes([m])
sleep(sleep_time)
v_smpl.pose[i] = 0
# Display the shape space
if show_shape_space:
colors = ['bisque', 'lavender', 'honeydew', 'gray', 'seashell']
# Demo 5 betas
nb_betas = 5
for orientation in camera_orientations:
for i in range(nb_betas):
mv.set_background_color(name_to_rgb[colors[i % len(colors)]])
for offset in np.linspace(0, 2, num=6):
v_smpl.betas[i] = offset
m.v = v_smpl.r
m.v = rotate(m.v, camera_orientations[orientation])
mv.set_dynamic_meshes([m])
sleep(sleep_time)
for offset in reversed(list(np.linspace(-2, 2, num=10))):
v_smpl.betas[i] = offset
m.v = v_smpl.r
m.v = rotate(m.v, camera_orientations[orientation])
mv.set_dynamic_meshes([m])
sleep(sleep_time)
v_smpl.betas[i] = 0