├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── configs ├── pointnet.ini └── voxnet.ini ├── create_animation.py ├── data └── .gitignore ├── environment.yml ├── eval.py ├── models ├── __init__.py ├── losses.py ├── pointnet.py └── voxnet.py ├── mug0.gif ├── mug1.gif ├── pointcloud_dataset.py ├── train_val.py ├── utils.py └── voxel_dataset.py /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/vim,linux,macos,python,pycharm 3 | 4 | ### Linux ### 5 | *~ 6 | 7 | # temporary files which can be created if a process still has a handle open of a deleted file 8 | .fuse_hidden* 9 | 10 | # KDE directory preferences 11 | .directory 12 | 13 | # Linux trash folder which might appear on any partition or disk 14 | .Trash-* 15 | 16 | # .nfs files are created when an open file is removed but is still being accessed 17 | .nfs* 18 | 19 | ### macOS ### 20 | # General 21 | .DS_Store 22 | .AppleDouble 23 | .LSOverride 24 | 25 | # Icon must end with two \r 26 | Icon 27 | 28 | # Thumbnails 29 | ._* 30 | 31 | # Files that might appear in the root of a volume 32 | .DocumentRevisions-V100 33 | .fseventsd 34 | .Spotlight-V100 35 | .TemporaryItems 36 | .Trashes 37 | .VolumeIcon.icns 38 | .com.apple.timemachine.donotpresent 39 | 40 | # Directories potentially created on remote AFP share 41 | .AppleDB 42 | .AppleDesktop 43 | Network Trash Folder 44 | Temporary Items 45 | .apdisk 46 | 47 | ### PyCharm ### 48 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 49 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 50 | 51 | # User-specific stuff 52 | .idea/**/workspace.xml 53 | .idea/**/tasks.xml 54 | .idea/**/usage.statistics.xml 55 | .idea/**/dictionaries 56 | .idea/**/shelf 57 | 58 | # Generated files 59 | .idea/**/contentModel.xml 60 | 61 | # Sensitive or high-churn files 62 | .idea/**/dataSources/ 63 | .idea/**/dataSources.ids 64 | .idea/**/dataSources.local.xml 65 | .idea/**/sqlDataSources.xml 66 | .idea/**/dynamic.xml 67 | .idea/**/uiDesigner.xml 68 | .idea/**/dbnavigator.xml 69 | 70 | # Gradle 71 | .idea/**/gradle.xml 72 | .idea/**/libraries 73 | 74 | # Gradle and Maven with auto-import 75 | # When using Gradle or Maven with auto-import, you should exclude module files, 76 | # since they will be recreated, and may cause churn. Uncomment if using 77 | # auto-import. 78 | # .idea/modules.xml 79 | # .idea/*.iml 80 | # .idea/modules 81 | 82 | # CMake 83 | cmake-build-*/ 84 | 85 | # Mongo Explorer plugin 86 | .idea/**/mongoSettings.xml 87 | 88 | # File-based project format 89 | *.iws 90 | 91 | # IntelliJ 92 | out/ 93 | 94 | # mpeltonen/sbt-idea plugin 95 | .idea_modules/ 96 | 97 | # JIRA plugin 98 | atlassian-ide-plugin.xml 99 | 100 | # Cursive Clojure plugin 101 | .idea/replstate.xml 102 | 103 | # Crashlytics plugin (for Android Studio and IntelliJ) 104 | com_crashlytics_export_strings.xml 105 | crashlytics.properties 106 | crashlytics-build.properties 107 | fabric.properties 108 | 109 | # Editor-based Rest Client 110 | .idea/httpRequests 111 | 112 | # Android studio 3.1+ serialized cache file 113 | .idea/caches/build_file_checksums.ser 114 | 115 | ### PyCharm Patch ### 116 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 117 | 118 | # *.iml 119 | # modules.xml 120 | # .idea/misc.xml 121 | # *.ipr 122 | 123 | # Sonarlint plugin 124 | .idea/sonarlint 125 | 126 | ### Python ### 127 | # Byte-compiled / optimized / DLL files 128 | __pycache__/ 129 | *.py[cod] 130 | *$py.class 131 | 132 | # C extensions 133 | *.so 134 | 135 | # Distribution / packaging 136 | .Python 137 | build/ 138 | develop-eggs/ 139 | dist/ 140 | downloads/ 141 | eggs/ 142 | .eggs/ 143 | lib/ 144 | lib64/ 145 | parts/ 146 | sdist/ 147 | var/ 148 | wheels/ 149 | *.egg-info/ 150 | .installed.cfg 151 | *.egg 152 | MANIFEST 153 | 154 | # PyInstaller 155 | # Usually these files are written by a python script from a template 156 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 157 | *.manifest 158 | *.spec 159 | 160 | # Installer logs 161 | pip-log.txt 162 | pip-delete-this-directory.txt 163 | 164 | # Unit test / coverage reports 165 | htmlcov/ 166 | .tox/ 167 | .nox/ 168 | .coverage 169 | .coverage.* 170 | .cache 171 | nosetests.xml 172 | coverage.xml 173 | *.cover 174 | .hypothesis/ 175 | .pytest_cache/ 176 | 177 | # Translations 178 | *.mo 179 | *.pot 180 | 181 | # Django stuff: 182 | *.log 183 | local_settings.py 184 | db.sqlite3 185 | 186 | # Flask stuff: 187 | instance/ 188 | .webassets-cache 189 | 190 | # Scrapy stuff: 191 | .scrapy 192 | 193 | # Sphinx documentation 194 | docs/_build/ 195 | 196 | # PyBuilder 197 | target/ 198 | 199 | # Jupyter Notebook 200 | .ipynb_checkpoints 201 | 202 | # IPython 203 | profile_default/ 204 | ipython_config.py 205 | 206 | # pyenv 207 | .python-version 208 | 209 | # celery beat schedule file 210 | celerybeat-schedule 211 | 212 | # SageMath parsed files 213 | *.sage.py 214 | 215 | # Environments 216 | .env 217 | .venv 218 | env/ 219 | venv/ 220 | ENV/ 221 | env.bak/ 222 | venv.bak/ 223 | 224 | # Spyder project settings 225 | .spyderproject 226 | .spyproject 227 | 228 | # Rope project settings 229 | .ropeproject 230 | 231 | # mkdocs documentation 232 | /site 233 | 234 | # mypy 235 | .mypy_cache/ 236 | .dmypy.json 237 | dmypy.json 238 | 239 | # Pyre type checker 240 | .pyre/ 241 | 242 | ### Python Patch ### 243 | .venv/ 244 | 245 | ### Python.VirtualEnv Stack ### 246 | # Virtualenv 247 | # http://iamzed.com/2009/05/07/a-primer-on-virtualenv/ 248 | [Bb]in 249 | [Ii]nclude 250 | [Ll]ib 251 | [Ll]ib64 252 | [Ll]ocal 253 | [Ss]cripts 254 | pyvenv.cfg 255 | pip-selfcheck.json 256 | 257 | ### Vim ### 258 | # Swap 259 | [._]*.s[a-v][a-z] 260 | [._]*.sw[a-p] 261 | [._]s[a-rt-v][a-z] 262 | [._]ss[a-gi-z] 263 | [._]sw[a-p] 264 | 265 | # Session 266 | Session.vim 267 | 268 | # Temporary 269 | .netrwhist 270 | # Auto-generated tag files 271 | tags 272 | # Persistent undo 273 | [._]*.un~ 274 | 275 | 276 | # End of https://www.gitignore.io/api/vim,linux,macos,python,pycharm -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [8 Sept 2024] I am aware the data download links are broken. the fix for this is being tracked in [this issue](https://github.com/samarth-robo/contactdb_prediction/issues/7). 2 | 3 | # [ContactDB: Analyzing and Predicting Grasp Contact via Thermal Imaging](https://contactdb.cc.gatech.edu) 4 | 5 | [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/contactdb-analyzing-and-predicting-grasp/human-grasp-contact-prediction-on-contactdb)](https://paperswithcode.com/sota/human-grasp-contact-prediction-on-contactdb?p=contactdb-analyzing-and-predicting-grasp) 6 | 7 | This repository contains code to analyze and predict contact maps for human grasping, presented in the paper 8 | 9 | [ContactDB: Analyzing and Predicting Grasp Contact via Thermal Imaging](https://contactdb.cc.gatech.edu) - [Samarth Brahmbhatt](https://samarth-robo.github.io/), [Cusuh Ham](https://cusuh.github.io/), [Charles C. Kemp](http://ckemp.bme.gatech.edu/), and [James Hays](https://www.cc.gatech.edu/~hays/), CVPR 2019 10 | 11 | [Paper (CVPR 2019 Oral)](https://arxiv.org/abs/1904.06830) | [Explore the dataset](https://contactdb.cc.gatech.edu/contactdb_explorer.html) | Poster | Slides 12 | 13 | Please see [contactdb_utils](https://github.com/samarth-robo/contactdb_utils) for access to raw ContactDB data, and code to process it; [analysis branch](https://github.com/samarth-robo/contactdb_prediction/tree/analysis) for code to generate various analysis graphs from the paper. 14 | 15 | ## Setup 16 | 1. Download and install [Miniconda](https://docs.conda.io/en/latest/miniconda.html) (Python 3.x version). 17 | 2. Download this repository: `git clone https://github.com/samarth-robo/contactdb_prediction.git`. Commands for the following steps should be executed from the `contactdb_prediction` directory. 18 | 2. Create the `contactdb_prediction` environment: `conda create env -f environment.yml`, and activate it: `source activate contactdb_prediction`. 19 | 3. Download the preprocessed contact maps from [this Dropbox link](https://www.dropbox.com/sh/x5ivxw75tvf6tax/AADXw7KRWbH3eEofbbr6NQQga?dl=0) (17.9 GB). If the download location is `CONTACTDB_DATA_DIR`, make a symlink to it: `ln -s CONTACTDB_DATA_DIR data/voxelized_meshes`. 20 | 4. Download the trained models from [this Dropbox link](https://www.dropbox.com/sh/3kvyhin9030mdzo/AAC_eYOVAvXMRhsAJsDlL_soa?dl=0) (700 MB). If the download location is `CONTACTDB_MODELS_DIR`, make a symlink to it: `ln -s CONTACTDB_MODELS_DIR data/checkpoints`. 21 | 5. (Optional, for comparison purposes): Download the predicted contact maps from [this Dropbox link](https://www.dropbox.com/sh/zrpgtoycbik0iq3/AAAHMyzs9Lc2kH8UPZttRCmGa?dl=0). 22 | 23 | ## Predicting Contact Maps 24 | We propose two methods to make diverse contact map predictions: [DiverseNet](http://openaccess.thecvf.com/content_cvpr_2018/papers/Firman_DiverseNet_When_One_CVPR_2018_paper.pdf) and [Stochastic Multiple Choice Learning (sMCL)](https://papers.nips.cc/paper/6270-stochastic-multiple-choice-learning-for-training-diverse-deep-ensembles). This branch has code for the **diversenet models**. Checkout the [smcl](https://github.com/samarth-robo/contactdb_prediction/tree/smcl) branch for sMCL code. 25 | 26 | Predict contact maps for the 'use' instruction, using the voxel grid 3D representation: 27 | 28 | ``` 29 | $ python eval.py --instruction use --config configs/voxnet.ini --checkpoint data/checkpoints/use_voxnet_diversenet_release/checkpoint_model_86_val_loss\=0.01107167.pth 30 | pan error = 0.0512 31 | mug error = 0.0706 32 | wine_glass error = 0.1398 33 | ``` 34 | 35 | You can add the `--show object ` flag to show the 10 diverse predictions: 36 | ``` 37 | $ python eval.py --instruction use --config configs/voxnet.ini --checkpoint data/checkpoints/use_voxnet_diversenet_release/checkpoint_model_86_val_loss\=0.01107167.pth --show_object mug 38 | mug error = 0.0706 39 | ``` 40 | 41 | 42 | In general, the command is 43 | 44 | `python eval.py --instruction --config --checkpoint ` 45 | 46 | Use the following checkpoints: 47 | 48 | | Method | Checkpoint | 49 | |:------------------:|:-------------------------------------------------------------------------------------------------:| 50 | | Use - VoxNet | data/checkpoints/use_voxnet_diversenet_release/checkpoint_model_86_val_loss\=0.01107167.pth | 51 | | Use - PointNet | data/checkpoints/use_pointnet_diversenet_release/checkpoint_model_29_val_loss\=0.6979221.pth | 52 | | Handoff - VoxNet | data/checkpoints/handoff_voxnet_diversenet_release/checkpoint_model_167_val_loss\=0.01268427.pth | 53 | | Handoff - PointNet | data/checkpoints/handoff_pointnet_diversenet_release/checkpoint_model_745_val_loss\=0.5969936.pth | 54 | 55 | ## Training your own models 56 | Start the [`visdom`](https://github.com/facebookresearch/visdom) server 57 | ``` 58 | $ source activate contactdb_prediction 59 | $ visdom 60 | ``` 61 | 62 | The base training command is 63 | 64 | `python train_val.py --instruction --config [--device --checkpoint_dir --data_dir ]` 65 | 66 | ## Citation 67 | ``` 68 | @inproceedings{brahmbhatt2018contactdb, 69 | title={{ContactDB: Analyzing and Predicting Grasp Contact via Thermal Imaging}}, 70 | author={Samarth Brahmbhatt and Cusuh Ham and Charles C. Kemp and James Hays}, 71 | booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, 72 | year={2019}, 73 | note={\url{https://contactdb.cc.gatech.edu}} 74 | } 75 | ``` 76 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/samarth-robo/contactdb_prediction/3d39fccb039854af0cfd0c7c1f96ccd68dcbffe0/__init__.py -------------------------------------------------------------------------------- /configs/pointnet.ini: -------------------------------------------------------------------------------- 1 | [hyperparams] 2 | n_points = 3000 3 | random_rotation = 180 4 | random_scale = 0.4 5 | n_ensemble = 10 6 | diverse_beta = 1 7 | pos_weight = 10 8 | droprate = 0 9 | lr_step_size = 1000 10 | lr_gamma = 0.1 11 | 12 | [optim] 13 | batch_size = 5 14 | max_epochs = 1000 15 | val_interval = 1 16 | weight_decay = 0.0005 17 | base_lr = 0.1 18 | momentum = 0.9 19 | 20 | [misc] 21 | log_interval = 20 22 | shuffle = yes 23 | num_workers = 4 24 | -------------------------------------------------------------------------------- /configs/voxnet.ini: -------------------------------------------------------------------------------- 1 | [hyperparams] 2 | grid_size = 64 3 | random_rotation = 180 4 | n_ensemble = 10 5 | diverse_beta = 1 6 | pos_weight = 10 7 | droprate = 0.2 8 | lr_step_size = 1000 9 | lr_gamma = 0.1 10 | 11 | [optim] 12 | batch_size = 5 13 | max_epochs = 1000 14 | val_interval = 1 15 | weight_decay = 0.0005 16 | base_lr = 0.1 17 | momentum = 0.9 18 | 19 | [misc] 20 | log_interval = 20 21 | shuffle = yes 22 | num_workers = 4 23 | -------------------------------------------------------------------------------- /create_animation.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This script generates screenshots of the object rotating around the up vector 3 | in the animation_images directory. 4 | You can upload them to online services like https://ezgif.com/maker 5 | to create animation GIFs 6 | ''' 7 | 8 | import os 9 | import open3d 10 | import numpy as np 11 | from utils import texture_proc 12 | import transforms3d.euler as txe 13 | from IPython.core.debugger import set_trace 14 | import matplotlib.pyplot as plt 15 | import pickle 16 | osp = os.path 17 | 18 | 19 | def animate(geomi, suffix=None): 20 | # adjust this transform as needed 21 | T = np.eye(4) 22 | T[:3, :3] = txe.euler2mat(np.deg2rad(-90), np.deg2rad(0), np.deg2rad(0)) 23 | geom.transform(T) 24 | 25 | animate.count = -1 26 | animate.step = 50.0 # simulates mouse cursor movement by 50 pixels 27 | animate.radian_per_pixel = 0.003 28 | 29 | def move_forward(vis): 30 | glb = animate 31 | ctr = vis.get_view_control() 32 | ro = vis.get_render_option() 33 | ro.point_size = 25.0 34 | if glb.count >= 0: 35 | image = vis.capture_screen_float_buffer(False) 36 | im_filename = osp.join('animation_images', 37 | 'image_{:03d}'.format(glb.count)) 38 | if suffix is not None: 39 | im_filename = '{:s}_{:s}'.format(im_filename, str(suffix)) 40 | im_filename += '.png' 41 | plt.imsave(im_filename, np.asarray(image)) 42 | 43 | if np.rad2deg(glb.radian_per_pixel * glb.step * glb.count) >= 360.0: 44 | vis.register_animation_callback(None) 45 | 46 | ctr.rotate(glb.step, 0) 47 | else: 48 | # no effect, adjust as needed. Higher values cause the view to zoom out 49 | ctr.scale(1) 50 | glb.count += 1 51 | 52 | open3d.draw_geometries_with_animation_callback([geom], move_forward) 53 | 54 | 55 | if __name__ == '__main__': 56 | MESH = True 57 | # for a textured mesh model (e.g. ContactDB contactmap) 58 | if MESH: 59 | filename = 'data/contactdb_contactmaps/42_handoff_cylinder_large.ply' 60 | filename = osp.expanduser(filename) 61 | geom = open3d.read_triangle_mesh(filename) 62 | geom.compute_vertex_normals() 63 | geom.compute_triangle_normals() 64 | 65 | c = np.asarray(geom.vertex_colors)[:, 0] 66 | c = texture_proc(c) 67 | c = plt.cm.inferno(c)[:, :3] 68 | geom.vertex_colors = open3d.Vector3dVector(c) 69 | animate(geom) 70 | else: # for the voxelgrid and pointcloud predictions made by ContactDB models 71 | filename = 'data/contactdb_predictions/camerav2_use_voxnet_diversenet_preds.pkl' 72 | filename = osp.expanduser(filename) 73 | with open(filename, 'rb') as f: 74 | d = pickle.load(f) 75 | cmap = np.asarray([[0, 0, 1], [1, 0, 0]]) 76 | z, y, x = np.nonzero(d['geom'][0]) 77 | pts = np.vstack((x, y, z)).T 78 | pred_idxs = [0, 4, 9] 79 | #pred_idxs = range(len(d['tex_preds'])) 80 | for pred_idx in pred_idxs: 81 | print(pred_idx) 82 | tex_pred = np.argmax(d['tex_preds'][pred_idx], axis=0) 83 | tex_pred = tex_pred[z, y, x] 84 | tex_pred = cmap[tex_pred] 85 | geom = open3d.PointCloud() 86 | geom.points = open3d.Vector3dVector(pts) 87 | geom.colors = open3d.Vector3dVector(tex_pred) 88 | animate(geom, pred_idx) 89 | #open3d.draw_geometries([geom]) 90 | -------------------------------------------------------------------------------- /data/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /environment.yml: -------------------------------------------------------------------------------- 1 | name: contact_heatmaps_ml 2 | 3 | channels: 4 | - conda-forge 5 | - pytorch 6 | - open3d-admin 7 | 8 | dependencies: 9 | - python=3.6.6 10 | - open3d 11 | - trimesh 12 | - pytorch=0.4.1 13 | - torchvision 14 | - matplotlib 15 | - ignite 16 | - pip 17 | - pip: 18 | - visdom 19 | - transforms3d 20 | -------------------------------------------------------------------------------- /eval.py: -------------------------------------------------------------------------------- 1 | from models.voxnet import DiverseVoxNet as VoxNet 2 | from models.pointnet import DiversePointNet as PointNet 3 | from voxel_dataset import VoxelDataset 4 | from pointcloud_dataset import PointCloudDataset 5 | from models.losses import DiverseLoss 6 | 7 | import numpy as np 8 | import open3d 9 | import os 10 | import torch 11 | from torch.utils.data import DataLoader 12 | import argparse 13 | import configparser 14 | import pickle 15 | from IPython.core.debugger import set_trace 16 | osp = os.path 17 | 18 | def show_pointcloud_texture(geom, tex_preds): 19 | cmap = np.asarray([[0, 0, 1], [1, 0, 0]]) 20 | x, y, z, scale = geom 21 | pts = np.vstack((x, y, z)).T * scale[0] 22 | for tex_pred in tex_preds: 23 | pc = open3d.PointCloud() 24 | pc.points = open3d.Vector3dVector(pts) 25 | tex_pred = np.argmax(tex_pred, axis=0) 26 | tex_pred = cmap[tex_pred] 27 | pc.colors = open3d.Vector3dVector(tex_pred) 28 | open3d.draw_geometries([pc]) 29 | 30 | 31 | def show_voxel_texture(geom, tex_preds): 32 | cmap = np.asarray([[0, 0, 1], [1, 0, 0]]) 33 | z, y, x = np.nonzero(geom[0]) 34 | pts = np.vstack((x, y, z)).T 35 | for tex_pred in tex_preds: 36 | tex_pred = np.argmax(tex_pred, axis=0) 37 | tex_pred = tex_pred[z, y, x] 38 | tex_pred = cmap[tex_pred] 39 | pc = open3d.PointCloud() 40 | pc.points = open3d.Vector3dVector(pts) 41 | pc.colors = open3d.Vector3dVector(tex_pred) 42 | open3d.draw_geometries([pc]) 43 | 44 | 45 | def eval(data_dir, instruction, checkpoint_filename, config_filename, device_id, 46 | test_only=False, show_object=None, save_preds=False): 47 | # config 48 | config = configparser.ConfigParser() 49 | config.read(config_filename) 50 | droprate = config['hyperparams'].getfloat('droprate') 51 | 52 | # cuda 53 | if 'CUDA_VISIBLE_DEVICES' not in os.environ: 54 | os.environ['CUDA_VISIBLE_DEVICES'] = str(device_id) 55 | else: 56 | devices = os.environ['CUDA_VISIBLE_DEVICES'] 57 | devices = devices.split(',')[device_id] 58 | os.environ['CUDA_VISIBLE_DEVICES'] = devices 59 | device = 'cuda:0' 60 | 61 | # load checkpoint 62 | checkpoint = torch.load(checkpoint_filename) 63 | 64 | # create model 65 | model_name = osp.split(config_filename)[1].split('.')[0] 66 | kwargs = dict(data_dir=data_dir, instruction=instruction, train=False, 67 | random_rotation=0, n_ensemble=-1, test_only=test_only) 68 | if 'voxnet' in model_name: 69 | model = VoxNet(n_ensemble=checkpoint.n_ensemble, droprate=droprate) 70 | model.voxnet.load_state_dict(checkpoint.voxnet.state_dict()) 71 | grid_size = config['hyperparams'].getint('grid_size') 72 | dset = VoxelDataset(grid_size=grid_size, **kwargs) 73 | elif 'pointnet' in model_name: 74 | model = PointNet(n_ensemble=checkpoint.n_ensemble, droprate=droprate) 75 | model.pointnet.load_state_dict(checkpoint.pointnet.state_dict()) 76 | n_points = config['hyperparams'].getint('n_points') 77 | dset = PointCloudDataset(n_points=n_points, random_scale=0, **kwargs) 78 | else: 79 | raise NotImplementedError 80 | if 'pointnet' not in model_name: 81 | model.eval() 82 | model.to(device=device) 83 | 84 | loss_fn = DiverseLoss(train=False, eval_mode=True) 85 | 86 | # eval loop! 87 | dloader = DataLoader(dset) 88 | for batch_idx, batch in enumerate(dloader): 89 | object_name = list(dset.filenames.keys())[batch_idx] 90 | if show_object is not None: 91 | if object_name != show_object: 92 | continue 93 | geom, tex_targs = batch 94 | geom = geom.to(device=device) 95 | tex_targs = tex_targs.to(device=device) 96 | with torch.no_grad(): 97 | tex_preds = model(geom) 98 | 99 | loss, match_indices = loss_fn(tex_preds, tex_targs) 100 | print('{:s} error = {:.4f}'.format(object_name, loss.item())) 101 | 102 | geom = geom.cpu().numpy().squeeze() 103 | tex_preds = tex_preds.cpu().numpy().squeeze() 104 | match_indices = match_indices.cpu().numpy().squeeze() 105 | tex_targs = tex_targs.cpu().numpy().squeeze() 106 | 107 | if (save_preds): 108 | output_data = { 109 | 'checkpoint_filename': checkpoint_filename, 110 | 'geom': geom, 111 | 'tex_preds': tex_preds, 112 | 'match_indices': match_indices, 113 | 'tex_targs': tex_targs} 114 | output_filename = '{:s}_{:s}_{:s}_diversenet_preds.pkl'.format(object_name, 115 | instruction, model_name) 116 | with open(output_filename, 'wb') as f: 117 | pickle.dump(output_data, f) 118 | print('{:s} saved'.format(output_filename)) 119 | 120 | if show_object is not None: 121 | if 'pointnet' in model_name: 122 | show_pointcloud_texture(geom, tex_preds) 123 | elif 'voxnet' in model_name: 124 | show_voxel_texture(geom, tex_preds) 125 | break 126 | else: 127 | raise NotImplementedError 128 | 129 | 130 | if __name__ == '__main__': 131 | parser = argparse.ArgumentParser() 132 | parser.add_argument('--data_dir', default=osp.join('data', 'voxelized_meshes')) 133 | parser.add_argument('--instruction', required=True) 134 | parser.add_argument('--checkpoint_filename', required=True) 135 | parser.add_argument('--config_filename', required=True) 136 | parser.add_argument('--test_only', action='store_true') 137 | parser.add_argument('--device_id', default=0) 138 | parser.add_argument('--show_object', default=None) 139 | args = parser.parse_args() 140 | 141 | eval(osp.expanduser(args.data_dir), args.instruction, 142 | osp.expanduser(args.checkpoint_filename), 143 | osp.expanduser(args.config_filename), args.device_id, 144 | test_only=args.test_only, show_object=args.show_object) 145 | -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/samarth-robo/contactdb_prediction/3d39fccb039854af0cfd0c7c1f96ccd68dcbffe0/models/__init__.py -------------------------------------------------------------------------------- /models/losses.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as tnn 3 | import numpy as np 4 | from IPython.core.debugger import set_trace 5 | 6 | # only count the loss where target is non-zero 7 | class TextureLoss(tnn.Module): 8 | def __init__(self, pos_weight=10): 9 | super(TextureLoss, self).__init__() 10 | self.loss = tnn.CrossEntropyLoss(weight=torch.Tensor([1, pos_weight]), 11 | ignore_index=2, reduction='none') 12 | 13 | def forward(self, preds, targs): 14 | loss = self.loss(preds, targs) 15 | loss = torch.mean(loss, 1) 16 | return loss 17 | 18 | 19 | def classification_error(preds, targs): 20 | _, pred_class = torch.max(preds, dim=1) 21 | errors = [] 22 | for pred, targ in zip(pred_class, targs): 23 | mask = targ != 2 24 | masked_pred = pred.masked_select(mask) 25 | masked_targ = targ.masked_select(mask) 26 | if torch.sum(masked_pred) == 0: # ignore degenerate masks 27 | error = torch.tensor(1000).to(device=preds.device, dtype=preds.dtype) 28 | else: 29 | error = masked_pred != masked_targ 30 | error = torch.mean(error.to(dtype=preds.dtype)) 31 | errors.append(error) 32 | errors = torch.stack(errors) 33 | return errors 34 | 35 | 36 | class DiverseLoss(tnn.Module): 37 | def __init__(self, pos_weight=10, beta=1, train=True, eval_mode=False): 38 | """ 39 | :param eval_mode: returns match indices, and computes loss as L2 loss 40 | """ 41 | super(DiverseLoss, self).__init__() 42 | self.loss = classification_error if eval_mode \ 43 | else TextureLoss(pos_weight=pos_weight) 44 | self.beta = beta 45 | self.train = train 46 | if eval_mode: 47 | self.train = False 48 | 49 | def forward(self, preds, targs): 50 | """ 51 | :param preds: N x Ep x 2 x P 52 | :param targs: N x Et x P 53 | :return: 54 | """ 55 | preds = preds.view(*preds.shape[:3], -1) 56 | targs = targs.view(*targs.shape[:2], -1) 57 | N, Ep, _, P = preds.shape 58 | _, Et, _ = targs.shape 59 | 60 | losses = [] 61 | match_indices = [] 62 | for pred, targ in zip(preds, targs): 63 | pred = pred.repeat(Et, 1, 1) 64 | targ = targ.repeat(1, Ep).view(-1, P) 65 | loss_matrix = self.loss(pred, targ).view(Et, Ep) 66 | loss, match_idx = loss_matrix.min(1) 67 | loss = loss.mean() 68 | if self.train: 69 | l_catchup = loss_matrix.min(0)[0].max() / Ep 70 | loss = loss + self.beta * l_catchup 71 | losses.append(loss) 72 | match_indices.append(match_idx) 73 | loss = torch.stack(losses).mean() 74 | match_indices = torch.stack(match_indices) 75 | 76 | return loss, match_indices 77 | -------------------------------------------------------------------------------- /models/pointnet.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.parallel 4 | import torch.utils.data 5 | from torch.autograd import Variable 6 | import numpy as np 7 | import torch.nn.functional as F 8 | from IPython.core.debugger import set_trace 9 | 10 | 11 | class STN3d(nn.Module): 12 | def __init__(self, n=4): 13 | super(STN3d, self).__init__() 14 | self.n = n 15 | self.conv1 = torch.nn.Conv1d(n, 64, 1, bias=False) 16 | self.conv2 = torch.nn.Conv1d(64, 128, 1, bias=False) 17 | self.conv3 = torch.nn.Conv1d(128, 1024, 1, bias=False) 18 | self.fc1 = nn.Linear(1024, 512, bias=False) 19 | self.fc2 = nn.Linear(512, 256, bias=False) 20 | self.fc3 = nn.Linear(256, n*n) 21 | self.relu = nn.ReLU() 22 | 23 | self.bn1 = nn.BatchNorm1d(64) 24 | self.bn2 = nn.BatchNorm1d(128) 25 | self.bn3 = nn.BatchNorm1d(1024) 26 | self.bn4 = nn.BatchNorm1d(512) 27 | self.bn5 = nn.BatchNorm1d(256) 28 | 29 | for m in self.modules(): 30 | if isinstance(m, nn.BatchNorm1d): 31 | nn.init.constant_(m.weight, 1) 32 | nn.init.constant_(m.bias, 0) 33 | 34 | def forward(self, x): 35 | batchsize = x.size()[0] 36 | x = F.relu(self.bn1(self.conv1(x))) 37 | x = F.relu(self.bn2(self.conv2(x))) 38 | x = F.relu(self.bn3(self.conv3(x))) 39 | x = torch.max(x, 2, keepdim=True)[0] 40 | x = x.view(-1, 1024) 41 | 42 | x = F.relu(self.bn4(self.fc1(x))) 43 | x = F.relu(self.bn5(self.fc2(x))) 44 | x = self.fc3(x) 45 | 46 | iden = np.eye(self.n).ravel().astype(np.float32) 47 | iden = torch.from_numpy(iden).view(1,self.n*self.n).repeat(batchsize,1) 48 | iden = iden.to(device=x.device) 49 | x = x + iden 50 | x = x.view(-1, self.n, self.n) 51 | return x 52 | 53 | 54 | class PointNetfeat(nn.Module): 55 | def __init__(self, global_feat = True, n=4, n_ensemble=20): 56 | super(PointNetfeat, self).__init__() 57 | self.n = n 58 | self.n_ensemble = n_ensemble 59 | self.global_feat = global_feat 60 | self.stn = STN3d(n=n) 61 | self.conv1 = torch.nn.Conv1d(n+self.n_ensemble, 64, 1, bias=False) 62 | self.conv2 = torch.nn.Conv1d(64, 128, 1, bias=False) 63 | self.conv3 = torch.nn.Conv1d(128, 1024, 1, bias=False) 64 | self.bn1 = nn.BatchNorm1d(64) 65 | self.bn2 = nn.BatchNorm1d(128) 66 | self.bn3 = nn.BatchNorm1d(1024) 67 | 68 | for m in self.modules(): 69 | if isinstance(m, nn.BatchNorm1d): 70 | nn.init.constant_(m.weight, 1) 71 | nn.init.constant_(m.bias, 0) 72 | 73 | def forward(self, x, c): 74 | batchsize = x.size()[0] 75 | n_pts = x.size()[2] 76 | trans = self.stn(x) 77 | x = x.transpose(2,1) 78 | x = torch.bmm(x, trans) 79 | x = x.transpose(2,1) 80 | x = torch.cat((x, c), dim=1) 81 | x = F.relu(self.bn1(self.conv1(x))) 82 | pointfeat = x 83 | x = F.relu(self.bn2(self.conv2(x))) 84 | x = self.bn3(self.conv3(x)) 85 | x = torch.max(x, 2, keepdim=True)[0] 86 | x = x.view(-1, 1024) 87 | if self.global_feat: 88 | return x, trans 89 | else: 90 | x = x.view(-1, 1024, 1).repeat(1, 1, n_pts) 91 | return torch.cat([x, pointfeat], 1), trans 92 | 93 | class PointNetCls(nn.Module): 94 | def __init__(self, k = 2): 95 | super(PointNetCls, self).__init__() 96 | self.feat = PointNetfeat(global_feat=True) 97 | self.fc1 = nn.Linear(1024, 512) 98 | self.fc2 = nn.Linear(512, 256) 99 | self.fc3 = nn.Linear(256, k) 100 | self.bn1 = nn.BatchNorm1d(512) 101 | self.bn2 = nn.BatchNorm1d(256) 102 | self.relu = nn.ReLU() 103 | def forward(self, x): 104 | x, trans = self.feat(x) 105 | x = F.relu(self.bn1(self.fc1(x))) 106 | x = F.relu(self.bn2(self.fc2(x))) 107 | x = self.fc3(x) 108 | return F.log_softmax(x, dim=0), trans 109 | 110 | class PointNetDenseCls(nn.Module): 111 | def __init__(self, k=2, n=4, n_ensemble=20, droprate=0): 112 | super(PointNetDenseCls, self).__init__() 113 | self.k = k 114 | self.n = n 115 | self.n_ensemble = n_ensemble 116 | self.droprate = droprate 117 | self.drop = torch.nn.Dropout(p=droprate) 118 | self.feat = PointNetfeat(global_feat=False, n=n, n_ensemble=n_ensemble) 119 | self.conv1 = torch.nn.Conv1d(1088, 512, 1, bias=False) 120 | self.conv2 = torch.nn.Conv1d(512, 256, 1, bias=False) 121 | self.conv3 = torch.nn.Conv1d(256+self.n_ensemble, 128, 1, bias=False) 122 | self.conv4 = torch.nn.Conv1d(128, self.k, 1) 123 | self.bn1 = nn.BatchNorm1d(512) 124 | self.bn2 = nn.BatchNorm1d(256) 125 | self.bn3 = nn.BatchNorm1d(128) 126 | 127 | for m in self.modules(): 128 | if isinstance(m, nn.BatchNorm1d): 129 | nn.init.constant_(m.weight, 1) 130 | nn.init.constant_(m.bias, 0) 131 | 132 | def forward(self, x, c): 133 | batchsize = x.size()[0] 134 | n_pts = x.size()[2] 135 | if self.droprate > 0: 136 | x = self.drop(x) 137 | x, _ = self.feat(x, c) 138 | x = F.relu(self.bn1(self.conv1(x))) 139 | x = F.relu(self.bn2(self.conv2(x))) 140 | x = torch.cat((x, c), dim=1) 141 | x = F.relu(self.bn3(self.conv3(x))) 142 | x = self.conv4(x) 143 | return x 144 | 145 | 146 | class DiversePointNet(nn.Module): 147 | def __init__(self, n_ensemble, n=4, droprate=0): 148 | super(DiversePointNet, self).__init__() 149 | self.n_ensemble = n_ensemble 150 | self.pointnet = PointNetDenseCls(n_ensemble=n_ensemble, n=n, 151 | droprate=droprate) 152 | 153 | def forward(self, xs): 154 | """ 155 | :param xs: N x 3 x P 156 | :return: N x E x P 157 | """ 158 | N, _, P = xs.shape 159 | preds = [] 160 | for x in xs: 161 | x = x.view(1, *x.shape).expand(self.n_ensemble, -1, -1) 162 | c = torch.eye(self.n_ensemble, dtype=x.dtype, device=x.device) 163 | c = c.view(self.n_ensemble, self.n_ensemble, 1).expand(-1, -1, P) 164 | pred = self.pointnet(x, c) 165 | preds.append(pred) 166 | preds = torch.stack(preds) 167 | return preds 168 | 169 | 170 | if __name__ == '__main__': 171 | sim_data = Variable(torch.rand(32,3,2500)) 172 | trans = STN3d() 173 | out = trans(sim_data) 174 | print('stn', out.size()) 175 | 176 | pointfeat = PointNetfeat(global_feat=True) 177 | out, _ = pointfeat(sim_data) 178 | print('global feat', out.size()) 179 | 180 | pointfeat = PointNetfeat(global_feat=False) 181 | out, _ = pointfeat(sim_data) 182 | print('point feat', out.size()) 183 | 184 | cls = PointNetCls(k = 5) 185 | out, _ = cls(sim_data) 186 | print('class', out.size()) 187 | 188 | seg = PointNetDenseCls(k = 3) 189 | out, _ = seg(sim_data) 190 | print('seg', out.size()) 191 | -------------------------------------------------------------------------------- /models/voxnet.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as tnn 3 | import torch.nn.functional as tnnF 4 | from IPython.core.debugger import set_trace 5 | 6 | class VoxNet(tnn.Module): 7 | def __init__(self, n_ensemble, inplanes=5, outplanes=2, droprate=0): 8 | super(VoxNet, self).__init__() 9 | self.droprate = droprate 10 | self.drop = tnn.Dropout(p=droprate) 11 | 12 | nc = inplanes 13 | nc *= 4 14 | self.conv1 = tnn.Conv3d(inplanes, nc, kernel_size=3, padding=1, bias=False) 15 | self.bn1 = tnn.BatchNorm3d(nc) 16 | self.pool1 = tnn.MaxPool3d(2) 17 | 18 | nc *= 4 19 | self.conv2 = tnn.Conv3d(self.conv1.out_channels+n_ensemble, nc, 20 | kernel_size=3, padding=1, bias=False) 21 | self.bn2 = tnn.BatchNorm3d(nc) 22 | self.pool2 = tnn.MaxPool3d(2) 23 | 24 | nc *= 4 25 | self.conv3 = tnn.Conv3d(self.conv2.out_channels, nc, kernel_size=3, 26 | padding=1, bias=False) 27 | self.bn3 = tnn.BatchNorm3d(nc) 28 | self.pool3 = tnn.MaxPool3d(4) 29 | 30 | inplanes = nc 31 | nc = nc // 4 32 | self.upconv1 = tnn.Conv3d(inplanes, nc, kernel_size=3, padding=1, bias=False) 33 | self.upbn1 = tnn.BatchNorm3d(nc) 34 | nc = nc // 4 35 | self.upconv2 = tnn.Conv3d(self.upconv1.out_channels, nc, kernel_size=3, 36 | padding=1, bias=False) 37 | self.upbn2 = tnn.BatchNorm3d(nc) 38 | nc = nc // 4 39 | self.upconv3 = tnn.Conv3d(self.upconv2.out_channels+n_ensemble, nc, 40 | kernel_size=3, padding=1, bias=False) 41 | self.upbn3 = tnn.BatchNorm3d(nc) 42 | self.upconv4 = tnn.Conv3d(self.upconv3.out_channels, outplanes, kernel_size=3, 43 | padding=1) 44 | 45 | for m in self.modules(): 46 | if isinstance(m, tnn.BatchNorm3d): 47 | tnn.init.constant_(m.weight, 1) 48 | tnn.init.constant_(m.bias, 0) 49 | 50 | def forward(self, x, c): 51 | if self.droprate > 0: 52 | x = self.drop(x) 53 | x = self.pool1(self.bn1(tnnF.relu(self.conv1(x)))) 54 | x = torch.cat((x, c), dim=1) 55 | x = self.pool2(self.bn2(tnnF.relu(self.conv2(x)))) 56 | x = self.pool3(self.bn3(tnnF.relu(self.conv3(x)))) 57 | x = self.upbn1(tnnF.relu(self.upconv1(x.view(x.shape[0], -1, 4, 4, 4)))) 58 | x = tnnF.interpolate(x, scale_factor=4) 59 | x = self.upbn2(tnnF.relu(self.upconv2(x))) 60 | x = tnnF.interpolate(x, scale_factor=2) 61 | x = torch.cat((x, c), dim=1) 62 | x = self.upbn3(tnnF.relu(self.upconv3(x))) 63 | x = tnnF.interpolate(x, scale_factor=2) 64 | x = self.upconv4(x) 65 | return x 66 | 67 | 68 | class DiverseVoxNet(tnn.Module): 69 | def __init__(self, n_ensemble, inplanes=5, droprate=0): 70 | super(DiverseVoxNet, self).__init__() 71 | self.n_ensemble = n_ensemble 72 | self.voxnet = VoxNet(n_ensemble=n_ensemble, inplanes=inplanes, 73 | droprate=droprate) 74 | 75 | def forward(self, xs): 76 | """ 77 | :param xs: N x 5 x DHW 78 | :return: N x E x DHW 79 | """ 80 | N, _, D, H, W = xs.shape 81 | preds = [] 82 | for x in xs: 83 | x = x.view(1, *x.shape).expand(self.n_ensemble, -1, -1, -1, -1) 84 | c = torch.eye(self.n_ensemble, dtype=x.dtype, device=x.device) 85 | c = c.view(*c.shape, 1, 1, 1).expand(-1, -1, D//2, H//2, W//2) 86 | pred = self.voxnet(x, c) 87 | preds.append(pred) # texture is 1-dimensional 88 | preds = torch.stack(preds) 89 | return preds 90 | -------------------------------------------------------------------------------- /mug0.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/samarth-robo/contactdb_prediction/3d39fccb039854af0cfd0c7c1f96ccd68dcbffe0/mug0.gif -------------------------------------------------------------------------------- /mug1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/samarth-robo/contactdb_prediction/3d39fccb039854af0cfd0c7c1f96ccd68dcbffe0/mug1.gif -------------------------------------------------------------------------------- /pointcloud_dataset.py: -------------------------------------------------------------------------------- 1 | import torch.utils.data as tdata 2 | import os 3 | import numpy as np 4 | import utils 5 | import transforms3d.euler as txe 6 | from collections import OrderedDict 7 | from IPython.core.debugger import set_trace 8 | osp = os.path 9 | 10 | 11 | class PointCloudDataset(tdata.Dataset): 12 | def __init__(self, data_dir, instruction, train, n_points=2500, 13 | include_sessions=None, exclude_sessions=None, 14 | random_rotation=180, random_scale=0.1, 15 | n_ensemble=20, color_thresh=0.4, test_only=False): 16 | super(PointCloudDataset, self).__init__() 17 | data_dir = osp.expanduser(data_dir) 18 | self.n_points = n_points 19 | self.random_rotation = random_rotation 20 | self.random_scale = random_scale 21 | self.n_ensemble = n_ensemble 22 | self.color_thresh = color_thresh 23 | 24 | # list the voxel grids 25 | self.filenames = OrderedDict() 26 | for filename in next(os.walk(data_dir))[-1]: 27 | if '_hollow.npy' not in filename: 28 | continue 29 | if test_only: 30 | if 'testonly' not in filename: 31 | continue 32 | else: 33 | if '_{:s}_'.format(instruction) not in filename: 34 | continue 35 | session_name = filename.split('_')[0] 36 | if include_sessions is not None: 37 | if session_name not in include_sessions: 38 | continue 39 | if exclude_sessions is not None: 40 | if session_name in exclude_sessions: 41 | continue 42 | offset = 1 if test_only else 2 43 | object_name = '_'.join(filename.split('.')[0].split('_')[offset:-1]) 44 | if not test_only: 45 | if train: 46 | if object_name in utils.test_objects: 47 | continue 48 | else: 49 | if object_name not in utils.test_objects: 50 | continue 51 | filename = osp.join(data_dir, filename) 52 | if object_name not in self.filenames: 53 | self.filenames[object_name] = [filename] 54 | else: 55 | self.filenames[object_name].append(filename) 56 | 57 | def __len__(self): 58 | return len(self.filenames) 59 | 60 | def __getitem__(self, index): 61 | # load geometry 62 | object_name = list(self.filenames.keys())[index] 63 | _, _, _, _, xx, yy, zz = np.load(self.filenames[object_name][0]) 64 | pts = np.vstack((xx, yy, zz)) 65 | offset = (pts.max(1, keepdims=True) + pts.min(1, keepdims=True)) / 2 66 | pts -= offset 67 | scale = max(pts.max(1) - pts.min(1)) / 2 68 | pts /= scale 69 | pts = np.vstack((pts, scale*np.ones(pts.shape[1]))) 70 | 71 | # resample 72 | pts_choice = np.random.choice(pts.shape[1], size=self.n_points, replace=True) 73 | pts = pts[:, pts_choice] 74 | 75 | # random perturbations 76 | # rotation 77 | if abs(self.random_rotation) > 0: 78 | theta = np.random.uniform(-np.pi*self.random_rotation/180, 79 | np.pi*self.random_rotation/180) 80 | R = txe.euler2mat(0, 0, theta) 81 | pts[:3] = R @ pts[:3] 82 | # scale 83 | if abs(self.random_scale) > 0: 84 | axis = np.random.choice(2) 85 | T = np.eye(3) 86 | T[axis, axis] = np.random.uniform(1-self.random_scale, 1+self.random_scale) 87 | pts[:3] = T @ pts[:3] 88 | 89 | # load textures 90 | N = len(self.filenames[object_name]) 91 | filename_choice = np.arange(N) 92 | if self.n_ensemble > 0 and self.n_ensemble < N: 93 | filename_choice = np.random.choice(N, size=self.n_ensemble, replace=False) 94 | cs = [] 95 | filenames = [self.filenames[object_name][c] for c in filename_choice] 96 | for filename in filenames: 97 | _, _, _, c, _, _, _ = np.load(filename) 98 | c = utils.discretize_texture(c, thresh=self.color_thresh) 99 | c = c[pts_choice] 100 | cs.append(c) 101 | cs = np.vstack(cs) 102 | 103 | return pts.astype(np.float32), cs.astype(np.int64) 104 | 105 | if __name__ == '__main__': 106 | n_ensemble = 1 107 | N_show = 30 108 | dset = PointCloudDataset(osp.join('data', 'voxelized_meshes'), 'use', 109 | train=True, random_rotation=180, n_ensemble=n_ensemble) 110 | for idx in np.random.choice(len(dset), N_show): 111 | geom, tex = dset[idx] 112 | utils.show_pointcloud(geom[:3].T, tex[0]) 113 | -------------------------------------------------------------------------------- /train_val.py: -------------------------------------------------------------------------------- 1 | from models.voxnet import DiverseVoxNet as VoxNet 2 | from models.pointnet import DiversePointNet as PointNet 3 | from models.losses import DiverseLoss 4 | from voxel_dataset import VoxelDataset 5 | from pointcloud_dataset import PointCloudDataset 6 | 7 | from ignite.engine import Engine, Events 8 | from ignite.handlers import ModelCheckpoint 9 | import visdom 10 | from torch.utils.data import DataLoader 11 | from torch import optim as toptim 12 | import numpy as np 13 | import os 14 | import torch 15 | import configparser 16 | import argparse 17 | import logging 18 | from IPython.core.debugger import set_trace 19 | osp = os.path 20 | 21 | def create_plot_window(vis, xlabel, ylabel, title, win, env, trace_name): 22 | if not isinstance(trace_name, list): 23 | trace_name = [trace_name] 24 | 25 | vis.line(X=np.array([1]), Y=np.array([np.nan]), win=win, env=env, 26 | name=trace_name[0], 27 | opts=dict(xlabel=xlabel, ylabel=ylabel, title=title)) 28 | for name in trace_name[1:]: 29 | vis.line(X=np.array([1]), Y=np.array([np.nan]), win=win, env=env, 30 | name=name) 31 | 32 | 33 | def train(data_dir, instruction, config_file, experiment_suffix=None, 34 | checkpoint_dir='.', device_id=0, weights_filename=None, 35 | include_sessions=None, exclude_sessions=None): 36 | # config 37 | config = configparser.ConfigParser() 38 | config.read(config_file) 39 | 40 | section = config['optim'] 41 | batch_size = section.getint('batch_size') 42 | max_epochs = section.getint('max_epochs') 43 | val_interval = section.getint('val_interval') 44 | do_val = val_interval > 0 45 | base_lr = section.getfloat('base_lr') 46 | momentum = section.getfloat('momentum') 47 | weight_decay = section.getfloat('weight_decay') 48 | 49 | section = config['misc'] 50 | log_interval = section.getint('log_interval') 51 | shuffle = section.getboolean('shuffle') 52 | num_workers = section.getint('num_workers') 53 | 54 | section = config['hyperparams'] 55 | n_ensemble = section.getint('n_ensemble') 56 | diverse_beta = section.getfloat('diverse_beta') 57 | pos_weight = section.getfloat('pos_weight') 58 | droprate = section.getfloat('droprate') 59 | lr_step_size = section.getint('lr_step_size', 10000) 60 | lr_gamma = section.getfloat('lr_gamma', 1.0) 61 | 62 | # cuda 63 | if 'CUDA_VISIBLE_DEVICES' not in os.environ: 64 | os.environ['CUDA_VISIBLE_DEVICES'] = str(device_id) 65 | else: 66 | devices = os.environ['CUDA_VISIBLE_DEVICES'] 67 | devices = devices.split(',')[device_id] 68 | os.environ['CUDA_VISIBLE_DEVICES'] = devices 69 | device = 'cuda:0' 70 | 71 | # create dataset and model 72 | model_name = config_file.split('/')[-1].split('.')[0] 73 | kwargs = dict(data_dir=data_dir, instruction=instruction, 74 | include_sessions=include_sessions, exclude_sessions=exclude_sessions, 75 | n_ensemble=n_ensemble) 76 | if 'voxnet' in model_name: 77 | model = VoxNet(n_ensemble=n_ensemble, droprate=droprate) 78 | grid_size = config['hyperparams'].getint('grid_size') 79 | random_rotation = config['hyperparams'].getfloat('random_rotation') 80 | train_dset = VoxelDataset(grid_size=grid_size, 81 | random_rotation=random_rotation, train=True, **kwargs) 82 | val_dset = VoxelDataset(grid_size=grid_size, random_rotation=0, 83 | train=False, **kwargs) 84 | elif 'pointnet' in model_name: 85 | model = PointNet(n_ensemble=n_ensemble, droprate=droprate) 86 | n_points = section.getint('n_points') 87 | random_rotation = config['hyperparams'].getfloat('random_rotation') 88 | random_scale = config['hyperparams'].getfloat('random_scale') 89 | train_dset = PointCloudDataset(n_points=n_points, train=True, 90 | random_rotation=random_rotation, random_scale=random_scale, **kwargs) 91 | val_dset = PointCloudDataset(n_points=n_points, train=False, 92 | random_rotation=0, random_scale=0, **kwargs) 93 | else: 94 | raise NotImplementedError 95 | 96 | # checkpointing 97 | exp_name = '{:s}_{:s}_diversenet'.format(instruction, model_name) 98 | if experiment_suffix: 99 | exp_name += '_{:s}'.format(experiment_suffix) 100 | 101 | def checkpoint_fn(engine: Engine): 102 | return -engine.state.avg_loss 103 | 104 | checkpoint_dir = osp.join(checkpoint_dir, exp_name) 105 | checkpoint_kwargs = dict(dirname=checkpoint_dir, filename_prefix='checkpoint', 106 | score_function=checkpoint_fn, create_dir=True, require_empty=False, 107 | save_as_state_dict=False) 108 | checkpoint_dict = {'model': model} 109 | 110 | # logging 111 | if not osp.isdir(checkpoint_dir): 112 | os.mkdir(checkpoint_dir) 113 | log_filename = osp.join(checkpoint_dir, 'training_log.txt') 114 | logging.basicConfig(level=logging.INFO, 115 | handlers=[logging.FileHandler(log_filename, mode='w'), logging.StreamHandler()]) 116 | logger = logging.getLogger() 117 | logger.info('Config from {:s}:'.format(config_file)) 118 | with open(config_file, 'r') as f: 119 | for line in f: 120 | logger.info(line.strip()) 121 | 122 | # load weights 123 | if weights_filename is not None: 124 | checkpoint = torch.load(osp.expanduser(weights_filename)) 125 | checkpoint = {k:v for k,v in checkpoint.items() if 'conv4' not in k} 126 | model.load_state_dict(checkpoint, strict=False) 127 | logger.info('Loaded weights from {:s}'.format(weights_filename)) 128 | model.to(device=device) 129 | 130 | # loss function 131 | loss_fn = DiverseLoss(beta=diverse_beta, pos_weight=pos_weight) 132 | loss_fn.to(device=device) 133 | if do_val: 134 | val_loss_fn = DiverseLoss(beta=diverse_beta, train=False, 135 | pos_weight=pos_weight) 136 | val_loss_fn.to(device=device) 137 | 138 | # optimizer 139 | optim = toptim.SGD(model.parameters(), lr=base_lr, weight_decay=weight_decay, 140 | momentum=momentum) 141 | lr_scheduler = toptim.lr_scheduler.StepLR(optim, step_size=lr_step_size, 142 | gamma=lr_gamma) 143 | 144 | # dataloader 145 | train_dloader = DataLoader(train_dset, batch_size=batch_size, shuffle=shuffle, 146 | pin_memory=True, num_workers=num_workers) 147 | if do_val: 148 | val_dloader = DataLoader(val_dset, batch_size=batch_size, shuffle=shuffle, 149 | pin_memory=True, num_workers=num_workers) 150 | 151 | # train and val loops 152 | def train_loop(engine: Engine, batch): 153 | geom, tex_targs = batch 154 | geom = geom.to(device=device, non_blocking=True) # Nx3xP 155 | tex_targs = tex_targs.to(device=device, non_blocking=True) # NxExP 156 | model.train() 157 | optim.zero_grad() 158 | tex_preds = model(geom) # NxExP 159 | loss, _ = loss_fn(tex_preds, tex_targs) 160 | loss.backward() 161 | optim.step() 162 | engine.state.train_loss = loss.item() 163 | return loss.item() 164 | trainer = Engine(train_loop) 165 | train_checkpoint_handler = ModelCheckpoint(score_name='train_loss', 166 | **checkpoint_kwargs) 167 | trainer.add_event_handler(Events.EPOCH_COMPLETED, train_checkpoint_handler, 168 | checkpoint_dict) 169 | 170 | if do_val: 171 | def val_loop(engine: Engine, batch): 172 | geom, tex_targs = batch 173 | geom = geom.to(device=device, non_blocking=True) 174 | tex_targs = tex_targs.to(device=device, non_blocking=True) 175 | if 'pointnet' not in model_name: 176 | # loss explodes for pointnet if model is in eval mode 177 | model.eval() 178 | with torch.no_grad(): 179 | tex_preds = model(geom) 180 | loss, _ = val_loss_fn(tex_preds, tex_targs) 181 | engine.state.val_loss = loss.item() 182 | return loss.item() 183 | valer = Engine(val_loop) 184 | val_checkpoint_handler = ModelCheckpoint(score_name='val_loss', 185 | **checkpoint_kwargs) 186 | valer.add_event_handler(Events.EPOCH_COMPLETED, val_checkpoint_handler, 187 | checkpoint_dict) 188 | 189 | # callbacks 190 | vis = visdom.Visdom() 191 | loss_win = 'loss' 192 | create_plot_window(vis, '#Epochs', 'Loss', 'Training and Validation Loss', 193 | win=loss_win, env=exp_name, trace_name=['train_loss', 'val_loss']) 194 | 195 | @trainer.on(Events.ITERATION_COMPLETED) 196 | def log_training_loss(engine): 197 | it = (engine.state.iteration - 1) % len(train_dloader) 198 | engine.state.avg_loss = (engine.state.avg_loss*it + engine.state.output) / \ 199 | (it + 1) 200 | 201 | if it % log_interval == 0: 202 | logger.info("{:s} train Epoch[{:03d}/{:03d}] Iteration[{:04d}/{:04d}] " 203 | "Loss: {:02.4f} lr: {:.4f}". 204 | format(exp_name, engine.state.epoch, max_epochs, it+1, len(train_dloader), 205 | engine.state.output, lr_scheduler.get_lr()[0])) 206 | epoch = engine.state.epoch - 1 +\ 207 | float(it)/(len(train_dloader)-1) 208 | 209 | vis.line(X=np.array([epoch]), Y=np.array([engine.state.output]), 210 | update='append', win=loss_win, env=exp_name, name='train_loss') 211 | 212 | if do_val: 213 | @valer.on(Events.ITERATION_COMPLETED) 214 | def avg_loss_callback(engine: Engine): 215 | it = (engine.state.iteration - 1) % len(train_dloader) 216 | engine.state.avg_loss = (engine.state.avg_loss*it + engine.state.output) / \ 217 | (it + 1) 218 | if it % log_interval == 0: 219 | logger.info("{:s} val Iteration[{:04d}/{:04d}] Loss: {:02.4f}" 220 | .format(exp_name, it+1, len(val_dloader), engine.state.output)) 221 | 222 | @valer.on(Events.EPOCH_COMPLETED) 223 | def log_val_loss(engine: Engine): 224 | vis.line(X=np.array([trainer.state.epoch]), 225 | Y=np.array([engine.state.avg_loss]), update='append', win=loss_win, 226 | env=exp_name, name='val_loss') 227 | 228 | @trainer.on(Events.EPOCH_COMPLETED) 229 | def run_val(engine: Engine): 230 | vis.save([exp_name]) 231 | if val_interval < 0: # don't do validation 232 | return 233 | if engine.state.epoch % val_interval != 0: 234 | return 235 | valer.run(val_dloader) 236 | 237 | @trainer.on(Events.EPOCH_STARTED) 238 | def step_lr_scheduler(engine: Engine): 239 | lr_scheduler.step() 240 | 241 | def reset_avg_loss(engine: Engine): 242 | engine.state.avg_loss = 0 243 | trainer.add_event_handler(Events.EPOCH_STARTED, reset_avg_loss) 244 | if do_val: 245 | valer.add_event_handler(Events.EPOCH_STARTED, reset_avg_loss) 246 | 247 | # Ignite the torch! 248 | trainer.run(train_dloader, max_epochs) 249 | 250 | 251 | if __name__ == '__main__': 252 | parser = argparse.ArgumentParser() 253 | parser.add_argument('--data_dir', 254 | default=osp.join('data', 'voxelized_meshes')) 255 | parser.add_argument('--checkpoint_dir', 256 | default=osp.join('data', 'checkpoints')) 257 | parser.add_argument('--instruction', required=True) 258 | parser.add_argument('--config_file', required=True) 259 | parser.add_argument('--weights_file', default=None) 260 | parser.add_argument('--suffix', default=None) 261 | parser.add_argument('--device_id', default=0) 262 | parser.add_argument('--include_sessions', default=None) 263 | parser.add_argument('--exclude_sessions', default=None) 264 | args = parser.parse_args() 265 | 266 | include_sessions = None 267 | if args.include_sessions is not None: 268 | include_sessions = args.include_sessions.split(',') 269 | exclude_sessions = None 270 | if args.exclude_sessions is not None: 271 | exclude_sessions = args.exclude_sessions.split(',') 272 | train(osp.expanduser(args.data_dir), args.instruction, args.config_file, 273 | experiment_suffix=args.suffix, device_id=args.device_id, 274 | checkpoint_dir=osp.expanduser(args.checkpoint_dir), 275 | weights_filename=args.weights_file, include_sessions=include_sessions, 276 | exclude_sessions=exclude_sessions) 277 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import open3d 3 | import os 4 | osp = os.path 5 | 6 | test_objects = ['mug', 'pan', 'wine_glass'] 7 | 8 | 9 | base_dir = osp.expanduser(osp.join('~', 'deepgrasp_data')) 10 | use_data_dirs = \ 11 | [osp.join(base_dir, 'data')]*28 + \ 12 | [osp.join(base_dir, 'data3')] + \ 13 | [osp.join(base_dir, 'data2')]*4 + \ 14 | [osp.join(base_dir, 'data3')]*17 15 | handoff_data_dirs = \ 16 | [osp.join(base_dir, 'data')]*24 + \ 17 | [osp.join(base_dir, 'data3')]*5 +\ 18 | [osp.join(base_dir, 'data2')]*4 + \ 19 | [osp.join(base_dir, 'data3')]*17 20 | 21 | 22 | def texture_proc(colors, a=0.05, invert=False): 23 | idx = colors > 0 24 | ci = colors[idx] 25 | if len(ci) == 0: 26 | return colors 27 | if invert: 28 | ci = 1 - ci 29 | # fit a sigmoid 30 | x1 = min(ci); y1 = a 31 | x2 = max(ci); y2 = 1-a 32 | lna = np.log((1 - y1) / y1) 33 | lnb = np.log((1 - y2) / y2) 34 | k = (lnb - lna) / (x1 - x2) 35 | mu = (x2*lna - x1*lnb) / (lna - lnb) 36 | # apply the sigmoid 37 | ci = np.exp(k * (ci-mu)) / (1 + np.exp(k * (ci-mu))) 38 | colors[idx] = ci 39 | return colors 40 | 41 | 42 | def discretize_texture(c, thresh=0.4, have_dontcare=True): 43 | idx = c > 0 44 | if sum(idx) == 0: 45 | return c 46 | ci = c[idx] 47 | c[:] = 2 if have_dontcare else 0 48 | ci = ci > thresh 49 | c[idx] = ci 50 | return c 51 | 52 | 53 | def show_pointcloud(pts, colors, 54 | cmap=np.asarray([[0,0,1],[1,0,0],[0,0,1]])): 55 | colors = np.asarray(colors) 56 | if (colors.dtype == int) and (colors.ndim == 1) and (cmap is not None): 57 | colors = cmap[colors] 58 | if colors.ndim == 1: 59 | colors = np.tile(colors, (3, 1)).T 60 | 61 | pc = open3d.PointCloud() 62 | pc.points = open3d.Vector3dVector(np.asarray(pts)) 63 | pc.colors = open3d.Vector3dVector(colors) 64 | 65 | open3d.draw_geometries([pc]) 66 | -------------------------------------------------------------------------------- /voxel_dataset.py: -------------------------------------------------------------------------------- 1 | import torch.utils.data as tdata 2 | import os 3 | import numpy as np 4 | import transforms3d.euler as txe 5 | import utils 6 | from collections import OrderedDict 7 | from IPython.core.debugger import set_trace 8 | osp = os.path 9 | 10 | 11 | class VoxelDataset(tdata.Dataset): 12 | def __init__(self, data_dir, instruction, train, 13 | grid_size=64, include_sessions=None, exclude_sessions=None, 14 | random_rotation=180, n_ensemble=20, color_thresh=0.4, test_only=False): 15 | super(VoxelDataset, self).__init__() 16 | 17 | data_dir = osp.expanduser(data_dir) 18 | self.grid_size = grid_size 19 | self.random_rotation = random_rotation 20 | self.n_ensemble = n_ensemble 21 | self.color_thresh = color_thresh 22 | 23 | # list the voxel grids 24 | self.filenames = OrderedDict() 25 | for filename in next(os.walk(data_dir))[-1]: 26 | if '_solid.npy' not in filename: 27 | continue 28 | if test_only: 29 | if 'testonly' not in filename: 30 | continue 31 | else: 32 | if '_{:s}_'.format(instruction) not in filename: 33 | continue 34 | session_name = filename.split('_')[0] 35 | if include_sessions is not None: 36 | if session_name not in include_sessions: 37 | continue 38 | if exclude_sessions is not None: 39 | if session_name in exclude_sessions: 40 | continue 41 | offset = 1 if test_only else 2 42 | object_name = '_'.join(filename.split('.')[0].split('_')[offset:-1]) 43 | if not test_only: 44 | if train: 45 | if object_name in utils.test_objects: 46 | continue 47 | else: 48 | if object_name not in utils.test_objects: 49 | continue 50 | filename = osp.join(data_dir, filename) 51 | if object_name not in self.filenames: 52 | self.filenames[object_name] = [filename] 53 | else: 54 | self.filenames[object_name].append(filename) 55 | 56 | def __len__(self): 57 | return len(self.filenames) 58 | 59 | def __getitem__(self, index): 60 | # load geometry 61 | object_name = list(self.filenames.keys())[index] 62 | x, y, z, c, xx, yy, zz = np.load(self.filenames[object_name][0]) 63 | x, y, z = x.astype(int), y.astype(int), z.astype(int) 64 | pts = np.vstack((xx, yy, zz)) 65 | offset = (pts.max(1, keepdims=True) + pts.min(1, keepdims=True)) / 2 66 | pts -= offset 67 | scale = max(pts.max(1) - pts.min(1)) / 2 68 | pts /= scale 69 | pts = np.vstack((np.ones(pts.shape[1]), pts, scale*np.ones(pts.shape[1]))) 70 | 71 | # center the object 72 | offset_x = (self.grid_size - x.max() - 1) // 2 73 | offset_y = (self.grid_size - y.max() - 1) // 2 74 | offset_z = (self.grid_size - z.max() - 1) // 2 75 | x += offset_x 76 | y += offset_y 77 | z += offset_z 78 | 79 | # random rotation 80 | if abs(self.random_rotation) > 0: 81 | theta = np.random.uniform(-np.pi*self.random_rotation/180, 82 | np.pi*self.random_rotation/180) 83 | R = txe.euler2mat(0, 0, theta) 84 | p = np.vstack((x, y, z)) + 0.5 85 | p = p - self.grid_size/2.0 86 | p = R @ p 87 | s = max(p.max(1) - p.min(1)) 88 | p = p * (self.grid_size-1) / s 89 | s = (p.max(1, keepdims=True) + p.min(1, keepdims=True)) / 2.0 90 | p = p + self.grid_size/2.0 - s 91 | x, y, z = (p-0.5).astype(int) 92 | 93 | # create occupancy grid 94 | geom = np.zeros((5, self.grid_size, self.grid_size, self.grid_size), 95 | dtype=np.float32) 96 | geom[:, z, y, x] = pts 97 | 98 | # load textures 99 | N = len(self.filenames[object_name]) 100 | choice = np.arange(N) 101 | if self.n_ensemble > 0 and self.n_ensemble < N: 102 | choice = np.random.choice(N, size=self.n_ensemble, replace=False) 103 | texs = [] 104 | filenames = [self.filenames[object_name][c] for c in choice] 105 | for filename in filenames: 106 | _, _, _, c, _, _, _ = np.load(filename) 107 | c = utils.discretize_texture(c, thresh=self.color_thresh) 108 | tex = 2 * np.ones((self.grid_size, self.grid_size, self.grid_size), 109 | dtype=np.float32) 110 | tex[z, y, x] = c 111 | texs.append(tex) 112 | texs = np.stack(texs) 113 | 114 | return geom.astype(np.float32), texs.astype(np.int) 115 | 116 | 117 | if __name__ == '__main__': 118 | n_ensemble = 1 119 | N_show = 30 120 | dset = VoxelDataset(osp.join('data', 'voxelized_meshes'), 'use', 121 | train=True, random_rotation=180, n_ensemble=n_ensemble) 122 | for idx in np.random.choice(len(dset), N_show): 123 | geom, tex = dset[idx] 124 | z, y, x = np.nonzero(geom[0]) # see which voxels are occupied 125 | c = tex[0, z, y, x] 126 | x3d = geom[1, z, y, x] 127 | y3d = geom[2, z, y, x] 128 | z3d = geom[3, z, y, x] 129 | #utils.show_pointcloud(np.vstack((x3d, y3d, z3d)).T, c) 130 | utils.show_pointcloud(np.vstack((x, y, z)).T, c) 131 | --------------------------------------------------------------------------------