Repository: GREAT-WHU/DBA-Fusion Branch: main Commit: 2c658a3be747 Files: 71 Total size: 377.7 KB Directory structure: gitextract_ny3kcvri/ ├── .gitignore ├── .gitmodules ├── LICENSE ├── README.md ├── batch_kitti360.py ├── batch_subt.py ├── batch_tumvi.py ├── batch_whu.py ├── calib/ │ ├── 0412.txt │ ├── 0412new.txt │ ├── 1012.txt │ ├── barn.txt │ ├── carla.txt │ ├── eth.txt │ ├── euroc.txt │ ├── handheld.txt │ ├── kitti_360.txt │ ├── subt.txt │ ├── tartan.txt │ ├── tum3.txt │ └── tumvi.txt ├── dataset/ │ ├── euroc_to_hdf5.py │ ├── kitti360_to_hdf5.py │ └── tumvi_to_hdf5.py ├── dbaf/ │ ├── covisible_graph.py │ ├── data_readers/ │ │ ├── __init__.py │ │ ├── augmentation.py │ │ ├── base.py │ │ ├── factory.py │ │ ├── rgbd_utils.py │ │ ├── stream.py │ │ ├── tartan.py │ │ └── tartan_test.txt │ ├── dbaf.py │ ├── dbaf_frontend.py │ ├── depth_video.py │ ├── droid_net.py │ ├── geoFunc/ │ │ ├── __init__.py │ │ ├── const_value.py │ │ └── trans.py │ ├── geom/ │ │ ├── __init__.py │ │ ├── ba.py │ │ ├── chol.py │ │ ├── graph_utils.py │ │ ├── losses.py │ │ └── projective_ops.py │ ├── modules/ │ │ ├── __init__.py │ │ ├── clipping.py │ │ ├── corr.py │ │ ├── extractor.py │ │ └── gru.py │ ├── motion_filter.py │ └── multi_sensor.py ├── demo_vio_kitti360.py ├── demo_vio_subt.py ├── demo_vio_tumvi.py ├── demo_vio_whu.py ├── evaluation_scripts/ │ ├── batch_tumvi.py │ ├── evaluate_kitti.py │ └── evaluate_tumvi.py ├── results/ │ └── PLACEHOLDER ├── setup.py ├── src/ │ ├── altcorr_kernel.cu │ ├── bacore.h │ ├── correlation_kernels.cu │ ├── droid.cpp │ └── droid_kernels.cu └── visualization/ ├── check_reconstruction_kitti.py ├── check_reconstruction_kitti_animation.py ├── check_reconstruction_tumvi.py └── check_reconstruction_tumvi_animation.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ a# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ cover/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder .pybuilder/ target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv # For a library or package, you might want to ignore these files since the code is # intended to run in multiple environments; otherwise, check them in: # .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ # pytype static type analyzer .pytype/ # Cython debug symbols cython_debug/ __pycache__ build dist *.egg-info *.vscode/ *.pth tests checkpoints datasets runs cache *.out *.o data figures/*.pdf ================================================ FILE: .gitmodules ================================================ [submodule "thirdparty/lietorch"] path = thirdparty/lietorch url = https://github.com/princeton-vl/lietorch [submodule "thirdparty/eigen"] path = thirdparty/eigen url = https://gitlab.com/libeigen/eigen.git ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # DBA-Fusion >Tightly Integrating Deep Dense Visual Bundle Adjustment with Multiple Sensors for Large-Scale Localization and Mapping
[[Paper](https://arxiv.org/abs/2403.13714)] [[Video](https://www.bilibili.com/video/BV1yeNEecEwR/?share_source=copy_web&vd_source=a659a573a520a1151e294d0c8b9c842a)] ## What is this? **DBA-Fusion** is basically a VIO system which fuses DROID-SLAM-like dense bundle adjustment (DBA) with classic factor graph optimization. This work enables **realtime metric-scale localization and dense mapping** with excellent accuracy and robustness. Besides, this framework supports the **flexible fusion of multiple sensors** like GNSS or wheel speed sensors, extending its applicability to large-scale scenarios.

## Update log - [x] Code Upload (2024/02/28) - [x] Monocular VIO Examples (2024/02/28) - [x] Multi-sensor data sequence (WUH1012) used in the manuscript is available [here](https://drive.google.com/file/d/1w7UsAwreou_9YRYHz13QIGu6jOJGpdg5/view?usp=sharing). - [x] Multi-Sensor Fusion Examples - [ ] Stereo/RGB-D VIO Support ## Installation The pipeline of the work is based on python, and the computation part is mainly based on Pytorch (with CUDA) and GTSAM. Use the following commands to set up the python environment. ```Bash conda create -n dbaf python=3.10.11 conda activate dbaf # Other CUDA versions should also be fine. pip install torch==1.11.0+cu113 torchvision==0.12.0+cu113 torchaudio==0.11.0 --extra-index-url https://download.pytorch.org/whl/cu113 pip install torch-scatter==2.0.9 -f https://data.pyg.org/whl/torch-1.11.0+cu113.html pip install gdown tqdm numpy==1.25.0 numpy-quaternion==2022.4.3 opencv-python==4.7.0.72 scipy pyparsing matplotlib h5py pip install evo --upgrade --no-binary evo pip install open3d # optional for visualization ``` As for GTSAM, we make some modifications to it to extend the python wrapper APIs, clone it from the following repository and install it under your python environment. ```Bash git clone https://github.com/yuxuanzhou97/gtsam cd gtsam mkdir build cd build cmake .. -DGTSAM_BUILD_PYTHON=1 -DGTSAM_PYTHON_VERSION=3.10.11 make python-install ``` Finally, run the following command to build DBA-Fusion. ```Bash git clone --recurse-submodules https://github.com/GREAT-WHU/DBA-Fusion.git cd DBA-Fusion python setup.py install ``` ## Run DBA-Fusion We don't modify the model of DROID-SLAM so you can directly employ the weight trained for DROID-SLAM. Here we use the [model](https://drive.google.com/file/d/1PpqVt1H4maBa_GbPJp4NwxRsd9jk-elh/view?usp=sharing) pre-trained on TartanAir (provided by [DROID-SLAM](https://github.com/princeton-vl/DROID-SLAM?tab=readme-ov-file)), which shows great zero-shot performance on real-world datasets. **(Attention!!!)** For the default configurations, around ~10GB GPU memory is needed. Lower the "max_factors" argument to 36 or lower could help reduce the memory usage to ~6GB. ### 1. TUM-VI 1.1 Download the [TUM-VI](https://cvg.cit.tum.de/data/datasets/visual-inertial-dataset) datasets (512*512). **(Optional)** For better speed performance, it is recommended to convert the PNG images to a single HDF5 file through ```Bash python dataset/tumvi_to_hdf5.py --imagedir=${DATASET_DIR}/dataset-${SEQ}_512_16/mav0/cam0/data --imagestamp=${DATASET_DIR}/dataset-${SEQ}_512_16/mav0/cam0/data.csv --h5path=${SEQ}.h5 --calib=calib/tumvi.txt --stride 4 ``` 1.2 Specify the data path in [batch_tumvi.py](../batch_tumvi.py) (if you use HDF5 file, activate the "--enable_h5" and "--h5_path" arguments), run the following command ```Bash python batch_tumvi.py # This would trigger demo_vio_tumvi.py automatically. ``` Look into [demo_vio_tumvi.py](../demo_vio_tumvi.py) to learn about the arguments. Data loading and almost all the parameters are specified in this **one** file. 1.3 The outputs of the program includes **a text file** which contains real-time navigation results and **a .pkl file** which contains all keyframe poses and point clouds. To evaluate the realtime pose estimation performance, run the following command (notice to change the file paths in *evaluate_kitti.py*) ```Bash python evaluation_scripts/evaluate_tumvi.py --seq ${SEQ} ``` or ```Bash python evaluation_scripts/batch_evaluate_tumvi.py ``` For 3D visualization, currently we haven't handled the realtime visualization functionality. Run the scripts in the **"visualization"** folder for post-time visualization. ```Bash python visualization/check_reconstruction_tumvi.py ``` ### 2. KITTI-360 2.1 Download the [KITTI-360](https://www.cvlibs.net/datasets/kitti-360/index.php) datasets. Notice that we use the **unrectified perspective images** for the evaluation (named like "2013_05_28_drive_XXXX_sync/image_00/data_rgb"). For **IMU** data and IMU-centered **ground-truth poses**, we transform the axises to **Right-Forward-Up (RFU)** and check the synchronization. Besides, we use [OpenVINS](https://github.com/rpng/open_vins/) (in stereo VIO mode) to online refine the Camera-IMU extrinsics and time offsets (whose pre-calibrated values seem not very accurate) on the sequences. The refined parameters are used for for all the tests. **To reproduce the results**, just download the our prepared IMU and ground-truth data from [here](https://drive.google.com/file/d/1BO8zGvoey7IdwbWXmAdlhGPr6hiCFJ6Y/view?usp=drive_link), then uncompress it to the data path. **(Optional)** Similar to the TUM-VI part, you can use the following script to generate a HDF5 file for best speed performance. ```Bash python dataset/kitti360_to_hdf5.py --imagedir=${DATASET_DIR}/2013_05_28_drive_%s_sync/image_00/data_rgb --imagestamp=${DATASET_DIR}/2013_05_28_drive_%s_sync/camstamp.txt --h5path=${SEQ}.h5 --calib=calib/kitti360.txt --stride 2 ``` 2.2 Run the following command ```Bash python batch_kitti360.py ``` Dataloading and parameters are specified in [demo_vio_kitti360.py](../demo_vio_kitti360.py). 2.3 For evaluation and visualization, run ```Bash python evaluation_scripts/evaluate_kitti360.py --seq ${SEQ} python visualization/check_reconstruction_kitti360.py ``` ### 3. WUH1012 Download our self-collected data sequence from [here](https://drive.google.com/file/d/1w7UsAwreou_9YRYHz13QIGu6jOJGpdg5/view?usp=sharing). See [batch_whu.py](../batch_whu.py) for multi-sensor fusion in different modes (VIO + wheel speed/GNSS), as described in the manuscript. ### 4. Run on Your Own Dataset To run monocular VIO on your own dataset, * Duplicate a script from [demo_vio_kitti360.py](../demo_vio_kitti360.py) or [demo_vio_tumvi.py](../demo_vio_tumvi.py). * In the script, specify the data loading procedure of IMU data and images. * Specify the camera intrinsics and camera-IMU extrinsics in the script. * Try it! ## Some Results - Visual point cloud map compared to accumulated LiDAR point clouds.
- Further processing on the visual point clouds. (P.S. For 3-D GS, the point positions and number are fixed. The training time is around 3 minutes on RTX4080 laptop. )
## Acknowledgement DBA-Fusion is developed by [GREAT](http://igmas.users.sgg.whu.edu.cn/group) (GNSS+ REsearch, Application and Teaching) Group, School of Geodesy and Geomatics, Wuhan University.


This work is based on [DROID-SLAM](https://github.com/princeton-vl/DROID-SLAM) and [GTSAM](https://github.com/borglab/gtsam). We use evaluation tools from [evo](https://github.com/MichaelGrupp/evo) and 3D visualization tools from [Open3d](https://github.com/MichaelGrupp/evo). ================================================ FILE: batch_kitti360.py ================================================ import os import subprocess for i in ['0000','0002','0003','0004','0005','0006','0009','0010']: p = subprocess.Popen("python demo_vio_kitti360.py" +\ " --imagedir=/home/zhouyuxuan/data/2013_05_28_drive_%s_sync/image_00/data_rgb"%i +\ " --imagestamp=/home/zhouyuxuan/data/2013_05_28_drive_%s_sync/camstamp.txt"%i +\ " --imupath=/home/zhouyuxuan/data/2013_05_28_drive_%s_sync/imu.txt"%i +\ " --gtpath=/home/zhouyuxuan/data/2013_05_28_drive_%s_sync/gt_local.txt"%i +\ # " --enable_h5" +\ # " --h5path=/home/zhouyuxuan/DROID-SLAM/%s.h5"%i +\ " --resultpath=results/result_%s.txt"%i +\ " --calib=calib/kitti_360.txt" +\ " --stride=2" +\ " --max_factors=48" +\ " --active_window=12" +\ " --frontend_window=5" +\ " --frontend_radius=2" +\ " --frontend_nms=1" +\ " --inac_range=3" +\ " --visual_only=0" +\ " --far_threshold=-1" +\ " --translation_threshold=0.5" +\ " --mask_threshold=1.0" +\ " --skip_edge=[-4,-5,-6]" +\ " --save_pkl" +\ " --pklpath=results/%s.pkl"%i +\ " --show_plot",shell=True) p.wait() ================================================ FILE: batch_subt.py ================================================ import os import subprocess for i in [\ # 'Handheld1_Folder',\ 'Handheld2_Folder',\ ]: p = subprocess.Popen("python demo_vio_subt.py" +\ " --imagedir=/mnt/e/subt/%s/cam_0"%i +\ " --imagestamp=/mnt/e/subt/%s/cam_0/timestamps.txt"%i +\ " --imupath=/mnt/e/subt/%s/imu/imu_data.csv"%i +\ " --resultpath=results/result_%s.txt"%i +\ " --calib=calib/subt.txt" +\ " --stride=8" +\ " --max_factors=48" +\ " --active_window=12" +\ " --frontend_window=5" +\ " --frontend_radius=2" +\ " --frontend_nms=1" +\ " --far_threshold=0.02" +\ " --inac_range=3" +\ " --visual_only=0" +\ " --translation_threshold=0.2" +\ " --mask_threshold=-1.0" +\ " --skip_edge=[-4,-5,-6]" +\ " --save_pkl" +\ " --pklpath=results/%s.pkl"%i +\ " --show_plot",shell=True) p.wait() ================================================ FILE: batch_tumvi.py ================================================ import os import subprocess for i in [\ 'outdoors1',\ 'outdoors2',\ 'outdoors3',\ 'outdoors4',\ 'outdoors5',\ 'outdoors6',\ 'outdoors7',\ 'outdoors8',\ 'magistrale1',\ 'magistrale2',\ 'magistrale3',\ 'magistrale4',\ 'magistrale5',\ 'magistrale6' ]: p = subprocess.Popen("python demo_vio_tumvi.py" +\ " --imagedir=/mnt/z/tum-vi/dataset-%s_512_16/mav0/cam0/data"%i +\ " --imagestamp=/mnt/z/tum-vi/dataset-%s_512_16/mav0/cam0/data.csv"%i +\ " --imupath=/mnt/z/tum-vi/dataset-%s_512_16/mav0/imu0/data.csv"%i +\ " --gtpath=/mnt/z/tum-vi/dataset-%s_512_16/dso/gt_imu.csv"%i +\ # " --enable_h5" +\ # " --h5path=/home/zhouyuxuan/DROID-SLAM/%s.h5"%i +\ " --resultpath=results/result_%s.txt"%i +\ " --calib=calib/tumvi.txt" +\ " --stride=4" +\ " --max_factors=48" +\ " --active_window=12" +\ " --frontend_window=5" +\ " --frontend_radius=2" +\ " --frontend_nms=1" +\ " --far_threshold=0.02" +\ " --inac_range=3" +\ " --visual_only=0" +\ " --translation_threshold=0.2" +\ " --mask_threshold=-1.0" +\ " --skip_edge=[-4,-5,-6]" +\ " --save_pkl" +\ " --pklpath=results/%s.pkl"%i +\ " --show_plot",shell=True) p.wait() ================================================ FILE: batch_whu.py ================================================ import os import subprocess # VIO p = subprocess.Popen("python demo_vio_whu.py" +\ " --imagedir=/home/zhouyuxuan/data/WUH1012/cam0" +\ " --imagestamp=/home/zhouyuxuan/data/WUH1012/camstamp.txt" +\ " --imupath=/home/zhouyuxuan/data/WUH1012/imu.txt" +\ " --gtpath=/home/zhouyuxuan/data/WUH1012/IE.txt" +\ " --resultpath=results/result_whu_vio.txt" +\ " --calib=calib/1012.txt" +\ " --stride=2" +\ " --max_factors=48" +\ " --active_window=12" +\ " --frontend_window=5" +\ " --frontend_radius=2" +\ " --frontend_nms=1" +\ " --inac_range=3" +\ " --visual_only=0" +\ " --far_threshold=-1" +\ " --translation_threshold=0.25" +\ " --mask_threshold=0.0" +\ " --skip_edge=[]" +\ " --save_pkl" +\ " --use_zupt" +\ " --pklpath=results/whu.pkl" +\ " --show_plot", shell=True) p.wait() # VIO + wheel p = subprocess.Popen("python demo_vio_whu.py" +\ " --imagedir=/home/zhouyuxuan/data/WUH1012/cam0" +\ " --imagestamp=/home/zhouyuxuan/data/WUH1012/camstamp.txt" +\ " --imupath=/home/zhouyuxuan/data/WUH1012/imu.txt" +\ " --gtpath=/home/zhouyuxuan/data/WUH1012/IE.txt" +\ " --resultpath=results/result_whu_viow.txt" +\ " --calib=calib/1012.txt" +\ " --stride=2" +\ " --max_factors=48" +\ " --active_window=12" +\ " --frontend_window=5" +\ " --frontend_radius=2" +\ " --frontend_nms=1" +\ " --inac_range=3" +\ " --visual_only=0" +\ " --far_threshold=-1" +\ " --translation_threshold=0.25" +\ " --mask_threshold=0.0" +\ " --skip_edge=[]" +\ " --save_pkl" +\ " --use_odo" +\ " --odopath=/home/zhouyuxuan/data/WUH1012/odo_synthesis.txt" +\ " --pklpath=results/whu.pkl" +\ " --show_plot", shell=True) p.wait() # VIO + GNSS p = subprocess.Popen("python demo_vio_whu.py" +\ " --imagedir=/home/zhouyuxuan/data/WUH1012/cam0" +\ " --imagestamp=/home/zhouyuxuan/data/WUH1012/camstamp.txt" +\ " --imupath=/home/zhouyuxuan/data/WUH1012/imu.txt" +\ " --gtpath=/home/zhouyuxuan/data/WUH1012/IE.txt" +\ " --resultpath=results/result_whu_viog.txt" +\ " --calib=calib/1012.txt" +\ " --stride=2" +\ " --max_factors=48" +\ " --active_window=12" +\ " --frontend_window=5" +\ " --frontend_radius=2" +\ " --frontend_nms=1" +\ " --inac_range=3" +\ " --visual_only=0" +\ " --far_threshold=-1" +\ " --translation_threshold=0.25" +\ " --mask_threshold=0.0" +\ " --skip_edge=[]" +\ " --save_pkl" +\ " --use_gnss" +\ " --gnsspath=/home/zhouyuxuan/data/data_20221012103154/SEPT-PVT.flt" +\ " --pklpath=results/whu.pkl" +\ " --show_plot", shell=True) p.wait() ================================================ FILE: calib/0412.txt ================================================ 889.32868436 889.32868436 515.73648834 202.43873596 ================================================ FILE: calib/0412new.txt ================================================ 885.839465 882.512623 505.509972 389.860117 -0.125551 0.065179 -0.000074 -0.000698 ================================================ FILE: calib/1012.txt ================================================ 890.21388839 889.56330572 512.88196119 381.38486858 -0.13095809 0.06640391 -0.00094794 0.0003389 ================================================ FILE: calib/barn.txt ================================================ 1161.545689 1161.545689 960.000000 540.000000 -0.025158 0.0 0.0 0.0 ================================================ FILE: calib/carla.txt ================================================ 886.8100 886.8100 512 256 ================================================ FILE: calib/eth.txt ================================================ 726.21081542969 726.21081542969 359.2048034668 202.47247314453 ================================================ FILE: calib/euroc.txt ================================================ 458.654 457.296 367.215 248.375 -0.28340811 0.07395907 0.00019359 1.76187114e-05 ================================================ FILE: calib/handheld.txt ================================================ 531.0895358407821 530.9183032386885 511.3708876141611 399.1276554093305 -0.3367182787437319 0.10679061024072911 0.0003055063102509499 0.0009756613499403765 ================================================ FILE: calib/kitti_360.txt ================================================ 788.629315 786.382230 687.158398 317.752196 -0.344441 0.141678 0.000414 -0.000222 -0.029608 ================================================ FILE: calib/subt.txt ================================================ 758.3153257832925 676.6492212772476 318.27111164892506 239.79816832491474 1.583106303248484 -0.059098218173967695 0.1793477408661115 0.0016819528105368057 -0.0005887999624264534 ================================================ FILE: calib/tartan.txt ================================================ 320.0 320.0 320.0 240.0 ================================================ FILE: calib/tum3.txt ================================================ 535.4 539.2 320.1 247.6 ================================================ FILE: calib/tumvi.txt ================================================ 190.97847715128717 190.9733070521226 254.93170605935475 256.8974428996504 0.0034823894022493434 0.0007150348452162257 -0.0020532361418706202 0.00020293673591811182 ================================================ FILE: dataset/euroc_to_hdf5.py ================================================ from tqdm import tqdm import numpy as np import torch import cv2 import os import argparse import h5py import pickle def show_image(image): image = image.permute(1, 2, 0).cpu().numpy() cv2.imshow('image', image / 255.0) cv2.waitKey(1) def image_stream(imagedir, imagestamp, h5path, calib, stride): """ image generator """ calib = np.loadtxt(calib, delimiter=" ") fx, fy, cx, cy = calib[:4] K = np.eye(3) K[0,0] = fx K[0,2] = cx K[1,1] = fy K[1,2] = cy Kn = np.eye(3) Kn[0,0] = fx Kn[0,2] = cx Kn[1,1] = fy Kn[1,2] = cy image_list = sorted(os.listdir(imagedir))[::stride] image_stamps = np.loadtxt(imagestamp,str,delimiter=',') image_dict = dict(zip(image_stamps[:,1],image_stamps[:,0])) h5_f = h5py.File(h5path,'w') for t, imfile in enumerate(image_list): image = cv2.imread(os.path.join(imagedir, imfile)) if len(calib) > 4: m1, m2 = cv2.initUndistortRectifyMap(K,calib[4:],np.eye(3),Kn,(image.shape[1],image.shape[0]),cv2.CV_32FC1) image = cv2.remap(image, m1, m2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT) tt = float(image_dict[imfile]) /1e9 h0, w0, _ = image.shape h1 = int(h0 * np.sqrt((384 * 512) / (h0 * w0))) w1 = int(w0 * np.sqrt((384 * 512) / (h0 * w0))) image = cv2.resize(image, (w1, h1)) image = image[:h1-h1%8, :w1-w1%8] image = torch.as_tensor(image).permute(2, 0, 1) intrinsics = torch.as_tensor([fx, fy, cx, cy ]) intrinsics[0::2] *= (w1 / w0) intrinsics[1::2] *= (h1 / h0) h5_f.create_dataset('%.10f'%tt,data = np.fromstring(pickle.dumps((tt, image[None], intrinsics)),dtype='uint8')) yield tt, image[None], intrinsics h5_f.close() if __name__ == '__main__': print(torch.cuda.device_count()) print(torch.cuda.is_available()) print(torch.cuda.current_device()) parser = argparse.ArgumentParser() parser.add_argument("--imagedir", type=str, help="path to image directory") parser.add_argument("--imagestamp", type=str, help="") parser.add_argument("--h5path", type=str, help="") parser.add_argument("--calib", type=str, help="path to calibration file") parser.add_argument("--stride", default=4, type=int, help="frame stride") parser.add_argument("--show_plot", action="store_true", help="") args = parser.parse_args() for (t, image, intrinsics) in tqdm(image_stream(args.imagedir, args.imagestamp,\ args.h5path, args.calib, args.stride)): if args.show_plot: show_image(image[0]) ================================================ FILE: dataset/kitti360_to_hdf5.py ================================================ from tqdm import tqdm import numpy as np import torch import cv2 import os import argparse import h5py import pickle def show_image(image): image = image.permute(1, 2, 0).cpu().numpy() cv2.imshow('image', image / 255.0) cv2.waitKey(1) def image_stream(imagedir, imagestamp, h5path, calib, stride): """ image generator """ calib = np.loadtxt(calib, delimiter=" ") fx, fy, cx, cy = calib[:4] K = np.eye(3) K[0,0] = fx K[0,2] = cx K[1,1] = fy K[1,2] = cy Kn = np.eye(3) Kn[0,0] = fx Kn[0,2] = cx Kn[1,1] = fy Kn[1,2] = cy image_list = sorted(os.listdir(imagedir))[::stride] image_stamps = np.loadtxt(imagestamp,str) image_dict = dict(zip(image_stamps[:,1],image_stamps[:,0])) h5_f = h5py.File(h5path,'w') for t, imfile in enumerate(image_list): image = cv2.imread(os.path.join(imagedir, imfile)) if len(calib) > 4: image = cv2.undistort(image, K, calib[4:]) tt = float(image_dict[imfile]) h0, w0, _ = image.shape h1 = int(h0 * np.sqrt((384 * 512) / (h0 * w0))) w1 = int(w0 * np.sqrt((384 * 512) / (h0 * w0))) image = cv2.resize(image, (w1, h1)) image = image[:h1-h1%8, :w1-w1%8] image = torch.as_tensor(image).permute(2, 0, 1) intrinsics = torch.as_tensor([fx, fy, cx, cy]) intrinsics[0::2] *= (w1 / w0) intrinsics[1::2] *= (h1 / h0) h5_f.create_dataset('%.10f'%tt,data = np.fromstring(pickle.dumps((tt, image[None], intrinsics)),dtype='uint8')) yield tt, image[None], intrinsics h5_f.close() if __name__ == '__main__': print(torch.cuda.device_count()) print(torch.cuda.is_available()) print(torch.cuda.current_device()) parser = argparse.ArgumentParser() parser.add_argument("--imagedir", type=str, help="path to image directory") parser.add_argument("--imagestamp", type=str, help="") parser.add_argument("--h5path", type=str, help="") parser.add_argument("--calib", type=str, help="path to calibration file") parser.add_argument("--stride", default=2, type=int, help="frame stride") parser.add_argument("--show_plot", action="store_true", help="") args = parser.parse_args() for (t, image, intrinsics) in tqdm(image_stream(args.imagedir, args.imagestamp,\ args.h5path, args.calib, args.stride)): if args.show_plot: show_image(image[0]) ================================================ FILE: dataset/tumvi_to_hdf5.py ================================================ from tqdm import tqdm import numpy as np import torch import cv2 import os import argparse import h5py import pickle def show_image(image): image = image.permute(1, 2, 0).cpu().numpy() cv2.imshow('image', image / 255.0) cv2.waitKey(1) def image_stream(imagedir, imagestamp, h5path, calib, stride): """ image generator """ calib = np.loadtxt(calib, delimiter=" ") fx, fy, cx, cy = calib[:4] K = np.eye(3) K[0,0] = fx K[0,2] = cx K[1,1] = fy K[1,2] = cy Kn = np.eye(3) Kn[0,0] = fx Kn[0,2] = cx Kn[1,1] = fy Kn[1,2] = cy image_list = sorted(os.listdir(imagedir))[::stride] image_stamps = np.loadtxt(imagestamp,str,delimiter=',') image_dict = dict(zip(image_stamps[:,1],image_stamps[:,0])) h5_f = h5py.File(h5path,'w') for t, imfile in enumerate(image_list): image = cv2.imread(os.path.join(imagedir, imfile)) if len(calib) > 4: m1, m2 = cv2.fisheye.initUndistortRectifyMap(K,calib[4:],np.eye(3),Kn,(512,512),cv2.CV_32FC1) image = cv2.remap(image, m1, m2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT) tt = float(image_dict[imfile]) /1e9 h0, w0, _ = image.shape h1 = int(h0 * np.sqrt((384 * 512) / (h0 * w0))) w1 = int(w0 * np.sqrt((384 * 512) / (h0 * w0))) image = cv2.resize(image, (w1, h1)) image = image[:h1-h1%8, :w1-w1%8] image = torch.as_tensor(image).permute(2, 0, 1) intrinsics = torch.as_tensor([fx, fy, cx, cy ]) intrinsics[0::2] *= (w1 / w0) intrinsics[1::2] *= (h1 / h0) h5_f.create_dataset('%.10f'%tt,data = np.fromstring(pickle.dumps((tt, image[None], intrinsics)),dtype='uint8')) yield tt, image[None], intrinsics h5_f.close() if __name__ == '__main__': print(torch.cuda.device_count()) print(torch.cuda.is_available()) print(torch.cuda.current_device()) parser = argparse.ArgumentParser() parser.add_argument("--imagedir", type=str, help="path to image directory") parser.add_argument("--imagestamp", type=str, help="") parser.add_argument("--h5path", type=str, help="") parser.add_argument("--calib", type=str, help="path to calibration file") parser.add_argument("--stride", default=4, type=int, help="frame stride") parser.add_argument("--show_plot", action="store_true", help="") args = parser.parse_args() for (t, image, intrinsics) in tqdm(image_stream(args.imagedir, args.imagestamp,\ args.h5path, args.calib, args.stride)): if args.show_plot: show_image(image[0]) ================================================ FILE: dbaf/covisible_graph.py ================================================ import torch import lietorch import numpy as np import matplotlib.pyplot as plt from lietorch import SE3 from modules.corr import CorrBlock, AltCorrBlock import geom.projective_ops as pops import matplotlib.pyplot as plt import cv2 from depth_video import DepthVideo import matplotlib.cm as cm import matplotlib class CovisibleGraph: def __init__(self, video: DepthVideo, update_op, device="cuda:0", corr_impl="volume", args = None): self.video = video self.update_op = update_op self.device = device self.max_factors = args.max_factors self.corr_impl = corr_impl self.upsample = args.upsample # operator at 1/8 resolution self.ht = ht = video.ht // 8 self.wd = wd = video.wd // 8 self.coords0 = pops.coords_grid(ht, wd, device=device) self.ii = torch.as_tensor([], dtype=torch.long, device=device) self.jj = torch.as_tensor([], dtype=torch.long, device=device) self.age = torch.as_tensor([], dtype=torch.long, device=device) self.corr, self.net, self.inp = None, None, None self.damping = 1e-6 * torch.ones_like(self.video.disps) self.target = torch.zeros([1, 0, ht, wd, 2], device=device, dtype=torch.float) self.weight = torch.zeros([1, 0, ht, wd, 2], device=device, dtype=torch.float) # inactive factors self.ii_inac = torch.as_tensor([], dtype=torch.long, device=device) self.jj_inac = torch.as_tensor([], dtype=torch.long, device=device) self.ii_bad = torch.as_tensor([], dtype=torch.long, device=device) self.jj_bad = torch.as_tensor([], dtype=torch.long, device=device) self.target_inac = torch.zeros([1, 0, ht, wd, 2], device=device, dtype=torch.float) self.weight_inac = torch.zeros([1, 0, ht, wd, 2], device=device, dtype=torch.float) self.far_threshold = args.far_threshold self.inac_range = args.inac_range self.mask_threshold = args.mask_threshold self.img_count = 0 self.skip_edge = args.skip_edge self.frontend_window = args.frontend_window # simple online visualization self.show_covisible_graph = False self.show_oldest_disparity = False self.show_flow_and_weight = False def __filter_repeated_edges(self, ii, jj): """ remove duplicate edges """ keep = torch.zeros(ii.shape[0], dtype=torch.bool, device=ii.device) eset = set( [(i.item(), j.item()) for i, j in zip(self.ii, self.jj)] + [(i.item(), j.item()) for i, j in zip(self.ii_inac, self.jj_inac)]) for k, (i, j) in enumerate(zip(ii, jj)): keep[k] = (i.item(), j.item()) not in eset return ii[keep], jj[keep] def print_edges(self): ii = self.ii.cpu().numpy() jj = self.jj.cpu().numpy() ix = np.argsort(ii) ii = ii[ix] jj = jj[ix] w = torch.mean(self.weight, dim=[0,2,3,4]).cpu().numpy() w = w[ix] for e in zip(ii, jj, w): print(e) print() def filter_edges(self): """ remove bad edges """ conf = torch.mean(self.weight, dim=[0,2,3,4]) mask = (torch.abs(self.ii-self.jj) > 2) & (conf < 0.001) self.ii_bad = torch.cat([self.ii_bad, self.ii[mask]]) self.jj_bad = torch.cat([self.jj_bad, self.jj[mask]]) self.rm_factors(mask, store=False) def clear_edges(self): self.rm_factors(self.ii >= 0) self.net = None self.inp = None @torch.cuda.amp.autocast(enabled=True) def add_factors(self, ii, jj, remove=False): """ add edges to factor graph """ if not isinstance(ii, torch.Tensor): ii = torch.as_tensor(ii, dtype=torch.long, device=self.device) if not isinstance(jj, torch.Tensor): jj = torch.as_tensor(jj, dtype=torch.long, device=self.device) # remove duplicate edges ii, jj = self.__filter_repeated_edges(ii, jj) if ii.shape[0] == 0: return # place limit on number of factors if self.max_factors > 0 and self.ii.shape[0] + ii.shape[0] > self.max_factors \ and self.corr is not None and remove: ix = torch.arange(len(self.age))[torch.argsort(self.age).cpu()] self.rm_factors(ix >= self.max_factors - ii.shape[0], store=True) net = self.video.nets[ii].to(self.device).unsqueeze(0) # correlation volume for new edges if self.corr_impl == "volume": c = (ii == jj).long() fmap1 = self.video.fmaps[ii,0].to(self.device).unsqueeze(0) fmap2 = self.video.fmaps[jj,c].to(self.device).unsqueeze(0) corr = CorrBlock(fmap1, fmap2) self.corr = corr if self.corr is None else self.corr.cat(corr) inp = self.video.inps[ii].to(self.device).unsqueeze(0) self.inp = inp if self.inp is None else torch.cat([self.inp, inp], 1) with torch.cuda.amp.autocast(enabled=False): target, _ = self.video.reproject(ii, jj) weight = torch.zeros_like(target) self.ii = torch.cat([self.ii, ii], 0) self.jj = torch.cat([self.jj, jj], 0) self.age = torch.cat([self.age, torch.zeros_like(ii)], 0) # reprojection factors self.net = net if self.net is None else torch.cat([self.net, net], 1) self.target = torch.cat([self.target, target], 1) self.weight = torch.cat([self.weight, weight], 1) @torch.cuda.amp.autocast(enabled=True) def rm_factors(self, mask, store=False): """ drop edges from factor graph """ # store estimated factors if store: self.ii_inac = torch.cat([self.ii_inac, self.ii[mask]], 0) self.jj_inac = torch.cat([self.jj_inac, self.jj[mask]], 0) self.target_inac = torch.cat([self.target_inac, self.target[:,mask]], 1) self.weight_inac = torch.cat([self.weight_inac, self.weight[:,mask]], 1) self.ii = self.ii[~mask] self.jj = self.jj[~mask] self.age = self.age[~mask] if self.corr_impl == "volume": self.corr = self.corr[~mask] if self.net is not None: self.net = self.net[:,~mask] if self.inp is not None: self.inp = self.inp[:,~mask] self.target = self.target[:,~mask] self.weight = self.weight[:,~mask] @torch.cuda.amp.autocast(enabled=True) def rm_keyframe(self, ix): """ drop edges from factor graph """ with self.video.get_lock(): self.video.images[ix] = self.video.images[ix+1] self.video.poses[ix] = self.video.poses[ix+1] self.video.disps[ix] = self.video.disps[ix+1] self.video.disps_sens[ix] = self.video.disps_sens[ix+1] self.video.intrinsics[ix] = self.video.intrinsics[ix+1] self.video.nets[ix] = self.video.nets[ix+1] self.video.inps[ix] = self.video.inps[ix+1] self.video.fmaps[ix] = self.video.fmaps[ix+1] self.video.tstamp[ix] = self.video.tstamp[ix+1] # BUG fix m = (self.ii_inac == ix) | (self.jj_inac == ix) self.ii_inac[self.ii_inac >= ix] -= 1 self.jj_inac[self.jj_inac >= ix] -= 1 if torch.any(m): self.ii_inac = self.ii_inac[~m] self.jj_inac = self.jj_inac[~m] self.target_inac = self.target_inac[:,~m] self.weight_inac = self.weight_inac[:,~m] m = (self.ii == ix) | (self.jj == ix) self.ii[self.ii >= ix] -= 1 self.jj[self.jj >= ix] -= 1 self.rm_factors(m, store=False) @torch.cuda.amp.autocast(enabled=True) def update(self, t0=None, t1=None, itrs=2, use_inactive=False, EP=1e-7, motion_only=False, marg = False): """ run update operator on factor graph """ self.video.logger.info('update') with torch.cuda.amp.autocast(enabled=False): coords1, mask = self.video.reproject(self.ii, self.jj) motn = torch.cat([coords1 - self.coords0, self.target - coords1], dim=-1) motn = motn.permute(0,1,4,2,3).clamp(-64.0, 64.0) # 1,2,4,48,96 corr = self.corr(coords1) self.net, delta, weight, damping, upmask = \ self.update_op(self.net, self.inp, corr, motn, self.ii, self.jj, self.upsample) if t0 is None: t0 = max(1, self.ii.min().item()+1) self.video.logger.info('ba') with torch.cuda.amp.autocast(enabled=False): self.target = coords1 + delta.to(dtype=torch.float) self.weight = weight.to(dtype=torch.float) ht, wd = self.coords0.shape[0:2] if self.upsample: self.damping[torch.unique(self.ii)] = damping if use_inactive: m = (self.ii_inac >= t0 - self.inac_range) & (self.jj_inac >= t0 - self.inac_range) ii = torch.cat([self.ii_inac[m], self.ii], 0) jj = torch.cat([self.jj_inac[m], self.jj], 0) target = torch.cat([self.target_inac[:,m], self.target], 1) weight = torch.cat([self.weight_inac[:,m], self.weight], 1) else: ii, jj, target, weight = self.ii, self.jj, self.target, self.weight # Some real-time visualization for debugging # 1) Disparity if self.show_oldest_disparity: disp_show_front = self.video.disps[self.ii[0]].cpu().numpy() disp_show_front = cv2.resize(disp_show_front,[disp_show_front.shape[1]*8,disp_show_front.shape[0]*8],interpolation = cv2.INTER_NEAREST) disp_show_front= disp_show_front.astype(np.float32) normalizer = matplotlib.colors.Normalize(vmin=-0.2, vmax=1.0) mapper = cm.ScalarMappable(norm=normalizer,cmap='magma') colormapped_im = (mapper.to_rgba(disp_show_front)[:, :, :3] * 255).astype(np.uint8) colormapped_im = cv2.cvtColor(colormapped_im,cv2.COLOR_RGB2BGR) cv2.imshow('colormapped_im',colormapped_im) cv2.waitKey(1) # 2) Optical flow and weight if self.show_flow_and_weight: rgb = self.video.images[torch.max(self.ii)].cpu().numpy().transpose(1,2,0) new_flow_id = torch.where(torch.logical_and(self.ii==torch.max(self.ii),self.jj==torch.max(self.ii)-5))[0][0].item() weight_cpu = weight[0,new_flow_id].cpu().numpy().astype(np.float32) weight_cpu = np.linalg.norm(weight_cpu,axis=2) normalizer = matplotlib.colors.Normalize(vmin=-0.0, vmax=1.5) mapper = cm.ScalarMappable(norm=normalizer,cmap='jet') colormapped_im = (mapper.to_rgba(weight_cpu)[:, :, :3] * 255).astype(np.uint8) colormapped_im = cv2.cvtColor(colormapped_im,cv2.COLOR_RGB2BGR) colormapped_im = cv2.resize(colormapped_im,[rgb.shape[1],rgb.shape[0]]) colormapped_im = cv2.addWeighted(rgb,0.5,colormapped_im,0.5,0) absflow = (self.target[0,new_flow_id] - self.coords0).cpu().numpy() for iii in range(0,absflow.shape[0],4): for jjj in range(0,absflow.shape[1],4): colormapped_im = cv2.line(colormapped_im, (jjj * 8,iii * 8),(int(round((jjj-absflow[iii,jjj,0])* 8)) ,int(round((iii-absflow[iii,jjj,1]) * 8))),(255,255,255),1,cv2.LINE_AA) cv2.imshow('weight_cpu',colormapped_im) self.img_count += 1 # 3) Covisible graph if self.show_covisible_graph: i0 = min(ii) i1 = max(ii) ppp = SE3(self.video.poses[i0:(i1+1)]).inv().matrix()[:,0:3,3].cpu().numpy() # [:,:3].cpu().numpy() scale = max(max(ppp[:,0]) - min(ppp[:,0]),max(ppp[:,1]) - min(ppp[:,1])) ppp[:,0] -= np.mean(ppp[:,0]) ppp[:,1] = -(ppp[:,1]- np.mean(ppp[:,1])) ppp *= max(round(1/scale * 200 / 50)*50,50) ppp += 500 mmm = np.zeros([1000,1000],dtype=np.uint8) for iii in range(0,i1+1-i0): mmm = cv2.circle(mmm,(int(round(ppp[iii,0])),int(round(ppp[iii,1]))),4,255,0) for iii in range(self.ii_inac[m].shape[0]): iiii = self.ii_inac[m][iii]-i0 jjjj = self.jj_inac[m][iii]-i0 mmm = cv2.line(mmm,(int(round(ppp[iiii,0])),int(round(ppp[iiii,1]))),(int(round(ppp[jjjj,0])),int(round(ppp[jjjj,1]))),128,1) for iii in range(self.ii.shape[0]): iiii = self.ii[iii]-i0 jjjj = self.jj[iii]-i0 mmm = cv2.line(mmm,(int(round(ppp[iiii,0])),int(round(ppp[iiii,1]))),(int(round(ppp[jjjj,0])),int(round(ppp[jjjj,1]))),255,1) cv2.imshow('window',mmm) ## Tricks for better performance # 1) downweight far points if self.far_threshold > 0 and self.video.imu_enabled: disp_mask = (self.video.disps < self.far_threshold) mask = disp_mask[ii, :, :] weight[:, mask] /= 1000.0 # 2) downweight far points if self.mask_threshold > 0 and self.video.imu_enabled: pose0 = SE3(self.video.poses[ii]) pose1 = SE3(self.video.poses[jj]) pose01 = pose0*pose1.inv() mask = torch.norm(pose01.translation()[:,:3],dim=1) < self.mask_threshold weight[:,mask,:,:,:] /= 1000.0 # 3) downweight edges related to the newest frame downweight_newframe = True if downweight_newframe: weight[:,ii==max(ii)] /= 10.0 weight[:,jj==max(jj)] /= 4.0 damping = .2 * self.damping[torch.unique(ii)].contiguous() + EP target = target.view(-1, ht, wd, 2).permute(0,3,1,2).contiguous() weight = weight.view(-1, ht, wd, 2).permute(0,3,1,2).contiguous() # Dense bundle adjustment self.video.ba(target, weight, damping, ii, jj, t0, t1, itrs=itrs, lm=1e-4, ep=0.1, motion_only=motion_only) if self.upsample: self.video.upsample(torch.unique(self.ii), upmask) self.age += 1 def add_neighborhood_factors(self, t0, t1, r=3): """ add edges between neighboring frames within radius r """ ii, jj = torch.meshgrid(torch.arange(t0,t1), torch.arange(t0,t1)) ii = ii.reshape(-1).to(dtype=torch.long, device=self.device) jj = jj.reshape(-1).to(dtype=torch.long, device=self.device) c = 1 if self.video.stereo else 0 keep = ((ii - jj).abs() > c) & ((ii - jj).abs() <= r) self.add_factors(ii[keep], jj[keep]) def add_proximity_factors(self, t0=0, t1=0, rad=2, nms=2, beta=0.25, thresh=16.0, remove=False): """ add edges to the factor graph based on distance """ t = self.video.counter.value ix = torch.arange(t0, t) jx = torch.arange(t1, t) ii, jj = torch.meshgrid(ix, jx) ii = ii.reshape(-1) jj = jj.reshape(-1) cc = ii.shape[0] # Opportunistic "skip" edges in the graph if self.skip_edge: if torch.max(ii) - torch.min(ii) == self.frontend_window - 1: jj_add = torch.min(ii) + torch.tensor(self.skip_edge) jj_add = jj_add[jj_add>0] ii_add = torch.zeros_like(jj_add) + torch.max(ii) jj = torch.cat([jj,jj_add]) ii = torch.cat([ii,ii_add]) d = self.video.distance(ii, jj, beta=beta) d[ii - rad < jj] = np.inf d[d > 100] = np.inf ii1 = torch.cat([self.ii, self.ii_bad, self.ii_inac], 0) jj1 = torch.cat([self.jj, self.jj_bad, self.jj_inac], 0) for i, j in zip(ii1.cpu().numpy(), jj1.cpu().numpy()): for di in range(-nms, nms+1): for dj in range(-nms, nms+1): if abs(di) + abs(dj) <= max(min(abs(i-j)-2, nms), 0): i1 = i + di j1 = j + dj if (t0 <= i1 < t) and (t1 <= j1 < t): d[(i1-t0)*(t-t1) + (j1-t1)] = np.inf es = [] for i in range(t0, t): if self.video.stereo: es.append((i, i)) d[(i-t0)*(t-t1) + (i-t1)] = np.inf for j in range(max(i-rad-1,0), i): es.append((i,j)) es.append((j,i)) if (i-t0)*(t-t1) + (j-t1) >=0: d[(i-t0)*(t-t1) + (j-t1)] = np.inf ix = torch.argsort(d) for k in ix: if k >= cc: continue if d[k].item() > thresh: continue if len(es) > self.max_factors: break i = ii[k] j = jj[k] # bidirectional es.append((i, j)) es.append((j, i)) for di in range(-nms, nms+1): for dj in range(-nms, nms+1): if abs(di) + abs(dj) <= max(min(abs(i-j)-2, nms), 0): i1 = i + di j1 = j + dj if (t0 <= i1 < t) and (t1 <= j1 < t): d[(i1-t0)*(t-t1) + (j1-t1)] = np.inf if ii.shape[0] > cc: ix = torch.argsort(d[cc:ii.shape[0]]) if d[cc + ix[0]] < thresh and d[cc + ix[0]] > 0: es.append((ii[cc+ix[0]],jj[cc+ix[0]])) es.append((jj[cc+ix[0]],ii[cc+ix[0]])) ii, jj = torch.as_tensor(es, device=self.device).unbind(dim=-1) self.add_factors(ii, jj, remove) ================================================ FILE: dbaf/data_readers/__init__.py ================================================ ================================================ FILE: dbaf/data_readers/augmentation.py ================================================ import torch import torchvision.transforms as transforms import numpy as np import torch.nn.functional as F class RGBDAugmentor: """ perform augmentation on RGB-D video """ def __init__(self, crop_size): self.crop_size = crop_size self.augcolor = transforms.Compose([ transforms.ToPILImage(), transforms.ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.4/3.14), transforms.RandomGrayscale(p=0.1), transforms.ToTensor()]) self.max_scale = 0.25 def spatial_transform(self, images, depths, poses, intrinsics): """ cropping and resizing """ ht, wd = images.shape[2:] max_scale = self.max_scale min_scale = np.log2(np.maximum( (self.crop_size[0] + 1) / float(ht), (self.crop_size[1] + 1) / float(wd))) scale = 2 ** np.random.uniform(min_scale, max_scale) intrinsics = scale * intrinsics depths = depths.unsqueeze(dim=1) images = F.interpolate(images, scale_factor=scale, mode='bilinear', align_corners=False, recompute_scale_factor=True) depths = F.interpolate(depths, scale_factor=scale, recompute_scale_factor=True) # always perform center crop (TODO: try non-center crops) y0 = (images.shape[2] - self.crop_size[0]) // 2 x0 = (images.shape[3] - self.crop_size[1]) // 2 intrinsics = intrinsics - torch.tensor([0.0, 0.0, x0, y0]) images = images[:, :, y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]] depths = depths[:, :, y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]] depths = depths.squeeze(dim=1) return images, poses, depths, intrinsics def color_transform(self, images): """ color jittering """ num, ch, ht, wd = images.shape images = images.permute(1, 2, 3, 0).reshape(ch, ht, wd*num) images = 255 * self.augcolor(images[[2,1,0]] / 255.0) return images[[2,1,0]].reshape(ch, ht, wd, num).permute(3,0,1,2).contiguous() def __call__(self, images, poses, depths, intrinsics): images = self.color_transform(images) return self.spatial_transform(images, depths, poses, intrinsics) ================================================ FILE: dbaf/data_readers/base.py ================================================ import numpy as np import torch import torch.utils.data as data import torch.nn.functional as F import csv import os import cv2 import math import random import json import pickle import os.path as osp from .augmentation import RGBDAugmentor from .rgbd_utils import * class RGBDDataset(data.Dataset): def __init__(self, name, datapath, n_frames=4, crop_size=[384,512], fmin=8.0, fmax=75.0, do_aug=True): """ Base class for RGBD dataset """ self.aug = None self.root = datapath self.name = name self.n_frames = n_frames self.fmin = fmin # exclude very easy examples self.fmax = fmax # exclude very hard examples if do_aug: self.aug = RGBDAugmentor(crop_size=crop_size) # building dataset is expensive, cache so only needs to be performed once cur_path = osp.dirname(osp.abspath(__file__)) if not os.path.isdir(osp.join(cur_path, 'cache')): os.mkdir(osp.join(cur_path, 'cache')) cache_path = osp.join(cur_path, 'cache', '{}.pickle'.format(self.name)) if osp.isfile(cache_path): scene_info = pickle.load(open(cache_path, 'rb'))[0] else: scene_info = self._build_dataset() with open(cache_path, 'wb') as cachefile: pickle.dump((scene_info,), cachefile) self.scene_info = scene_info self._build_dataset_index() def _build_dataset_index(self): self.dataset_index = [] for scene in self.scene_info: if not self.__class__.is_test_scene(scene): graph = self.scene_info[scene]['graph'] for i in graph: if len(graph[i][0]) > self.n_frames: self.dataset_index.append((scene, i)) else: print("Reserving {} for validation".format(scene)) @staticmethod def image_read(image_file): return cv2.imread(image_file) @staticmethod def depth_read(depth_file): return np.load(depth_file) def build_frame_graph(self, poses, depths, intrinsics, f=16, max_flow=256): """ compute optical flow distance between all pairs of frames """ def read_disp(fn): depth = self.__class__.depth_read(fn)[f//2::f, f//2::f] depth[depth < 0.01] = np.mean(depth) return 1.0 / depth poses = np.array(poses) intrinsics = np.array(intrinsics) / f disps = np.stack(list(map(read_disp, depths)), 0) d = f * compute_distance_matrix_flow(poses, disps, intrinsics) # uncomment for nice visualization # import matplotlib.pyplot as plt # plt.imshow(d) # plt.show() graph = {} for i in range(d.shape[0]): j, = np.where(d[i] < max_flow) graph[i] = (j, d[i,j]) return graph def __getitem__(self, index): """ return training video """ index = index % len(self.dataset_index) scene_id, ix = self.dataset_index[index] frame_graph = self.scene_info[scene_id]['graph'] images_list = self.scene_info[scene_id]['images'] depths_list = self.scene_info[scene_id]['depths'] poses_list = self.scene_info[scene_id]['poses'] intrinsics_list = self.scene_info[scene_id]['intrinsics'] inds = [ ix ] while len(inds) < self.n_frames: # get other frames within flow threshold k = (frame_graph[ix][1] > self.fmin) & (frame_graph[ix][1] < self.fmax) frames = frame_graph[ix][0][k] # prefer frames forward in time if np.count_nonzero(frames[frames > ix]): ix = np.random.choice(frames[frames > ix]) elif np.count_nonzero(frames): ix = np.random.choice(frames) inds += [ ix ] images, depths, poses, intrinsics = [], [], [], [] for i in inds: images.append(self.__class__.image_read(images_list[i])) depths.append(self.__class__.depth_read(depths_list[i])) poses.append(poses_list[i]) intrinsics.append(intrinsics_list[i]) images = np.stack(images).astype(np.float32) depths = np.stack(depths).astype(np.float32) poses = np.stack(poses).astype(np.float32) intrinsics = np.stack(intrinsics).astype(np.float32) images = torch.from_numpy(images).float() images = images.permute(0, 3, 1, 2) disps = torch.from_numpy(1.0 / depths) poses = torch.from_numpy(poses) intrinsics = torch.from_numpy(intrinsics) if self.aug is not None: images, poses, disps, intrinsics = \ self.aug(images, poses, disps, intrinsics) # scale scene if len(disps[disps>0.01]) > 0: s = disps[disps>0.01].mean() disps = disps / s poses[...,:3] *= s return images, poses, disps, intrinsics def __len__(self): return len(self.dataset_index) def __imul__(self, x): self.dataset_index *= x return self ================================================ FILE: dbaf/data_readers/factory.py ================================================ import pickle import os import os.path as osp # RGBD-Dataset from .tartan import TartanAir from .stream import ImageStream from .stream import StereoStream from .stream import RGBDStream # streaming datasets for inference from .tartan import TartanAirStream from .tartan import TartanAirTestStream def dataset_factory(dataset_list, **kwargs): """ create a combined dataset """ from torch.utils.data import ConcatDataset dataset_map = { 'tartan': (TartanAir, ) } db_list = [] for key in dataset_list: # cache datasets for faster future loading db = dataset_map[key][0](**kwargs) print("Dataset {} has {} images".format(key, len(db))) db_list.append(db) return ConcatDataset(db_list) def create_datastream(dataset_path, **kwargs): """ create data_loader to stream images 1 by 1 """ from torch.utils.data import DataLoader if osp.isfile(osp.join(dataset_path, 'calibration.txt')): db = ETH3DStream(dataset_path, **kwargs) elif osp.isdir(osp.join(dataset_path, 'image_left')): db = TartanAirStream(dataset_path, **kwargs) elif osp.isfile(osp.join(dataset_path, 'rgb.txt')): db = TUMStream(dataset_path, **kwargs) elif osp.isdir(osp.join(dataset_path, 'mav0')): db = EurocStream(dataset_path, **kwargs) elif osp.isfile(osp.join(dataset_path, 'calib.txt')): db = KITTIStream(dataset_path, **kwargs) else: # db = TartanAirStream(dataset_path, **kwargs) db = TartanAirTestStream(dataset_path, **kwargs) stream = DataLoader(db, shuffle=False, batch_size=1, num_workers=4) return stream def create_imagestream(dataset_path, **kwargs): """ create data_loader to stream images 1 by 1 """ from torch.utils.data import DataLoader db = ImageStream(dataset_path, **kwargs) return DataLoader(db, shuffle=False, batch_size=1, num_workers=4) def create_stereostream(dataset_path, **kwargs): """ create data_loader to stream images 1 by 1 """ from torch.utils.data import DataLoader db = StereoStream(dataset_path, **kwargs) return DataLoader(db, shuffle=False, batch_size=1, num_workers=4) def create_rgbdstream(dataset_path, **kwargs): """ create data_loader to stream images 1 by 1 """ from torch.utils.data import DataLoader db = RGBDStream(dataset_path, **kwargs) return DataLoader(db, shuffle=False, batch_size=1, num_workers=4) ================================================ FILE: dbaf/data_readers/rgbd_utils.py ================================================ import numpy as np import os.path as osp import torch from lietorch import SE3 import geom.projective_ops as pops from scipy.spatial.transform import Rotation def parse_list(filepath, skiprows=0): """ read list data """ data = np.loadtxt(filepath, delimiter=' ', dtype=np.unicode_, skiprows=skiprows) return data def associate_frames(tstamp_image, tstamp_depth, tstamp_pose, max_dt=1.0): """ pair images, depths, and poses """ associations = [] for i, t in enumerate(tstamp_image): if tstamp_pose is None: j = np.argmin(np.abs(tstamp_depth - t)) if (np.abs(tstamp_depth[j] - t) < max_dt): associations.append((i, j)) else: j = np.argmin(np.abs(tstamp_depth - t)) k = np.argmin(np.abs(tstamp_pose - t)) if (np.abs(tstamp_depth[j] - t) < max_dt) and \ (np.abs(tstamp_pose[k] - t) < max_dt): associations.append((i, j, k)) return associations def loadtum(datapath, frame_rate=-1): """ read video data in tum-rgbd format """ if osp.isfile(osp.join(datapath, 'groundtruth.txt')): pose_list = osp.join(datapath, 'groundtruth.txt') elif osp.isfile(osp.join(datapath, 'pose.txt')): pose_list = osp.join(datapath, 'pose.txt') else: return None, None, None, None image_list = osp.join(datapath, 'rgb.txt') depth_list = osp.join(datapath, 'depth.txt') calib_path = osp.join(datapath, 'calibration.txt') intrinsic = None if osp.isfile(calib_path): intrinsic = np.loadtxt(calib_path, delimiter=' ') intrinsic = intrinsic.astype(np.float64) image_data = parse_list(image_list) depth_data = parse_list(depth_list) pose_data = parse_list(pose_list, skiprows=1) pose_vecs = pose_data[:,1:].astype(np.float64) tstamp_image = image_data[:,0].astype(np.float64) tstamp_depth = depth_data[:,0].astype(np.float64) tstamp_pose = pose_data[:,0].astype(np.float64) associations = associate_frames(tstamp_image, tstamp_depth, tstamp_pose) # print(len(tstamp_image)) # print(len(associations)) indicies = range(len(associations))[::5] # indicies = [ 0 ] # for i in range(1, len(associations)): # t0 = tstamp_image[associations[indicies[-1]][0]] # t1 = tstamp_image[associations[i][0]] # if t1 - t0 > 1.0 / frame_rate: # indicies += [ i ] images, poses, depths, intrinsics, tstamps = [], [], [], [], [] for ix in indicies: (i, j, k) = associations[ix] images += [ osp.join(datapath, image_data[i,1]) ] depths += [ osp.join(datapath, depth_data[j,1]) ] poses += [ pose_vecs[k] ] tstamps += [ tstamp_image[i] ] if intrinsic is not None: intrinsics += [ intrinsic ] return images, depths, poses, intrinsics, tstamps def all_pairs_distance_matrix(poses, beta=2.5): """ compute distance matrix between all pairs of poses """ poses = np.array(poses, dtype=np.float32) poses[:,:3] *= beta # scale to balence rot + trans poses = SE3(torch.from_numpy(poses)) r = (poses[:,None].inv() * poses[None,:]).log() return r.norm(dim=-1).cpu().numpy() def pose_matrix_to_quaternion(pose): """ convert 4x4 pose matrix to (t, q) """ q = Rotation.from_matrix(pose[:3, :3]).as_quat() return np.concatenate([pose[:3, 3], q], axis=0) def compute_distance_matrix_flow(poses, disps, intrinsics): """ compute flow magnitude between all pairs of frames """ if not isinstance(poses, SE3): poses = torch.from_numpy(poses).float().cuda()[None] poses = SE3(poses).inv() disps = torch.from_numpy(disps).float().cuda()[None] intrinsics = torch.from_numpy(intrinsics).float().cuda()[None] N = poses.shape[1] ii, jj = torch.meshgrid(torch.arange(N), torch.arange(N)) ii = ii.reshape(-1).cuda() jj = jj.reshape(-1).cuda() MAX_FLOW = 100.0 matrix = np.zeros((N, N), dtype=np.float32) s = 2048 for i in range(0, ii.shape[0], s): flow1, val1 = pops.induced_flow(poses, disps, intrinsics, ii[i:i+s], jj[i:i+s]) flow2, val2 = pops.induced_flow(poses, disps, intrinsics, jj[i:i+s], ii[i:i+s]) flow = torch.stack([flow1, flow2], dim=2) val = torch.stack([val1, val2], dim=2) mag = flow.norm(dim=-1).clamp(max=MAX_FLOW) mag = mag.view(mag.shape[1], -1) val = val.view(val.shape[1], -1) mag = (mag * val).mean(-1) / val.mean(-1) mag[val.mean(-1) < 0.7] = np.inf i1 = ii[i:i+s].cpu().numpy() j1 = jj[i:i+s].cpu().numpy() matrix[i1, j1] = mag.cpu().numpy() return matrix def compute_distance_matrix_flow2(poses, disps, intrinsics, beta=0.4): """ compute flow magnitude between all pairs of frames """ # if not isinstance(poses, SE3): # poses = torch.from_numpy(poses).float().cuda()[None] # poses = SE3(poses).inv() # disps = torch.from_numpy(disps).float().cuda()[None] # intrinsics = torch.from_numpy(intrinsics).float().cuda()[None] N = poses.shape[1] ii, jj = torch.meshgrid(torch.arange(N), torch.arange(N)) ii = ii.reshape(-1) jj = jj.reshape(-1) MAX_FLOW = 128.0 matrix = np.zeros((N, N), dtype=np.float32) s = 2048 for i in range(0, ii.shape[0], s): flow1a, val1a = pops.induced_flow(poses, disps, intrinsics, ii[i:i+s], jj[i:i+s], tonly=True) flow1b, val1b = pops.induced_flow(poses, disps, intrinsics, ii[i:i+s], jj[i:i+s]) flow2a, val2a = pops.induced_flow(poses, disps, intrinsics, jj[i:i+s], ii[i:i+s], tonly=True) flow2b, val2b = pops.induced_flow(poses, disps, intrinsics, ii[i:i+s], jj[i:i+s]) flow1 = flow1a + beta * flow1b val1 = val1a * val2b flow2 = flow2a + beta * flow2b val2 = val2a * val2b flow = torch.stack([flow1, flow2], dim=2) val = torch.stack([val1, val2], dim=2) mag = flow.norm(dim=-1).clamp(max=MAX_FLOW) mag = mag.view(mag.shape[1], -1) val = val.view(val.shape[1], -1) mag = (mag * val).mean(-1) / val.mean(-1) mag[val.mean(-1) < 0.8] = np.inf i1 = ii[i:i+s].cpu().numpy() j1 = jj[i:i+s].cpu().numpy() matrix[i1, j1] = mag.cpu().numpy() return matrix ================================================ FILE: dbaf/data_readers/stream.py ================================================ import numpy as np import torch import torch.utils.data as data import torch.nn.functional as F import csv import os import cv2 import math import random import json import pickle import os.path as osp from .rgbd_utils import * class RGBDStream(data.Dataset): def __init__(self, datapath, frame_rate=-1, image_size=[384,512], crop_size=[0,0]): self.datapath = datapath self.frame_rate = frame_rate self.image_size = image_size self.crop_size = crop_size self._build_dataset_index() @staticmethod def image_read(image_file): return cv2.imread(image_file) @staticmethod def depth_read(depth_file): return np.load(depth_file) def __len__(self): return len(self.images) def __getitem__(self, index): """ return training video """ image = self.__class__.image_read(self.images[index]) image = torch.from_numpy(image).float() image = image.permute(2, 0, 1) try: tstamp = self.tstamps[index] except: tstamp = index pose = torch.from_numpy(self.poses[index]).float() intrinsic = torch.from_numpy(self.intrinsics[index]).float() # resize image sx = self.image_size[1] / image.shape[2] sy = self.image_size[0] / image.shape[1] image = F.interpolate(image[None], self.image_size, mode='bilinear', align_corners=False)[0] fx, fy, cx, cy = intrinsic.unbind(dim=0) fx, cx = sx * fx, sx * cx fy, cy = sy * fy, sy * cy # crop image if self.crop_size[0] > 0: cy = cy - self.crop_size[0] image = image[:,self.crop_size[0]:-self.crop_size[0],:] if self.crop_size[1] > 0: cx = cx - self.crop_size[1] image = image[:,:,self.crop_size[1]:-self.crop_size[1]] intrinsic = torch.stack([fx, fy, cx, cy]) return tstamp, image, pose, intrinsic class ImageStream(data.Dataset): def __init__(self, datapath, intrinsics, rate=1, image_size=[384,512]): rgb_list = osp.join(datapath, 'rgb.txt') if os.path.isfile(rgb_list): rgb_list = np.loadtxt(rgb_list, delimiter=' ', dtype=np.unicode_) self.timestamps = rgb_list[:,0].astype(np.float) self.images = [os.path.join(datapath, x) for x in rgb_list[:,1]] self.images = self.images[::rate] self.timestamps = self.timestamps[::rate] else: import glob self.images = sorted(glob.glob(osp.join(datapath, '*.jpg'))) + sorted(glob.glob(osp.join(datapath, '*.png'))) self.images = self.images[::rate] self.intrinsics = intrinsics self.image_size = image_size def __len__(self): return len(self.images) @staticmethod def image_read(imfile): return cv2.imread(imfile) def __getitem__(self, index): """ return training video """ image = self.__class__.image_read(self.images[index]) try: tstamp = self.timestamps[index] except: tstamp = index ht0, wd0 = image.shape[:2] ht1, wd1 = self.image_size intrinsics = torch.as_tensor(self.intrinsics) intrinsics[0] *= wd1 / wd0 intrinsics[1] *= ht1 / ht0 intrinsics[2] *= wd1 / wd0 intrinsics[3] *= ht1 / ht0 # resize image ikwargs = {'mode': 'bilinear', 'align_corners': True} image = torch.from_numpy(image).float().permute(2, 0, 1) image = F.interpolate(image[None], self.image_size, **ikwargs)[0] return tstamp, image, intrinsics class StereoStream(data.Dataset): def __init__(self, datapath, intrinsics, rate=1, image_size=[384,512], map_left=None, map_right=None, left_root='image_left', right_root='image_right'): import glob self.intrinsics = intrinsics self.image_size = image_size imgs = sorted(glob.glob(osp.join(datapath, left_root, '*.png')))[::rate] self.images_l = [] self.images_r = [] self.tstamps = [] for img_l in imgs: img_r = img_l.replace(left_root, right_root) if os.path.isfile(img_r): t = np.float(img_l.split('/')[-1].replace('.png', '')) self.tstamps.append(t) self.images_l += [ img_l ] self.images_r += [ img_r ] self.map_left = map_left self.map_right = map_right def __len__(self): return len(self.images_l) @staticmethod def image_read(imfile, imap=None): image = cv2.imread(imfile) if imap is not None: image = cv2.remap(image, imap[0], imap[1], interpolation=cv2.INTER_LINEAR) return image def __getitem__(self, index): """ return training video """ tstamp = self.tstamps[index] image_l = self.__class__.image_read(self.images_l[index], self.map_left) image_r = self.__class__.image_read(self.images_r[index], self.map_right) ht0, wd0 = image_l.shape[:2] ht1, wd1 = self.image_size intrinsics = torch.as_tensor(self.intrinsics) intrinsics[0] *= wd1 / wd0 intrinsics[1] *= ht1 / ht0 intrinsics[2] *= wd1 / wd0 intrinsics[3] *= ht1 / ht0 image_l = torch.from_numpy(image_l).float().permute(2, 0, 1) image_r = torch.from_numpy(image_r).float().permute(2, 0, 1) # resize image ikwargs = {'mode': 'bilinear', 'align_corners': True} image_l = F.interpolate(image_l[None], self.image_size, **ikwargs)[0] image_r = F.interpolate(image_r[None], self.image_size, **ikwargs)[0] return tstamp, image_l, image_r, intrinsics # class RGBDStream(data.Dataset): # def __init__(self, datapath, intrinsics=None, rate=1, image_size=[384,512]): # assoc_file = osp.join(datapath, 'associated.txt') # assoc_list = np.loadtxt(assoc_file, delimiter=' ', dtype=np.unicode_) # self.intrinsics = intrinsics # self.image_size = image_size # self.timestamps = assoc_list[:,0].astype(np.float)[::rate] # self.images = [os.path.join(datapath, x) for x in assoc_list[:,1]][::rate] # self.depths = [os.path.join(datapath, x) for x in assoc_list[:,3]][::rate] # def __len__(self): # return len(self.images) # @staticmethod # def image_read(imfile): # return cv2.imread(imfile) # @staticmethod # def depth_read(depth_file): # depth = cv2.imread(depth_file, cv2.IMREAD_ANYDEPTH) # return depth.astype(np.float32) / 5000.0 # def __getitem__(self, index): # """ return training video """ # tstamp = self.timestamps[index] # image = self.__class__.image_read(self.images[index]) # depth = self.__class__.depth_read(self.depths[index]) # ht0, wd0 = image.shape[:2] # ht1, wd1 = self.image_size # intrinsics = torch.as_tensor(self.intrinsics) # intrinsics[0] *= wd1 / wd0 # intrinsics[1] *= ht1 / ht0 # intrinsics[2] *= wd1 / wd0 # intrinsics[3] *= ht1 / ht0 # # resize image # ikwargs = {'mode': 'bilinear', 'align_corners': True} # image = torch.from_numpy(image).float().permute(2, 0, 1) # image = F.interpolate(image[None], self.image_size, **ikwargs)[0] # depth = torch.from_numpy(depth).float()[None,None] # depth = F.interpolate(depth, self.image_size, mode='nearest').squeeze() # return tstamp, image, depth, intrinsics ================================================ FILE: dbaf/data_readers/tartan.py ================================================ import numpy as np import torch import glob import cv2 import os import os.path as osp from lietorch import SE3 from .base import RGBDDataset from .stream import RGBDStream cur_path = osp.dirname(osp.abspath(__file__)) test_split = osp.join(cur_path, 'tartan_test.txt') test_split = open(test_split).read().split() class TartanAir(RGBDDataset): # scale depths to balance rot & trans DEPTH_SCALE = 5.0 def __init__(self, mode='training', **kwargs): self.mode = mode self.n_frames = 2 super(TartanAir, self).__init__(name='TartanAir', **kwargs) @staticmethod def is_test_scene(scene): # print(scene, any(x in scene for x in test_split)) return any(x in scene for x in test_split) def _build_dataset(self): from tqdm import tqdm print("Building TartanAir dataset") scene_info = {} scenes = glob.glob(osp.join(self.root, '*/*/*/*')) for scene in tqdm(sorted(scenes)): images = sorted(glob.glob(osp.join(scene, 'image_left/*.png'))) depths = sorted(glob.glob(osp.join(scene, 'depth_left/*.npy'))) poses = np.loadtxt(osp.join(scene, 'pose_left.txt'), delimiter=' ') poses = poses[:, [1, 2, 0, 4, 5, 3, 6]] poses[:,:3] /= TartanAir.DEPTH_SCALE intrinsics = [TartanAir.calib_read()] * len(images) # graph of co-visible frames based on flow graph = self.build_frame_graph(poses, depths, intrinsics) scene = '/'.join(scene.split('/')) scene_info[scene] = {'images': images, 'depths': depths, 'poses': poses, 'intrinsics': intrinsics, 'graph': graph} return scene_info @staticmethod def calib_read(): return np.array([320.0, 320.0, 320.0, 240.0]) @staticmethod def image_read(image_file): return cv2.imread(image_file) @staticmethod def depth_read(depth_file): depth = np.load(depth_file) / TartanAir.DEPTH_SCALE depth[depth==np.nan] = 1.0 depth[depth==np.inf] = 1.0 return depth class TartanAirStream(RGBDStream): def __init__(self, datapath, **kwargs): super(TartanAirStream, self).__init__(datapath=datapath, **kwargs) def _build_dataset_index(self): """ build list of images, poses, depths, and intrinsics """ self.root = 'datasets/TartanAir' scene = osp.join(self.root, self.datapath) image_glob = osp.join(scene, 'image_left/*.png') images = sorted(glob.glob(image_glob)) poses = np.loadtxt(osp.join(scene, 'pose_left.txt'), delimiter=' ') poses = poses[:, [1, 2, 0, 4, 5, 3, 6]] poses = SE3(torch.as_tensor(poses)) poses = poses[[0]].inv() * poses poses = poses.data.cpu().numpy() intrinsic = self.calib_read(self.datapath) intrinsics = np.tile(intrinsic[None], (len(images), 1)) self.images = images[::int(self.frame_rate)] self.poses = poses[::int(self.frame_rate)] self.intrinsics = intrinsics[::int(self.frame_rate)] @staticmethod def calib_read(datapath): return np.array([320.0, 320.0, 320.0, 240.0]) @staticmethod def image_read(image_file): return cv2.imread(image_file) class TartanAirTestStream(RGBDStream): def __init__(self, datapath, **kwargs): super(TartanAirTestStream, self).__init__(datapath=datapath, **kwargs) def _build_dataset_index(self): """ build list of images, poses, depths, and intrinsics """ self.root = 'datasets/mono' image_glob = osp.join(self.root, self.datapath, '*.png') images = sorted(glob.glob(image_glob)) poses = np.loadtxt(osp.join(self.root, 'mono_gt', self.datapath + '.txt'), delimiter=' ') poses = poses[:, [1, 2, 0, 4, 5, 3, 6]] poses = SE3(torch.as_tensor(poses)) poses = poses[[0]].inv() * poses poses = poses.data.cpu().numpy() intrinsic = self.calib_read(self.datapath) intrinsics = np.tile(intrinsic[None], (len(images), 1)) self.images = images[::int(self.frame_rate)] self.poses = poses[::int(self.frame_rate)] self.intrinsics = intrinsics[::int(self.frame_rate)] @staticmethod def calib_read(datapath): return np.array([320.0, 320.0, 320.0, 240.0]) @staticmethod def image_read(image_file): return cv2.imread(image_file) ================================================ FILE: dbaf/data_readers/tartan_test.txt ================================================ abandonedfactory/abandonedfactory/Easy/P011 abandonedfactory/abandonedfactory/Hard/P011 abandonedfactory_night/abandonedfactory_night/Easy/P013 abandonedfactory_night/abandonedfactory_night/Hard/P014 amusement/amusement/Easy/P008 amusement/amusement/Hard/P007 carwelding/carwelding/Easy/P007 endofworld/endofworld/Easy/P009 gascola/gascola/Easy/P008 gascola/gascola/Hard/P009 hospital/hospital/Easy/P036 hospital/hospital/Hard/P049 japanesealley/japanesealley/Easy/P007 japanesealley/japanesealley/Hard/P005 neighborhood/neighborhood/Easy/P021 neighborhood/neighborhood/Hard/P017 ocean/ocean/Easy/P013 ocean/ocean/Hard/P009 office2/office2/Easy/P011 office2/office2/Hard/P010 office/office/Hard/P007 oldtown/oldtown/Easy/P007 oldtown/oldtown/Hard/P008 seasidetown/seasidetown/Easy/P009 seasonsforest/seasonsforest/Easy/P011 seasonsforest/seasonsforest/Hard/P006 seasonsforest_winter/seasonsforest_winter/Easy/P009 seasonsforest_winter/seasonsforest_winter/Hard/P018 soulcity/soulcity/Easy/P012 soulcity/soulcity/Hard/P009 westerndesert/westerndesert/Easy/P013 westerndesert/westerndesert/Hard/P007 ================================================ FILE: dbaf/dbaf.py ================================================ import torch import lietorch import numpy as np from droid_net import DroidNet from depth_video import DepthVideo from motion_filter import MotionFilter from dbaf_frontend import DBAFusionFrontend from collections import OrderedDict from torch.multiprocessing import Process from lietorch import SE3 import geom.projective_ops as pops import droid_backends import pickle class DBAFusion: def __init__(self, args): super(DBAFusion, self).__init__() self.load_weights(args.weights) # load DroidNet weights self.args = args # store images, depth, poses, intrinsics (shared between processes) self.video = DepthVideo(args.image_size, args.buffer, save_pkl = args.save_pkl, stereo=args.stereo, upsample=args.upsample) # filter incoming frames so that there is enough motion self.filterx = MotionFilter(self.net, self.video, thresh=args.filter_thresh) # frontend process self.frontend = DBAFusionFrontend(self.net, self.video, self.args) self.pklpath = args.pklpath self.upsample = args.upsample def load_weights(self, weights): """ load trained model weights """ print(weights) self.net = DroidNet() state_dict = OrderedDict([ (k.replace("module.", ""), v) for (k, v) in torch.load(weights).items()]) state_dict["update.weight.2.weight"] = state_dict["update.weight.2.weight"][:2] state_dict["update.weight.2.bias"] = state_dict["update.weight.2.bias"][:2] state_dict["update.delta.2.weight"] = state_dict["update.delta.2.weight"][:2] state_dict["update.delta.2.bias"] = state_dict["update.delta.2.bias"][:2] self.net.load_state_dict(state_dict) self.net.to("cuda:0").eval() def track(self, tstamp, image, depth=None, intrinsics=None): """ main thread - update map """ with torch.no_grad(): # check there is enough motion self.filterx.track(tstamp, image, depth, intrinsics) # local bundle adjustment self.frontend() def terminate(self, stream=None): """ terminate the visualization process, return poses [t, q] """ del self.frontend def save_vis_easy(self): mcameras = {} mpoints = {} mstamps = {} with torch.no_grad(): dirty_index = torch.arange(0,self.video.count_save,device='cuda') stamps= torch.index_select(self.video.tstamp_save, 0 ,dirty_index) poses= torch.index_select( self.video.poses_save, 0 ,dirty_index) disps= torch.index_select( self.video.disps_save, 0 ,dirty_index) images = torch.index_select( self.video.images_save, 0 ,dirty_index) Ps = SE3(poses).inv().matrix().cpu().numpy() points = droid_backends.iproj(SE3(poses).inv().data, disps, self.video.intrinsics[0]).cpu() thresh = 0.4 * torch.ones_like(disps.mean(dim=[1,2])) / 4.0 * (1.0 / torch.median(disps.mean(dim=[1,2]))) # thresh = 0.4 * torch.ones_like(disps.mean(dim=[1,2])) count = droid_backends.depth_filter( self.video.poses_save, self.video.disps_save, self.video.intrinsics[0], dirty_index, thresh) count = count.cpu() disps = disps.cpu() if self.upsample: disps_up= torch.index_select( self.video.disps_up_save, 0 ,dirty_index) disps_up = disps_up.cpu() masks = ((count >= 1) & (disps > .5*disps.mean(dim=[1,2], keepdim=True))) for i in range(len(dirty_index)): pose = Ps[i] ix = dirty_index[i].item() mcameras[ix] = pose mask = masks[i].reshape(-1) pts = points[i].reshape(-1, 3)[mask].cpu().numpy() clr = images[i].reshape(-1, 3)[mask].cpu().numpy() stamp = stamps[i].cpu() if self.upsample: mpoints[ix] = {'pts':pts,'clr':clr,'disp':disps[i].cpu().numpy(),'disps_up':disps_up[i].cpu().numpy(),'rgb':images[i].cpu().numpy()} else: mpoints[ix] = {'pts':pts,'clr':clr,'disp':disps[i].cpu().numpy(),'rgb':images[i].cpu().numpy()} mstamps[ix] = stamp ddict = {'points':mpoints,'cameras':mcameras,'stamps':mstamps} f_save = open(self.pklpath, 'wb') pickle.dump(ddict,f_save) mcameras = {} mpoints = {} mstamps = {} with torch.no_grad(): dirty_index = torch.arange(0,self.video.count_save,device='cuda') stamps= torch.index_select(self.video.tstamp_save, 0 ,dirty_index) poses= torch.index_select( self.video.poses_save, 0 ,dirty_index) disps= torch.index_select( self.video.disps_save, 0 ,dirty_index) images = torch.index_select( self.video.images_save, 0 ,dirty_index) Ps = SE3(poses).inv().matrix().cpu().numpy() points = droid_backends.iproj(SE3(poses).inv().data, disps, self.video.intrinsics[0]).cpu() thresh = 0.4 * torch.ones_like(disps.mean(dim=[1,2])) count = droid_backends.depth_filter( self.video.poses_save, self.video.disps_save, self.video.intrinsics[0], dirty_index, thresh) count = count.cpu() disps = disps.cpu() masks = ((count >= 0) & (disps > .5*disps.mean(dim=[1,2], keepdim=True))) for i in range(len(dirty_index)): pose = Ps[i] ix = dirty_index[i].item() mcameras[ix] = pose mask = masks[i].reshape(-1) pts = points[i].reshape(-1, 3)[mask].cpu().numpy() clr = images[i].reshape(-1, 3)[mask].cpu().numpy() stamp = stamps[i].cpu() mpoints[ix] = {'pts':pts,'clr':clr,'disp':disps[i].cpu().numpy(),'rgb':images[i].cpu().numpy()} mstamps[ix] = stamp ddict = {'points':mpoints,'cameras':mcameras,'stamps':mstamps} f_save = open(self.pklpath.split('.')[0] + '_raw.pkl', 'wb') pickle.dump(ddict,f_save) ================================================ FILE: dbaf/dbaf_frontend.py ================================================ import torch import torchvision import numpy as np from lietorch import SE3, SO3 from covisible_graph import CovisibleGraph import matplotlib.pyplot as plt import gtsam import math import bisect from math import atan2, cos, sin import geoFunc.trans as trans from scipy.spatial.transform import Rotation class DBAFusionFrontend: def __init__(self, net, video, args): self.video = video self.update_op = net.update self.graph = CovisibleGraph(video, net.update, args=args) # local optimization window self.t0 = 0 self.t1 = 0 # frontend variables self.is_initialized = False self.count = 0 self.warmup = args.warmup self.vi_warmup = 12 if 'vi_warmup' in args: self.vi_warmup = args.vi_warmup self.beta = args.beta self.frontend_nms = args.frontend_nms self.keyframe_thresh = args.keyframe_thresh self.frontend_window = args.frontend_window self.frontend_thresh = args.frontend_thresh self.frontend_radius = args.frontend_radius ### DBAFusion self.all_imu = None self.cur_imu_ii = 0 self.is_init = False self.all_gnss = None self.all_odo = None self.all_gt = None self.all_gt_keys = None self.all_stamp = None self.cur_stamp_ii = 0 self.visual_only = args.visual_only self.visual_only_init = False self.translation_threshold = 0.0 self.active_window = args.active_window self.high_freq_output = True self.zupt = ('use_zupt' in args and args.use_zupt) if not self.visual_only: self.max_age = 25 self.iters1 = 2 self.iters2 = 1 else: self.max_age = 25 self.iters1 = 4 self.iters2 = 2 # visualization/output self.show_plot = args.show_plot self.result_file = open(args.resultpath,'wt') self.plt_pos = [[],[]] # X, Y self.plt_pos_ref = [[],[]] # X, Y self.plt_att = [[],[],[]] # pitch, roll, yaw self.plt_bg = [[],[],[]] # X, Y, Z self.plt_t = [] self.refTw = np.eye(4,4) if self.show_plot: plt.figure('monitor',figsize=[13,4]) plt.subplot(1,3,1); plt.gca().set_title('Trajectory') plt.gca().set_aspect(1) plt.subplot(1,3,2); plt.gca().set_title('Attitude Error/Attitude') plt.subplot(1,3,3); plt.gca().set_title('Gyroscope Bias') plt.ion() plt.pause(0.1) def get_pose_ref(self, tt:float): tt_found = self.all_gt_keys[bisect.bisect(self.all_gt_keys,tt)] return tt_found, self.all_gt[tt_found] def __rollup(self, roll): """ roll up window states to save memory """ self.t1 -= roll self.count -= roll self.video.counter.value -= roll self.video.tstamp = torch.roll(self.video.tstamp ,-roll,0) self.video.images = torch.roll(self.video.images ,-roll,0) self.video.dirty = torch.roll(self.video.dirty ,-roll,0) self.video.red = torch.roll(self.video.red ,-roll,0) self.video.poses = torch.roll(self.video.poses ,-roll,0) self.video.disps = torch.roll(self.video.disps ,-roll,0) self.video.disps_sens = torch.roll(self.video.disps_sens,-roll,0) self.video.disps_up = torch.roll(self.video.disps_up ,-roll,0) self.video.intrinsics = torch.roll(self.video.intrinsics,-roll,0) self.video.fmaps = torch.roll(self.video.fmaps ,-roll,0) self.video.nets = torch.roll(self.video.nets ,-roll,0) self.video.inps = torch.roll(self.video.inps ,-roll,0) self.graph.ii -= roll self.graph.jj -= roll self.graph.ii_inac -= roll self.graph.jj_inac -= roll rm_inac_index = torch.logical_and(torch.greater_equal(self.graph.ii_inac,0),torch.greater_equal(self.graph.jj_inac,0)) self.graph.ii_inac = self.graph.ii_inac[rm_inac_index] self.graph.jj_inac = self.graph.jj_inac[rm_inac_index] self.graph.target_inac = self.graph.target_inac[:,rm_inac_index,:,:,:] self.graph.weight_inac = self.graph.weight_inac[:,rm_inac_index,:,:,:] # need test self.graph.ii_bad -= roll self.graph.jj_bad -= roll self.video.last_t0 -= roll self.video.last_t1 -= roll self.video.cur_ii -= roll self.video.cur_jj -= roll if self.video.imu_enabled: graph_temp = gtsam.NonlinearFactorGraph() for i in range(self.video.cur_graph.size()): f = self.video.cur_graph.at(i) graph_temp.push_back(f.rekey((np.array(f.keys())-roll).tolist())) self.video.cur_graph = graph_temp result_temp = gtsam.Values() for i in self.video.cur_result.keys(): if gtsam.Symbol(i).chr() == ord('b'): result_temp.insert(i-roll,self.video.cur_result.atConstantBias(i)) elif gtsam.Symbol(i).chr() == ord('v'): result_temp.insert(i-roll,self.video.cur_result.atVector(i)) elif gtsam.Symbol(i).chr() == ord('x'): result_temp.insert(i-roll,self.video.cur_result.atPose3(i)) else: raise Exception() self.video.cur_result = result_temp self.video.marg_factor = self.video.marg_factor.rekey((np.array(self.video.marg_factor.keys())-roll).tolist()) self.video.state.timestamps = self.video.state.timestamps [roll:] self.video.state.wTbs = self.video.state.wTbs [roll:] self.video.state.vs = self.video.state.vs [roll:] self.video.state.bs = self.video.state.bs [roll:] self.video.state.preintegrations = self.video.state.preintegrations [roll:] self.video.state.preintegrations_meas = self.video.state.preintegrations_meas [roll:] self.video.state.gnss_valid = self.video.state.gnss_valid [roll:] self.video.state.gnss_position = self.video.state.gnss_position [roll:] self.video.state.odo_valid = self.video.state.odo_valid [roll:] self.video.state.odo_vel = self.video.state.odo_vel [roll:] def __update(self): """ add edges, perform update """ self.count += 1 self.t1 += 1 if self.video.imu_enabled and (self.video.tstamp[self.t1-1] - self.video.vi_init_time > 5.0): self.video.reinit = True self.video.vi_init_time = 1e9 ## new frame comes, append IMU cur_t = float(self.video.tstamp[self.t1-1].detach().cpu()) self.video.logger.info('predict %f' %cur_t) while self.all_imu[self.cur_imu_ii][0] < cur_t: ## high-frequency output # predict the pose of skipped frames through IMU preintegration if self.high_freq_output and self.video.imu_enabled: if self.all_imu[self.cur_imu_ii][0] > float(self.all_stamp[self.cur_stamp_ii][0]): self.video.state.append_imu_temp(float(self.all_stamp[self.cur_stamp_ii][0]),\ self.all_imu[self.cur_imu_ii][4:7],\ self.all_imu[self.cur_imu_ii][1:4]/180*math.pi,True) if float(self.all_stamp[self.cur_stamp_ii][0]) > self.video.state.timestamps[-1] and\ math.fabs(cur_t - float(self.all_stamp[self.cur_stamp_ii][0]))>1e-3: pose_temp = self.video.state.pose_temp ppp = pose_temp.pose().translation() qqq = Rotation.from_matrix(pose_temp.pose().rotation().matrix()).as_quat() line = '%.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f'%(float(self.all_stamp[self.cur_stamp_ii][0]),ppp[0],ppp[1],ppp[2]\ ,qqq[0],qqq[1],qqq[2],qqq[3]) if self.video.gnss_init_t1>0: p = self.video.ten0 + np.matmul(trans.Cen(self.video.ten0), ppp) line += ' %.6f %.6f %.6f'% (p[0],p[1],p[2]) self.result_file.writelines(line+'\n') # self.result_file.flush() self.cur_stamp_ii += 1 self.video.state.append_imu_temp(self.all_imu[self.cur_imu_ii][0],\ self.all_imu[self.cur_imu_ii][4:7],\ self.all_imu[self.cur_imu_ii][1:4]/180*math.pi) self.video.state.append_imu(self.all_imu[self.cur_imu_ii][0],\ self.all_imu[self.cur_imu_ii][4:7],\ self.all_imu[self.cur_imu_ii][1:4]/180*math.pi) self.cur_imu_ii += 1 self.video.state.append_imu(cur_t,\ self.all_imu[self.cur_imu_ii][4:7],\ self.all_imu[self.cur_imu_ii][1:4]/180*math.pi) self.video.state.append_img(cur_t) ## append GNSS if len(self.all_gnss) > 0: gnss_found = bisect.bisect(self.all_gnss[:,0],cur_t - 1e-6) else: gnss_found = -1 if gnss_found > 0 and self.all_gnss[gnss_found,0] - cur_t < 0.01 : self.video.state.append_gnss(cur_t,self.all_gnss[gnss_found,1:4]) ## append ZUPT if self.zupt and self.video.state.preintegrations[self.t1-3].deltaTij() > 3.0: if np.linalg.norm(self.video.state.vs[self.t1-2]) < 0.025: self.video.state.append_odo(cur_t,np.array([.0,.0,.0])) ## append ODO if len(self.all_odo) > 0: odo_found = bisect.bisect(self.all_odo[:,0],cur_t - 1e-6) else: odo_found = -1 if odo_found > 0 and self.all_odo[odo_found,0] - cur_t < 0.01 : self.video.state.append_odo(cur_t,self.all_odo[odo_found,1:4]) self.video.state.append_imu(self.all_imu[self.cur_imu_ii][0],\ self.all_imu[self.cur_imu_ii][4:7],\ self.all_imu[self.cur_imu_ii][1:4]/180*math.pi) self.cur_imu_ii += 1 ## predict pose (<5 ms) if self.video.imu_enabled: Twc = (self.video.state.wTbs[-1] * self.video.Tbc).matrix() TTT = torch.tensor(np.linalg.inv(Twc)) q = torch.tensor(Rotation.from_matrix(TTT[:3, :3]).as_quat()) t = TTT[:3,3] self.video.poses[self.t1-1] = torch.cat([t,q]) self.video.logger.info('manage edges') ## manage edges (60 ms) if self.graph.corr is not None: if self.visual_only: self.graph.rm_factors(torch.logical_and(self.graph.age > self.max_age,\ torch.logical_or(self.graph.ii < self.t1-self.active_window,self.graph.jj < self.t1-self.active_window)), store=True) else: self.graph.rm_factors(torch.logical_or(self.graph.age > self.max_age,\ torch.logical_or(self.graph.ii < self.t1-self.active_window,self.graph.jj < self.t1-self.active_window)), store=True) self.graph.add_proximity_factors(self.t1-5, max(self.t1-self.frontend_window, 0), rad=self.frontend_radius, nms=self.frontend_nms, thresh=self.frontend_thresh, beta=self.beta, remove=True) self.video.logger.info('non-keyframes %d' % self.graph.ii.shape[0]) ## non-keyframe update self.video.disps[self.t1-1] = torch.where(self.video.disps_sens[self.t1-1] > 0, self.video.disps_sens[self.t1-1], self.video.disps[self.t1-1]) for itr in range(self.iters1): self.graph.update(None, None, use_inactive=True) self.rollup = False if self.t1 > 65: self.__rollup(30) print('rollup ',self.graph.ii) self.rollup = True self.video.logger.info('output') ## visualization/output poses = SE3(self.video.poses) d = self.video.distance([self.t1-3], [self.t1-2], beta=self.beta, bidirectional=True) TTT = np.matmul(poses[self.t1-1].cpu().inv().matrix(),np.linalg.inv(self.video.Ti1c)) if self.video.imu_enabled or (self.visual_only and self.visual_only_init): ppp = TTT[0:3,3] qqq = Rotation.from_matrix(TTT[:3, :3]).as_quat() line = '%.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f'%(cur_t,ppp[0],ppp[1],ppp[2]\ ,qqq[0],qqq[1],qqq[2],qqq[3]) if self.video.gnss_init_t1>0: p = self.video.ten0 + np.matmul(trans.Cen(self.video.ten0), ppp.numpy()) line += ' %.6f %.6f %.6f'% (p[0],p[1],p[2]) self.result_file.writelines(line+'\n') self.result_file.flush() TTTref = np.matmul(self.refTw,TTT) ppp = TTTref[0:3,3] if self.show_plot: # if math.fabs(tt_found - cur_t) < 0.1: # for kitti and whu self.plt_pos[0].append(ppp[0]) self.plt_pos[1].append(ppp[1]) a1 = np.array(trans.m2att(TTTref[0:3,0:3]) )* 57.3 if self.all_gt is not None: tt_found,dd = self.get_pose_ref(cur_t -1e-3) self.plt_pos_ref[0].append(dd['T'][0,3]) self.plt_pos_ref[1].append(dd['T'][1,3]) a2 = np.array(trans.m2att(dd['T'][0:3,0:3]) )* 57.3 a1 -= a2 self.plt_att[0].append(a1[0]) self.plt_att[1].append(a1[1]) self.plt_att[2].append(a1[2]) bg = self.video.state.bs[self.t1-1].gyroscope() self.plt_bg[0].append(bg[0]) self.plt_bg[1].append(bg[1]) self.plt_bg[2].append(bg[2]) self.plt_t.append(cur_t) if self.rollup: plt.subplot(1,3,1) plt.cla(); plt.gca().set_title('Trajectory') plt.plot(self.plt_pos[0],self.plt_pos[1],marker='^') plt.plot(self.plt_pos_ref[0],self.plt_pos_ref[1],marker='^') plt.subplot(1,3,2) plt.cla(); plt.gca().set_title('Attitude Error/Attitude') plt.plot(self.plt_t,self.plt_att[0],c='r') plt.plot(self.plt_t,self.plt_att[1],c='g') plt.plot(self.plt_t,self.plt_att[2],c='b') plt.ylim([-10,10]) plt.subplot(1,3,3) plt.cla(); plt.gca().set_title('Gyroscope Bias') plt.plot(self.plt_t,self.plt_bg[0],c='r') plt.plot(self.plt_t,self.plt_bg[1],c='g') plt.plot(self.plt_t,self.plt_bg[2],c='b') plt.pause(0.1) ## keyframe update self.video.logger.info('keyframes %d' % self.graph.ii.shape[0]) if self.t1 > 10: cam_translation = torch.norm((poses[(self.t1-10):(self.t1-3)] * poses[self.t1-2].inv()[None]).translation()[:,0:3],dim=1) else: cam_translation = torch.norm((poses[(self.t1-6):(self.t1-3)] * poses[self.t1-2].inv()[None]).translation()[:,0:3],dim=1) if (d.item() < self.keyframe_thresh or (self.video.imu_enabled and torch.sum(cam_translation < self.translation_threshold)>0)): # gnss self.video.logger.info('remove new frame!!!!!!!!!!!!1') self.graph.rm_keyframe(self.t1 - 2) # merge preintegration[self.t1-2] and preintegration[self.t1-3] for iii in range(len(self.video.state.preintegrations_meas[self.t1-2])): dd = self.video.state.preintegrations_meas[self.t1-2][iii] if dd[2] > 0: self.video.state.preintegrations[self.t1-3].integrateMeasurement(dd[0],\ dd[1],\ dd[2]) self.video.state.preintegrations_meas[self.t1-3].append(dd) self.video.state.preintegrations[self.t1-2] = self.video.state.preintegrations[self.t1-1] self.video.state.preintegrations_meas[self.t1-2] = self.video.state.preintegrations_meas[self.t1-1] self.video.state.preintegrations.pop() self.video.state.preintegrations_meas.pop() self.video.rm_new_gnss(self.t1-2) self.video.state.wTbs[self.t1-2] = self.video.state.wTbs[self.t1-1]; self.video.state.wTbs.pop() self.video.state.bs [self.t1-2] = self.video.state.bs [self.t1-1]; self.video.state.bs.pop() self.video.state.vs [self.t1-2] = self.video.state.vs [self.t1-1]; self.video.state.vs .pop() self.video.state.gnss_valid [self.t1-2] = self.video.state.gnss_valid [self.t1-1]; self.video.state.gnss_valid .pop() self.video.state.gnss_position [self.t1-2] = self.video.state.gnss_position [self.t1-1]; self.video.state.gnss_position .pop() self.video.state.odo_valid [self.t1-2] = self.video.state.odo_valid [self.t1-1]; self.video.state.odo_valid .pop() self.video.state.odo_vel [self.t1-2] = self.video.state.odo_vel [self.t1-1]; self.video.state.odo_vel .pop() with self.video.get_lock(): self.video.counter.value -= 1 self.t1 -= 1 else: for itr in range(self.iters2): # print('b%d' % itr) self.graph.update(None, None, use_inactive=True) ## try initializing VI/GNSS if self.t1 > self.vi_warmup and self.video.vi_init_t1 < 0: self.init_VI() if not self.visual_only: for i in range(len(self.all_stamp)): # skip to next image if float(self.all_stamp[i][0]) < cur_t + 1e-6: continue else: self.cur_stamp_ii = i break if self.video.imu_enabled and self.video.gnss_init_time <= 0.0 and len(self.all_gnss)>0: self.init_GNSS() ## set pose for next itration self.video.poses[self.t1] = self.video.poses[self.t1-1] self.video.disps[self.t1] = self.video.disps[self.t1-1].mean() * 1.0 self.video.dirty[self.graph.ii.min():self.t1] = True def init_IMU(self): """ initialize IMU states """ cur_t = float(self.video.tstamp[self.t0].detach().cpu()) for i in range(len(self.all_imu)): if self.all_imu[i][0] < cur_t - 1e-6: continue else: self.cur_imu_ii = i break for i in range(self.t0,self.t1): tt = self.video.tstamp[i] if i == self.t0: self.video.state.init_first_state(cur_t,np.zeros(3),\ np.eye(3),\ np.zeros(3)) self.video.state.append_imu(self.all_imu[self.cur_imu_ii][0],\ self.all_imu[self.cur_imu_ii][4:7],\ self.all_imu[self.cur_imu_ii][1:4]/180*math.pi) self.cur_imu_ii += 1 self.is_init = True else: cur_t = float(self.video.tstamp[i].detach().cpu()) while self.all_imu[self.cur_imu_ii][0] < cur_t: self.video.state.append_imu(self.all_imu[self.cur_imu_ii][0],\ self.all_imu[self.cur_imu_ii][4:7],\ self.all_imu[self.cur_imu_ii][1:4]/180*math.pi) self.cur_imu_ii += 1 self.video.state.append_imu(cur_t,\ self.all_imu[self.cur_imu_ii][4:7],\ self.all_imu[self.cur_imu_ii][1:4]/180*math.pi) self.video.state.append_img(cur_t) if len(self.all_gnss) > 0: gnss_found = bisect.bisect(self.all_gnss[:,0],cur_t - 1e-6) else: gnss_found = -1 if gnss_found > 0 and self.all_gnss[gnss_found,0] - cur_t < 0.01: self.video.state.append_gnss(cur_t,self.all_gnss[gnss_found,1:4]) if len(self.all_odo) > 0: odo_found = bisect.bisect(self.all_odo[:,0],cur_t - 1e-6) else: odo_found = -1 if odo_found > 0 and self.all_odo[odo_found,0] - cur_t < 0.01 : self.video.state.append_odo(cur_t,self.all_odo[odo_found,1:4]) self.video.state.append_imu(self.all_imu[self.cur_imu_ii][0],\ self.all_imu[self.cur_imu_ii][4:7],\ self.all_imu[self.cur_imu_ii][1:4]/180*math.pi) self.cur_imu_ii += 1 Twc = np.matmul(np.array([[1,0,0,0],\ [0,1,0,0],\ [0,0,1,0.02*i],\ [0,0,0,1]]),self.video.Ti1c) # perturb the camera poses, which benefits the robustness of initial BA TTT = torch.tensor(np.linalg.inv(Twc)) q = torch.tensor(Rotation.from_matrix(TTT[:3, :3]).as_quat()) t = TTT[:3,3] if not self.video.imu_enabled: self.video.poses[i] = torch.cat([t,q]) def init_VI(self): """ initialize the V-I system, referring to VIN-Fusion """ sum_g = np.zeros(3,dtype = np.float64) ccount = 0 for i in range(self.t1 - 8 ,self.t1-1): dt = self.video.state.preintegrations[i].deltaTij() tmp_g = self.video.state.preintegrations[i].deltaVij()/dt sum_g += tmp_g ccount += 1 aver_g = sum_g * 1.0 / ccount var_g = 0.0 for i in range(self.t1 - 8 ,self.t1-1): dt = self.video.state.preintegrations[i].deltaTij() tmp_g = self.video.state.preintegrations[i].deltaVij()/dt var_g += np.linalg.norm(tmp_g - aver_g)**2 var_g =math.sqrt(var_g/ccount) if var_g < 0.25: print("IMU excitation not enough!",var_g) else: poses = SE3(self.video.poses) self.plt_pos = [[],[]] self.plt_pos_ref = [[],[]] for i in range(0,self.t1): ppp = np.matmul(poses[i].cpu().inv().matrix(),np.linalg.inv(self.video.Ti1c))[0:3,3] self.plt_pos[0].append(ppp[0]) self.plt_pos[1].append(ppp[1]) if self.all_gt is not None: tt_found,dd = self.get_pose_ref(self.video.tstamp[i]-1e-3) self.plt_pos_ref[0].append(dd['T'][0,3]) self.plt_pos_ref[1].append(dd['T'][1,3]) if self.show_plot: plt.subplot(1,3,1) plt.cla(); plt.gca().set_title('Trajectory') plt.plot(self.plt_pos[0],self.plt_pos[1],marker='^') plt.plot(self.plt_pos_ref[0],self.plt_pos_ref[1],marker='^') plt.pause(0.1) if not self.visual_only: self.VisualIMUAlignment(self.t1 - 8 ,self.t1, ignore_lever= True) self.graph.update(None, None, use_inactive=True) self.VisualIMUAlignment(self.t1 - 8 ,self.t1, ignore_lever= False) self.graph.update(None, None, use_inactive=True) self.VisualIMUAlignment(self.t1 - 8 ,self.t1, ignore_lever= False) self.video.imu_enabled = True else: self.VisualIMUAlignment(self.t1 - 8 ,self.t1, ignore_lever= True) self.graph.update(None, None, use_inactive=True) self.VisualIMUAlignment(self.t1 - 8 ,self.t1, ignore_lever= False) self.graph.update(None, None, use_inactive=True) self.VisualIMUAlignment(self.t1 - 8 ,self.t1, ignore_lever= False) self.visual_only_init = True self.video.set_prior(self.video.last_t0,self.t1) self.plt_pos = [[],[]] self.plt_pos_ref = [[],[]] for i in range(0,self.t1): TTT = self.video.state.wTbs[i].matrix() ppp = TTT[0:3,3] qqq = Rotation.from_matrix(TTT[:3, :3]).as_quat() self.result_file.writelines('%.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f\n'%(self.video.tstamp[i],ppp[0],ppp[1],ppp[2]\ ,qqq[0],qqq[1],qqq[2],qqq[3])) TTTref = np.matmul(self.refTw,TTT) # for visualization ppp = TTTref[0:3,3] qqq = Rotation.from_matrix(TTTref[:3, :3]).as_quat() self.plt_pos[0].append(ppp[0]) self.plt_pos[1].append(ppp[1]) if self.all_gt is not None: tt_found,dd = self.get_pose_ref(self.video.tstamp[i]-1e-3) self.plt_pos_ref[0].append(dd['T'][0,3]) self.plt_pos_ref[1].append(dd['T'][1,3]) if self.show_plot: plt.subplot(1,3,1) plt.cla(); plt.gca().set_title('Trajectory') plt.plot(self.plt_pos[0],self.plt_pos[1],marker='^') plt.plot(self.plt_pos_ref[0],self.plt_pos_ref[1],marker='^') plt.pause(0.1) for itr in range(1): self.graph.update(None, None, use_inactive=True) def init_GNSS(self): """ initialize the GNSS for geo-referencing fusion """ ten0 = np.array([self.all_gt[self.all_gt_keys[0]]['X0'],\ self.all_gt[self.all_gt_keys[0]]['Y0'],\ self.all_gt[self.all_gt_keys[0]]['Z0']]) self.video.ten0 = ten0 tn0 = []; tw =[] for i in range(len(self.video.state.wTbs) - 10,len(self.video.state.wTbs)): if self.video.state.gnss_valid[i]: # if not is_ref_set: # ten0 = self.video.sgraph.gnss_position[i] # is_ref_set = True teg = self.video.state.gnss_position[i] print(self.video.ten0) print(self.video.state.gnss_position[i]) tn0g = np.matmul(trans.Cen(self.video.ten0).T,(self.video.state.gnss_position[i] - self.video.ten0)) twb = self.video.state.wTbs[i].translation() tn0.append(tn0g) tw.append(twb) if len(tn0) > 1: tn0 = np.array(tn0) tw = np.array(tw) bl = np.linalg.norm(tn0[-1] - tn0[0]) print('GNSS Alignment Baseline: %.5f' % bl) if bl < 10.0: print('Baseline too short!!') return heading_w = math.atan2(tw[-1,1]-tw[0,1],tw[-1,0]-tw[0,0]) heading_n0 = math.atan2(tn0[-1,1]-tn0[0,1],tn0[-1,0]-tn0[0,0]) s_w = np.linalg.norm(tw[-1] - tw[0]) s_n0 = np.linalg.norm(tn0[-1] - tn0[0]) s = s_n0 / s_w Rn0w = trans.att2m(np.array([.0,.0,-heading_w + heading_n0])) tn0w = tn0 - np.matmul(Rn0w,tw.T * s).T poses = SE3(self.video.poses) wTcs = poses.inv().matrix().cpu().numpy() wTbs = np.matmul(wTcs,self.video.Tbc.inverse().matrix()) wTbs[:,0:3,3] = np.matmul(Rn0w,(wTbs[:,0:3,3]*s).T).T + tn0w[0] wTbs[:,0:3,0:3] = np.matmul(Rn0w, (wTbs[:,0:3,0:3]).T).T self.refTw = np.eye(4,4) for i in range(0,self.t1): self.video.state.wTbs[i] = gtsam.Pose3(wTbs[i]) self.video.state.vs[i] *= s wTcs = np.matmul(wTbs,self.video.Tbc.matrix()) for i in range(0,self.t1): TTT = np.linalg.inv(wTcs[i]) q = torch.tensor(Rotation.from_matrix(TTT[:3, :3]).as_quat()) t = torch.tensor(TTT[:3,3]) self.video.poses[i] = torch.cat([t,q]) self.video.disps[i] /= s self.video.gnss_init_t1 = self.t1 self.video.gnss_init_time = self.video.tstamp[self.t1-1] self.video.set_prior(self.video.last_t0,self.t1) self.plt_pos = [[],[]] self.plt_pos_ref = [[],[]] for i in range(0,self.t1): TTT = self.video.state.wTbs[i].matrix() ppp = TTT[0:3,3] qqq = Rotation.from_matrix(TTT[:3, :3]).as_quat() self.result_file.writelines('%.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f\n'%(self.video.tstamp[i],ppp[0],ppp[1],ppp[2]\ ,qqq[0],qqq[1],qqq[2],qqq[3])) TTTref = np.matmul(self.refTw,TTT) # for visualization ppp = TTTref[0:3,3] qqq = Rotation.from_matrix(TTTref[:3, :3]).as_quat() self.plt_pos[0].append(ppp[0]) self.plt_pos[1].append(ppp[1]) if self.all_gt is not None: tt_found,dd = self.get_pose_ref(self.video.tstamp[i]-1e-3) self.plt_pos_ref[0].append(dd['T'][0,3]) self.plt_pos_ref[1].append(dd['T'][1,3]) if self.show_plot: plt.subplot(1,3,1) plt.cla(); plt.gca().set_title('Trajectory') plt.plot(self.plt_pos[0],self.plt_pos[1],marker='^') plt.plot(self.plt_pos_ref[0],self.plt_pos_ref[1],marker='^') plt.pause(0.1) for itr in range(1): self.graph.update(None, None, use_inactive=True) print('GNSS initialized!!!!') def VisualIMUAlignment(self, t0, t1, ignore_lever, disable_scale = False): poses = SE3(self.video.poses) wTcs = poses.inv().matrix().cpu().numpy() if not ignore_lever: wTbs = np.matmul(wTcs,self.video.Tbc.inverse().matrix()) else: T_tmp = self.video.Tbc.inverse().matrix() T_tmp[0:3,3] = 0.0 wTbs = np.matmul(wTcs,T_tmp) cost = 0.0 # solveGyroscopeBias A = np.zeros([3,3]) b = np.zeros(3) H1 =np.zeros([15,6], order='F', dtype=np.float64) H2 =np.zeros([15,3], order='F', dtype=np.float64) H3 =np.zeros([15,6], order='F', dtype=np.float64) H4 =np.zeros([15,3], order='F', dtype=np.float64) H5 =np.zeros([15,6], order='F', dtype=np.float64) # navstate wrt. bias H6 =np.zeros([15,6], order='F', dtype=np.float64) for i in range(t0,t1-1): pose_i = gtsam.Pose3(wTbs[i]) pose_j = gtsam.Pose3(wTbs[i+1]) Rij = np.matmul(pose_i.rotation().matrix().T,pose_j.rotation().matrix()) imu_factor = gtsam.gtsam.CombinedImuFactor(0,1,2,3,4,5,self.video.state.preintegrations[i]) err = imu_factor.evaluateErrorCustom(pose_i,self.video.state.vs[i],\ pose_j,self.video.state.vs[i+1],\ self.video.state.bs[i],self.video.state.bs[i+1],\ H1,H2,H3,H4,H5,H6) tmp_A = H5[0:3,3:6] tmp_b = err[0:3] cost += np.dot(tmp_b,tmp_b) A += np.matmul(tmp_A.T,tmp_A) b += np.matmul(tmp_A.T,tmp_b) bg = -np.matmul(np.linalg.inv(A),b) for i in range(0,t1-1): pim = gtsam.PreintegratedCombinedMeasurements(self.video.state.params,\ gtsam.imuBias.ConstantBias(np.array([.0,.0,.0]),bg)) for iii in range(len(self.video.state.preintegrations_meas[i])): dd = self.video.state.preintegrations_meas[i][iii] if dd[2] > 0: pim.integrateMeasurement(dd[0],dd[1],dd[2]) self.video.state.preintegrations[i] = pim self.video.state.bs[i] = gtsam.imuBias.ConstantBias(np.array([.0,.0,.0]),bg) print('bg: ',bg) # linearAlignment all_frame_count = t1 - t0 n_state = all_frame_count * 3 + 3 + 1 A = np.zeros([n_state,n_state]) b = np.zeros(n_state) i_count = 0 for i in range(t0,t1-1): pose_i = gtsam.Pose3(wTbs[i]) pose_j = gtsam.Pose3(wTbs[i+1]) R_i = pose_i.rotation().matrix() t_i = pose_i.translation() R_j = pose_j.rotation().matrix() t_j = pose_j.translation() pim = self.video.state.preintegrations[i] tic = self.video.Tbc.translation() tmp_A = np.zeros([6,10]) tmp_b = np.zeros(6) dt = pim.deltaTij() tmp_A[0:3,0:3] = -dt * np.eye(3,3) tmp_A[0:3,6:9] = R_i.T * dt * dt / 2 tmp_A[0:3,9] = np.matmul(R_i.T, t_j-t_i) / 100.0 tmp_b[0:3] = pim.deltaPij() tmp_A[3:6,0:3] = -np.eye(3,3) tmp_A[3:6,3:6] = np.matmul(R_i.T, R_j) tmp_A[3:6,6:9] = R_i.T * dt tmp_b[3:6] = pim.deltaVij() r_A = np.matmul(tmp_A.T,tmp_A) r_b = np.matmul(tmp_A.T,tmp_b) A[i_count*3:i_count*3+6,i_count*3:i_count*3+6] += r_A[0:6,0:6] b[i_count*3:i_count*3+6] += r_b[0:6] A[-4:,-4:] += r_A[-4:,-4:] b[-4:] += r_b[-4:] A[i_count*3:i_count*3+6,n_state-4:] += r_A[0:6,-4:] A[n_state-4:,i_count*3:i_count*3+6] += r_A[-4:,0:6] i_count += 1 A = A * 1000.0 b = b * 1000.0 x = np.matmul(np.linalg.inv(A),b) s = x[n_state-1] / 100.0 g = x[-4:-1] # RefineGravity g0 = g / np.linalg.norm(g) * 9.81 lx = np.zeros(3) ly = np.zeros(3) n_state = all_frame_count * 3 + 2 + 1 A = np.zeros([n_state,n_state]) b = np.zeros(n_state) for k in range(4): aa = g / np.linalg.norm(g) tmp = np.array([.0,.0,1.0]) bb = (tmp - np.dot(aa,tmp) * aa) bb /= np.linalg.norm(bb) cc = np.cross(aa,bb) bc = np.zeros([3,2]) bc[0:3,0] = bb bc[0:3,1] = cc lxly = bc i_count = 0 for i in range(t0,t1-1): pose_i = gtsam.Pose3(wTbs[i]) pose_j = gtsam.Pose3(wTbs[i+1]) R_i = pose_i.rotation().matrix() t_i = pose_i.translation() R_j = pose_j.rotation().matrix() t_j = pose_j.translation() tmp_A = np.zeros([6,9]) tmp_b = np.zeros(6) pim = self.video.state.preintegrations[i] dt = pim.deltaTij() tmp_A[0:3,0:3] = -dt *np.eye(3,3) tmp_A[0:3,6:8] = np.matmul(R_i.T,lxly) * dt * dt /2 tmp_A[0:3,8] = np.matmul(R_i.T,t_j - t_i) / 100.0 tmp_b[0:3] = pim.deltaPij() - np.matmul(R_i.T,g0) * dt * dt / 2 tmp_A[3:6,0:3] = -np.eye(3) tmp_A[3:6,3:6] = np.matmul(R_i.T,R_j) tmp_A[3:6,6:8] = np.matmul(R_i.T,lxly) * dt tmp_b[3:6] = pim.deltaVij() - np.matmul(R_i.T,g0) * dt r_A = np.matmul(tmp_A.T,tmp_A) r_b = np.matmul(tmp_A.T,tmp_b) A[i_count*3:i_count*3+6,i_count*3:i_count*3+6] += r_A[0:6,0:6] b[i_count*3:i_count*3+6] += r_b[0:6] A[-3:,-3:] += r_A[-3:,-3:] b[-3:] += r_b[-3:] A[i_count*3:i_count*3+6,n_state-3:] += r_A[0:6,-3:] A[n_state-3:,i_count*3:i_count*3+6] += r_A[-3:,0:6] i_count += 1 A = A * 1000.0 b = b * 1000.0 x = np.matmul(np.linalg.inv(A),b) dg = x[-3:-1] g0 = g0 + np.matmul(lxly,dg) g0 = g0 / np.linalg.norm(g0) * 9.81 s = x[-1] / 100.0 print(s,g0,x) if disable_scale: s = 1.0 print('g,s:',g,s) if math.fabs(np.linalg.norm(g) - 9.81) < 0.5 and s > 0: print('V-I successfully initialized!') # visualInitialAlign wTbs[:,0:3,3] *= s # !!!!!!!!!!!!!!!!!!!!!!!! for i in range(0, t1-t0): self.video.state.vs[i+t0] = np.matmul(wTbs[i+t0,0:3,0:3],x[i*3:i*3+3]) # g2R ng1 = g0/ np.linalg.norm(g0) ng2 = np.array([0,0,1.0]) R0 = trans.FromTwoVectors(ng1,ng2) yaw = trans.R2ypr(R0)[0] R0 = np.matmul(trans.ypr2R(np.array([-yaw,0,0])),R0) # align for visualization ppp = np.matmul(R0,wTbs[t1-1,0:3,3]) RRR = np.matmul(R0,wTbs[t1-1,0:3,0:3]) if self.all_gt is not None: # align the initial poses for visualization tt_found,dd = self.get_pose_ref(self.video.tstamp[t1-1]-1e-3) self.refTw = np.matmul(dd['T'],np.linalg.inv(wTbs[t1-1])) self.refTw[0:3,0:3] = trans.att2m([0,0,trans.m2att(self.refTw[0:3,0:3])[2]]) g = np.matmul(R0,g0) for i in range(0,t1): wTbs[i,0:3,3] = np.matmul(R0,wTbs[i,0:3,3]) wTbs[i,0:3,0:3] = np.matmul(R0,wTbs[i,0:3,0:3]) self.video.state.vs[i] = np.matmul(R0, self.video.state.vs[i]) self.video.state.wTbs[i] = gtsam.Pose3(wTbs[i]) self.video.vi_init_t1 = t1 self.video.vi_init_time = self.video.tstamp[t1-1] if not ignore_lever: wTcs = np.matmul(wTbs,self.video.Tbc.matrix()) else: T_tmp = self.video.Tbc.matrix() T_tmp[0:3,3] = 0.0 wTcs = np.matmul(wTbs,T_tmp) for i in range(0,t1): TTT = np.linalg.inv(wTcs[i]) q = torch.tensor(Rotation.from_matrix(TTT[:3, :3]).as_quat()) t = torch.tensor(TTT[:3,3]) self.video.poses[i] = torch.cat([t,q]) self.video.disps[i] /= s def __initialize(self): """ initialize the SLAM system """ self.t0 = 0 self.t1 = self.video.counter.value self.graph.add_neighborhood_factors(self.t0, self.t1, r=3) self.init_IMU() self.graph.video.imu_enabled = False for itr in range(8): self.graph.update(1, use_inactive=True) self.graph.add_proximity_factors(0, 0, rad=2, nms=2, thresh=self.frontend_thresh, remove=False) for itr in range(8): self.graph.update(1, use_inactive=True) self.graph.video.imu_enabled = False for itr in range(8): self.graph.update(1, use_inactive=True) # torch.concat([self.graph.ii[None],self.graph.jj[None]]).T # self.video.normalize() self.video.poses[self.t1] = self.video.poses[self.t1-1].clone() self.video.disps[self.t1] = self.video.disps[self.t1-4:self.t1].mean() # initialization complete self.is_initialized = True with self.video.get_lock(): self.video.ready.value = 1 self.video.dirty[:self.t1] = True self.graph.rm_factors(self.graph.ii < self.warmup-4, store=True) def __call__(self): """ main update """ # do initialization if not self.is_initialized and self.video.counter.value == self.warmup: self.__initialize() # do update elif self.is_initialized and self.t1 < self.video.counter.value: self.__update() ================================================ FILE: dbaf/depth_video.py ================================================ import numpy as np import torch import lietorch import droid_backends from torch.multiprocessing import Process, Queue, Lock, Value from droid_net import cvx_upsample import geom.projective_ops as pops from multi_sensor import MultiSensorState import gtsam from gtsam.symbol_shorthand import B, V, X from scipy.spatial.transform import Rotation import copy import logging import geoFunc.trans as trans from lietorch import SE3 def BA2GTSAM(H: np.ndarray, v: np.ndarray, Tbc: gtsam.Pose3): A = -Tbc.inverse().AdjointMap() # A = -np.eye(6,6) A = np.concatenate([A[3:6,:],A[0:3,:]],axis=0) ss = H.shape[0]//6 J = np.zeros_like(H) for i in range(ss): J[(i*6):(i*6+6),(i*6):(i*6+6)] = A JT = J.T return np.matmul(np.matmul(JT,H),J),np.matmul(JT,v) def CustomHessianFactor(values: gtsam.Values, H: np.ndarray, v: np.ndarray): info_expand = np.zeros([H.shape[0]+1,H.shape[1]+1]) info_expand[0:-1,0:-1] = H info_expand[0:-1,-1] = v info_expand[-1,-1] = 0.0 # This is meaningless. h_f = gtsam.HessianFactor(values.keys(),[6]*len(values.keys()),info_expand) l_c = gtsam.LinearContainerFactor(h_f,values) return l_c class DepthVideo: def __init__(self, image_size=[480, 640], buffer=1024, save_pkl = False, stereo=False, upsample = False, device="cuda:0"): # current keyframe count self.counter = Value('i', 0) self.ready = Value('i', 0) self.ht = ht = image_size[0] self.wd = wd = image_size[1] ### state attributes ### self.tstamp = torch.zeros(buffer, device="cuda", dtype=torch.float64).share_memory_() self.images = torch.zeros(buffer, 3, ht, wd, device="cuda", dtype=torch.uint8) self.dirty = torch.zeros(buffer, device="cuda", dtype=torch.bool).share_memory_() self.red = torch.zeros(buffer, device="cuda", dtype=torch.bool).share_memory_() self.poses = torch.zeros(buffer, 7, device="cuda", dtype=torch.float).share_memory_() self.disps = torch.ones(buffer, ht//8, wd//8, device="cuda", dtype=torch.float).share_memory_() self.disps_sens = torch.zeros(buffer, ht//8, wd//8, device="cuda", dtype=torch.float).share_memory_() self.disps_up = torch.zeros(buffer, ht, wd, device="cuda", dtype=torch.float).share_memory_() self.intrinsics = torch.zeros(buffer, 4, device="cuda", dtype=torch.float).share_memory_() self.stereo = stereo c = 1 if not self.stereo else 2 ### feature attributes ### self.fmaps = torch.zeros(buffer, c, 128, ht//8, wd//8, dtype=torch.half, device="cuda").share_memory_() self.nets = torch.zeros(buffer, 128, ht//8, wd//8, dtype=torch.half, device="cuda").share_memory_() self.inps = torch.zeros(buffer, 128, ht//8, wd//8, dtype=torch.half, device="cuda").share_memory_() # initialize poses to identity transformation self.poses[:] = torch.as_tensor([0, 0, 0, 0, 0, 0, 1], dtype=torch.float, device="cuda") ### DBAFusion # for .pkl saving self.disps_save = torch.ones(5000, ht//8, wd//8, device="cuda", dtype=torch.float) self.poses_save = torch.ones(5000, 7, device="cuda", dtype=torch.float) self.tstamp_save = torch.zeros(5000, device="cuda", dtype=torch.float64) self.images_save = torch.zeros(5000, ht//8, wd//8, 3, device="cuda", dtype=torch.float) if upsample: self.disps_up_save = torch.zeros(5000, ht, wd, device="cuda", dtype=torch.float).share_memory_() self.count_save = 0 self.save_pkl = save_pkl self.upsample_flag = upsample self.state = MultiSensorState() self.last_t0 = 0 self.last_t1 = 0 self.cur_graph = None self.cur_result = None self.marg_factor = None self.prior_factor = [] self.prior_factor_map = {} self.cur_ii = None self.cur_jj = None self.cur_target = None self.cur_weight = None self.cur_eta = None self.imu_enabled = False self.ignore_imu = False self.xyz_ref = [] # extrinsics, need to be set in the main .py self.Ti1c = None # shape = (4,4) self.Tbc = None # gtsam.Pose3 self.tbg = None # shape = (3) self.reinit = False self.vi_init_t1 = -1 self.vi_init_time = 0.0 self.gnss_init_t1 = -1 self.gnss_init_time = 0.0 self.ten0 = None self.init_pose_sigma =np.array([0.1, 0.1, 0.0001, 0.0001,0.0001,0.0001]) self.init_bias_sigma =np.array([1.0,1.0,1.0, 0.1, 0.1, 0.1]) self.logger = logging.getLogger('dba_fusion') self.logger.setLevel(logging.DEBUG) fh = logging.FileHandler('dba_fusion.log') formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) # add the handlers to the logger self.logger.addHandler(fh) self.logger.info('Start logging!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!') def get_lock(self): return self.counter.get_lock() def __item_setter(self, index, item): if isinstance(index, int) and index >= self.counter.value: self.counter.value = index + 1 elif isinstance(index, torch.Tensor) and index.max().item() > self.counter.value: self.counter.value = index.max().item() + 1 self.tstamp[index] = item[0] self.images[index] = item[1] if item[2] is not None: self.poses[index] = item[2] if item[3] is not None: self.disps[index] = item[3] if item[4] is not None: depth = item[4][3::8,3::8] self.disps_sens[index] = torch.where(depth>0, 1.0/depth, depth) if item[5] is not None: self.intrinsics[index] = item[5] if len(item) > 6: self.fmaps[index] = item[6] if len(item) > 7: self.nets[index] = item[7] if len(item) > 8: self.inps[index] = item[8] def __setitem__(self, index, item): with self.get_lock(): self.__item_setter(index, item) def __getitem__(self, index): """ index the depth video """ with self.get_lock(): # support negative indexing if isinstance(index, int) and index < 0: index = self.counter.value + index item = ( self.poses[index], self.disps[index], self.intrinsics[index], self.fmaps[index], self.nets[index], self.inps[index]) return item def append(self, *item): with self.get_lock(): self.__item_setter(self.counter.value, item) ### geometric operations ### @staticmethod def format_indicies(ii, jj): """ to device, long, {-1} """ if not isinstance(ii, torch.Tensor): ii = torch.as_tensor(ii) if not isinstance(jj, torch.Tensor): jj = torch.as_tensor(jj) ii = ii.to(device="cuda", dtype=torch.long).reshape(-1) jj = jj.to(device="cuda", dtype=torch.long).reshape(-1) return ii, jj def upsample(self, ix, mask): """ upsample disparity """ disps_up = cvx_upsample(self.disps[ix].unsqueeze(-1), mask) self.disps_up[ix] = disps_up.squeeze() def normalize(self): """ normalize depth and poses """ with self.get_lock(): s = self.disps[:self.counter.value].mean() self.disps[:self.counter.value] /= s self.poses[:self.counter.value,:3] *= s self.dirty[:self.counter.value] = True def reproject(self, ii, jj): """ project points from ii -> jj """ ii, jj = DepthVideo.format_indicies(ii, jj) Gs = lietorch.SE3(self.poses[None]) coords, valid_mask = \ pops.projective_transform(Gs, self.disps[None], self.intrinsics[None], ii, jj) return coords, valid_mask def reproject_comp(self, ii, jj, xyz_comp): ii, jj = DepthVideo.format_indicies(ii,jj) Gs = lietorch.SE3(self.poses[None]) coords, valid_mask = \ pops.projective_transform_comp(Gs, self.disps[None], self.intrinsics[None], ii, jj, xyz_comp) return coords, valid_mask def distance(self, ii=None, jj=None, beta=0.3, bidirectional=True): """ frame distance metric """ return_matrix = False if ii is None: return_matrix = True N = self.counter.value ii, jj = torch.meshgrid(torch.arange(N), torch.arange(N)) ii, jj = DepthVideo.format_indicies(ii, jj) if bidirectional: poses = self.poses[:self.counter.value].clone() d1 = droid_backends.frame_distance( poses, self.disps, self.intrinsics[0], ii, jj, beta) d2 = droid_backends.frame_distance( poses, self.disps, self.intrinsics[0], jj, ii, beta) d = .5 * (d1 + d2) else: d = droid_backends.frame_distance( self.poses, self.disps, self.intrinsics[0], ii, jj, beta) if return_matrix: return d.reshape(N, N) return d def rm_new_gnss(self, t1): if (self.gnss_init_t1> 0 and self.state.gnss_valid[t1]) or self.state.odo_valid[t1]: graph_temp = gtsam.NonlinearFactorGraph() linear_point = self.marg_factor.linearizationPoint() graph_temp.push_back(self.marg_factor) if self.state.gnss_valid[t1]: T1 = self.state.wTbs[t1] T0 = self.state.wTbs[t1-1] p = np.matmul(trans.Cen(self.ten0).T, self.state.gnss_position[t1] - self.ten0) n0pbg = self.state.wTbs[t1].rotation().rotate(self.tbg) p = p - n0pbg p = p - T1.translation() + T0.translation() if not linear_point.exists(X(t1-1)): linear_point.insert(X(t1-1), self.cur_result.atPose3(X(t1-1))) gnss_factor = gtsam.GPSFactor(X(t1-1), p,\ gtsam.noiseModel.Robust.Create(\ gtsam.noiseModel.mEstimator.Cauchy(0.08),\ gtsam.noiseModel.Diagonal.Sigmas(np.array([1.0,1.0,5.0])))) graph_temp.push_back(gnss_factor) if self.state.odo_valid[t1]: v1 = np.matmul(self.state.wTbs[t1].rotation().matrix().T, self.state.vs[t1]) v0 = np.matmul(self.state.wTbs[t1-1].rotation().matrix().T, self.state.vs[t1-1]) v = self.state.odo_vel[t1] - v1 + v0 if not linear_point.exists(X(t1-1)): linear_point.insert(X(t1-1), self.cur_result.atPose3(X(t1-1))) if not linear_point.exists(V(t1-1)): linear_point.insert(V(t1-1), self.cur_result.atVector(V(t1-1))) odo_factor = gtsam.VelFactor(X(t1-1),V(t1-1),v,gtsam.noiseModel.Diagonal.Sigmas(np.array([2.0,2.0,2.0]))) graph_temp.push_back(odo_factor) h_factor = graph_temp.linearizeToHessianFactor(linear_point) self.marg_factor = gtsam.LinearContainerFactor(h_factor,linear_point) def set_prior(self, t0, t1): for i in range(t0,t0+2): self.prior_factor_map[i] = [] init_pose_sigma = self.init_pose_sigma if len(self.init_pose_sigma.shape) > 1: init_pose_sigma = self.init_pose_sigma[i-t0] self.prior_factor_map[i].append(gtsam.PriorFactorPose3(X(i),\ self.state.wTbs[i], \ gtsam.noiseModel.Diagonal.Sigmas(init_pose_sigma))) if not self.ignore_imu: self.prior_factor_map[i].append(gtsam.PriorFactorConstantBias(B(i),\ self.state.bs[i], \ gtsam.noiseModel.Diagonal.Sigmas(self.init_bias_sigma))) self.last_t0 = t0 self.last_t1 = t1 def ba(self, target, weight, eta, ii, jj, t0=1, t1=None, itrs=2, lm=1e-4, ep=0.1, motion_only=False): """ dense bundle adjustment (DBA) """ with self.get_lock(): if t1 is None: t1 = max(ii.max().item(), jj.max().item()) + 1 # 1) visual-only BA # 2) multi-sensor BA if not self.imu_enabled: droid_backends.ba(self.poses, self.disps, self.intrinsics[0], self.disps_sens, target, weight, eta, ii, jj, t0, t1, itrs, lm, ep, motion_only) for i in range(self.last_t0, min(ii.min().item(), jj.min().item())): if self.save_pkl: # save marginalized results self.tstamp_save[self.count_save] = self.tstamp[i].clone() self.disps_save[self.count_save] = self.disps[i].clone() self.poses_save[self.count_save] = self.poses[i].clone() if self.upsample_flag: self.disps_up_save[self.count_save] = self.disps_up[i].clone() self.images_save[self.count_save] = self.images[i,[2,1,0],::8,::8].permute(1,2,0) / 255.0 # might be "3::8, 3::8"? self.count_save += 1 self.last_t0 = min(ii.min().item(), jj.min().item()) self.last_t1 = t1 else: t0 = min(ii.min().item(), jj.min().item()) """ marginalization """ if self.last_t1!=t1 or self.last_t0 != t0: if self.last_t0 > t0: t0 = self.last_t0 elif self.last_t0 == t0: t0 = self.last_t0 else: marg_paras = [] # Construct a temporary factor graph (related to the old states) to obtain the marginalization information graph = gtsam.NonlinearFactorGraph() marg_idx = torch.logical_and(torch.greater_equal(self.cur_ii,self.last_t0),\ torch.less(self.cur_ii,t0)) marg_idx2 = torch.logical_and(torch.less(self.cur_ii,self.last_t1-2),\ torch.less(self.cur_jj,self.last_t1-2)) marg_idx = torch.logical_and(marg_idx,marg_idx2) marg_ii = self.cur_ii[marg_idx] marg_jj = self.cur_jj[marg_idx] marg_t0 = self.last_t0 marg_t1 = t0 + 1 if len(marg_ii) > 0: marg_t0 = self.last_t0 marg_t1 = torch.max(marg_jj).item()+1 marg_result = gtsam.Values() for i in range(self.last_t0,marg_t1): if i < t0: marg_paras.append(X(i)) if self.save_pkl: # save marginalized results self.tstamp_save[self.count_save] = self.tstamp[i].clone() self.disps_save[self.count_save] = self.disps[i].clone() self.poses_save[self.count_save] = self.poses[i].clone() if self.upsample_flag: self.disps_up_save[self.count_save] = self.disps_up[i].clone() self.images_save[self.count_save] = self.images[i,[2,1,0],::8,::8].permute(1,2,0) / 255.0 # might be "3::8, 3::8"? self.count_save += 1 marg_result.insert(X(i), self.cur_result.atPose3(X(i))) marg_target = self.cur_target[marg_idx] marg_weight = self.cur_weight[marg_idx] marg_eta = self.cur_eta[0:marg_t1-marg_t0] bacore = droid_backends.BACore() bacore.init(self.poses, self.disps, self.intrinsics[0], torch.zeros_like(self.disps_sens), marg_target, marg_weight, marg_eta, marg_ii, marg_jj, marg_t0, marg_t1, itrs, lm, ep, motion_only) H = torch.zeros([(marg_t1-marg_t0)*6,(marg_t1-marg_t0)*6],dtype=torch.float64,device='cpu') v = torch.zeros([(marg_t1-marg_t0)*6],dtype=torch.float64,device='cpu') bacore.hessian(H,v) for i in range(6): H[i,i] += 0.00025 # for stability # Hg,vg = BA2GTSAM(H,v,self.Tbc) Hgg = gtsam.BA2GTSAM(H,v,self.Tbc) Hg = Hgg[0:(marg_t1-marg_t0)*6,0:(marg_t1-marg_t0)*6] vg = Hgg[0:(marg_t1-marg_t0)*6, (marg_t1-marg_t0)*6] vis_factor = CustomHessianFactor(marg_result,Hg,vg) graph.push_back(vis_factor) for i in range(self.last_t0,marg_t1): if i < t0: if X(i) not in marg_paras: marg_paras.append(X(i)) if not self.ignore_imu: marg_paras.append(V(i)) marg_paras.append(B(i)) graph.push_back(gtsam.gtsam.CombinedImuFactor(\ X(i),V(i),X(i+1),V(i+1),B(i),B(i+1),\ self.state.preintegrations[i])) if self.gnss_init_t1 > 0: if self.state.gnss_valid[i]: p = np.matmul(trans.Cen(self.ten0).T, self.state.gnss_position[i] - self.ten0) n0pbg = self.state.wTbs[i].rotation().rotate(self.tbg) p = p - n0pbg gnss_factor = gtsam.GPSFactor(X(i), p,\ gtsam.noiseModel.Robust.Create(\ gtsam.noiseModel.mEstimator.Cauchy(0.08),\ gtsam.noiseModel.Diagonal.Sigmas(np.array([1.0,1.0,5.0])))) graph.push_back(gnss_factor) if self.state.odo_valid[i]: vb = self.state.odo_vel[i] odo_factor = gtsam.VelFactor(X(i),V(i),vb,gtsam.noiseModel.Diagonal.Sigmas(np.array([2.0,2.0,2.0]))) graph.push_back(odo_factor) keys = self.prior_factor_map.keys() for i in sorted(keys): if i < t0: for iii in range(len(self.prior_factor_map[i])): graph.push_back(self.prior_factor_map[i][iii]) del self.prior_factor_map[i] if not self.marg_factor == None: graph.push_back(self.marg_factor) self.marg_factor = gtsam.marginalizeOut(graph,self.cur_result,marg_paras) # covariance inflation of IMU biases if self.reinit == True: all_keys = self.marg_factor.keys() for i in range(len(all_keys)): if all_keys[i] == B(t0): all_keys[i] = B(0) graph = gtsam.NonlinearFactorGraph() graph.push_back(self.marg_factor.rekey(all_keys)) b_l = gtsam.BetweenFactorConstantBias(B(0),B(t0),gtsam.imuBias.ConstantBias(np.array([.0,.0,.0]),np.array([.0,.0,.0])),\ gtsam.noiseModel.Diagonal.Sigmas(self.init_bias_sigma)) graph.push_back(b_l) result_tmp = self.marg_factor.linearizationPoint() result_tmp.insert(B(0),result_tmp.atConstantBias(B(t0))) self.marg_factor = gtsam.marginalizeOut(graph,result_tmp,[B(0)]) self.reinit = False self.last_t0 = t0 self.last_t1 = t1 """ optimization """ H = torch.zeros([(t1-t0)*6,(t1-t0)*6],dtype=torch.float64,device='cpu') v = torch.zeros([(t1-t0)*6],dtype=torch.float64,device='cpu') dx = torch.zeros([(t1-t0)*6],dtype=torch.float64,device='cpu') bacore = droid_backends.BACore() active_index = torch.logical_and(ii>=t0,jj>=t0) self.cur_ii = ii[active_index] self.cur_jj = jj[active_index] self.cur_target = target[active_index] self.cur_weight = weight[active_index] self.cur_eta = eta[(t0-ii.min().item()):] bacore.init(self.poses, self.disps, self.intrinsics[0], self.disps_sens, self.cur_target, self.cur_weight, self.cur_eta, self.cur_ii, self.cur_jj, t0, t1, itrs, lm, ep, motion_only) self.cur_graph = gtsam.NonlinearFactorGraph() params = gtsam.LevenbergMarquardtParams()#;params.setMaxIterations(1) # imu factor if not self.ignore_imu: for i in range(t0,t1): if i > t0: imu_factor = gtsam.gtsam.CombinedImuFactor(\ X(i-1),V(i-1),X(i),V(i),B(i-1),B(i),\ self.state.preintegrations[i-1]) self.cur_graph.add(imu_factor) # prior factor keys = self.prior_factor_map.keys() for i in sorted(keys): if i >= t0 and i < t1: for iii in range(len(self.prior_factor_map[i])): self.cur_graph.push_back(self.prior_factor_map[i][iii]) # marginalization factor if self.marg_factor is not None: self.cur_graph.push_back(self.marg_factor) # GNSS factor if self.gnss_init_t1 > 0: for i in range(t0,t1): if self.state.gnss_valid[i]: p = np.matmul(trans.Cen(self.ten0).T, self.state.gnss_position[i] - self.ten0) n0pbg = self.state.wTbs[i].rotation().rotate(self.tbg) p = p - n0pbg gnss_factor = gtsam.GPSFactor(X(i), p,\ gtsam.noiseModel.Robust.Create(\ gtsam.noiseModel.mEstimator.Cauchy(0.08),\ gtsam.noiseModel.Diagonal.Sigmas(np.array([1.0,1.0,5.0])))) self.cur_graph.push_back(gnss_factor) # Odo factor for i in range(t0,t1): if self.state.odo_valid[i]: vb = self.state.odo_vel[i] odo_factor = gtsam.VelFactor(X(i),V(i),vb,gtsam.noiseModel.Diagonal.Sigmas(np.array([2.0,2.0,2.0]))) self.cur_graph.push_back(odo_factor) """ multi-sensor DBA iterations """ for iter in range(2): if iter > 0: self.cur_graph.resize(self.cur_graph.size()-1) bacore.hessian(H,v) # camera frame Hgg = gtsam.BA2GTSAM(H,v,self.Tbc) Hg = Hgg[0:(t1-t0)*6,0:(t1-t0)*6] vg = Hgg[0:(t1-t0)*6,(t1-t0)*6] initial = gtsam.Values() for i in range(t0,t1): initial.insert(X(i), self.state.wTbs[i]) # the indice need to be handled initial_vis = copy.deepcopy(initial) vis_factor = CustomHessianFactor(initial_vis,Hg,vg) self.cur_graph.push_back(vis_factor) if not self.ignore_imu: for i in range(t0,t1): initial.insert(B(i),self.state.bs[i]) initial.insert(V(i),self.state.vs[i]) optimizer = gtsam.LevenbergMarquardtOptimizer(self.cur_graph, initial, params) self.cur_result = optimizer.optimize() # retraction and depth update for i in range(t0,t1): p0 = initial.atPose3(X(i)) p1 = self.cur_result.atPose3(X(i)) xi = gtsam.Pose3.Logmap(p0.inverse()*p1) dx[(i-t0)*6:(i-t0)*6+6] = torch.tensor(xi) if not self.ignore_imu: self.state.bs[i] = self.cur_result.atConstantBias(B(i)) self.state.vs[i] = self.cur_result.atVector(V(i)) self.state.wTbs[i] = self.cur_result.atPose3(X(i)) dx = torch.tensor(gtsam.GTSAM2BA(dx,self.Tbc)) dx_dz = bacore.retract(dx) del bacore self.disps.clamp_(min=0.001) ================================================ FILE: dbaf/droid_net.py ================================================ import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict from modules.extractor import BasicEncoder from modules.corr import CorrBlock from modules.gru import ConvGRU from modules.clipping import GradientClip from lietorch import SE3 from geom.ba import BA import geom.projective_ops as pops from geom.graph_utils import graph_to_edge_list, keyframe_indicies from torch_scatter import scatter_mean import time def cvx_upsample(data, mask): """ upsample pixel-wise transformation field """ batch, ht, wd, dim = data.shape data = data.permute(0, 3, 1, 2) mask = mask.view(batch, 1, 9, 8, 8, ht, wd) mask = torch.softmax(mask, dim=2) up_data = F.unfold(data, [3,3], padding=1) up_data = up_data.view(batch, dim, 9, 1, 1, ht, wd) up_data = torch.sum(mask * up_data, dim=2) up_data = up_data.permute(0, 4, 2, 5, 3, 1) up_data = up_data.reshape(batch, 8*ht, 8*wd, dim) return up_data def upsample_disp(disp, mask): batch, num, ht, wd = disp.shape disp = disp.view(batch*num, ht, wd, 1) mask = mask.view(batch*num, -1, ht, wd) return cvx_upsample(disp, mask).view(batch, num, 8*ht, 8*wd) class GraphAgg(nn.Module): def __init__(self): super(GraphAgg, self).__init__() self.conv1 = nn.Conv2d(128, 128, 3, padding=1) self.conv2 = nn.Conv2d(128, 128, 3, padding=1) self.relu = nn.ReLU(inplace=True) self.eta = nn.Sequential( nn.Conv2d(128, 1, 3, padding=1), GradientClip(), nn.Softplus()) self.upmask = nn.Sequential( nn.Conv2d(128, 8*8*9, 1, padding=0)) def forward(self, net, ii): batch, num, ch, ht, wd = net.shape net = net.view(batch*num, ch, ht, wd) _, ix = torch.unique(ii, return_inverse=True) net = self.relu(self.conv1(net)) net = net.view(batch, num, 128, ht, wd) net = scatter_mean(net, ix, dim=1) net = net.view(-1, 128, ht, wd) net = self.relu(self.conv2(net)) eta = self.eta(net).view(batch, -1, ht, wd) upmask = self.upmask(net).view(batch, -1, 8*8*9, ht, wd) return .01 * eta, upmask class UpdateModule(nn.Module): def __init__(self): super(UpdateModule, self).__init__() cor_planes = 4 * (2*3 + 1)**2 self.corr_encoder = nn.Sequential( nn.Conv2d(cor_planes, 128, 1, padding=0), nn.ReLU(inplace=True), nn.Conv2d(128, 128, 3, padding=1), nn.ReLU(inplace=True)) self.flow_encoder = nn.Sequential( nn.Conv2d(4, 128, 7, padding=3), nn.ReLU(inplace=True), nn.Conv2d(128, 64, 3, padding=1), nn.ReLU(inplace=True)) self.weight = nn.Sequential( nn.Conv2d(128, 128, 3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(128, 2, 3, padding=1), GradientClip(), nn.Sigmoid()) self.delta = nn.Sequential( nn.Conv2d(128, 128, 3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(128, 2, 3, padding=1), GradientClip()) self.gru = ConvGRU(128, 128+128+64) self.agg = GraphAgg() def forward(self, net, inp, corr, flow=None, ii=None, jj=None, upsample = False): """ RaftSLAM update operator """ batch, num, ch, ht, wd = net.shape if flow is None: flow = torch.zeros(batch, num, 4, ht, wd, device=net.device) output_dim = (batch, num, -1, ht, wd) net = net.view(batch*num, -1, ht, wd) inp = inp.view(batch*num, -1, ht, wd) corr = corr.view(batch*num, -1, ht, wd) flow = flow.view(batch*num, -1, ht, wd) corr = self.corr_encoder(corr) flow = self.flow_encoder(flow) net = self.gru(net, inp, corr, flow) ### update variables ### delta = self.delta(net).view(*output_dim) weight = self.weight(net).view(*output_dim) delta = delta.permute(0,1,3,4,2)[...,:2].contiguous() weight = weight.permute(0,1,3,4,2)[...,:2].contiguous() net = net.view(*output_dim) if ii is not None: ### ATTENTION!!!! ### # We found this useless for VIO performance, thus disable it to save computation. # Feel free to re-enable it. if upsample: eta, upmask = self.agg(net, ii.to(net.device)) return net, delta, weight, eta, upmask else: return net, delta, weight, None, None else: return net, delta, weight class DroidNet(nn.Module): def __init__(self): super(DroidNet, self).__init__() self.fnet = BasicEncoder(output_dim=128, norm_fn='instance') self.cnet = BasicEncoder(output_dim=256, norm_fn='none') self.update = UpdateModule() def extract_features(self, images): """ run feeature extraction networks """ # normalize images images = images[:, :, [2,1,0]] / 255.0 mean = torch.as_tensor([0.485, 0.456, 0.406], device=images.device) std = torch.as_tensor([0.229, 0.224, 0.225], device=images.device) images = images.sub_(mean[:, None, None]).div_(std[:, None, None]) fmaps = self.fnet(images) net = self.cnet(images) net, inp = net.split([128,128], dim=2) net = torch.tanh(net) inp = torch.relu(inp) return fmaps, net, inp def forward(self, Gs, images, disps, intrinsics, graph=None, num_steps=12, fixedp=2): """ Estimates SE3 or Sim3 between pair of frames """ u = keyframe_indicies(graph) ii, jj, kk = graph_to_edge_list(graph) ii = ii.to(device=images.device, dtype=torch.long) jj = jj.to(device=images.device, dtype=torch.long) fmaps, net, inp = self.extract_features(images) net, inp = net[:,ii], inp[:,ii] corr_fn = CorrBlock(fmaps[:,ii], fmaps[:,jj], num_levels=4, radius=3) ht, wd = images.shape[-2:] coords0 = pops.coords_grid(ht//8, wd//8, device=images.device) coords1, _ = pops.projective_transform(Gs, disps, intrinsics, ii, jj) target = coords1.clone() Gs_list, disp_list, residual_list = [], [], [] for step in range(num_steps): Gs = Gs.detach() disps = disps.detach() coords1 = coords1.detach() target = target.detach() # extract motion features corr = corr_fn(coords1) resd = target - coords1 flow = coords1 - coords0 motion = torch.cat([flow, resd], dim=-1) motion = motion.permute(0,1,4,2,3).clamp(-64.0, 64.0) net, delta, weight, eta, upmask = \ self.update(net, inp, corr, motion, ii, jj) target = coords1 + delta for i in range(2): Gs, disps = BA(target, weight, eta, Gs, disps, intrinsics, ii, jj, fixedp=2) coords1, valid_mask = pops.projective_transform(Gs, disps, intrinsics, ii, jj) residual = (target - coords1) Gs_list.append(Gs) disp_list.append(upsample_disp(disps, upmask)) residual_list.append(valid_mask * residual) return Gs_list, disp_list, residual_list ================================================ FILE: dbaf/geoFunc/__init__.py ================================================ ================================================ FILE: dbaf/geoFunc/const_value.py ================================================ import math pi=math.pi a = 6378137 finv = 298.257223563 ================================================ FILE: dbaf/geoFunc/trans.py ================================================ import math from math import atan2, sin, cos from . import const_value import numpy as np from scipy.spatial.transform import Rotation def cart2geod(Xinput): X=Xinput[0] Y=Xinput[1] Z=Xinput[2] tolsq = 1e-10 maxit = 10 rtd = 180/const_value.pi esq = (2-1/const_value.finv) / const_value.finv oneesq = 1-esq P=math.sqrt(X*X+Y*Y) if P > 1e-20: dlambda = math.atan2(Y,X) *rtd else: dlambda = 0 if dlambda <0: dlambda = dlambda +360 r=math.sqrt(P*P+Z*Z) if r>1e-20: sinphi=Z/r else : sinphi=0 dphi = math.asin(sinphi) if r<1e-20: h=0 return h = r-const_value.a*(1-sinphi*sinphi/const_value.finv) for i in range(maxit): sinphi = math.sin(dphi) cosphi = math.cos(dphi) N_phi = const_value.a/math.sqrt(1-esq*sinphi*sinphi) dP =P -(N_phi+h)*cosphi dZ=Z-(N_phi*oneesq+h)*sinphi h=h+(sinphi*dZ+cosphi*dP) dphi =dphi+(cosphi*dZ - sinphi*dP)/(N_phi+h) if dP*dP + dZ*dZ= 0) & (jj >= 0) & (ii < n) & (jj < m) return scatter_sum(A[:,v], ii[v]*m + jj[v], dim=1, dim_size=n*m) def safe_scatter_add_vec(b, ii, n): v = (ii >= 0) & (ii < n) return scatter_sum(b[:,v], ii[v], dim=1, dim_size=n) # apply retraction operator to inv-depth maps def disp_retr(disps, dz, ii): ii = ii.to(device=dz.device) return disps + scatter_sum(dz, ii, dim=1, dim_size=disps.shape[1]) # apply retraction operator to poses def pose_retr(poses, dx, ii): ii = ii.to(device=dx.device) return poses.retr(scatter_sum(dx, ii, dim=1, dim_size=poses.shape[1])) def BA(target, weight, eta, poses, disps, intrinsics, ii, jj, fixedp=1, rig=1): """ Full Bundle Adjustment """ B, P, ht, wd = disps.shape N = ii.shape[0] D = poses.manifold_dim ### 1: commpute jacobians and residuals ### coords, valid, (Ji, Jj, Jz) = pops.projective_transform( poses, disps, intrinsics, ii, jj, jacobian=True) r = (target - coords).view(B, N, -1, 1) w = .001 * (valid * weight).view(B, N, -1, 1) ### 2: construct linear system ### Ji = Ji.reshape(B, N, -1, D) Jj = Jj.reshape(B, N, -1, D) wJiT = (w * Ji).transpose(2,3) wJjT = (w * Jj).transpose(2,3) Jz = Jz.reshape(B, N, ht*wd, -1) Hii = torch.matmul(wJiT, Ji) # [B,num,6,6] Hij = torch.matmul(wJiT, Jj) Hji = torch.matmul(wJjT, Ji) Hjj = torch.matmul(wJjT, Jj) vi = torch.matmul(wJiT, r).squeeze(-1) # [B,num,6] vj = torch.matmul(wJjT, r).squeeze(-1) Ei = (wJiT.view(B,N,D,ht*wd,-1) * Jz[:,:,None]).sum(dim=-1) # [B,num,6,ht*wd] Ej = (wJjT.view(B,N,D,ht*wd,-1) * Jz[:,:,None]).sum(dim=-1) # [B,num,6,ht*wd] w = w.view(B, N, ht*wd, -1) r = r.view(B, N, ht*wd, -1) wk = torch.sum(w*r*Jz, dim=-1) Ck = torch.sum(w*Jz*Jz, dim=-1) # [B,num,ht*wd] kx, kk = torch.unique(ii, return_inverse=True) M = kx.shape[0] # only optimize keyframe poses P = P // rig - fixedp ii = ii // rig - fixedp jj = jj // rig - fixedp H = safe_scatter_add_mat(Hii, ii, ii, P, P) + \ safe_scatter_add_mat(Hij, ii, jj, P, P) + \ safe_scatter_add_mat(Hji, jj, ii, P, P) + \ safe_scatter_add_mat(Hjj, jj, jj, P, P) E = safe_scatter_add_mat(Ei, ii, kk, P, M) + \ safe_scatter_add_mat(Ej, jj, kk, P, M) v = safe_scatter_add_vec(vi, ii, P) + \ safe_scatter_add_vec(vj, jj, P) C = safe_scatter_add_vec(Ck, kk, M) w = safe_scatter_add_vec(wk, kk, M) C = C + eta.view(*C.shape) + 1e-7 H = H.view(B, P, P, D, D) E = E.view(B, P, M, D, ht*wd) ### 3: solve the system ### dx, dz = schur_solve(H, E, C, v, w) ### 4: apply retraction ### poses = pose_retr(poses, dx, torch.arange(P) + fixedp) disps = disp_retr(disps, dz.view(B,-1,ht,wd), kx) disps = torch.where(disps > 10, torch.zeros_like(disps), disps) disps = disps.clamp(min=0.0) return poses, disps def MoBA(target, weight, eta, poses, disps, intrinsics, ii, jj, fixedp=1, rig=1): """ Motion only bundle adjustment """ B, P, ht, wd = disps.shape N = ii.shape[0] D = poses.manifold_dim ### 1: commpute jacobians and residuals ### coords, valid, (Ji, Jj, Jz) = pops.projective_transform( poses, disps, intrinsics, ii, jj, jacobian=True) r = (target - coords).view(B, N, -1, 1) w = .001 * (valid * weight).view(B, N, -1, 1) ### 2: construct linear system ### Ji = Ji.reshape(B, N, -1, D) Jj = Jj.reshape(B, N, -1, D) wJiT = (w * Ji).transpose(2,3) wJjT = (w * Jj).transpose(2,3) Hii = torch.matmul(wJiT, Ji) Hij = torch.matmul(wJiT, Jj) Hji = torch.matmul(wJjT, Ji) Hjj = torch.matmul(wJjT, Jj) vi = torch.matmul(wJiT, r).squeeze(-1) vj = torch.matmul(wJjT, r).squeeze(-1) # only optimize keyframe poses P = P // rig - fixedp ii = ii // rig - fixedp jj = jj // rig - fixedp H = safe_scatter_add_mat(Hii, ii, ii, P, P) + \ safe_scatter_add_mat(Hij, ii, jj, P, P) + \ safe_scatter_add_mat(Hji, jj, ii, P, P) + \ safe_scatter_add_mat(Hjj, jj, jj, P, P) v = safe_scatter_add_vec(vi, ii, P) + \ safe_scatter_add_vec(vj, jj, P) H = H.view(B, P, P, D, D) ### 3: solve the system ### dx = block_solve(H, v) ### 4: apply retraction ### poses = pose_retr(poses, dx, torch.arange(P) + fixedp) return poses ================================================ FILE: dbaf/geom/chol.py ================================================ import torch import torch.nn.functional as F import geom.projective_ops as pops class CholeskySolver(torch.autograd.Function): @staticmethod def forward(ctx, H, b): # don't crash training if cholesky decomp fails try: U = torch.linalg.cholesky(H) xs = torch.cholesky_solve(b, U) ctx.save_for_backward(U, xs) ctx.failed = False except Exception as e: print(e) ctx.failed = True xs = torch.zeros_like(b) return xs @staticmethod def backward(ctx, grad_x): if ctx.failed: return None, None U, xs = ctx.saved_tensors dz = torch.cholesky_solve(grad_x, U) dH = -torch.matmul(xs, dz.transpose(-1,-2)) return dH, dz def block_solve(H, b, ep=0.1, lm=0.0001): """ solve normal equations """ B, N, _, D, _ = H.shape I = torch.eye(D).to(H.device) H = H + (ep + lm*H) * I H = H.permute(0,1,3,2,4) H = H.reshape(B, N*D, N*D) b = b.reshape(B, N*D, 1) x = CholeskySolver.apply(H,b) return x.reshape(B, N, D) def schur_solve(H, E, C, v, w, ep=0.1, lm=0.0001, sless=False): """ solve using shur complement """ B, P, M, D, HW = E.shape H = H.permute(0,1,3,2,4).reshape(B, P*D, P*D) E = E.permute(0,1,3,2,4).reshape(B, P*D, M*HW) Q = (1.0 / C).view(B, M*HW, 1) # damping I = torch.eye(P*D).to(H.device) H = H + (ep + lm*H) * I v = v.reshape(B, P*D, 1) w = w.reshape(B, M*HW, 1) Et = E.transpose(1,2) S = H - torch.matmul(E, Q*Et) v = v - torch.matmul(E, Q*w) dx = CholeskySolver.apply(S, v) if sless: return dx.reshape(B, P, D) dz = Q * (w - Et @ dx) dx = dx.reshape(B, P, D) dz = dz.reshape(B, M, HW) return dx, dz ================================================ FILE: dbaf/geom/graph_utils.py ================================================ import torch import numpy as np from collections import OrderedDict import lietorch from data_readers.rgbd_utils import compute_distance_matrix_flow, compute_distance_matrix_flow2 def graph_to_edge_list(graph): ii, jj, kk = [], [], [] for s, u in enumerate(graph): for v in graph[u]: ii.append(u) jj.append(v) kk.append(s) ii = torch.as_tensor(ii) jj = torch.as_tensor(jj) kk = torch.as_tensor(kk) return ii, jj, kk def keyframe_indicies(graph): return torch.as_tensor([u for u in graph]) def meshgrid(m, n, device='cuda'): ii, jj = torch.meshgrid(torch.arange(m), torch.arange(n)) return ii.reshape(-1).to(device), jj.reshape(-1).to(device) def neighbourhood_graph(n, r): ii, jj = meshgrid(n, n) d = (ii - jj).abs() keep = (d >= 1) & (d <= r) return ii[keep], jj[keep] def build_frame_graph(poses, disps, intrinsics, num=16, thresh=24.0, r=2): """ construct a frame graph between co-visible frames """ N = poses.shape[1] poses = poses[0].cpu().numpy() disps = disps[0][:,3::8,3::8].cpu().numpy() intrinsics = intrinsics[0].cpu().numpy() / 8.0 d = compute_distance_matrix_flow(poses, disps, intrinsics) count = 0 graph = OrderedDict() for i in range(N): graph[i] = [] d[i,i] = np.inf for j in range(i-r, i+r+1): if 0 <= j < N and i != j: graph[i].append(j) d[i,j] = np.inf count += 1 while count < num: ix = np.argmin(d) i, j = ix // N, ix % N if d[i,j] < thresh: graph[i].append(j) d[i,j] = np.inf count += 1 else: break return graph def build_frame_graph_v2(poses, disps, intrinsics, num=16, thresh=24.0, r=2): """ construct a frame graph between co-visible frames """ N = poses.shape[1] # poses = poses[0].cpu().numpy() # disps = disps[0].cpu().numpy() # intrinsics = intrinsics[0].cpu().numpy() d = compute_distance_matrix_flow2(poses, disps, intrinsics) # import matplotlib.pyplot as plt # plt.imshow(d) # plt.show() count = 0 graph = OrderedDict() for i in range(N): graph[i] = [] d[i,i] = np.inf for j in range(i-r, i+r+1): if 0 <= j < N and i != j: graph[i].append(j) d[i,j] = np.inf count += 1 while 1: ix = np.argmin(d) i, j = ix // N, ix % N if d[i,j] < thresh: graph[i].append(j) for i1 in range(i-1, i+2): for j1 in range(j-1, j+2): if 0 <= i1 < N and 0 <= j1 < N: d[i1, j1] = np.inf count += 1 else: break return graph ================================================ FILE: dbaf/geom/losses.py ================================================ from collections import OrderedDict import numpy as np import torch from lietorch import SO3, SE3, Sim3 from .graph_utils import graph_to_edge_list from .projective_ops import projective_transform def pose_metrics(dE): """ Translation/Rotation/Scaling metrics from Sim3 """ t, q, s = dE.data.split([3, 4, 1], -1) ang = SO3(q).log().norm(dim=-1) # convert radians to degrees r_err = (180 / np.pi) * ang t_err = t.norm(dim=-1) s_err = (s - 1.0).abs() return r_err, t_err, s_err def fit_scale(Ps, Gs): b = Ps.shape[0] t1 = Ps.data[...,:3].detach().reshape(b, -1) t2 = Gs.data[...,:3].detach().reshape(b, -1) s = (t1*t2).sum(-1) / ((t2*t2).sum(-1) + 1e-8) return s def geodesic_loss(Ps, Gs, graph, gamma=0.9, do_scale=True): """ Loss function for training network """ # relative pose ii, jj, kk = graph_to_edge_list(graph) dP = Ps[:,jj] * Ps[:,ii].inv() n = len(Gs) geodesic_loss = 0.0 for i in range(n): w = gamma ** (n - i - 1) dG = Gs[i][:,jj] * Gs[i][:,ii].inv() if do_scale: s = fit_scale(dP, dG) dG = dG.scale(s[:,None]) # pose error d = (dG * dP.inv()).log() if isinstance(dG, SE3): tau, phi = d.split([3,3], dim=-1) geodesic_loss += w * ( tau.norm(dim=-1).mean() + phi.norm(dim=-1).mean()) elif isinstance(dG, Sim3): tau, phi, sig = d.split([3,3,1], dim=-1) geodesic_loss += w * ( tau.norm(dim=-1).mean() + phi.norm(dim=-1).mean() + 0.05 * sig.norm(dim=-1).mean()) dE = Sim3(dG * dP.inv()).detach() r_err, t_err, s_err = pose_metrics(dE) metrics = { 'rot_error': r_err.mean().item(), 'tr_error': t_err.mean().item(), 'bad_rot': (r_err < .1).float().mean().item(), 'bad_tr': (t_err < .01).float().mean().item(), } return geodesic_loss, metrics def residual_loss(residuals, gamma=0.9): """ loss on system residuals """ residual_loss = 0.0 n = len(residuals) for i in range(n): w = gamma ** (n - i - 1) residual_loss += w * residuals[i].abs().mean() return residual_loss, {'residual': residual_loss.item()} def flow_loss(Ps, disps, poses_est, disps_est, intrinsics, graph, gamma=0.9): """ optical flow loss """ N = Ps.shape[1] graph = OrderedDict() for i in range(N): graph[i] = [j for j in range(N) if abs(i-j)==1] ii, jj, kk = graph_to_edge_list(graph) coords0, val0 = projective_transform(Ps, disps, intrinsics, ii, jj) val0 = val0 * (disps[:,ii] > 0).float().unsqueeze(dim=-1) n = len(poses_est) flow_loss = 0.0 for i in range(n): w = gamma ** (n - i - 1) coords1, val1 = projective_transform(poses_est[i], disps_est[i], intrinsics, ii, jj) v = (val0 * val1).squeeze(dim=-1) epe = v * (coords1 - coords0).norm(dim=-1) flow_loss += w * epe.mean() epe = epe.reshape(-1)[v.reshape(-1) > 0.5] metrics = { 'f_error': epe.mean().item(), '1px': (epe<1.0).float().mean().item(), } return flow_loss, metrics ================================================ FILE: dbaf/geom/projective_ops.py ================================================ import torch import torch.nn.functional as F from lietorch import SE3, Sim3 MIN_DEPTH = 0.2 def extract_intrinsics(intrinsics): return intrinsics[...,None,None,:].unbind(dim=-1) def coords_grid(ht, wd, **kwargs): y, x = torch.meshgrid( torch.arange(ht).to(**kwargs).float(), torch.arange(wd).to(**kwargs).float()) return torch.stack([x, y], dim=-1) def iproj(disps, intrinsics, jacobian=False): """ pinhole camera inverse projection """ ht, wd = disps.shape[2:] fx, fy, cx, cy = extract_intrinsics(intrinsics) y, x = torch.meshgrid( torch.arange(ht).to(disps.device).float(), torch.arange(wd).to(disps.device).float()) i = torch.ones_like(disps) X = (x - cx) / fx Y = (y - cy) / fy pts = torch.stack([X, Y, i, disps], dim=-1) if jacobian: J = torch.zeros_like(pts) J[...,-1] = 1.0 return pts, J return pts, None def proj(Xs, intrinsics, jacobian=False, return_depth=False): """ pinhole camera projection """ fx, fy, cx, cy = extract_intrinsics(intrinsics) X, Y, Z, D = Xs.unbind(dim=-1) Z = torch.where(Z < 0.5*MIN_DEPTH, torch.ones_like(Z), Z) d = 1.0 / Z x = fx * (X * d) + cx y = fy * (Y * d) + cy if return_depth: coords = torch.stack([x, y, D*d], dim=-1) else: coords = torch.stack([x, y], dim=-1) if jacobian: B, N, H, W = d.shape o = torch.zeros_like(d) proj_jac = torch.stack([ fx*d, o, -fx*X*d*d, o, o, fy*d, -fy*Y*d*d, o, # o, o, -D*d*d, d, ], dim=-1).view(B, N, H, W, 2, 4) return coords, proj_jac return coords, None def actp(Gij, X0, jacobian=False): """ action on point cloud """ X1 = Gij[:,:,None,None] * X0 if jacobian: X, Y, Z, d = X1.unbind(dim=-1) o = torch.zeros_like(d) B, N, H, W = d.shape if isinstance(Gij, SE3): Ja = torch.stack([ d, o, o, o, Z, -Y, o, d, o, -Z, o, X, o, o, d, Y, -X, o, o, o, o, o, o, o, ], dim=-1).view(B, N, H, W, 4, 6) elif isinstance(Gij, Sim3): Ja = torch.stack([ d, o, o, o, Z, -Y, X, o, d, o, -Z, o, X, Y, o, o, d, Y, -X, o, Z, o, o, o, o, o, o, o ], dim=-1).view(B, N, H, W, 4, 7) return X1, Ja return X1, None def projective_transform(poses, depths, intrinsics, ii, jj, jacobian=False, return_depth=False): """ map points from ii->jj """ # inverse project (pinhole) X0, Jz = iproj(depths[:,ii], intrinsics[:,ii], jacobian=jacobian) # transform Gij = poses[:,jj] * poses[:,ii].inv() Gij.data[:,ii==jj] = torch.as_tensor([-0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0], device="cuda") X1, Ja = actp(Gij, X0, jacobian=jacobian) # 4*6 # project (pinhole) x1, Jp = proj(X1, intrinsics[:,jj], jacobian=jacobian, return_depth=return_depth) # 2*4 # exclude points too close to camera valid = ((X1[...,2] > MIN_DEPTH) & (X0[...,2] > MIN_DEPTH)).float() valid = valid.unsqueeze(-1) if jacobian: # Ji transforms according to dual adjoint Jj = torch.matmul(Jp, Ja) # 2*6 Ji = -Gij[:,:,None,None,None].adjT(Jj) # 2*6 * 6*6 Jz = Gij[:,:,None,None] * Jz Jz = torch.matmul(Jp, Jz.unsqueeze(-1)) return x1, valid, (Ji, Jj, Jz) return x1, valid def projective_transform_comp(poses, depths, intrinsics, ii, jj, xyz_comp, jacobian=False, return_depth=False): """ map points from ii->jj """ # inverse project (pinhole) X0, Jz = iproj(depths[:,ii], intrinsics[:,ii], jacobian=jacobian) # transform Gij = poses[:,jj] * poses[:,ii].inv() Gij.data[:,ii==jj] = torch.as_tensor([-0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0], device="cuda") X1, Ja = actp(Gij, X0, jacobian=jacobian) X1 = X1 + xyz_comp # compensate the object motion # project (pinhole) x1, Jp = proj(X1, intrinsics[:,jj], jacobian=jacobian, return_depth=return_depth) # exclude points too close to camera valid = ((X1[...,2] > MIN_DEPTH) & (X0[...,2] > MIN_DEPTH)).float() valid = valid.unsqueeze(-1) if jacobian: # Ji transforms according to dual adjoint Jj = torch.matmul(Jp, Ja) Ji = -Gij[:,:,None,None,None].adjT(Jj) Jz = Gij[:,:,None,None] * Jz Jz = torch.matmul(Jp, Jz.unsqueeze(-1)) return x1, valid, (Ji, Jj, Jz) return x1, valid def induced_flow(poses, disps, intrinsics, ii, jj): """ optical flow induced by camera motion """ ht, wd = disps.shape[2:] y, x = torch.meshgrid( torch.arange(ht).to(disps.device).float(), torch.arange(wd).to(disps.device).float()) coords0 = torch.stack([x, y], dim=-1) coords1, valid = projective_transform(poses, disps, intrinsics, ii, jj, False) return coords1[...,:2] - coords0, valid ================================================ FILE: dbaf/modules/__init__.py ================================================ ================================================ FILE: dbaf/modules/clipping.py ================================================ import torch import torch.nn as nn import torch.nn.functional as F GRAD_CLIP = .01 class GradClip(torch.autograd.Function): @staticmethod def forward(ctx, x): return x @staticmethod def backward(ctx, grad_x): o = torch.zeros_like(grad_x) grad_x = torch.where(grad_x.abs()>GRAD_CLIP, o, grad_x) grad_x = torch.where(torch.isnan(grad_x), o, grad_x) return grad_x class GradientClip(nn.Module): def __init__(self): super(GradientClip, self).__init__() def forward(self, x): return GradClip.apply(x) ================================================ FILE: dbaf/modules/corr.py ================================================ import torch import torch.nn.functional as F import droid_backends class CorrSampler(torch.autograd.Function): @staticmethod def forward(ctx, volume, coords, radius): ctx.save_for_backward(volume,coords) ctx.radius = radius corr, = droid_backends.corr_index_forward(volume, coords, radius) return corr @staticmethod def backward(ctx, grad_output): volume, coords = ctx.saved_tensors grad_output = grad_output.contiguous() grad_volume, = droid_backends.corr_index_backward(volume, coords, grad_output, ctx.radius) return grad_volume, None, None class CorrBlock: def __init__(self, fmap1, fmap2, num_levels=4, radius=3): self.num_levels = num_levels self.radius = radius self.corr_pyramid = [] # all pairs correlation corr = CorrBlock.corr(fmap1, fmap2) batch, num, h1, w1, h2, w2 = corr.shape corr = corr.reshape(batch*num*h1*w1, 1, h2, w2) for i in range(self.num_levels): self.corr_pyramid.append( corr.view(batch*num, h1, w1, h2//2**i, w2//2**i)) corr = F.avg_pool2d(corr, 2, stride=2) def __call__(self, coords): out_pyramid = [] batch, num, ht, wd, _ = coords.shape coords = coords.permute(0,1,4,2,3) coords = coords.contiguous().view(batch*num, 2, ht, wd) for i in range(self.num_levels): corr = CorrSampler.apply(self.corr_pyramid[i], coords/2**i, self.radius) # 我的理解,每一个点与其他每个点都有一个(2*3+1)^2=49长度的特征 out_pyramid.append(corr.view(batch, num, -1, ht, wd)) return torch.cat(out_pyramid, dim=2) def cat(self, other): for i in range(self.num_levels): self.corr_pyramid[i] = torch.cat([self.corr_pyramid[i], other.corr_pyramid[i]], 0) return self def __getitem__(self, index): for i in range(self.num_levels): self.corr_pyramid[i] = self.corr_pyramid[i][index] return self @staticmethod def corr(fmap1, fmap2): """ all-pairs correlation """ batch, num, dim, ht, wd = fmap1.shape fmap1 = fmap1.reshape(batch*num, dim, ht*wd) / 4.0 fmap2 = fmap2.reshape(batch*num, dim, ht*wd) / 4.0 corr = torch.matmul(fmap1.transpose(1,2), fmap2) return corr.view(batch, num, ht, wd, ht, wd) class CorrLayer(torch.autograd.Function): @staticmethod def forward(ctx, fmap1, fmap2, coords, r): ctx.r = r ctx.save_for_backward(fmap1, fmap2, coords) corr, = droid_backends.altcorr_forward(fmap1, fmap2, coords, ctx.r) return corr @staticmethod def backward(ctx, grad_corr): fmap1, fmap2, coords = ctx.saved_tensors grad_corr = grad_corr.contiguous() fmap1_grad, fmap2_grad, coords_grad = \ droid_backends.altcorr_backward(fmap1, fmap2, coords, grad_corr, ctx.r) return fmap1_grad, fmap2_grad, coords_grad, None class AltCorrBlock: def __init__(self, fmaps, num_levels=4, radius=3): self.num_levels = num_levels self.radius = radius B, N, C, H, W = fmaps.shape fmaps = fmaps.view(B*N, C, H, W) / 4.0 self.pyramid = [] for i in range(self.num_levels): sz = (B, N, H//2**i, W//2**i, C) fmap_lvl = fmaps.permute(0, 2, 3, 1).contiguous() self.pyramid.append(fmap_lvl.view(*sz)) fmaps = F.avg_pool2d(fmaps, 2, stride=2) def corr_fn(self, coords, ii, jj): B, N, H, W, S, _ = coords.shape coords = coords.permute(0, 1, 4, 2, 3, 5) corr_list = [] for i in range(self.num_levels): r = self.radius fmap1_i = self.pyramid[0][:, ii] fmap2_i = self.pyramid[i][:, jj] coords_i = (coords / 2**i).reshape(B*N, S, H, W, 2).contiguous() fmap1_i = fmap1_i.reshape((B*N,) + fmap1_i.shape[2:]) fmap2_i = fmap2_i.reshape((B*N,) + fmap2_i.shape[2:]) corr = CorrLayer.apply(fmap1_i.float(), fmap2_i.float(), coords_i, self.radius) corr = corr.view(B, N, S, -1, H, W).permute(0, 1, 3, 4, 5, 2) corr_list.append(corr) corr = torch.cat(corr_list, dim=2) return corr def __call__(self, coords, ii, jj): squeeze_output = False if len(coords.shape) == 5: coords = coords.unsqueeze(dim=-2) squeeze_output = True corr = self.corr_fn(coords, ii, jj) if squeeze_output: corr = corr.squeeze(dim=-1) return corr.contiguous() ================================================ FILE: dbaf/modules/extractor.py ================================================ import torch import torch.nn as nn import torch.nn.functional as F class ResidualBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(ResidualBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1) self.relu = nn.ReLU(inplace=True) num_groups = planes // 8 if norm_fn == 'group': self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) if not stride == 1: self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) elif norm_fn == 'batch': self.norm1 = nn.BatchNorm2d(planes) self.norm2 = nn.BatchNorm2d(planes) if not stride == 1: self.norm3 = nn.BatchNorm2d(planes) elif norm_fn == 'instance': self.norm1 = nn.InstanceNorm2d(planes) self.norm2 = nn.InstanceNorm2d(planes) if not stride == 1: self.norm3 = nn.InstanceNorm2d(planes) elif norm_fn == 'none': self.norm1 = nn.Sequential() self.norm2 = nn.Sequential() if not stride == 1: self.norm3 = nn.Sequential() if stride == 1: self.downsample = None else: self.downsample = nn.Sequential( nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm3) def forward(self, x): y = x y = self.relu(self.norm1(self.conv1(y))) y = self.relu(self.norm2(self.conv2(y))) if self.downsample is not None: x = self.downsample(x) return self.relu(x+y) class BottleneckBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(BottleneckBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes//4, kernel_size=1, padding=0) self.conv2 = nn.Conv2d(planes//4, planes//4, kernel_size=3, padding=1, stride=stride) self.conv3 = nn.Conv2d(planes//4, planes, kernel_size=1, padding=0) self.relu = nn.ReLU(inplace=True) num_groups = planes // 8 if norm_fn == 'group': self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes//4) self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes//4) self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) if not stride == 1: self.norm4 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) elif norm_fn == 'batch': self.norm1 = nn.BatchNorm2d(planes//4) self.norm2 = nn.BatchNorm2d(planes//4) self.norm3 = nn.BatchNorm2d(planes) if not stride == 1: self.norm4 = nn.BatchNorm2d(planes) elif norm_fn == 'instance': self.norm1 = nn.InstanceNorm2d(planes//4) self.norm2 = nn.InstanceNorm2d(planes//4) self.norm3 = nn.InstanceNorm2d(planes) if not stride == 1: self.norm4 = nn.InstanceNorm2d(planes) elif norm_fn == 'none': self.norm1 = nn.Sequential() self.norm2 = nn.Sequential() self.norm3 = nn.Sequential() if not stride == 1: self.norm4 = nn.Sequential() if stride == 1: self.downsample = None else: self.downsample = nn.Sequential( nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm4) def forward(self, x): y = x y = self.relu(self.norm1(self.conv1(y))) y = self.relu(self.norm2(self.conv2(y))) y = self.relu(self.norm3(self.conv3(y))) if self.downsample is not None: x = self.downsample(x) return self.relu(x+y) DIM=32 class BasicEncoder(nn.Module): def __init__(self, output_dim=128, norm_fn='batch', dropout=0.0, multidim=False): super(BasicEncoder, self).__init__() self.norm_fn = norm_fn self.multidim = multidim if self.norm_fn == 'group': self.norm1 = nn.GroupNorm(num_groups=8, num_channels=DIM) elif self.norm_fn == 'batch': self.norm1 = nn.BatchNorm2d(DIM) elif self.norm_fn == 'instance': self.norm1 = nn.InstanceNorm2d(DIM) elif self.norm_fn == 'none': self.norm1 = nn.Sequential() self.conv1 = nn.Conv2d(3, DIM, kernel_size=7, stride=2, padding=3) self.relu1 = nn.ReLU(inplace=True) self.in_planes = DIM self.layer1 = self._make_layer(DIM, stride=1) self.layer2 = self._make_layer(2*DIM, stride=2) self.layer3 = self._make_layer(4*DIM, stride=2) # output convolution self.conv2 = nn.Conv2d(4*DIM, output_dim, kernel_size=1) if self.multidim: self.layer4 = self._make_layer(256, stride=2) self.layer5 = self._make_layer(512, stride=2) self.in_planes = 256 self.layer6 = self._make_layer(256, stride=1) self.in_planes = 128 self.layer7 = self._make_layer(128, stride=1) self.up1 = nn.Conv2d(512, 256, 1) self.up2 = nn.Conv2d(256, 128, 1) self.conv3 = nn.Conv2d(128, output_dim, kernel_size=1) if dropout > 0: self.dropout = nn.Dropout2d(p=dropout) else: self.dropout = None for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)): if m.weight is not None: nn.init.constant_(m.weight, 1) if m.bias is not None: nn.init.constant_(m.bias, 0) def _make_layer(self, dim, stride=1): layer1 = ResidualBlock(self.in_planes, dim, self.norm_fn, stride=stride) layer2 = ResidualBlock(dim, dim, self.norm_fn, stride=1) layers = (layer1, layer2) self.in_planes = dim return nn.Sequential(*layers) def forward(self, x): b, n, c1, h1, w1 = x.shape x = x.view(b*n, c1, h1, w1) x = self.conv1(x) x = self.norm1(x) x = self.relu1(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.conv2(x) _, c2, h2, w2 = x.shape return x.view(b, n, c2, h2, w2) ================================================ FILE: dbaf/modules/gru.py ================================================ import torch import torch.nn as nn class ConvGRU(nn.Module): def __init__(self, h_planes=128, i_planes=128): super(ConvGRU, self).__init__() self.do_checkpoint = False self.convz = nn.Conv2d(h_planes+i_planes, h_planes, 3, padding=1) self.convr = nn.Conv2d(h_planes+i_planes, h_planes, 3, padding=1) self.convq = nn.Conv2d(h_planes+i_planes, h_planes, 3, padding=1) self.w = nn.Conv2d(h_planes, h_planes, 1, padding=0) self.convz_glo = nn.Conv2d(h_planes, h_planes, 1, padding=0) self.convr_glo = nn.Conv2d(h_planes, h_planes, 1, padding=0) self.convq_glo = nn.Conv2d(h_planes, h_planes, 1, padding=0) def forward(self, net, *inputs): inp = torch.cat(inputs, dim=1) net_inp = torch.cat([net, inp], dim=1) #[1,128+128+128+64,H//8,W//8] b, c, h, w = net.shape glo = torch.sigmoid(self.w(net)) * net glo = glo.view(b, c, h*w).mean(-1).view(b, c, 1, 1) # global context z = torch.sigmoid(self.convz(net_inp) + self.convz_glo(glo)) r = torch.sigmoid(self.convr(net_inp) + self.convr_glo(glo)) q = torch.tanh(self.convq(torch.cat([r*net, inp], dim=1)) + self.convq_glo(glo)) net = (1-z) * net + z * q return net ================================================ FILE: dbaf/motion_filter.py ================================================ import cv2 import torch import lietorch from collections import OrderedDict from droid_net import DroidNet import geom.projective_ops as pops from modules.corr import CorrBlock import numpy as np class MotionFilter: """ This class is used to filter incoming frames and extract features """ def __init__(self, net, video, thresh=2.5, device="cuda:0"): # split net modules self.cnet = net.cnet self.fnet = net.fnet self.update = net.update self.video = video self.thresh = thresh self.device = device self.count = 0 # mean, std for image normalization self.MEAN = torch.as_tensor([0.485, 0.456, 0.406], device=self.device)[:, None, None] self.STDV = torch.as_tensor([0.229, 0.224, 0.225], device=self.device)[:, None, None] @torch.cuda.amp.autocast(enabled=True) def __context_encoder(self, image): """ context features """ net, inp = self.cnet(image).split([128,128], dim=2) return net.tanh().squeeze(0), inp.relu().squeeze(0) @torch.cuda.amp.autocast(enabled=True) def context_encoder(self, image): """ context features """ net, inp = self.cnet(image).split([128,128], dim=2) return net.tanh().squeeze(0), inp.relu().squeeze(0) @torch.cuda.amp.autocast(enabled=True) def __feature_encoder(self, image): """ features for correlation volume """ return self.fnet(image).squeeze(0) @torch.cuda.amp.autocast(enabled=True) def feature_encoder(self, image): """ features for correlation volume """ return self.fnet(image).squeeze(0) @torch.cuda.amp.autocast(enabled=True) @torch.no_grad() def track(self, tstamp, image, depth=None, intrinsics=None): """ main update operation - run on every frame in video """ Id = lietorch.SE3.Identity(1,).data.squeeze() ht = image.shape[-2] // 8 wd = image.shape[-1] // 8 # normalize images inputs = image[None, :, [2,1,0]].to(self.device) / 255.0 inputs = inputs.sub_(self.MEAN).div_(self.STDV) # extract features gmap = self.__feature_encoder(inputs) #当前帧的特征, fnet ### always add first frame to the depth video ### if self.video.counter.value == 0: net, inp = self.__context_encoder(inputs[:,[0]]) self.net, self.inp, self.fmap = net, inp, gmap # [1,128,H//8,W//8], [1,128,H//8,W//8], [1,128,H//8,W//8] self.video.append(tstamp, image[0], Id, 1.0, depth, intrinsics / 8.0, gmap, net[0,0], inp[0,0]) ### only add new frame if there is enough motion ### else: # index correlation volume coords0 = pops.coords_grid(ht, wd, device=self.device)[None,None] corr = CorrBlock(self.fmap[None,[0]], gmap[None,[0]])(coords0) #关键帧和当前帧之间的相关运算 [None,[0]]即保留第一行之后进行unsqueeze(0), # approximate flow magnitude using 1 update iteration _, delta, weight = self.update(self.net[None], self.inp[None], corr) # check motion magnitue / add new frame to video if delta.norm(dim=-1).mean().item() > self.thresh: self.count = 0 net, inp = self.__context_encoder(inputs[:,[0]]) self.net, self.inp, self.fmap = net, inp, gmap self.video.append(tstamp, image[0], None, None, depth, intrinsics / 8.0, gmap, net[0], inp[0]) else: self.count += 1 ================================================ FILE: dbaf/multi_sensor.py ================================================ import numpy as np import gtsam import math GRAVITY = 9.807 class MultiSensorState: def __init__(self): self.cur_t = 0.0 """ IMU-centered states """ self.timestamps = [] # timestamps (len == N) self.wTbs = [] # poses (len == N) self.vs = [] # vels (len == N) self.bs = [] # biases (len == N) self.preintegrations = [] # preintegrations (len == N) self.preintegrations_meas = [] # raw IMU data (len == N) self.preintegration_temp = None # used for high-frequency prediction self.pose_temp = None # used for high-frequency prediction self.gnss_valid = [] # GNSS flags (len == N) self.gnss_position = [] # GNSS pos (len == N) self.odo_valid = [] # Odo flags (len == N) self.odo_vel = [] # Odo vel (len == N) self.marg_factor = None self.set_imu_params() def set_imu_params(self, noise = None): # default accel_noise_sigma = 0.0 gyro_noise_sigma = 0.0 accel_bias_rw_sigma = 0.0 gyro_bias_rw_sigma = 0.0 if noise != None: accel_noise_sigma = noise[0] gyro_noise_sigma = noise[1] accel_bias_rw_sigma = noise[2] gyro_bias_rw_sigma = noise[3] measured_acc_cov = np.eye(3,3) * math.pow(accel_noise_sigma,2) measured_omega_cov = np.eye(3,3) * math.pow(gyro_noise_sigma,2) integration_error_cov = np.eye(3,3) * 0e-8 bias_acc_cov = np.eye(3,3) * math.pow(accel_bias_rw_sigma,2) bias_omega_cov = np.eye(3,3) * math.pow(gyro_bias_rw_sigma,2) bias_acc_omega_init = np.eye(6,6) * 0e-5 params = gtsam.PreintegrationCombinedParams.MakeSharedU(GRAVITY) params.setAccelerometerCovariance(measured_acc_cov) params.setIntegrationCovariance(integration_error_cov) params.setGyroscopeCovariance(measured_omega_cov) params.setBiasAccCovariance(bias_acc_cov) params.setBiasOmegaCovariance(bias_omega_cov) params.setBiasAccOmegaInit(bias_acc_omega_init) self.params = params params_loose = gtsam.PreintegrationCombinedParams.MakeSharedU(GRAVITY) params_loose.setAccelerometerCovariance(measured_acc_cov* 100) params_loose.setIntegrationCovariance(integration_error_cov) params_loose.setGyroscopeCovariance(measured_omega_cov * 100) params_loose.setBiasAccCovariance(bias_acc_cov) params_loose.setBiasOmegaCovariance(bias_omega_cov) params_loose.setBiasAccOmegaInit(bias_acc_omega_init) self.params_loose = params_loose def init_first_state(self,t,pos,R,vel): self.timestamps.append(t) self.wTbs.append(gtsam.Pose3(gtsam.Rot3(R), gtsam.Point3(pos))) self.vs.append(vel) self.bs.append(gtsam.imuBias.ConstantBias(np.array([.0,.0,.0]),np.array([.0,.0,.0]))) self.preintegrations.append(gtsam.PreintegratedCombinedMeasurements(self.params,self.bs[-1])) self.preintegrations_meas.append([]) self.preintegration_temp = gtsam.PreintegratedCombinedMeasurements(self.params,self.bs[-1]) self.gnss_valid.append(False) self.gnss_position.append(np.array([.0,.0,.0])) self.odo_valid.append(False) self.odo_vel.append(np.array([.0,.0,.0])) self.cur_t = t def append_imu(self, t, measuredAcc, measuredOmega): if t - self.cur_t > 0: if t-self.cur_t > 0.025: # IMU gap found, loose the IMU factor new_preintegration = gtsam.PreintegratedCombinedMeasurements(self.params_loose,self.bs[-1]) for iii in range(len(self.preintegrations_meas[-1])): dd = self.preintegrations_meas[-1][iii] if dd[2] > 0: new_preintegration.integrateMeasurement(dd[0],dd[1],dd[2]) self.preintegrations[-1] = new_preintegration self.preintegrations[-1].integrateMeasurement(\ measuredAcc, measuredOmega, t - self.cur_t) if t - self.cur_t < 0: raise Exception("may not happen") self.preintegrations_meas[-1].append([measuredAcc, measuredOmega, t - self.cur_t, t]) # print('append_imu: ',measuredAcc,measuredOmega,t - self.cur_t,t) self.last_measuredAcc = measuredAcc self.last_measuredOmega = measuredOmega self.cur_t = t def append_imu_temp(self, t, measuredAcc, measuredOmega, predict_pose = False): if t - self.cur_t > 0: self.preintegration_temp.integrateMeasurement(\ measuredAcc, measuredOmega, t - self.cur_t) if predict_pose: prev_state = gtsam.gtsam.NavState(self.wTbs[-1],self.vs[-1]) prev_bias = self.bs[-1] self.pose_temp = self.preintegration_temp.predict(prev_state, prev_bias) def append_img(self, t): self.cur_t = t prev_state = gtsam.gtsam.NavState(self.wTbs[-1],self.vs[-1]) prev_bias = self.bs[-1] prop_state = self.preintegrations[-1].predict(prev_state, prev_bias) if self.preintegrations[-1].deltaTij()>1.0: prop_state = gtsam.gtsam.NavState(self.wTbs[-1],self.vs[-1]) self.timestamps.append(t) self.wTbs.append(prop_state.pose()) self.vs.append(prop_state.velocity()) self.bs.append(prev_bias) self.gnss_valid.append(False) self.gnss_position.append(np.array([.0,.0,.0])) self.odo_valid.append(False) self.odo_vel.append(np.array([.0,.0,.0])) self.preintegrations.append(\ gtsam.PreintegratedCombinedMeasurements(self.params,self.bs[-1])) self.preintegrations_meas.append([]) self.preintegration_temp = gtsam.PreintegratedCombinedMeasurements(self.params,self.bs[-1]) # ugly implementation # this should be called after append_img() def append_gnss(self,t,pos): if math.fabs(self.cur_t - t) > 0.01: print('Skip GNSS data due to unsynchronization!!') else: self.gnss_valid[-1] = True self.gnss_position[-1] = pos def append_odo(self,t,vel): if math.fabs(self.cur_t - t) > 0.01: print('Skip ODO data due to unsynchronization!!') else: self.odo_valid[-1] = True self.odo_vel[-1] = vel def predict(self): prev_state = gtsam.gtsam.NavState(self.wTbs[-1],self.vs[-1]) prev_bias = self.bs[-1] self.preintegrations[-1].predict(prev_state,prev_bias) ================================================ FILE: demo_vio_kitti360.py ================================================ import sys sys.path.append('dbaf') sys.path.append('dbaf/geoFunc') from tqdm import tqdm import numpy as np import torch import cv2 import os import argparse from dbaf import DBAFusion import h5py import pickle import re import math import gtsam import quaternion def show_image(image): image = image.permute(1, 2, 0).cpu().numpy() cv2.imshow('image', image / 255.0) cv2.waitKey(1) def image_stream(imagedir, imagestamp, enable_h5, h5path, calib, stride): """ image generator """ calib = np.loadtxt(calib, delimiter=" ") fx, fy, cx, cy = calib[:4] K = np.eye(3) K[0,0] = fx K[0,2] = cx K[1,1] = fy K[1,2] = cy if not enable_h5: image_list = sorted(os.listdir(imagedir))[::stride] image_stamps = np.loadtxt(imagestamp,str) image_dict = dict(zip(image_stamps[:,1],image_stamps[:,0])) for t, imfile in enumerate(image_list): image = cv2.imread(os.path.join(imagedir, imfile)) if len(calib) > 4: image = cv2.undistort(image, K, calib[4:]) tt = float(image_dict[imfile]) h0, w0, _ = image.shape h1 = int(h0 * np.sqrt((384 * 512) / (h0 * w0))) w1 = int(w0 * np.sqrt((384 * 512) / (h0 * w0))) image = cv2.resize(image, (w1, h1)) image = image[:h1-h1%8, :w1-w1%8] image = torch.as_tensor(image).permute(2, 0, 1) intrinsics = torch.as_tensor([fx, fy, cx, cy]) intrinsics[0::2] *= (w1 / w0) intrinsics[1::2] *= (h1 / h0) yield tt, image[None], intrinsics else: ccount = 0 h5_f = h5py.File(h5path,'r') all_keys = sorted(list(h5_f.keys())) for key in all_keys: ccount += 1 yield pickle.loads(np.array(h5_f[key])) if __name__ == '__main__': print(torch.cuda.device_count()) print(torch.cuda.is_available()) print(torch.cuda.current_device()) parser = argparse.ArgumentParser() parser.add_argument("--imagedir", type=str, help="path to image directory") parser.add_argument("--imagestamp", type=str, help="") parser.add_argument("--imupath", type=str, help="") parser.add_argument("--gtpath", type=str, help="") parser.add_argument("--enable_h5", action="store_true", help="") parser.add_argument("--h5path", type=str, help="") parser.add_argument("--resultpath", type=str, default="result.txt", help="") parser.add_argument("--calib", type=str, help="path to calibration file") parser.add_argument("--t0", default=0, type=int, help="starting frame") parser.add_argument("--stride", default=3, type=int, help="frame stride") parser.add_argument("--weights", default="droid.pth") parser.add_argument("--buffer", type=int, default=80) parser.add_argument("--image_size", default=[240, 320]) parser.add_argument("--max_factors", type=int, default=48, help="maximum active edges (which determines the GPU memory usage)") parser.add_argument("--beta", type=float, default=0.3, help="weight for translation / rotation components of flow") parser.add_argument("--filter_thresh", type=float, default=2.4, help="how much motion before considering new keyframe") parser.add_argument("--warmup", type=int, default=8, help="number of warmup frames") parser.add_argument("--keyframe_thresh", type=float, default=4.0, help="threshold to create a new keyframe") parser.add_argument("--frontend_thresh", type=float, default=16.0, help="add edges between frames whithin this distance") parser.add_argument("--frontend_window", type=int, default=25, help="frontend optimization window") parser.add_argument("--active_window", type=int, default=8, help="maximum frames involved in DBA") parser.add_argument("--inac_range", type=int, default=3, help="maximum inactive frames (whose flow wouldn't be updated) involved in DBA") parser.add_argument("--frontend_radius", type=int, default=2, help="force edges between frames within radius") parser.add_argument("--frontend_nms", type=int, default=1, help="non-maximal supression of edges") parser.add_argument("--backend_thresh", type=float, default=22.0) parser.add_argument("--backend_radius", type=int, default=2) parser.add_argument("--backend_nms", type=int, default=3) parser.add_argument("--upsample", action="store_true") parser.add_argument("--visual_only", type=int,default=0, help="wheter to disbale the IMU") parser.add_argument("--far_threshold", type=float, default=0.02, help="far pixels would be downweighted (unit: m^-1)") parser.add_argument("--translation_threshold", type=float, default=0.2, help="avoid the insertion of too close keyframes (unit: m)") parser.add_argument("--mask_threshold", type=float, default=-1, help="downweight too close edges (unit: m)") parser.add_argument("--skip_edge", type = str, default ="[]", help="whether to add 'skip' edges in the graph (for example, [-4,-5,-6] relative to the oldest active frame)") parser.add_argument("--save_pkl", action="store_true") parser.add_argument("--pklpath", default="result.pkl", help="path to saved reconstruction") parser.add_argument("--show_plot", action="store_true", help="plot the image/trajectory during running") args = parser.parse_args() args.skip_edge = eval(args.skip_edge) args.stereo = False dbaf = None torch.multiprocessing.set_start_method('spawn') """ Load reference trajectory (for visualization) """ all_gt ={} try: fp = open(args.gtpath,'rt') while True: line = fp.readline().strip() if line == '':break if line[0] == '#' : continue line = re.sub('\s\s+',' ',line) elem = line.split(' ') sod = float(elem[0]) if sod not in all_gt.keys(): all_gt[sod] ={} R = quaternion.as_rotation_matrix(quaternion.from_float_array([float(elem[7]),\ float(elem[4]),\ float(elem[5]),\ float(elem[6])])) TTT = np.eye(4,4) TTT[0:3,0:3] = R TTT[0:3,3] = np.array([ float(elem[1]), float(elem[2]), float(elem[3])]) all_gt[sod]['T'] = TTT all_gt_keys =sorted(all_gt.keys()) fp.close() except: pass """ Load IMU data """ all_imu = np.loadtxt(args.imupath) all_odo = [] all_gnss = [] tstamps = [] """ Load images """ try: for (t, image, intrinsics) in tqdm(image_stream(args.imagedir, args.imagestamp, args.enable_h5,\ args.h5path, args.calib, args.stride)): if args.show_plot: show_image(image[0]) if dbaf is None: args.image_size = [image.shape[2], image.shape[3]] dbaf = DBAFusion(args) all_imu[:,0] -= 0.04 # IMU-camera time offset dbaf.frontend.all_imu = all_imu dbaf.frontend.all_gnss = all_gnss dbaf.frontend.all_odo = all_odo dbaf.frontend.all_stamp = np.loadtxt(args.imagestamp,str) dbaf.frontend.all_stamp = dbaf.frontend.all_stamp[:,0].astype(np.float64)[None].transpose(1,0) if len(all_gt) > 0: dbaf.frontend.all_gt = all_gt dbaf.frontend.all_gt_keys = all_gt_keys # IMU-Camera Extrinsics dbaf.video.Ti1c = np.array( [0.99944133,-0.00228419,-0.03334389,-0.03734697, 0.03268308,-0.14183394,0.98935078,1.75837780, -0.00698916,-0.98988784,-0.14168005,0.59911765, 0.00000000,0.00000000,0.00000000,1.00000000]).reshape([4,4]) dbaf.video.Tbc = gtsam.Pose3(dbaf.video.Ti1c) # IMU parameters dbaf.video.state.set_imu_params([ 0.0003924 * 25,0.000205689024915 * 25, 0.004905 * 10, 0.000001454441043 * 500]) dbaf.video.init_pose_sigma = np.array([1.0, 1.0, 0.0001, 1.0, 1.0, 1.0]) dbaf.video.init_bias_sigma = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) dbaf.frontend.translation_threshold = args.translation_threshold dbaf.frontend.graph.mask_threshold = args.mask_threshold dbaf.track(t, image, intrinsics=intrinsics) dbaf.save_vis_easy() except Exception as err: print(err) dbaf.save_vis_easy() dbaf.terminate() ================================================ FILE: demo_vio_subt.py ================================================ import sys sys.path.append('dbaf') from tqdm import tqdm import numpy as np import torch import cv2 import os import argparse from dbaf import DBAFusion import h5py import pickle import re import math import quaternion import gtsam def show_image(image): image = image.permute(1, 2, 0).cpu().numpy() cv2.imshow('image', image / 255.0) cv2.waitKey(1) def image_stream(imagedir, imagestamp, enable_h5, h5path, calib, stride): """ image generator """ calib = np.loadtxt(calib, delimiter=" ") fx, fy, cx, cy = calib[:4] K = np.eye(3) K[0,0] = fx K[0,2] = cx K[1,1] = fy K[1,2] = cy Kn = np.eye(3) Kn[0,0] = fx*0.35 Kn[0,2] = cx Kn[1,1] = fy*0.35 Kn[1,2] = cy D = calib[5:] xi = np.array([calib[4]]) if not enable_h5: image_list = [f for f in os.listdir(imagedir) if f.endswith('.png')] image_list = sorted(image_list,key = lambda x: int(x.split('.')[0]))[2000::stride] image_stamps = np.loadtxt(imagestamp,str,delimiter=',')[2000::stride] for ii in range(len(image_list)): image = cv2.imread(os.path.join(imagedir, image_list[ii])) if len(calib) > 4: m1, m2 = cv2.omnidir.initUndistortRectifyMap(K,D,xi,np.eye(3),Kn,(image.shape[1],image.shape[0]),cv2.CV_32FC1, cv2.omnidir.RECTIFY_PERSPECTIVE) image = cv2.remap(image, m1, m2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT) tt = float(image_stamps[ii]) /1e9 h0, w0, _ = image.shape h1 = int(h0 * np.sqrt((384 * 512) / (h0 * w0))) w1 = int(w0 * np.sqrt((384 * 512) / (h0 * w0))) image = cv2.resize(image, (w1, h1)) image = image[:h1-h1%8, :w1-w1%8] image = torch.as_tensor(image).permute(2, 0, 1) intrinsics = torch.as_tensor([fx*0.35, fy*0.35, cx, cy ]) intrinsics[0::2] *= (w1 / w0) intrinsics[1::2] *= (h1 / h0) yield tt, image[None], intrinsics else: ccount = 0 h5_f = h5py.File(h5path,'r') all_keys = sorted(list(h5_f.keys())) for key in all_keys: ccount += 1 yield pickle.loads(np.array(h5_f[key])) if __name__ == '__main__': print(torch.cuda.device_count()) print(torch.cuda.is_available()) print(torch.cuda.current_device()) parser = argparse.ArgumentParser() parser.add_argument("--imagedir", type=str, help="path to image directory") parser.add_argument("--imagestamp", type=str, help="") parser.add_argument("--imupath", type=str, help="") parser.add_argument("--gtpath", type=str, help="") parser.add_argument("--enable_h5", action="store_true", help="") parser.add_argument("--h5path", type=str, help="") parser.add_argument("--resultpath", type=str, default="result.txt", help="") parser.add_argument("--calib", type=str, help="path to calibration file") parser.add_argument("--t0", default=0, type=int, help="starting frame") parser.add_argument("--stride", default=3, type=int, help="frame stride") parser.add_argument("--weights", default="droid.pth") parser.add_argument("--buffer", type=int, default=80) parser.add_argument("--image_size", default=[240, 320]) parser.add_argument("--max_factors", type=int, default=48, help="maximum active edges (which determines the GPU memory usage)") parser.add_argument("--beta", type=float, default=0.3, help="weight for translation / rotation components of flow") parser.add_argument("--filter_thresh", type=float, default=2.4, help="how much motion before considering new keyframe") parser.add_argument("--warmup", type=int, default=8, help="number of warmup frames") parser.add_argument("--keyframe_thresh", type=float, default=4.0, help="threshold to create a new keyframe") parser.add_argument("--frontend_thresh", type=float, default=16.0, help="add edges between frames whithin this distance") parser.add_argument("--frontend_window", type=int, default=25, help="frontend optimization window") parser.add_argument("--active_window", type=int, default=8, help="maximum frames involved in DBA") parser.add_argument("--inac_range", type=int, default=3, help="maximum inactive frames (whose flow wouldn't be updated) involved in DBA") parser.add_argument("--frontend_radius", type=int, default=2, help="force edges between frames within radius") parser.add_argument("--frontend_nms", type=int, default=1, help="non-maximal supression of edges") parser.add_argument("--backend_thresh", type=float, default=22.0) parser.add_argument("--backend_radius", type=int, default=2) parser.add_argument("--backend_nms", type=int, default=3) parser.add_argument("--upsample", action="store_true") parser.add_argument("--visual_only", type=int,default=0, help="wheter to disbale the IMU") parser.add_argument("--far_threshold", type=float, default=0.02, help="far pixels would be downweighted (unit: m^-1)") parser.add_argument("--translation_threshold", type=float, default=0.2, help="avoid the insertion of too close keyframes (unit: m)") parser.add_argument("--mask_threshold", type=float, default=-1, help="downweight too close edges (unit: m)") parser.add_argument("--skip_edge", type = str, default ="[]", help="whether to add 'skip' edges in the graph (for example, [-4,-5,-6] relative to the oldest active frame)") parser.add_argument("--save_pkl", action="store_true") parser.add_argument("--pklpath", default="result.pkl", help="path to saved reconstruction") parser.add_argument("--show_plot", action="store_true", help="plot the trajectory during running") args = parser.parse_args() args.skip_edge = eval(args.skip_edge) args.stereo = False dbaf = None torch.multiprocessing.set_start_method('spawn') """ Load reference trajectory (for visualization) """ all_gt ={} try: fp = open(args.gtpath,'rt') while True: line = fp.readline().strip() if line == '':break if line[0] == '#' : continue line = re.sub('\s\s+',' ',line) elem = line.split(',') sod = float(elem[0])/1e9 if sod not in all_gt.keys(): all_gt[sod] ={} R = quaternion.as_rotation_matrix(quaternion.from_float_array([float(elem[4]),\ float(elem[5]),\ float(elem[6]),\ float(elem[7])])) TTT = np.eye(4,4) TTT[0:3,0:3] = R TTT[0:3,3] = np.array([ float(elem[1]), float(elem[2]), float(elem[3])]) all_gt[sod]['T'] = TTT all_gt_keys =sorted(all_gt.keys()) fp.close() except: pass """ Load IMU data """ all_imu = np.loadtxt(args.imupath,delimiter=',',comments='#',skiprows=1) all_imu[:,0] /= 1e9 # all_imu[:,1:4] *= 180/math.pi all_imu_new = np.zeros_like(all_imu) all_imu_new[:,0] = all_imu[:,0] all_imu_new[:,1:4] = all_imu[:,5:8] * 180/math.pi all_imu_new[:,4:7] = all_imu[:,8:11] all_imu_new = all_imu_new[:,:7] tstamps = [] """ Load images """ for (t, image, intrinsics) in tqdm(image_stream(args.imagedir, args.imagestamp, args.enable_h5,\ args.h5path, args.calib, args.stride)): if args.show_plot: show_image(image[0]) if dbaf is None: args.image_size = [image.shape[2], image.shape[3]] dbaf = DBAFusion(args) dbaf.frontend.all_imu = all_imu_new dbaf.frontend.all_gnss = [] dbaf.frontend.all_odo = [] dbaf.frontend.all_stamp = np.loadtxt(args.imagestamp,str,delimiter=',') dbaf.frontend.all_stamp = dbaf.frontend.all_stamp.astype(np.float64)[2000::args.stride][None].transpose(1,0)/1e9 if len(all_gt) > 0: dbaf.frontend.all_gt = all_gt dbaf.frontend.all_gt_keys = all_gt_keys # IMU-Camera Extrinsics dbaf.video.Ti1c = np.array( [-0.04279531, -0.00237969, 0.99908103, 0.19499356, -0.99880330, -0.02359508, -0.04283961, 0.04340662, 0.02367534, -0.99971877, -0.00136708, -0.01782382, 0.00000000, 0.00000000, 0.00000000, 1.00000000]).reshape([4,4]) dbaf.video.Tbc = gtsam.Pose3(dbaf.video.Ti1c) # IMU parameters dbaf.video.state.set_imu_params((np.array([ 0.0003924 * 25,0.000205689024915 * 25, 0.004905 * 10, 0.000001454441043 * 500])*1.0).tolist()) dbaf.video.init_pose_sigma = np.array([1, 1, 0.0001, 0.0001,0.0001,0.0001]) dbaf.video.init_bias_sigma = np.array([1.0,1.0,1.0,1.0,1.0,1.0]) dbaf.frontend.translation_threshold = args.translation_threshold dbaf.frontend.graph.mask_threshold = args.mask_threshold dbaf.track(t, image, intrinsics=intrinsics) if args.save_pkl: dbaf.save_vis_easy() dbaf.terminate() ================================================ FILE: demo_vio_tumvi.py ================================================ import sys sys.path.append('dbaf') from tqdm import tqdm import numpy as np import torch import cv2 import os import argparse from dbaf import DBAFusion import h5py import pickle import re import math import quaternion import gtsam def show_image(image): image = image.permute(1, 2, 0).cpu().numpy() cv2.imshow('image', image / 255.0) cv2.waitKey(1) def image_stream(imagedir, imagestamp, enable_h5, h5path, calib, stride): """ image generator """ calib = np.loadtxt(calib, delimiter=" ") fx, fy, cx, cy = calib[:4] K = np.eye(3) K[0,0] = fx K[0,2] = cx K[1,1] = fy K[1,2] = cy Kn = np.eye(3) Kn[0,0] = fx Kn[0,2] = cx Kn[1,1] = fy Kn[1,2] = cy if not enable_h5: image_list = sorted(os.listdir(imagedir))[::stride] image_stamps = np.loadtxt(imagestamp,str,delimiter=',') image_dict = dict(zip(image_stamps[:,1],image_stamps[:,0])) for t, imfile in enumerate(image_list): image = cv2.imread(os.path.join(imagedir, imfile)) if len(calib) > 4: m1, m2 = cv2.fisheye.initUndistortRectifyMap(K,calib[4:],np.eye(3),Kn,(512,512),cv2.CV_32FC1) image = cv2.remap(image, m1, m2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT) tt = float(image_dict[imfile]) /1e9 h0, w0, _ = image.shape h1 = int(h0 * np.sqrt((384 * 512) / (h0 * w0))) w1 = int(w0 * np.sqrt((384 * 512) / (h0 * w0))) image = cv2.resize(image, (w1, h1)) image = image[:h1-h1%8, :w1-w1%8] image = torch.as_tensor(image).permute(2, 0, 1) intrinsics = torch.as_tensor([fx, fy, cx, cy ]) intrinsics[0::2] *= (w1 / w0) intrinsics[1::2] *= (h1 / h0) yield tt, image[None], intrinsics else: ccount = 0 h5_f = h5py.File(h5path,'r') all_keys = sorted(list(h5_f.keys())) for key in all_keys: ccount += 1 yield pickle.loads(np.array(h5_f[key])) if __name__ == '__main__': print(torch.cuda.device_count()) print(torch.cuda.is_available()) print(torch.cuda.current_device()) parser = argparse.ArgumentParser() parser.add_argument("--imagedir", type=str, help="path to image directory") parser.add_argument("--imagestamp", type=str, help="") parser.add_argument("--imupath", type=str, help="") parser.add_argument("--gtpath", type=str, help="") parser.add_argument("--enable_h5", action="store_true", help="") parser.add_argument("--h5path", type=str, help="") parser.add_argument("--resultpath", type=str, default="result.txt", help="") parser.add_argument("--calib", type=str, help="path to calibration file") parser.add_argument("--t0", default=0, type=int, help="starting frame") parser.add_argument("--stride", default=3, type=int, help="frame stride") parser.add_argument("--weights", default="droid.pth") parser.add_argument("--buffer", type=int, default=80) parser.add_argument("--image_size", default=[240, 320]) parser.add_argument("--max_factors", type=int, default=48, help="maximum active edges (which determines the GPU memory usage)") parser.add_argument("--beta", type=float, default=0.3, help="weight for translation / rotation components of flow") parser.add_argument("--filter_thresh", type=float, default=2.4, help="how much motion before considering new keyframe") parser.add_argument("--warmup", type=int, default=8, help="number of warmup frames") parser.add_argument("--keyframe_thresh", type=float, default=3.0, help="threshold to create a new keyframe") parser.add_argument("--frontend_thresh", type=float, default=16.0, help="add edges between frames whithin this distance") parser.add_argument("--frontend_window", type=int, default=25, help="frontend optimization window") parser.add_argument("--active_window", type=int, default=8, help="maximum frames involved in DBA") parser.add_argument("--inac_range", type=int, default=3, help="maximum inactive frames (whose flow wouldn't be updated) involved in DBA") parser.add_argument("--frontend_radius", type=int, default=2, help="force edges between frames within radius") parser.add_argument("--frontend_nms", type=int, default=1, help="non-maximal supression of edges") parser.add_argument("--backend_thresh", type=float, default=22.0) parser.add_argument("--backend_radius", type=int, default=2) parser.add_argument("--backend_nms", type=int, default=3) parser.add_argument("--upsample", action="store_true") parser.add_argument("--visual_only", type=int,default=0, help="wheter to disbale the IMU") parser.add_argument("--far_threshold", type=float, default=0.02, help="far pixels would be downweighted (unit: m^-1)") parser.add_argument("--translation_threshold", type=float, default=0.2, help="avoid the insertion of too close keyframes (unit: m)") parser.add_argument("--mask_threshold", type=float, default=-1, help="downweight too close edges (unit: m)") parser.add_argument("--skip_edge", type = str, default ="[]", help="whether to add 'skip' edges in the graph (for example, [-4,-5,-6] relative to the oldest active frame)") parser.add_argument("--save_pkl", action="store_true") parser.add_argument("--pklpath", default="result.pkl", help="path to saved reconstruction") parser.add_argument("--show_plot", action="store_true", help="plot the trajectory during running") args = parser.parse_args() args.skip_edge = eval(args.skip_edge) args.stereo = False dbaf = None torch.multiprocessing.set_start_method('spawn') """ Load reference trajectory (for visualization) """ all_gt ={} try: fp = open(args.gtpath,'rt') while True: line = fp.readline().strip() if line == '':break if line[0] == '#' : continue line = re.sub('\s\s+',' ',line) elem = line.split(',') sod = float(elem[0])/1e9 if sod not in all_gt.keys(): all_gt[sod] ={} R = quaternion.as_rotation_matrix(quaternion.from_float_array([float(elem[4]),\ float(elem[5]),\ float(elem[6]),\ float(elem[7])])) TTT = np.eye(4,4) TTT[0:3,0:3] = R TTT[0:3,3] = np.array([ float(elem[1]), float(elem[2]), float(elem[3])]) all_gt[sod]['T'] = TTT all_gt_keys =sorted(all_gt.keys()) fp.close() except: pass """ Load IMU data """ all_imu = np.loadtxt(args.imupath,delimiter=',') all_imu[:,0] /= 1e9 all_imu[:,1:4] *= 180/math.pi tstamps = [] """ Load images """ clahe = cv2.createCLAHE(2.0,tileGridSize=(8, 8)) for (t, image, intrinsics) in tqdm(image_stream(args.imagedir, args.imagestamp, args.enable_h5,\ args.h5path, args.calib, args.stride)): mm = clahe.apply(image[0][0].numpy()) image[0] = torch.tensor(mm[None].repeat(3,0)) if args.show_plot: show_image(image[0]) if dbaf is None: args.image_size = [image.shape[2], image.shape[3]] dbaf = DBAFusion(args) dbaf.frontend.all_imu = all_imu dbaf.frontend.all_gnss = [] dbaf.frontend.all_odo = [] dbaf.frontend.all_stamp = np.loadtxt(args.imagestamp,str,delimiter=',') dbaf.frontend.all_stamp = dbaf.frontend.all_stamp[:,0].astype(np.float64)[None].transpose(1,0)/1e9 if len(all_gt) > 0: dbaf.frontend.all_gt = all_gt dbaf.frontend.all_gt_keys = all_gt_keys # IMU-Camera Extrinsics dbaf.video.Ti1c = np.array( [-0.9995250378696743, 0.029615343885863205, -0.008522328211654736, 0.04727988224914392, 0.0075019185074052044, -0.03439736061393144, -0.9993800792498829, -0.047443232143367084, -0.02989013031643309, -0.998969345370175, 0.03415885127385616, -0.0681999605066297, 0.0, 0.0, 0.0, 1.0]).reshape([4,4]) dbaf.video.Ti1c = np.linalg.inv(dbaf.video.Ti1c) dbaf.video.Tbc = gtsam.Pose3(dbaf.video.Ti1c) # IMU parameters dbaf.video.state.set_imu_params((np.array([ 0.0003924 * 25,0.000205689024915 * 25, 0.004905 * 10, 0.000001454441043 * 5000])*1.0).tolist()) dbaf.video.init_pose_sigma = np.array([0.1, 0.1, 0.0001, 0.0001,0.0001,0.0001]) dbaf.video.init_bias_sigma = np.array([1.0,1.0,1.0, 1.0,1.0,1.0]) dbaf.frontend.translation_threshold = args.translation_threshold dbaf.frontend.graph.mask_threshold = args.mask_threshold dbaf.track(t, image, intrinsics=intrinsics) if args.save_pkl: dbaf.save_vis_easy() dbaf.terminate() ================================================ FILE: demo_vio_whu.py ================================================ import sys sys.path.append('dbaf') sys.path.append('dbaf/geoFunc') from tqdm import tqdm import numpy as np import torch import cv2 import os import argparse from dbaf import DBAFusion import h5py import pickle import re import math import gtsam import geoFunc.trans as trans def show_image(image): image = image.permute(1, 2, 0).cpu().numpy() cv2.imshow('image', image / 255.0) cv2.waitKey(1) def image_stream(imagedir, imagestamp, enable_h5, h5path, calib, stride): """ image generator """ calib = np.loadtxt(calib, delimiter=" ") fx, fy, cx, cy = calib[:4] K = np.eye(3) K[0,0] = fx K[0,2] = cx K[1,1] = fy K[1,2] = cy if not enable_h5: image_stamps = np.loadtxt(imagestamp,str,delimiter=',') image_dict = dict(zip(image_stamps[:,1],image_stamps[:,0])) image_list = list(image_dict) ccount = 0 for t, imfile in enumerate(image_list): tt = float(image_dict[imfile]) if int(tt*10)%2 == 1: continue ccount += 1 image = cv2.imread(os.path.join(imagedir, imfile)) if len(calib) > 4: image = cv2.undistort(image, K, calib[4:]) h0, w0, _ = image.shape h1 = int(h0 * np.sqrt((384 * 512) / (h0 * w0))) w1 = int(w0 * np.sqrt((384 * 512) / (h0 * w0))) image = cv2.resize(image, (w1, h1)) image = image[:h1-h1%8, :w1-w1%8] image = torch.as_tensor(image).permute(2, 0, 1) intrinsics = torch.as_tensor([fx, fy, cx, cy]) intrinsics[0::2] *= (w1 / w0) intrinsics[1::2] *= (h1 / h0) yield tt, image[None], intrinsics else: raise Exception() if __name__ == '__main__': print(torch.cuda.device_count()) print(torch.cuda.is_available()) print(torch.cuda.current_device()) parser = argparse.ArgumentParser() parser.add_argument("--imagedir", type=str, help="path to image directory") parser.add_argument("--imagestamp", type=str, help="") parser.add_argument("--imupath", type=str, help="") parser.add_argument("--gtpath", type=str, help="") parser.add_argument("--enable_h5", action="store_true", help="") parser.add_argument("--h5path", type=str, help="") parser.add_argument("--resultpath", type=str, help="") parser.add_argument("--calib", type=str, help="path to calibration file") parser.add_argument("--t0", default=0, type=int, help="starting frame") parser.add_argument("--stride", default=3, type=int, help="frame stride") parser.add_argument("--weights", default="droid.pth") parser.add_argument("--buffer", type=int, default=80) parser.add_argument("--image_size", default=[240, 320]) parser.add_argument("--max_factors", type=int, default=48, help="maximum active edges (which determines the GPU memory usage)") parser.add_argument("--beta", type=float, default=0.3, help="weight for translation / rotation components of flow") parser.add_argument("--filter_thresh", type=float, default=0.00, help="how much motion before considering new keyframe") parser.add_argument("--warmup", type=int, default=8, help="number of warmup frames") parser.add_argument("--vi_warmup", type=int, default=15, help="") parser.add_argument("--keyframe_thresh", type=float, default=3.0, help="threshold to create a new keyframe") parser.add_argument("--frontend_thresh", type=float, default=16.0, help="add edges between frames whithin this distance") parser.add_argument("--frontend_window", type=int, default=25, help="frontend optimization window") parser.add_argument("--active_window", type=int, default=8) parser.add_argument("--inac_range", type=int, default=3) parser.add_argument("--frontend_radius", type=int, default=2, help="force edges between frames within radius") parser.add_argument("--frontend_nms", type=int, default=1, help="non-maximal supression of edges") parser.add_argument("--backend_thresh", type=float, default=22.0) parser.add_argument("--backend_radius", type=int, default=2) parser.add_argument("--backend_nms", type=int, default=3) parser.add_argument("--upsample", action="store_true") parser.add_argument("--visual_only", type=int,default=0, help="wheter to disbale the IMU") parser.add_argument("--far_threshold", type=float, default=0.02, help="far pixels would be downweighted (unit: m^-1)") parser.add_argument("--translation_threshold", type=float, default=0.2, help="avoid the insertion of too close keyframes (unit: m)") parser.add_argument("--mask_threshold", type=float, default=-1, help="downweight too close edges (unit: m)") parser.add_argument("--skip_edge", type = str, default ="[]", help="whether to add 'skip' edges in the graph (for example, [-4,-5,-6] relative to the oldest active frame)") parser.add_argument("--save_pkl", action="store_true") parser.add_argument("--pklpath", default="result.pkl", help="path to saved reconstruction") parser.add_argument("--show_plot", action="store_true", help="plot the image/trajectory during running") parser.add_argument("--use_gnss", action="store_true") parser.add_argument("--gnsspath", type=str, help="") parser.add_argument("--use_odo", action="store_true") parser.add_argument("--odopath", type=str, help="") parser.add_argument("--use_zupt", action="store_true") args = parser.parse_args() args.skip_edge = eval(args.skip_edge) args.stereo = False dbaf = None all_gt ={} Ti0i1 =np.array([[ 9.99902524e-01, 1.39619889e-02, -7.31054713e-05, 1.00000000e-02], [-1.39621803e-02, 9.99888818e-01, -5.23545345e-03, -2.05000000e-01], [ 0.00000000e+00, 5.23596383e-03, 9.99986292e-01, -5.00000000e-02], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]]) Ten0 = None is_ref_set = False fp = open(args.gtpath,'rt') while True: line = fp.readline().strip() if line == '':break if line[0] == '#' :continue line = re.sub('\s\s+',' ',line) elem = line.split(' ') sod = float(elem[1]) if sod not in all_gt.keys(): all_gt[sod] ={} all_gt[sod]['X0'] = float(elem[2]) all_gt[sod]['Y0'] = float(elem[3]) all_gt[sod]['Z0'] = float(elem[4]) all_gt[sod]['VX0'] = float(elem[15]) all_gt[sod]['VY0'] = float(elem[16]) all_gt[sod]['VZ0'] = float(elem[17]) all_gt[sod]['ATTX0']= float(elem[25]) all_gt[sod]['ATTY0']= float(elem[26]) all_gt[sod]['ATTZ0']= -float(elem[24]) Ren = trans.Cen([all_gt[sod]['X0'],all_gt[sod]['Y0'],all_gt[sod]['Z0']]) ani0 = [all_gt[sod]['ATTX0']/180*math.pi,\ all_gt[sod]['ATTY0']/180*math.pi,\ all_gt[sod]['ATTZ0']/180*math.pi] Rni0 = trans.att2m(ani0) Rei0 = np.matmul(Ren,Rni0) tei0 = np.array([all_gt[sod]['X0'],all_gt[sod]['Y0'],all_gt[sod]['Z0']]) Tei0 = np.eye(4,4) Tei0[0:3,0:3] = Rei0 Tei0[0:3,3] = tei0 if not is_ref_set: is_ref_set = True Ten0 = np.eye(4,4) Ten0[0:3,0:3] = trans.Cen(tei0) Ten0[0:3,3] = tei0 Tn0i0 = np.matmul(np.linalg.inv(Ten0),Tei0) Tn0i1 = np.matmul(Tn0i0,Ti0i1) all_gt[sod]['T'] = Tn0i1 all_gt_keys =sorted(all_gt.keys()) fp.close() all_imu = np.loadtxt(args.imupath,delimiter=' ') if args.use_gnss and os.path.isfile(args.gnsspath): fix_map = {b'Fixed':1.0,b'Float':0.0} all_gnss = np.genfromtxt(args.gnsspath,converters={16: lambda x: fix_map[x]}) else: all_gnss = [] if args.use_odo and os.path.isfile(args.odopath): all_odo = np.genfromtxt(args.odopath) all_odo = all_odo[np.fabs(all_odo[:,0] - np.round(all_odo[:,0]))<0.001] np.random.seed(12345) all_odo[:,1:] += np.random.randn(all_odo.shape[0],3)*0.05 else: all_odo = [] tstamps = [] # try: for (t, image, intrinsics) in tqdm(image_stream(args.imagedir, args.imagestamp, args.enable_h5,\ args.h5path, args.calib, args.stride)): if args.show_plot: show_image(image[0]) if dbaf is None: args.image_size = [image.shape[2], image.shape[3]] dbaf = DBAFusion(args) dbaf.frontend.all_imu = all_imu dbaf.frontend.all_stamp = np.loadtxt(args.imagestamp,str,delimiter=',') dbaf.frontend.all_gnss = all_gnss dbaf.frontend.all_odo = all_odo if len(all_gt) > 0: dbaf.frontend.all_gt = all_gt dbaf.frontend.all_gt_keys = all_gt_keys dbaf.video.Ti1c = np.array( [0.99988370,-0.00563944,-0.01418468,-0.15590000, 0.01424932,0.01159187,0.99983149,0.63466000, -0.00547407,-0.99991712,0.01167088,0.04605000, 0.00000000,0.00000000,0.00000000,1.00000000]).reshape([4,4]) dbaf.video.tbg = np.array([-0.0125, -0.26, 0.2091]) dbaf.video.Tbc = gtsam.Pose3(dbaf.video.Ti1c) dbaf.video.state.set_imu_params([ 0.0003924 * 25,0.000205689024915 * 25, 0.004905 * 10, 0.000001454441043 * 25]) if args.use_gnss: dbaf.video.init_pose_sigma = np.array([1.0, 1.0, 10.0,10.0,10.0,10.0]) else: dbaf.video.init_pose_sigma = np.array([[0.1, 0.1, 0.0001, 0.0001,0.0001,0.0001], [1.0, 1.0, 0.0001, 10.0, 10.0, 10.0]]) dbaf.video.init_bias_sigma = np.array([1.0,1.0,1.0, 0.1, 0.1, 0.1]) dbaf.frontend.translation_threshold = args.translation_threshold dbaf.frontend.graph.mask_threshold = args.mask_threshold dbaf.track(t, image, intrinsics=intrinsics) dbaf.save_vis_easy() dbaf.terminate() ================================================ FILE: evaluation_scripts/batch_tumvi.py ================================================ import subprocess for seq in ['magistrale1','magistrale2','magistrale3','magistrale4','magistrale5','magistrale6',\ 'outdoors1','outdoors2','outdoors3','outdoors4','outdoors5','outdoors6','outdoors7','outdoors8']: p = subprocess.Popen('python ./evaluation_scripts/evaluate_tumvi.py --batch --seq=%s | grep rmse' % seq, shell = True) p.wait() ================================================ FILE: evaluation_scripts/evaluate_kitti.py ================================================ import argparse import logging import typing import numpy as np import evo.common_ape_rpe as common from evo.core import lie_algebra, sync, metrics from evo.core.result import Result from evo.core.trajectory import PosePath3D, PoseTrajectory3D from evo.tools import file_interface, log from evo.tools.settings import SETTINGS import matplotlib.pyplot as plt import copy from scipy.spatial.transform import Rotation import bisect import math import time logger = logging.getLogger(__name__) SEP = "-" * 80 # separator line def ape(traj_ref: PosePath3D, traj_est: PosePath3D, pose_relation: metrics.PoseRelation, align: bool = False, correct_scale: bool = False, n_to_align: int = -1, align_origin: bool = False, ref_name: str = "reference", est_name: str = "estimate", change_unit: typing.Optional[metrics.Unit] = None) -> Result: if n_to_align >0 : print('>>>>> only use the starting segment') n_to_align = np.where((np.array(traj_ref.timestamps)[1:]-np.array(traj_ref.timestamps)[0:-1])>100)[0][0]-1 # Align the trajectories. only_scale = correct_scale and not align alignment_transformation = None if align or correct_scale: logger.debug(SEP) alignment_transformation = lie_algebra.sim3( *traj_est.align(traj_ref, correct_scale, only_scale, n=n_to_align)) elif align_origin: logger.debug(SEP) alignment_transformation = traj_est.align_origin(traj_ref) # Calculate APE. logger.debug(SEP) data = (traj_ref, traj_est) ape_metric = metrics.APE(pose_relation) ape_metric.process_data(data) if change_unit: ape_metric.change_unit(change_unit) title = str(ape_metric) if align and not correct_scale: title += "\n(with SE(3) Umeyama alignment)" elif align and correct_scale: title += "\n(with Sim(3) Umeyama alignment)" elif only_scale: title += "\n(scale corrected)" elif align_origin: title += "\n(with origin alignment)" else: title += "\n(not aligned)" if (align or correct_scale) and n_to_align != -1: title += " (aligned poses: {})".format(n_to_align) ape_result = ape_metric.get_result(ref_name, est_name) ape_result.info["title"] = title logger.debug(SEP) logger.info(ape_result.pretty_str()) ape_result.add_trajectory(ref_name, traj_ref) ape_result.add_trajectory(est_name, traj_est) if isinstance(traj_est, PoseTrajectory3D): seconds_from_start = np.array( [t - traj_est.timestamps[0] for t in traj_est.timestamps]) ape_result.add_np_array("seconds_from_start", seconds_from_start) ape_result.add_np_array("timestamps", traj_est.timestamps) ape_result.add_np_array("distances_from_start", traj_ref.distances) ape_result.add_np_array("distances", traj_est.distances) if alignment_transformation is not None: ape_result.add_np_array("alignment_transformation_sim3", alignment_transformation) return ape_result if __name__ == '__main__': color_list = [[0,0,1],[1,0.6,1],[1,0,0]] plt.figure('1',figsize=[6,6]) parser = argparse.ArgumentParser() parser.add_argument('--seq', type=str, help='seq',default='0010') args = parser.parse_args() args.subcommand = 'tum' seq = args.seq args.ref_file = '/home/zhouyuxuan/data/2013_05_28_drive_%s_sync/gt_local.txt' % seq args.pose_relation = 'trans_part' args.align = True args.correct_scale = False args.n_to_align = 1 args.align_origin = False args.plot_mode = 'xyz' args.plot_x_dimension = 'seconds' args.plot_colormap_min = None args.plot_colormap_max = None args.plot_colormap_max_percentile = None args.ros_map_yaml = None args.plot = True args.est_files = ['results/result_%s.txt' %seq] label_list = ['DBA-Fusion (M)'] args.save_plot = False args.serialize_plot = False for iii in range(len(args.est_files)): args.est_file = args.est_files[iii] if args.est_file.find('visual') != -1: args.correct_scale = True else: args.correct_scale = False traj_ref, traj_est, ref_name, est_name = common.load_trajectories(args) traj_ref_sel, traj_est_sel = sync.associate_trajectories( traj_ref, traj_est, 0.01,0.0, first_name=ref_name, snd_name=est_name) args.n_to_align = -1 pose_relation = common.get_pose_relation(args) result = ape(traj_ref=traj_ref_sel, traj_est=traj_est_sel, pose_relation=pose_relation, align=args.align, correct_scale=args.correct_scale, n_to_align=args.n_to_align, align_origin=args.align_origin, ref_name=ref_name, est_name=est_name) traj_est_sel = copy.deepcopy(result.trajectories[est_name]) T01 = result.np_arrays['alignment_transformation_sim3'] print(T01) result = ape(traj_ref=traj_ref_sel, traj_est=traj_est_sel, pose_relation=pose_relation, align=args.align, correct_scale=False, n_to_align=-1, align_origin=args.align_origin, ref_name=ref_name, est_name=est_name) print(result) traj_est.transform(T01) if iii == 0: x_series=[] y_series=[] z_series=[] for i in range(len(traj_ref.poses_se3)): TTT = traj_ref.poses_se3[i] x_series.append(TTT[0,3]) y_series.append(TTT[1,3]) z_series.append(TTT[2,3]) plt.plot(x_series,y_series,c=[0,0,0],linestyle = '--') x_series=[] y_series=[] z_series=[] for i in range(len(traj_est.poses_se3)): TTT = traj_est.poses_se3[i] x_series.append(TTT[0,3]) y_series.append(TTT[1,3]) z_series.append(TTT[2,3]) ppp = TTT[0:3,3] qqq = Rotation.from_matrix(TTT[:3, :3]/np.power(np.linalg.det(TTT[:3, :3]),1.0/3)).as_quat() plt.plot(x_series,y_series,c=color_list[iii],label = label_list[iii]) # t_series=[] # x_series=[] # y_series=[] # z_series=[] # for i in range(len(traj_ref_sel.timestamps)): # T0 = traj_ref_sel.poses_se3[i] # T1 = traj_est_sel.poses_se3[i] # T01 = np.matmul(np.linalg.inv(T0),T1) # att = Rotation.from_matrix(T01[0:3,0:3]).as_rotvec() # t_series.append(traj_ref_sel.timestamps[i]) # x_series.append(att[0]) # y_series.append(att[1]) # z_series.append(att[2]) # plt.figure() # plt.plot(t_series,x_series) # plt.plot(t_series,y_series) # plt.plot(t_series,z_series) # plt.show() print('Evaluating relative pose error ...') subtraj_length = [100,200,300,400,500,600,700,800] max_dist_difH=1 rel_trans_error_dist = [] rel_att_error_dist = [] for i in range(8): subsection_index=[] max_dist_diff=0.2*subtraj_length[i] traj_len = len(traj_ref_sel.timestamps) for j in range(traj_len-2): k = bisect.bisect(traj_ref_sel.distances,traj_ref_sel.distances[j]+subtraj_length[i]-max_dist_difH) if k > 0 and k < traj_len and math.fabs(traj_ref_sel.distances[k] - (traj_ref_sel.distances[j]+subtraj_length[i]))< max_dist_difH: subsection_index.append([j,k]) print("The trajectory at %dm have %d matching points... " %(subtraj_length[i],len(subsection_index))) rel_tran_errors = [] rel_att_errors = [] for ii in subsection_index: T_gt_1 =traj_ref_sel.poses_se3[ii[0]] T_gt_2 =traj_ref_sel.poses_se3[ii[1]] T_est_1 =traj_est_sel.poses_se3[ii[0]] T_est_2 =traj_est_sel.poses_se3[ii[1]] T_gt_12=np.matmul(np.linalg.inv(T_gt_1),T_gt_2) T_est_12=np.matmul(np.linalg.inv(T_est_1),T_est_2) T_error=np.matmul(np.linalg.inv(T_gt_12),T_est_12) rel_tran_error = np.linalg.norm(T_error[0:3,3]) rel_att_error = np.linalg.norm(Rotation.from_matrix(T_error[0:3,0:3]).as_rotvec()) rel_tran_errors.append(rel_tran_error/subtraj_length[i]*100) rel_att_errors.append(rel_att_error/subtraj_length[i]*100/math.pi*180) rel_trans_error_dist.append(np.mean(np.array(rel_tran_errors))) rel_att_error_dist.append(np.mean(np.array(rel_att_errors))) print('Relative Translation Error: %f%%' % np.mean(np.array(rel_trans_error_dist))) print('Relative Rotation Error: %f deg / 100 m' % np.mean(np.array(rel_att_error_dist))) plt.show() ================================================ FILE: evaluation_scripts/evaluate_tumvi.py ================================================ import argparse import logging import typing import numpy as np import evo.common_ape_rpe as common from evo.core import lie_algebra, sync, metrics from evo.core.result import Result from evo.core.trajectory import PosePath3D, PoseTrajectory3D from evo.tools import file_interface, log from evo.tools.settings import SETTINGS import matplotlib.pyplot as plt import matplotlib import copy import os matplotlib.rcParams['mathtext.fontset'] = 'custom' matplotlib.rcParams['mathtext.rm'] = 'Times New Roman' matplotlib.rcParams['mathtext.it'] = 'Times New Roman:italic' matplotlib.rcParams['mathtext.bf'] = 'Times New Roman:bold' matplotlib.rcParams['font.family'] = 'Arial' font0={'family':'Arial', 'style':'normal', 'weight':'bold', 'color':'black', 'size':6 } font1={'family':'Arial', 'style':'normal', 'weight':'bold', 'color':'black', 'size':8 } logger = logging.getLogger(__name__) SEP = "-" * 80 # separator line def ape(traj_ref: PosePath3D, traj_est: PosePath3D, pose_relation: metrics.PoseRelation, align: bool = False, correct_scale: bool = False, n_to_align: int = -1, align_origin: bool = False, ref_name: str = "reference", est_name: str = "estimate", change_unit: typing.Optional[metrics.Unit] = None) -> Result: if n_to_align >0 : print('>>>>> only use the starting segment') n_to_align = np.where((np.array(traj_ref.timestamps)[1:]-np.array(traj_ref.timestamps)[0:-1])>100)[0][0]-1 # Align the trajectories. only_scale = correct_scale and not align alignment_transformation = None if align or correct_scale: logger.debug(SEP) alignment_transformation = lie_algebra.sim3( *traj_est.align(traj_ref, correct_scale, only_scale, n=n_to_align)) elif align_origin: logger.debug(SEP) alignment_transformation = traj_est.align_origin(traj_ref) # Calculate APE. logger.debug(SEP) data = (traj_ref, traj_est) ape_metric = metrics.APE(pose_relation) ape_metric.process_data(data) if change_unit: ape_metric.change_unit(change_unit) title = str(ape_metric) if align and not correct_scale: title += "\n(with SE(3) Umeyama alignment)" elif align and correct_scale: title += "\n(with Sim(3) Umeyama alignment)" elif only_scale: title += "\n(scale corrected)" elif align_origin: title += "\n(with origin alignment)" else: title += "\n(not aligned)" if (align or correct_scale) and n_to_align != -1: title += " (aligned poses: {})".format(n_to_align) ape_result = ape_metric.get_result(ref_name, est_name) ape_result.info["title"] = title logger.debug(SEP) logger.info(ape_result.pretty_str()) ape_result.add_trajectory(ref_name, traj_ref) ape_result.add_trajectory(est_name, traj_est) if isinstance(traj_est, PoseTrajectory3D): seconds_from_start = np.array( [t - traj_est.timestamps[0] for t in traj_est.timestamps]) ape_result.add_np_array("seconds_from_start", seconds_from_start) ape_result.add_np_array("timestamps", traj_est.timestamps) ape_result.add_np_array("distances_from_start", traj_ref.distances) ape_result.add_np_array("distances", traj_est.distances) if alignment_transformation is not None: ape_result.add_np_array("alignment_transformation_sim3", alignment_transformation) return ape_result if __name__ == '__main__': color_list = [np.array([133,164,195])/255.0,[1,0.6,1],[1,0,0]] plt.figure('1',figsize=[6,6]) parser = argparse.ArgumentParser() parser.add_argument('--seq', type=str, help='seq', default='outdoors1') parser.add_argument('--batch', action="store_true") args = parser.parse_args() args.subcommand = 'tum' seq = args.seq args.ref_file = '/mnt/z/tum-vi/dataset-%s_512_16/dso/gt_imu.csv' % seq # Convert GT format dd = np.loadtxt(args.ref_file,delimiter=',',comments='#') dd_new = np.copy(dd) dd_new[:,0] /= 1e9 dd_new[:,4] = dd[:,7] dd_new[:,5] = dd[:,4] dd_new[:,6] = dd[:,5] dd_new[:,7] = dd[:,6] args.ref_file = os.path.join(os.path.dirname(args.ref_file),'gt_imu_temp.txt') np.savetxt(args.ref_file, dd_new,delimiter=' ') args.pose_relation = 'trans_part' args.align = True args.correct_scale = False args.n_to_align = 1 args.align_origin = False args.plot_mode = 'xyz' args.plot_x_dimension = 'seconds' args.plot_colormap_min = None args.plot_colormap_max = None args.plot_colormap_max_percentile = None args.ros_map_yaml = None args.plot = True args.est_files = ['results/result_%s.txt' % seq] label_list = ['DBA-Fusion (M)'] args.save_plot = False args.serialize_plot = False for iii in range(len(args.est_files)): args.est_file = args.est_files[iii] if args.est_file.find('visual') != -1: args.correct_scale = True else: args.correct_scale = False traj_ref, traj_est, ref_name, est_name = common.load_trajectories(args) traj_ref_sel, traj_est_sel = sync.associate_trajectories( traj_ref, traj_est, 0.01,0.0, first_name=ref_name, snd_name=est_name) # use the starting part for scale estimation args.n_to_align = np.where((np.array(traj_ref_sel.timestamps)[1:]-np.array(traj_ref_sel.timestamps)[0:-1])>100)[0][0]-1 pose_relation = common.get_pose_relation(args) result = ape(traj_ref=traj_ref_sel, traj_est=traj_est_sel, pose_relation=pose_relation, align=args.align, correct_scale=args.correct_scale, n_to_align=args.n_to_align, align_origin=args.align_origin, ref_name=ref_name, est_name=est_name) traj_est_sel = copy.deepcopy(result.trajectories[est_name]) T01 = result.np_arrays['alignment_transformation_sim3'] # metric-scale APE calculation result = ape(traj_ref=traj_ref_sel, traj_est=traj_est_sel, pose_relation=pose_relation, align=args.align, correct_scale=False, n_to_align=-1, align_origin=args.align_origin, ref_name=ref_name, est_name=est_name) print(result) if args.batch: quit() # visualization traj_est.transform(T01) if iii == 0: x_series=[] y_series=[] z_series=[] for i in range(len(traj_ref.poses_se3)): TTT = traj_ref.poses_se3[i] x_series.append(TTT[0,3]) y_series.append(TTT[1,3]) z_series.append(TTT[2,3]) plt.plot(x_series,y_series,c=[0,0,0],linestyle = '--',linewidth=0.5) x_series=[] y_series=[] z_series=[] for i in range(len(traj_est.poses_se3)): TTT = traj_est.poses_se3[i] x_series.append(TTT[0,3]) y_series.append(TTT[1,3]) z_series.append(TTT[2,3]) plt.plot(x_series,y_series,c=color_list[iii],label = label_list[iii],linewidth=0.5) ll = max(max(x_series)-min(x_series),max(y_series)-min(y_series)) plt.xlim([(max(x_series)+min(x_series))/2 - 0.65*ll,(max(x_series)+min(x_series))/2+0.65*ll]) plt.ylim([(max(y_series)+min(y_series))/2 - 0.65*ll,(max(y_series)+min(y_series))/2+0.65*ll]) # plt.xlabel('X [m]') # plt.ylabel('Y [m]') plt.tick_params(labelsize=6,direction='in') lg = plt.legend(loc='upper right',markerscale=3,fontsize=5,framealpha=1,ncol=1,columnspacing=0.3,handletextpad=0.3,edgecolor='black',fancybox=False) lg.set_zorder(200) lg.get_frame().set_linewidth(0.8) plt.gca().yaxis.set_label_coords(-.1, .5) plt.show() ================================================ FILE: results/PLACEHOLDER ================================================ ================================================ FILE: setup.py ================================================ from setuptools import setup from torch.utils.cpp_extension import BuildExtension, CUDAExtension import os.path as osp ROOT = osp.dirname(osp.abspath(__file__)) setup( name='droid_backends', ext_modules=[ CUDAExtension('droid_backends', include_dirs=[osp.join(ROOT, 'thirdparty/eigen')], sources=[ 'src/droid.cpp', 'src/droid_kernels.cu', 'src/correlation_kernels.cu', 'src/altcorr_kernel.cu', ], extra_compile_args={ 'cxx': ['-O3'], 'nvcc': ['-O3', '-gencode=arch=compute_60,code=sm_60', '-gencode=arch=compute_61,code=sm_61', '-gencode=arch=compute_70,code=sm_70', '-gencode=arch=compute_75,code=sm_75', '-gencode=arch=compute_80,code=sm_80', '-gencode=arch=compute_86,code=sm_86', ] }), ], cmdclass={ 'build_ext' : BuildExtension } ) setup( name='lietorch', version='0.2', description='Lie Groups for PyTorch', packages=['lietorch'], package_dir={'': 'thirdparty/lietorch'}, ext_modules=[ CUDAExtension('lietorch_backends', include_dirs=[ osp.join(ROOT, 'thirdparty/lietorch/lietorch/include'), osp.join(ROOT, 'thirdparty/eigen')], sources=[ 'thirdparty/lietorch/lietorch/src/lietorch.cpp', 'thirdparty/lietorch/lietorch/src/lietorch_gpu.cu', 'thirdparty/lietorch/lietorch/src/lietorch_cpu.cpp'], extra_compile_args={ 'cxx': ['-O2'], 'nvcc': ['-O2', '-gencode=arch=compute_60,code=sm_60', '-gencode=arch=compute_61,code=sm_61', '-gencode=arch=compute_70,code=sm_70', '-gencode=arch=compute_75,code=sm_75', '-gencode=arch=compute_80,code=sm_80', '-gencode=arch=compute_86,code=sm_86', ] }), ], cmdclass={ 'build_ext' : BuildExtension } ) ================================================ FILE: src/altcorr_kernel.cu ================================================ #include #include #include #include #include #include #include #include #include #include #define BLOCK_H 4 #define BLOCK_W 8 #define BLOCK_HW BLOCK_H * BLOCK_W #define CHANNEL_STRIDE 32 __forceinline__ __device__ bool within_bounds(int h, int w, int H, int W) { return h >= 0 && h < H && w >= 0 && w < W; } template __global__ void altcorr_forward_kernel( const torch::PackedTensorAccessor32 fmap1, const torch::PackedTensorAccessor32 fmap2, const torch::PackedTensorAccessor32 coords, torch::PackedTensorAccessor32 corr, int r) { const int b = blockIdx.x; const int h0 = blockIdx.y * blockDim.x; const int w0 = blockIdx.z * blockDim.y; const int tid = threadIdx.x * blockDim.y + threadIdx.y; const int H1 = fmap1.size(1); const int W1 = fmap1.size(2); const int H2 = fmap2.size(1); const int W2 = fmap2.size(2); const int N = coords.size(1); const int C = fmap1.size(3); __shared__ scalar_t f1[CHANNEL_STRIDE][BLOCK_HW]; __shared__ scalar_t f2[CHANNEL_STRIDE][BLOCK_HW]; __shared__ float x2s[BLOCK_HW]; __shared__ float y2s[BLOCK_HW]; for (int c=0; c(floor(y2s[k1])) - r + iy; int w2 = static_cast(floor(x2s[k1])) - r + ix; int c2 = tid % CHANNEL_STRIDE; if (within_bounds(h2, w2, H2, W2)) f2[c2][k1] = fmap2[b][h2][w2][c+c2]; else f2[c2][k1] = static_cast(0.0); } __syncthreads(); scalar_t s = 0.0; for (int k=0; k((dy) * (dx)); scalar_t ne = s * static_cast((dy) * (1-dx)); scalar_t sw = s * static_cast((1-dy) * (dx)); scalar_t se = s * static_cast((1-dy) * (1-dx)); // if (iy > 0 && ix > 0 && within_bounds(h1, w1, H1, W1)) // corr[b][n][ix_nw][h1][w1] += nw; // if (iy > 0 && ix < rd && within_bounds(h1, w1, H1, W1)) // corr[b][n][ix_ne][h1][w1] += ne; // if (iy < rd && ix > 0 && within_bounds(h1, w1, H1, W1)) // corr[b][n][ix_sw][h1][w1] += sw; // if (iy < rd && ix < rd && within_bounds(h1, w1, H1, W1)) // corr[b][n][ix_se][h1][w1] += se; scalar_t* corr_ptr = &corr[b][n][0][h1][w1]; if (iy > 0 && ix > 0 && within_bounds(h1, w1, H1, W1)) *(corr_ptr + ix_nw) += nw; if (iy > 0 && ix < rd && within_bounds(h1, w1, H1, W1)) *(corr_ptr + ix_ne) += ne; if (iy < rd && ix > 0 && within_bounds(h1, w1, H1, W1)) *(corr_ptr + ix_sw) += sw; if (iy < rd && ix < rd && within_bounds(h1, w1, H1, W1)) *(corr_ptr + ix_se) += se; } } } } } template __global__ void altcorr_backward_kernel( const torch::PackedTensorAccessor32 fmap1, const torch::PackedTensorAccessor32 fmap2, const torch::PackedTensorAccessor32 coords, const torch::PackedTensorAccessor32 corr_grad, torch::PackedTensorAccessor32 fmap1_grad, torch::PackedTensorAccessor32 fmap2_grad, torch::PackedTensorAccessor32 coords_grad, int r) { const int b = blockIdx.x; const int h0 = blockIdx.y * blockDim.x; const int w0 = blockIdx.z * blockDim.y; const int tid = threadIdx.x * blockDim.y + threadIdx.y; const int H1 = fmap1.size(1); const int W1 = fmap1.size(2); const int H2 = fmap2.size(1); const int W2 = fmap2.size(2); const int N = coords.size(1); const int C = fmap1.size(3); __shared__ scalar_t f1[CHANNEL_STRIDE][BLOCK_HW+1]; __shared__ scalar_t f2[CHANNEL_STRIDE][BLOCK_HW+1]; __shared__ scalar_t f1_grad[CHANNEL_STRIDE][BLOCK_HW+1]; __shared__ scalar_t f2_grad[CHANNEL_STRIDE][BLOCK_HW+1]; __shared__ scalar_t x2s[BLOCK_HW]; __shared__ scalar_t y2s[BLOCK_HW]; for (int c=0; c(floor(y2s[k1]))-r+iy; int w2 = static_cast(floor(x2s[k1]))-r+ix; int c2 = tid % CHANNEL_STRIDE; auto fptr = fmap2[b][h2][w2]; if (within_bounds(h2, w2, H2, W2)) f2[c2][k1] = fptr[c+c2]; else f2[c2][k1] = 0.0; f2_grad[c2][k1] = 0.0; } __syncthreads(); const scalar_t* grad_ptr = &corr_grad[b][n][0][h1][w1]; scalar_t g = 0.0; int ix_nw = H1*W1*((iy-1) + rd*(ix-1)); int ix_ne = H1*W1*((iy-1) + rd*ix); int ix_sw = H1*W1*(iy + rd*(ix-1)); int ix_se = H1*W1*(iy + rd*ix); if (iy > 0 && ix > 0 && within_bounds(h1, w1, H1, W1)) g += *(grad_ptr + ix_nw) * dy * dx; if (iy > 0 && ix < rd && within_bounds(h1, w1, H1, W1)) g += *(grad_ptr + ix_ne) * dy * (1-dx); if (iy < rd && ix > 0 && within_bounds(h1, w1, H1, W1)) g += *(grad_ptr + ix_sw) * (1-dy) * dx; if (iy < rd && ix < rd && within_bounds(h1, w1, H1, W1)) g += *(grad_ptr + ix_se) * (1-dy) * (1-dx); for (int k=0; k(floor(y2s[k1]))-r+iy; int w2 = static_cast(floor(x2s[k1]))-r+ix; int c2 = tid % CHANNEL_STRIDE; scalar_t* fptr = &fmap2_grad[b][h2][w2][0]; if (within_bounds(h2, w2, H2, W2)) atomicAdd(fptr+c+c2, f2_grad[c2][k1]); } } } } __syncthreads(); for (int k=0; k altcorr_cuda_forward( torch::Tensor fmap1, torch::Tensor fmap2, torch::Tensor coords, int radius) { const auto B = coords.size(0); const auto N = coords.size(1); const auto H = coords.size(2); const auto W = coords.size(3); const auto rd = 2 * radius + 1; auto opts = fmap1.options(); auto corr = torch::zeros({B, N, rd*rd, H, W}, opts); const dim3 blocks(B, (H+BLOCK_H-1)/BLOCK_H, (W+BLOCK_W-1)/BLOCK_W); const dim3 threads(BLOCK_H, BLOCK_W); AT_DISPATCH_FLOATING_TYPES_AND_HALF(fmap1.type(), "altcorr_forward_kernel", ([&] { altcorr_forward_kernel<<>>( fmap1.packed_accessor32(), fmap2.packed_accessor32(), coords.packed_accessor32(), corr.packed_accessor32(), radius); })); return {corr}; } std::vector altcorr_cuda_backward( torch::Tensor fmap1, torch::Tensor fmap2, torch::Tensor coords, torch::Tensor corr_grad, int radius) { const auto B = coords.size(0); const auto N = coords.size(1); const auto H1 = fmap1.size(1); const auto W1 = fmap1.size(2); const auto H2 = fmap2.size(1); const auto W2 = fmap2.size(2); const auto C = fmap1.size(3); auto opts = fmap1.options(); auto fmap1_grad = torch::zeros({B, H1, W1, C}, opts); auto fmap2_grad = torch::zeros({B, H2, W2, C}, opts); auto coords_grad = torch::zeros({B, N, H1, W1, 2}, opts); const dim3 blocks(B, (H1+BLOCK_H-1)/BLOCK_H, (W1+BLOCK_W-1)/BLOCK_W); const dim3 threads(BLOCK_H, BLOCK_W); altcorr_backward_kernel<<>>( fmap1.packed_accessor32(), fmap2.packed_accessor32(), coords.packed_accessor32(), corr_grad.packed_accessor32(), fmap1_grad.packed_accessor32(), fmap2_grad.packed_accessor32(), coords_grad.packed_accessor32(), radius); return {fmap1_grad, fmap2_grad, coords_grad}; } ================================================ FILE: src/bacore.h ================================================ #include #include class BACore { public: BACore(){} ~BACore(){} public: void init(torch::Tensor _poses, torch::Tensor _disps, torch::Tensor _intrinsics, torch::Tensor _disps_sens, torch::Tensor _targets, torch::Tensor _weights, torch::Tensor _eta, torch::Tensor _ii, torch::Tensor _jj, const int t0, const int t1, const int iterations, const float lm, const float ep, const bool motion_only); void hessian(torch::Tensor H, torch::Tensor v); void optimize(torch::Tensor H, torch::Tensor v); std::vector retract(torch::Tensor _dx); public: torch::Tensor poses; torch::Tensor disps; torch::Tensor intrinsics; torch::Tensor disps_sens; torch::Tensor targets; torch::Tensor weights; torch::Tensor eta; torch::Tensor ii; torch::Tensor jj; int t0,t1; float lm, ep; torch::Tensor ts; torch::Tensor ii_exp; torch::Tensor jj_exp; std::tuple kuniq; torch::Tensor kx; torch::Tensor kk_exp; // 不重复元素的索引 torch::Tensor dx; torch::Tensor dz; // initialize buffers torch::Tensor Hs; torch::Tensor vs; torch::Tensor Eii; torch::Tensor Eij; torch::Tensor Cii; torch::Tensor wi; torch::Tensor m ; torch::Tensor C ; torch::Tensor w ; torch::Tensor Q ; torch::Tensor Ei; torch::Tensor E ; }; ================================================ FILE: src/correlation_kernels.cu ================================================ #include #include #include #include #include #include #include #include #include #define BLOCK 16 __forceinline__ __device__ bool within_bounds(int h, int w, int H, int W) { return h >= 0 && h < H && w >= 0 && w < W; } template __global__ void corr_index_forward_kernel( const torch::PackedTensorAccessor32 volume, const torch::PackedTensorAccessor32 coords, torch::PackedTensorAccessor32 corr, int r) { // batch index const int x = blockIdx.x * blockDim.x + threadIdx.x; const int y = blockIdx.y * blockDim.y + threadIdx.y; const int n = blockIdx.z; const int h1 = volume.size(1); const int w1 = volume.size(2); const int h2 = volume.size(3); const int w2 = volume.size(4); if (!within_bounds(y, x, h1, w1)) { return; } float x0 = coords[n][0][y][x]; float y0 = coords[n][1][y][x]; float dx = x0 - floor(x0); float dy = y0 - floor(y0); int rd = 2*r + 1; for (int i=0; i(floor(x0)) - r + i; int y1 = static_cast(floor(y0)) - r + j; if (within_bounds(y1, x1, h2, w2)) { scalar_t s = volume[n][y][x][y1][x1]; if (i > 0 && j > 0) corr[n][i-1][j-1][y][x] += s * scalar_t(dx * dy); if (i > 0 && j < rd) corr[n][i-1][j][y][x] += s * scalar_t(dx * (1.0f-dy)); if (i < rd && j > 0) corr[n][i][j-1][y][x] += s * scalar_t((1.0f-dx) * dy); if (i < rd && j < rd) corr[n][i][j][y][x] += s * scalar_t((1.0f-dx) * (1.0f-dy)); } } } } template __global__ void corr_index_backward_kernel( const torch::PackedTensorAccessor32 coords, const torch::PackedTensorAccessor32 corr_grad, torch::PackedTensorAccessor32 volume_grad, int r) { // batch index const int x = blockIdx.x * blockDim.x + threadIdx.x; const int y = blockIdx.y * blockDim.y + threadIdx.y; const int n = blockIdx.z; const int h1 = volume_grad.size(1); const int w1 = volume_grad.size(2); const int h2 = volume_grad.size(3); const int w2 = volume_grad.size(4); if (!within_bounds(y, x, h1, w1)) { return; } float x0 = coords[n][0][y][x]; float y0 = coords[n][1][y][x]; float dx = x0 - floor(x0); float dy = y0 - floor(y0); int rd = 2*r + 1; for (int i=0; i(floor(x0)) - r + i; int y1 = static_cast(floor(y0)) - r + j; if (within_bounds(y1, x1, h2, w2)) { scalar_t g = 0.0; if (i > 0 && j > 0) g += corr_grad[n][i-1][j-1][y][x] * scalar_t(dx * dy); if (i > 0 && j < rd) g += corr_grad[n][i-1][j][y][x] * scalar_t(dx * (1.0f-dy)); if (i < rd && j > 0) g += corr_grad[n][i][j-1][y][x] * scalar_t((1.0f-dx) * dy); if (i < rd && j < rd) g += corr_grad[n][i][j][y][x] * scalar_t((1.0f-dx) * (1.0f-dy)); volume_grad[n][y][x][y1][x1] += g; } } } } std::vector corr_index_cuda_forward( torch::Tensor volume, torch::Tensor coords, int radius) { const auto batch_size = volume.size(0); const auto ht = volume.size(1); const auto wd = volume.size(2); const dim3 blocks((wd + BLOCK - 1) / BLOCK, (ht + BLOCK - 1) / BLOCK, batch_size); const dim3 threads(BLOCK, BLOCK); auto opts = volume.options(); torch::Tensor corr = torch::zeros( {batch_size, 2*radius+1, 2*radius+1, ht, wd}, opts); AT_DISPATCH_FLOATING_TYPES_AND_HALF(volume.type(), "sampler_forward_kernel", ([&] { corr_index_forward_kernel<<>>( volume.packed_accessor32(), coords.packed_accessor32(), corr.packed_accessor32(), radius); })); return {corr}; } std::vector corr_index_cuda_backward( torch::Tensor volume, torch::Tensor coords, torch::Tensor corr_grad, int radius) { const auto batch_size = volume.size(0); const auto ht = volume.size(1); const auto wd = volume.size(2); auto volume_grad = torch::zeros_like(volume); const dim3 blocks((wd + BLOCK - 1) / BLOCK, (ht + BLOCK - 1) / BLOCK, batch_size); const dim3 threads(BLOCK, BLOCK); AT_DISPATCH_FLOATING_TYPES_AND_HALF(volume.type(), "sampler_backward_kernel", ([&] { corr_index_backward_kernel<<>>( coords.packed_accessor32(), corr_grad.packed_accessor32(), volume_grad.packed_accessor32(), radius); })); return {volume_grad}; } ================================================ FILE: src/droid.cpp ================================================ #include #include #include "bacore.h" // CUDA forward declarations std::vector projective_transform_cuda( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics, torch::Tensor ii, torch::Tensor jj); torch::Tensor depth_filter_cuda( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics, torch::Tensor ix, torch::Tensor thresh); torch::Tensor frame_distance_cuda( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics, torch::Tensor ii, torch::Tensor jj, const float beta); std::vector projmap_cuda( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics, torch::Tensor ii, torch::Tensor jj); torch::Tensor iproj_cuda( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics); std::vector ba_cuda( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics, torch::Tensor disps_sens, torch::Tensor targets, torch::Tensor weights, torch::Tensor eta, torch::Tensor ii, torch::Tensor jj, const int t0, const int t1, const int iterations, const float lm, const float ep, const bool motion_only); std::vector ba_cuda_extend( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics, torch::Tensor disps_sens, torch::Tensor targets, torch::Tensor weights, torch::Tensor eta, torch::Tensor ii, torch::Tensor jj, torch::Tensor H, torch::Tensor v, torch::Tensor A_prior, const int t0, const int t1, const int iterations, const float lm, const float ep, const bool motion_only, const bool skip_solve); std::vector corr_index_cuda_forward( torch::Tensor volume, torch::Tensor coords, int radius); std::vector corr_index_cuda_backward( torch::Tensor volume, torch::Tensor coords, torch::Tensor corr_grad, int radius); std::vector altcorr_cuda_forward( torch::Tensor fmap1, torch::Tensor fmap2, torch::Tensor coords, int radius); std::vector altcorr_cuda_backward( torch::Tensor fmap1, torch::Tensor fmap2, torch::Tensor coords, torch::Tensor corr_grad, int radius); #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CONTIGUOUS(x) std::vector ba( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics, torch::Tensor disps_sens, torch::Tensor targets, torch::Tensor weights, torch::Tensor eta, torch::Tensor ii, torch::Tensor jj, const int t0, const int t1, const int iterations, const float lm, const float ep, const bool motion_only) { CHECK_INPUT(targets); CHECK_INPUT(weights); CHECK_INPUT(poses); CHECK_INPUT(disps); CHECK_INPUT(intrinsics); CHECK_INPUT(disps_sens); CHECK_INPUT(ii); CHECK_INPUT(jj); return ba_cuda(poses, disps, intrinsics, disps_sens, targets, weights, eta, ii, jj, t0, t1, iterations, lm, ep, motion_only); } std::vector ba_extend( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics, torch::Tensor disps_sens, torch::Tensor targets, torch::Tensor weights, torch::Tensor eta, torch::Tensor ii, torch::Tensor jj, torch::Tensor H, torch::Tensor v, torch::Tensor A_prior, const int t0, const int t1, const int iterations, const float lm, const float ep, const bool motion_only, const bool skip_solve) { CHECK_INPUT(targets); CHECK_INPUT(weights); CHECK_INPUT(poses); CHECK_INPUT(disps); CHECK_INPUT(intrinsics); CHECK_INPUT(disps_sens); CHECK_INPUT(ii); CHECK_INPUT(jj); CHECK_INPUT(H); CHECK_INPUT(v); CHECK_INPUT(A_prior); std::vector dx_dz = ba_cuda_extend(poses, disps, intrinsics, disps_sens, targets, weights, eta, ii, jj, H, v, A_prior, t0, t1, iterations, lm, ep, motion_only, skip_solve); return dx_dz; } torch::Tensor frame_distance( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics, torch::Tensor ii, torch::Tensor jj, const float beta) { CHECK_INPUT(poses); CHECK_INPUT(disps); CHECK_INPUT(intrinsics); CHECK_INPUT(ii); CHECK_INPUT(jj); return frame_distance_cuda(poses, disps, intrinsics, ii, jj, beta); } std::vector projmap( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics, torch::Tensor ii, torch::Tensor jj) { CHECK_INPUT(poses); CHECK_INPUT(disps); CHECK_INPUT(intrinsics); CHECK_INPUT(ii); CHECK_INPUT(jj); return projmap_cuda(poses, disps, intrinsics, ii, jj); } torch::Tensor iproj( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics) { CHECK_INPUT(poses); CHECK_INPUT(disps); CHECK_INPUT(intrinsics); return iproj_cuda(poses, disps, intrinsics); } // c++ python binding std::vector corr_index_forward( torch::Tensor volume, torch::Tensor coords, int radius) { CHECK_INPUT(volume); CHECK_INPUT(coords); return corr_index_cuda_forward(volume, coords, radius); } std::vector corr_index_backward( torch::Tensor volume, torch::Tensor coords, torch::Tensor corr_grad, int radius) { CHECK_INPUT(volume); CHECK_INPUT(coords); CHECK_INPUT(corr_grad); auto volume_grad = corr_index_cuda_backward(volume, coords, corr_grad, radius); return {volume_grad}; } std::vector altcorr_forward( torch::Tensor fmap1, torch::Tensor fmap2, torch::Tensor coords, int radius) { CHECK_INPUT(fmap1); CHECK_INPUT(fmap2); CHECK_INPUT(coords); return altcorr_cuda_forward(fmap1, fmap2, coords, radius); } std::vector altcorr_backward( torch::Tensor fmap1, torch::Tensor fmap2, torch::Tensor coords, torch::Tensor corr_grad, int radius) { CHECK_INPUT(fmap1); CHECK_INPUT(fmap2); CHECK_INPUT(coords); CHECK_INPUT(corr_grad); return altcorr_cuda_backward(fmap1, fmap2, coords, corr_grad, radius); } torch::Tensor depth_filter( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics, torch::Tensor ix, torch::Tensor thresh) { CHECK_INPUT(poses); CHECK_INPUT(disps); CHECK_INPUT(intrinsics); CHECK_INPUT(ix); CHECK_INPUT(thresh); return depth_filter_cuda(poses, disps, intrinsics, ix, thresh); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { // bundle adjustment kernels m.def("ba", &ba, "bundle adjustment"); m.def("ba_extend", &ba_extend, "bundle adjustment (extended)"); m.def("frame_distance", &frame_distance, "frame_distance"); m.def("projmap", &projmap, "projmap"); m.def("depth_filter", &depth_filter, "depth_filter"); m.def("iproj", &iproj, "back projection"); // correlation volume kernels m.def("altcorr_forward", &altcorr_forward, "ALTCORR forward"); m.def("altcorr_backward", &altcorr_backward, "ALTCORR backward"); m.def("corr_index_forward", &corr_index_forward, "INDEX forward"); m.def("corr_index_backward", &corr_index_backward, "INDEX backward"); py::class_(m, "BACore").def(py::init<>()) .def("init", &BACore::init) .def("hessian", &BACore::hessian) .def("optimize", &BACore::optimize) .def("retract", &BACore::retract); } ================================================ FILE: src/droid_kernels.cu ================================================ #include #include #include #include #include #include #include #include #include // #include "utils.cuh" #include #include #include #include #include "bacore.h" typedef Eigen::SparseMatrix SpMat; typedef Eigen::Triplet T; typedef std::vector> graph_t; typedef std::vector tensor_list_t; #define MIN_DEPTH 0.25 #define THREADS 256 #define NUM_BLOCKS(batch_size) ((batch_size + THREADS - 1) / THREADS) #define GPU_1D_KERNEL_LOOP(k, n) \ for (size_t k = threadIdx.x; k 1e-4) { float a = (1 - cosf(theta)) / theta_sq; crossInplace(phi, tau); t[0] += a * tau[0]; t[1] += a * tau[1]; t[2] += a * tau[2]; float b = (theta - sinf(theta)) / (theta * theta_sq); crossInplace(phi, tau); t[0] += b * tau[0]; t[1] += b * tau[1]; t[2] += b * tau[2]; } } torch::Tensor solveDense(const Eigen::MatrixXd& A, const Eigen::MatrixXd& Aprior, const Eigen::VectorXd& b, const int N, const int M, const float lm=0.0001,const float ep = 0.1){ torch::Tensor dx; Eigen::MatrixXd L = A + Aprior; L.diagonal().array() += ep + lm * L.diagonal().array(); Eigen::LLT solver; solver.compute(L); if (solver.info() == Eigen::Success) { Eigen::VectorXd x = solver.solve(b); dx = torch::from_blob(x.data(), {N, M}, torch::TensorOptions() .dtype(torch::kFloat64)).to(torch::kCUDA).to(torch::kFloat32); } else { dx = torch::zeros({N, M}, torch::TensorOptions() .device(torch::kCUDA).dtype(torch::kFloat32)); } return dx; } torch::Tensor solveDenseD(const Eigen::MatrixXd& A, const Eigen::VectorXd& b, const int N, const int M, const float lm=0.0001,const float ep = 0.1){ torch::Tensor dx; Eigen::MatrixXd L(A); L.diagonal().array() += ep + lm * L.diagonal().array(); Eigen::LLT solver; solver.compute(L); if (solver.info() == Eigen::Success) { Eigen::VectorXd x = solver.solve(b); dx = torch::from_blob(x.data(), {N, M}, torch::TensorOptions() .dtype(torch::kFloat64)).to(torch::kCUDA).to(torch::kFloat32); } else { dx = torch::zeros({N, M}, torch::TensorOptions() .device(torch::kCUDA).dtype(torch::kFloat32)); } return dx; } __global__ void projective_transform_kernel( const torch::PackedTensorAccessor32 target, const torch::PackedTensorAccessor32 weight, const torch::PackedTensorAccessor32 poses, const torch::PackedTensorAccessor32 disps, const torch::PackedTensorAccessor32 intrinsics, const torch::PackedTensorAccessor32 ii, const torch::PackedTensorAccessor32 jj, torch::PackedTensorAccessor32 Hs, // Hessian of Poses torch::PackedTensorAccessor32 vs, // Residuals (Pose) torch::PackedTensorAccessor32 Eii,// Hessian, Disps_i - Pose_i torch::PackedTensorAccessor32 Eij,// Hessian, Disps_i - Pose_j torch::PackedTensorAccessor32 Cii,// Hessian, Disps_i - Disps_i torch::PackedTensorAccessor32 bz) // Residuals (Disp) { const int block_id = blockIdx.x; const int thread_id = threadIdx.x; const int ht = disps.size(1); const int wd = disps.size(2); int ix = static_cast(ii[block_id]); int jx = static_cast(jj[block_id]); __shared__ float fx; __shared__ float fy; __shared__ float cx; __shared__ float cy; __shared__ float ti[3], tj[3], tij[3]; __shared__ float qi[4], qj[4], qij[4]; // load intrinsics from global memory if (thread_id == 0) { fx = intrinsics[0]; fy = intrinsics[1]; cx = intrinsics[2]; cy = intrinsics[3]; } __syncthreads(); // stereo frames if (ix == jx) { if (thread_id == 0) { tij[0] = -0.1; tij[1] = 0; tij[2] = 0; qij[0] = 0; qij[1] = 0; qij[2] = 0; qij[3] = 1; } } else { // load poses from global memory if (thread_id < 3) { ti[thread_id] = poses[ix][thread_id]; tj[thread_id] = poses[jx][thread_id]; } if (thread_id < 4) { qi[thread_id] = poses[ix][thread_id+3]; qj[thread_id] = poses[jx][thread_id+3]; } __syncthreads(); if (thread_id == 0) { relSE3(ti, qi, tj, qj, tij, qij); } } __syncthreads(); //points float Xi[4]; float Xj[4]; // jacobians float Jx[12]; float Jz; float* Ji = &Jx[0]; float* Jj = &Jx[6]; // hessians float hij[12*(12+1)/2]; float vi[6], vj[6]; int l; for (l=0; l<12*(12+1)/2; l++) { hij[l] = 0; } for (int n=0; n<6; n++) { vi[n] = 0; vj[n] = 0; } __syncthreads(); GPU_1D_KERNEL_LOOP(k, ht*wd) { const int i = k / wd; const int j = k % wd; const float u = static_cast(j); const float v = static_cast(i); // homogenous coordinates Xi[0] = (u - cx) / fx; Xi[1] = (v - cy) / fy; Xi[2] = 1; Xi[3] = disps[ix][i][j]; // transform homogenous point actSE3(tij, qij, Xi, Xj); const float x = Xj[0]; const float y = Xj[1]; const float h = Xj[3]; const float d = (Xj[2] < MIN_DEPTH) ? 0.0 : 1.0 / Xj[2]; const float d2 = d * d; float wu = (Xj[2] < MIN_DEPTH) ? 0.0 : .001 * weight[block_id][0][i][j]; float wv = (Xj[2] < MIN_DEPTH) ? 0.0 : .001 * weight[block_id][1][i][j]; const float ru = target[block_id][0][i][j] - (fx * d * x + cx); const float rv = target[block_id][1][i][j] - (fy * d * y + cy); // x - coordinate Jj[0] = fx * (h*d); Jj[1] = fx * 0; Jj[2] = fx * (-x*h*d2); Jj[3] = fx * (-x*y*d2); Jj[4] = fx * (1 + x*x*d2); Jj[5] = fx * (-y*d); Jz = fx * (tij[0] * d - tij[2] * (x * d2)); Cii[block_id][k] = wu * Jz * Jz; bz[block_id][k] = wu * ru * Jz; if (ix == jx) wu = 0; adjSE3(tij, qij, Jj, Ji); for (int n=0; n<6; n++) Ji[n] *= -1; l=0; for (int n=0; n<12; n++) { for (int m=0; m<=n; m++) { hij[l] += wu * Jx[n] * Jx[m]; l++; } } for (int n=0; n<6; n++) { vi[n] += wu * ru * Ji[n]; vj[n] += wu * ru * Jj[n]; Eii[block_id][n][k] = wu * Jz * Ji[n]; Eij[block_id][n][k] = wu * Jz * Jj[n]; } Jj[0] = fy * 0; Jj[1] = fy * (h*d); Jj[2] = fy * (-y*h*d2); Jj[3] = fy * (-1 - y*y*d2); Jj[4] = fy * (x*y*d2); Jj[5] = fy * (x*d); Jz = fy * (tij[1] * d - tij[2] * (y * d2)); Cii[block_id][k] += wv * Jz * Jz; bz[block_id][k] += wv * rv * Jz; if (ix == jx) wv = 0; adjSE3(tij, qij, Jj, Ji); for (int n=0; n<6; n++) Ji[n] *= -1; l=0; for (int n=0; n<12; n++) { for (int m=0; m<=n; m++) { hij[l] += wv * Jx[n] * Jx[m]; l++; } } for (int n=0; n<6; n++) { vi[n] += wv * rv * Ji[n]; vj[n] += wv * rv * Jj[n]; Eii[block_id][n][k] += wv * Jz * Ji[n]; Eij[block_id][n][k] += wv * Jz * Jj[n]; } } __syncthreads(); __shared__ float sdata[THREADS]; for (int n=0; n<6; n++) { sdata[threadIdx.x] = vi[n]; blockReduce(sdata); if (threadIdx.x == 0) { vs[0][block_id][n] = sdata[0]; } __syncthreads(); sdata[threadIdx.x] = vj[n]; blockReduce(sdata); if (threadIdx.x == 0) { vs[1][block_id][n] = sdata[0]; } } l=0; for (int n=0; n<12; n++) { for (int m=0; m<=n; m++) { sdata[threadIdx.x] = hij[l]; blockReduce(sdata); if (threadIdx.x == 0) { if (n<6 && m<6) { Hs[0][block_id][n][m] = sdata[0]; Hs[0][block_id][m][n] = sdata[0]; } else if (n >=6 && m<6) { Hs[1][block_id][m][n-6] = sdata[0]; Hs[2][block_id][n-6][m] = sdata[0]; } else { Hs[3][block_id][n-6][m-6] = sdata[0]; Hs[3][block_id][m-6][n-6] = sdata[0]; } } l++; } } } __global__ void projmap_kernel( const torch::PackedTensorAccessor32 poses, const torch::PackedTensorAccessor32 disps, const torch::PackedTensorAccessor32 intrinsics, const torch::PackedTensorAccessor32 ii, const torch::PackedTensorAccessor32 jj, torch::PackedTensorAccessor32 coords, torch::PackedTensorAccessor32 valid) { const int block_id = blockIdx.x; const int thread_id = threadIdx.x; const int ht = disps.size(1); const int wd = disps.size(2); __shared__ int ix; __shared__ int jx; __shared__ float fx; __shared__ float fy; __shared__ float cx; __shared__ float cy; __shared__ float ti[3], tj[3], tij[3]; __shared__ float qi[4], qj[4], qij[4]; // load intrinsics from global memory if (thread_id == 0) { ix = static_cast(ii[block_id]); jx = static_cast(jj[block_id]); fx = intrinsics[0]; fy = intrinsics[1]; cx = intrinsics[2]; cy = intrinsics[3]; } __syncthreads(); // load poses from global memory if (thread_id < 3) { ti[thread_id] = poses[ix][thread_id]; tj[thread_id] = poses[jx][thread_id]; } if (thread_id < 4) { qi[thread_id] = poses[ix][thread_id+3]; qj[thread_id] = poses[jx][thread_id+3]; } __syncthreads(); if (thread_id == 0) { relSE3(ti, qi, tj, qj, tij, qij); } //points float Xi[4]; float Xj[4]; __syncthreads(); GPU_1D_KERNEL_LOOP(k, ht*wd) { const int i = k / wd; const int j = k % wd; const float u = static_cast(j); const float v = static_cast(i); // homogenous coordinates Xi[0] = (u - cx) / fx; Xi[1] = (v - cy) / fy; Xi[2] = 1; Xi[3] = disps[ix][i][j]; // transform homogenous point actSE3(tij, qij, Xi, Xj); coords[block_id][i][j][0] = u; coords[block_id][i][j][1] = v; if (Xj[2] > 0.01) { coords[block_id][i][j][0] = fx * (Xj[0] / Xj[2]) + cx; coords[block_id][i][j][1] = fy * (Xj[1] / Xj[2]) + cy; } valid[block_id][i][j][0] = (Xj[2] > MIN_DEPTH) ? 1.0 : 0.0; } } __global__ void frame_distance_kernel( const torch::PackedTensorAccessor32 poses, const torch::PackedTensorAccessor32 disps, const torch::PackedTensorAccessor32 intrinsics, const torch::PackedTensorAccessor32 ii, const torch::PackedTensorAccessor32 jj, torch::PackedTensorAccessor32 dist, const float beta) { const int block_id = blockIdx.x; const int thread_id = threadIdx.x; const int ht = disps.size(1); const int wd = disps.size(2); __shared__ int ix; __shared__ int jx; __shared__ float fx; __shared__ float fy; __shared__ float cx; __shared__ float cy; __shared__ float ti[3], tj[3], tij[3]; __shared__ float qi[4], qj[4], qij[4]; // load intrinsics from global memory if (thread_id == 0) { ix = static_cast(ii[block_id]); jx = static_cast(jj[block_id]); fx = intrinsics[0]; fy = intrinsics[1]; cx = intrinsics[2]; cy = intrinsics[3]; } __syncthreads(); //points float Xi[4]; float Xj[4]; __shared__ float accum[THREADS]; accum[thread_id] = 0; __shared__ float valid[THREADS]; valid[thread_id] = 0; __shared__ float total[THREADS]; total[thread_id] = 0; __syncthreads(); for (int n=0; n<1; n++) { if (thread_id < 3) { ti[thread_id] = poses[ix][thread_id]; tj[thread_id] = poses[jx][thread_id]; } if (thread_id < 4) { qi[thread_id] = poses[ix][thread_id+3]; qj[thread_id] = poses[jx][thread_id+3]; } __syncthreads(); relSE3(ti, qi, tj, qj, tij, qij); float d, du, dv; GPU_1D_KERNEL_LOOP(k, ht*wd) { const int i = k / wd; const int j = k % wd; const float u = static_cast(j); const float v = static_cast(i); // if (disps[ix][i][j] < 0.01) { // continue; // } // homogenous coordinates Xi[0] = (u - cx) / fx; Xi[1] = (v - cy) / fy; Xi[2] = 1; Xi[3] = disps[ix][i][j]; // transform homogenous point actSE3(tij, qij, Xi, Xj); du = fx * (Xj[0] / Xj[2]) + cx - u; dv = fy * (Xj[1] / Xj[2]) + cy - v; d = sqrtf(du*du + dv*dv); total[threadIdx.x] += beta; if (Xj[2] > MIN_DEPTH) { accum[threadIdx.x] += beta * d; valid[threadIdx.x] += beta; } Xi[0] = (u - cx) / fx; Xi[1] = (v - cy) / fy; Xi[2] = 1; Xi[3] = disps[ix][i][j]; Xj[0] = Xi[0] + Xi[3] * tij[0]; Xj[1] = Xi[1] + Xi[3] * tij[1]; Xj[2] = Xi[2] + Xi[3] * tij[2]; du = fx * (Xj[0] / Xj[2]) + cx - u; dv = fy * (Xj[1] / Xj[2]) + cy - v; d = sqrtf(du*du + dv*dv); total[threadIdx.x] += (1 - beta); if (Xj[2] > MIN_DEPTH) { accum[threadIdx.x] += (1 - beta) * d; valid[threadIdx.x] += (1 - beta); } } if (threadIdx.x == 0) { int tmp = ix; ix = jx; jx = tmp; } __syncthreads(); } __syncthreads(); blockReduce(accum); __syncthreads(); blockReduce(total); __syncthreads(); blockReduce(valid); __syncthreads(); if (thread_id == 0) { // dist[block_id] = (valid[0] / (total[0] + 1e-8) < 0.75) ? 1000.0 : accum[0] / valid[0]; dist[block_id] = (valid[0] / (total[0] + 1e-8) < 0.75) ? 1000.0 : accum[0] / valid[0]; } } __global__ void depth_filter_kernel( const torch::PackedTensorAccessor32 poses, const torch::PackedTensorAccessor32 disps, const torch::PackedTensorAccessor32 intrinsics, const torch::PackedTensorAccessor32 inds, const torch::PackedTensorAccessor32 thresh, torch::PackedTensorAccessor32 counter) { const int block_id = blockIdx.x; const int neigh_id = blockIdx.y; const int index = blockIdx.z * blockDim.x + threadIdx.x; // if (threadIdx.x == 0) { // printf("%d %d %d %d\n", blockIdx.x, blockIdx.y, blockDim.x, threadIdx.x); // } const int num = disps.size(0); const int ht = disps.size(1); const int wd = disps.size(2); __shared__ int ix; __shared__ int jx; __shared__ float fx; __shared__ float fy; __shared__ float cx; __shared__ float cy; __shared__ float ti[3], tj[3], tij[3]; __shared__ float qi[4], qj[4], qij[4]; if (threadIdx.x == 0) { ix = static_cast(inds[block_id]); jx = (neigh_id < 3) ? ix - neigh_id - 1 : ix + neigh_id; fx = intrinsics[0]; fy = intrinsics[1]; cx = intrinsics[2]; cy = intrinsics[3]; } __syncthreads(); if (jx < 0 || jx >= num) { return; } const float t = thresh[block_id]; // load poses from global memory if (threadIdx.x < 3) { ti[threadIdx.x] = poses[ix][threadIdx.x]; tj[threadIdx.x] = poses[jx][threadIdx.x]; } if (threadIdx.x < 4) { qi[threadIdx.x] = poses[ix][threadIdx.x+3]; qj[threadIdx.x] = poses[jx][threadIdx.x+3]; } __syncthreads(); if (threadIdx.x == 0) { relSE3(ti, qi, tj, qj, tij, qij); } //points float Xi[4]; float Xj[4]; __syncthreads(); if (index < ht*wd) { const int i = index / wd; const int j = index % wd; const float ui = static_cast(j); const float vi = static_cast(i); const float di = disps[ix][i][j]; // homogenous coordinates Xi[0] = (ui - cx) / fx; Xi[1] = (vi - cy) / fy; Xi[2] = 1; Xi[3] = di; // transform homogenous point actSE3(tij, qij, Xi, Xj); const float uj = fx * (Xj[0] / Xj[2]) + cx; const float vj = fy * (Xj[1] / Xj[2]) + cy; const float dj = Xj[3] / Xj[2]; const int u0 = static_cast(floor(uj)); const int v0 = static_cast(floor(vj)); if (u0 >= 0 && v0 >= 0 && u0 < wd-1 && v0 < ht-1) { const float wx = ceil(uj) - uj; const float wy = ceil(vj) - vj; const float d00 = disps[jx][v0+0][u0+0]; const float d01 = disps[jx][v0+0][u0+1]; const float d10 = disps[jx][v0+1][u0+0]; const float d11 = disps[jx][v0+1][u0+1]; const float dj_hat = wy*wx*d00 + wy*(1-wx)*d01 + (1-wy)*wx*d10 + (1-wy)*(1-wx)*d11; const float err = abs(1.0/dj - 1.0/dj_hat); if (abs(1.0/dj - 1.0/d00) < t) atomicAdd(&counter[block_id][i][j], 1.0f); else if (abs(1.0/dj - 1.0/d01) < t) atomicAdd(&counter[block_id][i][j], 1.0f); else if (abs(1.0/dj - 1.0/d10) < t) atomicAdd(&counter[block_id][i][j], 1.0f); else if (abs(1.0/dj - 1.0/d11) < t) atomicAdd(&counter[block_id][i][j], 1.0f); } } } __global__ void iproj_kernel( const torch::PackedTensorAccessor32 poses, const torch::PackedTensorAccessor32 disps, const torch::PackedTensorAccessor32 intrinsics, torch::PackedTensorAccessor32 points) { const int block_id = blockIdx.x; const int index = blockIdx.y * blockDim.x + threadIdx.x; const int num = disps.size(0); const int ht = disps.size(1); const int wd = disps.size(2); __shared__ float fx; __shared__ float fy; __shared__ float cx; __shared__ float cy; __shared__ float t[3]; __shared__ float q[4]; if (threadIdx.x == 0) { fx = intrinsics[0]; fy = intrinsics[1]; cx = intrinsics[2]; cy = intrinsics[3]; } __syncthreads(); // load poses from global memory if (threadIdx.x < 3) { t[threadIdx.x] = poses[block_id][threadIdx.x]; } if (threadIdx.x < 4) { q[threadIdx.x] = poses[block_id][threadIdx.x+3]; } __syncthreads(); //points float Xi[4]; float Xj[4]; if (index < ht*wd) { const int i = index / wd; const int j = index % wd; const float ui = static_cast(j); const float vi = static_cast(i); const float di = disps[block_id][i][j]; // homogenous coordinates Xi[0] = (ui - cx) / fx; Xi[1] = (vi - cy) / fy; Xi[2] = 1; Xi[3] = di; // transform homogenous point actSE3(t, q, Xi, Xj); points[block_id][i][j][0] = Xj[0] / Xj[3]; points[block_id][i][j][1] = Xj[1] / Xj[3]; points[block_id][i][j][2] = Xj[2] / Xj[3]; } } __global__ void accum_kernel( const torch::PackedTensorAccessor32 inps, const torch::PackedTensorAccessor32 ptrs, const torch::PackedTensorAccessor32 idxs, torch::PackedTensorAccessor32 outs) { const int block_id = blockIdx.x; const int D = inps.size(2); const int start = ptrs[block_id]; const int end = ptrs[block_id+1]; for (int k=threadIdx.x; k poses, const torch::PackedTensorAccessor32 dx, const int t0, const int t1) { for (int k=t0+threadIdx.x; k disps, const torch::PackedTensorAccessor32 dz, const torch::PackedTensorAccessor32 inds) { const int i = inds[blockIdx.x]; const int ht = disps.size(1); const int wd = disps.size(2); for (int k=threadIdx.x; k(); long* jx_data = jx_cpu.data_ptr(); long* kx_data = inds.data_ptr(); int count = jx.size(0); std::vector cols; torch::Tensor ptrs_cpu = torch::zeros({count+1}, torch::TensorOptions().dtype(torch::kInt64)); long* ptrs_data = ptrs_cpu.data_ptr(); ptrs_data[0] = 0; int i = 0; for (int j=0; j(); for (int i=0; i>>( data.packed_accessor32(), ptrs.packed_accessor32(), idxs.packed_accessor32(), out.packed_accessor32()); return out; } __global__ void EEt6x6_kernel( const torch::PackedTensorAccessor32 E, const torch::PackedTensorAccessor32 Q, const torch::PackedTensorAccessor32 idx, torch::PackedTensorAccessor32 S) { // indicices const int ix = idx[blockIdx.x][0]; const int jx = idx[blockIdx.x][1]; const int kx = idx[blockIdx.x][2]; const int D = E.size(2); float dS[6][6]; float ei[6]; float ej[6]; for (int i=0; i<6; i++) { for (int j=0; j<6; j++) { dS[i][j] = 0; } } for (int k=threadIdx.x; k E, const torch::PackedTensorAccessor32 Q, const torch::PackedTensorAccessor32 w, const torch::PackedTensorAccessor32 idx, torch::PackedTensorAccessor32 v) { const int D = E.size(2); const int kx = idx[blockIdx.x][0]; float b[6]; for (int n=0; n<6; n++) { b[n] = 0.0; } for (int k=threadIdx.x; k E, const torch::PackedTensorAccessor32 x, const torch::PackedTensorAccessor32 idx, torch::PackedTensorAccessor32 w) { const int D = E.size(2); const int ix = idx[blockIdx.x]; if (idx[blockIdx.x] <= 0 || idx[blockIdx.x] >= x.size(0)) return; for (int k=threadIdx.x; k A; Eigen::VectorX b; SparseBlock(int N, int M) : N(N), M(M) { A = Eigen::SparseMatrix(N*M, N*M); b = Eigen::VectorXd::Zero(N*M); } SparseBlock(Eigen::SparseMatrix const& A, Eigen::VectorX const& b, int N, int M) : A(A), b(b), N(N), M(M) {} void update_lhs(torch::Tensor As, torch::Tensor ii, torch::Tensor jj) { auto As_cpu = As.to(torch::kCPU).to(torch::kFloat64); auto ii_cpu = ii.to(torch::kCPU).to(torch::kInt64); auto jj_cpu = jj.to(torch::kCPU).to(torch::kInt64); auto As_acc = As_cpu.accessor(); auto ii_acc = ii_cpu.accessor(); auto jj_acc = jj_cpu.accessor(); std::vector tripletList; for (int n=0; n= 0 && j >= 0) { for (int k=0; k(); auto ii_acc = ii_cpu.accessor(); for (int n=0; n= 0) { for (int j=0; j get_dense() { Eigen::MatrixXd Ad = Eigen::MatrixXd(A); torch::Tensor H = torch::from_blob(Ad.data(), {N*M, N*M}, torch::TensorOptions() .dtype(torch::kFloat64)).to(torch::kCUDA).to(torch::kFloat32); torch::Tensor v = torch::from_blob(b.data(), {N*M, 1}, torch::TensorOptions() .dtype(torch::kFloat64)).to(torch::kCUDA).to(torch::kFloat32); return std::make_tuple(H, v); } void get_dense_extend(torch::PackedTensorAccessor32 H, torch::PackedTensorAccessor32 v) { // Eigen::MatrixXd Ad = Eigen::MatrixXd(A); // std::cerr< L(A); L.diagonal().array() += ep + lm * L.diagonal().array(); Eigen::SimplicialLLT> solver; solver.compute(L); if (solver.info() == Eigen::Success) { Eigen::VectorXd x = solver.solve(b); dx = torch::from_blob(x.data(), {N, M}, torch::TensorOptions() .dtype(torch::kFloat64)).to(torch::kCUDA).to(torch::kFloat32); } else { dx = torch::zeros({N, M}, torch::TensorOptions() .device(torch::kCUDA).dtype(torch::kFloat32)); } return dx; } torch::Tensor solve_dense(const float lm=0.0001,const float ep = 0.1){ torch::Tensor dx; Eigen::MatrixXd L(A); L.diagonal().array() += ep + lm * L.diagonal().array(); Eigen::LLT solver; solver.compute(L); if (solver.info() == Eigen::Success) { Eigen::VectorXd x = solver.solve(b); dx = torch::from_blob(x.data(), {N, M}, torch::TensorOptions() .dtype(torch::kFloat64)).to(torch::kCUDA).to(torch::kFloat32); } else { dx = torch::zeros({N, M}, torch::TensorOptions() .device(torch::kCUDA).dtype(torch::kFloat32)); } return dx; } private: const int N; const int M; }; SparseBlock schur_block(torch::Tensor E, torch::Tensor Q, torch::Tensor w, torch::Tensor ii, torch::Tensor jj, torch::Tensor kk, const int t0, const int t1) { torch::Tensor ii_cpu = ii.to(torch::kCPU); torch::Tensor jj_cpu = jj.to(torch::kCPU); torch::Tensor kk_cpu = kk.to(torch::kCPU); const int P = t1 - t0; const long* ii_data = ii_cpu.data_ptr(); const long* jj_data = jj_cpu.data_ptr(); const long* kk_data = kk_cpu.data_ptr(); std::vector> graph(P); std::vector> index(P); for (int n=0; n= t0 && j <= t1) { const int t = j - t0; graph[t].push_back(k); index[t].push_back(n); } } std::vector ii_list, jj_list, idx, jdx; for (int i=0; i>>( E.packed_accessor32(), Q.packed_accessor32(), ix_cuda.packed_accessor32(), S.packed_accessor32()); Ev6x1_kernel<<>>( E.packed_accessor32(), Q.packed_accessor32(), w.packed_accessor32(), jx_cuda.packed_accessor32(), v.packed_accessor32()); // schur block SparseBlock A(P, 6); A.update_lhs(S, ii2_cpu, jj2_cpu); A.update_rhs(v, jj_cpu - t0); return A; } std::vector ba_cuda( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics, torch::Tensor disps_sens, torch::Tensor targets, torch::Tensor weights, torch::Tensor eta, torch::Tensor ii, torch::Tensor jj, const int t0, const int t1, const int iterations, const float lm, const float ep, const bool motion_only) { auto opts = poses.options(); const int num = ii.size(0); const int ht = disps.size(1); const int wd = disps.size(2); torch::Tensor ts = torch::arange(t0, t1).to(torch::kCUDA); torch::Tensor ii_exp = torch::cat({ts, ii}, 0); torch::Tensor jj_exp = torch::cat({ts, jj}, 0); std::tuple kuniq = torch::_unique(ii_exp, true, true); torch::Tensor kx = std::get<0>(kuniq); torch::Tensor kk_exp = std::get<1>(kuniq); torch::Tensor dx; torch::Tensor dz; // initialize buffers torch::Tensor Hs = torch::zeros({4, num, 6, 6}, opts); torch::Tensor vs = torch::zeros({2, num, 6}, opts); torch::Tensor Eii = torch::zeros({num, 6, ht*wd}, opts); torch::Tensor Eij = torch::zeros({num, 6, ht*wd}, opts); torch::Tensor Cii = torch::zeros({num, ht*wd}, opts); torch::Tensor wi = torch::zeros({num, ht*wd}, opts); for (int itr=0; itr>>( targets.packed_accessor32(), weights.packed_accessor32(), poses.packed_accessor32(), disps.packed_accessor32(), intrinsics.packed_accessor32(), ii.packed_accessor32(), jj.packed_accessor32(), Hs.packed_accessor32(), vs.packed_accessor32(), Eii.packed_accessor32(), Eij.packed_accessor32(), Cii.packed_accessor32(), wi.packed_accessor32()); // pose x pose block SparseBlock A(t1 - t0, 6); A.update_lhs(Hs.reshape({-1, 6, 6}), torch::cat({ii, ii, jj, jj}) - t0, torch::cat({ii, jj, ii, jj}) - t0); A.update_rhs(vs.reshape({-1, 6}), torch::cat({ii, jj}) - t0); if (motion_only) { dx = A.solve(lm, ep); // update poses pose_retr_kernel<<<1, THREADS>>>( poses.packed_accessor32(), dx.packed_accessor32(), t0, t1); } else { // add depth residual if there are depth sensor measurements const float alpha = 0.05; torch::Tensor m = (disps_sens.index({kx, "..."}) > 0).to(torch::TensorOptions().dtype(torch::kFloat32)).view({-1, ht*wd}); torch::Tensor C = accum_cuda(Cii, ii, kx) + m * alpha + (1 - m) * eta.view({-1, ht*wd}); torch::Tensor w = accum_cuda(wi, ii, kx) - m * alpha * (disps.index({kx, "..."}) - disps_sens.index({kx, "..."})).view({-1, ht*wd}); torch::Tensor Q = 1.0 / C; torch::Tensor Ei = accum_cuda(Eii.view({num, 6*ht*wd}), ii, ts).view({t1-t0, 6, ht*wd}); torch::Tensor E = torch::cat({Ei, Eij}, 0); SparseBlock S = schur_block(E, Q, w, ii_exp, jj_exp, kk_exp, t0, t1); dx = (A - S).solve(lm, ep); torch::Tensor ix = jj_exp - t0; torch::Tensor dw = torch::zeros({ix.size(0), ht*wd}, opts); EvT6x1_kernel<<>>( E.packed_accessor32(), dx.packed_accessor32(), ix.packed_accessor32(), dw.packed_accessor32()); dz = Q * (w - accum_cuda(dw, ii_exp, kx)); // update poses pose_retr_kernel<<<1, THREADS>>>( poses.packed_accessor32(), dx.packed_accessor32(), t0, t1); // update disparity maps disp_retr_kernel<<>>( disps.packed_accessor32(), dz.packed_accessor32(), kx.packed_accessor32()); } } return {dx, dz}; } std::vector ba_cuda_extend( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics, torch::Tensor disps_sens, torch::Tensor targets, torch::Tensor weights, torch::Tensor eta, torch::Tensor ii, torch::Tensor jj, torch::Tensor H, torch::Tensor v, torch::Tensor A_prior, const int t0, const int t1, const int iterations, const float lm, const float ep, const bool motion_only, const bool skip_solve) { auto opts = poses.options(); const int num = ii.size(0); const int ht = disps.size(1); const int wd = disps.size(2); torch::Tensor ts = torch::arange(t0, t1).to(torch::kCUDA); torch::Tensor ii_exp = torch::cat({ts, ii}, 0); torch::Tensor jj_exp = torch::cat({ts, jj}, 0); std::tuple kuniq = torch::_unique(ii_exp, true, true); torch::Tensor kx = std::get<0>(kuniq); torch::Tensor kk_exp = std::get<1>(kuniq); // 不重复元素的索引 torch::Tensor dx; torch::Tensor dz; // initialize buffers torch::Tensor Hs = torch::zeros({4, num, 6, 6}, opts); torch::Tensor vs = torch::zeros({2, num, 6}, opts); torch::Tensor Eii = torch::zeros({num, 6, ht*wd}, opts); torch::Tensor Eij = torch::zeros({num, 6, ht*wd}, opts); torch::Tensor Cii = torch::zeros({num, ht*wd}, opts); torch::Tensor wi = torch::zeros({num, ht*wd}, opts); std::cerr<<"start iteration"<>>( targets.packed_accessor32(), weights.packed_accessor32(), poses.packed_accessor32(), disps.packed_accessor32(), intrinsics.packed_accessor32(), ii.packed_accessor32(), jj.packed_accessor32(), Hs.packed_accessor32(), vs.packed_accessor32(), Eii.packed_accessor32(), Eij.packed_accessor32(), Cii.packed_accessor32(), wi.packed_accessor32()); std::cerr<<"projective_transform_kernel"<>>( poses.packed_accessor32(), dx.packed_accessor32(), t0, t1); } else { // add depth residual if there are depth sensor measurements const float alpha = 0.05; torch::Tensor m = (disps_sens.index({kx, "..."}) > 0).to(torch::TensorOptions().dtype(torch::kFloat32)).view({-1, ht*wd}); torch::Tensor C = accum_cuda(Cii, ii, kx) + m * alpha + (1 - m) * eta.view({-1, ht*wd}); torch::Tensor w = accum_cuda(wi, ii, kx) - m * alpha * (disps.index({kx, "..."}) - disps_sens.index({kx, "..."})).view({-1, ht*wd}); torch::Tensor Q = 1.0 / C; std::cerr<<"ii"<(); for(int i =0;i(); auto v_accessor = v.accessor(); for(int i =0;i>>( E.packed_accessor32(), dx.packed_accessor32(), ix.packed_accessor32(), dw.packed_accessor32()); dz = Q * (w - accum_cuda(dw, ii_exp, kx)); // update poses pose_retr_kernel<<<1, THREADS>>>( poses.packed_accessor32(), dx.packed_accessor32(), t0, t1); // update disparity maps disp_retr_kernel<<>>( disps.packed_accessor32(), dz.packed_accessor32(), kx.packed_accessor32()); } } return {dx, dz}; } torch::Tensor frame_distance_cuda( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics, torch::Tensor ii, torch::Tensor jj, const float beta) { auto opts = poses.options(); const int num = ii.size(0); torch::Tensor dist = torch::zeros({num}, opts); frame_distance_kernel<<>>( poses.packed_accessor32(), disps.packed_accessor32(), intrinsics.packed_accessor32(), ii.packed_accessor32(), jj.packed_accessor32(), dist.packed_accessor32(), beta); return dist; } std::vector projmap_cuda( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics, torch::Tensor ii, torch::Tensor jj) { auto opts = poses.options(); const int num = ii.size(0); const int ht = disps.size(1); const int wd = disps.size(2); torch::Tensor coords = torch::zeros({num, ht, wd, 3}, opts); torch::Tensor valid = torch::zeros({num, ht, wd, 1}, opts); projmap_kernel<<>>( poses.packed_accessor32(), disps.packed_accessor32(), intrinsics.packed_accessor32(), ii.packed_accessor32(), jj.packed_accessor32(), coords.packed_accessor32(), valid.packed_accessor32()); return {coords, valid}; } torch::Tensor depth_filter_cuda( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics, torch::Tensor ix, torch::Tensor thresh) { const int num = ix.size(0); const int ht = disps.size(1); const int wd = disps.size(2); torch::Tensor counter = torch::zeros({num, ht, wd}, disps.options()); dim3 blocks(num, 6, NUM_BLOCKS(ht * wd)); depth_filter_kernel<<>>( poses.packed_accessor32(), disps.packed_accessor32(), intrinsics.packed_accessor32(), ix.packed_accessor32(), thresh.packed_accessor32(), counter.packed_accessor32()); return counter; } torch::Tensor iproj_cuda( torch::Tensor poses, torch::Tensor disps, torch::Tensor intrinsics) { const int nm = disps.size(0); const int ht = disps.size(1); const int wd = disps.size(2); auto opts = disps.options(); torch::Tensor points = torch::zeros({nm, ht, wd, 3}, opts); dim3 blocks(nm, NUM_BLOCKS(ht * wd)); iproj_kernel<<>>( poses.packed_accessor32(), disps.packed_accessor32(), intrinsics.packed_accessor32(), points.packed_accessor32()); return points; } void BACore::init(torch::Tensor _poses, torch::Tensor _disps, torch::Tensor _intrinsics, torch::Tensor _disps_sens, torch::Tensor _targets, torch::Tensor _weights, torch::Tensor _eta, torch::Tensor _ii, torch::Tensor _jj, const int _t0, const int _t1, const int iterations, const float _lm, const float _ep, const bool motion_only) { poses = _poses; disps = _disps; intrinsics = _intrinsics; disps_sens = _disps_sens; targets = _targets; weights = _weights; eta = _eta; ii = _ii; jj = _jj; t0 = _t0; t1 = _t1; lm = _lm; ep = _ep; auto opts = poses.options(); const int num = ii.size(0); const int ht = disps.size(1); const int wd = disps.size(2); ts = torch::arange(t0, t1).to(torch::kCUDA); ii_exp = torch::cat({ts, ii}, 0); jj_exp = torch::cat({ts, jj}, 0); kuniq = torch::_unique(ii_exp, true, true); kx = std::get<0>(kuniq); kk_exp = std::get<1>(kuniq); // 不重复元素的索引 // initialize buffers Hs = torch::zeros({4, num, 6, 6}, opts); vs = torch::zeros({2, num, 6}, opts); Eii = torch::zeros({num, 6, ht * wd}, opts); Eij = torch::zeros({num, 6, ht * wd}, opts); Cii = torch::zeros({num, ht * wd}, opts); wi = torch::zeros({num, ht * wd}, opts); } void BACore::hessian(torch::Tensor H, torch::Tensor v) { const int num = ii.size(0); const int ht = disps.size(1); const int wd = disps.size(2); projective_transform_kernel<<>>( targets.packed_accessor32(), weights.packed_accessor32(), poses.packed_accessor32(), disps.packed_accessor32(), intrinsics.packed_accessor32(), ii.packed_accessor32(), jj.packed_accessor32(), Hs.packed_accessor32(), vs.packed_accessor32(), Eii.packed_accessor32(), Eij.packed_accessor32(), Cii.packed_accessor32(), wi.packed_accessor32()); // pose x pose block SparseBlock A(t1 - t0, 6); A.update_lhs(Hs.reshape({-1, 6, 6}), torch::cat({ii, ii, jj, jj}) - t0, torch::cat({ii, jj, ii, jj}) - t0); A.update_rhs(vs.reshape({-1, 6}), torch::cat({ii, jj}) - t0); // add depth residual if there are depth sensor measurements // const float alpha = 0.05; const float alpha = 0.001; m = (disps_sens.index({kx, "..."}) > 0).to(torch::TensorOptions().dtype(torch::kFloat32)).view({-1, ht*wd}); C = accum_cuda(Cii, ii, kx) + m * alpha + (1 - m) * eta.view({-1, ht*wd}); w = accum_cuda(wi, ii, kx) - m * alpha * (disps.index({kx, "..."}) - disps_sens.index({kx, "..."})).view({-1, ht*wd}); Q = 1.0 / C; Ei = accum_cuda(Eii.view({num, 6*ht*wd}), ii, ts).view({t1-t0, 6, ht*wd}); E = torch::cat({Ei, Eij}, 0); SparseBlock S = schur_block(E, Q, w, ii_exp, jj_exp, kk_exp, t0, t1); SparseBlock A_S = A-S; // This is a CPU matrix. // Extract information matrix Eigen::MatrixXd Ad(A_S.A); Eigen::VectorXd vd(A_S.b); auto H_accessor = H.accessor(); auto v_accessor = v.accessor(); for(int i =0;i(); auto v_accessor = v.accessor(); for (int i = 0; i < H_accessor.size(0); i++) { for (int j = 0; j < H_accessor.size(1); j++) { Ad(i, j) = H_accessor[i][j]; } vd(i) = v_accessor[i]; } dx = solveDenseD(Ad, vd, t1 - t0, 6, lm, ep); } std::vector BACore::retract(torch::Tensor _dx) { const int num = ii.size(0); const int ht = disps.size(1); const int wd = disps.size(2); auto opts = poses.options(); auto _dx_accessor = _dx.accessor(); Eigen::VectorXd x((t1-t0)*6); for(int i = 0 ;i<(t1-t0)*6;i++) x(i) = _dx_accessor[i]; dx = torch::from_blob(x.data(), {t1-t0, 6}, torch::TensorOptions() .dtype(torch::kFloat64)).to(torch::kCUDA).to(torch::kFloat32); // dx = _dx.detach().to(torch::kCUDA).to(torch::kFloat32); torch::Tensor ix = jj_exp - t0; torch::Tensor dw = torch::zeros({ix.size(0), ht*wd}, opts); EvT6x1_kernel<<>>( E.packed_accessor32(), dx.packed_accessor32(), ix.packed_accessor32(), dw.packed_accessor32()); dz = Q * (w - accum_cuda(dw, ii_exp, kx)); // update poses pose_retr_kernel<<<1, THREADS>>>( poses.packed_accessor32(), dx.packed_accessor32(), t0, t1); // update disparity maps disp_retr_kernel<<>>( disps.packed_accessor32(), dz.packed_accessor32(), kx.packed_accessor32()); return {dx, dz}; } ================================================ FILE: visualization/check_reconstruction_kitti.py ================================================ import numpy as np import cv2 import open3d as o3d import matplotlib.pyplot as plt from lietorch import SO3, SE3, Sim3 from scipy.spatial.transform import Rotation as R import copy import pickle import re CAM_POINTS = np.array([ [ 0, 0, 0], [-1, -1, 1.5], [ 1, -1, 1.5], [ 1, 1, 1.5], [-1, 1, 1.5], [-0.5, 1, 1.5], [ 0.5, 1, 1.5], [ 0, 1.2, 1.5]]) CAM_LINES = np.array([ [1,2], [2,3], [3,4], [4,1], [1,0], [0,2], [3,0], [0,4], [5,7], [7,6]]) def create_camera_actor(g, scale=0.05): """ build open3d camera polydata """ camera_actor = o3d.geometry.LineSet( points=o3d.utility.Vector3dVector(scale * CAM_POINTS), lines=o3d.utility.Vector2iVector(CAM_LINES)) color = (g * 1.0, 0.5 * (1-g), 0.9 * (1-g)) camera_actor.paint_uniform_color(color) return camera_actor def create_point_actor(points, colors): """ open3d point cloud from numpy array """ point_cloud = o3d.geometry.PointCloud() point_cloud.points = o3d.utility.Vector3dVector(points) # if colors != None: point_cloud.colors = o3d.utility.Vector3dVector(colors) return point_cloud rotating = False def str2array(ss): elem = re.sub('\s\s+',' ',ss).split(' ') num=[] for e in elem: num.append(float(e)) return np.array(num) f = open(r'./results/0002.pkl','rb') dump_data= pickle.load(f) print(dump_data.keys()) vis = o3d.visualization.VisualizerWithKeyCallback() vis.create_window(window_name='123') vis.get_render_option().point_size = 1 opt = vis.get_render_option() opt.background_color = np.asarray([0,0,0]) def key_action_callback(vis, action, mods): print(action) if action == 1: # key down ctr = vis.get_view_control() view_params = ctr.convert_to_view_parameters() print(view_params) return True def save_callback(vis, action, mods): print(action) if action == 1: # key down vis.capture_screen_image("2.PNG") return True # key_action_callback will be triggered when there's a keyboard press, release or repeat event vis.register_key_action_callback(32, key_action_callback) # space vis.register_key_action_callback(264, save_callback) # down for ix in sorted(dump_data['points'].keys()): if ix < 550 : continue if ix > 750 : continue dd=dump_data['points'][ix] pts = dd['pts'] clr = dd['clr'] pose = dump_data['cameras'][ix] pose[0:3,3] = pose[0:3,3] # print(pose) npts = np.asarray(pts) nclr = np.asarray(clr) mask0 = npts[:,2] -5.0 mask1 = np.logical_or(npts_c[:,1]> -0.0,nclr[:,0]<0.4) mask2 = npts_c[:,2] < 10.0 mask = np.logical_and(np.logical_and(mask0,mask1),mask2) point_actor = create_point_actor(pts[mask], clr[mask]) vis.add_geometry(point_actor) cam_actor = create_camera_actor(1.0,0.5) cam_actor.transform(pose) vis.add_geometry(cam_actor) ctr = vis.get_view_control() camera_params = ctr.convert_to_pinhole_camera_parameters() pose = dump_data['cameras'][ix] theta = 15/180.0*math.pi view_pose = np.array([[1.0,0.0,0.0,0.0], [0.0,math.cos(theta),math.sin(theta),-5.0], [0.0,-math.sin(theta),math.cos(theta),-30.0], [0.0,0.0,0.0,1.0]]) pose = np.matmul(pose,view_pose) camera_params.extrinsic = np.linalg.inv(pose) print(camera_params.intrinsic) ctr.convert_from_pinhole_camera_parameters(camera_params) vis.poll_events() vis.update_renderer() # vis.capture_screen_image("gif/%010d.jpg"%ix) # vis.run() vis.destroy_window() quit() ================================================ FILE: visualization/check_reconstruction_tumvi.py ================================================ import numpy as np import cv2 import open3d as o3d import matplotlib.pyplot as plt from lietorch import SO3, SE3, Sim3 from scipy.spatial.transform import Rotation as R import copy import pickle import re CAM_POINTS = np.array([ [ 0, 0, 0], [-1, -1, 1.5], [ 1, -1, 1.5], [ 1, 1, 1.5], [-1, 1, 1.5], [-0.5, 1, 1.5], [ 0.5, 1, 1.5], [ 0, 1.2, 1.5]]) CAM_LINES = np.array([ [1,2], [2,3], [3,4], [4,1], [1,0], [0,2], [3,0], [0,4], [5,7], [7,6]]) def create_camera_actor(g, scale=0.05): """ build open3d camera polydata """ camera_actor = o3d.geometry.LineSet( points=o3d.utility.Vector3dVector(scale * CAM_POINTS), lines=o3d.utility.Vector2iVector(CAM_LINES)) color = (g * 1.0, 0.5 * (1-g), 0.9 * (1-g)) camera_actor.paint_uniform_color(color) return camera_actor def create_point_actor(points, colors): """ open3d point cloud from numpy array """ point_cloud = o3d.geometry.PointCloud() point_cloud.points = o3d.utility.Vector3dVector(points) # if colors != None: point_cloud.colors = o3d.utility.Vector3dVector(colors) return point_cloud rotating = False def str2array(ss): elem = re.sub('\s\s+',' ',ss).split(' ') num=[] for e in elem: num.append(float(e)) return np.array(num) f = open(r'./reconstructions/outdoors6.pkl','rb') dump_data= pickle.load(f) print(dump_data.keys()) vis = o3d.visualization.VisualizerWithKeyCallback() vis.create_window(window_name='123') vis.get_render_option().point_size = 2 opt = vis.get_render_option() opt.background_color = np.asarray([0,0,0]) def key_action_callback(vis, action, mods): print(action) if action == 1: # key down ctr = vis.get_view_control() view_params = ctr.convert_to_view_parameters() print(view_params) return True # key_action_callback will be triggered when there's a keyboard press, release or repeat event vis.register_key_action_callback(32, key_action_callback) # space # animation_callback is always repeatedly called by the visualizer for ix in sorted(dump_data['points'].keys()): if ix < 1800 : continue if ix > 2800 : continue dd=dump_data['points'][ix] pts = dd['pts'] # * 17.0 clr = dd['clr'] pose = dump_data['cameras'][ix] pose[0:3,3] = pose[0:3,3] #* 17.0 npts_c = np.matmul(pose[0:3,0:3].T,(pts-pose[0:3,3]).T).T npts = np.asarray(pts) nclr = np.asarray(clr) mask0 = npts_c[:,1]> -5.0 mask1 = np.logical_or(npts_c[:,1]> -0.0,nclr[:,0]<0.4) mask2 = npts_c[:,2] < 10.0 mask = np.logical_and(np.logical_and(mask0,mask1),mask2) point_actor = create_point_actor(pts[mask], clr[mask]) vis.add_geometry(point_actor) cam_actor = create_camera_actor(1.0,0.05) cam_actor.transform(pose) vis.add_geometry(cam_actor) print('[INFO] Use [ , ] to adjust the perspective !!!') print('[INFO] Use + , - to adjust the point size !!!') vis.run() vis.destroy_window() quit() ================================================ FILE: visualization/check_reconstruction_tumvi_animation.py ================================================ import numpy as np import cv2 import open3d as o3d import matplotlib.pyplot as plt from lietorch import SO3, SE3, Sim3 from scipy.spatial.transform import Rotation as R import copy import pickle import re import math CAM_POINTS = np.array([ [ 0, 0, 0], [-1, -1, 1.5], [ 1, -1, 1.5], [ 1, 1, 1.5], [-1, 1, 1.5], [-0.5, 1, 1.5], [ 0.5, 1, 1.5], [ 0, 1.2, 1.5]]) CAM_LINES = np.array([ [1,2], [2,3], [3,4], [4,1], [1,0], [0,2], [3,0], [0,4], [5,7], [7,6]]) def create_camera_actor(g, scale=0.05): """ build open3d camera polydata """ camera_actor = o3d.geometry.LineSet( points=o3d.utility.Vector3dVector(scale * CAM_POINTS), lines=o3d.utility.Vector2iVector(CAM_LINES)) color = (g * 1.0, 0.5 * (1-g), 0.9 * (1-g)) camera_actor.paint_uniform_color(color) return camera_actor def create_point_actor(points, colors): """ open3d point cloud from numpy array """ point_cloud = o3d.geometry.PointCloud() point_cloud.points = o3d.utility.Vector3dVector(points) # if colors != None: point_cloud.colors = o3d.utility.Vector3dVector(colors) return point_cloud rotating = False def str2array(ss): elem = re.sub('\s\s+',' ',ss).split(' ') num=[] for e in elem: num.append(float(e)) return np.array(num) f = open(r'./results/outdoors6.pkl','rb') dump_data= pickle.load(f) print(dump_data.keys()) vis = o3d.visualization.VisualizerWithKeyCallback() vis.create_window(window_name='123') vis.get_render_option().point_size = 4 opt = vis.get_render_option() opt.background_color = np.asarray([0,0,0]) def key_action_callback(vis, action, mods): print(action) if action == 1: # key down ctr = vis.get_view_control() view_params = ctr.convert_to_view_parameters() print(view_params) return True vis.register_key_action_callback(32, key_action_callback) # space for ix in sorted(dump_data['points'].keys()): if ix < 520 : continue if ix > 920 : continue # if ix < 800 : continue # if ix > 1800 : continue dd=dump_data['points'][ix] pts = dd['pts'] # * 17.0 clr = dd['clr'] pose = dump_data['cameras'][ix] pose[0:3,3] = pose[0:3,3] npts_c = np.matmul(pose[0:3,0:3].T,(pts-pose[0:3,3]).T).T npts = np.asarray(pts) nclr = np.asarray(clr) mask0 = npts_c[:,1]> -5.0 mask1 = np.logical_or(npts_c[:,1]> -0.0,nclr[:,0]<0.4) mask2 = npts_c[:,2] < 10.0 mask = np.logical_and(np.logical_and(mask0,mask1),mask2) point_actor = create_point_actor(pts[mask], clr[mask]) vis.add_geometry(point_actor) cam_actor = create_camera_actor(1.0,0.3) cam_actor.transform(pose) vis.add_geometry(cam_actor) ctr = vis.get_view_control() camera_params = ctr.convert_to_pinhole_camera_parameters() pose = dump_data['cameras'][ix] theta = 30/180.0*math.pi view_pose = np.array([[1.0,0.0,0.0,0.0], [0.0,math.cos(theta),math.sin(theta),-15.0 * 0.7], [0.0,-math.sin(theta),math.cos(theta),-30.0 * 0.7], [0.0,0.0,0.0,1.0]]) if ix > 5: rotvec_sum = np.array([0.0,0.0,0.0]) t_sum = np.array([0.0,0.0,0.0]) for ii in range(5): RR = dump_data['cameras'][ix-4+ii][0:3,0:3] rotvec_sum += R.as_rotvec(R.from_matrix(RR)) t_sum += dump_data['cameras'][ix-4+ii][0:3,3] rotvec = rotvec_sum/5.0 pose[0:3,0:3] = R.from_rotvec(rotvec).as_matrix() pose[0:3,3] = t_sum/5.0 pose = np.matmul(pose,view_pose) camera_params.extrinsic = np.linalg.inv(pose) print(camera_params.intrinsic) ctr.convert_from_pinhole_camera_parameters(camera_params) vis.poll_events() vis.update_renderer() # vis.capture_screen_image("tum_gif/%010d.jpg"%ix) vis.destroy_window() quit()