Spaces:
Running
on
Zero
Running
on
Zero
JianyuanWang
commited on
Commit
•
8866a87
1
Parent(s):
5e437cf
upload vggsfm
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- vggsfm/.gitignore +143 -0
- vggsfm/CHANGELOG.txt +19 -0
- vggsfm/CODE_OF_CONDUCT.md +80 -0
- vggsfm/CONTRIBUTING.md +31 -0
- vggsfm/LICENSE.txt +399 -0
- vggsfm/README.md +117 -0
- vggsfm/assets/ui.png +0 -0
- vggsfm/cfgs/demo.yaml +80 -0
- vggsfm/demo.py +489 -0
- vggsfm/examples/apple/images/frame000007.jpg +0 -0
- vggsfm/examples/apple/images/frame000012.jpg +0 -0
- vggsfm/examples/apple/images/frame000017.jpg +0 -0
- vggsfm/examples/apple/images/frame000019.jpg +0 -0
- vggsfm/examples/apple/images/frame000024.jpg +0 -0
- vggsfm/examples/apple/images/frame000025.jpg +0 -0
- vggsfm/examples/apple/images/frame000043.jpg +0 -0
- vggsfm/examples/apple/images/frame000052.jpg +0 -0
- vggsfm/examples/apple/images/frame000070.jpg +0 -0
- vggsfm/examples/apple/images/frame000077.jpg +0 -0
- vggsfm/examples/apple/images/frame000085.jpg +0 -0
- vggsfm/examples/apple/images/frame000096.jpg +0 -0
- vggsfm/examples/apple/images/frame000128.jpg +0 -0
- vggsfm/examples/apple/images/frame000145.jpg +0 -0
- vggsfm/examples/apple/images/frame000160.jpg +0 -0
- vggsfm/examples/apple/images/frame000162.jpg +0 -0
- vggsfm/examples/apple/images/frame000168.jpg +0 -0
- vggsfm/examples/apple/images/frame000172.jpg +0 -0
- vggsfm/examples/apple/images/frame000191.jpg +0 -0
- vggsfm/examples/apple/images/frame000200.jpg +0 -0
- vggsfm/examples/british_museum/images/29057984_287139632.jpg +0 -0
- vggsfm/examples/british_museum/images/32630292_7166579210.jpg +0 -0
- vggsfm/examples/british_museum/images/45839934_4117745134.jpg +0 -0
- vggsfm/examples/british_museum/images/51004432_567773767.jpg +0 -0
- vggsfm/examples/british_museum/images/62620282_3728576515.jpg +0 -0
- vggsfm/examples/british_museum/images/71931631_7212707886.jpg +0 -0
- vggsfm/examples/british_museum/images/78600497_407639599.jpg +0 -0
- vggsfm/examples/british_museum/images/80340357_5029510336.jpg +0 -0
- vggsfm/examples/british_museum/images/81272348_2712949069.jpg +0 -0
- vggsfm/examples/british_museum/images/93266801_2335569192.jpg +0 -0
- vggsfm/examples/cake/images/frame000020.jpg +0 -0
- vggsfm/examples/cake/images/frame000069.jpg +0 -0
- vggsfm/examples/cake/images/frame000096.jpg +0 -0
- vggsfm/examples/cake/images/frame000112.jpg +0 -0
- vggsfm/examples/cake/images/frame000146.jpg +0 -0
- vggsfm/examples/cake/images/frame000149.jpg +0 -0
- vggsfm/examples/cake/images/frame000166.jpg +0 -0
- vggsfm/examples/cake/images/frame000169.jpg +0 -0
- vggsfm/install.sh +47 -0
- vggsfm/minipytorch3d/__init__.py +0 -0
- vggsfm/minipytorch3d/cameras.py +1722 -0
vggsfm/.gitignore
ADDED
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.hydra/
|
2 |
+
output/
|
3 |
+
|
4 |
+
# Byte-compiled / optimized / DLL files
|
5 |
+
__pycache__/
|
6 |
+
*.py[cod]
|
7 |
+
*$py.class
|
8 |
+
|
9 |
+
# C extensions
|
10 |
+
*.so
|
11 |
+
|
12 |
+
# Distribution / packaging
|
13 |
+
.Python
|
14 |
+
build/
|
15 |
+
develop-eggs/
|
16 |
+
dist/
|
17 |
+
downloads/
|
18 |
+
eggs/
|
19 |
+
.eggs/
|
20 |
+
lib/
|
21 |
+
lib64/
|
22 |
+
parts/
|
23 |
+
sdist/
|
24 |
+
var/
|
25 |
+
wheels/
|
26 |
+
pip-wheel-metadata/
|
27 |
+
share/python-wheels/
|
28 |
+
*.egg-info/
|
29 |
+
.installed.cfg
|
30 |
+
*.egg
|
31 |
+
MANIFEST
|
32 |
+
|
33 |
+
# PyInstaller
|
34 |
+
# Usually these files are written by a python script from a template
|
35 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
36 |
+
*.manifest
|
37 |
+
*.spec
|
38 |
+
|
39 |
+
# Installer logs
|
40 |
+
pip-log.txt
|
41 |
+
pip-delete-this-directory.txt
|
42 |
+
|
43 |
+
# Unit test / coverage reports
|
44 |
+
htmlcov/
|
45 |
+
.tox/
|
46 |
+
.nox/
|
47 |
+
.coverage
|
48 |
+
.coverage.*
|
49 |
+
.cache
|
50 |
+
nosetests.xml
|
51 |
+
coverage.xml
|
52 |
+
*.cover
|
53 |
+
*.py,cover
|
54 |
+
.hypothesis/
|
55 |
+
.pytest_cache/
|
56 |
+
cover/
|
57 |
+
|
58 |
+
# Translations
|
59 |
+
*.mo
|
60 |
+
*.pot
|
61 |
+
|
62 |
+
# Django stuff:
|
63 |
+
*.log
|
64 |
+
local_settings.py
|
65 |
+
db.sqlite3
|
66 |
+
db.sqlite3-journal
|
67 |
+
|
68 |
+
# Flask stuff:
|
69 |
+
instance/
|
70 |
+
.webassets-cache
|
71 |
+
|
72 |
+
# Scrapy stuff:
|
73 |
+
.scrapy
|
74 |
+
|
75 |
+
# Sphinx documentation
|
76 |
+
docs/_build/
|
77 |
+
|
78 |
+
# PyBuilder
|
79 |
+
target/
|
80 |
+
|
81 |
+
# Jupyter Notebook
|
82 |
+
.ipynb_checkpoints
|
83 |
+
|
84 |
+
# IPython
|
85 |
+
profile_default/
|
86 |
+
ipython_config.py
|
87 |
+
|
88 |
+
# pyenv
|
89 |
+
.python-version
|
90 |
+
|
91 |
+
# pipenv
|
92 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
93 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
94 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
95 |
+
# install all needed dependencies.
|
96 |
+
#Pipfile.lock
|
97 |
+
|
98 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
99 |
+
__pypackages__/
|
100 |
+
|
101 |
+
# Celery stuff
|
102 |
+
celerybeat-schedule
|
103 |
+
celerybeat.pid
|
104 |
+
|
105 |
+
# SageMath parsed files
|
106 |
+
*.sage.py
|
107 |
+
|
108 |
+
# Environments
|
109 |
+
.env
|
110 |
+
.venv
|
111 |
+
env/
|
112 |
+
venv/
|
113 |
+
ENV/
|
114 |
+
env.bak/
|
115 |
+
venv.bak/
|
116 |
+
|
117 |
+
# Spyder project settings
|
118 |
+
.spyderproject
|
119 |
+
.spyproject
|
120 |
+
|
121 |
+
# Rope project settings
|
122 |
+
.ropeproject
|
123 |
+
|
124 |
+
# mkdocs documentation
|
125 |
+
/site
|
126 |
+
|
127 |
+
# mypy
|
128 |
+
.mypy_cache/
|
129 |
+
.dmypy.json
|
130 |
+
dmypy.json
|
131 |
+
|
132 |
+
# Pyre type checker
|
133 |
+
.pyre/
|
134 |
+
|
135 |
+
# pytype static type analyzer
|
136 |
+
.pytype/
|
137 |
+
|
138 |
+
# Profiling data
|
139 |
+
.prof
|
140 |
+
|
141 |
+
# Folder specific to your needs
|
142 |
+
**/tmp/
|
143 |
+
**/outputs/
|
vggsfm/CHANGELOG.txt
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
VGGSfM 2.0
|
2 |
+
|
3 |
+
* More powerful camera and track predictor
|
4 |
+
* Save the GPU memory usage by around 50%
|
5 |
+
* Add Poselib as an option for Fundamental Matrix Estimation
|
6 |
+
* Support COLMAP-tyle output
|
7 |
+
* Provide focal length in pixel
|
8 |
+
* Normalize the scene after each BA
|
9 |
+
* Remove preliminary_cameras for simplicity
|
10 |
+
* Switch to lightglue instead of gluefactory
|
11 |
+
* Upgrade pycolmap from 0.5.0 to 0.6.1
|
12 |
+
|
13 |
+
|
14 |
+
|
15 |
+
TODO:
|
16 |
+
1. Make precision consistent
|
17 |
+
2. Provide a step-by-step instruction for using VGGSfM for 3D Gaussian
|
18 |
+
3. Support shared cameras
|
19 |
+
|
vggsfm/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Code of Conduct
|
2 |
+
|
3 |
+
## Our Pledge
|
4 |
+
|
5 |
+
In the interest of fostering an open and welcoming environment, we as
|
6 |
+
contributors and maintainers pledge to make participation in our project and
|
7 |
+
our community a harassment-free experience for everyone, regardless of age, body
|
8 |
+
size, disability, ethnicity, sex characteristics, gender identity and expression,
|
9 |
+
level of experience, education, socio-economic status, nationality, personal
|
10 |
+
appearance, race, religion, or sexual identity and orientation.
|
11 |
+
|
12 |
+
## Our Standards
|
13 |
+
|
14 |
+
Examples of behavior that contributes to creating a positive environment
|
15 |
+
include:
|
16 |
+
|
17 |
+
* Using welcoming and inclusive language
|
18 |
+
* Being respectful of differing viewpoints and experiences
|
19 |
+
* Gracefully accepting constructive criticism
|
20 |
+
* Focusing on what is best for the community
|
21 |
+
* Showing empathy towards other community members
|
22 |
+
|
23 |
+
Examples of unacceptable behavior by participants include:
|
24 |
+
|
25 |
+
* The use of sexualized language or imagery and unwelcome sexual attention or
|
26 |
+
advances
|
27 |
+
* Trolling, insulting/derogatory comments, and personal or political attacks
|
28 |
+
* Public or private harassment
|
29 |
+
* Publishing others' private information, such as a physical or electronic
|
30 |
+
address, without explicit permission
|
31 |
+
* Other conduct which could reasonably be considered inappropriate in a
|
32 |
+
professional setting
|
33 |
+
|
34 |
+
## Our Responsibilities
|
35 |
+
|
36 |
+
Project maintainers are responsible for clarifying the standards of acceptable
|
37 |
+
behavior and are expected to take appropriate and fair corrective action in
|
38 |
+
response to any instances of unacceptable behavior.
|
39 |
+
|
40 |
+
Project maintainers have the right and responsibility to remove, edit, or
|
41 |
+
reject comments, commits, code, wiki edits, issues, and other contributions
|
42 |
+
that are not aligned to this Code of Conduct, or to ban temporarily or
|
43 |
+
permanently any contributor for other behaviors that they deem inappropriate,
|
44 |
+
threatening, offensive, or harmful.
|
45 |
+
|
46 |
+
## Scope
|
47 |
+
|
48 |
+
This Code of Conduct applies within all project spaces, and it also applies when
|
49 |
+
an individual is representing the project or its community in public spaces.
|
50 |
+
Examples of representing a project or community include using an official
|
51 |
+
project e-mail address, posting via an official social media account, or acting
|
52 |
+
as an appointed representative at an online or offline event. Representation of
|
53 |
+
a project may be further defined and clarified by project maintainers.
|
54 |
+
|
55 |
+
This Code of Conduct also applies outside the project spaces when there is a
|
56 |
+
reasonable belief that an individual's behavior may have a negative impact on
|
57 |
+
the project or its community.
|
58 |
+
|
59 |
+
## Enforcement
|
60 |
+
|
61 |
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
62 |
+
reported by contacting the project team at <opensource-conduct@fb.com>. All
|
63 |
+
complaints will be reviewed and investigated and will result in a response that
|
64 |
+
is deemed necessary and appropriate to the circumstances. The project team is
|
65 |
+
obligated to maintain confidentiality with regard to the reporter of an incident.
|
66 |
+
Further details of specific enforcement policies may be posted separately.
|
67 |
+
|
68 |
+
Project maintainers who do not follow or enforce the Code of Conduct in good
|
69 |
+
faith may face temporary or permanent repercussions as determined by other
|
70 |
+
members of the project's leadership.
|
71 |
+
|
72 |
+
## Attribution
|
73 |
+
|
74 |
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
75 |
+
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
|
76 |
+
|
77 |
+
[homepage]: https://www.contributor-covenant.org
|
78 |
+
|
79 |
+
For answers to common questions about this code of conduct, see
|
80 |
+
https://www.contributor-covenant.org/faq
|
vggsfm/CONTRIBUTING.md
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Contributing to PoseDiffusion
|
2 |
+
We want to make contributing to this project as easy and transparent as
|
3 |
+
possible.
|
4 |
+
|
5 |
+
## Pull Requests
|
6 |
+
We actively welcome your pull requests.
|
7 |
+
|
8 |
+
1. Fork the repo and create your branch from `main`.
|
9 |
+
2. If you've added code that should be tested, add tests.
|
10 |
+
3. If you've changed APIs, update the documentation.
|
11 |
+
4. Ensure the test suite passes.
|
12 |
+
5. Make sure your code lints.
|
13 |
+
6. If you haven't already, complete the Contributor License Agreement ("CLA").
|
14 |
+
|
15 |
+
## Contributor License Agreement ("CLA")
|
16 |
+
In order to accept your pull request, we need you to submit a CLA. You only need
|
17 |
+
to do this once to work on any of Facebook's open source projects.
|
18 |
+
|
19 |
+
Complete your CLA here: <https://code.facebook.com/cla>
|
20 |
+
|
21 |
+
## Issues
|
22 |
+
We use GitHub issues to track public bugs. Please ensure your description is
|
23 |
+
clear and has sufficient instructions to be able to reproduce the issue.
|
24 |
+
|
25 |
+
Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
|
26 |
+
disclosure of security bugs. In those cases, please go through the process
|
27 |
+
outlined on that page and do not file a public issue.
|
28 |
+
|
29 |
+
## License
|
30 |
+
By contributing to PoseDiffusion, you agree that your contributions will be licensed
|
31 |
+
under the LICENSE file in the root directory of this source tree.
|
vggsfm/LICENSE.txt
ADDED
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Attribution-NonCommercial 4.0 International
|
2 |
+
|
3 |
+
=======================================================================
|
4 |
+
|
5 |
+
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
6 |
+
does not provide legal services or legal advice. Distribution of
|
7 |
+
Creative Commons public licenses does not create a lawyer-client or
|
8 |
+
other relationship. Creative Commons makes its licenses and related
|
9 |
+
information available on an "as-is" basis. Creative Commons gives no
|
10 |
+
warranties regarding its licenses, any material licensed under their
|
11 |
+
terms and conditions, or any related information. Creative Commons
|
12 |
+
disclaims all liability for damages resulting from their use to the
|
13 |
+
fullest extent possible.
|
14 |
+
|
15 |
+
Using Creative Commons Public Licenses
|
16 |
+
|
17 |
+
Creative Commons public licenses provide a standard set of terms and
|
18 |
+
conditions that creators and other rights holders may use to share
|
19 |
+
original works of authorship and other material subject to copyright
|
20 |
+
and certain other rights specified in the public license below. The
|
21 |
+
following considerations are for informational purposes only, are not
|
22 |
+
exhaustive, and do not form part of our licenses.
|
23 |
+
|
24 |
+
Considerations for licensors: Our public licenses are
|
25 |
+
intended for use by those authorized to give the public
|
26 |
+
permission to use material in ways otherwise restricted by
|
27 |
+
copyright and certain other rights. Our licenses are
|
28 |
+
irrevocable. Licensors should read and understand the terms
|
29 |
+
and conditions of the license they choose before applying it.
|
30 |
+
Licensors should also secure all rights necessary before
|
31 |
+
applying our licenses so that the public can reuse the
|
32 |
+
material as expected. Licensors should clearly mark any
|
33 |
+
material not subject to the license. This includes other CC-
|
34 |
+
licensed material, or material used under an exception or
|
35 |
+
limitation to copyright. More considerations for licensors:
|
36 |
+
wiki.creativecommons.org/Considerations_for_licensors
|
37 |
+
|
38 |
+
Considerations for the public: By using one of our public
|
39 |
+
licenses, a licensor grants the public permission to use the
|
40 |
+
licensed material under specified terms and conditions. If
|
41 |
+
the licensor's permission is not necessary for any reason--for
|
42 |
+
example, because of any applicable exception or limitation to
|
43 |
+
copyright--then that use is not regulated by the license. Our
|
44 |
+
licenses grant only permissions under copyright and certain
|
45 |
+
other rights that a licensor has authority to grant. Use of
|
46 |
+
the licensed material may still be restricted for other
|
47 |
+
reasons, including because others have copyright or other
|
48 |
+
rights in the material. A licensor may make special requests,
|
49 |
+
such as asking that all changes be marked or described.
|
50 |
+
Although not required by our licenses, you are encouraged to
|
51 |
+
respect those requests where reasonable. More_considerations
|
52 |
+
for the public:
|
53 |
+
wiki.creativecommons.org/Considerations_for_licensees
|
54 |
+
|
55 |
+
=======================================================================
|
56 |
+
|
57 |
+
Creative Commons Attribution-NonCommercial 4.0 International Public
|
58 |
+
License
|
59 |
+
|
60 |
+
By exercising the Licensed Rights (defined below), You accept and agree
|
61 |
+
to be bound by the terms and conditions of this Creative Commons
|
62 |
+
Attribution-NonCommercial 4.0 International Public License ("Public
|
63 |
+
License"). To the extent this Public License may be interpreted as a
|
64 |
+
contract, You are granted the Licensed Rights in consideration of Your
|
65 |
+
acceptance of these terms and conditions, and the Licensor grants You
|
66 |
+
such rights in consideration of benefits the Licensor receives from
|
67 |
+
making the Licensed Material available under these terms and
|
68 |
+
conditions.
|
69 |
+
|
70 |
+
Section 1 -- Definitions.
|
71 |
+
|
72 |
+
a. Adapted Material means material subject to Copyright and Similar
|
73 |
+
Rights that is derived from or based upon the Licensed Material
|
74 |
+
and in which the Licensed Material is translated, altered,
|
75 |
+
arranged, transformed, or otherwise modified in a manner requiring
|
76 |
+
permission under the Copyright and Similar Rights held by the
|
77 |
+
Licensor. For purposes of this Public License, where the Licensed
|
78 |
+
Material is a musical work, performance, or sound recording,
|
79 |
+
Adapted Material is always produced where the Licensed Material is
|
80 |
+
synched in timed relation with a moving image.
|
81 |
+
|
82 |
+
b. Adapter's License means the license You apply to Your Copyright
|
83 |
+
and Similar Rights in Your contributions to Adapted Material in
|
84 |
+
accordance with the terms and conditions of this Public License.
|
85 |
+
|
86 |
+
c. Copyright and Similar Rights means copyright and/or similar rights
|
87 |
+
closely related to copyright including, without limitation,
|
88 |
+
performance, broadcast, sound recording, and Sui Generis Database
|
89 |
+
Rights, without regard to how the rights are labeled or
|
90 |
+
categorized. For purposes of this Public License, the rights
|
91 |
+
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
92 |
+
Rights.
|
93 |
+
d. Effective Technological Measures means those measures that, in the
|
94 |
+
absence of proper authority, may not be circumvented under laws
|
95 |
+
fulfilling obligations under Article 11 of the WIPO Copyright
|
96 |
+
Treaty adopted on December 20, 1996, and/or similar international
|
97 |
+
agreements.
|
98 |
+
|
99 |
+
e. Exceptions and Limitations means fair use, fair dealing, and/or
|
100 |
+
any other exception or limitation to Copyright and Similar Rights
|
101 |
+
that applies to Your use of the Licensed Material.
|
102 |
+
|
103 |
+
f. Licensed Material means the artistic or literary work, database,
|
104 |
+
or other material to which the Licensor applied this Public
|
105 |
+
License.
|
106 |
+
|
107 |
+
g. Licensed Rights means the rights granted to You subject to the
|
108 |
+
terms and conditions of this Public License, which are limited to
|
109 |
+
all Copyright and Similar Rights that apply to Your use of the
|
110 |
+
Licensed Material and that the Licensor has authority to license.
|
111 |
+
|
112 |
+
h. Licensor means the individual(s) or entity(ies) granting rights
|
113 |
+
under this Public License.
|
114 |
+
|
115 |
+
i. NonCommercial means not primarily intended for or directed towards
|
116 |
+
commercial advantage or monetary compensation. For purposes of
|
117 |
+
this Public License, the exchange of the Licensed Material for
|
118 |
+
other material subject to Copyright and Similar Rights by digital
|
119 |
+
file-sharing or similar means is NonCommercial provided there is
|
120 |
+
no payment of monetary compensation in connection with the
|
121 |
+
exchange.
|
122 |
+
|
123 |
+
j. Share means to provide material to the public by any means or
|
124 |
+
process that requires permission under the Licensed Rights, such
|
125 |
+
as reproduction, public display, public performance, distribution,
|
126 |
+
dissemination, communication, or importation, and to make material
|
127 |
+
available to the public including in ways that members of the
|
128 |
+
public may access the material from a place and at a time
|
129 |
+
individually chosen by them.
|
130 |
+
|
131 |
+
k. Sui Generis Database Rights means rights other than copyright
|
132 |
+
resulting from Directive 96/9/EC of the European Parliament and of
|
133 |
+
the Council of 11 March 1996 on the legal protection of databases,
|
134 |
+
as amended and/or succeeded, as well as other essentially
|
135 |
+
equivalent rights anywhere in the world.
|
136 |
+
|
137 |
+
l. You means the individual or entity exercising the Licensed Rights
|
138 |
+
under this Public License. Your has a corresponding meaning.
|
139 |
+
|
140 |
+
Section 2 -- Scope.
|
141 |
+
|
142 |
+
a. License grant.
|
143 |
+
|
144 |
+
1. Subject to the terms and conditions of this Public License,
|
145 |
+
the Licensor hereby grants You a worldwide, royalty-free,
|
146 |
+
non-sublicensable, non-exclusive, irrevocable license to
|
147 |
+
exercise the Licensed Rights in the Licensed Material to:
|
148 |
+
|
149 |
+
a. reproduce and Share the Licensed Material, in whole or
|
150 |
+
in part, for NonCommercial purposes only; and
|
151 |
+
|
152 |
+
b. produce, reproduce, and Share Adapted Material for
|
153 |
+
NonCommercial purposes only.
|
154 |
+
|
155 |
+
2. Exceptions and Limitations. For the avoidance of doubt, where
|
156 |
+
Exceptions and Limitations apply to Your use, this Public
|
157 |
+
License does not apply, and You do not need to comply with
|
158 |
+
its terms and conditions.
|
159 |
+
|
160 |
+
3. Term. The term of this Public License is specified in Section
|
161 |
+
6(a).
|
162 |
+
|
163 |
+
4. Media and formats; technical modifications allowed. The
|
164 |
+
Licensor authorizes You to exercise the Licensed Rights in
|
165 |
+
all media and formats whether now known or hereafter created,
|
166 |
+
and to make technical modifications necessary to do so. The
|
167 |
+
Licensor waives and/or agrees not to assert any right or
|
168 |
+
authority to forbid You from making technical modifications
|
169 |
+
necessary to exercise the Licensed Rights, including
|
170 |
+
technical modifications necessary to circumvent Effective
|
171 |
+
Technological Measures. For purposes of this Public License,
|
172 |
+
simply making modifications authorized by this Section 2(a)
|
173 |
+
(4) never produces Adapted Material.
|
174 |
+
|
175 |
+
5. Downstream recipients.
|
176 |
+
|
177 |
+
a. Offer from the Licensor -- Licensed Material. Every
|
178 |
+
recipient of the Licensed Material automatically
|
179 |
+
receives an offer from the Licensor to exercise the
|
180 |
+
Licensed Rights under the terms and conditions of this
|
181 |
+
Public License.
|
182 |
+
|
183 |
+
b. No downstream restrictions. You may not offer or impose
|
184 |
+
any additional or different terms or conditions on, or
|
185 |
+
apply any Effective Technological Measures to, the
|
186 |
+
Licensed Material if doing so restricts exercise of the
|
187 |
+
Licensed Rights by any recipient of the Licensed
|
188 |
+
Material.
|
189 |
+
|
190 |
+
6. No endorsement. Nothing in this Public License constitutes or
|
191 |
+
may be construed as permission to assert or imply that You
|
192 |
+
are, or that Your use of the Licensed Material is, connected
|
193 |
+
with, or sponsored, endorsed, or granted official status by,
|
194 |
+
the Licensor or others designated to receive attribution as
|
195 |
+
provided in Section 3(a)(1)(A)(i).
|
196 |
+
|
197 |
+
b. Other rights.
|
198 |
+
|
199 |
+
1. Moral rights, such as the right of integrity, are not
|
200 |
+
licensed under this Public License, nor are publicity,
|
201 |
+
privacy, and/or other similar personality rights; however, to
|
202 |
+
the extent possible, the Licensor waives and/or agrees not to
|
203 |
+
assert any such rights held by the Licensor to the limited
|
204 |
+
extent necessary to allow You to exercise the Licensed
|
205 |
+
Rights, but not otherwise.
|
206 |
+
|
207 |
+
2. Patent and trademark rights are not licensed under this
|
208 |
+
Public License.
|
209 |
+
|
210 |
+
3. To the extent possible, the Licensor waives any right to
|
211 |
+
collect royalties from You for the exercise of the Licensed
|
212 |
+
Rights, whether directly or through a collecting society
|
213 |
+
under any voluntary or waivable statutory or compulsory
|
214 |
+
licensing scheme. In all other cases the Licensor expressly
|
215 |
+
reserves any right to collect such royalties, including when
|
216 |
+
the Licensed Material is used other than for NonCommercial
|
217 |
+
purposes.
|
218 |
+
|
219 |
+
Section 3 -- License Conditions.
|
220 |
+
|
221 |
+
Your exercise of the Licensed Rights is expressly made subject to the
|
222 |
+
following conditions.
|
223 |
+
|
224 |
+
a. Attribution.
|
225 |
+
|
226 |
+
1. If You Share the Licensed Material (including in modified
|
227 |
+
form), You must:
|
228 |
+
|
229 |
+
a. retain the following if it is supplied by the Licensor
|
230 |
+
with the Licensed Material:
|
231 |
+
|
232 |
+
i. identification of the creator(s) of the Licensed
|
233 |
+
Material and any others designated to receive
|
234 |
+
attribution, in any reasonable manner requested by
|
235 |
+
the Licensor (including by pseudonym if
|
236 |
+
designated);
|
237 |
+
|
238 |
+
ii. a copyright notice;
|
239 |
+
|
240 |
+
iii. a notice that refers to this Public License;
|
241 |
+
|
242 |
+
iv. a notice that refers to the disclaimer of
|
243 |
+
warranties;
|
244 |
+
|
245 |
+
v. a URI or hyperlink to the Licensed Material to the
|
246 |
+
extent reasonably practicable;
|
247 |
+
|
248 |
+
b. indicate if You modified the Licensed Material and
|
249 |
+
retain an indication of any previous modifications; and
|
250 |
+
|
251 |
+
c. indicate the Licensed Material is licensed under this
|
252 |
+
Public License, and include the text of, or the URI or
|
253 |
+
hyperlink to, this Public License.
|
254 |
+
|
255 |
+
2. You may satisfy the conditions in Section 3(a)(1) in any
|
256 |
+
reasonable manner based on the medium, means, and context in
|
257 |
+
which You Share the Licensed Material. For example, it may be
|
258 |
+
reasonable to satisfy the conditions by providing a URI or
|
259 |
+
hyperlink to a resource that includes the required
|
260 |
+
information.
|
261 |
+
|
262 |
+
3. If requested by the Licensor, You must remove any of the
|
263 |
+
information required by Section 3(a)(1)(A) to the extent
|
264 |
+
reasonably practicable.
|
265 |
+
|
266 |
+
4. If You Share Adapted Material You produce, the Adapter's
|
267 |
+
License You apply must not prevent recipients of the Adapted
|
268 |
+
Material from complying with this Public License.
|
269 |
+
|
270 |
+
Section 4 -- Sui Generis Database Rights.
|
271 |
+
|
272 |
+
Where the Licensed Rights include Sui Generis Database Rights that
|
273 |
+
apply to Your use of the Licensed Material:
|
274 |
+
|
275 |
+
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
276 |
+
to extract, reuse, reproduce, and Share all or a substantial
|
277 |
+
portion of the contents of the database for NonCommercial purposes
|
278 |
+
only;
|
279 |
+
|
280 |
+
b. if You include all or a substantial portion of the database
|
281 |
+
contents in a database in which You have Sui Generis Database
|
282 |
+
Rights, then the database in which You have Sui Generis Database
|
283 |
+
Rights (but not its individual contents) is Adapted Material; and
|
284 |
+
|
285 |
+
c. You must comply with the conditions in Section 3(a) if You Share
|
286 |
+
all or a substantial portion of the contents of the database.
|
287 |
+
|
288 |
+
For the avoidance of doubt, this Section 4 supplements and does not
|
289 |
+
replace Your obligations under this Public License where the Licensed
|
290 |
+
Rights include other Copyright and Similar Rights.
|
291 |
+
|
292 |
+
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
293 |
+
|
294 |
+
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
295 |
+
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
296 |
+
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
297 |
+
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
298 |
+
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
299 |
+
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
300 |
+
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
301 |
+
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
302 |
+
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
303 |
+
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
304 |
+
|
305 |
+
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
306 |
+
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
307 |
+
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
308 |
+
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
309 |
+
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
310 |
+
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
311 |
+
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
312 |
+
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
313 |
+
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
314 |
+
|
315 |
+
c. The disclaimer of warranties and limitation of liability provided
|
316 |
+
above shall be interpreted in a manner that, to the extent
|
317 |
+
possible, most closely approximates an absolute disclaimer and
|
318 |
+
waiver of all liability.
|
319 |
+
|
320 |
+
Section 6 -- Term and Termination.
|
321 |
+
|
322 |
+
a. This Public License applies for the term of the Copyright and
|
323 |
+
Similar Rights licensed here. However, if You fail to comply with
|
324 |
+
this Public License, then Your rights under this Public License
|
325 |
+
terminate automatically.
|
326 |
+
|
327 |
+
b. Where Your right to use the Licensed Material has terminated under
|
328 |
+
Section 6(a), it reinstates:
|
329 |
+
|
330 |
+
1. automatically as of the date the violation is cured, provided
|
331 |
+
it is cured within 30 days of Your discovery of the
|
332 |
+
violation; or
|
333 |
+
|
334 |
+
2. upon express reinstatement by the Licensor.
|
335 |
+
|
336 |
+
For the avoidance of doubt, this Section 6(b) does not affect any
|
337 |
+
right the Licensor may have to seek remedies for Your violations
|
338 |
+
of this Public License.
|
339 |
+
|
340 |
+
c. For the avoidance of doubt, the Licensor may also offer the
|
341 |
+
Licensed Material under separate terms or conditions or stop
|
342 |
+
distributing the Licensed Material at any time; however, doing so
|
343 |
+
will not terminate this Public License.
|
344 |
+
|
345 |
+
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
346 |
+
License.
|
347 |
+
|
348 |
+
Section 7 -- Other Terms and Conditions.
|
349 |
+
|
350 |
+
a. The Licensor shall not be bound by any additional or different
|
351 |
+
terms or conditions communicated by You unless expressly agreed.
|
352 |
+
|
353 |
+
b. Any arrangements, understandings, or agreements regarding the
|
354 |
+
Licensed Material not stated herein are separate from and
|
355 |
+
independent of the terms and conditions of this Public License.
|
356 |
+
|
357 |
+
Section 8 -- Interpretation.
|
358 |
+
|
359 |
+
a. For the avoidance of doubt, this Public License does not, and
|
360 |
+
shall not be interpreted to, reduce, limit, restrict, or impose
|
361 |
+
conditions on any use of the Licensed Material that could lawfully
|
362 |
+
be made without permission under this Public License.
|
363 |
+
|
364 |
+
b. To the extent possible, if any provision of this Public License is
|
365 |
+
deemed unenforceable, it shall be automatically reformed to the
|
366 |
+
minimum extent necessary to make it enforceable. If the provision
|
367 |
+
cannot be reformed, it shall be severed from this Public License
|
368 |
+
without affecting the enforceability of the remaining terms and
|
369 |
+
conditions.
|
370 |
+
|
371 |
+
c. No term or condition of this Public License will be waived and no
|
372 |
+
failure to comply consented to unless expressly agreed to by the
|
373 |
+
Licensor.
|
374 |
+
|
375 |
+
d. Nothing in this Public License constitutes or may be interpreted
|
376 |
+
as a limitation upon, or waiver of, any privileges and immunities
|
377 |
+
that apply to the Licensor or You, including from the legal
|
378 |
+
processes of any jurisdiction or authority.
|
379 |
+
|
380 |
+
=======================================================================
|
381 |
+
|
382 |
+
Creative Commons is not a party to its public
|
383 |
+
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
384 |
+
its public licenses to material it publishes and in those instances
|
385 |
+
will be considered the “Licensor.” The text of the Creative Commons
|
386 |
+
public licenses is dedicated to the public domain under the CC0 Public
|
387 |
+
Domain Dedication. Except for the limited purpose of indicating that
|
388 |
+
material is shared under a Creative Commons public license or as
|
389 |
+
otherwise permitted by the Creative Commons policies published at
|
390 |
+
creativecommons.org/policies, Creative Commons does not authorize the
|
391 |
+
use of the trademark "Creative Commons" or any other trademark or logo
|
392 |
+
of Creative Commons without its prior written consent including,
|
393 |
+
without limitation, in connection with any unauthorized modifications
|
394 |
+
to any of its public licenses or any other arrangements,
|
395 |
+
understandings, or agreements concerning use of licensed material. For
|
396 |
+
the avoidance of doubt, this paragraph does not form part of the
|
397 |
+
public licenses.
|
398 |
+
|
399 |
+
Creative Commons may be contacted at creativecommons.org.
|
vggsfm/README.md
ADDED
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# VGGSfM: Visual Geometry Grounded Deep Structure From Motion
|
2 |
+
|
3 |
+
|
4 |
+
![Teaser](https://raw.githubusercontent.com/vggsfm/vggsfm.github.io/main/resources/vggsfm_teaser.gif)
|
5 |
+
|
6 |
+
**[Meta AI Research, GenAI](https://ai.facebook.com/research/)**; **[University of Oxford, VGG](https://www.robots.ox.ac.uk/~vgg/)**
|
7 |
+
|
8 |
+
|
9 |
+
[Jianyuan Wang](https://jytime.github.io/), [Nikita Karaev](https://nikitakaraevv.github.io/), [Christian Rupprecht](https://chrirupp.github.io/), [David Novotny](https://d-novotny.github.io/)
|
10 |
+
|
11 |
+
|
12 |
+
|
13 |
+
<p
|
14 |
+
dir="auto">[<a href="https://arxiv.org/pdf/2312.04563.pdf" rel="nofollow">Paper</a>]
|
15 |
+
[<a href="https://vggsfm.github.io/" rel="nofollow">Project Page</a>]
|
16 |
+
[Version 2.0]
|
17 |
+
</p>
|
18 |
+
|
19 |
+
|
20 |
+
**Updates:**
|
21 |
+
- [Jun 25, 2024] Upgrade to VGGSfM 2.0! More memory efficient, more robust, more powerful, and easier to start!
|
22 |
+
|
23 |
+
|
24 |
+
- [Apr 23, 2024] Release the code and model weight for VGGSfM v1.1.
|
25 |
+
|
26 |
+
|
27 |
+
|
28 |
+
|
29 |
+
## Installation
|
30 |
+
We provide a simple installation script that, by default, sets up a conda environment with Python 3.10, PyTorch 2.1, and CUDA 12.1.
|
31 |
+
|
32 |
+
```.bash
|
33 |
+
source install.sh
|
34 |
+
```
|
35 |
+
|
36 |
+
This script installs official pytorch3d, accelerate, lightglue, pycolmap, and visdom. Besides, it will also (optionally) install [poselib](https://github.com/PoseLib/PoseLib) using the python wheel under the folder ```wheels```, which is compiled by us instead of the official poselib team.
|
37 |
+
|
38 |
+
## Demo
|
39 |
+
|
40 |
+
### 1. Download Model
|
41 |
+
To get started, you need to first download the checkpoint. We provide the checkpoint for v2.0 model by [Hugging Face](https://huggingface.co/facebook/VGGSfM/blob/main/vggsfm_v2_0_0.bin) and [Google Drive](https://drive.google.com/file/d/163bHiqeTJhQ2_UnihRNPRA4Y9X8-gZ1-/view?usp=sharing).
|
42 |
+
|
43 |
+
### 2. Run the Demo
|
44 |
+
|
45 |
+
Now time to enjoy your 3D reconstruction! You can start by our provided examples, such as:
|
46 |
+
|
47 |
+
```bash
|
48 |
+
python demo.py SCENE_DIR=examples/cake resume_ckpt=/PATH/YOUR/CKPT
|
49 |
+
|
50 |
+
python demo.py SCENE_DIR=examples/british_museum query_frame_num=2 resume_ckpt=/PATH/YOUR/CKPT
|
51 |
+
|
52 |
+
python demo.py SCENE_DIR=examples/apple query_frame_num=5 max_query_pts=1600 resume_ckpt=/PATH/YOUR/CKPT
|
53 |
+
```
|
54 |
+
|
55 |
+
All default settings for the flags are specified in `cfgs/demo.yaml`. For example, we have modified the values of `query_frame_num` and `max_query_pts` from the default settings of `3` and `4096` to `5` and `1600`, respectively, to ensure a 32 GB GPU can work for ```examples/apple```.
|
56 |
+
|
57 |
+
|
58 |
+
The reconstruction result (camera parameters and 3D points) will be automatically saved in the COLMAP format at ```output/seq_name```. You can use the [COLMAP GUI](https://colmap.github.io/gui.html) to view them.
|
59 |
+
|
60 |
+
If you want to visualize it more easily, we provide an approach supported by [visdom](https://github.com/fossasia/visdom). To begin using Visdom, start the server by entering ```visdom``` in the command line. Once the server is running, access Visdom by navigating to ```http://localhost:8097``` in your web browser. Now every reconstruction will be visualized and saved to the visdom server by enabling ```visualize=True```:
|
61 |
+
|
62 |
+
```bash
|
63 |
+
python demo.py visualize=True ...(other flags)
|
64 |
+
```
|
65 |
+
|
66 |
+
By doing so, you should see an interface such as:
|
67 |
+
|
68 |
+
![UI](assets/ui.png)
|
69 |
+
|
70 |
+
|
71 |
+
|
72 |
+
### 3. Try your own data
|
73 |
+
|
74 |
+
You only need to specify the address of your data, such as:
|
75 |
+
|
76 |
+
```bash
|
77 |
+
python demo.py SCENE_DIR=examples/YOUR_FOLDER ...(other flags)
|
78 |
+
```
|
79 |
+
|
80 |
+
Please ensure that the images are stored in ```YOUR_FOLDER/images```. This folder should contain only the images. Check the ```examples``` folder for the desired data structure.
|
81 |
+
|
82 |
+
|
83 |
+
Have fun and feel free to create an issue if you meet any problem. SfM is always about corner/hard cases. I am happy to help. If you prefer not to share your images publicly, please send them to me by email.
|
84 |
+
|
85 |
+
### FAQ
|
86 |
+
|
87 |
+
* What should I do if I encounter an out-of-memory error?
|
88 |
+
|
89 |
+
To resolve an out-of-memory error, you can start by reducing the number of ```max_query_pts``` from the default ```4096``` to a lower value. If necessary, consider decreasing the ```query_frame_num```. Be aware that these adjustments may result in a sparser point cloud and could potentially impact the accuracy of the reconstruction.
|
90 |
+
|
91 |
+
|
92 |
+
|
93 |
+
## Testing
|
94 |
+
|
95 |
+
We are still preparing the testing script for VGGSfM v2. However, you can use our code for VGGSfM v1.1 to reproduce our benchmark results in the paper. Please refer to the branch ```v1.1```.
|
96 |
+
|
97 |
+
|
98 |
+
## Acknowledgement
|
99 |
+
|
100 |
+
We are highly inspired by [colmap](https://github.com/colmap/colmap), [pycolmap](https://github.com/colmap/pycolmap), [posediffusion](https://github.com/facebookresearch/PoseDiffusion), [cotracker](https://github.com/facebookresearch/co-tracker), and [kornia](https://github.com/kornia/kornia).
|
101 |
+
|
102 |
+
|
103 |
+
## License
|
104 |
+
See the [LICENSE](./LICENSE) file for details about the license under which this code is made available.
|
105 |
+
|
106 |
+
|
107 |
+
## Citing VGGSfM
|
108 |
+
|
109 |
+
If you find our repository useful, please consider giving it a star ⭐ and citing our paper in your work:
|
110 |
+
|
111 |
+
```bibtex
|
112 |
+
@article{wang2023vggsfm,
|
113 |
+
title={VGGSfM: Visual Geometry Grounded Deep Structure From Motion},
|
114 |
+
author={Wang, Jianyuan and Karaev, Nikita and Rupprecht, Christian and Novotny, David},
|
115 |
+
journal={arXiv preprint arXiv:2312.04563},
|
116 |
+
year={2023}
|
117 |
+
}
|
vggsfm/assets/ui.png
ADDED
vggsfm/cfgs/demo.yaml
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
hydra:
|
2 |
+
run:
|
3 |
+
dir: .
|
4 |
+
|
5 |
+
seed: 0
|
6 |
+
img_size: 1024
|
7 |
+
|
8 |
+
viz_ip: 127.0.0.1
|
9 |
+
|
10 |
+
debug: False
|
11 |
+
|
12 |
+
center_order: True
|
13 |
+
mixed_precision: fp16
|
14 |
+
extract_color: True
|
15 |
+
filter_invalid_frame: True
|
16 |
+
|
17 |
+
comple_nonvis: True
|
18 |
+
query_frame_num: 3
|
19 |
+
robust_refine: 2
|
20 |
+
BA_iters: 2
|
21 |
+
|
22 |
+
|
23 |
+
load_gt: False
|
24 |
+
visualize: False
|
25 |
+
fmat_thres: 4.0
|
26 |
+
max_reproj_error: 4.0
|
27 |
+
init_max_reproj_error: 4.0
|
28 |
+
max_query_pts: 4096
|
29 |
+
|
30 |
+
|
31 |
+
|
32 |
+
SCENE_DIR: examples/cake
|
33 |
+
|
34 |
+
resume_ckpt: ckpt/vggsfm_v2_0_0.bin
|
35 |
+
|
36 |
+
|
37 |
+
query_method: "sp+sift"
|
38 |
+
|
39 |
+
use_poselib: True
|
40 |
+
|
41 |
+
MODEL:
|
42 |
+
_target_: vggsfm.models.VGGSfM
|
43 |
+
|
44 |
+
TRACK:
|
45 |
+
_target_: vggsfm.models.TrackerPredictor
|
46 |
+
|
47 |
+
efficient_corr: False
|
48 |
+
|
49 |
+
COARSE:
|
50 |
+
stride: 4
|
51 |
+
down_ratio: 2
|
52 |
+
FEATURENET:
|
53 |
+
_target_: vggsfm.models.BasicEncoder
|
54 |
+
|
55 |
+
PREDICTOR:
|
56 |
+
_target_: vggsfm.models.BaseTrackerPredictor
|
57 |
+
|
58 |
+
FINE:
|
59 |
+
FEATURENET:
|
60 |
+
_target_: vggsfm.models.ShallowEncoder
|
61 |
+
|
62 |
+
|
63 |
+
PREDICTOR:
|
64 |
+
_target_: vggsfm.models.BaseTrackerPredictor
|
65 |
+
depth: 4
|
66 |
+
corr_levels: 3
|
67 |
+
corr_radius: 3
|
68 |
+
latent_dim: 32
|
69 |
+
hidden_size: 256
|
70 |
+
fine: True
|
71 |
+
use_spaceatt: False
|
72 |
+
|
73 |
+
CAMERA:
|
74 |
+
_target_: vggsf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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
|
7 |
+
import os
|
8 |
+
import time
|
9 |
+
import random
|
10 |
+
import torch
|
11 |
+
import torch.nn as nn
|
12 |
+
import torch.nn.functional as F
|
13 |
+
import numpy as np
|
14 |
+
from torch.cuda.amp import autocast
|
15 |
+
import hydra
|
16 |
+
|
17 |
+
from omegaconf import DictConfig, OmegaConf
|
18 |
+
from hydra.utils import instantiate
|
19 |
+
|
20 |
+
from lightglue import LightGlue, SuperPoint, SIFT, ALIKED
|
21 |
+
|
22 |
+
import pycolmap
|
23 |
+
|
24 |
+
from visdom import Visdom
|
25 |
+
|
26 |
+
|
27 |
+
from vggsfm.datasets.demo_loader import DemoLoader
|
28 |
+
from vggsfm.two_view_geo.estimate_preliminary import estimate_preliminary_cameras
|
29 |
+
|
30 |
+
try:
|
31 |
+
import poselib
|
32 |
+
from vggsfm.two_view_geo.estimate_preliminary import estimate_preliminary_cameras_poselib
|
33 |
+
|
34 |
+
print("Poselib is available")
|
35 |
+
except:
|
36 |
+
print("Poselib is not installed. Please disable use_poselib")
|
37 |
+
|
38 |
+
from vggsfm.utils.utils import (
|
39 |
+
set_seed_and_print,
|
40 |
+
farthest_point_sampling,
|
41 |
+
calculate_index_mappings,
|
42 |
+
switch_tensor_order,
|
43 |
+
)
|
44 |
+
|
45 |
+
|
46 |
+
@hydra.main(config_path="cfgs/", config_name="demo")
|
47 |
+
def demo_fn(cfg: DictConfig):
|
48 |
+
OmegaConf.set_struct(cfg, False)
|
49 |
+
|
50 |
+
# Print configuration
|
51 |
+
print("Model Config:", OmegaConf.to_yaml(cfg))
|
52 |
+
|
53 |
+
torch.backends.cudnn.enabled = False
|
54 |
+
torch.backends.cudnn.benchmark = True
|
55 |
+
torch.backends.cudnn.deterministic = True
|
56 |
+
|
57 |
+
# Set seed
|
58 |
+
seed_all_random_engines(cfg.seed)
|
59 |
+
|
60 |
+
# Model instantiation
|
61 |
+
model = instantiate(cfg.MODEL, _recursive_=False, cfg=cfg)
|
62 |
+
|
63 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
64 |
+
|
65 |
+
model = model.to(device)
|
66 |
+
|
67 |
+
# Prepare test dataset
|
68 |
+
test_dataset = DemoLoader(
|
69 |
+
SCENE_DIR=cfg.SCENE_DIR, img_size=cfg.img_size, normalize_cameras=False, load_gt=cfg.load_gt, cfg=cfg
|
70 |
+
)
|
71 |
+
|
72 |
+
if cfg.resume_ckpt:
|
73 |
+
# Reload model
|
74 |
+
checkpoint = torch.load(cfg.resume_ckpt)
|
75 |
+
model.load_state_dict(checkpoint, strict=True)
|
76 |
+
print(f"Successfully resumed from {cfg.resume_ckpt}")
|
77 |
+
|
78 |
+
if cfg.visualize:
|
79 |
+
from pytorch3d.structures import Pointclouds
|
80 |
+
from pytorch3d.vis.plotly_vis import plot_scene
|
81 |
+
from pytorch3d.renderer.cameras import PerspectiveCameras as PerspectiveCamerasVisual
|
82 |
+
|
83 |
+
viz = Visdom()
|
84 |
+
|
85 |
+
|
86 |
+
sequence_list = test_dataset.sequence_list
|
87 |
+
|
88 |
+
for seq_name in sequence_list:
|
89 |
+
print("*" * 50 + f" Testing on Scene {seq_name} " + "*" * 50)
|
90 |
+
|
91 |
+
# Load the data
|
92 |
+
batch, image_paths = test_dataset.get_data(sequence_name=seq_name, return_path=True)
|
93 |
+
|
94 |
+
# Send to GPU
|
95 |
+
images = batch["image"].to(device)
|
96 |
+
crop_params = batch["crop_params"].to(device)
|
97 |
+
|
98 |
+
|
99 |
+
# Unsqueeze to have batch size = 1
|
100 |
+
images = images.unsqueeze(0)
|
101 |
+
crop_params = crop_params.unsqueeze(0)
|
102 |
+
|
103 |
+
batch_size = len(images)
|
104 |
+
|
105 |
+
with torch.no_grad():
|
106 |
+
# Run the model
|
107 |
+
assert cfg.mixed_precision in ("None", "bf16", "fp16")
|
108 |
+
if cfg.mixed_precision == "None":
|
109 |
+
dtype = torch.float32
|
110 |
+
elif cfg.mixed_precision == "bf16":
|
111 |
+
dtype = torch.bfloat16
|
112 |
+
elif cfg.mixed_precision == "fp16":
|
113 |
+
dtype = torch.float16
|
114 |
+
else:
|
115 |
+
raise NotImplementedError(f"dtype {cfg.mixed_precision} is not supported now")
|
116 |
+
|
117 |
+
predictions = run_one_scene(
|
118 |
+
model,
|
119 |
+
images,
|
120 |
+
crop_params=crop_params,
|
121 |
+
query_frame_num=cfg.query_frame_num,
|
122 |
+
image_paths=image_paths,
|
123 |
+
dtype=dtype,
|
124 |
+
cfg=cfg,
|
125 |
+
)
|
126 |
+
|
127 |
+
# Export prediction as colmap format
|
128 |
+
reconstruction_pycolmap = predictions["reconstruction"]
|
129 |
+
output_path = os.path.join("output", seq_name)
|
130 |
+
print("-" * 50)
|
131 |
+
print(f"The output has been saved in COLMAP style at: {output_path} ")
|
132 |
+
os.makedirs(output_path, exist_ok=True)
|
133 |
+
reconstruction_pycolmap.write(output_path)
|
134 |
+
|
135 |
+
pred_cameras_PT3D = predictions["pred_cameras_PT3D"]
|
136 |
+
|
137 |
+
if cfg.visualize:
|
138 |
+
if "points3D_rgb" in predictions:
|
139 |
+
pcl = Pointclouds(points=predictions["points3D"][None], features=predictions["points3D_rgb"][None])
|
140 |
+
else:
|
141 |
+
pcl = Pointclouds(points=predictions["points3D"][None])
|
142 |
+
|
143 |
+
visual_cameras = PerspectiveCamerasVisual(
|
144 |
+
R=pred_cameras_PT3D.R,
|
145 |
+
T=pred_cameras_PT3D.T,
|
146 |
+
device=pred_cameras_PT3D.device,
|
147 |
+
)
|
148 |
+
|
149 |
+
visual_dict = {"scenes": {"points": pcl, "cameras": visual_cameras}}
|
150 |
+
|
151 |
+
fig = plot_scene(visual_dict, camera_scale=0.05)
|
152 |
+
|
153 |
+
env_name = f"demo_visual_{seq_name}"
|
154 |
+
print(f"Visualizing the scene by visdom at env: {env_name}")
|
155 |
+
viz.plotlyplot(fig, env=env_name, win="3D")
|
156 |
+
|
157 |
+
return True
|
158 |
+
|
159 |
+
|
160 |
+
def run_one_scene(model, images, crop_params=None, query_frame_num=3, image_paths=None, dtype=None, cfg=None):
|
161 |
+
"""
|
162 |
+
images have been normalized to the range [0, 1] instead of [0, 255]
|
163 |
+
"""
|
164 |
+
batch_num, frame_num, image_dim, height, width = images.shape
|
165 |
+
device = images.device
|
166 |
+
reshaped_image = images.reshape(batch_num * frame_num, image_dim, height, width)
|
167 |
+
|
168 |
+
predictions = {}
|
169 |
+
extra_dict = {}
|
170 |
+
|
171 |
+
camera_predictor = model.camera_predictor
|
172 |
+
track_predictor = model.track_predictor
|
173 |
+
triangulator = model.triangulator
|
174 |
+
|
175 |
+
# Find the query frames
|
176 |
+
# First use DINO to find the most common frame among all the input frames
|
177 |
+
# i.e., the one has highest (average) cosine similarity to all others
|
178 |
+
# Then use farthest_point_sampling to find the next ones
|
179 |
+
# The number of query frames is determined by query_frame_num
|
180 |
+
|
181 |
+
with autocast(dtype=dtype):
|
182 |
+
query_frame_indexes = find_query_frame_indexes(reshaped_image, camera_predictor, frame_num)
|
183 |
+
|
184 |
+
image_paths = [os.path.basename(imgpath) for imgpath in image_paths]
|
185 |
+
|
186 |
+
if cfg.center_order:
|
187 |
+
# The code below switchs the first frame (frame 0) to the most common frame
|
188 |
+
center_frame_index = query_frame_indexes[0]
|
189 |
+
center_order = calculate_index_mappings(center_frame_index, frame_num, device=device)
|
190 |
+
|
191 |
+
images, crop_params = switch_tensor_order([images, crop_params], center_order, dim=1)
|
192 |
+
reshaped_image = switch_tensor_order([reshaped_image], center_order, dim=0)[0]
|
193 |
+
|
194 |
+
image_paths = [image_paths[i] for i in center_order.cpu().numpy().tolist()]
|
195 |
+
|
196 |
+
# Also update query_frame_indexes:
|
197 |
+
query_frame_indexes = [center_frame_index if x == 0 else x for x in query_frame_indexes]
|
198 |
+
query_frame_indexes[0] = 0
|
199 |
+
|
200 |
+
# only pick query_frame_num
|
201 |
+
query_frame_indexes = query_frame_indexes[:query_frame_num]
|
202 |
+
|
203 |
+
# Prepare image feature maps for tracker
|
204 |
+
fmaps_for_tracker = track_predictor.process_images_to_fmaps(images)
|
205 |
+
|
206 |
+
# Predict tracks
|
207 |
+
with autocast(dtype=dtype):
|
208 |
+
pred_track, pred_vis, pred_score = predict_tracks(
|
209 |
+
cfg.query_method,
|
210 |
+
cfg.max_query_pts,
|
211 |
+
track_predictor,
|
212 |
+
images,
|
213 |
+
fmaps_for_tracker,
|
214 |
+
query_frame_indexes,
|
215 |
+
frame_num,
|
216 |
+
device,
|
217 |
+
cfg,
|
218 |
+
)
|
219 |
+
|
220 |
+
if cfg.comple_nonvis:
|
221 |
+
pred_track, pred_vis, pred_score = comple_nonvis_frames(
|
222 |
+
track_predictor,
|
223 |
+
images,
|
224 |
+
fmaps_for_tracker,
|
225 |
+
frame_num,
|
226 |
+
device,
|
227 |
+
pred_track,
|
228 |
+
pred_vis,
|
229 |
+
pred_score,
|
230 |
+
500,
|
231 |
+
cfg=cfg,
|
232 |
+
)
|
233 |
+
|
234 |
+
torch.cuda.empty_cache()
|
235 |
+
|
236 |
+
# If necessary, force all the predictions at the padding areas as non-visible
|
237 |
+
if crop_params is not None:
|
238 |
+
boundaries = crop_params[:, :, -4:-2].abs().to(device)
|
239 |
+
boundaries = torch.cat([boundaries, reshaped_image.shape[-1] - boundaries], dim=-1)
|
240 |
+
hvis = torch.logical_and(
|
241 |
+
pred_track[..., 1] >= boundaries[:, :, 1:2], pred_track[..., 1] <= boundaries[:, :, 3:4]
|
242 |
+
)
|
243 |
+
wvis = torch.logical_and(
|
244 |
+
pred_track[..., 0] >= boundaries[:, :, 0:1], pred_track[..., 0] <= boundaries[:, :, 2:3]
|
245 |
+
)
|
246 |
+
force_vis = torch.logical_and(hvis, wvis)
|
247 |
+
pred_vis = pred_vis * force_vis.float()
|
248 |
+
|
249 |
+
# TODO: plot 2D matches
|
250 |
+
if cfg.use_poselib:
|
251 |
+
estimate_preliminary_cameras_fn = estimate_preliminary_cameras_poselib
|
252 |
+
else:
|
253 |
+
estimate_preliminary_cameras_fn = estimate_preliminary_cameras
|
254 |
+
|
255 |
+
# Estimate preliminary_cameras by recovering fundamental/essential/homography matrix from 2D matches
|
256 |
+
# By default, we use fundamental matrix estimation with 7p/8p+LORANSAC
|
257 |
+
# All the operations are batched and differentiable (if necessary)
|
258 |
+
# except when you enable use_poselib to save GPU memory
|
259 |
+
_, preliminary_dict = estimate_preliminary_cameras_fn(
|
260 |
+
pred_track,
|
261 |
+
pred_vis,
|
262 |
+
width,
|
263 |
+
height,
|
264 |
+
tracks_score=pred_score,
|
265 |
+
max_error=cfg.fmat_thres,
|
266 |
+
loopresidual=True,
|
267 |
+
# max_ransac_iters=cfg.max_ransac_iters,
|
268 |
+
)
|
269 |
+
|
270 |
+
pose_predictions = camera_predictor(reshaped_image, batch_size=batch_num)
|
271 |
+
|
272 |
+
pred_cameras = pose_predictions["pred_cameras"]
|
273 |
+
|
274 |
+
# Conduct Triangulation and Bundle Adjustment
|
275 |
+
(
|
276 |
+
BA_cameras_PT3D,
|
277 |
+
extrinsics_opencv,
|
278 |
+
intrinsics_opencv,
|
279 |
+
points3D,
|
280 |
+
points3D_rgb,
|
281 |
+
reconstruction,
|
282 |
+
valid_frame_mask,
|
283 |
+
) = triangulator(
|
284 |
+
pred_cameras,
|
285 |
+
pred_track,
|
286 |
+
pred_vis,
|
287 |
+
images,
|
288 |
+
preliminary_dict,
|
289 |
+
image_paths=image_paths,
|
290 |
+
crop_params=crop_params,
|
291 |
+
pred_score=pred_score,
|
292 |
+
fmat_thres=cfg.fmat_thres,
|
293 |
+
BA_iters=cfg.BA_iters,
|
294 |
+
max_reproj_error = cfg.max_reproj_error,
|
295 |
+
init_max_reproj_error=cfg.init_max_reproj_error,
|
296 |
+
cfg=cfg,
|
297 |
+
)
|
298 |
+
|
299 |
+
if cfg.center_order:
|
300 |
+
# NOTE we changed the image order previously, now we need to switch it back
|
301 |
+
BA_cameras_PT3D = BA_cameras_PT3D[center_order]
|
302 |
+
extrinsics_opencv = extrinsics_opencv[center_order]
|
303 |
+
intrinsics_opencv = intrinsics_opencv[center_order]
|
304 |
+
|
305 |
+
predictions["pred_cameras_PT3D"] = BA_cameras_PT3D
|
306 |
+
predictions["extrinsics_opencv"] = extrinsics_opencv
|
307 |
+
predictions["intrinsics_opencv"] = intrinsics_opencv
|
308 |
+
predictions["points3D"] = points3D
|
309 |
+
predictions["points3D_rgb"] = points3D_rgb
|
310 |
+
predictions["reconstruction"] = reconstruction
|
311 |
+
return predictions
|
312 |
+
|
313 |
+
|
314 |
+
def predict_tracks(
|
315 |
+
query_method,
|
316 |
+
max_query_pts,
|
317 |
+
track_predictor,
|
318 |
+
images,
|
319 |
+
fmaps_for_tracker,
|
320 |
+
query_frame_indexes,
|
321 |
+
frame_num,
|
322 |
+
device,
|
323 |
+
cfg=None,
|
324 |
+
):
|
325 |
+
pred_track_list = []
|
326 |
+
pred_vis_list = []
|
327 |
+
pred_score_list = []
|
328 |
+
|
329 |
+
for query_index in query_frame_indexes:
|
330 |
+
print(f"Predicting tracks with query_index = {query_index}")
|
331 |
+
|
332 |
+
# Find query_points at the query frame
|
333 |
+
query_points = get_query_points(images[:, query_index], query_method, max_query_pts)
|
334 |
+
|
335 |
+
# Switch so that query_index frame stays at the first frame
|
336 |
+
# This largely simplifies the code structure of tracker
|
337 |
+
new_order = calculate_index_mappings(query_index, frame_num, device=device)
|
338 |
+
images_feed, fmaps_feed = switch_tensor_order([images, fmaps_for_tracker], new_order)
|
339 |
+
|
340 |
+
# Feed into track predictor
|
341 |
+
fine_pred_track, _, pred_vis, pred_score = track_predictor(images_feed, query_points, fmaps=fmaps_feed)
|
342 |
+
|
343 |
+
# Switch back the predictions
|
344 |
+
fine_pred_track, pred_vis, pred_score = switch_tensor_order([fine_pred_track, pred_vis, pred_score], new_order)
|
345 |
+
|
346 |
+
# Append predictions for different queries
|
347 |
+
pred_track_list.append(fine_pred_track)
|
348 |
+
pred_vis_list.append(pred_vis)
|
349 |
+
pred_score_list.append(pred_score)
|
350 |
+
|
351 |
+
pred_track = torch.cat(pred_track_list, dim=2)
|
352 |
+
pred_vis = torch.cat(pred_vis_list, dim=2)
|
353 |
+
pred_score = torch.cat(pred_score_list, dim=2)
|
354 |
+
|
355 |
+
return pred_track, pred_vis, pred_score
|
356 |
+
|
357 |
+
|
358 |
+
def comple_nonvis_frames(
|
359 |
+
track_predictor,
|
360 |
+
images,
|
361 |
+
fmaps_for_tracker,
|
362 |
+
frame_num,
|
363 |
+
device,
|
364 |
+
pred_track,
|
365 |
+
pred_vis,
|
366 |
+
pred_score,
|
367 |
+
min_vis=500,
|
368 |
+
cfg=None,
|
369 |
+
):
|
370 |
+
# if a frame has too few visible inlier, use it as a query
|
371 |
+
non_vis_frames = torch.nonzero((pred_vis.squeeze(0) > 0.05).sum(-1) < min_vis).squeeze(-1).tolist()
|
372 |
+
last_query = -1
|
373 |
+
while len(non_vis_frames) > 0:
|
374 |
+
print("Processing non visible frames")
|
375 |
+
print(non_vis_frames)
|
376 |
+
if non_vis_frames[0] == last_query:
|
377 |
+
print("The non vis frame still does not has enough 2D matches")
|
378 |
+
pred_track_comple, pred_vis_comple, pred_score_comple = predict_tracks(
|
379 |
+
"sp+sift+aliked",
|
380 |
+
cfg.max_query_pts // 2,
|
381 |
+
track_predictor,
|
382 |
+
images,
|
383 |
+
fmaps_for_tracker,
|
384 |
+
non_vis_frames,
|
385 |
+
frame_num,
|
386 |
+
device,
|
387 |
+
cfg,
|
388 |
+
)
|
389 |
+
# concat predictions
|
390 |
+
pred_track = torch.cat([pred_track, pred_track_comple], dim=2)
|
391 |
+
pred_vis = torch.cat([pred_vis, pred_vis_comple], dim=2)
|
392 |
+
pred_score = torch.cat([pred_score, pred_score_comple], dim=2)
|
393 |
+
break
|
394 |
+
|
395 |
+
non_vis_query_list = [non_vis_frames[0]]
|
396 |
+
last_query = non_vis_frames[0]
|
397 |
+
pred_track_comple, pred_vis_comple, pred_score_comple = predict_tracks(
|
398 |
+
cfg.query_method,
|
399 |
+
cfg.max_query_pts,
|
400 |
+
track_predictor,
|
401 |
+
images,
|
402 |
+
fmaps_for_tracker,
|
403 |
+
non_vis_query_list,
|
404 |
+
frame_num,
|
405 |
+
device,
|
406 |
+
cfg,
|
407 |
+
)
|
408 |
+
|
409 |
+
# concat predictions
|
410 |
+
pred_track = torch.cat([pred_track, pred_track_comple], dim=2)
|
411 |
+
pred_vis = torch.cat([pred_vis, pred_vis_comple], dim=2)
|
412 |
+
pred_score = torch.cat([pred_score, pred_score_comple], dim=2)
|
413 |
+
non_vis_frames = torch.nonzero((pred_vis.squeeze(0) > 0.05).sum(-1) < min_vis).squeeze(-1).tolist()
|
414 |
+
return pred_track, pred_vis, pred_score
|
415 |
+
|
416 |
+
|
417 |
+
def find_query_frame_indexes(reshaped_image, camera_predictor, query_frame_num, image_size=336):
|
418 |
+
# Downsample image to image_size x image_size
|
419 |
+
# because we found it is unnecessary to use high resolution
|
420 |
+
rgbs = F.interpolate(reshaped_image, (image_size, image_size), mode="bilinear", align_corners=True)
|
421 |
+
rgbs = camera_predictor._resnet_normalize_image(rgbs)
|
422 |
+
|
423 |
+
# Get the image features (patch level)
|
424 |
+
frame_feat = camera_predictor.backbone(rgbs, is_training=True)
|
425 |
+
frame_feat = frame_feat["x_norm_patchtokens"]
|
426 |
+
frame_feat_norm = F.normalize(frame_feat, p=2, dim=1)
|
427 |
+
|
428 |
+
# Compute the similiarty matrix
|
429 |
+
frame_feat_norm = frame_feat_norm.permute(1, 0, 2)
|
430 |
+
similarity_matrix = torch.bmm(frame_feat_norm, frame_feat_norm.transpose(-1, -2))
|
431 |
+
similarity_matrix = similarity_matrix.mean(dim=0)
|
432 |
+
distance_matrix = 1 - similarity_matrix.clone()
|
433 |
+
|
434 |
+
# Ignore self-pairing
|
435 |
+
similarity_matrix.fill_diagonal_(0)
|
436 |
+
|
437 |
+
similarity_sum = similarity_matrix.sum(dim=1)
|
438 |
+
|
439 |
+
# Find the most common frame
|
440 |
+
most_common_frame_index = torch.argmax(similarity_sum).item()
|
441 |
+
|
442 |
+
# Conduct FPS sampling
|
443 |
+
# Starting from the most_common_frame_index,
|
444 |
+
# try to find the farthest frame,
|
445 |
+
# then the farthest to the last found frame
|
446 |
+
# (frames are not allowed to be found twice)
|
447 |
+
fps_idx = farthest_point_sampling(distance_matrix, query_frame_num, most_common_frame_index)
|
448 |
+
|
449 |
+
return fps_idx
|
450 |
+
|
451 |
+
|
452 |
+
def get_query_points(query_image, query_method, max_query_num=4096, det_thres=0.005):
|
453 |
+
# Run superpoint and sift on the target frame
|
454 |
+
# Feel free to modify for your own
|
455 |
+
|
456 |
+
methods = query_method.split("+")
|
457 |
+
pred_points = []
|
458 |
+
|
459 |
+
for method in methods:
|
460 |
+
if "sp" in method:
|
461 |
+
extractor = SuperPoint(max_num_keypoints=max_query_num, detection_threshold=det_thres).cuda().eval()
|
462 |
+
elif "sift" in method:
|
463 |
+
extractor = SIFT(max_num_keypoints=max_query_num).cuda().eval()
|
464 |
+
elif "aliked" in method:
|
465 |
+
extractor = ALIKED(max_num_keypoints=max_query_num, detection_threshold=det_thres).cuda().eval()
|
466 |
+
else:
|
467 |
+
raise NotImplementedError(f"query method {method} is not supprted now")
|
468 |
+
|
469 |
+
query_points = extractor.extract(query_image)["keypoints"]
|
470 |
+
pred_points.append(query_points)
|
471 |
+
|
472 |
+
query_points = torch.cat(pred_points, dim=1)
|
473 |
+
|
474 |
+
if query_points.shape[1] > max_query_num:
|
475 |
+
random_point_indices = torch.randperm(query_points.shape[1])[:max_query_num]
|
476 |
+
query_points = query_points[:, random_point_indices, :]
|
477 |
+
|
478 |
+
return query_points
|
479 |
+
|
480 |
+
|
481 |
+
def seed_all_random_engines(seed: int) -> None:
|
482 |
+
np.random.seed(seed)
|
483 |
+
torch.manual_seed(seed)
|
484 |
+
random.seed(seed)
|
485 |
+
|
486 |
+
|
487 |
+
if __name__ == "__main__":
|
488 |
+
with torch.no_grad():
|
489 |
+
demo_fn()
|
vggsfm/examples/apple/images/frame000007.jpg
ADDED
vggsfm/examples/apple/images/frame000012.jpg
ADDED
vggsfm/examples/apple/images/frame000017.jpg
ADDED
vggsfm/examples/apple/images/frame000019.jpg
ADDED
vggsfm/examples/apple/images/frame000024.jpg
ADDED
vggsfm/examples/apple/images/frame000025.jpg
ADDED
vggsfm/examples/apple/images/frame000043.jpg
ADDED
vggsfm/examples/apple/images/frame000052.jpg
ADDED
vggsfm/examples/apple/images/frame000070.jpg
ADDED
vggsfm/examples/apple/images/frame000077.jpg
ADDED
vggsfm/examples/apple/images/frame000085.jpg
ADDED
vggsfm/examples/apple/images/frame000096.jpg
ADDED
vggsfm/examples/apple/images/frame000128.jpg
ADDED
vggsfm/examples/apple/images/frame000145.jpg
ADDED
vggsfm/examples/apple/images/frame000160.jpg
ADDED
vggsfm/examples/apple/images/frame000162.jpg
ADDED
vggsfm/examples/apple/images/frame000168.jpg
ADDED
vggsfm/examples/apple/images/frame000172.jpg
ADDED
vggsfm/examples/apple/images/frame000191.jpg
ADDED
vggsfm/examples/apple/images/frame000200.jpg
ADDED
vggsfm/examples/british_museum/images/29057984_287139632.jpg
ADDED
vggsfm/examples/british_museum/images/32630292_7166579210.jpg
ADDED
vggsfm/examples/british_museum/images/45839934_4117745134.jpg
ADDED
vggsfm/examples/british_museum/images/51004432_567773767.jpg
ADDED
vggsfm/examples/british_museum/images/62620282_3728576515.jpg
ADDED
vggsfm/examples/british_museum/images/71931631_7212707886.jpg
ADDED
vggsfm/examples/british_museum/images/78600497_407639599.jpg
ADDED
vggsfm/examples/british_museum/images/80340357_5029510336.jpg
ADDED
vggsfm/examples/british_museum/images/81272348_2712949069.jpg
ADDED
vggsfm/examples/british_museum/images/93266801_2335569192.jpg
ADDED
vggsfm/examples/cake/images/frame000020.jpg
ADDED
vggsfm/examples/cake/images/frame000069.jpg
ADDED
vggsfm/examples/cake/images/frame000096.jpg
ADDED
vggsfm/examples/cake/images/frame000112.jpg
ADDED
vggsfm/examples/cake/images/frame000146.jpg
ADDED
vggsfm/examples/cake/images/frame000149.jpg
ADDED
vggsfm/examples/cake/images/frame000166.jpg
ADDED
vggsfm/examples/cake/images/frame000169.jpg
ADDED
vggsfm/install.sh
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
|
7 |
+
# This Script Assumes Python 3.10, CUDA 12.1
|
8 |
+
|
9 |
+
conda deactivate
|
10 |
+
|
11 |
+
# Set environment variables
|
12 |
+
export ENV_NAME=vggsfm
|
13 |
+
export PYTHON_VERSION=3.10
|
14 |
+
export PYTORCH_VERSION=2.1.0
|
15 |
+
export CUDA_VERSION=12.1
|
16 |
+
|
17 |
+
# Create a new conda environment and activate it
|
18 |
+
conda create -n $ENV_NAME python=$PYTHON_VERSION
|
19 |
+
conda activate $ENV_NAME
|
20 |
+
|
21 |
+
# Install PyTorch, torchvision, and PyTorch3D using conda
|
22 |
+
conda install pytorch=$PYTORCH_VERSION torchvision pytorch-cuda=$CUDA_VERSION -c pytorch -c nvidia
|
23 |
+
conda install -c fvcore -c iopath -c conda-forge fvcore iopath
|
24 |
+
conda install pytorch3d -c pytorch3d
|
25 |
+
|
26 |
+
# Install pip packages
|
27 |
+
pip install hydra-core --upgrade
|
28 |
+
pip install omegaconf opencv-python einops visdom
|
29 |
+
pip install accelerate==0.24.0
|
30 |
+
|
31 |
+
# Install LightGlue
|
32 |
+
git clone https://github.com/cvg/LightGlue.git dependency/LightGlue
|
33 |
+
|
34 |
+
cd dependency/LightGlue/
|
35 |
+
python -m pip install -e . # editable mode
|
36 |
+
cd ../../
|
37 |
+
|
38 |
+
# Force numpy <2
|
39 |
+
pip install numpy==1.26.3
|
40 |
+
|
41 |
+
# Ensure the version of pycolmap is 0.6.1
|
42 |
+
pip install pycolmap==0.6.1
|
43 |
+
|
44 |
+
# (Optional) Install poselib
|
45 |
+
pip install https://huggingface.co/facebook/VGGSfM/resolve/main/poselib-2.0.2-cp310-cp310-linux_x86_64.whl
|
46 |
+
|
47 |
+
|
vggsfm/minipytorch3d/__init__.py
ADDED
File without changes
|
vggsfm/minipytorch3d/cameras.py
ADDED
@@ -0,0 +1,1722 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# This source code is licensed under the BSD-style license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
|
7 |
+
# pyre-unsafe
|
8 |
+
|
9 |
+
import math
|
10 |
+
import warnings
|
11 |
+
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
|
12 |
+
|
13 |
+
import numpy as np
|
14 |
+
import torch
|
15 |
+
import torch.nn.functional as F
|
16 |
+
|
17 |
+
# from pytorch3d.common.datatypes import Device
|
18 |
+
|
19 |
+
from .device_utils import Device, get_device, make_device
|
20 |
+
from .transform3d import Rotate, Transform3d, Translate
|
21 |
+
from .renderer_utils import convert_to_tensors_and_broadcast, TensorProperties
|
22 |
+
|
23 |
+
|
24 |
+
# Default values for rotation and translation matrices.
|
25 |
+
_R = torch.eye(3)[None] # (1, 3, 3)
|
26 |
+
_T = torch.zeros(1, 3) # (1, 3)
|
27 |
+
|
28 |
+
# An input which is a float per batch element
|
29 |
+
_BatchFloatType = Union[float, Sequence[float], torch.Tensor]
|
30 |
+
|
31 |
+
# one or two floats per batch element
|
32 |
+
_FocalLengthType = Union[float, Sequence[Tuple[float]], Sequence[Tuple[float, float]], torch.Tensor]
|
33 |
+
|
34 |
+
|
35 |
+
class CamerasBase(TensorProperties):
|
36 |
+
"""
|
37 |
+
`CamerasBase` implements a base class for all cameras.
|
38 |
+
|
39 |
+
For cameras, there are four different coordinate systems (or spaces)
|
40 |
+
- World coordinate system: This is the system the object lives - the world.
|
41 |
+
- Camera view coordinate system: This is the system that has its origin on
|
42 |
+
the camera and the Z-axis perpendicular to the image plane.
|
43 |
+
In PyTorch3D, we assume that +X points left, and +Y points up and
|
44 |
+
+Z points out from the image plane.
|
45 |
+
The transformation from world --> view happens after applying a rotation (R)
|
46 |
+
and translation (T)
|
47 |
+
- NDC coordinate system: This is the normalized coordinate system that confines
|
48 |
+
points in a volume the rendered part of the object or scene, also known as
|
49 |
+
view volume. For square images, given the PyTorch3D convention, (+1, +1, znear)
|
50 |
+
is the top left near corner, and (-1, -1, zfar) is the bottom right far
|
51 |
+
corner of the volume.
|
52 |
+
The transformation from view --> NDC happens after applying the camera
|
53 |
+
projection matrix (P) if defined in NDC space.
|
54 |
+
For non square images, we scale the points such that smallest side
|
55 |
+
has range [-1, 1] and the largest side has range [-u, u], with u > 1.
|
56 |
+
- Screen coordinate system: This is another representation of the view volume with
|
57 |
+
the XY coordinates defined in image space instead of a normalized space.
|
58 |
+
|
59 |
+
An illustration of the coordinate systems can be found in pytorch3d/docs/notes/cameras.md.
|
60 |
+
|
61 |
+
CameraBase defines methods that are common to all camera models:
|
62 |
+
- `get_camera_center` that returns the optical center of the camera in
|
63 |
+
world coordinates
|
64 |
+
- `get_world_to_view_transform` which returns a 3D transform from
|
65 |
+
world coordinates to the camera view coordinates (R, T)
|
66 |
+
- `get_full_projection_transform` which composes the projection
|
67 |
+
transform (P) with the world-to-view transform (R, T)
|
68 |
+
- `transform_points` which takes a set of input points in world coordinates and
|
69 |
+
projects to the space the camera is defined in (NDC or screen)
|
70 |
+
- `get_ndc_camera_transform` which defines the transform from screen/NDC to
|
71 |
+
PyTorch3D's NDC space
|
72 |
+
- `transform_points_ndc` which takes a set of points in world coordinates and
|
73 |
+
projects them to PyTorch3D's NDC space
|
74 |
+
- `transform_points_screen` which takes a set of points in world coordinates and
|
75 |
+
projects them to screen space
|
76 |
+
|
77 |
+
For each new camera, one should implement the `get_projection_transform`
|
78 |
+
routine that returns the mapping from camera view coordinates to camera
|
79 |
+
coordinates (NDC or screen).
|
80 |
+
|
81 |
+
Another useful function that is specific to each camera model is
|
82 |
+
`unproject_points` which sends points from camera coordinates (NDC or screen)
|
83 |
+
back to camera view or world coordinates depending on the `world_coordinates`
|
84 |
+
boolean argument of the function.
|
85 |
+
"""
|
86 |
+
|
87 |
+
# Used in __getitem__ to index the relevant fields
|
88 |
+
# When creating a new camera, this should be set in the __init__
|
89 |
+
_FIELDS: Tuple[str, ...] = ()
|
90 |
+
|
91 |
+
# Names of fields which are a constant property of the whole batch, rather
|
92 |
+
# than themselves a batch of data.
|
93 |
+
# When joining objects into a batch, they will have to agree.
|
94 |
+
_SHARED_FIELDS: Tuple[str, ...] = ()
|
95 |
+
|
96 |
+
def get_projection_transform(self, **kwargs):
|
97 |
+
"""
|
98 |
+
Calculate the projective transformation matrix.
|
99 |
+
|
100 |
+
Args:
|
101 |
+
**kwargs: parameters for the projection can be passed in as keyword
|
102 |
+
arguments to override the default values set in `__init__`.
|
103 |
+
|
104 |
+
Return:
|
105 |
+
a `Transform3d` object which represents a batch of projection
|
106 |
+
matrices of shape (N, 3, 3)
|
107 |
+
"""
|
108 |
+
raise NotImplementedError()
|
109 |
+
|
110 |
+
def unproject_points(self, xy_depth: torch.Tensor, **kwargs):
|
111 |
+
"""
|
112 |
+
Transform input points from camera coordinates (NDC or screen)
|
113 |
+
to the world / camera coordinates.
|
114 |
+
|
115 |
+
Each of the input points `xy_depth` of shape (..., 3) is
|
116 |
+
a concatenation of the x, y location and its depth.
|
117 |
+
|
118 |
+
For instance, for an input 2D tensor of shape `(num_points, 3)`
|
119 |
+
`xy_depth` takes the following form:
|
120 |
+
`xy_depth[i] = [x[i], y[i], depth[i]]`,
|
121 |
+
for a each point at an index `i`.
|
122 |
+
|
123 |
+
The following example demonstrates the relationship between
|
124 |
+
`transform_points` and `unproject_points`:
|
125 |
+
|
126 |
+
.. code-block:: python
|
127 |
+
|
128 |
+
cameras = # camera object derived from CamerasBase
|
129 |
+
xyz = # 3D points of shape (batch_size, num_points, 3)
|
130 |
+
# transform xyz to the camera view coordinates
|
131 |
+
xyz_cam = cameras.get_world_to_view_transform().transform_points(xyz)
|
132 |
+
# extract the depth of each point as the 3rd coord of xyz_cam
|
133 |
+
depth = xyz_cam[:, :, 2:]
|
134 |
+
# project the points xyz to the camera
|
135 |
+
xy = cameras.transform_points(xyz)[:, :, :2]
|
136 |
+
# append depth to xy
|
137 |
+
xy_depth = torch.cat((xy, depth), dim=2)
|
138 |
+
# unproject to the world coordinates
|
139 |
+
xyz_unproj_world = cameras.unproject_points(xy_depth, world_coordinates=True)
|
140 |
+
print(torch.allclose(xyz, xyz_unproj_world)) # True
|
141 |
+
# unproject to the camera coordinates
|
142 |
+
xyz_unproj = cameras.unproject_points(xy_depth, world_coordinates=False)
|
143 |
+
print(torch.allclose(xyz_cam, xyz_unproj)) # True
|
144 |
+
|
145 |
+
Args:
|
146 |
+
xy_depth: torch tensor of shape (..., 3).
|
147 |
+
world_coordinates: If `True`, unprojects the points back to world
|
148 |
+
coordinates using the camera extrinsics `R` and `T`.
|
149 |
+
`False` ignores `R` and `T` and unprojects to
|
150 |
+
the camera view coordinates.
|
151 |
+
from_ndc: If `False` (default), assumes xy part of input is in
|
152 |
+
NDC space if self.in_ndc(), otherwise in screen space. If
|
153 |
+
`True`, assumes xy is in NDC space even if the camera
|
154 |
+
is defined in screen space.
|
155 |
+
|
156 |
+
Returns
|
157 |
+
new_points: unprojected points with the same shape as `xy_depth`.
|
158 |
+
"""
|
159 |
+
raise NotImplementedError()
|
160 |
+
|
161 |
+
def get_camera_center(self, **kwargs) -> torch.Tensor:
|
162 |
+
"""
|
163 |
+
Return the 3D location of the camera optical center
|
164 |
+
in the world coordinates.
|
165 |
+
|
166 |
+
Args:
|
167 |
+
**kwargs: parameters for the camera extrinsics can be passed in
|
168 |
+
as keyword arguments to override the default values
|
169 |
+
set in __init__.
|
170 |
+
|
171 |
+
Setting R or T here will update the values set in init as these
|
172 |
+
values may be needed later on in the rendering pipeline e.g. for
|
173 |
+
lighting calculations.
|
174 |
+
|
175 |
+
Returns:
|
176 |
+
C: a batch of 3D locations of shape (N, 3) denoting
|
177 |
+
the locations of the center of each camera in the batch.
|
178 |
+
"""
|
179 |
+
w2v_trans = self.get_world_to_view_transform(**kwargs)
|
180 |
+
P = w2v_trans.inverse().get_matrix()
|
181 |
+
# the camera center is the translation component (the first 3 elements
|
182 |
+
# of the last row) of the inverted world-to-view
|
183 |
+
# transform (4x4 RT matrix)
|
184 |
+
C = P[:, 3, :3]
|
185 |
+
return C
|
186 |
+
|
187 |
+
def get_world_to_view_transform(self, **kwargs) -> Transform3d:
|
188 |
+
"""
|
189 |
+
Return the world-to-view transform.
|
190 |
+
|
191 |
+
Args:
|
192 |
+
**kwargs: parameters for the camera extrinsics can be passed in
|
193 |
+
as keyword arguments to override the default values
|
194 |
+
set in __init__.
|
195 |
+
|
196 |
+
Setting R and T here will update the values set in init as these
|
197 |
+
values may be needed later on in the rendering pipeline e.g. for
|
198 |
+
lighting calculations.
|
199 |
+
|
200 |
+
Returns:
|
201 |
+
A Transform3d object which represents a batch of transforms
|
202 |
+
of shape (N, 3, 3)
|
203 |
+
"""
|
204 |
+
R: torch.Tensor = kwargs.get("R", self.R)
|
205 |
+
T: torch.Tensor = kwargs.get("T", self.T)
|
206 |
+
self.R = R
|
207 |
+
self.T = T
|
208 |
+
world_to_view_transform = get_world_to_view_transform(R=R, T=T)
|
209 |
+
return world_to_view_transform
|
210 |
+
|
211 |
+
def get_full_projection_transform(self, **kwargs) -> Transform3d:
|
212 |
+
"""
|
213 |
+
Return the full world-to-camera transform composing the
|
214 |
+
world-to-view and view-to-camera transforms.
|
215 |
+
If camera is defined in NDC space, the projected points are in NDC space.
|
216 |
+
If camera is defined in screen space, the projected points are in screen space.
|
217 |
+
|
218 |
+
Args:
|
219 |
+
**kwargs: parameters for the projection transforms can be passed in
|
220 |
+
as keyword arguments to override the default values
|
221 |
+
set in __init__.
|
222 |
+
|
223 |
+
Setting R and T here will update the values set in init as these
|
224 |
+
values may be needed later on in the rendering pipeline e.g. for
|
225 |
+
lighting calculations.
|
226 |
+
|
227 |
+
Returns:
|
228 |
+
a Transform3d object which represents a batch of transforms
|
229 |
+
of shape (N, 3, 3)
|
230 |
+
"""
|
231 |
+
self.R: torch.Tensor = kwargs.get("R", self.R)
|
232 |
+
self.T: torch.Tensor = kwargs.get("T", self.T)
|
233 |
+
world_to_view_transform = self.get_world_to_view_transform(R=self.R, T=self.T)
|
234 |
+
view_to_proj_transform = self.get_projection_transform(**kwargs)
|
235 |
+
return world_to_view_transform.compose(view_to_proj_transform)
|
236 |
+
|
237 |
+
def transform_points(self, points, eps: Optional[float] = None, **kwargs) -> torch.Tensor:
|
238 |
+
"""
|
239 |
+
Transform input points from world to camera space.
|
240 |
+
If camera is defined in NDC space, the projected points are in NDC space.
|
241 |
+
If camera is defined in screen space, the projected points are in screen space.
|
242 |
+
|
243 |
+
For `CamerasBase.transform_points`, setting `eps > 0`
|
244 |
+
stabilizes gradients since it leads to avoiding division
|
245 |
+
by excessively low numbers for points close to the camera plane.
|
246 |
+
|
247 |
+
Args:
|
248 |
+
points: torch tensor of shape (..., 3).
|
249 |
+
eps: If eps!=None, the argument is used to clamp the
|
250 |
+
divisor in the homogeneous normalization of the points
|
251 |
+
transformed to the ndc space. Please see
|
252 |
+
`transforms.Transform3d.transform_points` for details.
|
253 |
+
|
254 |
+
For `CamerasBase.transform_points`, setting `eps > 0`
|
255 |
+
stabilizes gradients since it leads to avoiding division
|
256 |
+
by excessively low numbers for points close to the
|
257 |
+
camera plane.
|
258 |
+
|
259 |
+
Returns
|
260 |
+
new_points: transformed points with the same shape as the input.
|
261 |
+
"""
|
262 |
+
world_to_proj_transform = self.get_full_projection_transform(**kwargs)
|
263 |
+
return world_to_proj_transform.transform_points(points, eps=eps)
|
264 |
+
|
265 |
+
def get_ndc_camera_transform(self, **kwargs) -> Transform3d:
|
266 |
+
"""
|
267 |
+
Returns the transform from camera projection space (screen or NDC) to NDC space.
|
268 |
+
For cameras that can be specified in screen space, this transform
|
269 |
+
allows points to be converted from screen to NDC space.
|
270 |
+
The default transform scales the points from [0, W]x[0, H]
|
271 |
+
to [-1, 1]x[-u, u] or [-u, u]x[-1, 1] where u > 1 is the aspect ratio of the image.
|
272 |
+
This function should be modified per camera definitions if need be,
|
273 |
+
e.g. for Perspective/Orthographic cameras we provide a custom implementation.
|
274 |
+
This transform assumes PyTorch3D coordinate system conventions for
|
275 |
+
both the NDC space and the input points.
|
276 |
+
|
277 |
+
This transform interfaces with the PyTorch3D renderer which assumes
|
278 |
+
input points to the renderer to be in NDC space.
|
279 |
+
"""
|
280 |
+
if self.in_ndc():
|
281 |
+
return Transform3d(device=self.device, dtype=torch.float32)
|
282 |
+
else:
|
283 |
+
# For custom cameras which can be defined in screen space,
|
284 |
+
# users might might have to implement the screen to NDC transform based
|
285 |
+
# on the definition of the camera parameters.
|
286 |
+
# See PerspectiveCameras/OrthographicCameras for an example.
|
287 |
+
# We don't flip xy because we assume that world points are in
|
288 |
+
# PyTorch3D coordinates, and thus conversion from screen to ndc
|
289 |
+
# is a mere scaling from image to [-1, 1] scale.
|
290 |
+
image_size = kwargs.get("image_size", self.get_image_size())
|
291 |
+
return get_screen_to_ndc_transform(self, with_xyflip=False, image_size=image_size)
|
292 |
+
|
293 |
+
def transform_points_ndc(self, points, eps: Optional[float] = None, **kwargs) -> torch.Tensor:
|
294 |
+
"""
|
295 |
+
Transforms points from PyTorch3D world/camera space to NDC space.
|
296 |
+
Input points follow the PyTorch3D coordinate system conventions: +X left, +Y up.
|
297 |
+
Output points are in NDC space: +X left, +Y up, origin at image center.
|
298 |
+
|
299 |
+
Args:
|
300 |
+
points: torch tensor of shape (..., 3).
|
301 |
+
eps: If eps!=None, the argument is used to clamp the
|
302 |
+
divisor in the homogeneous normalization of the points
|
303 |
+
transformed to the ndc space. Please see
|
304 |
+
`transforms.Transform3d.transform_points` for details.
|
305 |
+
|
306 |
+
For `CamerasBase.transform_points`, setting `eps > 0`
|
307 |
+
stabilizes gradients since it leads to avoiding division
|
308 |
+
by excessively low numbers for points close to the
|
309 |
+
camera plane.
|
310 |
+
|
311 |
+
Returns
|
312 |
+
new_points: transformed points with the same shape as the input.
|
313 |
+
"""
|
314 |
+
world_to_ndc_transform = self.get_full_projection_transform(**kwargs)
|
315 |
+
if not self.in_ndc():
|
316 |
+
to_ndc_transform = self.get_ndc_camera_transform(**kwargs)
|
317 |
+
world_to_ndc_transform = world_to_ndc_transform.compose(to_ndc_transform)
|
318 |
+
|
319 |
+
return world_to_ndc_transform.transform_points(points, eps=eps)
|
320 |
+
|
321 |
+
def transform_points_screen(
|
322 |
+
self, points, eps: Optional[float] = None, with_xyflip: bool = True, **kwargs
|
323 |
+
) -> torch.Tensor:
|
324 |
+
"""
|
325 |
+
Transforms points from PyTorch3D world/camera space to screen space.
|
326 |
+
Input points follow the PyTorch3D coordinate system conventions: +X left, +Y up.
|
327 |
+
Output points are in screen space: +X right, +Y down, origin at top left corner.
|
328 |
+
|
329 |
+
Args:
|
330 |
+
points: torch tensor of shape (..., 3).
|
331 |
+
eps: If eps!=None, the argument is used to clamp the
|
332 |
+
divisor in the homogeneous normalization of the points
|
333 |
+
transformed to the ndc space. Please see
|
334 |
+
`transforms.Transform3d.transform_points` for details.
|
335 |
+
|
336 |
+
For `CamerasBase.transform_points`, setting `eps > 0`
|
337 |
+
stabilizes gradients since it leads to avoiding division
|
338 |
+
by excessively low numbers for points close to the
|
339 |
+
camera plane.
|
340 |
+
with_xyflip: If True, flip x and y directions. In world/camera/ndc coords,
|
341 |
+
+x points to the left and +y up. If with_xyflip is true, in screen
|
342 |
+
coords +x points right, and +y down, following the usual RGB image
|
343 |
+
convention. Warning: do not set to False unless you know what you're
|
344 |
+
doing!
|
345 |
+
|
346 |
+
Returns
|
347 |
+
new_points: transformed points with the same shape as the input.
|
348 |
+
"""
|
349 |
+
points_ndc = self.transform_points_ndc(points, eps=eps, **kwargs)
|
350 |
+
image_size = kwargs.get("image_size", self.get_image_size())
|
351 |
+
return get_ndc_to_screen_transform(self, with_xyflip=with_xyflip, image_size=image_size).transform_points(
|
352 |
+
points_ndc, eps=eps
|
353 |
+
)
|
354 |
+
|
355 |
+
def clone(self):
|
356 |
+
"""
|
357 |
+
Returns a copy of `self`.
|
358 |
+
"""
|
359 |
+
cam_type = type(self)
|
360 |
+
other = cam_type(device=self.device)
|
361 |
+
return super().clone(other)
|
362 |
+
|
363 |
+
def is_perspective(self):
|
364 |
+
raise NotImplementedError()
|
365 |
+
|
366 |
+
def in_ndc(self):
|
367 |
+
"""
|
368 |
+
Specifies whether the camera is defined in NDC space
|
369 |
+
or in screen (image) space
|
370 |
+
"""
|
371 |
+
raise NotImplementedError()
|
372 |
+
|
373 |
+
def get_znear(self):
|
374 |
+
return getattr(self, "znear", None)
|
375 |
+
|
376 |
+
def get_image_size(self):
|
377 |
+
"""
|
378 |
+
Returns the image size, if provided, expected in the form of (height, width)
|
379 |
+
The image size is used for conversion of projected points to screen coordinates.
|
380 |
+
"""
|
381 |
+
return getattr(self, "image_size", None)
|
382 |
+
|
383 |
+
def __getitem__(self, index: Union[int, List[int], torch.BoolTensor, torch.LongTensor]) -> "CamerasBase":
|
384 |
+
"""
|
385 |
+
Override for the __getitem__ method in TensorProperties which needs to be
|
386 |
+
refactored.
|
387 |
+
|
388 |
+
Args:
|
389 |
+
index: an integer index, list/tensor of integer indices, or tensor of boolean
|
390 |
+
indicators used to filter all the fields in the cameras given by self._FIELDS.
|
391 |
+
Returns:
|
392 |
+
an instance of the current cameras class with only the values at the selected index.
|
393 |
+
"""
|
394 |
+
|
395 |
+
kwargs = {}
|
396 |
+
|
397 |
+
tensor_types = {
|
398 |
+
# pyre-fixme[16]: Module `cuda` has no attribute `BoolTensor`.
|
399 |
+
"bool": (torch.BoolTensor, torch.cuda.BoolTensor),
|
400 |
+
# pyre-fixme[16]: Module `cuda` has no attribute `LongTensor`.
|
401 |
+
"long": (torch.LongTensor, torch.cuda.LongTensor),
|
402 |
+
}
|
403 |
+
if not isinstance(index, (int, list, *tensor_types["bool"], *tensor_types["long"])) or (
|
404 |
+
isinstance(index, list) and not all(isinstance(i, int) and not isinstance(i, bool) for i in index)
|
405 |
+
):
|
406 |
+
msg = "Invalid index type, expected int, List[int] or Bool/LongTensor; got %r"
|
407 |
+
raise ValueError(msg % type(index))
|
408 |
+
|
409 |
+
if isinstance(index, int):
|
410 |
+
index = [index]
|
411 |
+
|
412 |
+
if isinstance(index, tensor_types["bool"]):
|
413 |
+
# pyre-fixme[16]: Item `List` of `Union[List[int], BoolTensor,
|
414 |
+
# LongTensor]` has no attribute `ndim`.
|
415 |
+
# pyre-fixme[16]: Item `List` of `Union[List[int], BoolTensor,
|
416 |
+
# LongTensor]` has no attribute `shape`.
|
417 |
+
if index.ndim != 1 or index.shape[0] != len(self):
|
418 |
+
raise ValueError(
|
419 |
+
# pyre-fixme[16]: Item `List` of `Union[List[int], BoolTensor,
|
420 |
+
# LongTensor]` has no attribute `shape`.
|
421 |
+
f"Boolean index of shape {index.shape} does not match cameras"
|
422 |
+
)
|
423 |
+
elif max(index) >= len(self):
|
424 |
+
raise IndexError(f"Index {max(index)} is out of bounds for select cameras")
|
425 |
+
|
426 |
+
for field in self._FIELDS:
|
427 |
+
val = getattr(self, field, None)
|
428 |
+
if val is None:
|
429 |
+
continue
|
430 |
+
|
431 |
+
# e.g. "in_ndc" is set as attribute "_in_ndc" on the class
|
432 |
+
# but provided as "in_ndc" on initialization
|
433 |
+
if field.startswith("_"):
|
434 |
+
field = field[1:]
|
435 |
+
|
436 |
+
if isinstance(val, (str, bool)):
|
437 |
+
kwargs[field] = val
|
438 |
+
elif isinstance(val, torch.Tensor):
|
439 |
+
# In the init, all inputs will be converted to
|
440 |
+
# tensors before setting as attributes
|
441 |
+
kwargs[field] = val[index]
|
442 |
+
else:
|
443 |
+
raise ValueError(f"Field {field} type is not supported for indexing")
|
444 |
+
|
445 |
+
kwargs["device"] = self.device
|
446 |
+
return self.__class__(**kwargs)
|
447 |
+
|
448 |
+
|
449 |
+
############################################################
|
450 |
+
# Field of View Camera Classes #
|
451 |
+
############################################################
|
452 |
+
|
453 |
+
|
454 |
+
def OpenGLPerspectiveCameras(
|
455 |
+
znear: _BatchFloatType = 1.0,
|
456 |
+
zfar: _BatchFloatType = 100.0,
|
457 |
+
aspect_ratio: _BatchFloatType = 1.0,
|
458 |
+
fov: _BatchFloatType = 60.0,
|
459 |
+
degrees: bool = True,
|
460 |
+
R: torch.Tensor = _R,
|
461 |
+
T: torch.Tensor = _T,
|
462 |
+
device: Device = "cpu",
|
463 |
+
) -> "FoVPerspectiveCameras":
|
464 |
+
"""
|
465 |
+
OpenGLPerspectiveCameras has been DEPRECATED. Use FoVPerspectiveCameras instead.
|
466 |
+
Preserving OpenGLPerspectiveCameras for backward compatibility.
|
467 |
+
"""
|
468 |
+
|
469 |
+
warnings.warn(
|
470 |
+
"""OpenGLPerspectiveCameras is deprecated,
|
471 |
+
Use FoVPerspectiveCameras instead.
|
472 |
+
OpenGLPerspectiveCameras will be removed in future releases.""",
|
473 |
+
PendingDeprecationWarning,
|
474 |
+
)
|
475 |
+
|
476 |
+
return FoVPerspectiveCameras(
|
477 |
+
znear=znear, zfar=zfar, aspect_ratio=aspect_ratio, fov=fov, degrees=degrees, R=R, T=T, device=device
|
478 |
+
)
|
479 |
+
|
480 |
+
|
481 |
+
class FoVPerspectiveCameras(CamerasBase):
|
482 |
+
"""
|
483 |
+
A class which stores a batch of parameters to generate a batch of
|
484 |
+
projection matrices by specifying the field of view.
|
485 |
+
The definitions of the parameters follow the OpenGL perspective camera.
|
486 |
+
|
487 |
+
The extrinsics of the camera (R and T matrices) can also be set in the
|
488 |
+
initializer or passed in to `get_full_projection_transform` to get
|
489 |
+
the full transformation from world -> ndc.
|
490 |
+
|
491 |
+
The `transform_points` method calculates the full world -> ndc transform
|
492 |
+
and then applies it to the input points.
|
493 |
+
|
494 |
+
The transforms can also be returned separately as Transform3d objects.
|
495 |
+
|
496 |
+
* Setting the Aspect Ratio for Non Square Images *
|
497 |
+
|
498 |
+
If the desired output image size is non square (i.e. a tuple of (H, W) where H != W)
|
499 |
+
the aspect ratio needs special consideration: There are two aspect ratios
|
500 |
+
to be aware of:
|
501 |
+
- the aspect ratio of each pixel
|
502 |
+
- the aspect ratio of the output image
|
503 |
+
The `aspect_ratio` setting in the FoVPerspectiveCameras sets the
|
504 |
+
pixel aspect ratio. When using this camera with the differentiable rasterizer
|
505 |
+
be aware that in the rasterizer we assume square pixels, but allow
|
506 |
+
variable image aspect ratio (i.e rectangle images).
|
507 |
+
|
508 |
+
In most cases you will want to set the camera `aspect_ratio=1.0`
|
509 |
+
(i.e. square pixels) and only vary the output image dimensions in pixels
|
510 |
+
for rasterization.
|
511 |
+
"""
|
512 |
+
|
513 |
+
# For __getitem__
|
514 |
+
_FIELDS = ("K", "znear", "zfar", "aspect_ratio", "fov", "R", "T", "degrees")
|
515 |
+
|
516 |
+
_SHARED_FIELDS = ("degrees",)
|
517 |
+
|
518 |
+
def __init__(
|
519 |
+
self,
|
520 |
+
znear: _BatchFloatType = 1.0,
|
521 |
+
zfar: _BatchFloatType = 100.0,
|
522 |
+
aspect_ratio: _BatchFloatType = 1.0,
|
523 |
+
fov: _BatchFloatType = 60.0,
|
524 |
+
degrees: bool = True,
|
525 |
+
R: torch.Tensor = _R,
|
526 |
+
T: torch.Tensor = _T,
|
527 |
+
K: Optional[torch.Tensor] = None,
|
528 |
+
device: Device = "cpu",
|
529 |
+
) -> None:
|
530 |
+
"""
|
531 |
+
|
532 |
+
Args:
|
533 |
+
znear: near clipping plane of the view frustrum.
|
534 |
+
zfar: far clipping plane of the view frustrum.
|
535 |
+
aspect_ratio: aspect ratio of the image pixels.
|
536 |
+
1.0 indicates square pixels.
|
537 |
+
fov: field of view angle of the camera.
|
538 |
+
degrees: bool, set to True if fov is specified in degrees.
|
539 |
+
R: Rotation matrix of shape (N, 3, 3)
|
540 |
+
T: Translation matrix of shape (N, 3)
|
541 |
+
K: (optional) A calibration matrix of shape (N, 4, 4)
|
542 |
+
If provided, don't need znear, zfar, fov, aspect_ratio, degrees
|
543 |
+
device: Device (as str or torch.device)
|
544 |
+
"""
|
545 |
+
# The initializer formats all inputs to torch tensors and broadcasts
|
546 |
+
# all the inputs to have the same batch dimension where necessary.
|
547 |
+
super().__init__(device=device, znear=znear, zfar=zfar, aspect_ratio=aspect_ratio, fov=fov, R=R, T=T, K=K)
|
548 |
+
|
549 |
+
# No need to convert to tensor or broadcast.
|
550 |
+
self.degrees = degrees
|
551 |
+
|
552 |
+
def compute_projection_matrix(self, znear, zfar, fov, aspect_ratio, degrees: bool) -> torch.Tensor:
|
553 |
+
"""
|
554 |
+
Compute the calibration matrix K of shape (N, 4, 4)
|
555 |
+
|
556 |
+
Args:
|
557 |
+
znear: near clipping plane of the view frustrum.
|
558 |
+
zfar: far clipping plane of the view frustrum.
|
559 |
+
fov: field of view angle of the camera.
|
560 |
+
aspect_ratio: aspect ratio of the image pixels.
|
561 |
+
1.0 indicates square pixels.
|
562 |
+
degrees: bool, set to True if fov is specified in degrees.
|
563 |
+
|
564 |
+
Returns:
|
565 |
+
torch.FloatTensor of the calibration matrix with shape (N, 4, 4)
|
566 |
+
"""
|
567 |
+
K = torch.zeros((self._N, 4, 4), device=self.device, dtype=torch.float32)
|
568 |
+
ones = torch.ones((self._N), dtype=torch.float32, device=self.device)
|
569 |
+
if degrees:
|
570 |
+
fov = (np.pi / 180) * fov
|
571 |
+
|
572 |
+
if not torch.is_tensor(fov):
|
573 |
+
fov = torch.tensor(fov, device=self.device)
|
574 |
+
tanHalfFov = torch.tan((fov / 2))
|
575 |
+
max_y = tanHalfFov * znear
|
576 |
+
min_y = -max_y
|
577 |
+
max_x = max_y * aspect_ratio
|
578 |
+
min_x = -max_x
|
579 |
+
|
580 |
+
# NOTE: In OpenGL the projection matrix changes the handedness of the
|
581 |
+
# coordinate frame. i.e the NDC space positive z direction is the
|
582 |
+
# camera space negative z direction. This is because the sign of the z
|
583 |
+
# in the projection matrix is set to -1.0.
|
584 |
+
# In pytorch3d we maintain a right handed coordinate system throughout
|
585 |
+
# so the so the z sign is 1.0.
|
586 |
+
z_sign = 1.0
|
587 |
+
|
588 |
+
# pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`.
|
589 |
+
K[:, 0, 0] = 2.0 * znear / (max_x - min_x)
|
590 |
+
# pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`.
|
591 |
+
K[:, 1, 1] = 2.0 * znear / (max_y - min_y)
|
592 |
+
K[:, 0, 2] = (max_x + min_x) / (max_x - min_x)
|
593 |
+
K[:, 1, 2] = (max_y + min_y) / (max_y - min_y)
|
594 |
+
K[:, 3, 2] = z_sign * ones
|
595 |
+
|
596 |
+
# NOTE: This maps the z coordinate from [0, 1] where z = 0 if the point
|
597 |
+
# is at the near clipping plane and z = 1 when the point is at the far
|
598 |
+
# clipping plane.
|
599 |
+
K[:, 2, 2] = z_sign * zfar / (zfar - znear)
|
600 |
+
K[:, 2, 3] = -(zfar * znear) / (zfar - znear)
|
601 |
+
|
602 |
+
return K
|
603 |
+
|
604 |
+
def get_projection_transform(self, **kwargs) -> Transform3d:
|
605 |
+
"""
|
606 |
+
Calculate the perspective projection matrix with a symmetric
|
607 |
+
viewing frustrum. Use column major order.
|
608 |
+
The viewing frustrum will be projected into ndc, s.t.
|
609 |
+
(max_x, max_y) -> (+1, +1)
|
610 |
+
(min_x, min_y) -> (-1, -1)
|
611 |
+
|
612 |
+
Args:
|
613 |
+
**kwargs: parameters for the projection can be passed in as keyword
|
614 |
+
arguments to override the default values set in `__init__`.
|
615 |
+
|
616 |
+
Return:
|
617 |
+
a Transform3d object which represents a batch of projection
|
618 |
+
matrices of shape (N, 4, 4)
|
619 |
+
|
620 |
+
.. code-block:: python
|
621 |
+
|
622 |
+
h1 = (max_y + min_y)/(max_y - min_y)
|
623 |
+
w1 = (max_x + min_x)/(max_x - min_x)
|
624 |
+
tanhalffov = tan((fov/2))
|
625 |
+
s1 = 1/tanhalffov
|
626 |
+
s2 = 1/(tanhalffov * (aspect_ratio))
|
627 |
+
|
628 |
+
# To map z to the range [0, 1] use:
|
629 |
+
f1 = far / (far - near)
|
630 |
+
f2 = -(far * near) / (far - near)
|
631 |
+
|
632 |
+
# Projection matrix
|
633 |
+
K = [
|
634 |
+
[s1, 0, w1, 0],
|
635 |
+
[0, s2, h1, 0],
|
636 |
+
[0, 0, f1, f2],
|
637 |
+
[0, 0, 1, 0],
|
638 |
+
]
|
639 |
+
"""
|
640 |
+
K = kwargs.get("K", self.K)
|
641 |
+
if K is not None:
|
642 |
+
if K.shape != (self._N, 4, 4):
|
643 |
+
msg = "Expected K to have shape of (%r, 4, 4)"
|
644 |
+
raise ValueError(msg % (self._N))
|
645 |
+
else:
|
646 |
+
K = self.compute_projection_matrix(
|
647 |
+
kwargs.get("znear", self.znear),
|
648 |
+
kwargs.get("zfar", self.zfar),
|
649 |
+
kwargs.get("fov", self.fov),
|
650 |
+
kwargs.get("aspect_ratio", self.aspect_ratio),
|
651 |
+
kwargs.get("degrees", self.degrees),
|
652 |
+
)
|
653 |
+
|
654 |
+
# Transpose the projection matrix as PyTorch3D transforms use row vectors.
|
655 |
+
transform = Transform3d(matrix=K.transpose(1, 2).contiguous(), device=self.device)
|
656 |
+
return transform
|
657 |
+
|
658 |
+
def unproject_points(
|
659 |
+
self, xy_depth: torch.Tensor, world_coordinates: bool = True, scaled_depth_input: bool = False, **kwargs
|
660 |
+
) -> torch.Tensor:
|
661 |
+
""">!
|
662 |
+
FoV cameras further allow for passing depth in world units
|
663 |
+
(`scaled_depth_input=False`) or in the [0, 1]-normalized units
|
664 |
+
(`scaled_depth_input=True`)
|
665 |
+
|
666 |
+
Args:
|
667 |
+
scaled_depth_input: If `True`, assumes the input depth is in
|
668 |
+
the [0, 1]-normalized units. If `False` the input depth is in
|
669 |
+
the world units.
|
670 |
+
"""
|
671 |
+
|
672 |
+
# obtain the relevant transformation to ndc
|
673 |
+
if world_coordinates:
|
674 |
+
to_ndc_transform = self.get_full_projection_transform()
|
675 |
+
else:
|
676 |
+
to_ndc_transform = self.get_projection_transform()
|
677 |
+
|
678 |
+
if scaled_depth_input:
|
679 |
+
# the input is scaled depth, so we don't have to do anything
|
680 |
+
xy_sdepth = xy_depth
|
681 |
+
else:
|
682 |
+
# parse out important values from the projection matrix
|
683 |
+
K_matrix = self.get_projection_transform(**kwargs.copy()).get_matrix()
|
684 |
+
# parse out f1, f2 from K_matrix
|
685 |
+
unsqueeze_shape = [1] * xy_depth.dim()
|
686 |
+
unsqueeze_shape[0] = K_matrix.shape[0]
|
687 |
+
f1 = K_matrix[:, 2, 2].reshape(unsqueeze_shape)
|
688 |
+
f2 = K_matrix[:, 3, 2].reshape(unsqueeze_shape)
|
689 |
+
# get the scaled depth
|
690 |
+
sdepth = (f1 * xy_depth[..., 2:3] + f2) / xy_depth[..., 2:3]
|
691 |
+
# concatenate xy + scaled depth
|
692 |
+
xy_sdepth = torch.cat((xy_depth[..., 0:2], sdepth), dim=-1)
|
693 |
+
|
694 |
+
# unproject with inverse of the projection
|
695 |
+
unprojection_transform = to_ndc_transform.inverse()
|
696 |
+
return unprojection_transform.transform_points(xy_sdepth)
|
697 |
+
|
698 |
+
def is_perspective(self):
|
699 |
+
return True
|
700 |
+
|
701 |
+
def in_ndc(self):
|
702 |
+
return True
|
703 |
+
|
704 |
+
|
705 |
+
def OpenGLOrthographicCameras(
|
706 |
+
znear: _BatchFloatType = 1.0,
|
707 |
+
zfar: _BatchFloatType = 100.0,
|
708 |
+
top: _BatchFloatType = 1.0,
|
709 |
+
bottom: _BatchFloatType = -1.0,
|
710 |
+
left: _BatchFloatType = -1.0,
|
711 |
+
right: _BatchFloatType = 1.0,
|
712 |
+
scale_xyz=((1.0, 1.0, 1.0),), # (1, 3)
|
713 |
+
R: torch.Tensor = _R,
|
714 |
+
T: torch.Tensor = _T,
|
715 |
+
device: Device = "cpu",
|
716 |
+
) -> "FoVOrthographicCameras":
|
717 |
+
"""
|
718 |
+
OpenGLOrthographicCameras has been DEPRECATED. Use FoVOrthographicCameras instead.
|
719 |
+
Preserving OpenGLOrthographicCameras for backward compatibility.
|
720 |
+
"""
|
721 |
+
|
722 |
+
warnings.warn(
|
723 |
+
"""OpenGLOrthographicCameras is deprecated,
|
724 |
+
Use FoVOrthographicCameras instead.
|
725 |
+
OpenGLOrthographicCameras will be removed in future releases.""",
|
726 |
+
PendingDeprecationWarning,
|
727 |
+
)
|
728 |
+
|
729 |
+
return FoVOrthographicCameras(
|
730 |
+
znear=znear,
|
731 |
+
zfar=zfar,
|
732 |
+
max_y=top,
|
733 |
+
min_y=bottom,
|
734 |
+
max_x=right,
|
735 |
+
min_x=left,
|
736 |
+
scale_xyz=scale_xyz,
|
737 |
+
R=R,
|
738 |
+
T=T,
|
739 |
+
device=device,
|
740 |
+
)
|
741 |
+
|
742 |
+
|
743 |
+
class FoVOrthographicCameras(CamerasBase):
|
744 |
+
"""
|
745 |
+
A class which stores a batch of parameters to generate a batch of
|
746 |
+
projection matrices by specifying the field of view.
|
747 |
+
The definitions of the parameters follow the OpenGL orthographic camera.
|
748 |
+
"""
|
749 |
+
|
750 |
+
# For __getitem__
|
751 |
+
_FIELDS = ("K", "znear", "zfar", "R", "T", "max_y", "min_y", "max_x", "min_x", "scale_xyz")
|
752 |
+
|
753 |
+
def __init__(
|
754 |
+
self,
|
755 |
+
znear: _BatchFloatType = 1.0,
|
756 |
+
zfar: _BatchFloatType = 100.0,
|
757 |
+
max_y: _BatchFloatType = 1.0,
|
758 |
+
min_y: _BatchFloatType = -1.0,
|
759 |
+
max_x: _BatchFloatType = 1.0,
|
760 |
+
min_x: _BatchFloatType = -1.0,
|
761 |
+
scale_xyz=((1.0, 1.0, 1.0),), # (1, 3)
|
762 |
+
R: torch.Tensor = _R,
|
763 |
+
T: torch.Tensor = _T,
|
764 |
+
K: Optional[torch.Tensor] = None,
|
765 |
+
device: Device = "cpu",
|
766 |
+
):
|
767 |
+
"""
|
768 |
+
|
769 |
+
Args:
|
770 |
+
znear: near clipping plane of the view frustrum.
|
771 |
+
zfar: far clipping plane of the view frustrum.
|
772 |
+
max_y: maximum y coordinate of the frustrum.
|
773 |
+
min_y: minimum y coordinate of the frustrum.
|
774 |
+
max_x: maximum x coordinate of the frustrum.
|
775 |
+
min_x: minimum x coordinate of the frustrum
|
776 |
+
scale_xyz: scale factors for each axis of shape (N, 3).
|
777 |
+
R: Rotation matrix of shape (N, 3, 3).
|
778 |
+
T: Translation of shape (N, 3).
|
779 |
+
K: (optional) A calibration matrix of shape (N, 4, 4)
|
780 |
+
If provided, don't need znear, zfar, max_y, min_y, max_x, min_x, scale_xyz
|
781 |
+
device: torch.device or string.
|
782 |
+
|
783 |
+
Only need to set min_x, max_x, min_y, max_y for viewing frustrums
|
784 |
+
which are non symmetric about the origin.
|
785 |
+
"""
|
786 |
+
# The initializer formats all inputs to torch tensors and broadcasts
|
787 |
+
# all the inputs to have the same batch dimension where necessary.
|
788 |
+
super().__init__(
|
789 |
+
device=device,
|
790 |
+
znear=znear,
|
791 |
+
zfar=zfar,
|
792 |
+
max_y=max_y,
|
793 |
+
min_y=min_y,
|
794 |
+
max_x=max_x,
|
795 |
+
min_x=min_x,
|
796 |
+
scale_xyz=scale_xyz,
|
797 |
+
R=R,
|
798 |
+
T=T,
|
799 |
+
K=K,
|
800 |
+
)
|
801 |
+
|
802 |
+
def compute_projection_matrix(self, znear, zfar, max_x, min_x, max_y, min_y, scale_xyz) -> torch.Tensor:
|
803 |
+
"""
|
804 |
+
Compute the calibration matrix K of shape (N, 4, 4)
|
805 |
+
|
806 |
+
Args:
|
807 |
+
znear: near clipping plane of the view frustrum.
|
808 |
+
zfar: far clipping plane of the view frustrum.
|
809 |
+
max_x: maximum x coordinate of the frustrum.
|
810 |
+
min_x: minimum x coordinate of the frustrum
|
811 |
+
max_y: maximum y coordinate of the frustrum.
|
812 |
+
min_y: minimum y coordinate of the frustrum.
|
813 |
+
scale_xyz: scale factors for each axis of shape (N, 3).
|
814 |
+
"""
|
815 |
+
K = torch.zeros((self._N, 4, 4), dtype=torch.float32, device=self.device)
|
816 |
+
ones = torch.ones((self._N), dtype=torch.float32, device=self.device)
|
817 |
+
# NOTE: OpenGL flips handedness of coordinate system between camera
|
818 |
+
# space and NDC space so z sign is -ve. In PyTorch3D we maintain a
|
819 |
+
# right handed coordinate system throughout.
|
820 |
+
z_sign = +1.0
|
821 |
+
|
822 |
+
K[:, 0, 0] = (2.0 / (max_x - min_x)) * scale_xyz[:, 0]
|
823 |
+
K[:, 1, 1] = (2.0 / (max_y - min_y)) * scale_xyz[:, 1]
|
824 |
+
K[:, 0, 3] = -(max_x + min_x) / (max_x - min_x)
|
825 |
+
K[:, 1, 3] = -(max_y + min_y) / (max_y - min_y)
|
826 |
+
K[:, 3, 3] = ones
|
827 |
+
|
828 |
+
# NOTE: This maps the z coordinate to the range [0, 1] and replaces the
|
829 |
+
# the OpenGL z normalization to [-1, 1]
|
830 |
+
K[:, 2, 2] = z_sign * (1.0 / (zfar - znear)) * scale_xyz[:, 2]
|
831 |
+
K[:, 2, 3] = -znear / (zfar - znear)
|
832 |
+
|
833 |
+
return K
|
834 |
+
|
835 |
+
def get_projection_transform(self, **kwargs) -> Transform3d:
|
836 |
+
"""
|
837 |
+
Calculate the orthographic projection matrix.
|
838 |
+
Use column major order.
|
839 |
+
|
840 |
+
Args:
|
841 |
+
**kwargs: parameters for the projection can be passed in to
|
842 |
+
override the default values set in __init__.
|
843 |
+
Return:
|
844 |
+
a Transform3d object which represents a batch of projection
|
845 |
+
matrices of shape (N, 4, 4)
|
846 |
+
|
847 |
+
.. code-block:: python
|
848 |
+
|
849 |
+
scale_x = 2 / (max_x - min_x)
|
850 |
+
scale_y = 2 / (max_y - min_y)
|
851 |
+
scale_z = 2 / (far-near)
|
852 |
+
mid_x = (max_x + min_x) / (max_x - min_x)
|
853 |
+
mix_y = (max_y + min_y) / (max_y - min_y)
|
854 |
+
mid_z = (far + near) / (far - near)
|
855 |
+
|
856 |
+
K = [
|
857 |
+
[scale_x, 0, 0, -mid_x],
|
858 |
+
[0, scale_y, 0, -mix_y],
|
859 |
+
[0, 0, -scale_z, -mid_z],
|
860 |
+
[0, 0, 0, 1],
|
861 |
+
]
|
862 |
+
"""
|
863 |
+
K = kwargs.get("K", self.K)
|
864 |
+
if K is not None:
|
865 |
+
if K.shape != (self._N, 4, 4):
|
866 |
+
msg = "Expected K to have shape of (%r, 4, 4)"
|
867 |
+
raise ValueError(msg % (self._N))
|
868 |
+
else:
|
869 |
+
K = self.compute_projection_matrix(
|
870 |
+
kwargs.get("znear", self.znear),
|
871 |
+
kwargs.get("zfar", self.zfar),
|
872 |
+
kwargs.get("max_x", self.max_x),
|
873 |
+
kwargs.get("min_x", self.min_x),
|
874 |
+
kwargs.get("max_y", self.max_y),
|
875 |
+
kwargs.get("min_y", self.min_y),
|
876 |
+
kwargs.get("scale_xyz", self.scale_xyz),
|
877 |
+
)
|
878 |
+
|
879 |
+
transform = Transform3d(matrix=K.transpose(1, 2).contiguous(), device=self.device)
|
880 |
+
return transform
|
881 |
+
|
882 |
+
def unproject_points(
|
883 |
+
self, xy_depth: torch.Tensor, world_coordinates: bool = True, scaled_depth_input: bool = False, **kwargs
|
884 |
+
) -> torch.Tensor:
|
885 |
+
""">!
|
886 |
+
FoV cameras further allow for passing depth in world units
|
887 |
+
(`scaled_depth_input=False`) or in the [0, 1]-normalized units
|
888 |
+
(`scaled_depth_input=True`)
|
889 |
+
|
890 |
+
Args:
|
891 |
+
scaled_depth_input: If `True`, assumes the input depth is in
|
892 |
+
the [0, 1]-normalized units. If `False` the input depth is in
|
893 |
+
the world units.
|
894 |
+
"""
|
895 |
+
|
896 |
+
if world_coordinates:
|
897 |
+
to_ndc_transform = self.get_full_projection_transform(**kwargs.copy())
|
898 |
+
else:
|
899 |
+
to_ndc_transform = self.get_projection_transform(**kwargs.copy())
|
900 |
+
|
901 |
+
if scaled_depth_input:
|
902 |
+
# the input depth is already scaled
|
903 |
+
xy_sdepth = xy_depth
|
904 |
+
else:
|
905 |
+
# we have to obtain the scaled depth first
|
906 |
+
K = self.get_projection_transform(**kwargs).get_matrix()
|
907 |
+
unsqueeze_shape = [1] * K.dim()
|
908 |
+
unsqueeze_shape[0] = K.shape[0]
|
909 |
+
mid_z = K[:, 3, 2].reshape(unsqueeze_shape)
|
910 |
+
scale_z = K[:, 2, 2].reshape(unsqueeze_shape)
|
911 |
+
scaled_depth = scale_z * xy_depth[..., 2:3] + mid_z
|
912 |
+
# cat xy and scaled depth
|
913 |
+
xy_sdepth = torch.cat((xy_depth[..., :2], scaled_depth), dim=-1)
|
914 |
+
# finally invert the transform
|
915 |
+
unprojection_transform = to_ndc_transform.inverse()
|
916 |
+
return unprojection_transform.transform_points(xy_sdepth)
|
917 |
+
|
918 |
+
def is_perspective(self):
|
919 |
+
return False
|
920 |
+
|
921 |
+
def in_ndc(self):
|
922 |
+
return True
|
923 |
+
|
924 |
+
|
925 |
+
############################################################
|
926 |
+
# MultiView Camera Classes #
|
927 |
+
############################################################
|
928 |
+
"""
|
929 |
+
Note that the MultiView Cameras accept parameters in NDC space.
|
930 |
+
"""
|
931 |
+
|
932 |
+
|
933 |
+
def SfMPerspectiveCameras(
|
934 |
+
focal_length: _FocalLengthType = 1.0,
|
935 |
+
principal_point=((0.0, 0.0),),
|
936 |
+
R: torch.Tensor = _R,
|
937 |
+
T: torch.Tensor = _T,
|
938 |
+
device: Device = "cpu",
|
939 |
+
) -> "PerspectiveCameras":
|
940 |
+
"""
|
941 |
+
SfMPerspectiveCameras has been DEPRECATED. Use PerspectiveCameras instead.
|
942 |
+
Preserving SfMPerspectiveCameras for backward compatibility.
|
943 |
+
"""
|
944 |
+
|
945 |
+
warnings.warn(
|
946 |
+
"""SfMPerspectiveCameras is deprecated,
|
947 |
+
Use PerspectiveCameras instead.
|
948 |
+
SfMPerspectiveCameras will be removed in future releases.""",
|
949 |
+
PendingDeprecationWarning,
|
950 |
+
)
|
951 |
+
|
952 |
+
return PerspectiveCameras(focal_length=focal_length, principal_point=principal_point, R=R, T=T, device=device)
|
953 |
+
|
954 |
+
|
955 |
+
class PerspectiveCameras(CamerasBase):
|
956 |
+
"""
|
957 |
+
A class which stores a batch of parameters to generate a batch of
|
958 |
+
transformation matrices using the multi-view geometry convention for
|
959 |
+
perspective camera.
|
960 |
+
|
961 |
+
Parameters for this camera are specified in NDC if `in_ndc` is set to True.
|
962 |
+
If parameters are specified in screen space, `in_ndc` must be set to False.
|
963 |
+
"""
|
964 |
+
|
965 |
+
# For __getitem__
|
966 |
+
_FIELDS = (
|
967 |
+
"K",
|
968 |
+
"R",
|
969 |
+
"T",
|
970 |
+
"focal_length",
|
971 |
+
"principal_point",
|
972 |
+
"_in_ndc", # arg is in_ndc but attribute set as _in_ndc
|
973 |
+
"image_size",
|
974 |
+
)
|
975 |
+
|
976 |
+
_SHARED_FIELDS = ("_in_ndc",)
|
977 |
+
|
978 |
+
def __init__(
|
979 |
+
self,
|
980 |
+
focal_length: _FocalLengthType = 1.0,
|
981 |
+
principal_point=((0.0, 0.0),),
|
982 |
+
R: torch.Tensor = _R,
|
983 |
+
T: torch.Tensor = _T,
|
984 |
+
K: Optional[torch.Tensor] = None,
|
985 |
+
device: Device = "cpu",
|
986 |
+
in_ndc: bool = True,
|
987 |
+
image_size: Optional[Union[List, Tuple, torch.Tensor]] = None,
|
988 |
+
) -> None:
|
989 |
+
"""
|
990 |
+
|
991 |
+
Args:
|
992 |
+
focal_length: Focal length of the camera in world units.
|
993 |
+
A tensor of shape (N, 1) or (N, 2) for
|
994 |
+
square and non-square pixels respectively.
|
995 |
+
principal_point: xy coordinates of the center of
|
996 |
+
the principal point of the camera in pixels.
|
997 |
+
A tensor of shape (N, 2).
|
998 |
+
in_ndc: True if camera parameters are specified in NDC.
|
999 |
+
If camera parameters are in screen space, it must
|
1000 |
+
be set to False.
|
1001 |
+
R: Rotation matrix of shape (N, 3, 3)
|
1002 |
+
T: Translation matrix of shape (N, 3)
|
1003 |
+
K: (optional) A calibration matrix of shape (N, 4, 4)
|
1004 |
+
If provided, don't need focal_length, principal_point
|
1005 |
+
image_size: (height, width) of image size.
|
1006 |
+
A tensor of shape (N, 2) or a list/tuple. Required for screen cameras.
|
1007 |
+
device: torch.device or string
|
1008 |
+
"""
|
1009 |
+
# The initializer formats all inputs to torch tensors and broadcasts
|
1010 |
+
# all the inputs to have the same batch dimension where necessary.
|
1011 |
+
kwargs = {"image_size": image_size} if image_size is not None else {}
|
1012 |
+
super().__init__(
|
1013 |
+
device=device,
|
1014 |
+
focal_length=focal_length,
|
1015 |
+
principal_point=principal_point,
|
1016 |
+
R=R,
|
1017 |
+
T=T,
|
1018 |
+
K=K,
|
1019 |
+
_in_ndc=in_ndc,
|
1020 |
+
**kwargs, # pyre-ignore
|
1021 |
+
)
|
1022 |
+
if image_size is not None:
|
1023 |
+
if (self.image_size < 1).any(): # pyre-ignore
|
1024 |
+
raise ValueError("Image_size provided has invalid values")
|
1025 |
+
else:
|
1026 |
+
self.image_size = None
|
1027 |
+
|
1028 |
+
# When focal length is provided as one value, expand to
|
1029 |
+
# create (N, 2) shape tensor
|
1030 |
+
if self.focal_length.ndim == 1: # (N,)
|
1031 |
+
self.focal_length = self.focal_length[:, None] # (N, 1)
|
1032 |
+
self.focal_length = self.focal_length.expand(-1, 2) # (N, 2)
|
1033 |
+
|
1034 |
+
def get_projection_transform(self, **kwargs) -> Transform3d:
|
1035 |
+
"""
|
1036 |
+
Calculate the projection matrix using the
|
1037 |
+
multi-view geometry convention.
|
1038 |
+
|
1039 |
+
Args:
|
1040 |
+
**kwargs: parameters for the projection can be passed in as keyword
|
1041 |
+
arguments to override the default values set in __init__.
|
1042 |
+
|
1043 |
+
Returns:
|
1044 |
+
A `Transform3d` object with a batch of `N` projection transforms.
|
1045 |
+
|
1046 |
+
.. code-block:: python
|
1047 |
+
|
1048 |
+
fx = focal_length[:, 0]
|
1049 |
+
fy = focal_length[:, 1]
|
1050 |
+
px = principal_point[:, 0]
|
1051 |
+
py = principal_point[:, 1]
|
1052 |
+
|
1053 |
+
K = [
|
1054 |
+
[fx, 0, px, 0],
|
1055 |
+
[0, fy, py, 0],
|
1056 |
+
[0, 0, 0, 1],
|
1057 |
+
[0, 0, 1, 0],
|
1058 |
+
]
|
1059 |
+
"""
|
1060 |
+
K = kwargs.get("K", self.K)
|
1061 |
+
if K is not None:
|
1062 |
+
if K.shape != (self._N, 4, 4):
|
1063 |
+
msg = "Expected K to have shape of (%r, 4, 4)"
|
1064 |
+
raise ValueError(msg % (self._N))
|
1065 |
+
else:
|
1066 |
+
K = _get_sfm_calibration_matrix(
|
1067 |
+
self._N,
|
1068 |
+
self.device,
|
1069 |
+
kwargs.get("focal_length", self.focal_length),
|
1070 |
+
kwargs.get("principal_point", self.principal_point),
|
1071 |
+
orthographic=False,
|
1072 |
+
)
|
1073 |
+
|
1074 |
+
transform = Transform3d(matrix=K.transpose(1, 2).contiguous(), device=self.device)
|
1075 |
+
return transform
|
1076 |
+
|
1077 |
+
def unproject_points(
|
1078 |
+
self, xy_depth: torch.Tensor, world_coordinates: bool = True, from_ndc: bool = False, **kwargs
|
1079 |
+
) -> torch.Tensor:
|
1080 |
+
"""
|
1081 |
+
Args:
|
1082 |
+
from_ndc: If `False` (default), assumes xy part of input is in
|
1083 |
+
NDC space if self.in_ndc(), otherwise in screen space. If
|
1084 |
+
`True`, assumes xy is in NDC space even if the camera
|
1085 |
+
is defined in screen space.
|
1086 |
+
"""
|
1087 |
+
if world_coordinates:
|
1088 |
+
to_camera_transform = self.get_full_projection_transform(**kwargs)
|
1089 |
+
else:
|
1090 |
+
to_camera_transform = self.get_projection_transform(**kwargs)
|
1091 |
+
if from_ndc:
|
1092 |
+
to_camera_transform = to_camera_transform.compose(self.get_ndc_camera_transform())
|
1093 |
+
|
1094 |
+
unprojection_transform = to_camera_transform.inverse()
|
1095 |
+
xy_inv_depth = torch.cat((xy_depth[..., :2], 1.0 / xy_depth[..., 2:3]), dim=-1) # type: ignore
|
1096 |
+
return unprojection_transform.transform_points(xy_inv_depth)
|
1097 |
+
|
1098 |
+
def get_principal_point(self, **kwargs) -> torch.Tensor:
|
1099 |
+
"""
|
1100 |
+
Return the camera's principal point
|
1101 |
+
|
1102 |
+
Args:
|
1103 |
+
**kwargs: parameters for the camera extrinsics can be passed in
|
1104 |
+
as keyword arguments to override the default values
|
1105 |
+
set in __init__.
|
1106 |
+
"""
|
1107 |
+
proj_mat = self.get_projection_transform(**kwargs).get_matrix()
|
1108 |
+
return proj_mat[:, 2, :2]
|
1109 |
+
|
1110 |
+
def get_ndc_camera_transform(self, **kwargs) -> Transform3d:
|
1111 |
+
"""
|
1112 |
+
Returns the transform from camera projection space (screen or NDC) to NDC space.
|
1113 |
+
If the camera is defined already in NDC space, the transform is identity.
|
1114 |
+
For cameras defined in screen space, we adjust the principal point computation
|
1115 |
+
which is defined in the image space (commonly) and scale the points to NDC space.
|
1116 |
+
|
1117 |
+
This transform leaves the depth unchanged.
|
1118 |
+
|
1119 |
+
Important: This transforms assumes PyTorch3D conventions for the input points,
|
1120 |
+
i.e. +X left, +Y up.
|
1121 |
+
"""
|
1122 |
+
if self.in_ndc():
|
1123 |
+
ndc_transform = Transform3d(device=self.device, dtype=torch.float32)
|
1124 |
+
else:
|
1125 |
+
# when cameras are defined in screen/image space, the principal point is
|
1126 |
+
# provided in the (+X right, +Y down), aka image, coordinate system.
|
1127 |
+
# Since input points are defined in the PyTorch3D system (+X left, +Y up),
|
1128 |
+
# we need to adjust for the principal point transform.
|
1129 |
+
pr_point_fix = torch.zeros((self._N, 4, 4), device=self.device, dtype=torch.float32)
|
1130 |
+
pr_point_fix[:, 0, 0] = 1.0
|
1131 |
+
pr_point_fix[:, 1, 1] = 1.0
|
1132 |
+
pr_point_fix[:, 2, 2] = 1.0
|
1133 |
+
pr_point_fix[:, 3, 3] = 1.0
|
1134 |
+
pr_point_fix[:, :2, 3] = -2.0 * self.get_principal_point(**kwargs)
|
1135 |
+
pr_point_fix_transform = Transform3d(matrix=pr_point_fix.transpose(1, 2).contiguous(), device=self.device)
|
1136 |
+
image_size = kwargs.get("image_size", self.get_image_size())
|
1137 |
+
screen_to_ndc_transform = get_screen_to_ndc_transform(self, with_xyflip=False, image_size=image_size)
|
1138 |
+
ndc_transform = pr_point_fix_transform.compose(screen_to_ndc_transform)
|
1139 |
+
|
1140 |
+
return ndc_transform
|
1141 |
+
|
1142 |
+
def is_perspective(self):
|
1143 |
+
return True
|
1144 |
+
|
1145 |
+
def in_ndc(self):
|
1146 |
+
return self._in_ndc
|
1147 |
+
|
1148 |
+
|
1149 |
+
def SfMOrthographicCameras(
|
1150 |
+
focal_length: _FocalLengthType = 1.0,
|
1151 |
+
principal_point=((0.0, 0.0),),
|
1152 |
+
R: torch.Tensor = _R,
|
1153 |
+
T: torch.Tensor = _T,
|
1154 |
+
device: Device = "cpu",
|
1155 |
+
) -> "OrthographicCameras":
|
1156 |
+
"""
|
1157 |
+
SfMOrthographicCameras has been DEPRECATED. Use OrthographicCameras instead.
|
1158 |
+
Preserving SfMOrthographicCameras for backward compatibility.
|
1159 |
+
"""
|
1160 |
+
|
1161 |
+
warnings.warn(
|
1162 |
+
"""SfMOrthographicCameras is deprecated,
|
1163 |
+
Use OrthographicCameras instead.
|
1164 |
+
SfMOrthographicCameras will be removed in future releases.""",
|
1165 |
+
PendingDeprecationWarning,
|
1166 |
+
)
|
1167 |
+
|
1168 |
+
return OrthographicCameras(focal_length=focal_length, principal_point=principal_point, R=R, T=T, device=device)
|
1169 |
+
|
1170 |
+
|
1171 |
+
class OrthographicCameras(CamerasBase):
|
1172 |
+
"""
|
1173 |
+
A class which stores a batch of parameters to generate a batch of
|
1174 |
+
transformation matrices using the multi-view geometry convention for
|
1175 |
+
orthographic camera.
|
1176 |
+
|
1177 |
+
Parameters for this camera are specified in NDC if `in_ndc` is set to True.
|
1178 |
+
If parameters are specified in screen space, `in_ndc` must be set to False.
|
1179 |
+
"""
|
1180 |
+
|
1181 |
+
# For __getitem__
|
1182 |
+
_FIELDS = ("K", "R", "T", "focal_length", "principal_point", "_in_ndc", "image_size")
|
1183 |
+
|
1184 |
+
_SHARED_FIELDS = ("_in_ndc",)
|
1185 |
+
|
1186 |
+
def __init__(
|
1187 |
+
self,
|
1188 |
+
focal_length: _FocalLengthType = 1.0,
|
1189 |
+
principal_point=((0.0, 0.0),),
|
1190 |
+
R: torch.Tensor = _R,
|
1191 |
+
T: torch.Tensor = _T,
|
1192 |
+
K: Optional[torch.Tensor] = None,
|
1193 |
+
device: Device = "cpu",
|
1194 |
+
in_ndc: bool = True,
|
1195 |
+
image_size: Optional[Union[List, Tuple, torch.Tensor]] = None,
|
1196 |
+
) -> None:
|
1197 |
+
"""
|
1198 |
+
|
1199 |
+
Args:
|
1200 |
+
focal_length: Focal length of the camera in world units.
|
1201 |
+
A tensor of shape (N, 1) or (N, 2) for
|
1202 |
+
square and non-square pixels respectively.
|
1203 |
+
principal_point: xy coordinates of the center of
|
1204 |
+
the principal point of the camera in pixels.
|
1205 |
+
A tensor of shape (N, 2).
|
1206 |
+
in_ndc: True if camera parameters are specified in NDC.
|
1207 |
+
If False, then camera parameters are in screen space.
|
1208 |
+
R: Rotation matrix of shape (N, 3, 3)
|
1209 |
+
T: Translation matrix of shape (N, 3)
|
1210 |
+
K: (optional) A calibration matrix of shape (N, 4, 4)
|
1211 |
+
If provided, don't need focal_length, principal_point, image_size
|
1212 |
+
image_size: (height, width) of image size.
|
1213 |
+
A tensor of shape (N, 2) or list/tuple. Required for screen cameras.
|
1214 |
+
device: torch.device or string
|
1215 |
+
"""
|
1216 |
+
# The initializer formats all inputs to torch tensors and broadcasts
|
1217 |
+
# all the inputs to have the same batch dimension where necessary.
|
1218 |
+
kwargs = {"image_size": image_size} if image_size is not None else {}
|
1219 |
+
super().__init__(
|
1220 |
+
device=device,
|
1221 |
+
focal_length=focal_length,
|
1222 |
+
principal_point=principal_point,
|
1223 |
+
R=R,
|
1224 |
+
T=T,
|
1225 |
+
K=K,
|
1226 |
+
_in_ndc=in_ndc,
|
1227 |
+
**kwargs, # pyre-ignore
|
1228 |
+
)
|
1229 |
+
if image_size is not None:
|
1230 |
+
if (self.image_size < 1).any(): # pyre-ignore
|
1231 |
+
raise ValueError("Image_size provided has invalid values")
|
1232 |
+
else:
|
1233 |
+
self.image_size = None
|
1234 |
+
|
1235 |
+
# When focal length is provided as one value, expand to
|
1236 |
+
# create (N, 2) shape tensor
|
1237 |
+
if self.focal_length.ndim == 1: # (N,)
|
1238 |
+
self.focal_length = self.focal_length[:, None] # (N, 1)
|
1239 |
+
self.focal_length = self.focal_length.expand(-1, 2) # (N, 2)
|
1240 |
+
|
1241 |
+
def get_projection_transform(self, **kwargs) -> Transform3d:
|
1242 |
+
"""
|
1243 |
+
Calculate the projection matrix using
|
1244 |
+
the multi-view geometry convention.
|
1245 |
+
|
1246 |
+
Args:
|
1247 |
+
**kwargs: parameters for the projection can be passed in as keyword
|
1248 |
+
arguments to override the default values set in __init__.
|
1249 |
+
|
1250 |
+
Returns:
|
1251 |
+
A `Transform3d` object with a batch of `N` projection transforms.
|
1252 |
+
|
1253 |
+
.. code-block:: python
|
1254 |
+
|
1255 |
+
fx = focal_length[:,0]
|
1256 |
+
fy = focal_length[:,1]
|
1257 |
+
px = principal_point[:,0]
|
1258 |
+
py = principal_point[:,1]
|
1259 |
+
|
1260 |
+
K = [
|
1261 |
+
[fx, 0, 0, px],
|
1262 |
+
[0, fy, 0, py],
|
1263 |
+
[0, 0, 1, 0],
|
1264 |
+
[0, 0, 0, 1],
|
1265 |
+
]
|
1266 |
+
"""
|
1267 |
+
K = kwargs.get("K", self.K)
|
1268 |
+
if K is not None:
|
1269 |
+
if K.shape != (self._N, 4, 4):
|
1270 |
+
msg = "Expected K to have shape of (%r, 4, 4)"
|
1271 |
+
raise ValueError(msg % (self._N))
|
1272 |
+
else:
|
1273 |
+
K = _get_sfm_calibration_matrix(
|
1274 |
+
self._N,
|
1275 |
+
self.device,
|
1276 |
+
kwargs.get("focal_length", self.focal_length),
|
1277 |
+
kwargs.get("principal_point", self.principal_point),
|
1278 |
+
orthographic=True,
|
1279 |
+
)
|
1280 |
+
|
1281 |
+
transform = Transform3d(matrix=K.transpose(1, 2).contiguous(), device=self.device)
|
1282 |
+
return transform
|
1283 |
+
|
1284 |
+
def unproject_points(
|
1285 |
+
self, xy_depth: torch.Tensor, world_coordinates: bool = True, from_ndc: bool = False, **kwargs
|
1286 |
+
) -> torch.Tensor:
|
1287 |
+
"""
|
1288 |
+
Args:
|
1289 |
+
from_ndc: If `False` (default), assumes xy part of input is in
|
1290 |
+
NDC space if self.in_ndc(), otherwise in screen space. If
|
1291 |
+
`True`, assumes xy is in NDC space even if the camera
|
1292 |
+
is defined in screen space.
|
1293 |
+
"""
|
1294 |
+
if world_coordinates:
|
1295 |
+
to_camera_transform = self.get_full_projection_transform(**kwargs)
|
1296 |
+
else:
|
1297 |
+
to_camera_transform = self.get_projection_transform(**kwargs)
|
1298 |
+
if from_ndc:
|
1299 |
+
to_camera_transform = to_camera_transform.compose(self.get_ndc_camera_transform())
|
1300 |
+
|
1301 |
+
unprojection_transform = to_camera_transform.inverse()
|
1302 |
+
return unprojection_transform.transform_points(xy_depth)
|
1303 |
+
|
1304 |
+
def get_principal_point(self, **kwargs) -> torch.Tensor:
|
1305 |
+
"""
|
1306 |
+
Return the camera's principal point
|
1307 |
+
|
1308 |
+
Args:
|
1309 |
+
**kwargs: parameters for the camera extrinsics can be passed in
|
1310 |
+
as keyword arguments to override the default values
|
1311 |
+
set in __init__.
|
1312 |
+
"""
|
1313 |
+
proj_mat = self.get_projection_transform(**kwargs).get_matrix()
|
1314 |
+
return proj_mat[:, 3, :2]
|
1315 |
+
|
1316 |
+
def get_ndc_camera_transform(self, **kwargs) -> Transform3d:
|
1317 |
+
"""
|
1318 |
+
Returns the transform from camera projection space (screen or NDC) to NDC space.
|
1319 |
+
If the camera is defined already in NDC space, the transform is identity.
|
1320 |
+
For cameras defined in screen space, we adjust the principal point computation
|
1321 |
+
which is defined in the image space (commonly) and scale the points to NDC space.
|
1322 |
+
|
1323 |
+
Important: This transforms assumes PyTorch3D conventions for the input points,
|
1324 |
+
i.e. +X left, +Y up.
|
1325 |
+
"""
|
1326 |
+
if self.in_ndc():
|
1327 |
+
ndc_transform = Transform3d(device=self.device, dtype=torch.float32)
|
1328 |
+
else:
|
1329 |
+
# when cameras are defined in screen/image space, the principal point is
|
1330 |
+
# provided in the (+X right, +Y down), aka image, coordinate system.
|
1331 |
+
# Since input points are defined in the PyTorch3D system (+X left, +Y up),
|
1332 |
+
# we need to adjust for the principal point transform.
|
1333 |
+
pr_point_fix = torch.zeros((self._N, 4, 4), device=self.device, dtype=torch.float32)
|
1334 |
+
pr_point_fix[:, 0, 0] = 1.0
|
1335 |
+
pr_point_fix[:, 1, 1] = 1.0
|
1336 |
+
pr_point_fix[:, 2, 2] = 1.0
|
1337 |
+
pr_point_fix[:, 3, 3] = 1.0
|
1338 |
+
pr_point_fix[:, :2, 3] = -2.0 * self.get_principal_point(**kwargs)
|
1339 |
+
pr_point_fix_transform = Transform3d(matrix=pr_point_fix.transpose(1, 2).contiguous(), device=self.device)
|
1340 |
+
image_size = kwargs.get("image_size", self.get_image_size())
|
1341 |
+
screen_to_ndc_transform = get_screen_to_ndc_transform(self, with_xyflip=False, image_size=image_size)
|
1342 |
+
ndc_transform = pr_point_fix_transform.compose(screen_to_ndc_transform)
|
1343 |
+
|
1344 |
+
return ndc_transform
|
1345 |
+
|
1346 |
+
def is_perspective(self):
|
1347 |
+
return False
|
1348 |
+
|
1349 |
+
def in_ndc(self):
|
1350 |
+
return self._in_ndc
|
1351 |
+
|
1352 |
+
|
1353 |
+
################################################
|
1354 |
+
# Helper functions for cameras #
|
1355 |
+
################################################
|
1356 |
+
|
1357 |
+
|
1358 |
+
def _get_sfm_calibration_matrix(
|
1359 |
+
N: int, device: Device, focal_length, principal_point, orthographic: bool = False
|
1360 |
+
) -> torch.Tensor:
|
1361 |
+
"""
|
1362 |
+
Returns a calibration matrix of a perspective/orthographic camera.
|
1363 |
+
|
1364 |
+
Args:
|
1365 |
+
N: Number of cameras.
|
1366 |
+
focal_length: Focal length of the camera.
|
1367 |
+
principal_point: xy coordinates of the center of
|
1368 |
+
the principal point of the camera in pixels.
|
1369 |
+
orthographic: Boolean specifying if the camera is orthographic or not
|
1370 |
+
|
1371 |
+
The calibration matrix `K` is set up as follows:
|
1372 |
+
|
1373 |
+
.. code-block:: python
|
1374 |
+
|
1375 |
+
fx = focal_length[:,0]
|
1376 |
+
fy = focal_length[:,1]
|
1377 |
+
px = principal_point[:,0]
|
1378 |
+
py = principal_point[:,1]
|
1379 |
+
|
1380 |
+
for orthographic==True:
|
1381 |
+
K = [
|
1382 |
+
[fx, 0, 0, px],
|
1383 |
+
[0, fy, 0, py],
|
1384 |
+
[0, 0, 1, 0],
|
1385 |
+
[0, 0, 0, 1],
|
1386 |
+
]
|
1387 |
+
else:
|
1388 |
+
K = [
|
1389 |
+
[fx, 0, px, 0],
|
1390 |
+
[0, fy, py, 0],
|
1391 |
+
[0, 0, 0, 1],
|
1392 |
+
[0, 0, 1, 0],
|
1393 |
+
]
|
1394 |
+
|
1395 |
+
Returns:
|
1396 |
+
A calibration matrix `K` of the SfM-conventioned camera
|
1397 |
+
of shape (N, 4, 4).
|
1398 |
+
"""
|
1399 |
+
|
1400 |
+
if not torch.is_tensor(focal_length):
|
1401 |
+
focal_length = torch.tensor(focal_length, device=device)
|
1402 |
+
|
1403 |
+
if focal_length.ndim in (0, 1) or focal_length.shape[1] == 1:
|
1404 |
+
fx = fy = focal_length
|
1405 |
+
else:
|
1406 |
+
fx, fy = focal_length.unbind(1)
|
1407 |
+
|
1408 |
+
if not torch.is_tensor(principal_point):
|
1409 |
+
principal_point = torch.tensor(principal_point, device=device)
|
1410 |
+
|
1411 |
+
px, py = principal_point.unbind(1)
|
1412 |
+
|
1413 |
+
K = fx.new_zeros(N, 4, 4)
|
1414 |
+
K[:, 0, 0] = fx
|
1415 |
+
K[:, 1, 1] = fy
|
1416 |
+
if orthographic:
|
1417 |
+
K[:, 0, 3] = px
|
1418 |
+
K[:, 1, 3] = py
|
1419 |
+
K[:, 2, 2] = 1.0
|
1420 |
+
K[:, 3, 3] = 1.0
|
1421 |
+
else:
|
1422 |
+
K[:, 0, 2] = px
|
1423 |
+
K[:, 1, 2] = py
|
1424 |
+
K[:, 3, 2] = 1.0
|
1425 |
+
K[:, 2, 3] = 1.0
|
1426 |
+
|
1427 |
+
return K
|
1428 |
+
|
1429 |
+
|
1430 |
+
################################################
|
1431 |
+
# Helper functions for world to view transforms
|
1432 |
+
################################################
|
1433 |
+
|
1434 |
+
|
1435 |
+
def get_world_to_view_transform(R: torch.Tensor = _R, T: torch.Tensor = _T) -> Transform3d:
|
1436 |
+
"""
|
1437 |
+
This function returns a Transform3d representing the transformation
|
1438 |
+
matrix to go from world space to view space by applying a rotation and
|
1439 |
+
a translation.
|
1440 |
+
|
1441 |
+
PyTorch3D uses the same convention as Hartley & Zisserman.
|
1442 |
+
I.e., for camera extrinsic parameters R (rotation) and T (translation),
|
1443 |
+
we map a 3D point `X_world` in world coordinates to
|
1444 |
+
a point `X_cam` in camera coordinates with:
|
1445 |
+
`X_cam = X_world R + T`
|
1446 |
+
|
1447 |
+
Args:
|
1448 |
+
R: (N, 3, 3) matrix representing the rotation.
|
1449 |
+
T: (N, 3) matrix representing the translation.
|
1450 |
+
|
1451 |
+
Returns:
|
1452 |
+
a Transform3d object which represents the composed RT transformation.
|
1453 |
+
|
1454 |
+
"""
|
1455 |
+
# TODO: also support the case where RT is specified as one matrix
|
1456 |
+
# of shape (N, 4, 4).
|
1457 |
+
|
1458 |
+
if T.shape[0] != R.shape[0]:
|
1459 |
+
msg = "Expected R, T to have the same batch dimension; got %r, %r"
|
1460 |
+
raise ValueError(msg % (R.shape[0], T.shape[0]))
|
1461 |
+
if T.dim() != 2 or T.shape[1:] != (3,):
|
1462 |
+
msg = "Expected T to have shape (N, 3); got %r"
|
1463 |
+
raise ValueError(msg % repr(T.shape))
|
1464 |
+
if R.dim() != 3 or R.shape[1:] != (3, 3):
|
1465 |
+
msg = "Expected R to have shape (N, 3, 3); got %r"
|
1466 |
+
raise ValueError(msg % repr(R.shape))
|
1467 |
+
|
1468 |
+
# Create a Transform3d object
|
1469 |
+
T_ = Translate(T, device=T.device)
|
1470 |
+
R_ = Rotate(R, device=R.device)
|
1471 |
+
return R_.compose(T_)
|
1472 |
+
|
1473 |
+
|
1474 |
+
def camera_position_from_spherical_angles(
|
1475 |
+
distance: float, elevation: float, azimuth: float, degrees: bool = True, device: Device = "cpu"
|
1476 |
+
) -> torch.Tensor:
|
1477 |
+
"""
|
1478 |
+
Calculate the location of the camera based on the distance away from
|
1479 |
+
the target point, the elevation and azimuth angles.
|
1480 |
+
|
1481 |
+
Args:
|
1482 |
+
distance: distance of the camera from the object.
|
1483 |
+
elevation, azimuth: angles.
|
1484 |
+
The inputs distance, elevation and azimuth can be one of the following
|
1485 |
+
- Python scalar
|
1486 |
+
- Torch scalar
|
1487 |
+
- Torch tensor of shape (N) or (1)
|
1488 |
+
degrees: bool, whether the angles are specified in degrees or radians.
|
1489 |
+
device: str or torch.device, device for new tensors to be placed on.
|
1490 |
+
|
1491 |
+
The vectors are broadcast against each other so they all have shape (N, 1).
|
1492 |
+
|
1493 |
+
Returns:
|
1494 |
+
camera_position: (N, 3) xyz location of the camera.
|
1495 |
+
"""
|
1496 |
+
broadcasted_args = convert_to_tensors_and_broadcast(distance, elevation, azimuth, device=device)
|
1497 |
+
dist, elev, azim = broadcasted_args
|
1498 |
+
if degrees:
|
1499 |
+
elev = math.pi / 180.0 * elev
|
1500 |
+
azim = math.pi / 180.0 * azim
|
1501 |
+
x = dist * torch.cos(elev) * torch.sin(azim)
|
1502 |
+
y = dist * torch.sin(elev)
|
1503 |
+
z = dist * torch.cos(elev) * torch.cos(azim)
|
1504 |
+
camera_position = torch.stack([x, y, z], dim=1)
|
1505 |
+
if camera_position.dim() == 0:
|
1506 |
+
camera_position = camera_position.view(1, -1) # add batch dim.
|
1507 |
+
return camera_position.view(-1, 3)
|
1508 |
+
|
1509 |
+
|
1510 |
+
def look_at_rotation(camera_position, at=((0, 0, 0),), up=((0, 1, 0),), device: Device = "cpu") -> torch.Tensor:
|
1511 |
+
"""
|
1512 |
+
This function takes a vector 'camera_position' which specifies the location
|
1513 |
+
of the camera in world coordinates and two vectors `at` and `up` which
|
1514 |
+
indicate the position of the object and the up directions of the world
|
1515 |
+
coordinate system respectively. The object is assumed to be centered at
|
1516 |
+
the origin.
|
1517 |
+
|
1518 |
+
The output is a rotation matrix representing the transformation
|
1519 |
+
from world coordinates -> view coordinates.
|
1520 |
+
|
1521 |
+
Args:
|
1522 |
+
camera_position: position of the camera in world coordinates
|
1523 |
+
at: position of the object in world coordinates
|
1524 |
+
up: vector specifying the up direction in the world coordinate frame.
|
1525 |
+
|
1526 |
+
The inputs camera_position, at and up can each be a
|
1527 |
+
- 3 element tuple/list
|
1528 |
+
- torch tensor of shape (1, 3)
|
1529 |
+
- torch tensor of shape (N, 3)
|
1530 |
+
|
1531 |
+
The vectors are broadcast against each other so they all have shape (N, 3).
|
1532 |
+
|
1533 |
+
Returns:
|
1534 |
+
R: (N, 3, 3) batched rotation matrices
|
1535 |
+
"""
|
1536 |
+
# Format input and broadcast
|
1537 |
+
broadcasted_args = convert_to_tensors_and_broadcast(camera_position, at, up, device=device)
|
1538 |
+
camera_position, at, up = broadcasted_args
|
1539 |
+
for t, n in zip([camera_position, at, up], ["camera_position", "at", "up"]):
|
1540 |
+
if t.shape[-1] != 3:
|
1541 |
+
msg = "Expected arg %s to have shape (N, 3); got %r"
|
1542 |
+
raise ValueError(msg % (n, t.shape))
|
1543 |
+
z_axis = F.normalize(at - camera_position, eps=1e-5)
|
1544 |
+
x_axis = F.normalize(torch.cross(up, z_axis, dim=1), eps=1e-5)
|
1545 |
+
y_axis = F.normalize(torch.cross(z_axis, x_axis, dim=1), eps=1e-5)
|
1546 |
+
is_close = torch.isclose(x_axis, torch.tensor(0.0), atol=5e-3).all(dim=1, keepdim=True)
|
1547 |
+
if is_close.any():
|
1548 |
+
replacement = F.normalize(torch.cross(y_axis, z_axis, dim=1), eps=1e-5)
|
1549 |
+
x_axis = torch.where(is_close, replacement, x_axis)
|
1550 |
+
R = torch.cat((x_axis[:, None, :], y_axis[:, None, :], z_axis[:, None, :]), dim=1)
|
1551 |
+
return R.transpose(1, 2)
|
1552 |
+
|
1553 |
+
|
1554 |
+
def look_at_view_transform(
|
1555 |
+
dist: _BatchFloatType = 1.0,
|
1556 |
+
elev: _BatchFloatType = 0.0,
|
1557 |
+
azim: _BatchFloatType = 0.0,
|
1558 |
+
degrees: bool = True,
|
1559 |
+
eye: Optional[Union[Sequence, torch.Tensor]] = None,
|
1560 |
+
at=((0, 0, 0),), # (1, 3)
|
1561 |
+
up=((0, 1, 0),), # (1, 3)
|
1562 |
+
device: Device = "cpu",
|
1563 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
1564 |
+
"""
|
1565 |
+
This function returns a rotation and translation matrix
|
1566 |
+
to apply the 'Look At' transformation from world -> view coordinates [0].
|
1567 |
+
|
1568 |
+
Args:
|
1569 |
+
dist: distance of the camera from the object
|
1570 |
+
elev: angle in degrees or radians. This is the angle between the
|
1571 |
+
vector from the object to the camera, and the horizontal plane y = 0 (xz-plane).
|
1572 |
+
azim: angle in degrees or radians. The vector from the object to
|
1573 |
+
the camera is projected onto a horizontal plane y = 0.
|
1574 |
+
azim is the angle between the projected vector and a
|
1575 |
+
reference vector at (0, 0, 1) on the reference plane (the horizontal plane).
|
1576 |
+
dist, elev and azim can be of shape (1), (N).
|
1577 |
+
degrees: boolean flag to indicate if the elevation and azimuth
|
1578 |
+
angles are specified in degrees or radians.
|
1579 |
+
eye: the position of the camera(s) in world coordinates. If eye is not
|
1580 |
+
None, it will override the camera position derived from dist, elev, azim.
|
1581 |
+
up: the direction of the x axis in the world coordinate system.
|
1582 |
+
at: the position of the object(s) in world coordinates.
|
1583 |
+
eye, up and at can be of shape (1, 3) or (N, 3).
|
1584 |
+
|
1585 |
+
Returns:
|
1586 |
+
2-element tuple containing
|
1587 |
+
|
1588 |
+
- **R**: the rotation to apply to the points to align with the camera.
|
1589 |
+
- **T**: the translation to apply to the points to align with the camera.
|
1590 |
+
|
1591 |
+
References:
|
1592 |
+
[0] https://www.scratchapixel.com
|
1593 |
+
"""
|
1594 |
+
|
1595 |
+
if eye is not None:
|
1596 |
+
broadcasted_args = convert_to_tensors_and_broadcast(eye, at, up, device=device)
|
1597 |
+
eye, at, up = broadcasted_args
|
1598 |
+
C = eye
|
1599 |
+
else:
|
1600 |
+
broadcasted_args = convert_to_tensors_and_broadcast(dist, elev, azim, at, up, device=device)
|
1601 |
+
dist, elev, azim, at, up = broadcasted_args
|
1602 |
+
C = camera_position_from_spherical_angles(dist, elev, azim, degrees=degrees, device=device) + at
|
1603 |
+
|
1604 |
+
R = look_at_rotation(C, at, up, device=device)
|
1605 |
+
T = -torch.bmm(R.transpose(1, 2), C[:, :, None])[:, :, 0]
|
1606 |
+
return R, T
|
1607 |
+
|
1608 |
+
|
1609 |
+
def get_ndc_to_screen_transform(
|
1610 |
+
cameras, with_xyflip: bool = False, image_size: Optional[Union[List, Tuple, torch.Tensor]] = None
|
1611 |
+
) -> Transform3d:
|
1612 |
+
"""
|
1613 |
+
PyTorch3D NDC to screen conversion.
|
1614 |
+
Conversion from PyTorch3D's NDC space (+X left, +Y up) to screen/image space
|
1615 |
+
(+X right, +Y down, origin top left).
|
1616 |
+
|
1617 |
+
Args:
|
1618 |
+
cameras
|
1619 |
+
with_xyflip: flips x- and y-axis if set to True.
|
1620 |
+
Optional kwargs:
|
1621 |
+
image_size: ((height, width),) specifying the height, width
|
1622 |
+
of the image. If not provided, it reads it from cameras.
|
1623 |
+
|
1624 |
+
We represent the NDC to screen conversion as a Transform3d
|
1625 |
+
with projection matrix
|
1626 |
+
|
1627 |
+
K = [
|
1628 |
+
[s, 0, 0, cx],
|
1629 |
+
[0, s, 0, cy],
|
1630 |
+
[0, 0, 1, 0],
|
1631 |
+
[0, 0, 0, 1],
|
1632 |
+
]
|
1633 |
+
|
1634 |
+
"""
|
1635 |
+
# We require the image size, which is necessary for the transform
|
1636 |
+
if image_size is None:
|
1637 |
+
msg = "For NDC to screen conversion, image_size=(height, width) needs to be specified."
|
1638 |
+
raise ValueError(msg)
|
1639 |
+
|
1640 |
+
K = torch.zeros((cameras._N, 4, 4), device=cameras.device, dtype=torch.float32)
|
1641 |
+
if not torch.is_tensor(image_size):
|
1642 |
+
image_size = torch.tensor(image_size, device=cameras.device)
|
1643 |
+
# pyre-fixme[16]: Item `List` of `Union[List[typing.Any], Tensor, Tuple[Any,
|
1644 |
+
# ...]]` has no attribute `view`.
|
1645 |
+
image_size = image_size.view(-1, 2) # of shape (1 or B)x2
|
1646 |
+
height, width = image_size.unbind(1)
|
1647 |
+
|
1648 |
+
# For non square images, we scale the points such that smallest side
|
1649 |
+
# has range [-1, 1] and the largest side has range [-u, u], with u > 1.
|
1650 |
+
# This convention is consistent with the PyTorch3D renderer
|
1651 |
+
scale = (image_size.min(dim=1).values - 0.0) / 2.0
|
1652 |
+
|
1653 |
+
K[:, 0, 0] = scale
|
1654 |
+
K[:, 1, 1] = scale
|
1655 |
+
K[:, 0, 3] = -1.0 * (width - 0.0) / 2.0
|
1656 |
+
K[:, 1, 3] = -1.0 * (height - 0.0) / 2.0
|
1657 |
+
K[:, 2, 2] = 1.0
|
1658 |
+
K[:, 3, 3] = 1.0
|
1659 |
+
|
1660 |
+
# Transpose the projection matrix as PyTorch3D transforms use row vectors.
|
1661 |
+
transform = Transform3d(matrix=K.transpose(1, 2).contiguous(), device=cameras.device)
|
1662 |
+
|
1663 |
+
if with_xyflip:
|
1664 |
+
# flip x, y axis
|
1665 |
+
xyflip = torch.eye(4, device=cameras.device, dtype=torch.float32)
|
1666 |
+
xyflip[0, 0] = -1.0
|
1667 |
+
xyflip[1, 1] = -1.0
|
1668 |
+
xyflip = xyflip.view(1, 4, 4).expand(cameras._N, -1, -1)
|
1669 |
+
xyflip_transform = Transform3d(matrix=xyflip.transpose(1, 2).contiguous(), device=cameras.device)
|
1670 |
+
transform = transform.compose(xyflip_transform)
|
1671 |
+
return transform
|
1672 |
+
|
1673 |
+
|
1674 |
+
def get_screen_to_ndc_transform(
|
1675 |
+
cameras, with_xyflip: bool = False, image_size: Optional[Union[List, Tuple, torch.Tensor]] = None
|
1676 |
+
) -> Transform3d:
|
1677 |
+
"""
|
1678 |
+
Screen to PyTorch3D NDC conversion.
|
1679 |
+
Conversion from screen/image space (+X right, +Y down, origin top left)
|
1680 |
+
to PyTorch3D's NDC space (+X left, +Y up).
|
1681 |
+
|
1682 |
+
Args:
|
1683 |
+
cameras
|
1684 |
+
with_xyflip: flips x- and y-axis if set to True.
|
1685 |
+
Optional kwargs:
|
1686 |
+
image_size: ((height, width),) specifying the height, width
|
1687 |
+
of the image. If not provided, it reads it from cameras.
|
1688 |
+
|
1689 |
+
We represent the screen to NDC conversion as a Transform3d
|
1690 |
+
with projection matrix
|
1691 |
+
|
1692 |
+
K = [
|
1693 |
+
[1/s, 0, 0, cx/s],
|
1694 |
+
[ 0, 1/s, 0, cy/s],
|
1695 |
+
[ 0, 0, 1, 0],
|
1696 |
+
[ 0, 0, 0, 1],
|
1697 |
+
]
|
1698 |
+
|
1699 |
+
"""
|
1700 |
+
transform = get_ndc_to_screen_transform(cameras, with_xyflip=with_xyflip, image_size=image_size).inverse()
|
1701 |
+
return transform
|
1702 |
+
|
1703 |
+
|
1704 |
+
def try_get_projection_transform(cameras: CamerasBase, cameras_kwargs: Dict[str, Any]) -> Optional[Transform3d]:
|
1705 |
+
"""
|
1706 |
+
Try block to get projection transform from cameras and cameras_kwargs.
|
1707 |
+
|
1708 |
+
Args:
|
1709 |
+
cameras: cameras instance, can be linear cameras or nonliear cameras
|
1710 |
+
cameras_kwargs: camera parameters to be passed to cameras
|
1711 |
+
|
1712 |
+
Returns:
|
1713 |
+
If the camera implemented projection_transform, return the
|
1714 |
+
projection transform; Otherwise, return None
|
1715 |
+
"""
|
1716 |
+
|
1717 |
+
transform = None
|
1718 |
+
try:
|
1719 |
+
transform = cameras.get_projection_transform(**cameras_kwargs)
|
1720 |
+
except NotImplementedError:
|
1721 |
+
pass
|
1722 |
+
return transform
|