├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── assets ├── comparison_with_mano.jpg ├── each_component.jpg └── teaser.png ├── common ├── __pycache__ │ ├── base.cpython-38.pyc │ ├── logger.cpython-38.pyc │ └── timer.cpython-38.pyc ├── base.py ├── logger.py ├── nets │ ├── DiffableRenderer │ │ ├── DiffableRenderer.py │ │ └── __pycache__ │ │ │ └── DiffableRenderer.cpython-38.pyc │ ├── __pycache__ │ │ ├── layer.cpython-38.pyc │ │ ├── loss.cpython-38.pyc │ │ ├── module.cpython-38.pyc │ │ └── resnet.cpython-38.pyc │ ├── layer.py │ ├── loss.py │ ├── module.py │ └── resnet.py ├── timer.py └── utils │ ├── __init__.py │ ├── __pycache__ │ ├── __init__.cpython-38.pyc │ ├── dir.cpython-38.pyc │ ├── mesh.cpython-38.pyc │ ├── preprocessing.cpython-38.pyc │ ├── transforms.cpython-38.pyc │ └── vis.cpython-38.pyc │ ├── dir.py │ ├── mesh.py │ ├── preprocessing.py │ ├── transforms.py │ └── vis.py ├── data ├── __pycache__ │ └── dataset.cpython-38.pyc └── dataset.py ├── demo └── demo.py ├── main ├── __pycache__ │ ├── config.cpython-38.pyc │ └── model.cpython-38.pyc ├── config.py ├── model.py ├── test.py └── train.py └── tool ├── download_3d_scans_decimated.py ├── download_depthmaps.py ├── download_images.py └── download_others.py /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | Jan 05 2021 2 | 3 | ## Initial Release 4 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to make participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies within all project spaces, and it also applies when 49 | an individual is representing the project or its community in public spaces. 50 | Examples of representing a project or community include using an official 51 | project e-mail address, posting via an official social media account, or acting 52 | as an appointed representative at an online or offline event. Representation of 53 | a project may be further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at . All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to DeepHandMesh 2 | We want to make contributing to this project as easy and transparent as 3 | possible. 4 | 5 | ## Pull Requests 6 | We actively welcome your pull requests. 7 | 8 | 1. Fork the repo and create your branch from `master`. 9 | 2. If you've added code that should be tested, add tests. 10 | 3. If you've changed APIs, update the documentation. 11 | 4. Ensure the test suite passes. 12 | 5. Make sure your code lints. 13 | 6. If you haven't already, complete the Contributor License Agreement ("CLA"). 14 | 15 | ## Contributor License Agreement ("CLA") 16 | In order to accept your pull request, we need you to submit a CLA. You only need 17 | to do this once to work on any of Facebook's open source projects. 18 | 19 | Complete your CLA here: 20 | 21 | ## Issues 22 | We use GitHub issues to track public bugs. Please ensure your description is 23 | clear and has sufficient instructions to be able to reproduce the issue. 24 | 25 | Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe 26 | disclosure of security bugs. In those cases, please go through the process 27 | outlined on that page and do not file a public issue. 28 | 29 | ## License 30 | By contributing to DeepHandMesh, you agree that your contributions will be licensed 31 | under the LICENSE file in the root directory of this source tree. 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | Section 1 -- Definitions. 71 | 72 | a. Adapted Material means material subject to Copyright and Similar 73 | Rights that is derived from or based upon the Licensed Material 74 | and in which the Licensed Material is translated, altered, 75 | arranged, transformed, or otherwise modified in a manner requiring 76 | permission under the Copyright and Similar Rights held by the 77 | Licensor. For purposes of this Public License, where the Licensed 78 | Material is a musical work, performance, or sound recording, 79 | Adapted Material is always produced where the Licensed Material is 80 | synched in timed relation with a moving image. 81 | 82 | b. Adapter's License means the license You apply to Your Copyright 83 | and Similar Rights in Your contributions to Adapted Material in 84 | accordance with the terms and conditions of this Public License. 85 | 86 | c. Copyright and Similar Rights means copyright and/or similar rights 87 | closely related to copyright including, without limitation, 88 | performance, broadcast, sound recording, and Sui Generis Database 89 | Rights, without regard to how the rights are labeled or 90 | categorized. For purposes of this Public License, the rights 91 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 92 | Rights. 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. NonCommercial means not primarily intended for or directed towards 116 | commercial advantage or monetary compensation. For purposes of 117 | this Public License, the exchange of the Licensed Material for 118 | other material subject to Copyright and Similar Rights by digital 119 | file-sharing or similar means is NonCommercial provided there is 120 | no payment of monetary compensation in connection with the 121 | exchange. 122 | 123 | j. Share means to provide material to the public by any means or 124 | process that requires permission under the Licensed Rights, such 125 | as reproduction, public display, public performance, distribution, 126 | dissemination, communication, or importation, and to make material 127 | available to the public including in ways that members of the 128 | public may access the material from a place and at a time 129 | individually chosen by them. 130 | 131 | k. Sui Generis Database Rights means rights other than copyright 132 | resulting from Directive 96/9/EC of the European Parliament and of 133 | the Council of 11 March 1996 on the legal protection of databases, 134 | as amended and/or succeeded, as well as other essentially 135 | equivalent rights anywhere in the world. 136 | 137 | l. You means the individual or entity exercising the Licensed Rights 138 | under this Public License. Your has a corresponding meaning. 139 | 140 | Section 2 -- Scope. 141 | 142 | a. License grant. 143 | 144 | 1. Subject to the terms and conditions of this Public License, 145 | the Licensor hereby grants You a worldwide, royalty-free, 146 | non-sublicensable, non-exclusive, irrevocable license to 147 | exercise the Licensed Rights in the Licensed Material to: 148 | 149 | a. reproduce and Share the Licensed Material, in whole or 150 | in part, for NonCommercial purposes only; and 151 | 152 | b. produce, reproduce, and Share Adapted Material for 153 | NonCommercial purposes only. 154 | 155 | 2. Exceptions and Limitations. For the avoidance of doubt, where 156 | Exceptions and Limitations apply to Your use, this Public 157 | License does not apply, and You do not need to comply with 158 | its terms and conditions. 159 | 160 | 3. Term. The term of this Public License is specified in Section 161 | 6(a). 162 | 163 | 4. Media and formats; technical modifications allowed. The 164 | Licensor authorizes You to exercise the Licensed Rights in 165 | all media and formats whether now known or hereafter created, 166 | and to make technical modifications necessary to do so. The 167 | Licensor waives and/or agrees not to assert any right or 168 | authority to forbid You from making technical modifications 169 | necessary to exercise the Licensed Rights, including 170 | technical modifications necessary to circumvent Effective 171 | Technological Measures. For purposes of this Public License, 172 | simply making modifications authorized by this Section 2(a) 173 | (4) never produces Adapted Material. 174 | 175 | 5. Downstream recipients. 176 | 177 | a. Offer from the Licensor -- Licensed Material. Every 178 | recipient of the Licensed Material automatically 179 | receives an offer from the Licensor to exercise the 180 | Licensed Rights under the terms and conditions of this 181 | Public License. 182 | 183 | b. No downstream restrictions. You may not offer or impose 184 | any additional or different terms or conditions on, or 185 | apply any Effective Technological Measures to, the 186 | Licensed Material if doing so restricts exercise of the 187 | Licensed Rights by any recipient of the Licensed 188 | Material. 189 | 190 | 6. No endorsement. Nothing in this Public License constitutes or 191 | may be construed as permission to assert or imply that You 192 | are, or that Your use of the Licensed Material is, connected 193 | with, or sponsored, endorsed, or granted official status by, 194 | the Licensor or others designated to receive attribution as 195 | provided in Section 3(a)(1)(A)(i). 196 | 197 | b. Other rights. 198 | 199 | 1. Moral rights, such as the right of integrity, are not 200 | licensed under this Public License, nor are publicity, 201 | privacy, and/or other similar personality rights; however, to 202 | the extent possible, the Licensor waives and/or agrees not to 203 | assert any such rights held by the Licensor to the limited 204 | extent necessary to allow You to exercise the Licensed 205 | Rights, but not otherwise. 206 | 207 | 2. Patent and trademark rights are not licensed under this 208 | Public License. 209 | 210 | 3. To the extent possible, the Licensor waives any right to 211 | collect royalties from You for the exercise of the Licensed 212 | Rights, whether directly or through a collecting society 213 | under any voluntary or waivable statutory or compulsory 214 | licensing scheme. In all other cases the Licensor expressly 215 | reserves any right to collect such royalties, including when 216 | the Licensed Material is used other than for NonCommercial 217 | purposes. 218 | 219 | Section 3 -- License Conditions. 220 | 221 | Your exercise of the Licensed Rights is expressly made subject to the 222 | following conditions. 223 | 224 | a. Attribution. 225 | 226 | 1. If You Share the Licensed Material (including in modified 227 | form), You must: 228 | 229 | a. retain the following if it is supplied by the Licensor 230 | with the Licensed Material: 231 | 232 | i. identification of the creator(s) of the Licensed 233 | Material and any others designated to receive 234 | attribution, in any reasonable manner requested by 235 | the Licensor (including by pseudonym if 236 | designated); 237 | 238 | ii. a copyright notice; 239 | 240 | iii. a notice that refers to this Public License; 241 | 242 | iv. a notice that refers to the disclaimer of 243 | warranties; 244 | 245 | v. a URI or hyperlink to the Licensed Material to the 246 | extent reasonably practicable; 247 | 248 | b. indicate if You modified the Licensed Material and 249 | retain an indication of any previous modifications; and 250 | 251 | c. indicate the Licensed Material is licensed under this 252 | Public License, and include the text of, or the URI or 253 | hyperlink to, this Public License. 254 | 255 | 2. You may satisfy the conditions in Section 3(a)(1) in any 256 | reasonable manner based on the medium, means, and context in 257 | which You Share the Licensed Material. For example, it may be 258 | reasonable to satisfy the conditions by providing a URI or 259 | hyperlink to a resource that includes the required 260 | information. 261 | 262 | 3. If requested by the Licensor, You must remove any of the 263 | information required by Section 3(a)(1)(A) to the extent 264 | reasonably practicable. 265 | 266 | 4. If You Share Adapted Material You produce, the Adapter's 267 | License You apply must not prevent recipients of the Adapted 268 | Material from complying with this Public License. 269 | 270 | Section 4 -- Sui Generis Database Rights. 271 | 272 | Where the Licensed Rights include Sui Generis Database Rights that 273 | apply to Your use of the Licensed Material: 274 | 275 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 276 | to extract, reuse, reproduce, and Share all or a substantial 277 | portion of the contents of the database for NonCommercial purposes 278 | only; 279 | 280 | b. if You include all or a substantial portion of the database 281 | contents in a database in which You have Sui Generis Database 282 | Rights, then the database in which You have Sui Generis Database 283 | Rights (but not its individual contents) is Adapted Material; and 284 | 285 | c. You must comply with the conditions in Section 3(a) if You Share 286 | all or a substantial portion of the contents of the database. 287 | 288 | For the avoidance of doubt, this Section 4 supplements and does not 289 | replace Your obligations under this Public License where the Licensed 290 | Rights include other Copyright and Similar Rights. 291 | 292 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 293 | 294 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 295 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 296 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 297 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 298 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 299 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 300 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 301 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 302 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 303 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 304 | 305 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 306 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 307 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 308 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 309 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 310 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 311 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 312 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 313 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 314 | 315 | c. The disclaimer of warranties and limitation of liability provided 316 | above shall be interpreted in a manner that, to the extent 317 | possible, most closely approximates an absolute disclaimer and 318 | waiver of all liability. 319 | 320 | Section 6 -- Term and Termination. 321 | 322 | a. This Public License applies for the term of the Copyright and 323 | Similar Rights licensed here. However, if You fail to comply with 324 | this Public License, then Your rights under this Public License 325 | terminate automatically. 326 | 327 | b. Where Your right to use the Licensed Material has terminated under 328 | Section 6(a), it reinstates: 329 | 330 | 1. automatically as of the date the violation is cured, provided 331 | it is cured within 30 days of Your discovery of the 332 | violation; or 333 | 334 | 2. upon express reinstatement by the Licensor. 335 | 336 | For the avoidance of doubt, this Section 6(b) does not affect any 337 | right the Licensor may have to seek remedies for Your violations 338 | of this Public License. 339 | 340 | c. For the avoidance of doubt, the Licensor may also offer the 341 | Licensed Material under separate terms or conditions or stop 342 | distributing the Licensed Material at any time; however, doing so 343 | will not terminate this Public License. 344 | 345 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 346 | License. 347 | 348 | Section 7 -- Other Terms and Conditions. 349 | 350 | a. The Licensor shall not be bound by any additional or different 351 | terms or conditions communicated by You unless expressly agreed. 352 | 353 | b. Any arrangements, understandings, or agreements regarding the 354 | Licensed Material not stated herein are separate from and 355 | independent of the terms and conditions of this Public License. 356 | 357 | Section 8 -- Interpretation. 358 | 359 | a. For the avoidance of doubt, this Public License does not, and 360 | shall not be interpreted to, reduce, limit, restrict, or impose 361 | conditions on any use of the Licensed Material that could lawfully 362 | be made without permission under this Public License. 363 | 364 | b. To the extent possible, if any provision of this Public License is 365 | deemed unenforceable, it shall be automatically reformed to the 366 | minimum extent necessary to make it enforceable. If the provision 367 | cannot be reformed, it shall be severed from this Public License 368 | without affecting the enforceability of the remaining terms and 369 | conditions. 370 | 371 | c. No term or condition of this Public License will be waived and no 372 | failure to comply consented to unless expressly agreed to by the 373 | Licensor. 374 | 375 | d. Nothing in this Public License constitutes or may be interpreted 376 | as a limitation upon, or waiver of, any privileges and immunities 377 | that apply to the Licensor or You, including from the legal 378 | processes of any jurisdiction or authority. 379 | 380 | ======================================================================= 381 | 382 | Creative Commons is not a party to its public 383 | licenses. Notwithstanding, Creative Commons may elect to apply one of 384 | its public licenses to material it publishes and in those instances 385 | will be considered the “Licensor.” The text of the Creative Commons 386 | public licenses is dedicated to the public domain under the CC0 Public 387 | Domain Dedication. Except for the limited purpose of indicating that 388 | material is shared under a Creative Commons public license or as 389 | otherwise permitted by the Creative Commons policies published at 390 | creativecommons.org/policies, Creative Commons does not authorize the 391 | use of the trademark "Creative Commons" or any other trademark or logo 392 | of Creative Commons without its prior written consent including, 393 | without limitation, in connection with any unauthorized modifications 394 | to any of its public licenses or any other arrangements, 395 | understandings, or agreements concerning use of licensed material. For 396 | the avoidance of doubt, this paragraph does not form part of the 397 | public licenses. 398 | 399 | Creative Commons may be contacted at creativecommons.org. 400 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DeepHandMesh: A Weakly-Supervised Deep Encoder-Decoder Framework for High-Fidelity Hand Mesh Modeling 2 | 3 |

4 | 5 |

6 | 7 | ## Introduction 8 | This repo is official **[PyTorch](https://pytorch.org)** implementation of **[DeepHandMesh: A Weakly-Supervised Deep Encoder-Decoder Framework for High-Fidelity Hand Mesh Modeling (ECCV 2020. Oral.)](https://arxiv.org/abs/2008.08213)**. 9 | 10 | ## Demo 11 | * Download pre-trained DeepHandMesh from [here](https://drive.google.com/drive/folders/1bNq3syXTnzEs2jTGBANzv3sDi7Cpp46S?usp=sharing). 12 | * Place the downloaded file at `demo/subject_${SUBJECT_IDX}` folder, where the filename is `snapshot_${EPOCH}.pth.tar`. 13 | * Download hand model from [here](https://drive.google.com/file/d/1LjQ-rbWrXj1lcp2we00hMJdeMwMLIXus/view?usp=sharing) and place it at `data` folder. 14 | * Set hand joint Euler angles at [here](https://github.com/facebookresearch/DeepHandMesh/blob/508119e288ef35d4160043e5d3d174d2bf0d1873/demo/demo.py#L73). 15 | * Run `python demo.py --gpu 0 --subject ${SUBJECT_IDX} --test_epoch ${EPOCH}`. 16 | 17 | ## DeepHandMesh dataset 18 | * For the **DeepHandMesh dataset download and instructions**, go to [[HOMEPAGE](https://mks0601.github.io/DeepHandMesh/)]. 19 | * Belows are instructions for DeepHandMesh for the weakly-supervised high-fidelity 3D hand mesh modeling. 20 | 21 | ## Directory 22 | ### Root 23 | The `${ROOT}` is described as below. 24 | ``` 25 | ${ROOT} 26 | |-- data 27 | |-- common 28 | |-- main 29 | |-- output 30 | |-- demo 31 | ``` 32 | * `data` contains data loading codes and soft links to images and annotations directories. 33 | * `common` contains kernel codes. 34 | * `main` contains high-level codes for training or testing the network. 35 | * `output` contains log, trained models, visualized outputs, and test result. 36 | * `demo` contains demo codes. 37 | 38 | ### Data 39 | You need to follow directory structure of the `data` as below. 40 | ``` 41 | ${ROOT} 42 | |-- data 43 | | |-- images 44 | | | |-- subject_1 45 | | | |-- subject_2 46 | | | |-- subject_3 47 | | | |-- subject_4 48 | | |-- annotations 49 | | | |-- 3D_scans_decimated 50 | | | | |-- subject_4 51 | | | |-- depthmaps 52 | | | | |-- subject_4 53 | | | |-- keypoints 54 | | | | |-- subject_4 55 | | | |-- KRT_512 56 | | |-- hand_model 57 | | | |-- global_pose.txt 58 | | | |-- global_pose_inv.txt 59 | | | |-- hand.fbx 60 | | | |-- hand.obj 61 | | | |-- local_pose.txt 62 | | | |-- skeleton.txt 63 | | | |-- skinning_weight.txt 64 | ``` 65 | * Download datasets and hand model from [[HOMEPAGE](https://mks0601.github.io/DeepHandMesh/)]. 66 | 67 | ### Output 68 | You need to follow the directory structure of the `output` folder as below. 69 | ``` 70 | ${ROOT} 71 | |-- output 72 | | |-- log 73 | | |-- model_dump 74 | | |-- result 75 | | |-- vis 76 | ``` 77 | * `log` folder contains training log file. 78 | * `model_dump` folder contains saved checkpoints for each epoch. 79 | * `result` folder contains final estimation files generated in the testing stage. 80 | * `vis` folder contains visualized results. 81 | 82 | ## Running DeepHandMesh 83 | ### Prerequisites 84 | * For the training, install neural renderer from [here](https://github.com/daniilidis-group/neural_renderer). 85 | * After the install, uncomment line 12 of `main/model.py` (`from nets.DiffableRenderer.DiffableRenderer import RenderLayer`) and line 40 of `main/model.py` (`self.renderer = RenderLayer()`). 86 | * If you want only testing, you do not have to install it. 87 | 88 | ### Start 89 | * In the `main/config.py`, you can change settings of the model 90 | 91 | ### Train 92 | In the `main` folder, run 93 | ```bash 94 | python train.py --gpu 0-3 --subject 4 95 | ``` 96 | to train the network on the GPU 0,1,2,3. `--gpu 0,1,2,3` can be used instead of `--gpu 0-3`. You can use `--continue` to resume the training. 97 | Only subject 4 is supported for the training. 98 | 99 | 100 | ### Test 101 | Place trained model at the `output/model_dump/subject_${SUBJECT_IDX}`. 102 | 103 | In the `main` folder, run 104 | ```bash 105 | python test.py --gpu 0-3 --test_epoch 4 --subject 4 106 | ``` 107 | to test the network on the GPU 0,1,2,3 with `snapshot_4.pth.tar`. `--gpu 0,1,2,3` can be used instead of `--gpu 0-3`. 108 | Only subject 4 is supported for the testing. 109 | It will save images and output meshes. 110 | 111 | ## Results 112 | Here I report results of DeepHandMesh and pre-trained DeepHandMesh. 113 | 114 | ### Pre-trained DeepHandMesh 115 | * Pre-trained DeepHandMesh [[Download](https://drive.google.com/drive/folders/1bNq3syXTnzEs2jTGBANzv3sDi7Cpp46S?usp=sharing)] 116 | 117 | ### Effect of Identity- and Pose-Dependent Correctives 118 |

119 | 120 |

121 | 122 | ### Comparison with MANO 123 |

124 | 125 |

126 | 127 | ## Reference 128 | ``` 129 | @InProceedings{Moon_2020_ECCV_DeepHandMesh, 130 | author = {Moon, Gyeongsik and Shiratori, Takaaki and Lee, Kyoung Mu}, 131 | title = {DeepHandMesh: A Weakly-supervised Deep Encoder-Decoder Framework for High-fidelity Hand Mesh Modeling}, 132 | booktitle = {European Conference on Computer Vision (ECCV)}, 133 | year = {2020} 134 | } 135 | ``` 136 | 137 | ## License 138 | DeepHandMesh is CC-BY-NC 4.0 licensed, as found in the LICENSE file. 139 | -------------------------------------------------------------------------------- /assets/comparison_with_mano.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/assets/comparison_with_mano.jpg -------------------------------------------------------------------------------- /assets/each_component.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/assets/each_component.jpg -------------------------------------------------------------------------------- /assets/teaser.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/assets/teaser.png -------------------------------------------------------------------------------- /common/__pycache__/base.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/common/__pycache__/base.cpython-38.pyc -------------------------------------------------------------------------------- /common/__pycache__/logger.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/common/__pycache__/logger.cpython-38.pyc -------------------------------------------------------------------------------- /common/__pycache__/timer.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/common/__pycache__/timer.cpython-38.pyc -------------------------------------------------------------------------------- /common/base.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 os 9 | import os.path as osp 10 | import math 11 | import time 12 | import glob 13 | import abc 14 | from torch.utils.data import DataLoader 15 | import torch.optim 16 | import torchvision.transforms as transforms 17 | 18 | from config import cfg 19 | from dataset import Dataset 20 | from timer import Timer 21 | from logger import colorlogger 22 | from torch.nn.parallel.data_parallel import DataParallel 23 | from model import get_model 24 | 25 | class Base(object): 26 | __metaclass__ = abc.ABCMeta 27 | 28 | def __init__(self, log_name='logs.txt'): 29 | 30 | self.cur_epoch = 0 31 | 32 | # timer 33 | self.tot_timer = Timer() 34 | self.gpu_timer = Timer() 35 | self.read_timer = Timer() 36 | 37 | # logger 38 | self.logger = colorlogger(cfg.log_dir, log_name=log_name) 39 | 40 | @abc.abstractmethod 41 | def _make_batch_generator(self): 42 | return 43 | 44 | @abc.abstractmethod 45 | def _make_model(self): 46 | return 47 | 48 | 49 | class Trainer(Base): 50 | 51 | def __init__(self): 52 | super(Trainer, self).__init__(log_name = 'train_logs.txt') 53 | 54 | def get_optimizer(self, model): 55 | optimizer = torch.optim.Adam(model.parameters(), lr=cfg.lr) 56 | return optimizer 57 | 58 | def set_lr(self, epoch): 59 | if len(cfg.lr_dec_epoch) == 0: 60 | return cfg.lr 61 | 62 | for e in cfg.lr_dec_epoch: 63 | if epoch < e: 64 | break 65 | if epoch < cfg.lr_dec_epoch[-1]: 66 | idx = cfg.lr_dec_epoch.index(e) 67 | for g in self.optimizer.param_groups: 68 | g['lr'] = cfg.lr / (cfg.lr_dec_factor ** idx) 69 | else: 70 | for g in self.optimizer.param_groups: 71 | g['lr'] = cfg.lr / (cfg.lr_dec_factor ** len(cfg.lr_dec_epoch)) 72 | 73 | def get_lr(self): 74 | for g in self.optimizer.param_groups: 75 | cur_lr = g['lr'] 76 | 77 | return cur_lr 78 | def _make_batch_generator(self): 79 | # data load and construct batch generator 80 | self.logger.info("Creating dataset...") 81 | trainset_loader = Dataset(transforms.ToTensor(), 'train') 82 | batch_generator = DataLoader(dataset=trainset_loader, batch_size=cfg.num_gpus*cfg.train_batch_size, shuffle=True, num_workers=cfg.num_thread, pin_memory=True) 83 | 84 | self.mesh = trainset_loader.mesh 85 | self.root_joint_idx = trainset_loader.root_joint_idx 86 | self.align_joint_idx = trainset_loader.align_joint_idx 87 | self.non_rigid_joint_idx = trainset_loader.non_rigid_joint_idx 88 | self.itr_per_epoch = math.ceil(trainset_loader.__len__() / cfg.num_gpus / cfg.train_batch_size) 89 | self.batch_generator = batch_generator 90 | 91 | def _make_model(self): 92 | # prepare network 93 | self.logger.info("Creating graph and optimizer...") 94 | model = get_model('train', self.mesh, self.root_joint_idx, self.align_joint_idx, self.non_rigid_joint_idx) 95 | model = DataParallel(model).cuda() 96 | optimizer = self.get_optimizer(model) 97 | if cfg.continue_train: 98 | start_epoch, model, optimizer = self.load_model(model, optimizer) 99 | else: 100 | start_epoch = 0 101 | model.train() 102 | 103 | self.start_epoch = start_epoch 104 | self.model = model 105 | self.optimizer = optimizer 106 | 107 | def save_model(self, state, epoch): 108 | file_path = osp.join(cfg.model_dir,'snapshot_{}.pth.tar'.format(str(epoch))) 109 | torch.save(state, file_path) 110 | self.logger.info("Write snapshot into {}".format(file_path)) 111 | 112 | def load_model(self, model, optimizer): 113 | model_file_list = glob.glob(osp.join(cfg.model_dir,'*.pth.tar')) 114 | cur_epoch = max([int(file_name[file_name.find('snapshot_') + 9 : file_name.find('.pth.tar')]) for file_name in model_file_list]) 115 | model_path = osp.join(cfg.model_dir, 'snapshot_' + str(cur_epoch) + '.pth.tar') 116 | self.logger.info('Load checkpoint from {}'.format(model_path)) 117 | ckpt = torch.load(model_path) 118 | start_epoch = ckpt['epoch'] + 1 119 | 120 | model.load_state_dict(ckpt['network'], strict=False) 121 | try: 122 | optimizer.load_state_dict(ckpt['optimizer']) 123 | except: 124 | pass 125 | 126 | return start_epoch, model, optimizer 127 | 128 | 129 | class Tester(Base): 130 | def __init__(self, test_epoch): 131 | self.test_epoch = int(test_epoch) 132 | super(Tester, self).__init__(log_name = 'test_logs.txt') 133 | 134 | def _make_batch_generator(self): 135 | # data load and construct batch generator 136 | self.logger.info("Creating dataset...") 137 | testset_loader = Dataset(transforms.ToTensor(), 'test') 138 | batch_generator = DataLoader(dataset=testset_loader, batch_size=cfg.num_gpus*cfg.test_batch_size, shuffle=False, num_workers=cfg.num_thread, pin_memory=True) 139 | 140 | self.mesh = testset_loader.mesh 141 | self.root_joint_idx = testset_loader.root_joint_idx 142 | self.align_joint_idx = testset_loader.align_joint_idx 143 | self.non_rigid_joint_idx = testset_loader.non_rigid_joint_idx 144 | self.batch_generator = batch_generator 145 | 146 | def _make_model(self): 147 | model_path = os.path.join(cfg.model_dir, 'snapshot_%d.pth.tar' % self.test_epoch) 148 | assert os.path.exists(model_path), 'Cannot find model at ' + model_path 149 | self.logger.info('Load checkpoint from {}'.format(model_path)) 150 | 151 | # prepare network 152 | self.logger.info("Creating graph...") 153 | model = get_model('test', self.mesh, self.root_joint_idx, self.align_joint_idx, self.non_rigid_joint_idx) 154 | model = DataParallel(model).cuda() 155 | ckpt = torch.load(model_path) 156 | model.load_state_dict(ckpt['network'], strict=False) 157 | model.eval() 158 | 159 | self.model = model 160 | 161 | def _evaluate(self, preds, result_save_path): 162 | self.testset.evaluate(preds, result_save_path) 163 | 164 | -------------------------------------------------------------------------------- /common/logger.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 logging 9 | import os 10 | 11 | OK = '\033[92m' 12 | WARNING = '\033[93m' 13 | FAIL = '\033[91m' 14 | END = '\033[0m' 15 | 16 | PINK = '\033[95m' 17 | BLUE = '\033[94m' 18 | GREEN = OK 19 | RED = FAIL 20 | WHITE = END 21 | YELLOW = WARNING 22 | 23 | class colorlogger(): 24 | def __init__(self, log_dir, log_name='train_logs.txt'): 25 | # set log 26 | self._logger = logging.getLogger(log_name) 27 | self._logger.setLevel(logging.INFO) 28 | log_file = os.path.join(log_dir, log_name) 29 | if not os.path.exists(log_dir): 30 | os.makedirs(log_dir) 31 | file_log = logging.FileHandler(log_file, mode='a') 32 | file_log.setLevel(logging.INFO) 33 | console_log = logging.StreamHandler() 34 | console_log.setLevel(logging.INFO) 35 | formatter = logging.Formatter( 36 | "{}%(asctime)s{} %(message)s".format(GREEN, END), 37 | "%m-%d %H:%M:%S") 38 | file_log.setFormatter(formatter) 39 | console_log.setFormatter(formatter) 40 | self._logger.addHandler(file_log) 41 | self._logger.addHandler(console_log) 42 | 43 | def debug(self, msg): 44 | self._logger.debug(str(msg)) 45 | 46 | def info(self, msg): 47 | self._logger.info(str(msg)) 48 | 49 | def warning(self, msg): 50 | self._logger.warning(WARNING + 'WRN: ' + str(msg) + END) 51 | 52 | def critical(self, msg): 53 | self._logger.critical(RED + 'CRI: ' + str(msg) + END) 54 | 55 | def error(self, msg): 56 | self._logger.error(RED + 'ERR: ' + str(msg) + END) 57 | 58 | -------------------------------------------------------------------------------- /common/nets/DiffableRenderer/DiffableRenderer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 os 9 | import sys 10 | import numpy as np 11 | import torch 12 | import torch.nn as nn 13 | import torch.nn.functional as F 14 | from config import cfg 15 | import neural_renderer as nr 16 | 17 | def index_selection_nd(x, I, dim): 18 | target_shape = [*x.shape] 19 | del target_shape[dim] 20 | target_shape[dim:dim] = [*I.shape] 21 | return x.index_select(dim, I.view(-1)).reshape(target_shape) 22 | 23 | class RenderLayer(nn.Module): 24 | def __init__(self): 25 | super(RenderLayer, self).__init__() 26 | 27 | def forward(self, vertex, cam_param, img_affine_trans_mat, mesh): 28 | batch_size = vertex.shape[0] 29 | face_num = len(mesh['vi']) 30 | focal, princpt, campos, camrot = cam_param['focal'], cam_param['princpt'], cam_param['campos'], cam_param['camrot'] 31 | 32 | # project vertex world -> camera space 33 | vertex = vertex - campos.view(-1,1,3) 34 | vertex = torch.cat([torch.mm(camrot[i],vertex[i].permute(1,0)).permute(1,0)[None,:,:] for i in range(batch_size)],0) 35 | vertex_3d_x = vertex[:,:,0] 36 | vertex_3d_y = vertex[:,:,1] 37 | vertex_z = vertex[:,:,2] 38 | vertex_z = vertex_z + (vertex_z==0).type('torch.cuda.FloatTensor')*1e-4 39 | 40 | # project camera -> image space 41 | vertex_2d_x = (vertex_3d_x / vertex_z * focal[:,0].view(-1,1) + princpt[:,0].view(-1,1))[:,:,None] 42 | vertex_2d_y = (vertex_3d_y / vertex_z * focal[:,1].view(-1,1) + princpt[:,1].view(-1,1))[:,:,None] 43 | vertex_2d = torch.cat([vertex_2d_x, vertex_2d_y, torch.ones_like(vertex_2d_x)],2) 44 | 45 | # apply affine transform (crop and resize) 46 | vertex_2d = torch.bmm(img_affine_trans_mat, vertex_2d.permute(0,2,1)).permute(0,2,1) 47 | 48 | ################################## 49 | # neural renderer (for depth map rendering) 50 | vertex_2d_norm = torch.cat([vertex_2d[:,:,0:1]/cfg.rendered_img_shape[1]*2-1,\ 51 | (cfg.rendered_img_shape[0] - 1 - vertex_2d[:,:,1:2])/cfg.rendered_img_shape[0]*2-1, \ 52 | vertex_z[:,:,None]],2) 53 | 54 | # vertex_2d_v0, v1, v2: batch_size x face_num x 3. coordinates of vertices for each face 55 | vertex_2d_v0 = torch.cat([index_selection_nd(vertex_2d_norm[i], mesh['vi'][:,0], 0)[None, ...] for i in range(batch_size)], dim=0) 56 | vertex_2d_v1 = torch.cat([index_selection_nd(vertex_2d_norm[i], mesh['vi'][:,1], 0)[None, ...] for i in range(batch_size)], dim=0) 57 | vertex_2d_v2 = torch.cat([index_selection_nd(vertex_2d_norm[i], mesh['vi'][:,2], 0)[None, ...] for i in range(batch_size)], dim=0) 58 | face_vertices = torch.cat([vertex_2d_v0[:,:,None,:], vertex_2d_v1[:,:,None,:], vertex_2d_v2[:,:,None,:]], 2) 59 | 60 | rendered_depthmap = nr.rasterize_depth(face_vertices, cfg.rendered_img_shape[0], False, near=cfg.depth_min, far=cfg.depth_max)[:,None,:,:] 61 | rendered_depthmap[rendered_depthmap == cfg.depth_max] = 0 62 | 63 | return rendered_depthmap 64 | 65 | -------------------------------------------------------------------------------- /common/nets/DiffableRenderer/__pycache__/DiffableRenderer.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/common/nets/DiffableRenderer/__pycache__/DiffableRenderer.cpython-38.pyc -------------------------------------------------------------------------------- /common/nets/__pycache__/layer.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/common/nets/__pycache__/layer.cpython-38.pyc -------------------------------------------------------------------------------- /common/nets/__pycache__/loss.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/common/nets/__pycache__/loss.cpython-38.pyc -------------------------------------------------------------------------------- /common/nets/__pycache__/module.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/common/nets/__pycache__/module.cpython-38.pyc -------------------------------------------------------------------------------- /common/nets/__pycache__/resnet.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/common/nets/__pycache__/resnet.cpython-38.pyc -------------------------------------------------------------------------------- /common/nets/layer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 | import torch.nn as nn 10 | import torch.nn.functional as F 11 | from torch.nn.parameter import Parameter 12 | from torch.nn.modules.module import Module 13 | import math 14 | import numbers 15 | from config import cfg 16 | 17 | def make_linear_layers(feat_dims, relu_final=True): 18 | layers = [] 19 | for i in range(len(feat_dims)-1): 20 | layers.append(nn.Linear(feat_dims[i], feat_dims[i+1])) 21 | 22 | # Do not use ReLU for final estimation 23 | if i < len(feat_dims)-2 or (i == len(feat_dims)-2 and relu_final): 24 | layers.append(nn.ReLU(inplace=True)) 25 | 26 | return nn.Sequential(*layers) 27 | 28 | def make_conv_layers(feat_dims, kernel=3, stride=1, padding=1, bnrelu_final=True): 29 | layers = [] 30 | for i in range(len(feat_dims)-1): 31 | layers.append( 32 | nn.Conv2d( 33 | in_channels=feat_dims[i], 34 | out_channels=feat_dims[i+1], 35 | kernel_size=kernel, 36 | stride=stride, 37 | padding=padding 38 | )) 39 | # Do not use BN and ReLU for final estimation 40 | if i < len(feat_dims)-2 or (i == len(feat_dims)-2 and bnrelu_final): 41 | layers.append(nn.BatchNorm2d(feat_dims[i+1])) 42 | layers.append(nn.ReLU(inplace=True)) 43 | 44 | return nn.Sequential(*layers) 45 | 46 | def make_deconv_layers(feat_dims, bnrelu_final=True): 47 | layers = [] 48 | for i in range(len(feat_dims)-1): 49 | layers.append( 50 | nn.ConvTranspose2d( 51 | in_channels=feat_dims[i], 52 | out_channels=feat_dims[i+1], 53 | kernel_size=4, 54 | stride=2, 55 | padding=1, 56 | output_padding=0, 57 | bias=False)) 58 | 59 | # Do not use BN and ReLU for final estimation 60 | if i < len(feat_dims)-2 or (i == len(feat_dims)-2 and bnrelu_final): 61 | layers.append(nn.BatchNorm2d(feat_dims[i+1])) 62 | layers.append(nn.ReLU(inplace=True)) 63 | 64 | return nn.Sequential(*layers) 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /common/nets/loss.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 | import torch.nn as nn 10 | from torch.nn import functional as F 11 | import numpy as np 12 | from config import cfg 13 | import math 14 | 15 | class DepthmapLoss(nn.Module): 16 | def __init__(self): 17 | super(DepthmapLoss, self).__init__() 18 | 19 | def smooth_l1_loss(self, out, gt): 20 | return F.smooth_l1_loss(out, gt, reduction='none') 21 | 22 | def forward(self, depthmap_out, depthmap_gt): 23 | if isinstance(depthmap_out,list) and isinstance(depthmap_gt,list): 24 | mask = [((depthmap_out[i] != 0) * (depthmap_gt[i] != 0)).float() for i in range(len(depthmap_out))] 25 | loss = [self.smooth_l1_loss(depthmap_out[i], depthmap_gt[i]) * mask[i] for i in range(len(depthmap_out))] 26 | loss = sum(loss)/len(loss) 27 | elif isinstance(depthmap_out,torch.Tensor) and isinstance(depthmap_gt,torch.Tensor): 28 | mask = ((depthmap_out != 0) * (depthmap_gt != 0)).float() 29 | loss = self.smooth_l1_loss(depthmap_out, depthmap_gt) * mask 30 | else: 31 | assert 0 32 | 33 | return loss 34 | 35 | class JointLoss(nn.Module): 36 | def __init__(self): 37 | super(JointLoss, self).__init__() 38 | 39 | def l1_loss(self, out, gt): 40 | return torch.abs(out - gt) 41 | 42 | def forward(self, joint_out, joint_gt, joint_valid): 43 | loss = self.l1_loss(joint_out, joint_gt) * joint_valid 44 | return loss 45 | 46 | class PenetLoss(nn.Module): 47 | def __init__(self, skeleton, segmentation, root_joint_idx, non_rigid_joint_idx): 48 | super(PenetLoss, self).__init__() 49 | self.skeleton = skeleton 50 | self.joint_num = len(skeleton) 51 | self.root_joint_idx = root_joint_idx 52 | self.non_rigid_joint_idx = non_rigid_joint_idx 53 | self.register_buffer('segmentation', torch.from_numpy(segmentation).cuda().float()) 54 | 55 | def traverse_skeleton(self, cur_joint_idx, path, all_path): 56 | # skeleton hierarchy 57 | path.append(cur_joint_idx) 58 | if len(self.skeleton[cur_joint_idx]['child_id']) > 0: 59 | for child_id in self.skeleton[cur_joint_idx]['child_id']: 60 | path_for_each_node = path.copy() 61 | self.traverse_skeleton(child_id, path, all_path) 62 | path = path_for_each_node 63 | else: 64 | all_path.append(path) 65 | 66 | def make_combination(self, data): 67 | combination = [] 68 | assert len(data) > 1 69 | for i in range(len(data)-1): 70 | for j in range(i+1,len(data)): 71 | combination.append([data[i],data[j]]) 72 | return combination 73 | 74 | def make_bone_helper(self, bone, template_pose, mesh_v, start_joint_idx, end_joint_idx, step): 75 | bone['start_joint_idx'].append(start_joint_idx) 76 | bone['end_joint_idx'].append(end_joint_idx) 77 | bone['step'].append(step) 78 | bone['point_num'] += 1 79 | 80 | cur_dir = template_pose[end_joint_idx,:3,3] - template_pose[start_joint_idx,:3,3] 81 | cur_pos = template_pose[start_joint_idx,:3,3] + cur_dir * step 82 | vector = mesh_v - cur_pos[None,None,:] 83 | min_dist, min_dist_idx = torch.min(torch.sqrt(torch.sum(vector**2,2)),1)#[0] 84 | bone['min_dist'].append(min_dist) 85 | 86 | def make_bone(self, bone, template_pose, mesh_v, cur_joint_idx): 87 | # make bone by interpolating joint of mesh 88 | if len(self.skeleton[cur_joint_idx]['child_id']) == 0: 89 | self.make_bone_helper(bone, template_pose, mesh_v, cur_joint_idx, cur_joint_idx, 0) 90 | 91 | for child_joint_idx in self.skeleton[cur_joint_idx]['child_id']: 92 | for step in torch.arange(0,1,cfg.bone_step_size): 93 | self.make_bone_helper(bone, template_pose, mesh_v, cur_joint_idx, child_joint_idx, step) 94 | self.make_bone(bone, template_pose, mesh_v, child_joint_idx) 95 | 96 | def get_bone_data(self, template_pose, mesh_v): 97 | bone = {'start_joint_idx': [], 'end_joint_idx': [], 'step': [], 'min_dist': [], 'point_num': 0} 98 | self.make_bone(bone, template_pose, mesh_v, self.root_joint_idx) 99 | bone['start_joint_idx'] = torch.cuda.LongTensor(bone['start_joint_idx']) 100 | bone['end_joint_idx'] = torch.cuda.LongTensor(bone['end_joint_idx']) 101 | bone['step'] = torch.cuda.FloatTensor(bone['step']) 102 | bone['min_dist'] = torch.stack(bone['min_dist']) # point_num x batch_size 103 | return bone 104 | 105 | def get_bone_from_joint(self, joint, bone): 106 | batch_size = joint.shape[0] 107 | bone_num = bone['point_num'] 108 | vec_dir = joint[:,bone['end_joint_idx'],:] - joint[:,bone['start_joint_idx'],:] 109 | bone_out = joint[:,bone['start_joint_idx'],:] + vec_dir * bone['step'][None,:,None].repeat(batch_size,1,3) 110 | bone_out = bone_out.view(batch_size,bone_num,3) 111 | return bone_out 112 | 113 | def forward(self, template_pose, mesh_v, joint_out, geo_out): 114 | batch_size = joint_out.shape[0] 115 | 116 | bone = self.get_bone_data(template_pose, mesh_v) 117 | bone_out_from_joint = self.get_bone_from_joint(joint_out, bone) 118 | 119 | skeleton_path = [] 120 | self.traverse_skeleton(self.root_joint_idx, [], skeleton_path) 121 | skeleton_part = [] 122 | for path in skeleton_path: 123 | for pid in range(len(path)-1): 124 | start_joint_idx = path[pid]; end_joint_idx = path[pid+1] 125 | skeleton_part.append([start_joint_idx, end_joint_idx]) 126 | skeleton_part = self.make_combination(skeleton_part) # (combination num x 2 (part_1, part_2) x 2 (start, end joint idx)) 127 | 128 | # rigid part 129 | loss_penetration_rigid = 0 130 | loss_penetration_rigid_cnt = 0 131 | for cid in range(len(skeleton_part)): 132 | # first part index 133 | start_joint_idx_1 = skeleton_part[cid][0][0] 134 | end_joint_idx_1 = skeleton_part[cid][0][1] 135 | 136 | # second part index 137 | start_joint_idx_2 = skeleton_part[cid][1][0] 138 | end_joint_idx_2 = skeleton_part[cid][1][1] 139 | 140 | # exclude adjant parts 141 | if start_joint_idx_1 == start_joint_idx_2 or start_joint_idx_1 == end_joint_idx_2 or end_joint_idx_1 == start_joint_idx_2: 142 | continue 143 | 144 | # first part distance thr (radius of sphere) 145 | bone_mask_1 = ((bone['start_joint_idx'] == start_joint_idx_1) * (bone['end_joint_idx'] == end_joint_idx_1)).byte() 146 | if torch.sum(bone_mask_1) == 0: 147 | continue 148 | bone_1 = bone_out_from_joint[:,bone_mask_1,:] 149 | dist_thr_1 = bone['min_dist'][bone_mask_1].permute(1,0) 150 | 151 | # second part distance thr (radius of sphere) 152 | bone_mask_2 = ((bone['start_joint_idx'] == start_joint_idx_2) * (bone['end_joint_idx'] == end_joint_idx_2)).byte() 153 | if torch.sum(bone_mask_2) == 0: 154 | continue 155 | bone_2 = bone_out_from_joint[:,bone_mask_2,:] 156 | dist_thr_2 = bone['min_dist'][bone_mask_2].permute(1,0) 157 | 158 | # loss calculate 159 | dist = torch.sqrt(torch.sum((bone_1[:,:,None,:].repeat(1,1,bone_2.shape[1],1) - bone_2[:,None,:,:].repeat(1,bone_1.shape[1],1,1))**2,3)) 160 | dist_thr = dist_thr_1[:,:,None].repeat(1,1,dist_thr_2.shape[1]) + dist_thr_2[:,None,:].repeat(1,dist_thr_1.shape[1],1) 161 | loss_penetration_rigid += torch.clamp(dist_thr - dist, min=0).mean((1,2)) 162 | loss_penetration_rigid_cnt += 1 163 | 164 | # non-rigid joint 165 | loss_penetration_non_rigid = 0 166 | loss_penetration_non_rigid_cnt = 0 167 | for nr_jid in self.non_rigid_joint_idx: 168 | nr_skin = geo_out[:,(self.segmentation == nr_jid).byte(),:] 169 | for path in skeleton_path: 170 | is_penetrating = torch.cuda.FloatTensor([0 for _ in range(batch_size)]) 171 | 172 | # only consider finger tips 173 | for pid in range(len(path)-2,len(path)-1): 174 | start_joint_idx = path[pid]; end_joint_idx = path[pid+1]; 175 | 176 | # exclude path from root through the thumb path 177 | if 'thumb' in self.skeleton[start_joint_idx]['name'] or 'thumb' in self.skeleton[end_joint_idx]['name']: 178 | continue 179 | 180 | bone_mask = ((bone['start_joint_idx'] == start_joint_idx) * (bone['end_joint_idx'] == end_joint_idx)).byte() 181 | bone_pid = bone_out_from_joint[:,bone_mask,:] 182 | dist = torch.sqrt(torch.sum((nr_skin[:,:,None,:].repeat(1,1,bone_pid.shape[1],1) - bone_pid[:,None,:,:].repeat(1,nr_skin.shape[1],1,1))**2,3)) 183 | dist = torch.min(dist,1)[0] # use minimum distance from a bone to skin 184 | dist_thr = bone['min_dist'][bone_mask].permute(1,0) 185 | 186 | loss_per_batch = [] 187 | for bid in range(batch_size): 188 | collision_idx = torch.nonzero(dist[bid] < dist_thr[bid]) 189 | if len(collision_idx) > 0: # collision occur 190 | is_penetrating[bid] = 1 191 | bone_idx = torch.min(collision_idx) # bone start from parent to child -> just pick min idx 192 | loss = torch.abs((dist[bid][bone_idx:] - dist_thr[bid][bone_idx:]).mean()).view(1) 193 | elif is_penetrating[bid] == 1: 194 | loss = torch.abs((dist[bid] - dist_thr[bid]).mean()).view(1) 195 | else: 196 | loss = torch.zeros((1)).cuda().float() 197 | loss_per_batch.append(loss) 198 | loss_penetration_non_rigid += torch.cat(loss_per_batch) 199 | loss_penetration_non_rigid_cnt += 1 200 | 201 | loss_penetration_rigid = loss_penetration_rigid / loss_penetration_rigid_cnt 202 | loss_penetration_non_rigid = loss_penetration_non_rigid / loss_penetration_non_rigid_cnt 203 | loss = cfg.loss_penet_r_weight * loss_penetration_rigid + cfg.loss_penet_nr_weight * loss_penetration_non_rigid 204 | return loss 205 | 206 | class LaplacianLoss(nn.Module): 207 | def __init__(self, vertex, faces, average=False): 208 | super(LaplacianLoss, self).__init__() 209 | self.nv = vertex.shape[0] 210 | self.nf = faces.shape[0] 211 | self.average = average 212 | laplacian = np.zeros([self.nv, self.nv]).astype(np.float32) 213 | 214 | laplacian[faces[:, 0], faces[:, 1]] = -1 215 | laplacian[faces[:, 1], faces[:, 0]] = -1 216 | laplacian[faces[:, 1], faces[:, 2]] = -1 217 | laplacian[faces[:, 2], faces[:, 1]] = -1 218 | laplacian[faces[:, 2], faces[:, 0]] = -1 219 | laplacian[faces[:, 0], faces[:, 2]] = -1 220 | 221 | r, c = np.diag_indices(laplacian.shape[0]) 222 | laplacian[r, c] = -laplacian.sum(1) 223 | 224 | for i in range(self.nv): 225 | laplacian[i, :] /= (laplacian[i, i] + 1e-8) 226 | 227 | self.register_buffer('laplacian', torch.from_numpy(laplacian).cuda().float()) 228 | 229 | def forward(self, x): 230 | batch_size = x.size(0) 231 | x = torch.cat([torch.matmul(self.laplacian,x[i])[None,:,:] for i in range(batch_size)],0) 232 | x = x.pow(2).sum(2) 233 | if self.average: 234 | return x.sum() / batch_size 235 | else: 236 | return x 237 | 238 | -------------------------------------------------------------------------------- /common/nets/module.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 | import torch.nn as nn 10 | from torch.nn import functional as F 11 | from config import cfg 12 | from nets.layer import make_linear_layers, make_conv_layers, make_deconv_layers 13 | from nets.resnet import ResNetBackbone 14 | import math 15 | 16 | class BackboneNet(nn.Module): 17 | def __init__(self): 18 | super(BackboneNet, self).__init__() 19 | self.resnet = ResNetBackbone(cfg.resnet_type) 20 | self.fc = make_linear_layers([2048,cfg.backbone_img_feat_dim]) 21 | 22 | def init_weights(self): 23 | self.resnet.init_weights() 24 | 25 | def forward(self, img): 26 | img_feat = self.resnet(img) 27 | img_feat = F.avg_pool2d(img_feat,(img_feat.shape[2],img_feat.shape[3])).view(-1,2048) 28 | img_feat = self.fc(img_feat) 29 | return img_feat 30 | 31 | class PoseNet(nn.Module): 32 | def __init__(self, skeleton): 33 | super(PoseNet, self).__init__() 34 | self.joint_num = len(skeleton) 35 | self.register_buffer('DoF', torch.cat([torch.from_numpy(skeleton[i]['DoF'])[None,:] for i in range(self.joint_num)]).cuda().float()) 36 | self.dof_num = int(torch.sum(self.DoF)) 37 | self.fc = make_linear_layers([cfg.backbone_img_feat_dim,512,self.dof_num], relu_final=False) 38 | 39 | def output_to_euler_angle(self, x): 40 | batch_size = x.shape[0] 41 | idx = torch.nonzero(self.DoF) # idx[:,0]: joint_idx, idx[:,1]: 0: x, 1: y, 2: z 42 | 43 | # normalize x to [-1,1] 44 | x = torch.tanh(x) * math.pi 45 | 46 | # plug in estimated euler angle. for DoF==0, angles are to zero 47 | euler_angle = torch.zeros((batch_size, self.joint_num, 3)).cuda().float() 48 | euler_angle[:,idx[:,0],idx[:,1]] = x 49 | 50 | return euler_angle 51 | 52 | def forward(self, img_feat_all_view): 53 | output = self.fc(img_feat_all_view) 54 | angle = self.output_to_euler_angle(output) 55 | return angle 56 | 57 | class SkeletonRefineNet(nn.Module): 58 | def __init__(self, skeleton): 59 | super(SkeletonRefineNet, self).__init__() 60 | self.joint_num = len(skeleton) 61 | self.fc_skeleton = make_linear_layers([cfg.id_code_dim,64,self.joint_num*3], relu_final=False) 62 | 63 | def forward(self, id_code): 64 | skeleton_corrective = self.fc_skeleton(id_code).view(self.joint_num,3) 65 | return skeleton_corrective 66 | 67 | class SkinRefineNet(nn.Module): 68 | def __init__(self, skeleton, vertex_num): 69 | super(SkinRefineNet, self).__init__() 70 | self.joint_num = len(skeleton) 71 | self.vertex_num = vertex_num 72 | self.fc_pose = make_linear_layers([self.joint_num*3,256,vertex_num*3], relu_final=False) 73 | self.fc_id = make_linear_layers([cfg.id_code_dim,256,vertex_num*3], relu_final=False) 74 | 75 | def forward(self, joint_euler, id_code): 76 | joint_euler = joint_euler.view(-1,self.joint_num*3) 77 | pose_corrective = self.fc_pose(joint_euler).view(-1,self.vertex_num,3) 78 | id_corrective = self.fc_id(id_code).view(-1,self.vertex_num,3) 79 | return pose_corrective, id_corrective 80 | 81 | 82 | -------------------------------------------------------------------------------- /common/nets/resnet.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 os 9 | import os.path as osp 10 | from config import cfg 11 | import torch 12 | import torch.nn as nn 13 | from torchvision.models.resnet import BasicBlock, Bottleneck 14 | from torchvision.models.resnet import model_urls 15 | 16 | class ResNetBackbone(nn.Module): 17 | 18 | def __init__(self, resnet_type): 19 | 20 | resnet_spec = {18: (BasicBlock, [2, 2, 2, 2], [64, 64, 128, 256, 512], 'resnet18'), 21 | 34: (BasicBlock, [3, 4, 6, 3], [64, 64, 128, 256, 512], 'resnet34'), 22 | 50: (Bottleneck, [3, 4, 6, 3], [64, 256, 512, 1024, 2048], 'resnet50'), 23 | 101: (Bottleneck, [3, 4, 23, 3], [64, 256, 512, 1024, 2048], 'resnet101'), 24 | 152: (Bottleneck, [3, 8, 36, 3], [64, 256, 512, 1024, 2048], 'resnet152')} 25 | block, layers, channels, name = resnet_spec[resnet_type] 26 | 27 | self.name = name 28 | self.inplanes = 64 29 | super(ResNetBackbone, self).__init__() 30 | self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, 31 | bias=False) 32 | self.bn1 = nn.BatchNorm2d(64) 33 | self.relu = nn.ReLU(inplace=True) 34 | self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) 35 | self.layer1 = self._make_layer(block, 64, layers[0]) 36 | self.layer2 = self._make_layer(block, 128, layers[1], stride=2) 37 | self.layer3 = self._make_layer(block, 256, layers[2], stride=2) 38 | self.layer4 = self._make_layer(block, 512, layers[3], stride=2) 39 | 40 | for m in self.modules(): 41 | if isinstance(m, nn.Conv2d): 42 | # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 43 | nn.init.normal_(m.weight, mean=0, std=0.001) 44 | elif isinstance(m, nn.BatchNorm2d): 45 | nn.init.constant_(m.weight, 1) 46 | nn.init.constant_(m.bias, 0) 47 | 48 | def _make_layer(self, block, planes, blocks, stride=1): 49 | downsample = None 50 | if stride != 1 or self.inplanes != planes * block.expansion: 51 | downsample = nn.Sequential( 52 | nn.Conv2d(self.inplanes, planes * block.expansion, 53 | kernel_size=1, stride=stride, bias=False), 54 | nn.BatchNorm2d(planes * block.expansion), 55 | ) 56 | 57 | layers = [] 58 | layers.append(block(self.inplanes, planes, stride, downsample)) 59 | self.inplanes = planes * block.expansion 60 | for i in range(1, blocks): 61 | layers.append(block(self.inplanes, planes)) 62 | 63 | return nn.Sequential(*layers) 64 | 65 | def forward(self, x): 66 | x = self.conv1(x) 67 | x = self.bn1(x) 68 | x = self.relu(x) 69 | x = self.maxpool(x) 70 | 71 | x = self.layer1(x) 72 | x = self.layer2(x) 73 | x = self.layer3(x) 74 | x = self.layer4(x) 75 | 76 | return x 77 | 78 | def init_weights(self): 79 | org_resnet = torch.utils.model_zoo.load_url(model_urls[self.name]) 80 | # drop orginal resnet fc layer, add 'None' in case of no fc layer, that will raise error 81 | org_resnet.pop('fc.weight', None) 82 | org_resnet.pop('fc.bias', None) 83 | 84 | self.load_state_dict(org_resnet) 85 | print("Initialize resnet from model zoo") 86 | 87 | 88 | -------------------------------------------------------------------------------- /common/timer.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------- 2 | # Fast R-CNN 3 | # Copyright (c) 2015 Microsoft 4 | # Licensed under The MIT License [see LICENSE for details] 5 | # Written by Ross Girshick 6 | # -------------------------------------------------------- 7 | # -----------------------LICENSE-------------------------- 8 | # Fast R-CNN 9 | # 10 | # Copyright (c) Microsoft Corporation 11 | # 12 | # All rights reserved. 13 | # 14 | # MIT License 15 | # 16 | # Permission is hereby granted, free of charge, to any person obtaining a 17 | # copy of this software and associated documentation files (the "Software"), 18 | # to deal in the Software without restriction, including without limitation 19 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 20 | # and/or sell copies of the Software, and to permit persons to whom the 21 | # Software is furnished to do so, subject to the following conditions: 22 | # 23 | # The above copyright notice and this permission notice shall be included 24 | # in all copies or substantial portions of the Software. 25 | # 26 | # THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 27 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 28 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 29 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 30 | # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 31 | # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 32 | # OTHER DEALINGS IN THE SOFTWARE. 33 | # -------------------------------------------------------- 34 | # 35 | # The code is from the publicly available implementation of Fast R-CNN 36 | # https://github.com/rbgirshick/fast-rcnn/blob/master/lib/utils/timer.py 37 | 38 | import time 39 | 40 | class Timer(object): 41 | """A simple timer.""" 42 | def __init__(self): 43 | self.total_time = 0. 44 | self.calls = 0 45 | self.start_time = 0. 46 | self.diff = 0. 47 | self.average_time = 0. 48 | self.warm_up = 0 49 | 50 | def tic(self): 51 | # using time.time instead of time.clock because time time.clock 52 | # does not normalize for multithreading 53 | self.start_time = time.time() 54 | 55 | def toc(self, average=True): 56 | self.diff = time.time() - self.start_time 57 | if self.warm_up < 10: 58 | self.warm_up += 1 59 | return self.diff 60 | else: 61 | self.total_time += self.diff 62 | self.calls += 1 63 | self.average_time = self.total_time / self.calls 64 | 65 | if average: 66 | return self.average_time 67 | else: 68 | return self.diff 69 | -------------------------------------------------------------------------------- /common/utils/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 | -------------------------------------------------------------------------------- /common/utils/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/common/utils/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /common/utils/__pycache__/dir.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/common/utils/__pycache__/dir.cpython-38.pyc -------------------------------------------------------------------------------- /common/utils/__pycache__/mesh.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/common/utils/__pycache__/mesh.cpython-38.pyc -------------------------------------------------------------------------------- /common/utils/__pycache__/preprocessing.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/common/utils/__pycache__/preprocessing.cpython-38.pyc -------------------------------------------------------------------------------- /common/utils/__pycache__/transforms.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/common/utils/__pycache__/transforms.cpython-38.pyc -------------------------------------------------------------------------------- /common/utils/__pycache__/vis.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/common/utils/__pycache__/vis.cpython-38.pyc -------------------------------------------------------------------------------- /common/utils/dir.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 os 9 | import sys 10 | 11 | def make_folder(folder_name): 12 | if not os.path.exists(folder_name): 13 | os.makedirs(folder_name) 14 | 15 | def add_pypath(path): 16 | if path not in sys.path: 17 | sys.path.insert(0, path) 18 | 19 | -------------------------------------------------------------------------------- /common/utils/mesh.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 scipy.sparse as sp 10 | import torch 11 | import torch.nn as nn 12 | from config import cfg 13 | import os 14 | import os.path as osp 15 | import math 16 | from utils.preprocessing import load_img 17 | import cv2 18 | 19 | class Mesh(object): 20 | # A simple class for creating and manipulating trimesh objects 21 | def __init__(self, obj_filename): 22 | 23 | self.v = np.zeros((0,3), dtype=np.float32) # (x,y,z) coordinates of mesh 24 | self.vi = np.zeros((0,3), dtype=np.int32) # vertex indices (v) of each mesh triangle 25 | self.vt = np.zeros((0,2), dtype=np.float32) # (u,v) coordinates of texture in UV space 26 | self.vti = np.zeros((0,3), dtype=np.int32) # vertex indices (vt) of each mesh triangle 27 | self.load_obj(obj_filename) 28 | 29 | self.skeleton= None # joint information 30 | self.global_pose = None # 6D global pose 31 | self.skinning_weight = None # skinning weight of template mesh 32 | self.segmentation = None # segmentation obtained from skinnig weight 33 | self.local_pose = None # local pose 34 | self.global_pose_inv = None # inverse of global pose 35 | 36 | def load_obj(self, file_name): 37 | obj_file = open(file_name) 38 | for line in obj_file: 39 | words = line.split(' ') 40 | if words[0] == 'v': 41 | x,y,z = float(words[1]) * 10, float(words[2]) * 10, float(words[3]) * 10 # change cm to mm 42 | self.v = np.concatenate((self.v, np.array([x,y,z]).reshape(1,3)), axis=0) 43 | elif words[0] == 'vt': 44 | u,v = float(words[1]), float(words[2]) 45 | self.vt = np.concatenate((self.vt, np.array([u,v]).reshape(1,2)), axis=0) 46 | elif words[0] == 'f': 47 | vi_1, vti_1 = words[1].split('/')[:2] 48 | vi_2, vti_2 = words[2].split('/')[:2] 49 | vi_3, vti_3 = words[3].split('/')[:2] 50 | 51 | # change 1-based index to 0-based index 52 | vi_1, vi_2, vi_3 = int(vi_1)-1, int(vi_2)-1, int(vi_3)-1 53 | vti_1, vti_2, vti_3 = int(vti_1)-1, int(vti_2)-1, int(vti_3)-1 54 | 55 | self.vi = np.concatenate((self.vi, np.array([vi_1,vi_2,vi_3]).reshape(1,3)), axis=0) 56 | self.vti = np.concatenate((self.vti, np.array([vti_1,vti_2,vti_3]).reshape(1,3)), axis=0) 57 | else: 58 | pass 59 | 60 | def save_obj(self, v, color=None, file_name='output.obj'): 61 | obj_file = open(file_name, 'w') 62 | for i in range(len(v)): 63 | if color is None: 64 | obj_file.write('v ' + str(v[i][0]) + ' ' + str(v[i][1]) + ' ' + str(v[i][2]) + '\n') 65 | else: 66 | obj_file.write('v ' + str(v[i][0]) + ' ' + str(v[i][1]) + ' ' + str(v[i][2]) + ' ' + str(color[i][0]) + ' ' + str(color[i][1]) + ' ' + str(color[i][2]) + '\n') 67 | for i in range(len(self.vt)): 68 | obj_file.write('vt ' + str(self.vt[i][0]) + ' ' + str(self.vt[i][1]) + '\n') 69 | for i in range(len(self.vi)): 70 | obj_file.write('f ' + str(self.vi[i][0]+1) + '/' + str(self.vti[i][0]+1) + ' ' + str(self.vi[i][1]+1) + '/' + str(self.vti[i][1]+1) + ' ' + str(self.vi[i][2]+1) + '/' + str(self.vti[i][2]+1) + '\n') 71 | obj_file.close() 72 | 73 | def load_skeleton(self, path, joint_num): 74 | 75 | # load joint info (name, parent_id) 76 | skeleton = [{} for _ in range(joint_num)] 77 | with open(path) as fp: 78 | for line in fp: 79 | if line[0] == '#': continue 80 | splitted = line.split(' ') 81 | joint_name, joint_id, joint_parent_id = splitted 82 | joint_id, joint_parent_id = int(joint_id), int(joint_parent_id) 83 | skeleton[joint_id]['name'] = joint_name 84 | skeleton[joint_id]['parent_id'] = joint_parent_id 85 | 86 | if joint_name.endswith('null'): 87 | skeleton[joint_id]['DoF'] = np.array([0,0,0],dtype=np.float32) 88 | elif joint_name.endswith('3'): 89 | skeleton[joint_id]['DoF'] = np.array([0,0,1],dtype=np.float32) 90 | elif joint_name.endswith('2'): 91 | skeleton[joint_id]['DoF'] = np.array([0,0,1],dtype=np.float32) 92 | elif joint_name.endswith('1'): 93 | skeleton[joint_id]['DoF'] = np.array([1,1,1],dtype=np.float32) 94 | elif joint_name.endswith('thumb0'): 95 | skeleton[joint_id]['DoF'] = np.array([1,1,1],dtype=np.float32) 96 | else: 97 | skeleton[joint_id]['DoF'] = np.array([0,0,0],dtype=np.float32) 98 | 99 | # save child_id 100 | for i in range(len(skeleton)): 101 | joint_child_id = [] 102 | for j in range(len(skeleton)): 103 | if skeleton[j]['parent_id'] == i: 104 | joint_child_id.append(j) 105 | skeleton[i]['child_id'] = joint_child_id 106 | 107 | self.skeleton = skeleton 108 | 109 | def load_skinning_weight(self, skinning_weight_path): 110 | # load skinning_weight of mesh 111 | self.skinning_weight = np.zeros((len(self.v),len(self.skeleton)), dtype=np.float32) 112 | self.segmentation = np.zeros((len(self.v)), dtype=np.float32) 113 | with open(skinning_weight_path) as fp: 114 | for line in fp: 115 | if line[0] == '#': continue 116 | splitted = line.split(' ')[:-1] 117 | vertex_idx = int(splitted[0]) 118 | for i in range(0,len(splitted)-1,2): 119 | joint_name = splitted[1+i] 120 | joint_idx = [idx for idx,_ in enumerate(self.skeleton) if _['name'] == joint_name][0] 121 | weight = float(splitted[1+(i+1)]) 122 | self.skinning_weight[vertex_idx][joint_idx] = weight 123 | 124 | self.segmentation[vertex_idx] = np.argmax(self.skinning_weight[vertex_idx]) 125 | 126 | def load_global_pose(self, global_pose_path): 127 | # load global pose of mesh 128 | self.global_pose = np.zeros((len(self.skeleton),4,4), dtype=np.float32) 129 | with open(global_pose_path) as fp: 130 | for line in fp: 131 | if line[0] == '#': continue 132 | splitted = line.split(' ') 133 | joint_name = splitted[0] 134 | joint_idx = [i for i,_ in enumerate(self.skeleton) if _['name'] == joint_name][0] 135 | self.global_pose[joint_idx] = np.array([float(x) for x in splitted[1:-1]]).reshape(4,4) 136 | 137 | def load_local_pose(self, local_pose_path): 138 | # load local pose of mesh 139 | self.local_pose = np.zeros((len(self.skeleton),4,4), dtype=np.float32) 140 | with open(local_pose_path) as fp: 141 | for line in fp: 142 | if line[0] == '#': continue 143 | splitted = line.split(' ') 144 | joint_name = splitted[0] 145 | joint_idx = [i for i,_ in enumerate(self.skeleton) if _['name'] == joint_name][0] 146 | self.local_pose[joint_idx] = np.array([float(x) for x in splitted[1:-1]]).reshape(4,4) 147 | 148 | def load_global_pose_inv(self, global_pose_inv_path): 149 | # load global inv pose of mesh 150 | self.global_pose_inv = np.zeros((len(self.skeleton),4,4), dtype=np.float32) 151 | with open(global_pose_inv_path) as fp: 152 | for line in fp: 153 | if line[0] == '#': continue 154 | splitted = line.split(' ') 155 | joint_name = splitted[0] 156 | joint_idx = [i for i,_ in enumerate(self.skeleton) if _['name'] == joint_name][0] 157 | self.global_pose_inv[joint_idx] = np.array([float(x) for x in splitted[1:-1]]).reshape(4,4) 158 | 159 | 160 | -------------------------------------------------------------------------------- /common/utils/preprocessing.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 os 9 | import os.path as osp 10 | import cv2 11 | import numpy as np 12 | from config import cfg 13 | from utils.transforms import world2cam, cam2pixel 14 | from glob import glob 15 | 16 | def load_img(path, order='RGB'): 17 | 18 | # load 19 | img = cv2.imread(path, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION) 20 | if not isinstance(img, np.ndarray): 21 | raise IOError("Fail to read %s" % path) 22 | 23 | if order=='RGB': 24 | img = img[:,:,::-1].copy() 25 | 26 | img = img.astype(np.float32) 27 | return img 28 | 29 | def load_krt(path): 30 | # Load KRT file containing intrinsic and extrinsic camera parameters 31 | cameras = {} 32 | 33 | with open(path, "r") as f: 34 | while True: 35 | name = f.readline() 36 | if name == "": 37 | break 38 | 39 | intrin = [[float(x) for x in f.readline().split()] for i in range(3)] 40 | dist = [float(x) for x in f.readline().split()] 41 | extrin = [[float(x) for x in f.readline().split()] for i in range(3)] 42 | f.readline() 43 | 44 | cameras[name[:-1]] = { 45 | "intrin": np.array(intrin), 46 | "dist": np.array(dist), 47 | "extrin": np.array(extrin)} 48 | 49 | return cameras 50 | 51 | def get_bbox(joint_world, joint_valid, camrot, campos, focal, princpt): 52 | 53 | joint_cam = [] 54 | for i in range(len(joint_world)): 55 | joint_cam.append(world2cam(joint_world[i], camrot, campos)) 56 | joint_cam = np.array(joint_cam).reshape(-1,3) 57 | 58 | x_img, y_img, z_img = cam2pixel(joint_cam, focal, princpt) 59 | x_img = x_img[joint_valid[:,0]==1]; y_img = y_img[joint_valid[:,0]==1]; 60 | xmin = min(x_img); ymin = min(y_img); xmax = max(x_img); ymax = max(y_img); 61 | 62 | x_center = (xmin+xmax)/2.; width = xmax-xmin; 63 | xmin = x_center - 0.5*width*1.5 64 | xmax = x_center + 0.5*width*1.5 65 | 66 | y_center = (ymin+ymax)/2.; height = ymax-ymin; 67 | ymin = y_center - 0.5*height*1.5 68 | ymax = y_center + 0.5*height*1.5 69 | 70 | bbox = np.array([xmin, ymin, xmax, ymax]).astype(np.float32) 71 | 72 | return bbox 73 | 74 | 75 | def generate_patch_image(cvimg, bbox, do_flip, scale, rot, out_shape): 76 | img = cvimg.copy() 77 | img_height, img_width, img_channels = img.shape 78 | 79 | bb_c_x = float(bbox[0] + 0.5*bbox[2]) 80 | bb_c_y = float(bbox[1] + 0.5*bbox[3]) 81 | bb_width = float(bbox[2]) 82 | bb_height = float(bbox[3]) 83 | 84 | if do_flip: 85 | img = img[:, ::-1, :] 86 | bb_c_x = img_width - bb_c_x - 1 87 | 88 | trans = gen_trans_from_patch_cv(bb_c_x, bb_c_y, bb_width, bb_height, out_shape[1], out_shape[0], scale, rot) 89 | img_patch = cv2.warpAffine(img, trans, (int(out_shape[1]), int(out_shape[0])), flags=cv2.INTER_LINEAR) 90 | img_patch = img_patch.astype(np.float32) 91 | 92 | return img_patch 93 | 94 | def rotate_2d(pt_2d, rot_rad): 95 | x = pt_2d[0] 96 | y = pt_2d[1] 97 | sn, cs = np.sin(rot_rad), np.cos(rot_rad) 98 | xx = x * cs - y * sn 99 | yy = x * sn + y * cs 100 | return np.array([xx, yy], dtype=np.float32) 101 | 102 | def gen_trans_from_patch_cv(c_x, c_y, src_width, src_height, dst_width, dst_height, scale, rot, inv=False): 103 | # augment size with scale 104 | src_w = src_width * scale 105 | src_h = src_height * scale 106 | src_center = np.array([c_x, c_y], dtype=np.float32) 107 | 108 | # augment rotation 109 | rot_rad = np.pi * rot / 180 110 | src_downdir = rotate_2d(np.array([0, src_h * 0.5], dtype=np.float32), rot_rad) 111 | src_rightdir = rotate_2d(np.array([src_w * 0.5, 0], dtype=np.float32), rot_rad) 112 | 113 | dst_w = dst_width 114 | dst_h = dst_height 115 | dst_center = np.array([dst_w * 0.5, dst_h * 0.5], dtype=np.float32) 116 | dst_downdir = np.array([0, dst_h * 0.5], dtype=np.float32) 117 | dst_rightdir = np.array([dst_w * 0.5, 0], dtype=np.float32) 118 | 119 | src = np.zeros((3, 2), dtype=np.float32) 120 | src[0, :] = src_center 121 | src[1, :] = src_center + src_downdir 122 | src[2, :] = src_center + src_rightdir 123 | 124 | dst = np.zeros((3, 2), dtype=np.float32) 125 | dst[0, :] = dst_center 126 | dst[1, :] = dst_center + dst_downdir 127 | dst[2, :] = dst_center + dst_rightdir 128 | 129 | if inv: 130 | trans = cv2.getAffineTransform(np.float32(dst), np.float32(src)) 131 | else: 132 | trans = cv2.getAffineTransform(np.float32(src), np.float32(dst)) 133 | 134 | return trans 135 | 136 | def trans_point2d(pt_2d, trans): 137 | src_pt = np.array([pt_2d[0], pt_2d[1], 1.]).T 138 | dst_pt = np.dot(trans, src_pt) 139 | return dst_pt[0:2] 140 | 141 | 142 | -------------------------------------------------------------------------------- /common/utils/transforms.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 | import numpy as np 10 | from config import cfg 11 | 12 | def cam2pixel(cam_coord, f, c): 13 | x = cam_coord[..., 0] / (cam_coord[..., 2] + 1e-8) * f[0] + c[0] 14 | y = cam_coord[..., 1] / (cam_coord[..., 2] + 1e-8) * f[1] + c[1] 15 | z = cam_coord[..., 2] 16 | return x,y,z 17 | 18 | def pixel2cam(pixel_coord, f, c): 19 | x = (pixel_coord[..., 0] - c[0]) / f[0] * pixel_coord[..., 2] 20 | y = (pixel_coord[..., 1] - c[1]) / f[1] * pixel_coord[..., 2] 21 | z = pixel_coord[..., 2] 22 | return x,y,z 23 | 24 | def world2cam(world_coord, R, T): 25 | cam_coord = np.dot(R, world_coord - T) 26 | return cam_coord 27 | 28 | def forward_kinematics(skeleton, cur_joint_idx, local_pose, global_pose): 29 | 30 | child_id = skeleton[cur_joint_idx]['child_id'] 31 | if len(child_id) == 0: 32 | return 33 | 34 | for joint_id in child_id: 35 | global_pose[joint_id] = torch.mm(global_pose[cur_joint_idx], local_pose[joint_id]) 36 | forward_kinematics(skeleton, joint_id, local_pose, global_pose) 37 | 38 | def rigid_transform_3D(A, B): 39 | centroid_A = torch.mean(A,0) 40 | centroid_B = torch.mean(B,0) 41 | H = torch.mm((A - centroid_A).permute(1,0), B - centroid_B) 42 | 43 | U, s, V = torch.svd(H) 44 | 45 | R = torch.mm(V, U.permute(1,0)) 46 | if torch.det(R) < 0: 47 | V = torch.stack((V[:,0],V[:,1],-V[:,2]),1) 48 | #V[:,2] = -V[:,2] 49 | R = torch.mm(V, U.permute(1,0)) 50 | t = -torch.mm(R, centroid_A[:,None]) + centroid_B[:,None] 51 | t = t.view(3,1) 52 | return R, t 53 | 54 | def euler2mat(theta, to_4x4=False): 55 | 56 | assert theta.shape[-1] == 3 57 | 58 | original_shape = list(theta.shape) 59 | original_shape.append(3) 60 | 61 | theta = theta.view(-1, 3) 62 | theta_x = theta[:,0:1] 63 | theta_y = theta[:,1:2] 64 | theta_z = theta[:,2:3] 65 | 66 | R_x = torch.cat([\ 67 | torch.stack([torch.ones_like(theta_x), torch.zeros_like(theta_x), torch.zeros_like(theta_x)],2),\ 68 | torch.stack([torch.zeros_like(theta_x), torch.cos(theta_x), -torch.sin(theta_x)],2),\ 69 | torch.stack([torch.zeros_like(theta_x), torch.sin(theta_x), torch.cos(theta_x)],2)\ 70 | ],1) 71 | 72 | R_y = torch.cat([\ 73 | torch.stack([torch.cos(theta_y), torch.zeros_like(theta_y), torch.sin(theta_y)],2),\ 74 | torch.stack([torch.zeros_like(theta_y), torch.ones_like(theta_y), torch.zeros_like(theta_y)],2),\ 75 | torch.stack([-torch.sin(theta_y), torch.zeros_like(theta_y), torch.cos(theta_y)],2),\ 76 | ],1) 77 | 78 | R_z = torch.cat([\ 79 | torch.stack([torch.cos(theta_z), -torch.sin(theta_z), torch.zeros_like(theta_z)],2),\ 80 | torch.stack([torch.sin(theta_z), torch.cos(theta_z), torch.zeros_like(theta_z)],2),\ 81 | torch.stack([torch.zeros_like(theta_z), torch.zeros_like(theta_z), torch.ones_like(theta_z)],2),\ 82 | ],1) 83 | 84 | R = torch.bmm(R_z, torch.bmm( R_y, R_x )) 85 | 86 | if to_4x4: 87 | batch_size = R.shape[0] 88 | R = torch.cat([R,torch.zeros((batch_size,3,1)).cuda().float()],2) 89 | R = torch.cat([R,torch.cuda.FloatTensor([0,0,0,1])[None,None,:].repeat(batch_size,1,1)],1) # 0001 90 | original_shape[-2] = 4; original_shape[-1] = 4 91 | 92 | R = R.view(original_shape) 93 | return R 94 | 95 | def rgb2gray(rgb): 96 | r,g,b = rgb[0], rgb[1], rgb[2] 97 | gray = 0.2989*r + 0.5870*g + 0.1140*b 98 | return gray 99 | -------------------------------------------------------------------------------- /common/utils/vis.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 os 9 | import os.path as osp 10 | import cv2 11 | import numpy as np 12 | import matplotlib 13 | #matplotlib.use('tkagg') 14 | from mpl_toolkits.mplot3d import Axes3D 15 | import matplotlib.pyplot as plt 16 | import matplotlib as mpl 17 | from config import cfg 18 | from PIL import Image, ImageDraw 19 | 20 | def get_keypoint_rgb(skeleton): 21 | rgb_dict= {} 22 | for joint_id in range(len(skeleton)): 23 | joint_name = skeleton[joint_id]['name'] 24 | 25 | if joint_name.endswith('thumb_null'): 26 | rgb_dict[joint_name] = (255, 0, 0) 27 | elif joint_name.endswith('thumb3'): 28 | rgb_dict[joint_name] = (255, 51, 51) 29 | elif joint_name.endswith('thumb2'): 30 | rgb_dict[joint_name] = (255, 102, 102) 31 | elif joint_name.endswith('thumb1'): 32 | rgb_dict[joint_name] = (255, 153, 153) 33 | elif joint_name.endswith('thumb0'): 34 | rgb_dict[joint_name] = (255, 204, 204) 35 | elif joint_name.endswith('index_null'): 36 | rgb_dict[joint_name] = (0, 255, 0) 37 | elif joint_name.endswith('index3'): 38 | rgb_dict[joint_name] = (51, 255, 51) 39 | elif joint_name.endswith('index2'): 40 | rgb_dict[joint_name] = (102, 255, 102) 41 | elif joint_name.endswith('index1'): 42 | rgb_dict[joint_name] = (153, 255, 153) 43 | elif joint_name.endswith('middle_null'): 44 | rgb_dict[joint_name] = (255, 128, 0) 45 | elif joint_name.endswith('middle3'): 46 | rgb_dict[joint_name] = (255, 153, 51) 47 | elif joint_name.endswith('middle2'): 48 | rgb_dict[joint_name] = (255, 178, 102) 49 | elif joint_name.endswith('middle1'): 50 | rgb_dict[joint_name] = (255, 204, 153) 51 | elif joint_name.endswith('ring_null'): 52 | rgb_dict[joint_name] = (0, 128, 255) 53 | elif joint_name.endswith('ring3'): 54 | rgb_dict[joint_name] = (51, 153, 255) 55 | elif joint_name.endswith('ring2'): 56 | rgb_dict[joint_name] = (102, 178, 255) 57 | elif joint_name.endswith('ring1'): 58 | rgb_dict[joint_name] = (153, 204, 255) 59 | elif joint_name.endswith('pinky_null'): 60 | rgb_dict[joint_name] = (255, 0, 255) 61 | elif joint_name.endswith('pinky3'): 62 | rgb_dict[joint_name] = (255, 51, 255) 63 | elif joint_name.endswith('pinky2'): 64 | rgb_dict[joint_name] = (255, 102, 255) 65 | elif joint_name.endswith('pinky1'): 66 | rgb_dict[joint_name] = (255, 153, 255) 67 | else: 68 | rgb_dict[joint_name] = (230, 230, 0) 69 | """ 70 | elif joint_name.endswith('wrist'): 71 | elif joint_name.endswith('wrist_twist'): 72 | elif joint_name.endswith('forearm'): 73 | else: 74 | print('Unsupported joint name: ' + joint_name) 75 | assert 0 76 | """ 77 | 78 | return rgb_dict 79 | 80 | def vis_keypoints(img, kps, score, skeleton, filename, score_thr=0.4, line_width=3, circle_rad = 3): 81 | 82 | rgb_dict = get_keypoint_rgb(skeleton) 83 | _img = Image.fromarray(img.transpose(1,2,0).astype('uint8')) 84 | draw = ImageDraw.Draw(_img) 85 | for i in range(len(skeleton)): 86 | joint_name = skeleton[i]['name'] 87 | pid = skeleton[i]['parent_id'] 88 | parent_joint_name = skeleton[pid]['name'] 89 | 90 | kps_i = (kps[i][0].astype(np.int32), kps[i][1].astype(np.int32)) 91 | kps_pid = (kps[pid][0].astype(np.int32), kps[pid][1].astype(np.int32)) 92 | 93 | if score[i] > score_thr and score[pid] > score_thr and pid != -1: 94 | draw.line([(kps[i][0], kps[i][1]), (kps[pid][0], kps[pid][1])], fill=rgb_dict[parent_joint_name], width=line_width) 95 | if score[i] > score_thr: 96 | draw.ellipse((kps[i][0]-circle_rad, kps[i][1]-circle_rad, kps[i][0]+circle_rad, kps[i][1]+circle_rad), fill=rgb_dict[joint_name]) 97 | if score[pid] > score_thr and pid != -1: 98 | draw.ellipse((kps[pid][0]-circle_rad, kps[pid][1]-circle_rad, kps[pid][0]+circle_rad, kps[pid][1]+circle_rad), fill=rgb_dict[parent_joint_name]) 99 | 100 | _img.save(osp.join(cfg.vis_dir, filename)) 101 | 102 | 103 | def vis_3d_keypoints(kps_3d, score, skeleton, filename, score_thr=0.4, line_width=3, circle_rad=3): 104 | 105 | fig = plt.figure() 106 | ax = fig.add_subplot(111, projection='3d') 107 | rgb_dict = get_keypoint_rgb(skeleton) 108 | 109 | for i in range(len(skeleton)): 110 | joint_name = skeleton[i]['name'] 111 | pid = skeleton[i]['parent_id'] 112 | parent_joint_name = skeleton[pid]['name'] 113 | 114 | x = np.array([kps_3d[i,0], kps_3d[pid,0]]) 115 | y = np.array([kps_3d[i,1], kps_3d[pid,1]]) 116 | z = np.array([kps_3d[i,2], kps_3d[pid,2]]) 117 | 118 | if score[i] > score_thr and score[pid] > score_thr and pid != -1: 119 | ax.plot(x, z, -y, c = np.array(rgb_dict[parent_joint_name])/255., linewidth = line_width) 120 | if score[i] > score_thr: 121 | ax.scatter(kps_3d[i,0], kps_3d[i,2], -kps_3d[i,1], c = np.array(rgb_dict[joint_name]).reshape(1,3)/255., marker='o') 122 | if score[pid] > score_thr and pid != -1: 123 | ax.scatter(kps_3d[pid,0], kps_3d[pid,2], -kps_3d[pid,1], c = np.array(rgb_dict[parent_joint_name]).reshape(1,3)/255., marker='o') 124 | 125 | #plt.show() 126 | #cv2.waitKey(0) 127 | 128 | fig.savefig(osp.join(cfg.vis_dir, filename), dpi=fig.dpi) 129 | 130 | -------------------------------------------------------------------------------- /data/__pycache__/dataset.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/data/__pycache__/dataset.cpython-38.pyc -------------------------------------------------------------------------------- /data/dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 | import torch.utils.data 11 | import cv2 12 | from glob import glob 13 | import os.path as osp 14 | from config import cfg 15 | from utils.preprocessing import load_img, load_krt, get_bbox, generate_patch_image, gen_trans_from_patch_cv 16 | from utils.transforms import world2cam, cam2pixel 17 | from utils import mesh 18 | import pickle 19 | from PIL import Image, ImageDraw 20 | import random 21 | 22 | class Dataset(torch.utils.data.Dataset): 23 | def __init__(self, transform, mode): 24 | self.mode = mode 25 | self.img_path = '../data/images/subject_' + cfg.subject 26 | self.annot_path = '../data/annotations' 27 | self.hand_model_path = '../data/hand_model' 28 | 29 | if cfg.subject == '1': 30 | self.sequence_names = glob(osp.join(self.img_path, '00*')) # 00: right single hand, 01: left single hand, 02: double hands 31 | else: 32 | self.sequence_names = glob(osp.join(self.img_path, '*RT*')) # RT: right single hand, LT: left single hand, DH: double hands 33 | self.sequence_names = [name for name in self.sequence_names if osp.isdir(name)] 34 | self.sequence_names = [name for name in self.sequence_names if 'ROM' not in name] # 'ROM' exclude in training 35 | self.sequence_names = [x.split('/')[-1] for x in self.sequence_names] 36 | 37 | self.krt_path = osp.join(self.annot_path, 'KRT_512') # camera parameters 38 | 39 | self.obj_file_path = osp.join(self.hand_model_path, 'hand.obj') 40 | self.template_skeleton_path = osp.join(self.hand_model_path, 'skeleton.txt') 41 | self.template_skinning_weight_path = osp.join(self.hand_model_path, 'skinning_weight.txt') 42 | self.template_local_pose_path = osp.join(self.hand_model_path, 'local_pose.txt') 43 | self.template_global_pose_path = osp.join(self.hand_model_path, 'global_pose.txt') 44 | self.template_global_pose_inv_path = osp.join(self.hand_model_path, 'global_pose_inv.txt') 45 | 46 | self.joint_num = 22 47 | self.root_joint_idx = 21 48 | self.align_joint_idx = [8, 12, 16, 20, 21] 49 | self.non_rigid_joint_idx = [3,21] 50 | 51 | self.original_img_shape = (512, 334) # height, width 52 | self.transform = transform 53 | 54 | # load template mesh things 55 | self.mesh = mesh.Mesh(self.obj_file_path) 56 | self.mesh.load_skeleton(self.template_skeleton_path, self.joint_num) 57 | self.mesh.load_skinning_weight(self.template_skinning_weight_path) 58 | self.mesh.load_local_pose(self.template_local_pose_path) 59 | self.mesh.load_global_pose(self.template_global_pose_path) 60 | self.mesh.load_global_pose_inv(self.template_global_pose_inv_path) 61 | 62 | # camera load 63 | krt = load_krt(self.krt_path) 64 | self.all_cameras = krt.keys() 65 | self.selected_cameras = [x for x in self.all_cameras if x[:2] == "40"] # 40xx cameras: color cameras 66 | 67 | # compute view directions of each camera 68 | campos = {} 69 | camrot = {} 70 | focal = {} 71 | princpt = {} 72 | for cam in self.selected_cameras: 73 | campos[cam] = -np.dot(krt[cam]['extrin'][:3, :3].T, krt[cam]['extrin'][:3, 3]).astype(np.float32) 74 | camrot[cam] = np.array(krt[cam]['extrin'][:3, :3]).astype(np.float32) 75 | focal[cam] = krt[cam]['intrin'][:2, :2] 76 | focal[cam] = np.array([focal[cam][0][0], focal[cam][1][1]]).astype(np.float32) 77 | princpt[cam] = np.array(krt[cam]['intrin'][:2, 2]).astype(np.float32) 78 | self.campos = campos 79 | self.camrot = camrot 80 | self.focal = focal 81 | self.princpt = princpt 82 | 83 | # get info for all frames 84 | self.framelist = [] 85 | for seq_name in self.sequence_names: 86 | for cam in self.selected_cameras: 87 | img_path_list = glob(osp.join(self.img_path, seq_name, 'cam' + cam, '*.jpg')) 88 | for img_path in img_path_list: 89 | frame_idx = int(img_path.split('/')[-1][5:-4]) 90 | 91 | # load joint 3D world coordinates 92 | joint_path = osp.join(self.annot_path, 'keypoints', 'subject_' + cfg.subject, "keypoints{:04d}".format(frame_idx) + '.pts') 93 | if osp.isfile(joint_path): 94 | joint_coord, joint_valid = self.load_joint_coord(joint_path, 'right', self.mesh.skeleton) # only use right hand 95 | else: 96 | continue 97 | 98 | joint = {'world_coord': joint_coord, 'valid': joint_valid} 99 | frame = {'img_path': img_path, 'seq_name': seq_name, 'cam': cam, 'frame_idx': frame_idx, 'joint': joint} 100 | self.framelist.append(frame) 101 | 102 | def __len__(self): 103 | return len(self.framelist) 104 | 105 | def __getitem__(self, idx): 106 | frame = self.framelist[idx] 107 | img_path, cam, frame_idx, joint = frame['img_path'], frame['cam'], frame['frame_idx'], frame['joint'] 108 | joint_coord, joint_valid = joint['world_coord'], joint['valid'] 109 | 110 | # input data 111 | # bbox calculate 112 | bbox = get_bbox(joint_coord, joint_valid, self.camrot[cam], self.campos[cam], self.focal[cam], self.princpt[cam]) 113 | xmin, ymin, xmax, ymax = bbox 114 | xmin = max(xmin,0); ymin = max(ymin,0); xmax = min(xmax, self.original_img_shape[1]-1); ymax = min(ymax, self.original_img_shape[0]-1); 115 | bbox = np.array([xmin, ymin, xmax, ymax]) 116 | 117 | # image read 118 | img = load_img(img_path) 119 | xmin, ymin, xmax, ymax = bbox 120 | xmin, xmax = np.array([xmin, xmax])/self.original_img_shape[1]*img.shape[1]; ymin, ymax = np.array([ymin, ymax])/self.original_img_shape[0]*img.shape[0] 121 | bbox_img = np.array([xmin, ymin, xmax-xmin+1, ymax-ymin+1]) 122 | img = generate_patch_image(img, bbox_img, False, 1.0, 0.0, cfg.input_img_shape) 123 | input_img = self.transform(img)/255. 124 | 125 | 126 | target_depthmaps = []; cam_params = []; affine_transes = []; 127 | for cam in random.sample(self.selected_cameras, cfg.render_view_num): 128 | # bbox calculate 129 | bbox = get_bbox(joint_coord, joint_valid, self.camrot[cam], self.campos[cam], self.focal[cam], self.princpt[cam]) 130 | xmin, ymin, xmax, ymax = bbox 131 | xmin = max(xmin,0); ymin = max(ymin,0); xmax = min(xmax, self.original_img_shape[1]-1); ymax = min(ymax, self.original_img_shape[0]-1); 132 | bbox = np.array([xmin, ymin, xmax, ymax]) 133 | 134 | # depthmap read 135 | depthmap_path = osp.join(self.annot_path, 'depthmaps', 'subject_' + cfg.subject, "{:06d}".format(frame_idx), 'depthmap' + cam + '.pkl') 136 | with open(depthmap_path,'rb') as f: 137 | depthmap = pickle.load(f).astype(np.float32) 138 | xmin, ymin, xmax, ymax = bbox 139 | xmin, xmax = np.array([xmin, xmax])/self.original_img_shape[1]*depthmap.shape[1]; ymin, ymax = np.array([ymin, ymax])/self.original_img_shape[0]*depthmap.shape[0] 140 | bbox_depthmap = np.array([xmin, ymin, xmax-xmin+1, ymax-ymin+1]) 141 | depthmap = generate_patch_image(depthmap[:,:,None], bbox_depthmap, False, 1.0, 0.0, cfg.rendered_img_shape) 142 | target_depthmaps.append(self.transform(depthmap)) 143 | 144 | xmin, ymin, xmax, ymax = bbox 145 | affine_transes.append(gen_trans_from_patch_cv((xmin+xmax+1)/2., (ymin+ymax+1)/2., xmax-xmin+1, ymax-ymin+1, cfg.rendered_img_shape[1], cfg.rendered_img_shape[0], 1.0, 0.0).astype(np.float32)) 146 | cam_params.append({'camrot': self.camrot[cam], 'campos': self.campos[cam], 'focal': self.focal[cam], 'princpt': self.princpt[cam]}) 147 | 148 | inputs = {'img': input_img} 149 | targets = {'depthmap': target_depthmaps, 'joint': joint} 150 | meta_info = {'cam_param': cam_params, 'affine_trans': affine_transes} 151 | 152 | return inputs, targets, meta_info 153 | 154 | def load_joint_coord(self, joint_path, hand_type, skeleton): 155 | 156 | # create link between (joint_index in file, joint_name) 157 | # all the codes use joint index and name of 'skeleton.txt' 158 | db_joint_name = ['b_r_thumb_null', 'b_r_thumb3', 'b_r_thumb2', 'b_r_thumb1', 'b_r_index_null', 'b_r_index3', 'b_r_index2', 'b_r_index1', 'b_r_middle_null', 'b_r_middle3', 'b_r_middle2', 'b_r_middle1', 'b_r_ring_null', 'b_r_ring3', 'b_r_ring2', 'b_r_ring1', 'b_r_pinky_null', 'b_r_pinky3', 'b_r_pinky2', 'b_r_pinky1', 'b_r_wrist'] # joint names of 'keypointst****.pts' 159 | 160 | # load 3D world coordinates of joints 161 | joint_world = np.ones((len(skeleton),3),dtype=np.float32) 162 | joint_valid = np.zeros((len(skeleton),1),dtype=np.float32) 163 | with open(joint_path) as f: 164 | for line in f: 165 | parsed_line = line.split() 166 | parsed_line = [float(x) for x in parsed_line] 167 | joint_idx, x_world, y_world, z_world, score_sum, num_view = parsed_line 168 | joint_idx = int(joint_idx) # joint_idx of the file 169 | 170 | if hand_type == 'right' and joint_idx > 20: # 00: right hand, 21~41: left hand 171 | continue 172 | if hand_type == 'left' and joint_idx < 21: # 01: left hand, 0~20: right hand 173 | continue 174 | 175 | joint_name = db_joint_name[joint_idx] 176 | joint_idx = [i for i,_ in enumerate(skeleton) if _['name'] == joint_name][0] # joint_idx which follows 'skeleton.txt' 177 | 178 | joint_world[joint_idx] = np.array([x_world, y_world, z_world], dtype=np.float32) 179 | joint_valid[joint_idx] = 1 180 | 181 | return joint_world, joint_valid 182 | 183 | 184 | -------------------------------------------------------------------------------- /demo/demo.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 | from tqdm import tqdm 10 | import numpy as np 11 | import cv2 12 | import math 13 | import torch 14 | import torch.backends.cudnn as cudnn 15 | import sys 16 | import os 17 | import os.path as osp 18 | from torch.nn.parallel.data_parallel import DataParallel 19 | 20 | sys.path.insert(0, osp.join('..', 'main')) 21 | sys.path.insert(0, osp.join('..', 'data')) 22 | sys.path.insert(0, osp.join('..', 'common')) 23 | from config import cfg 24 | from utils import mesh 25 | from model import get_model 26 | 27 | def parse_args(): 28 | parser = argparse.ArgumentParser() 29 | parser.add_argument('--gpu', type=str, dest='gpu_ids') 30 | parser.add_argument('--test_epoch', type=str, dest='test_epoch') 31 | parser.add_argument('--subject', type=str, dest='subject') 32 | args = parser.parse_args() 33 | 34 | if not args.gpu_ids: 35 | assert 0, "Please set propoer gpu ids" 36 | 37 | if '-' in args.gpu_ids: 38 | gpus = args.gpu_ids.split('-') 39 | gpus[0] = int(gpus[0]) 40 | gpus[1] = int(gpus[1]) + 1 41 | args.gpu_ids = ','.join(map(lambda x: str(x), list(range(*gpus)))) 42 | 43 | assert args.test_epoch, 'Test epoch is required.' 44 | assert args.subject, 'Testing subject is required' 45 | return args 46 | 47 | # argument parsing 48 | args = parse_args() 49 | cfg.set_args(args.subject, args.gpu_ids) 50 | cudnn.benchmark = True 51 | 52 | # hand model settings 53 | joint_num = 22 54 | root_joint_idx = 21 55 | align_joint_idx = [8, 12, 16, 20, 21] 56 | non_rigid_joint_idx = [3,21] 57 | hand_model_path = '../data/hand_model' 58 | mesh = mesh.Mesh(osp.join(hand_model_path, 'hand.obj')) 59 | mesh.load_skeleton(osp.join(hand_model_path, 'skeleton.txt'), joint_num) # joint set is defined in here 60 | mesh.load_skinning_weight(osp.join(hand_model_path, 'skinning_weight.txt')) 61 | mesh.load_local_pose(osp.join(hand_model_path, 'local_pose.txt')) 62 | mesh.load_global_pose(osp.join(hand_model_path, 'global_pose.txt')) 63 | mesh.load_global_pose_inv(osp.join(hand_model_path, 'global_pose_inv.txt')) 64 | 65 | # load pre-trained DeepHandMesh 66 | model_path = './subject_' + args.subject + '/snapshot_' + args.test_epoch + '.pth.tar' 67 | assert os.path.exists(model_path), 'Cannot find model at ' + model_path 68 | model = get_model('test', mesh, root_joint_idx, align_joint_idx, non_rigid_joint_idx) 69 | model = DataParallel(model).cuda() 70 | ckpt = torch.load(model_path) 71 | model.load_state_dict(ckpt['network'], strict=False) 72 | model.eval() 73 | 74 | # forward and save output 75 | joint_euler = torch.zeros((1,joint_num,3)).float().cuda() 76 | joint_euler[0,8,2] = math.pi/2 77 | joint_euler[0,12,2] = math.pi/2 78 | joint_euler[0,16,2] = math.pi/2 79 | joint_euler[0,20,2] = math.pi/2 80 | with torch.no_grad(): 81 | out = model.module.decode(joint_euler) 82 | mesh.save_obj(out['mesh_out_refined'][0].cpu().numpy(), None, 'mesh.obj') 83 | 84 | -------------------------------------------------------------------------------- /main/__pycache__/config.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/main/__pycache__/config.cpython-38.pyc -------------------------------------------------------------------------------- /main/__pycache__/model.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/DeepHandMesh/efda66ee79fe59d38c989ffa5bc031b7e4c08074/main/__pycache__/model.cpython-38.pyc -------------------------------------------------------------------------------- /main/config.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 os 9 | import os.path as osp 10 | import sys 11 | import math 12 | import numpy as np 13 | 14 | class Config: 15 | ## input, output 16 | input_img_shape = (256,256) 17 | rendered_img_shape = (256,256) 18 | depth_min = 1 19 | depth_max = 99999 20 | render_view_num = 6 21 | backbone_img_feat_dim = 512 22 | id_code_dim = 32 23 | bone_step_size = 0.1 24 | 25 | ## model 26 | resnet_type = 50 # 18, 34, 50, 101, 152 27 | 28 | ## training config 29 | lr_dec_epoch = [30, 32] 30 | end_epoch = 35 31 | lr = 1e-4 32 | lr_dec_factor = 10 33 | train_batch_size = 8 34 | loss_penet_r_weight = 1 35 | loss_penet_nr_weight = 5 36 | loss_lap_weight = 5 37 | 38 | ## testing config 39 | test_batch_size = 1 40 | 41 | ## directory 42 | cur_dir = osp.dirname(os.path.abspath(__file__)) 43 | root_dir = osp.join(cur_dir, '..') 44 | data_dir = osp.join(root_dir, 'data') 45 | output_dir = osp.join(root_dir, 'output') 46 | model_dir = osp.join(output_dir, 'model_dump') 47 | vis_dir = osp.join(output_dir, 'vis') 48 | log_dir = osp.join(output_dir, 'log') 49 | result_dir = osp.join(output_dir, 'result') 50 | 51 | ## others 52 | num_thread = 40 53 | gpu_ids = '0' 54 | num_gpus = 1 55 | continue_train = False 56 | 57 | def set_args(self, subject, gpu_ids, continue_train=False): 58 | self.subject = subject 59 | self.gpu_ids = gpu_ids 60 | self.num_gpus = len(self.gpu_ids.split(',')) 61 | self.continue_train = continue_train 62 | os.environ["CUDA_VISIBLE_DEVICES"] = self.gpu_ids 63 | print('>>> Using GPU: {}'.format(self.gpu_ids)) 64 | 65 | self.model_dir = osp.join(self.model_dir, 'subject_' + str(self.subject)) 66 | self.vis_dir = osp.join(self.vis_dir, 'subject_' + str(self.subject)) 67 | self.log_dir = osp.join(self.log_dir, 'subject_' + str(self.subject)) 68 | self.result_dir = osp.join(self.result_dir, 'subject_' + str(self.subject)) 69 | 70 | cfg = Config() 71 | 72 | sys.path.insert(0, osp.join(cfg.root_dir, 'common')) 73 | from utils.dir import add_pypath, make_folder 74 | add_pypath(osp.join(cfg.data_dir)) 75 | make_folder(cfg.model_dir) 76 | make_folder(cfg.vis_dir) 77 | make_folder(cfg.log_dir) 78 | make_folder(cfg.result_dir) 79 | 80 | -------------------------------------------------------------------------------- /main/model.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 | import torch.nn as nn 10 | import torch.nn.functional as F 11 | from nets.module import BackboneNet, PoseNet, SkeletonRefineNet, SkinRefineNet 12 | #from nets.DiffableRenderer.DiffableRenderer import RenderLayer 13 | from nets.loss import DepthmapLoss, JointLoss, PenetLoss, LaplacianLoss 14 | from utils.transforms import euler2mat, forward_kinematics, rigid_transform_3D 15 | from config import cfg 16 | import math 17 | 18 | class Model(nn.Module): 19 | def __init__(self, backbone_net, pose_net, skeleton_refine_net, skin_refine_net, mesh, root_joint_idx, align_joint_idx, non_rigid_joint_idx): 20 | super(Model, self).__init__() 21 | 22 | # template mesh things 23 | self.mesh = mesh 24 | self.skeleton = self.mesh.skeleton 25 | 26 | # keypoint things 27 | self.joint_num = len(self.skeleton) 28 | self.root_joint_idx = root_joint_idx 29 | self.align_joint_idx = align_joint_idx 30 | self.non_rigid_joint_idx = non_rigid_joint_idx 31 | 32 | # identity-dependent things 33 | self.register_buffer('id_code', torch.randn(cfg.id_code_dim)) 34 | 35 | # modules 36 | self.backbone_net = backbone_net 37 | self.pose_net = pose_net 38 | self.skeleton_refine_net = skeleton_refine_net 39 | self.skin_refine_net = skin_refine_net 40 | #self.renderer = RenderLayer() 41 | 42 | # loss functions 43 | self.depthmap_loss = DepthmapLoss() 44 | self.joint_loss = JointLoss() 45 | self.penet_loss = PenetLoss(self.skeleton, self.mesh.segmentation, self.root_joint_idx, self.non_rigid_joint_idx) 46 | self.lap_loss = LaplacianLoss(self.mesh.v, self.mesh.vi) 47 | 48 | def get_mesh_data(self, batch_size): 49 | mesh ={} 50 | mesh['v'] = torch.from_numpy(self.mesh.v).cuda().float()[None,:,:].repeat(batch_size,1,1) # xyz coordinates of vertex (v_xyz x 3) 51 | mesh['vi'] = torch.from_numpy(self.mesh.vi).cuda().long() # vertex (xyz) indices of each mesh triangle (F x 3) 52 | mesh['vt'] = torch.from_numpy(self.mesh.vt).cuda().float() # uv coordinates of vertex (v_uv x 2) 53 | mesh['vti'] = torch.from_numpy(self.mesh.vti).cuda().long() # texture vertex (uv) indices of each mesh triangle (F x 3) 54 | mesh['local_pose'] = torch.from_numpy(self.mesh.local_pose).cuda().float() 55 | mesh['global_pose'] = torch.from_numpy(self.mesh.global_pose).cuda().float() 56 | mesh['global_pose_inv'] = torch.from_numpy(self.mesh.global_pose_inv).cuda().float() 57 | mesh['skinning_weight'] = torch.from_numpy(self.mesh.skinning_weight).cuda().float()[None,:,:].repeat(batch_size,1,1) 58 | mesh['segmentation'] = torch.from_numpy(self.mesh.segmentation).cuda().long() 59 | return mesh 60 | 61 | def forward(self, inputs, targets, meta_info, mode): 62 | input_img = inputs['img'] 63 | batch_size = input_img.shape[0] 64 | mesh = self.get_mesh_data(batch_size) 65 | align_joint_idx = torch.Tensor(self.align_joint_idx).long() 66 | 67 | # extract image feature 68 | img_feat = self.backbone_net(input_img) 69 | 70 | # estimate local euler angle change for each joint 71 | joint_euler = self.pose_net(img_feat) 72 | joint_rot_mat = euler2mat(joint_euler, to_4x4=True) 73 | 74 | # estimate skeleton corrective 75 | skeleton_corrective = self.skeleton_refine_net(self.id_code) 76 | mesh['local_pose_refined'] = mesh['local_pose'].clone() 77 | mesh['local_pose_refined'][:,:3,3] += skeleton_corrective 78 | mesh['global_pose_refined'] = [None for _ in range(self.joint_num)] 79 | mesh['global_pose_refined'][self.root_joint_idx] = mesh['global_pose'][self.root_joint_idx].clone() 80 | forward_kinematics(self.skeleton, self.root_joint_idx, mesh['local_pose_refined'], mesh['global_pose_refined']) 81 | mesh['global_pose_refined'] = torch.stack(mesh['global_pose_refined']) 82 | 83 | # rigid transform for root joint 84 | global_pose = [[None for _ in range(self.joint_num)] for _ in range(batch_size)] 85 | if mode == 'train': 86 | for i in range(batch_size): 87 | cur_sample = mesh['global_pose_refined'][align_joint_idx,:3,3].view(len(align_joint_idx),3) 88 | gt_sample = targets['joint']['world_coord'][i][align_joint_idx].view(len(align_joint_idx),3) 89 | R,t = rigid_transform_3D(cur_sample, gt_sample) 90 | mat = torch.cat((torch.cat((R,t),1), torch.cuda.FloatTensor([[0,0,0,1]]))) 91 | global_pose[i][self.root_joint_idx] = torch.mm(mat, mesh['global_pose_refined'][self.root_joint_idx]) 92 | elif mode == 'test': 93 | for i in range(batch_size): 94 | global_pose[i][self.root_joint_idx] = torch.eye(4).float().cuda() # use identity matrix in testing stage 95 | 96 | 97 | # forward kinematics 98 | joint_out = []; joint_trans_mat = []; 99 | for i in range(batch_size): 100 | forward_kinematics(self.skeleton, self.root_joint_idx, torch.bmm(mesh['local_pose_refined'], joint_rot_mat[i]), global_pose[i]) 101 | joint_out.append(torch.cat([global_pose[i][j][None,:3,3] for j in range(self.joint_num)],0)) 102 | joint_trans_mat.append(torch.cat([torch.mm(global_pose[i][j], mesh['global_pose_inv'][j,:,:])[None,:,:] for j in range(self.joint_num)])) 103 | joint_out = torch.cat(joint_out).view(batch_size,self.joint_num,3) 104 | joint_trans_mat = torch.cat(joint_trans_mat).view(batch_size,self.joint_num,4,4).permute(1,0,2,3) 105 | 106 | # estimate corrective vector 107 | pose_corrective, id_corrective = self.skin_refine_net(joint_euler.detach(), self.id_code[None,:].repeat(batch_size,1)) 108 | mesh_refined_xyz = mesh['v'] + pose_corrective + id_corrective 109 | 110 | # LBS 111 | mesh_refined_xyz1 = torch.cat([mesh_refined_xyz, torch.ones_like(mesh_refined_xyz[:,:,:1])],2) 112 | mesh_out_refined = sum([mesh['skinning_weight'][:,:,j,None]*torch.bmm(joint_trans_mat[j],mesh_refined_xyz1.permute(0,2,1)).permute(0,2,1)[:,:,:3] for j in range(self.joint_num)]) 113 | 114 | # loss functions in training stage 115 | if mode == 'train': 116 | # render depthmap 117 | cam_param, affine_trans = meta_info['cam_param'], meta_info['affine_trans'] 118 | depthmap_out_refined = [] 119 | for cid in range(len(cam_param)): 120 | rendered_depthmap_refined = self.renderer(mesh_out_refined, cam_param[cid], affine_trans[cid], mesh) 121 | depthmap_out_refined.append(rendered_depthmap_refined) 122 | 123 | # zero pose template mesh with correctives (for penet loss and test output) 124 | joint_trans_mat = torch.bmm(mesh['global_pose_refined'], mesh['global_pose_inv'])[:,None,:,:].repeat(1,batch_size,1,1) 125 | mesh_refined_v = mesh['v'] + pose_corrective + id_corrective 126 | mesh_refined_v = torch.cat([mesh_refined_v, torch.ones_like(mesh_refined_v[:,:,:1])],2) 127 | mesh_refined_v = sum([mesh['skinning_weight'][:,:,j,None]*torch.bmm(joint_trans_mat[j],mesh_refined_v.permute(0,2,1)).permute(0,2,1)[:,:,:3] for j in range(self.joint_num)]) 128 | 129 | loss = {} 130 | loss['joint'] = self.joint_loss(joint_out, targets['joint']['world_coord'], targets['joint']['valid']) 131 | loss['depthmap'] = self.depthmap_loss(depthmap_out_refined, targets['depthmap']) 132 | loss['penet'] = self.penet_loss(mesh['global_pose_refined'].detach(), mesh_refined_v.detach(), joint_out, mesh_out_refined) 133 | loss['lap'] = self.lap_loss(mesh_out_refined) * cfg.loss_lap_weight 134 | return loss 135 | 136 | # output in testing stage 137 | elif mode == 'test': 138 | out = {} 139 | out['joint_out'] = joint_out 140 | out['mesh_out_refined'] = mesh_out_refined 141 | return out 142 | 143 | def decode(self, joint_euler): 144 | batch_size = joint_euler.shape[0] 145 | mesh = self.get_mesh_data(batch_size) 146 | joint_rot_mat = euler2mat(joint_euler, to_4x4=True) 147 | 148 | # estimate skeleton corrective 149 | skeleton_corrective = self.skeleton_refine_net(self.id_code) 150 | mesh['local_pose_refined'] = mesh['local_pose'].clone() 151 | mesh['local_pose_refined'][:,:3,3] += skeleton_corrective 152 | mesh['global_pose_refined'] = [None for _ in range(self.joint_num)] 153 | mesh['global_pose_refined'][self.root_joint_idx] = mesh['global_pose'][self.root_joint_idx].clone() 154 | forward_kinematics(self.skeleton, self.root_joint_idx, mesh['local_pose_refined'], mesh['global_pose_refined']) 155 | mesh['global_pose_refined'] = torch.stack(mesh['global_pose_refined']) 156 | 157 | # rigid transform for root joint 158 | global_pose = [[None for _ in range(self.joint_num)] for _ in range(batch_size)] 159 | for i in range(batch_size): 160 | global_pose[i][self.root_joint_idx] = torch.eye(4).float().cuda() # use identity matrix in testing stage 161 | 162 | # forward kinematics 163 | joint_out = []; joint_trans_mat = []; 164 | for i in range(batch_size): 165 | forward_kinematics(self.skeleton, self.root_joint_idx, torch.bmm(mesh['local_pose_refined'], joint_rot_mat[i]), global_pose[i]) 166 | joint_out.append(torch.cat([global_pose[i][j][None,:3,3] for j in range(self.joint_num)],0)) 167 | joint_trans_mat.append(torch.cat([torch.mm(global_pose[i][j], mesh['global_pose_inv'][j,:,:])[None,:,:] for j in range(self.joint_num)])) 168 | joint_out = torch.cat(joint_out).view(batch_size,self.joint_num,3) 169 | joint_trans_mat = torch.cat(joint_trans_mat).view(batch_size,self.joint_num,4,4).permute(1,0,2,3) 170 | 171 | # estimate corrective vector 172 | pose_corrective, id_corrective = self.skin_refine_net(joint_euler.detach(), self.id_code[None,:].repeat(batch_size,1)) 173 | mesh_refined_xyz = mesh['v'] + pose_corrective + id_corrective 174 | 175 | # LBS 176 | mesh_refined_xyz1 = torch.cat([mesh_refined_xyz, torch.ones_like(mesh_refined_xyz[:,:,:1])],2) 177 | mesh_out_refined = sum([mesh['skinning_weight'][:,:,j,None]*torch.bmm(joint_trans_mat[j],mesh_refined_xyz1.permute(0,2,1)).permute(0,2,1)[:,:,:3] for j in range(self.joint_num)]) 178 | 179 | out = {} 180 | out['joint_out'] = joint_out 181 | out['mesh_out_refined'] = mesh_out_refined 182 | return out 183 | 184 | def init_weights(m): 185 | if type(m) == nn.ConvTranspose2d: 186 | nn.init.normal_(m.weight,std=0.001) 187 | elif type(m) == nn.Conv2d: 188 | nn.init.normal_(m.weight,std=0.001) 189 | nn.init.constant_(m.bias, 0) 190 | elif type(m) == nn.BatchNorm2d: 191 | nn.init.constant_(m.weight,1) 192 | nn.init.constant_(m.bias,0) 193 | elif type(m) == nn.Linear: 194 | nn.init.normal_(m.weight,std=0.01) 195 | nn.init.constant_(m.bias,0) 196 | 197 | def get_model(mode, mesh, root_joint_idx, align_joint_idx, non_rigid_joint_idx): 198 | backbone_net = BackboneNet() 199 | pose_net = PoseNet(mesh.skeleton) 200 | skeleton_refine_net = SkeletonRefineNet(mesh.skeleton) 201 | skin_refine_net = SkinRefineNet(mesh.skeleton, len(mesh.v)) 202 | 203 | if mode == 'train': 204 | backbone_net.init_weights() 205 | pose_net.apply(init_weights) 206 | skeleton_refine_net.apply(init_weights) 207 | skin_refine_net.apply(init_weights) 208 | 209 | model = Model(backbone_net, pose_net, skeleton_refine_net, skin_refine_net, mesh, root_joint_idx, align_joint_idx, non_rigid_joint_idx) 210 | return model 211 | 212 | -------------------------------------------------------------------------------- /main/test.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 | from tqdm import tqdm 10 | import numpy as np 11 | import cv2 12 | from config import cfg 13 | import torch 14 | from base import Tester 15 | import torch.backends.cudnn as cudnn 16 | 17 | def parse_args(): 18 | parser = argparse.ArgumentParser() 19 | parser.add_argument('--gpu', type=str, dest='gpu_ids') 20 | parser.add_argument('--test_epoch', type=str, dest='test_epoch') 21 | parser.add_argument('--subject', type=str, dest='subject') 22 | args = parser.parse_args() 23 | 24 | if not args.gpu_ids: 25 | assert 0, "Please set propoer gpu ids" 26 | 27 | if '-' in args.gpu_ids: 28 | gpus = args.gpu_ids.split('-') 29 | gpus[0] = int(gpus[0]) 30 | gpus[1] = int(gpus[1]) + 1 31 | args.gpu_ids = ','.join(map(lambda x: str(x), list(range(*gpus)))) 32 | 33 | assert args.test_epoch, 'Test epoch is required.' 34 | assert args.subject == '4', 'Testing only supports subject_4' 35 | return args 36 | 37 | def main(): 38 | 39 | args = parse_args() 40 | cfg.set_args(args.subject, args.gpu_ids) 41 | cudnn.benchmark = True 42 | 43 | tester = Tester(args.test_epoch) 44 | tester._make_batch_generator() 45 | tester._make_model() 46 | 47 | with torch.no_grad(): 48 | for itr, (inputs, targets, meta_info) in enumerate(tqdm(tester.batch_generator)): 49 | 50 | # forward 51 | out = tester.model(inputs, targets, meta_info, 'test') 52 | 53 | vis = True 54 | if vis: 55 | filename = str(itr) 56 | for bid in range(len(out['mesh_out_refined'])): 57 | img = inputs['img'][bid].detach().cpu().numpy().transpose(1,2,0)[:,:,::-1]*255 58 | cv2.imwrite(filename + '.jpg', img) 59 | tester.mesh.save_obj(out['mesh_out_refined'][bid].cpu().numpy(), None, filename + '_refined.obj') 60 | 61 | if __name__ == "__main__": 62 | main() 63 | -------------------------------------------------------------------------------- /main/train.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 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 | from config import cfg 10 | import torch 11 | from base import Trainer 12 | import torch.backends.cudnn as cudnn 13 | 14 | def parse_args(): 15 | parser = argparse.ArgumentParser() 16 | parser.add_argument('--gpu', type=str, dest='gpu_ids') 17 | parser.add_argument('--continue', dest='continue_train', action='store_true') 18 | parser.add_argument('--subject', type=str, dest='subject') 19 | args = parser.parse_args() 20 | 21 | if not args.gpu_ids: 22 | assert 0, "Please set propoer gpu ids" 23 | 24 | if '-' in args.gpu_ids: 25 | gpus = args.gpu_ids.split('-') 26 | gpus[0] = int(gpus[0]) 27 | gpus[1] = int(gpus[1]) + 1 28 | args.gpu_ids = ','.join(map(lambda x: str(x), list(range(*gpus)))) 29 | 30 | assert args.subject, 'Training subject is required' 31 | assert args.subject == '4', 'Training only supports subject_4' 32 | return args 33 | 34 | def main(): 35 | 36 | # argument parse and create log 37 | args = parse_args() 38 | cfg.set_args(args.subject, args.gpu_ids, args.continue_train) 39 | cudnn.benchmark = True 40 | 41 | trainer = Trainer() 42 | trainer._make_batch_generator() 43 | trainer._make_model() 44 | 45 | # train 46 | for epoch in range(trainer.start_epoch, cfg.end_epoch): 47 | 48 | trainer.set_lr(epoch) 49 | trainer.tot_timer.tic() 50 | trainer.read_timer.tic() 51 | for itr, (inputs, targets, meta_info) in enumerate(trainer.batch_generator): 52 | trainer.read_timer.toc() 53 | trainer.gpu_timer.tic() 54 | 55 | # forward 56 | trainer.optimizer.zero_grad() 57 | loss = trainer.model(inputs, targets, meta_info, 'train') 58 | loss = {k:loss[k].mean() for k in loss} 59 | 60 | # backward 61 | sum(loss[k] for k in loss).backward() 62 | trainer.optimizer.step() 63 | trainer.gpu_timer.toc() 64 | screen = [ 65 | 'Epoch %d/%d itr %d/%d:' % (epoch, cfg.end_epoch, itr, trainer.itr_per_epoch), 66 | 'lr: %g' % (trainer.get_lr()), 67 | 'speed: %.2f(%.2fs r%.2f)s/itr' % ( 68 | trainer.tot_timer.average_time, trainer.gpu_timer.average_time, trainer.read_timer.average_time), 69 | '%.2fh/epoch' % (trainer.tot_timer.average_time / 3600. * trainer.itr_per_epoch), 70 | ] 71 | screen += ['%s: %.4f' % ('loss_' + k, v.detach()) for k,v in loss.items()] 72 | trainer.logger.info(' '.join(screen)) 73 | 74 | trainer.tot_timer.toc() 75 | trainer.tot_timer.tic() 76 | trainer.read_timer.tic() 77 | 78 | # save model 79 | trainer.save_model({ 80 | 'epoch': epoch, 81 | 'network': trainer.model.state_dict(), 82 | 'optimizer': trainer.optimizer.state_dict(), 83 | }, epoch) 84 | 85 | 86 | if __name__ == "__main__": 87 | main() 88 | -------------------------------------------------------------------------------- /tool/download_3d_scans_decimated.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | root_path = './annotations/3D_scans_decimated' 4 | os.makedirs(root_path, exist_ok=True) 5 | os.chdir(root_path) 6 | 7 | # download 8 | url = 'https://github.com/facebookresearch/DeepHandMesh/releases/download/dataset/3D_scans_decimated.zip' 9 | cmd = 'wget ' + url 10 | os.system(cmd) 11 | cmd = 'unzip 3D_scans_decimated.zip' 12 | os.system(cmd) 13 | for name in ('aa', 'ab', 'ac', 'ad', 'ae', 'af', 'ag', 'ah', 'ai', 'aj', 'ak', 'al', 'am', 'an', 'ao', 'ap', 'aq', 'ar', 'as', 'at', 'au', 'av', 'aw', 'ax', 'ay', 'az', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'bg', 'bh', 'bi', 'bj', 'bk', 'bl', 'bm', 'bn', 'bo'): 14 | url = 'https://github.com/facebookresearch/DeepHandMesh/releases/download/dataset/3D_scans_decimated.tar.gz' + name + '.zip' 15 | cmd = 'wget ' + url 16 | os.system(cmd) 17 | 18 | # verify downloaded files 19 | cmd = 'python verify_download.py' 20 | os.system(cmd) 21 | 22 | # unzip downloaded files 23 | cmd = 'sh unzip.sh' 24 | os.system(cmd) 25 | 26 | -------------------------------------------------------------------------------- /tool/download_depthmaps.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | root_path = './annotations/depthmaps' 4 | os.makedirs(root_path, exist_ok=True) 5 | os.chdir(root_path) 6 | 7 | # download 8 | url = 'https://github.com/facebookresearch/DeepHandMesh/releases/download/dataset/depthmaps.zip' 9 | cmd = 'wget ' + url 10 | os.system(cmd) 11 | cmd = 'unzip depthmaps.zip' 12 | os.system(cmd) 13 | for name in ('aa', 'ab', 'ac', 'ad', 'ae', 'af', 'ag', 'ah', 'ai', 'aj', 'ak', 'al', 'am', 'an', 'ao', 'ap', 'aq', 'ar', 'as', 'at', 'au', 'av', 'aw', 'ax', 'ay', 'az'): 14 | url = 'https://github.com/facebookresearch/DeepHandMesh/releases/download/dataset/depthmaps.tar.gz' + name + '.zip' 15 | cmd = 'wget ' + url 16 | os.system(cmd) 17 | 18 | # verify downloaded files 19 | cmd = 'python verify_download.py' 20 | os.system(cmd) 21 | 22 | # unzip downloaded files 23 | cmd = 'sh unzip.sh' 24 | os.system(cmd) 25 | 26 | -------------------------------------------------------------------------------- /tool/download_images.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | root_path = './images' 4 | os.makedirs(root_path, exist_ok=True) 5 | os.chdir(root_path) 6 | 7 | # download 8 | url = 'https://github.com/facebookresearch/DeepHandMesh/releases/download/dataset/images.zip' 9 | cmd = 'wget ' + url 10 | os.system(cmd) 11 | cmd = 'unzip images.zip' 12 | os.system(cmd) 13 | for name in ('aa', 'ab', 'ac', 'ad', 'ae', 'af'): 14 | url = 'https://github.com/facebookresearch/DeepHandMesh/releases/download/dataset/images.tar.gz' + name + '.zip' 15 | cmd = 'wget ' + url 16 | os.system(cmd) 17 | 18 | # verify downloaded files 19 | cmd = 'python verify_download.py' 20 | os.system(cmd) 21 | 22 | # unzip downloaded files 23 | cmd = 'sh unzip.sh' 24 | os.system(cmd) 25 | 26 | -------------------------------------------------------------------------------- /tool/download_others.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | # download hand model 4 | root_path = './hand_model' 5 | os.makedirs(root_path, exist_ok=True) 6 | os.chdir(root_path) 7 | 8 | url = 'https://github.com/facebookresearch/DeepHandMesh/releases/download/dataset/hand_model.zip' 9 | cmd = 'wget ' + url 10 | os.system(cmd) 11 | cmd = 'unzip hand_model.zip' 12 | os.system(cmd) 13 | 14 | os.chdir('..') 15 | root_path = './annotations' 16 | os.makedirs(root_path, exist_ok=True) 17 | os.chdir(root_path) 18 | 19 | # download keypoints 20 | url = 'https://github.com/facebookresearch/DeepHandMesh/releases/download/dataset/keypoints.zip' 21 | cmd = 'wget ' + url 22 | os.system(cmd) 23 | cmd = 'unzip keypoints.zip' 24 | os.system(cmd) 25 | 26 | # download keypoints 27 | url = 'https://github.com/facebookresearch/DeepHandMesh/releases/download/dataset/KRT_512.zip' 28 | cmd = 'wget ' + url 29 | os.system(cmd) 30 | cmd = 'unzip KRT_512.zip' 31 | os.system(cmd) 32 | --------------------------------------------------------------------------------