XingyiHe commited on
Commit
e993022
·
1 Parent(s): 613cb7c
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. CODE_OF_CONDUCT.md +128 -0
  2. LICENSE +201 -0
  3. MANIFEST.in +12 -0
  4. README.md +7 -4
  5. __pycache__/app.cpython-38.pyc +0 -0
  6. app.py +27 -0
  7. config/config.yaml +33 -0
  8. docker/build_docker.bat +3 -0
  9. docker/run_docker.bat +1 -0
  10. docker/run_docker.sh +1 -0
  11. environment.yaml +14 -0
  12. imcui/__init__.py +0 -0
  13. imcui/__pycache__/__init__.cpython-38.pyc +0 -0
  14. imcui/api/__init__.py +47 -0
  15. imcui/api/client.py +232 -0
  16. imcui/api/config/api.yaml +51 -0
  17. imcui/api/core.py +308 -0
  18. imcui/api/server.py +170 -0
  19. imcui/api/test/CMakeLists.txt +17 -0
  20. imcui/api/test/build_and_run.sh +16 -0
  21. imcui/api/test/client.cpp +81 -0
  22. imcui/api/test/helper.h +405 -0
  23. imcui/datasets/.gitignore +0 -0
  24. imcui/hloc/__init__.py +65 -0
  25. imcui/hloc/__pycache__/__init__.cpython-38.pyc +0 -0
  26. imcui/hloc/__pycache__/extract_features.cpython-38.pyc +0 -0
  27. imcui/hloc/__pycache__/match_dense.cpython-38.pyc +0 -0
  28. imcui/hloc/__pycache__/match_features.cpython-38.pyc +0 -0
  29. imcui/hloc/colmap_from_nvm.py +216 -0
  30. imcui/hloc/extract_features.py +607 -0
  31. imcui/hloc/extractors/__init__.py +0 -0
  32. imcui/hloc/extractors/__pycache__/__init__.cpython-38.pyc +0 -0
  33. imcui/hloc/extractors/alike.py +61 -0
  34. imcui/hloc/extractors/aliked.py +32 -0
  35. imcui/hloc/extractors/cosplace.py +44 -0
  36. imcui/hloc/extractors/d2net.py +60 -0
  37. imcui/hloc/extractors/darkfeat.py +44 -0
  38. imcui/hloc/extractors/dedode.py +86 -0
  39. imcui/hloc/extractors/dir.py +78 -0
  40. imcui/hloc/extractors/disk.py +35 -0
  41. imcui/hloc/extractors/dog.py +135 -0
  42. imcui/hloc/extractors/eigenplaces.py +57 -0
  43. imcui/hloc/extractors/example.py +56 -0
  44. imcui/hloc/extractors/fire.py +72 -0
  45. imcui/hloc/extractors/fire_local.py +84 -0
  46. imcui/hloc/extractors/lanet.py +63 -0
  47. imcui/hloc/extractors/netvlad.py +146 -0
  48. imcui/hloc/extractors/openibl.py +26 -0
  49. imcui/hloc/extractors/r2d2.py +73 -0
  50. imcui/hloc/extractors/rekd.py +60 -0
CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, religion, or sexual identity
10
+ and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the
26
+ overall community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or
31
+ advances of any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email
35
+ address, without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official e-mail address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series
86
+ of actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or
93
+ permanent ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within
113
+ the community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.0, available at
119
+ https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120
+
121
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct
122
+ enforcement ladder](https://github.com/mozilla/diversity).
123
+
124
+ [homepage]: https://www.contributor-covenant.org
125
+
126
+ For answers to common questions about this code of conduct, see the FAQ at
127
+ https://www.contributor-covenant.org/faq. Translations are available at
128
+ https://www.contributor-covenant.org/translations.
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
MANIFEST.in ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # logo
2
+ include imcui/assets/logo.webp
3
+
4
+ recursive-include imcui/ui *.yaml
5
+ recursive-include imcui/api *.yaml
6
+ recursive-include imcui/third_party *.yaml *.cfg *.yml
7
+
8
+ # ui examples
9
+ recursive-include imcui/datasets *.JPG *.jpg *.png
10
+
11
+ # model
12
+ recursive-include imcui/third_party/SuperGluePretrainedNetwork *.pth
README.md CHANGED
@@ -1,12 +1,15 @@
1
  ---
2
- title: MatchAnything Det
3
- emoji: 📊
4
  colorFrom: red
5
- colorTo: green
6
  sdk: gradio
7
- sdk_version: 5.49.1
 
 
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: MatchAnything-Det
3
+ emoji: 🏢
4
  colorFrom: red
5
+ colorTo: blue
6
  sdk: gradio
7
+ python_version: 3.10.13
8
+ sdk_version: 4.44.0
9
+ # sdk_version: 5.23.0
10
  app_file: app.py
11
  pinned: false
12
+ license: apache-2.0
13
  ---
14
 
15
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
__pycache__/app.cpython-38.pyc ADDED
Binary file (690 Bytes). View file
 
app.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import spaces
2
+ import argparse
3
+ from pathlib import Path
4
+ from imcui.ui.app_class import ImageMatchingApp
5
+
6
+ if __name__ == "__main__":
7
+ parser = argparse.ArgumentParser()
8
+ parser.add_argument(
9
+ "--server_name",
10
+ type=str,
11
+ default="0.0.0.0",
12
+ help="server name",
13
+ )
14
+ parser.add_argument(
15
+ "--server_port",
16
+ type=int,
17
+ default=7860,
18
+ help="server port",
19
+ )
20
+ parser.add_argument(
21
+ "--config",
22
+ type=str,
23
+ default=Path(__file__).parent / "config/config.yaml",
24
+ help="config file",
25
+ )
26
+ args = parser.parse_args()
27
+ ImageMatchingApp(args.server_name, args.server_port, config=args.config).run()
config/config.yaml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ server:
2
+ name: "0.0.0.0"
3
+ port: 16010
4
+
5
+ defaults:
6
+ setting_threshold: 0.1
7
+ max_keypoints: 2000
8
+ keypoint_threshold: 0.05
9
+ enable_ransac: true
10
+ ransac_method: CV2_USAC_MAGSAC
11
+ ransac_reproj_threshold: 8
12
+ ransac_confidence: 0.999
13
+ ransac_max_iter: 10000
14
+ ransac_num_samples: 4
15
+ match_threshold: 0.2
16
+ setting_geometry: Homography
17
+
18
+ matcher_zoo:
19
+ matchanything:
20
+ matcher: matchanything
21
+ dense: true
22
+ info:
23
+ name: MatchAnything #dispaly name
24
+ source: "ZJU3DV"
25
+ display: true
26
+
27
+ retrieval_zoo:
28
+ netvlad:
29
+ enable: true
30
+ openibl:
31
+ enable: true
32
+ cosplace:
33
+ enable: true
docker/build_docker.bat ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ docker build -t image-matching-webui:latest . --no-cache
2
+ # docker tag image-matching-webui:latest vincentqin/image-matching-webui:latest
3
+ # docker push vincentqin/image-matching-webui:latest
docker/run_docker.bat ADDED
@@ -0,0 +1 @@
 
 
1
+ docker run -it -p 7860:7860 vincentqin/image-matching-webui:latest python app.py --server_name "0.0.0.0" --server_port=7860
docker/run_docker.sh ADDED
@@ -0,0 +1 @@
 
 
1
+ docker run -it -p 7860:7860 vincentqin/image-matching-webui:latest python app.py --server_name "0.0.0.0" --server_port=7860
environment.yaml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: imw
2
+ channels:
3
+ - pytorch
4
+ - nvidia
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - python=3.8
9
+ - pytorch-cuda=11.7
10
+ - pytorch=1.12.0
11
+ - torchvision=0.13.1
12
+ - pip
13
+ - pip:
14
+ - -r requirements.txt
imcui/__init__.py ADDED
File without changes
imcui/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (144 Bytes). View file
 
imcui/api/__init__.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import io
3
+ from typing import List
4
+
5
+ import numpy as np
6
+ from fastapi.exceptions import HTTPException
7
+ from PIL import Image
8
+ from pydantic import BaseModel
9
+
10
+ from ..hloc import logger
11
+ from .core import ImageMatchingAPI
12
+
13
+
14
+ class ImagesInput(BaseModel):
15
+ data: List[str] = []
16
+ max_keypoints: List[int] = []
17
+ timestamps: List[str] = []
18
+ grayscale: bool = False
19
+ image_hw: List[List[int]] = [[], []]
20
+ feature_type: int = 0
21
+ rotates: List[float] = []
22
+ scales: List[float] = []
23
+ reference_points: List[List[float]] = []
24
+ binarize: bool = False
25
+
26
+
27
+ def decode_base64_to_image(encoding):
28
+ if encoding.startswith("data:image/"):
29
+ encoding = encoding.split(";")[1].split(",")[1]
30
+ try:
31
+ image = Image.open(io.BytesIO(base64.b64decode(encoding)))
32
+ return image
33
+ except Exception as e:
34
+ logger.warning(f"API cannot decode image: {e}")
35
+ raise HTTPException(status_code=500, detail="Invalid encoded image") from e
36
+
37
+
38
+ def to_base64_nparray(encoding: str) -> np.ndarray:
39
+ return np.array(decode_base64_to_image(encoding)).astype("uint8")
40
+
41
+
42
+ __all__ = [
43
+ "ImageMatchingAPI",
44
+ "ImagesInput",
45
+ "decode_base64_to_image",
46
+ "to_base64_nparray",
47
+ ]
imcui/api/client.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import base64
3
+ import os
4
+ import pickle
5
+ import time
6
+ from typing import Dict, List
7
+
8
+ import cv2
9
+ import numpy as np
10
+ import requests
11
+
12
+ ENDPOINT = "http://127.0.0.1:8001"
13
+ if "REMOTE_URL_RAILWAY" in os.environ:
14
+ ENDPOINT = os.environ["REMOTE_URL_RAILWAY"]
15
+
16
+ print(f"API ENDPOINT: {ENDPOINT}")
17
+
18
+ API_VERSION = f"{ENDPOINT}/version"
19
+ API_URL_MATCH = f"{ENDPOINT}/v1/match"
20
+ API_URL_EXTRACT = f"{ENDPOINT}/v1/extract"
21
+
22
+
23
+ def read_image(path: str) -> str:
24
+ """
25
+ Read an image from a file, encode it as a JPEG and then as a base64 string.
26
+
27
+ Args:
28
+ path (str): The path to the image to read.
29
+
30
+ Returns:
31
+ str: The base64 encoded image.
32
+ """
33
+ # Read the image from the file
34
+ img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
35
+
36
+ # Encode the image as a png, NO COMPRESSION!!!
37
+ retval, buffer = cv2.imencode(".png", img)
38
+
39
+ # Encode the JPEG as a base64 string
40
+ b64img = base64.b64encode(buffer).decode("utf-8")
41
+
42
+ return b64img
43
+
44
+
45
+ def do_api_requests(url=API_URL_EXTRACT, **kwargs):
46
+ """
47
+ Helper function to send an API request to the image matching service.
48
+
49
+ Args:
50
+ url (str): The URL of the API endpoint to use. Defaults to the
51
+ feature extraction endpoint.
52
+ **kwargs: Additional keyword arguments to pass to the API.
53
+
54
+ Returns:
55
+ List[Dict[str, np.ndarray]]: A list of dictionaries containing the
56
+ extracted features. The keys are "keypoints", "descriptors", and
57
+ "scores", and the values are ndarrays of shape (N, 2), (N, ?),
58
+ and (N,), respectively.
59
+ """
60
+ # Set up the request body
61
+ reqbody = {
62
+ # List of image data base64 encoded
63
+ "data": [],
64
+ # List of maximum number of keypoints to extract from each image
65
+ "max_keypoints": [100, 100],
66
+ # List of timestamps for each image (not used?)
67
+ "timestamps": ["0", "1"],
68
+ # Whether to convert the images to grayscale
69
+ "grayscale": 0,
70
+ # List of image height and width
71
+ "image_hw": [[640, 480], [320, 240]],
72
+ # Type of feature to extract
73
+ "feature_type": 0,
74
+ # List of rotation angles for each image
75
+ "rotates": [0.0, 0.0],
76
+ # List of scale factors for each image
77
+ "scales": [1.0, 1.0],
78
+ # List of reference points for each image (not used)
79
+ "reference_points": [[640, 480], [320, 240]],
80
+ # Whether to binarize the descriptors
81
+ "binarize": True,
82
+ }
83
+ # Update the request body with the additional keyword arguments
84
+ reqbody.update(kwargs)
85
+ try:
86
+ # Send the request
87
+ r = requests.post(url, json=reqbody)
88
+ if r.status_code == 200:
89
+ # Return the response
90
+ return r.json()
91
+ else:
92
+ # Print an error message if the response code is not 200
93
+ print(f"Error: Response code {r.status_code} - {r.text}")
94
+ except Exception as e:
95
+ # Print an error message if an exception occurs
96
+ print(f"An error occurred: {e}")
97
+
98
+
99
+ def send_request_match(path0: str, path1: str) -> Dict[str, np.ndarray]:
100
+ """
101
+ Send a request to the API to generate a match between two images.
102
+
103
+ Args:
104
+ path0 (str): The path to the first image.
105
+ path1 (str): The path to the second image.
106
+
107
+ Returns:
108
+ Dict[str, np.ndarray]: A dictionary containing the generated matches.
109
+ The keys are "keypoints0", "keypoints1", "matches0", and "matches1",
110
+ and the values are ndarrays of shape (N, 2), (N, 2), (N, 2), and
111
+ (N, 2), respectively.
112
+ """
113
+ files = {"image0": open(path0, "rb"), "image1": open(path1, "rb")}
114
+ try:
115
+ # TODO: replace files with post json
116
+ response = requests.post(API_URL_MATCH, files=files)
117
+ pred = {}
118
+ if response.status_code == 200:
119
+ pred = response.json()
120
+ for key in list(pred.keys()):
121
+ pred[key] = np.array(pred[key])
122
+ else:
123
+ print(f"Error: Response code {response.status_code} - {response.text}")
124
+ finally:
125
+ files["image0"].close()
126
+ files["image1"].close()
127
+ return pred
128
+
129
+
130
+ def send_request_extract(
131
+ input_images: str, viz: bool = False
132
+ ) -> List[Dict[str, np.ndarray]]:
133
+ """
134
+ Send a request to the API to extract features from an image.
135
+
136
+ Args:
137
+ input_images (str): The path to the image.
138
+
139
+ Returns:
140
+ List[Dict[str, np.ndarray]]: A list of dictionaries containing the
141
+ extracted features. The keys are "keypoints", "descriptors", and
142
+ "scores", and the values are ndarrays of shape (N, 2), (N, 128),
143
+ and (N,), respectively.
144
+ """
145
+ image_data = read_image(input_images)
146
+ inputs = {
147
+ "data": [image_data],
148
+ }
149
+ response = do_api_requests(
150
+ url=API_URL_EXTRACT,
151
+ **inputs,
152
+ )
153
+ # breakpoint()
154
+ # print("Keypoints detected: {}".format(len(response[0]["keypoints"])))
155
+
156
+ # draw matching, debug only
157
+ if viz:
158
+ from hloc.utils.viz import plot_keypoints
159
+ from ui.viz import fig2im, plot_images
160
+
161
+ kpts = np.array(response[0]["keypoints_orig"])
162
+ if "image_orig" in response[0].keys():
163
+ img_orig = np.array(["image_orig"])
164
+
165
+ output_keypoints = plot_images([img_orig], titles="titles", dpi=300)
166
+ plot_keypoints([kpts])
167
+ output_keypoints = fig2im(output_keypoints)
168
+ cv2.imwrite(
169
+ "demo_match.jpg",
170
+ output_keypoints[:, :, ::-1].copy(), # RGB -> BGR
171
+ )
172
+ return response
173
+
174
+
175
+ def get_api_version():
176
+ try:
177
+ response = requests.get(API_VERSION).json()
178
+ print("API VERSION: {}".format(response["version"]))
179
+ except Exception as e:
180
+ print(f"An error occurred: {e}")
181
+
182
+
183
+ if __name__ == "__main__":
184
+ from pathlib import Path
185
+
186
+ parser = argparse.ArgumentParser(
187
+ description="Send text to stable audio server and receive generated audio."
188
+ )
189
+ parser.add_argument(
190
+ "--image0",
191
+ required=False,
192
+ help="Path for the file's melody",
193
+ default=str(
194
+ Path(__file__).parents[1]
195
+ / "datasets/sacre_coeur/mapping_rot/02928139_3448003521_rot45.jpg"
196
+ ),
197
+ )
198
+ parser.add_argument(
199
+ "--image1",
200
+ required=False,
201
+ help="Path for the file's melody",
202
+ default=str(
203
+ Path(__file__).parents[1]
204
+ / "datasets/sacre_coeur/mapping_rot/02928139_3448003521_rot90.jpg"
205
+ ),
206
+ )
207
+ args = parser.parse_args()
208
+
209
+ # get api version
210
+ get_api_version()
211
+
212
+ # request match
213
+ # for i in range(10):
214
+ # t1 = time.time()
215
+ # preds = send_request_match(args.image0, args.image1)
216
+ # t2 = time.time()
217
+ # print(
218
+ # "Time cost1: {} seconds, matched: {}".format(
219
+ # (t2 - t1), len(preds["mmkeypoints0_orig"])
220
+ # )
221
+ # )
222
+
223
+ # request extract
224
+ for i in range(1000):
225
+ t1 = time.time()
226
+ preds = send_request_extract(args.image0)
227
+ t2 = time.time()
228
+ print(f"Time cost2: {(t2 - t1)} seconds")
229
+
230
+ # dump preds
231
+ with open("preds.pkl", "wb") as f:
232
+ pickle.dump(preds, f)
imcui/api/config/api.yaml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file was generated using the `serve build` command on Ray v2.38.0.
2
+
3
+ proxy_location: EveryNode
4
+ http_options:
5
+ host: 0.0.0.0
6
+ port: 8001
7
+
8
+ grpc_options:
9
+ port: 9000
10
+ grpc_servicer_functions: []
11
+
12
+ logging_config:
13
+ encoding: TEXT
14
+ log_level: INFO
15
+ logs_dir: null
16
+ enable_access_log: true
17
+
18
+ applications:
19
+ - name: app1
20
+ route_prefix: /
21
+ import_path: api.server:service
22
+ runtime_env: {}
23
+ deployments:
24
+ - name: ImageMatchingService
25
+ num_replicas: 4
26
+ ray_actor_options:
27
+ num_cpus: 2.0
28
+ num_gpus: 1.0
29
+
30
+ api:
31
+ feature:
32
+ output: feats-superpoint-n4096-rmax1600
33
+ model:
34
+ name: superpoint
35
+ nms_radius: 3
36
+ max_keypoints: 4096
37
+ keypoint_threshold: 0.005
38
+ preprocessing:
39
+ grayscale: True
40
+ force_resize: True
41
+ resize_max: 1600
42
+ width: 640
43
+ height: 480
44
+ dfactor: 8
45
+ matcher:
46
+ output: matches-NN-mutual
47
+ model:
48
+ name: nearest_neighbor
49
+ do_mutual_check: True
50
+ match_threshold: 0.2
51
+ dense: False
imcui/api/core.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # api.py
2
+ import warnings
3
+ from pathlib import Path
4
+ from typing import Any, Dict, Optional
5
+
6
+ import cv2
7
+ import matplotlib.pyplot as plt
8
+ import numpy as np
9
+ import torch
10
+
11
+ from ..hloc import extract_features, logger, match_dense, match_features
12
+ from ..hloc.utils.viz import add_text, plot_keypoints
13
+ from ..ui.utils import filter_matches, get_feature_model, get_model
14
+ from ..ui.viz import display_matches, fig2im, plot_images
15
+
16
+ warnings.simplefilter("ignore")
17
+
18
+
19
+ class ImageMatchingAPI(torch.nn.Module):
20
+ default_conf = {
21
+ "ransac": {
22
+ "enable": True,
23
+ "estimator": "poselib",
24
+ "geometry": "homography",
25
+ "method": "RANSAC",
26
+ "reproj_threshold": 3,
27
+ "confidence": 0.9999,
28
+ "max_iter": 10000,
29
+ },
30
+ }
31
+
32
+ def __init__(
33
+ self,
34
+ conf: dict = {},
35
+ device: str = "cpu",
36
+ detect_threshold: float = 0.015,
37
+ max_keypoints: int = 1024,
38
+ match_threshold: float = 0.2,
39
+ ) -> None:
40
+ """
41
+ Initializes an instance of the ImageMatchingAPI class.
42
+
43
+ Args:
44
+ conf (dict): A dictionary containing the configuration parameters.
45
+ device (str, optional): The device to use for computation. Defaults to "cpu".
46
+ detect_threshold (float, optional): The threshold for detecting keypoints. Defaults to 0.015.
47
+ max_keypoints (int, optional): The maximum number of keypoints to extract. Defaults to 1024.
48
+ match_threshold (float, optional): The threshold for matching keypoints. Defaults to 0.2.
49
+
50
+ Returns:
51
+ None
52
+ """
53
+ super().__init__()
54
+ self.device = device
55
+ self.conf = {**self.default_conf, **conf}
56
+ self._updata_config(detect_threshold, max_keypoints, match_threshold)
57
+ self._init_models()
58
+ if device == "cuda":
59
+ memory_allocated = torch.cuda.memory_allocated(device)
60
+ memory_reserved = torch.cuda.memory_reserved(device)
61
+ logger.info(f"GPU memory allocated: {memory_allocated / 1024**2:.3f} MB")
62
+ logger.info(f"GPU memory reserved: {memory_reserved / 1024**2:.3f} MB")
63
+ self.pred = None
64
+
65
+ def parse_match_config(self, conf):
66
+ if conf["dense"]:
67
+ return {
68
+ **conf,
69
+ "matcher": match_dense.confs.get(conf["matcher"]["model"]["name"]),
70
+ "dense": True,
71
+ }
72
+ else:
73
+ return {
74
+ **conf,
75
+ "feature": extract_features.confs.get(conf["feature"]["model"]["name"]),
76
+ "matcher": match_features.confs.get(conf["matcher"]["model"]["name"]),
77
+ "dense": False,
78
+ }
79
+
80
+ def _updata_config(
81
+ self,
82
+ detect_threshold: float = 0.015,
83
+ max_keypoints: int = 1024,
84
+ match_threshold: float = 0.2,
85
+ ):
86
+ self.dense = self.conf["dense"]
87
+ if self.conf["dense"]:
88
+ try:
89
+ self.conf["matcher"]["model"]["match_threshold"] = match_threshold
90
+ except TypeError as e:
91
+ logger.error(e)
92
+ else:
93
+ self.conf["feature"]["model"]["max_keypoints"] = max_keypoints
94
+ self.conf["feature"]["model"]["keypoint_threshold"] = detect_threshold
95
+ self.extract_conf = self.conf["feature"]
96
+
97
+ self.match_conf = self.conf["matcher"]
98
+
99
+ def _init_models(self):
100
+ # initialize matcher
101
+ self.matcher = get_model(self.match_conf)
102
+ # initialize extractor
103
+ if self.dense:
104
+ self.extractor = None
105
+ else:
106
+ self.extractor = get_feature_model(self.conf["feature"])
107
+
108
+ def _forward(self, img0, img1):
109
+ if self.dense:
110
+ pred = match_dense.match_images(
111
+ self.matcher,
112
+ img0,
113
+ img1,
114
+ self.match_conf["preprocessing"],
115
+ device=self.device,
116
+ )
117
+ last_fixed = "{}".format( # noqa: F841
118
+ self.match_conf["model"]["name"]
119
+ )
120
+ else:
121
+ pred0 = extract_features.extract(
122
+ self.extractor, img0, self.extract_conf["preprocessing"]
123
+ )
124
+ pred1 = extract_features.extract(
125
+ self.extractor, img1, self.extract_conf["preprocessing"]
126
+ )
127
+ pred = match_features.match_images(self.matcher, pred0, pred1)
128
+ return pred
129
+
130
+ def _convert_pred(self, pred):
131
+ ret = {
132
+ k: v.cpu().detach()[0].numpy() if isinstance(v, torch.Tensor) else v
133
+ for k, v in pred.items()
134
+ }
135
+ ret = {
136
+ k: v[0].cpu().detach().numpy() if isinstance(v, list) else v
137
+ for k, v in ret.items()
138
+ }
139
+ return ret
140
+
141
+ @torch.inference_mode()
142
+ def extract(self, img0: np.ndarray, **kwargs) -> Dict[str, np.ndarray]:
143
+ """Extract features from a single image.
144
+
145
+ Args:
146
+ img0 (np.ndarray): image
147
+
148
+ Returns:
149
+ Dict[str, np.ndarray]: feature dict
150
+ """
151
+
152
+ # setting prams
153
+ self.extractor.conf["max_keypoints"] = kwargs.get("max_keypoints", 512)
154
+ self.extractor.conf["keypoint_threshold"] = kwargs.get(
155
+ "keypoint_threshold", 0.0
156
+ )
157
+
158
+ pred = extract_features.extract(
159
+ self.extractor, img0, self.extract_conf["preprocessing"]
160
+ )
161
+ pred = self._convert_pred(pred)
162
+ # back to origin scale
163
+ s0 = pred["original_size"] / pred["size"]
164
+ pred["keypoints_orig"] = (
165
+ match_features.scale_keypoints(pred["keypoints"] + 0.5, s0) - 0.5
166
+ )
167
+ # TODO: rotate back
168
+ binarize = kwargs.get("binarize", False)
169
+ if binarize:
170
+ assert "descriptors" in pred
171
+ pred["descriptors"] = (pred["descriptors"] > 0).astype(np.uint8)
172
+ pred["descriptors"] = pred["descriptors"].T # N x DIM
173
+ return pred
174
+
175
+ @torch.inference_mode()
176
+ def forward(
177
+ self,
178
+ img0: np.ndarray,
179
+ img1: np.ndarray,
180
+ ) -> Dict[str, np.ndarray]:
181
+ """
182
+ Forward pass of the image matching API.
183
+
184
+ Args:
185
+ img0: A 3D NumPy array of shape (H, W, C) representing the first image.
186
+ Values are in the range [0, 1] and are in RGB mode.
187
+ img1: A 3D NumPy array of shape (H, W, C) representing the second image.
188
+ Values are in the range [0, 1] and are in RGB mode.
189
+
190
+ Returns:
191
+ A dictionary containing the following keys:
192
+ - image0_orig: The original image 0.
193
+ - image1_orig: The original image 1.
194
+ - keypoints0_orig: The keypoints detected in image 0.
195
+ - keypoints1_orig: The keypoints detected in image 1.
196
+ - mkeypoints0_orig: The raw matches between image 0 and image 1.
197
+ - mkeypoints1_orig: The raw matches between image 1 and image 0.
198
+ - mmkeypoints0_orig: The RANSAC inliers in image 0.
199
+ - mmkeypoints1_orig: The RANSAC inliers in image 1.
200
+ - mconf: The confidence scores for the raw matches.
201
+ - mmconf: The confidence scores for the RANSAC inliers.
202
+ """
203
+ # Take as input a pair of images (not a batch)
204
+ assert isinstance(img0, np.ndarray)
205
+ assert isinstance(img1, np.ndarray)
206
+ self.pred = self._forward(img0, img1)
207
+ if self.conf["ransac"]["enable"]:
208
+ self.pred = self._geometry_check(self.pred)
209
+ return self.pred
210
+
211
+ def _geometry_check(
212
+ self,
213
+ pred: Dict[str, Any],
214
+ ) -> Dict[str, Any]:
215
+ """
216
+ Filter matches using RANSAC. If keypoints are available, filter by keypoints.
217
+ If lines are available, filter by lines. If both keypoints and lines are
218
+ available, filter by keypoints.
219
+
220
+ Args:
221
+ pred (Dict[str, Any]): dict of matches, including original keypoints.
222
+ See :func:`filter_matches` for the expected keys.
223
+
224
+ Returns:
225
+ Dict[str, Any]: filtered matches
226
+ """
227
+ pred = filter_matches(
228
+ pred,
229
+ ransac_method=self.conf["ransac"]["method"],
230
+ ransac_reproj_threshold=self.conf["ransac"]["reproj_threshold"],
231
+ ransac_confidence=self.conf["ransac"]["confidence"],
232
+ ransac_max_iter=self.conf["ransac"]["max_iter"],
233
+ )
234
+ return pred
235
+
236
+ def visualize(
237
+ self,
238
+ log_path: Optional[Path] = None,
239
+ ) -> None:
240
+ """
241
+ Visualize the matches.
242
+
243
+ Args:
244
+ log_path (Path, optional): The directory to save the images. Defaults to None.
245
+
246
+ Returns:
247
+ None
248
+ """
249
+ if self.conf["dense"]:
250
+ postfix = str(self.conf["matcher"]["model"]["name"])
251
+ else:
252
+ postfix = "{}_{}".format(
253
+ str(self.conf["feature"]["model"]["name"]),
254
+ str(self.conf["matcher"]["model"]["name"]),
255
+ )
256
+ titles = [
257
+ "Image 0 - Keypoints",
258
+ "Image 1 - Keypoints",
259
+ ]
260
+ pred: Dict[str, Any] = self.pred
261
+ image0: np.ndarray = pred["image0_orig"]
262
+ image1: np.ndarray = pred["image1_orig"]
263
+ output_keypoints: np.ndarray = plot_images(
264
+ [image0, image1], titles=titles, dpi=300
265
+ )
266
+ if "keypoints0_orig" in pred.keys() and "keypoints1_orig" in pred.keys():
267
+ plot_keypoints([pred["keypoints0_orig"], pred["keypoints1_orig"]])
268
+ text: str = (
269
+ f"# keypoints0: {len(pred['keypoints0_orig'])} \n"
270
+ + f"# keypoints1: {len(pred['keypoints1_orig'])}"
271
+ )
272
+ add_text(0, text, fs=15)
273
+ output_keypoints = fig2im(output_keypoints)
274
+ # plot images with raw matches
275
+ titles = [
276
+ "Image 0 - Raw matched keypoints",
277
+ "Image 1 - Raw matched keypoints",
278
+ ]
279
+ output_matches_raw, num_matches_raw = display_matches(
280
+ pred, titles=titles, tag="KPTS_RAW"
281
+ )
282
+ # plot images with ransac matches
283
+ titles = [
284
+ "Image 0 - Ransac matched keypoints",
285
+ "Image 1 - Ransac matched keypoints",
286
+ ]
287
+ output_matches_ransac, num_matches_ransac = display_matches(
288
+ pred, titles=titles, tag="KPTS_RANSAC"
289
+ )
290
+ if log_path is not None:
291
+ img_keypoints_path: Path = log_path / f"img_keypoints_{postfix}.png"
292
+ img_matches_raw_path: Path = log_path / f"img_matches_raw_{postfix}.png"
293
+ img_matches_ransac_path: Path = (
294
+ log_path / f"img_matches_ransac_{postfix}.png"
295
+ )
296
+ cv2.imwrite(
297
+ str(img_keypoints_path),
298
+ output_keypoints[:, :, ::-1].copy(), # RGB -> BGR
299
+ )
300
+ cv2.imwrite(
301
+ str(img_matches_raw_path),
302
+ output_matches_raw[:, :, ::-1].copy(), # RGB -> BGR
303
+ )
304
+ cv2.imwrite(
305
+ str(img_matches_ransac_path),
306
+ output_matches_ransac[:, :, ::-1].copy(), # RGB -> BGR
307
+ )
308
+ plt.close("all")
imcui/api/server.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # server.py
2
+ import warnings
3
+ from pathlib import Path
4
+ from typing import Union
5
+
6
+ import numpy as np
7
+ import ray
8
+ import torch
9
+ import yaml
10
+ from fastapi import FastAPI, File, UploadFile
11
+ from fastapi.responses import JSONResponse
12
+ from PIL import Image
13
+ from ray import serve
14
+
15
+ from . import ImagesInput, to_base64_nparray
16
+ from .core import ImageMatchingAPI
17
+ from ..hloc import DEVICE
18
+ from ..ui import get_version
19
+
20
+ warnings.simplefilter("ignore")
21
+ app = FastAPI()
22
+ if ray.is_initialized():
23
+ ray.shutdown()
24
+ ray.init(
25
+ dashboard_port=8265,
26
+ ignore_reinit_error=True,
27
+ )
28
+ serve.start(
29
+ http_options={"host": "0.0.0.0", "port": 8001},
30
+ )
31
+
32
+ num_gpus = 1 if torch.cuda.is_available() else 0
33
+
34
+
35
+ @serve.deployment(
36
+ num_replicas=4, ray_actor_options={"num_cpus": 2, "num_gpus": num_gpus}
37
+ )
38
+ @serve.ingress(app)
39
+ class ImageMatchingService:
40
+ def __init__(self, conf: dict, device: str):
41
+ self.conf = conf
42
+ self.api = ImageMatchingAPI(conf=conf, device=device)
43
+
44
+ @app.get("/")
45
+ def root(self):
46
+ return "Hello, world!"
47
+
48
+ @app.get("/version")
49
+ async def version(self):
50
+ return {"version": get_version()}
51
+
52
+ @app.post("/v1/match")
53
+ async def match(
54
+ self, image0: UploadFile = File(...), image1: UploadFile = File(...)
55
+ ):
56
+ """
57
+ Handle the image matching request and return the processed result.
58
+
59
+ Args:
60
+ image0 (UploadFile): The first image file for matching.
61
+ image1 (UploadFile): The second image file for matching.
62
+
63
+ Returns:
64
+ JSONResponse: A JSON response containing the filtered match results
65
+ or an error message in case of failure.
66
+ """
67
+ try:
68
+ # Load the images from the uploaded files
69
+ image0_array = self.load_image(image0)
70
+ image1_array = self.load_image(image1)
71
+
72
+ # Perform image matching using the API
73
+ output = self.api(image0_array, image1_array)
74
+
75
+ # Keys to skip in the output
76
+ skip_keys = ["image0_orig", "image1_orig"]
77
+
78
+ # Postprocess the output to filter unwanted data
79
+ pred = self.postprocess(output, skip_keys)
80
+
81
+ # Return the filtered prediction as a JSON response
82
+ return JSONResponse(content=pred)
83
+ except Exception as e:
84
+ # Return an error message with status code 500 in case of exception
85
+ return JSONResponse(content={"error": str(e)}, status_code=500)
86
+
87
+ @app.post("/v1/extract")
88
+ async def extract(self, input_info: ImagesInput):
89
+ """
90
+ Extract keypoints and descriptors from images.
91
+
92
+ Args:
93
+ input_info: An object containing the image data and options.
94
+
95
+ Returns:
96
+ A list of dictionaries containing the keypoints and descriptors.
97
+ """
98
+ try:
99
+ preds = []
100
+ for i, input_image in enumerate(input_info.data):
101
+ # Load the image from the input data
102
+ image_array = to_base64_nparray(input_image)
103
+ # Extract keypoints and descriptors
104
+ output = self.api.extract(
105
+ image_array,
106
+ max_keypoints=input_info.max_keypoints[i],
107
+ binarize=input_info.binarize,
108
+ )
109
+ # Do not return the original image and image_orig
110
+ # skip_keys = ["image", "image_orig"]
111
+ skip_keys = []
112
+
113
+ # Postprocess the output
114
+ pred = self.postprocess(output, skip_keys)
115
+ preds.append(pred)
116
+ # Return the list of extracted features
117
+ return JSONResponse(content=preds)
118
+ except Exception as e:
119
+ # Return an error message if an exception occurs
120
+ return JSONResponse(content={"error": str(e)}, status_code=500)
121
+
122
+ def load_image(self, file_path: Union[str, UploadFile]) -> np.ndarray:
123
+ """
124
+ Reads an image from a file path or an UploadFile object.
125
+
126
+ Args:
127
+ file_path: A file path or an UploadFile object.
128
+
129
+ Returns:
130
+ A numpy array representing the image.
131
+ """
132
+ if isinstance(file_path, str):
133
+ file_path = Path(file_path).resolve(strict=False)
134
+ else:
135
+ file_path = file_path.file
136
+ with Image.open(file_path) as img:
137
+ image_array = np.array(img)
138
+ return image_array
139
+
140
+ def postprocess(self, output: dict, skip_keys: list, binarize: bool = True) -> dict:
141
+ pred = {}
142
+ for key, value in output.items():
143
+ if key in skip_keys:
144
+ continue
145
+ if isinstance(value, np.ndarray):
146
+ pred[key] = value.tolist()
147
+ return pred
148
+
149
+ def run(self, host: str = "0.0.0.0", port: int = 8001):
150
+ import uvicorn
151
+
152
+ uvicorn.run(app, host=host, port=port)
153
+
154
+
155
+ def read_config(config_path: Path) -> dict:
156
+ with open(config_path, "r") as f:
157
+ conf = yaml.safe_load(f)
158
+ return conf
159
+
160
+
161
+ # api server
162
+ conf = read_config(Path(__file__).parent / "config/api.yaml")
163
+ service = ImageMatchingService.bind(conf=conf["api"], device=DEVICE)
164
+ handle = serve.run(service, route_prefix="/")
165
+
166
+ # serve run api.server_ray:service
167
+
168
+ # build to generate config file
169
+ # serve build api.server_ray:service -o api/config/ray.yaml
170
+ # serve run api/config/ray.yaml
imcui/api/test/CMakeLists.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cmake_minimum_required(VERSION 3.10)
2
+ project(imatchui)
3
+
4
+ set(OpenCV_DIR /usr/include/opencv4)
5
+ find_package(OpenCV REQUIRED)
6
+
7
+ find_package(Boost REQUIRED COMPONENTS system)
8
+ if(Boost_FOUND)
9
+ include_directories(${Boost_INCLUDE_DIRS})
10
+ endif()
11
+
12
+ add_executable(client client.cpp)
13
+
14
+ target_include_directories(client PRIVATE ${Boost_LIBRARIES}
15
+ ${OpenCV_INCLUDE_DIRS})
16
+
17
+ target_link_libraries(client PRIVATE curl jsoncpp b64 ${OpenCV_LIBS})
imcui/api/test/build_and_run.sh ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # g++ main.cpp -I/usr/include/opencv4 -lcurl -ljsoncpp -lb64 -lopencv_core -lopencv_imgcodecs -o main
2
+ # sudo apt-get update
3
+ # sudo apt-get install libboost-all-dev -y
4
+ # sudo apt-get install libcurl4-openssl-dev libjsoncpp-dev libb64-dev libopencv-dev -y
5
+
6
+ cd build
7
+ cmake ..
8
+ make -j12
9
+
10
+ echo " ======== RUN DEMO ========"
11
+
12
+ ./client
13
+
14
+ echo " ======== END DEMO ========"
15
+
16
+ cd ..
imcui/api/test/client.cpp ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <curl/curl.h>
2
+ #include <opencv2/opencv.hpp>
3
+ #include "helper.h"
4
+
5
+ int main() {
6
+ std::string img_path =
7
+ "../../../datasets/sacre_coeur/mapping_rot/02928139_3448003521_rot45.jpg";
8
+ cv::Mat original_img = cv::imread(img_path, cv::IMREAD_GRAYSCALE);
9
+
10
+ if (original_img.empty()) {
11
+ throw std::runtime_error("Failed to decode image");
12
+ }
13
+
14
+ // Convert the image to Base64
15
+ std::string base64_img = image_to_base64(original_img);
16
+
17
+ // Convert the Base64 back to an image
18
+ cv::Mat decoded_img = base64_to_image(base64_img);
19
+ cv::imwrite("decoded_image.jpg", decoded_img);
20
+ cv::imwrite("original_img.jpg", original_img);
21
+
22
+ // The images should be identical
23
+ if (cv::countNonZero(original_img != decoded_img) != 0) {
24
+ std::cerr << "The images are not identical" << std::endl;
25
+ return -1;
26
+ } else {
27
+ std::cout << "The images are identical!" << std::endl;
28
+ }
29
+
30
+ // construct params
31
+ APIParams params{.data = {base64_img},
32
+ .max_keypoints = {100, 100},
33
+ .timestamps = {"0", "1"},
34
+ .grayscale = {0},
35
+ .image_hw = {{480, 640}, {240, 320}},
36
+ .feature_type = 0,
37
+ .rotates = {0.0f, 0.0f},
38
+ .scales = {1.0f, 1.0f},
39
+ .reference_points = {{1.23e+2f, 1.2e+1f},
40
+ {5.0e-1f, 3.0e-1f},
41
+ {2.3e+2f, 2.2e+1f},
42
+ {6.0e-1f, 4.0e-1f}},
43
+ .binarize = {1}};
44
+
45
+ KeyPointResults kpts_results;
46
+
47
+ // Convert the parameters to JSON
48
+ Json::Value jsonData = paramsToJson(params);
49
+ std::string url = "http://127.0.0.1:8001/v1/extract";
50
+ Json::StreamWriterBuilder writer;
51
+ std::string output = Json::writeString(writer, jsonData);
52
+
53
+ CURL* curl;
54
+ CURLcode res;
55
+ std::string readBuffer;
56
+
57
+ curl_global_init(CURL_GLOBAL_DEFAULT);
58
+ curl = curl_easy_init();
59
+ if (curl) {
60
+ struct curl_slist* hs = NULL;
61
+ hs = curl_slist_append(hs, "Content-Type: application/json");
62
+ curl_easy_setopt(curl, CURLOPT_HTTPHEADER, hs);
63
+ curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
64
+ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, output.c_str());
65
+ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
66
+ curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
67
+ res = curl_easy_perform(curl);
68
+
69
+ if (res != CURLE_OK)
70
+ fprintf(
71
+ stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
72
+ else {
73
+ // std::cout << "Response from server: " << readBuffer << std::endl;
74
+ kpts_results = decode_response(readBuffer);
75
+ }
76
+ curl_easy_cleanup(curl);
77
+ }
78
+ curl_global_cleanup();
79
+
80
+ return 0;
81
+ }
imcui/api/test/helper.h ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ #include <b64/encode.h>
3
+ #include <fstream>
4
+ #include <jsoncpp/json/json.h>
5
+ #include <opencv2/opencv.hpp>
6
+ #include <sstream>
7
+ #include <vector>
8
+
9
+ // base64 to image
10
+ #include <boost/archive/iterators/base64_from_binary.hpp>
11
+ #include <boost/archive/iterators/binary_from_base64.hpp>
12
+ #include <boost/archive/iterators/transform_width.hpp>
13
+
14
+ /// Parameters used in the API
15
+ struct APIParams {
16
+ /// A list of images, base64 encoded
17
+ std::vector<std::string> data;
18
+
19
+ /// The maximum number of keypoints to detect for each image
20
+ std::vector<int> max_keypoints;
21
+
22
+ /// The timestamps of the images
23
+ std::vector<std::string> timestamps;
24
+
25
+ /// Whether to convert the images to grayscale
26
+ bool grayscale;
27
+
28
+ /// The height and width of each image
29
+ std::vector<std::vector<int>> image_hw;
30
+
31
+ /// The type of feature detector to use
32
+ int feature_type;
33
+
34
+ /// The rotations of the images
35
+ std::vector<double> rotates;
36
+
37
+ /// The scales of the images
38
+ std::vector<double> scales;
39
+
40
+ /// The reference points of the images
41
+ std::vector<std::vector<float>> reference_points;
42
+
43
+ /// Whether to binarize the descriptors
44
+ bool binarize;
45
+ };
46
+
47
+ /**
48
+ * @brief Contains the results of a keypoint detector.
49
+ *
50
+ * @details Stores the keypoints and descriptors for each image.
51
+ */
52
+ class KeyPointResults {
53
+ public:
54
+ KeyPointResults() {
55
+ }
56
+
57
+ /**
58
+ * @brief Constructor.
59
+ *
60
+ * @param kp The keypoints for each image.
61
+ */
62
+ KeyPointResults(const std::vector<std::vector<cv::KeyPoint>>& kp,
63
+ const std::vector<cv::Mat>& desc)
64
+ : keypoints(kp), descriptors(desc) {
65
+ }
66
+
67
+ /**
68
+ * @brief Append keypoints to the result.
69
+ *
70
+ * @param kpts The keypoints to append.
71
+ */
72
+ inline void append_keypoints(std::vector<cv::KeyPoint>& kpts) {
73
+ keypoints.emplace_back(kpts);
74
+ }
75
+
76
+ /**
77
+ * @brief Append descriptors to the result.
78
+ *
79
+ * @param desc The descriptors to append.
80
+ */
81
+ inline void append_descriptors(cv::Mat& desc) {
82
+ descriptors.emplace_back(desc);
83
+ }
84
+
85
+ /**
86
+ * @brief Get the keypoints.
87
+ *
88
+ * @return The keypoints.
89
+ */
90
+ inline std::vector<std::vector<cv::KeyPoint>> get_keypoints() {
91
+ return keypoints;
92
+ }
93
+
94
+ /**
95
+ * @brief Get the descriptors.
96
+ *
97
+ * @return The descriptors.
98
+ */
99
+ inline std::vector<cv::Mat> get_descriptors() {
100
+ return descriptors;
101
+ }
102
+
103
+ private:
104
+ std::vector<std::vector<cv::KeyPoint>> keypoints;
105
+ std::vector<cv::Mat> descriptors;
106
+ std::vector<std::vector<float>> scores;
107
+ };
108
+
109
+ /**
110
+ * @brief Decodes a base64 encoded string.
111
+ *
112
+ * @param base64 The base64 encoded string to decode.
113
+ * @return The decoded string.
114
+ */
115
+ std::string base64_decode(const std::string& base64) {
116
+ using namespace boost::archive::iterators;
117
+ using It = transform_width<binary_from_base64<std::string::const_iterator>, 8, 6>;
118
+
119
+ // Find the position of the last non-whitespace character
120
+ auto end = base64.find_last_not_of(" \t\n\r");
121
+ if (end != std::string::npos) {
122
+ // Move one past the last non-whitespace character
123
+ end += 1;
124
+ }
125
+
126
+ // Decode the base64 string and return the result
127
+ return std::string(It(base64.begin()), It(base64.begin() + end));
128
+ }
129
+
130
+ /**
131
+ * @brief Decodes a base64 string into an OpenCV image
132
+ *
133
+ * @param base64 The base64 encoded string
134
+ * @return The decoded OpenCV image
135
+ */
136
+ cv::Mat base64_to_image(const std::string& base64) {
137
+ // Decode the base64 string
138
+ std::string decodedStr = base64_decode(base64);
139
+
140
+ // Decode the image
141
+ std::vector<uchar> data(decodedStr.begin(), decodedStr.end());
142
+ cv::Mat img = cv::imdecode(data, cv::IMREAD_GRAYSCALE);
143
+
144
+ // Check for errors
145
+ if (img.empty()) {
146
+ throw std::runtime_error("Failed to decode image");
147
+ }
148
+
149
+ return img;
150
+ }
151
+
152
+ /**
153
+ * @brief Encodes an OpenCV image into a base64 string
154
+ *
155
+ * This function takes an OpenCV image and encodes it into a base64 string.
156
+ * The image is first encoded as a PNG image, and then the resulting
157
+ * bytes are encoded as a base64 string.
158
+ *
159
+ * @param img The OpenCV image
160
+ * @return The base64 encoded string
161
+ *
162
+ * @throws std::runtime_error if the image is empty or encoding fails
163
+ */
164
+ std::string image_to_base64(cv::Mat& img) {
165
+ if (img.empty()) {
166
+ throw std::runtime_error("Failed to read image");
167
+ }
168
+
169
+ // Encode the image as a PNG
170
+ std::vector<uchar> buf;
171
+ if (!cv::imencode(".png", img, buf)) {
172
+ throw std::runtime_error("Failed to encode image");
173
+ }
174
+
175
+ // Encode the bytes as a base64 string
176
+ using namespace boost::archive::iterators;
177
+ using It =
178
+ base64_from_binary<transform_width<std::vector<uchar>::const_iterator, 6, 8>>;
179
+ std::string base64(It(buf.begin()), It(buf.end()));
180
+
181
+ // Pad the string with '=' characters to a multiple of 4 bytes
182
+ base64.append((3 - buf.size() % 3) % 3, '=');
183
+
184
+ return base64;
185
+ }
186
+
187
+ /**
188
+ * @brief Callback function for libcurl to write data to a string
189
+ *
190
+ * This function is used as a callback for libcurl to write data to a string.
191
+ * It takes the contents, size, and nmemb as parameters, and writes the data to
192
+ * the string.
193
+ *
194
+ * @param contents The data to write
195
+ * @param size The size of the data
196
+ * @param nmemb The number of members in the data
197
+ * @param s The string to write the data to
198
+ * @return The number of bytes written
199
+ */
200
+ size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* s) {
201
+ size_t newLength = size * nmemb;
202
+ try {
203
+ // Resize the string to fit the new data
204
+ s->resize(s->size() + newLength);
205
+ } catch (std::bad_alloc& e) {
206
+ // If there's an error allocating memory, return 0
207
+ return 0;
208
+ }
209
+
210
+ // Copy the data to the string
211
+ std::copy(static_cast<const char*>(contents),
212
+ static_cast<const char*>(contents) + newLength,
213
+ s->begin() + s->size() - newLength);
214
+ return newLength;
215
+ }
216
+
217
+ // Helper functions
218
+
219
+ /**
220
+ * @brief Helper function to convert a type to a Json::Value
221
+ *
222
+ * This function takes a value of type T and converts it to a Json::Value.
223
+ * It is used to simplify the process of converting a type to a Json::Value.
224
+ *
225
+ * @param val The value to convert
226
+ * @return The converted Json::Value
227
+ */
228
+ template <typename T> Json::Value toJson(const T& val) {
229
+ return Json::Value(val);
230
+ }
231
+
232
+ /**
233
+ * @brief Converts a vector to a Json::Value
234
+ *
235
+ * This function takes a vector of type T and converts it to a Json::Value.
236
+ * Each element in the vector is appended to the Json::Value array.
237
+ *
238
+ * @param vec The vector to convert to Json::Value
239
+ * @return The Json::Value representing the vector
240
+ */
241
+ template <typename T> Json::Value vectorToJson(const std::vector<T>& vec) {
242
+ Json::Value json(Json::arrayValue);
243
+ for (const auto& item : vec) {
244
+ json.append(item);
245
+ }
246
+ return json;
247
+ }
248
+
249
+ /**
250
+ * @brief Converts a nested vector to a Json::Value
251
+ *
252
+ * This function takes a nested vector of type T and converts it to a
253
+ * Json::Value. Each sub-vector is converted to a Json::Value array and appended
254
+ * to the main Json::Value array.
255
+ *
256
+ * @param vec The nested vector to convert to Json::Value
257
+ * @return The Json::Value representing the nested vector
258
+ */
259
+ template <typename T>
260
+ Json::Value nestedVectorToJson(const std::vector<std::vector<T>>& vec) {
261
+ Json::Value json(Json::arrayValue);
262
+ for (const auto& subVec : vec) {
263
+ json.append(vectorToJson(subVec));
264
+ }
265
+ return json;
266
+ }
267
+
268
+ /**
269
+ * @brief Converts the APIParams struct to a Json::Value
270
+ *
271
+ * This function takes an APIParams struct and converts it to a Json::Value.
272
+ * The Json::Value is a JSON object with the following fields:
273
+ * - data: a JSON array of base64 encoded images
274
+ * - max_keypoints: a JSON array of integers, max number of keypoints for each
275
+ * image
276
+ * - timestamps: a JSON array of timestamps, one for each image
277
+ * - grayscale: a JSON boolean, whether to convert images to grayscale
278
+ * - image_hw: a nested JSON array, each sub-array contains the height and width
279
+ * of an image
280
+ * - feature_type: a JSON integer, the type of feature detector to use
281
+ * - rotates: a JSON array of doubles, the rotation of each image
282
+ * - scales: a JSON array of doubles, the scale of each image
283
+ * - reference_points: a nested JSON array, each sub-array contains the
284
+ * reference points of an image
285
+ * - binarize: a JSON boolean, whether to binarize the descriptors
286
+ *
287
+ * @param params The APIParams struct to convert
288
+ * @return The Json::Value representing the APIParams struct
289
+ */
290
+ Json::Value paramsToJson(const APIParams& params) {
291
+ Json::Value json;
292
+ json["data"] = vectorToJson(params.data);
293
+ json["max_keypoints"] = vectorToJson(params.max_keypoints);
294
+ json["timestamps"] = vectorToJson(params.timestamps);
295
+ json["grayscale"] = toJson(params.grayscale);
296
+ json["image_hw"] = nestedVectorToJson(params.image_hw);
297
+ json["feature_type"] = toJson(params.feature_type);
298
+ json["rotates"] = vectorToJson(params.rotates);
299
+ json["scales"] = vectorToJson(params.scales);
300
+ json["reference_points"] = nestedVectorToJson(params.reference_points);
301
+ json["binarize"] = toJson(params.binarize);
302
+ return json;
303
+ }
304
+
305
+ template <typename T> cv::Mat jsonToMat(Json::Value json) {
306
+ int rows = json.size();
307
+ int cols = json[0].size();
308
+
309
+ // Create a single array to hold all the data.
310
+ std::vector<T> data;
311
+ data.reserve(rows * cols);
312
+
313
+ for (int i = 0; i < rows; i++) {
314
+ for (int j = 0; j < cols; j++) {
315
+ data.push_back(static_cast<T>(json[i][j].asInt()));
316
+ }
317
+ }
318
+
319
+ // Create a cv::Mat object that points to the data.
320
+ cv::Mat mat(rows, cols, CV_8UC1,
321
+ data.data()); // Change the type if necessary.
322
+ // cv::Mat mat(cols, rows,CV_8UC1, data.data()); // Change the type if
323
+ // necessary.
324
+
325
+ return mat;
326
+ }
327
+
328
+ /**
329
+ * @brief Decodes the response of the server and prints the keypoints
330
+ *
331
+ * This function takes the response of the server, a JSON string, and decodes
332
+ * it. It then prints the keypoints and draws them on the original image.
333
+ *
334
+ * @param response The response of the server
335
+ * @return The keypoints and descriptors
336
+ */
337
+ KeyPointResults decode_response(const std::string& response, bool viz = true) {
338
+ Json::CharReaderBuilder builder;
339
+ Json::CharReader* reader = builder.newCharReader();
340
+
341
+ Json::Value jsonData;
342
+ std::string errors;
343
+
344
+ // Parse the JSON response
345
+ bool parsingSuccessful = reader->parse(
346
+ response.c_str(), response.c_str() + response.size(), &jsonData, &errors);
347
+ delete reader;
348
+
349
+ if (!parsingSuccessful) {
350
+ // Handle error
351
+ std::cout << "Failed to parse the JSON, errors:" << std::endl;
352
+ std::cout << errors << std::endl;
353
+ return KeyPointResults();
354
+ }
355
+
356
+ KeyPointResults kpts_results;
357
+
358
+ // Iterate over the images
359
+ for (const auto& jsonItem : jsonData) {
360
+ auto jkeypoints = jsonItem["keypoints"];
361
+ auto jkeypoints_orig = jsonItem["keypoints_orig"];
362
+ auto jdescriptors = jsonItem["descriptors"];
363
+ auto jscores = jsonItem["scores"];
364
+ auto jimageSize = jsonItem["image_size"];
365
+ auto joriginalSize = jsonItem["original_size"];
366
+ auto jsize = jsonItem["size"];
367
+
368
+ std::vector<cv::KeyPoint> vkeypoints;
369
+ std::vector<float> vscores;
370
+
371
+ // Iterate over the keypoints
372
+ int counter = 0;
373
+ for (const auto& keypoint : jkeypoints_orig) {
374
+ if (counter < 10) {
375
+ // Print the first 10 keypoints
376
+ std::cout << keypoint[0].asFloat() << ", " << keypoint[1].asFloat()
377
+ << std::endl;
378
+ }
379
+ counter++;
380
+ // Convert the Json::Value to a cv::KeyPoint
381
+ vkeypoints.emplace_back(
382
+ cv::KeyPoint(keypoint[0].asFloat(), keypoint[1].asFloat(), 0.0));
383
+ }
384
+
385
+ if (viz && jsonItem.isMember("image_orig")) {
386
+ auto jimg_orig = jsonItem["image_orig"];
387
+ cv::Mat img = jsonToMat<uchar>(jimg_orig);
388
+ cv::imwrite("viz_image_orig.jpg", img);
389
+
390
+ // Draw keypoints on the image
391
+ cv::Mat imgWithKeypoints;
392
+ cv::drawKeypoints(img, vkeypoints, imgWithKeypoints, cv::Scalar(0, 0, 255));
393
+
394
+ // Write the image with keypoints
395
+ std::string filename = "viz_image_orig_keypoints.jpg";
396
+ cv::imwrite(filename, imgWithKeypoints);
397
+ }
398
+
399
+ // Iterate over the descriptors
400
+ cv::Mat descriptors = jsonToMat<uchar>(jdescriptors);
401
+ kpts_results.append_keypoints(vkeypoints);
402
+ kpts_results.append_descriptors(descriptors);
403
+ }
404
+ return kpts_results;
405
+ }
imcui/datasets/.gitignore ADDED
File without changes
imcui/hloc/__init__.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import sys
3
+
4
+ import torch
5
+ from packaging import version
6
+
7
+ __version__ = "1.5"
8
+
9
+ LOG_PATH = "log.txt"
10
+
11
+
12
+ def read_logs():
13
+ sys.stdout.flush()
14
+ with open(LOG_PATH, "r") as f:
15
+ return f.read()
16
+
17
+
18
+ def flush_logs():
19
+ sys.stdout.flush()
20
+ logs = open(LOG_PATH, "w")
21
+ logs.close()
22
+
23
+
24
+ formatter = logging.Formatter(
25
+ fmt="[%(asctime)s %(name)s %(levelname)s] %(message)s",
26
+ datefmt="%Y/%m/%d %H:%M:%S",
27
+ )
28
+
29
+ logs_file = open(LOG_PATH, "w")
30
+ logs_file.close()
31
+
32
+ file_handler = logging.FileHandler(filename=LOG_PATH)
33
+ file_handler.setFormatter(formatter)
34
+ file_handler.setLevel(logging.INFO)
35
+ stdout_handler = logging.StreamHandler()
36
+ stdout_handler.setFormatter(formatter)
37
+ stdout_handler.setLevel(logging.INFO)
38
+ logger = logging.getLogger("hloc")
39
+ logger.setLevel(logging.INFO)
40
+ logger.addHandler(file_handler)
41
+ logger.addHandler(stdout_handler)
42
+ logger.propagate = False
43
+
44
+ try:
45
+ import pycolmap
46
+ except ImportError:
47
+ logger.warning("pycolmap is not installed, some features may not work.")
48
+ else:
49
+ min_version = version.parse("0.6.0")
50
+ found_version = pycolmap.__version__
51
+ if found_version != "dev":
52
+ version = version.parse(found_version)
53
+ if version < min_version:
54
+ s = f"pycolmap>={min_version}"
55
+ logger.warning(
56
+ "hloc requires %s but found pycolmap==%s, "
57
+ 'please upgrade with `pip install --upgrade "%s"`',
58
+ s,
59
+ found_version,
60
+ s,
61
+ )
62
+
63
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
64
+
65
+ MODEL_REPO_ID = "LittleFrog/MatchAnything_checkpoints"
imcui/hloc/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (1.64 kB). View file
 
imcui/hloc/__pycache__/extract_features.cpython-38.pyc ADDED
Binary file (11.2 kB). View file
 
imcui/hloc/__pycache__/match_dense.cpython-38.pyc ADDED
Binary file (18.9 kB). View file
 
imcui/hloc/__pycache__/match_features.cpython-38.pyc ADDED
Binary file (10.7 kB). View file
 
imcui/hloc/colmap_from_nvm.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import sqlite3
3
+ from collections import defaultdict
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+ from tqdm import tqdm
8
+
9
+ from . import logger
10
+ from .utils.read_write_model import (
11
+ CAMERA_MODEL_NAMES,
12
+ Camera,
13
+ Image,
14
+ Point3D,
15
+ write_model,
16
+ )
17
+
18
+
19
+ def recover_database_images_and_ids(database_path):
20
+ images = {}
21
+ cameras = {}
22
+ db = sqlite3.connect(str(database_path))
23
+ ret = db.execute("SELECT name, image_id, camera_id FROM images;")
24
+ for name, image_id, camera_id in ret:
25
+ images[name] = image_id
26
+ cameras[name] = camera_id
27
+ db.close()
28
+ logger.info(f"Found {len(images)} images and {len(cameras)} cameras in database.")
29
+ return images, cameras
30
+
31
+
32
+ def quaternion_to_rotation_matrix(qvec):
33
+ qvec = qvec / np.linalg.norm(qvec)
34
+ w, x, y, z = qvec
35
+ R = np.array(
36
+ [
37
+ [
38
+ 1 - 2 * y * y - 2 * z * z,
39
+ 2 * x * y - 2 * z * w,
40
+ 2 * x * z + 2 * y * w,
41
+ ],
42
+ [
43
+ 2 * x * y + 2 * z * w,
44
+ 1 - 2 * x * x - 2 * z * z,
45
+ 2 * y * z - 2 * x * w,
46
+ ],
47
+ [
48
+ 2 * x * z - 2 * y * w,
49
+ 2 * y * z + 2 * x * w,
50
+ 1 - 2 * x * x - 2 * y * y,
51
+ ],
52
+ ]
53
+ )
54
+ return R
55
+
56
+
57
+ def camera_center_to_translation(c, qvec):
58
+ R = quaternion_to_rotation_matrix(qvec)
59
+ return (-1) * np.matmul(R, c)
60
+
61
+
62
+ def read_nvm_model(nvm_path, intrinsics_path, image_ids, camera_ids, skip_points=False):
63
+ with open(intrinsics_path, "r") as f:
64
+ raw_intrinsics = f.readlines()
65
+
66
+ logger.info(f"Reading {len(raw_intrinsics)} cameras...")
67
+ cameras = {}
68
+ for intrinsics in raw_intrinsics:
69
+ intrinsics = intrinsics.strip("\n").split(" ")
70
+ name, camera_model, width, height = intrinsics[:4]
71
+ params = [float(p) for p in intrinsics[4:]]
72
+ camera_model = CAMERA_MODEL_NAMES[camera_model]
73
+ assert len(params) == camera_model.num_params
74
+ camera_id = camera_ids[name]
75
+ camera = Camera(
76
+ id=camera_id,
77
+ model=camera_model.model_name,
78
+ width=int(width),
79
+ height=int(height),
80
+ params=params,
81
+ )
82
+ cameras[camera_id] = camera
83
+
84
+ nvm_f = open(nvm_path, "r")
85
+ line = nvm_f.readline()
86
+ while line == "\n" or line.startswith("NVM_V3"):
87
+ line = nvm_f.readline()
88
+ num_images = int(line)
89
+ assert num_images == len(cameras)
90
+
91
+ logger.info(f"Reading {num_images} images...")
92
+ image_idx_to_db_image_id = []
93
+ image_data = []
94
+ i = 0
95
+ while i < num_images:
96
+ line = nvm_f.readline()
97
+ if line == "\n":
98
+ continue
99
+ data = line.strip("\n").split(" ")
100
+ image_data.append(data)
101
+ image_idx_to_db_image_id.append(image_ids[data[0]])
102
+ i += 1
103
+
104
+ line = nvm_f.readline()
105
+ while line == "\n":
106
+ line = nvm_f.readline()
107
+ num_points = int(line)
108
+
109
+ if skip_points:
110
+ logger.info(f"Skipping {num_points} points.")
111
+ num_points = 0
112
+ else:
113
+ logger.info(f"Reading {num_points} points...")
114
+ points3D = {}
115
+ image_idx_to_keypoints = defaultdict(list)
116
+ i = 0
117
+ pbar = tqdm(total=num_points, unit="pts")
118
+ while i < num_points:
119
+ line = nvm_f.readline()
120
+ if line == "\n":
121
+ continue
122
+
123
+ data = line.strip("\n").split(" ")
124
+ x, y, z, r, g, b, num_observations = data[:7]
125
+ obs_image_ids, point2D_idxs = [], []
126
+ for j in range(int(num_observations)):
127
+ s = 7 + 4 * j
128
+ img_index, kp_index, kx, ky = data[s : s + 4]
129
+ image_idx_to_keypoints[int(img_index)].append(
130
+ (int(kp_index), float(kx), float(ky), i)
131
+ )
132
+ db_image_id = image_idx_to_db_image_id[int(img_index)]
133
+ obs_image_ids.append(db_image_id)
134
+ point2D_idxs.append(kp_index)
135
+
136
+ point = Point3D(
137
+ id=i,
138
+ xyz=np.array([x, y, z], float),
139
+ rgb=np.array([r, g, b], int),
140
+ error=1.0, # fake
141
+ image_ids=np.array(obs_image_ids, int),
142
+ point2D_idxs=np.array(point2D_idxs, int),
143
+ )
144
+ points3D[i] = point
145
+
146
+ i += 1
147
+ pbar.update(1)
148
+ pbar.close()
149
+
150
+ logger.info("Parsing image data...")
151
+ images = {}
152
+ for i, data in enumerate(image_data):
153
+ # Skip the focal length. Skip the distortion and terminal 0.
154
+ name, _, qw, qx, qy, qz, cx, cy, cz, _, _ = data
155
+ qvec = np.array([qw, qx, qy, qz], float)
156
+ c = np.array([cx, cy, cz], float)
157
+ t = camera_center_to_translation(c, qvec)
158
+
159
+ if i in image_idx_to_keypoints:
160
+ # NVM only stores triangulated 2D keypoints: add dummy ones
161
+ keypoints = image_idx_to_keypoints[i]
162
+ point2D_idxs = np.array([d[0] for d in keypoints])
163
+ tri_xys = np.array([[x, y] for _, x, y, _ in keypoints])
164
+ tri_ids = np.array([i for _, _, _, i in keypoints])
165
+
166
+ num_2Dpoints = max(point2D_idxs) + 1
167
+ xys = np.zeros((num_2Dpoints, 2), float)
168
+ point3D_ids = np.full(num_2Dpoints, -1, int)
169
+ xys[point2D_idxs] = tri_xys
170
+ point3D_ids[point2D_idxs] = tri_ids
171
+ else:
172
+ xys = np.zeros((0, 2), float)
173
+ point3D_ids = np.full(0, -1, int)
174
+
175
+ image_id = image_ids[name]
176
+ image = Image(
177
+ id=image_id,
178
+ qvec=qvec,
179
+ tvec=t,
180
+ camera_id=camera_ids[name],
181
+ name=name,
182
+ xys=xys,
183
+ point3D_ids=point3D_ids,
184
+ )
185
+ images[image_id] = image
186
+
187
+ return cameras, images, points3D
188
+
189
+
190
+ def main(nvm, intrinsics, database, output, skip_points=False):
191
+ assert nvm.exists(), nvm
192
+ assert intrinsics.exists(), intrinsics
193
+ assert database.exists(), database
194
+
195
+ image_ids, camera_ids = recover_database_images_and_ids(database)
196
+
197
+ logger.info("Reading the NVM model...")
198
+ model = read_nvm_model(
199
+ nvm, intrinsics, image_ids, camera_ids, skip_points=skip_points
200
+ )
201
+
202
+ logger.info("Writing the COLMAP model...")
203
+ output.mkdir(exist_ok=True, parents=True)
204
+ write_model(*model, path=str(output), ext=".bin")
205
+ logger.info("Done.")
206
+
207
+
208
+ if __name__ == "__main__":
209
+ parser = argparse.ArgumentParser()
210
+ parser.add_argument("--nvm", required=True, type=Path)
211
+ parser.add_argument("--intrinsics", required=True, type=Path)
212
+ parser.add_argument("--database", required=True, type=Path)
213
+ parser.add_argument("--output", required=True, type=Path)
214
+ parser.add_argument("--skip_points", action="store_true")
215
+ args = parser.parse_args()
216
+ main(**args.__dict__)
imcui/hloc/extract_features.py ADDED
@@ -0,0 +1,607 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import collections.abc as collections
3
+ import pprint
4
+ from pathlib import Path
5
+ from types import SimpleNamespace
6
+ from typing import Dict, List, Optional, Union
7
+
8
+ import cv2
9
+ import h5py
10
+ import numpy as np
11
+ import PIL.Image
12
+ import torch
13
+ import torchvision.transforms.functional as F
14
+ from tqdm import tqdm
15
+
16
+ from . import extractors, logger
17
+ from .utils.base_model import dynamic_load
18
+ from .utils.io import list_h5_names, read_image
19
+ from .utils.parsers import parse_image_lists
20
+
21
+ """
22
+ A set of standard configurations that can be directly selected from the command
23
+ line using their name. Each is a dictionary with the following entries:
24
+ - output: the name of the feature file that will be generated.
25
+ - model: the model configuration, as passed to a feature extractor.
26
+ - preprocessing: how to preprocess the images read from disk.
27
+ """
28
+ confs = {
29
+ "superpoint_aachen": {
30
+ "output": "feats-superpoint-n4096-r1024",
31
+ "model": {
32
+ "name": "superpoint",
33
+ "nms_radius": 3,
34
+ "max_keypoints": 4096,
35
+ "keypoint_threshold": 0.005,
36
+ },
37
+ "preprocessing": {
38
+ "grayscale": True,
39
+ "force_resize": True,
40
+ "resize_max": 1600,
41
+ "width": 640,
42
+ "height": 480,
43
+ "dfactor": 8,
44
+ },
45
+ },
46
+ # Resize images to 1600px even if they are originally smaller.
47
+ # Improves the keypoint localization if the images are of good quality.
48
+ "superpoint_max": {
49
+ "output": "feats-superpoint-n4096-rmax1600",
50
+ "model": {
51
+ "name": "superpoint",
52
+ "nms_radius": 3,
53
+ "max_keypoints": 4096,
54
+ "keypoint_threshold": 0.005,
55
+ },
56
+ "preprocessing": {
57
+ "grayscale": True,
58
+ "force_resize": True,
59
+ "resize_max": 1600,
60
+ "width": 640,
61
+ "height": 480,
62
+ "dfactor": 8,
63
+ },
64
+ },
65
+ "superpoint_inloc": {
66
+ "output": "feats-superpoint-n4096-r1600",
67
+ "model": {
68
+ "name": "superpoint",
69
+ "nms_radius": 4,
70
+ "max_keypoints": 4096,
71
+ "keypoint_threshold": 0.005,
72
+ },
73
+ "preprocessing": {
74
+ "grayscale": True,
75
+ "resize_max": 1600,
76
+ },
77
+ },
78
+ "r2d2": {
79
+ "output": "feats-r2d2-n5000-r1024",
80
+ "model": {
81
+ "name": "r2d2",
82
+ "max_keypoints": 5000,
83
+ "reliability_threshold": 0.7,
84
+ "repetability_threshold": 0.7,
85
+ },
86
+ "preprocessing": {
87
+ "grayscale": False,
88
+ "force_resize": True,
89
+ "resize_max": 1024,
90
+ "width": 640,
91
+ "height": 480,
92
+ "dfactor": 8,
93
+ },
94
+ },
95
+ "d2net-ss": {
96
+ "output": "feats-d2net-ss-n5000-r1600",
97
+ "model": {
98
+ "name": "d2net",
99
+ "multiscale": False,
100
+ "max_keypoints": 5000,
101
+ },
102
+ "preprocessing": {
103
+ "grayscale": False,
104
+ "resize_max": 1600,
105
+ },
106
+ },
107
+ "d2net-ms": {
108
+ "output": "feats-d2net-ms-n5000-r1600",
109
+ "model": {
110
+ "name": "d2net",
111
+ "multiscale": True,
112
+ "max_keypoints": 5000,
113
+ },
114
+ "preprocessing": {
115
+ "grayscale": False,
116
+ "resize_max": 1600,
117
+ },
118
+ },
119
+ "rord": {
120
+ "output": "feats-rord-ss-n5000-r1600",
121
+ "model": {
122
+ "name": "rord",
123
+ "multiscale": False,
124
+ "max_keypoints": 5000,
125
+ },
126
+ "preprocessing": {
127
+ "grayscale": False,
128
+ "resize_max": 1600,
129
+ },
130
+ },
131
+ "rootsift": {
132
+ "output": "feats-rootsift-n5000-r1600",
133
+ "model": {
134
+ "name": "dog",
135
+ "descriptor": "rootsift",
136
+ "max_keypoints": 5000,
137
+ },
138
+ "preprocessing": {
139
+ "grayscale": True,
140
+ "force_resize": True,
141
+ "resize_max": 1600,
142
+ "width": 640,
143
+ "height": 480,
144
+ "dfactor": 8,
145
+ },
146
+ },
147
+ "sift": {
148
+ "output": "feats-sift-n5000-r1600",
149
+ "model": {
150
+ "name": "sift",
151
+ "rootsift": True,
152
+ "max_keypoints": 5000,
153
+ },
154
+ "preprocessing": {
155
+ "grayscale": True,
156
+ "force_resize": True,
157
+ "resize_max": 1600,
158
+ "width": 640,
159
+ "height": 480,
160
+ "dfactor": 8,
161
+ },
162
+ },
163
+ "sosnet": {
164
+ "output": "feats-sosnet-n5000-r1600",
165
+ "model": {
166
+ "name": "dog",
167
+ "descriptor": "sosnet",
168
+ "max_keypoints": 5000,
169
+ },
170
+ "preprocessing": {
171
+ "grayscale": True,
172
+ "resize_max": 1600,
173
+ "force_resize": True,
174
+ "width": 640,
175
+ "height": 480,
176
+ "dfactor": 8,
177
+ },
178
+ },
179
+ "hardnet": {
180
+ "output": "feats-hardnet-n5000-r1600",
181
+ "model": {
182
+ "name": "dog",
183
+ "descriptor": "hardnet",
184
+ "max_keypoints": 5000,
185
+ },
186
+ "preprocessing": {
187
+ "grayscale": True,
188
+ "resize_max": 1600,
189
+ "force_resize": True,
190
+ "width": 640,
191
+ "height": 480,
192
+ "dfactor": 8,
193
+ },
194
+ },
195
+ "disk": {
196
+ "output": "feats-disk-n5000-r1600",
197
+ "model": {
198
+ "name": "disk",
199
+ "max_keypoints": 5000,
200
+ },
201
+ "preprocessing": {
202
+ "grayscale": False,
203
+ "resize_max": 1600,
204
+ },
205
+ },
206
+ "xfeat": {
207
+ "output": "feats-xfeat-n5000-r1600",
208
+ "model": {
209
+ "name": "xfeat",
210
+ "max_keypoints": 5000,
211
+ },
212
+ "preprocessing": {
213
+ "grayscale": False,
214
+ "resize_max": 1600,
215
+ },
216
+ },
217
+ "aliked-n16-rot": {
218
+ "output": "feats-aliked-n16-rot",
219
+ "model": {
220
+ "name": "aliked",
221
+ "model_name": "aliked-n16rot",
222
+ "max_num_keypoints": -1,
223
+ "detection_threshold": 0.2,
224
+ "nms_radius": 2,
225
+ },
226
+ "preprocessing": {
227
+ "grayscale": False,
228
+ "resize_max": 1024,
229
+ },
230
+ },
231
+ "aliked-n16": {
232
+ "output": "feats-aliked-n16",
233
+ "model": {
234
+ "name": "aliked",
235
+ "model_name": "aliked-n16",
236
+ "max_num_keypoints": -1,
237
+ "detection_threshold": 0.2,
238
+ "nms_radius": 2,
239
+ },
240
+ "preprocessing": {
241
+ "grayscale": False,
242
+ "resize_max": 1024,
243
+ },
244
+ },
245
+ "alike": {
246
+ "output": "feats-alike-n5000-r1600",
247
+ "model": {
248
+ "name": "alike",
249
+ "max_keypoints": 5000,
250
+ "use_relu": True,
251
+ "multiscale": False,
252
+ "detection_threshold": 0.5,
253
+ "top_k": -1,
254
+ "sub_pixel": False,
255
+ },
256
+ "preprocessing": {
257
+ "grayscale": False,
258
+ "resize_max": 1600,
259
+ },
260
+ },
261
+ "lanet": {
262
+ "output": "feats-lanet-n5000-r1600",
263
+ "model": {
264
+ "name": "lanet",
265
+ "keypoint_threshold": 0.1,
266
+ "max_keypoints": 5000,
267
+ },
268
+ "preprocessing": {
269
+ "grayscale": False,
270
+ "resize_max": 1600,
271
+ },
272
+ },
273
+ "darkfeat": {
274
+ "output": "feats-darkfeat-n5000-r1600",
275
+ "model": {
276
+ "name": "darkfeat",
277
+ "max_keypoints": 5000,
278
+ "reliability_threshold": 0.7,
279
+ "repetability_threshold": 0.7,
280
+ },
281
+ "preprocessing": {
282
+ "grayscale": False,
283
+ "force_resize": True,
284
+ "resize_max": 1600,
285
+ "width": 640,
286
+ "height": 480,
287
+ "dfactor": 8,
288
+ },
289
+ },
290
+ "dedode": {
291
+ "output": "feats-dedode-n5000-r1600",
292
+ "model": {
293
+ "name": "dedode",
294
+ "max_keypoints": 5000,
295
+ },
296
+ "preprocessing": {
297
+ "grayscale": False,
298
+ "force_resize": True,
299
+ "resize_max": 1600,
300
+ "width": 768,
301
+ "height": 768,
302
+ "dfactor": 8,
303
+ },
304
+ },
305
+ "example": {
306
+ "output": "feats-example-n2000-r1024",
307
+ "model": {
308
+ "name": "example",
309
+ "keypoint_threshold": 0.1,
310
+ "max_keypoints": 2000,
311
+ "model_name": "model.pth",
312
+ },
313
+ "preprocessing": {
314
+ "grayscale": False,
315
+ "force_resize": True,
316
+ "resize_max": 1024,
317
+ "width": 768,
318
+ "height": 768,
319
+ "dfactor": 8,
320
+ },
321
+ },
322
+ "sfd2": {
323
+ "output": "feats-sfd2-n4096-r1600",
324
+ "model": {
325
+ "name": "sfd2",
326
+ "max_keypoints": 4096,
327
+ },
328
+ "preprocessing": {
329
+ "grayscale": False,
330
+ "force_resize": True,
331
+ "resize_max": 1600,
332
+ "width": 640,
333
+ "height": 480,
334
+ "conf_th": 0.001,
335
+ "multiscale": False,
336
+ "scales": [1.0],
337
+ },
338
+ },
339
+ # Global descriptors
340
+ "dir": {
341
+ "output": "global-feats-dir",
342
+ "model": {"name": "dir"},
343
+ "preprocessing": {"resize_max": 1024},
344
+ },
345
+ "netvlad": {
346
+ "output": "global-feats-netvlad",
347
+ "model": {"name": "netvlad"},
348
+ "preprocessing": {"resize_max": 1024},
349
+ },
350
+ "openibl": {
351
+ "output": "global-feats-openibl",
352
+ "model": {"name": "openibl"},
353
+ "preprocessing": {"resize_max": 1024},
354
+ },
355
+ "cosplace": {
356
+ "output": "global-feats-cosplace",
357
+ "model": {"name": "cosplace"},
358
+ "preprocessing": {"resize_max": 1024},
359
+ },
360
+ "eigenplaces": {
361
+ "output": "global-feats-eigenplaces",
362
+ "model": {"name": "eigenplaces"},
363
+ "preprocessing": {"resize_max": 1024},
364
+ },
365
+ }
366
+
367
+
368
+ def resize_image(image, size, interp):
369
+ if interp.startswith("cv2_"):
370
+ interp = getattr(cv2, "INTER_" + interp[len("cv2_") :].upper())
371
+ h, w = image.shape[:2]
372
+ if interp == cv2.INTER_AREA and (w < size[0] or h < size[1]):
373
+ interp = cv2.INTER_LINEAR
374
+ resized = cv2.resize(image, size, interpolation=interp)
375
+ elif interp.startswith("pil_"):
376
+ interp = getattr(PIL.Image, interp[len("pil_") :].upper())
377
+ resized = PIL.Image.fromarray(image.astype(np.uint8))
378
+ resized = resized.resize(size, resample=interp)
379
+ resized = np.asarray(resized, dtype=image.dtype)
380
+ else:
381
+ raise ValueError(f"Unknown interpolation {interp}.")
382
+ return resized
383
+
384
+
385
+ class ImageDataset(torch.utils.data.Dataset):
386
+ default_conf = {
387
+ "globs": ["*.jpg", "*.png", "*.jpeg", "*.JPG", "*.PNG"],
388
+ "grayscale": False,
389
+ "resize_max": None,
390
+ "force_resize": False,
391
+ "interpolation": "cv2_area", # pil_linear is more accurate but slower
392
+ }
393
+
394
+ def __init__(self, root, conf, paths=None):
395
+ self.conf = conf = SimpleNamespace(**{**self.default_conf, **conf})
396
+ self.root = root
397
+
398
+ if paths is None:
399
+ paths = []
400
+ for g in conf.globs:
401
+ paths += list(Path(root).glob("**/" + g))
402
+ if len(paths) == 0:
403
+ raise ValueError(f"Could not find any image in root: {root}.")
404
+ paths = sorted(list(set(paths)))
405
+ self.names = [i.relative_to(root).as_posix() for i in paths]
406
+ logger.info(f"Found {len(self.names)} images in root {root}.")
407
+ else:
408
+ if isinstance(paths, (Path, str)):
409
+ self.names = parse_image_lists(paths)
410
+ elif isinstance(paths, collections.Iterable):
411
+ self.names = [p.as_posix() if isinstance(p, Path) else p for p in paths]
412
+ else:
413
+ raise ValueError(f"Unknown format for path argument {paths}.")
414
+
415
+ for name in self.names:
416
+ if not (root / name).exists():
417
+ raise ValueError(f"Image {name} does not exists in root: {root}.")
418
+
419
+ def __getitem__(self, idx):
420
+ name = self.names[idx]
421
+ image = read_image(self.root / name, self.conf.grayscale)
422
+ image = image.astype(np.float32)
423
+ size = image.shape[:2][::-1]
424
+
425
+ if self.conf.resize_max and (
426
+ self.conf.force_resize or max(size) > self.conf.resize_max
427
+ ):
428
+ scale = self.conf.resize_max / max(size)
429
+ size_new = tuple(int(round(x * scale)) for x in size)
430
+ image = resize_image(image, size_new, self.conf.interpolation)
431
+
432
+ if self.conf.grayscale:
433
+ image = image[None]
434
+ else:
435
+ image = image.transpose((2, 0, 1)) # HxWxC to CxHxW
436
+ image = image / 255.0
437
+
438
+ data = {
439
+ "image": image,
440
+ "original_size": np.array(size),
441
+ }
442
+ return data
443
+
444
+ def __len__(self):
445
+ return len(self.names)
446
+
447
+
448
+ def extract(model, image_0, conf):
449
+ default_conf = {
450
+ "grayscale": True,
451
+ "resize_max": 1024,
452
+ "dfactor": 8,
453
+ "cache_images": False,
454
+ "force_resize": False,
455
+ "width": 320,
456
+ "height": 240,
457
+ "interpolation": "cv2_area",
458
+ }
459
+ conf = SimpleNamespace(**{**default_conf, **conf})
460
+ device = "cuda" if torch.cuda.is_available() else "cpu"
461
+
462
+ def preprocess(image: np.ndarray, conf: SimpleNamespace):
463
+ image = image.astype(np.float32, copy=False)
464
+ size = image.shape[:2][::-1]
465
+ scale = np.array([1.0, 1.0])
466
+ if conf.resize_max:
467
+ scale = conf.resize_max / max(size)
468
+ if scale < 1.0:
469
+ size_new = tuple(int(round(x * scale)) for x in size)
470
+ image = resize_image(image, size_new, "cv2_area")
471
+ scale = np.array(size) / np.array(size_new)
472
+ if conf.force_resize:
473
+ image = resize_image(image, (conf.width, conf.height), "cv2_area")
474
+ size_new = (conf.width, conf.height)
475
+ scale = np.array(size) / np.array(size_new)
476
+ if conf.grayscale:
477
+ assert image.ndim == 2, image.shape
478
+ image = image[None]
479
+ else:
480
+ image = image.transpose((2, 0, 1)) # HxWxC to CxHxW
481
+ image = torch.from_numpy(image / 255.0).float()
482
+
483
+ # assure that the size is divisible by dfactor
484
+ size_new = tuple(
485
+ map(
486
+ lambda x: int(x // conf.dfactor * conf.dfactor),
487
+ image.shape[-2:],
488
+ )
489
+ )
490
+ image = F.resize(image, size=size_new, antialias=True)
491
+ input_ = image.to(device, non_blocking=True)[None]
492
+ data = {
493
+ "image": input_,
494
+ "image_orig": image_0,
495
+ "original_size": np.array(size),
496
+ "size": np.array(image.shape[1:][::-1]),
497
+ }
498
+ return data
499
+
500
+ # convert to grayscale if needed
501
+ if len(image_0.shape) == 3 and conf.grayscale:
502
+ image0 = cv2.cvtColor(image_0, cv2.COLOR_RGB2GRAY)
503
+ else:
504
+ image0 = image_0
505
+ # comment following lines, image is always RGB mode
506
+ # if not conf.grayscale and len(image_0.shape) == 3:
507
+ # image0 = image_0[:, :, ::-1] # BGR to RGB
508
+ data = preprocess(image0, conf)
509
+ pred = model({"image": data["image"]})
510
+ pred["image_size"] = data["original_size"]
511
+ pred = {**pred, **data}
512
+ return pred
513
+
514
+
515
+ @torch.no_grad()
516
+ def main(
517
+ conf: Dict,
518
+ image_dir: Path,
519
+ export_dir: Optional[Path] = None,
520
+ as_half: bool = True,
521
+ image_list: Optional[Union[Path, List[str]]] = None,
522
+ feature_path: Optional[Path] = None,
523
+ overwrite: bool = False,
524
+ ) -> Path:
525
+ logger.info(
526
+ "Extracting local features with configuration:" f"\n{pprint.pformat(conf)}"
527
+ )
528
+
529
+ dataset = ImageDataset(image_dir, conf["preprocessing"], image_list)
530
+ if feature_path is None:
531
+ feature_path = Path(export_dir, conf["output"] + ".h5")
532
+ feature_path.parent.mkdir(exist_ok=True, parents=True)
533
+ skip_names = set(
534
+ list_h5_names(feature_path) if feature_path.exists() and not overwrite else ()
535
+ )
536
+ dataset.names = [n for n in dataset.names if n not in skip_names]
537
+ if len(dataset.names) == 0:
538
+ logger.info("Skipping the extraction.")
539
+ return feature_path
540
+
541
+ device = "cuda" if torch.cuda.is_available() else "cpu"
542
+ Model = dynamic_load(extractors, conf["model"]["name"])
543
+ model = Model(conf["model"]).eval().to(device)
544
+
545
+ loader = torch.utils.data.DataLoader(
546
+ dataset, num_workers=1, shuffle=False, pin_memory=True
547
+ )
548
+ for idx, data in enumerate(tqdm(loader)):
549
+ name = dataset.names[idx]
550
+ pred = model({"image": data["image"].to(device, non_blocking=True)})
551
+ pred = {k: v[0].cpu().numpy() for k, v in pred.items()}
552
+
553
+ pred["image_size"] = original_size = data["original_size"][0].numpy()
554
+ if "keypoints" in pred:
555
+ size = np.array(data["image"].shape[-2:][::-1])
556
+ scales = (original_size / size).astype(np.float32)
557
+ pred["keypoints"] = (pred["keypoints"] + 0.5) * scales[None] - 0.5
558
+ if "scales" in pred:
559
+ pred["scales"] *= scales.mean()
560
+ # add keypoint uncertainties scaled to the original resolution
561
+ uncertainty = getattr(model, "detection_noise", 1) * scales.mean()
562
+
563
+ if as_half:
564
+ for k in pred:
565
+ dt = pred[k].dtype
566
+ if (dt == np.float32) and (dt != np.float16):
567
+ pred[k] = pred[k].astype(np.float16)
568
+
569
+ with h5py.File(str(feature_path), "a", libver="latest") as fd:
570
+ try:
571
+ if name in fd:
572
+ del fd[name]
573
+ grp = fd.create_group(name)
574
+ for k, v in pred.items():
575
+ grp.create_dataset(k, data=v)
576
+ if "keypoints" in pred:
577
+ grp["keypoints"].attrs["uncertainty"] = uncertainty
578
+ except OSError as error:
579
+ if "No space left on device" in error.args[0]:
580
+ logger.error(
581
+ "Out of disk space: storing features on disk can take "
582
+ "significant space, did you enable the as_half flag?"
583
+ )
584
+ del grp, fd[name]
585
+ raise error
586
+
587
+ del pred
588
+
589
+ logger.info("Finished exporting features.")
590
+ return feature_path
591
+
592
+
593
+ if __name__ == "__main__":
594
+ parser = argparse.ArgumentParser()
595
+ parser.add_argument("--image_dir", type=Path, required=True)
596
+ parser.add_argument("--export_dir", type=Path, required=True)
597
+ parser.add_argument(
598
+ "--conf",
599
+ type=str,
600
+ default="superpoint_aachen",
601
+ choices=list(confs.keys()),
602
+ )
603
+ parser.add_argument("--as_half", action="store_true")
604
+ parser.add_argument("--image_list", type=Path)
605
+ parser.add_argument("--feature_path", type=Path)
606
+ args = parser.parse_args()
607
+ main(confs[args.conf], args.image_dir, args.export_dir, args.as_half)
imcui/hloc/extractors/__init__.py ADDED
File without changes
imcui/hloc/extractors/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (160 Bytes). View file
 
imcui/hloc/extractors/alike.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import torch
5
+
6
+ from .. import MODEL_REPO_ID, logger
7
+
8
+ from ..utils.base_model import BaseModel
9
+
10
+ alike_path = Path(__file__).parent / "../../third_party/ALIKE"
11
+ sys.path.append(str(alike_path))
12
+ from alike import ALike as Alike_
13
+ from alike import configs
14
+
15
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
16
+
17
+
18
+ class Alike(BaseModel):
19
+ default_conf = {
20
+ "model_name": "alike-t", # 'alike-t', 'alike-s', 'alike-n', 'alike-l'
21
+ "use_relu": True,
22
+ "multiscale": False,
23
+ "max_keypoints": 1000,
24
+ "detection_threshold": 0.5,
25
+ "top_k": -1,
26
+ "sub_pixel": False,
27
+ }
28
+
29
+ required_inputs = ["image"]
30
+
31
+ def _init(self, conf):
32
+ model_path = self._download_model(
33
+ repo_id=MODEL_REPO_ID,
34
+ filename="{}/{}.pth".format(Path(__file__).stem, self.conf["model_name"]),
35
+ )
36
+ logger.info("Loaded Alike model from {}".format(model_path))
37
+ configs[conf["model_name"]]["model_path"] = model_path
38
+ self.net = Alike_(
39
+ **configs[conf["model_name"]],
40
+ device=device,
41
+ top_k=conf["top_k"],
42
+ scores_th=conf["detection_threshold"],
43
+ n_limit=conf["max_keypoints"],
44
+ )
45
+ logger.info("Load Alike model done.")
46
+
47
+ def _forward(self, data):
48
+ image = data["image"]
49
+ image = image.permute(0, 2, 3, 1).squeeze()
50
+ image = image.cpu().numpy() * 255.0
51
+ pred = self.net(image, sub_pixel=self.conf["sub_pixel"])
52
+
53
+ keypoints = pred["keypoints"]
54
+ descriptors = pred["descriptors"]
55
+ scores = pred["scores"]
56
+
57
+ return {
58
+ "keypoints": torch.from_numpy(keypoints)[None],
59
+ "scores": torch.from_numpy(scores)[None],
60
+ "descriptors": torch.from_numpy(descriptors.T)[None],
61
+ }
imcui/hloc/extractors/aliked.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ from ..utils.base_model import BaseModel
5
+
6
+ lightglue_path = Path(__file__).parent / "../../third_party/LightGlue"
7
+ sys.path.append(str(lightglue_path))
8
+
9
+ from lightglue import ALIKED as ALIKED_
10
+
11
+
12
+ class ALIKED(BaseModel):
13
+ default_conf = {
14
+ "model_name": "aliked-n16",
15
+ "max_num_keypoints": -1,
16
+ "detection_threshold": 0.2,
17
+ "nms_radius": 2,
18
+ }
19
+ required_inputs = ["image"]
20
+
21
+ def _init(self, conf):
22
+ conf.pop("name")
23
+ self.model = ALIKED_(**conf)
24
+
25
+ def _forward(self, data):
26
+ features = self.model(data)
27
+
28
+ return {
29
+ "keypoints": [f for f in features["keypoints"]],
30
+ "scores": [f for f in features["keypoint_scores"]],
31
+ "descriptors": [f.t() for f in features["descriptors"]],
32
+ }
imcui/hloc/extractors/cosplace.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Code for loading models trained with CosPlace as a global features extractor
3
+ for geolocalization through image retrieval.
4
+ Multiple models are available with different backbones. Below is a summary of
5
+ models available (backbone : list of available output descriptors
6
+ dimensionality). For example you can use a model based on a ResNet50 with
7
+ descriptors dimensionality 1024.
8
+ ResNet18: [32, 64, 128, 256, 512]
9
+ ResNet50: [32, 64, 128, 256, 512, 1024, 2048]
10
+ ResNet101: [32, 64, 128, 256, 512, 1024, 2048]
11
+ ResNet152: [32, 64, 128, 256, 512, 1024, 2048]
12
+ VGG16: [ 64, 128, 256, 512]
13
+
14
+ CosPlace paper: https://arxiv.org/abs/2204.02287
15
+ """
16
+
17
+ import torch
18
+ import torchvision.transforms as tvf
19
+
20
+ from ..utils.base_model import BaseModel
21
+
22
+
23
+ class CosPlace(BaseModel):
24
+ default_conf = {"backbone": "ResNet50", "fc_output_dim": 2048}
25
+ required_inputs = ["image"]
26
+
27
+ def _init(self, conf):
28
+ self.net = torch.hub.load(
29
+ "gmberton/CosPlace",
30
+ "get_trained_model",
31
+ backbone=conf["backbone"],
32
+ fc_output_dim=conf["fc_output_dim"],
33
+ ).eval()
34
+
35
+ mean = [0.485, 0.456, 0.406]
36
+ std = [0.229, 0.224, 0.225]
37
+ self.norm_rgb = tvf.Normalize(mean=mean, std=std)
38
+
39
+ def _forward(self, data):
40
+ image = self.norm_rgb(data["image"])
41
+ desc = self.net(image)
42
+ return {
43
+ "global_descriptor": desc,
44
+ }
imcui/hloc/extractors/d2net.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import torch
5
+
6
+ from .. import MODEL_REPO_ID, logger
7
+ from ..utils.base_model import BaseModel
8
+
9
+ d2net_path = Path(__file__).parent / "../../third_party/d2net"
10
+ sys.path.append(str(d2net_path))
11
+ from lib.model_test import D2Net as _D2Net
12
+ from lib.pyramid import process_multiscale
13
+
14
+
15
+ class D2Net(BaseModel):
16
+ default_conf = {
17
+ "model_name": "d2_tf.pth",
18
+ "checkpoint_dir": d2net_path / "models",
19
+ "use_relu": True,
20
+ "multiscale": False,
21
+ "max_keypoints": 1024,
22
+ }
23
+ required_inputs = ["image"]
24
+
25
+ def _init(self, conf):
26
+ logger.info("Loading D2Net model...")
27
+ model_path = self._download_model(
28
+ repo_id=MODEL_REPO_ID,
29
+ filename="{}/{}".format(Path(__file__).stem, self.conf["model_name"]),
30
+ )
31
+ logger.info(f"Loading model from {model_path}...")
32
+ self.net = _D2Net(
33
+ model_file=model_path, use_relu=conf["use_relu"], use_cuda=False
34
+ )
35
+ logger.info("Load D2Net model done.")
36
+
37
+ def _forward(self, data):
38
+ image = data["image"]
39
+ image = image.flip(1) # RGB -> BGR
40
+ norm = image.new_tensor([103.939, 116.779, 123.68])
41
+ image = image * 255 - norm.view(1, 3, 1, 1) # caffe normalization
42
+
43
+ if self.conf["multiscale"]:
44
+ keypoints, scores, descriptors = process_multiscale(image, self.net)
45
+ else:
46
+ keypoints, scores, descriptors = process_multiscale(
47
+ image, self.net, scales=[1]
48
+ )
49
+ keypoints = keypoints[:, [1, 0]] # (x, y) and remove the scale
50
+
51
+ idxs = scores.argsort()[-self.conf["max_keypoints"] or None :]
52
+ keypoints = keypoints[idxs, :2]
53
+ descriptors = descriptors[idxs]
54
+ scores = scores[idxs]
55
+
56
+ return {
57
+ "keypoints": torch.from_numpy(keypoints)[None],
58
+ "scores": torch.from_numpy(scores)[None],
59
+ "descriptors": torch.from_numpy(descriptors.T)[None],
60
+ }
imcui/hloc/extractors/darkfeat.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ from .. import MODEL_REPO_ID, logger
5
+
6
+ from ..utils.base_model import BaseModel
7
+
8
+ darkfeat_path = Path(__file__).parent / "../../third_party/DarkFeat"
9
+ sys.path.append(str(darkfeat_path))
10
+ from darkfeat import DarkFeat as DarkFeat_
11
+
12
+
13
+ class DarkFeat(BaseModel):
14
+ default_conf = {
15
+ "model_name": "DarkFeat.pth",
16
+ "max_keypoints": 1000,
17
+ "detection_threshold": 0.5,
18
+ "sub_pixel": False,
19
+ }
20
+ required_inputs = ["image"]
21
+
22
+ def _init(self, conf):
23
+ model_path = self._download_model(
24
+ repo_id=MODEL_REPO_ID,
25
+ filename="{}/{}".format(Path(__file__).stem, self.conf["model_name"]),
26
+ )
27
+ logger.info("Loaded DarkFeat model: {}".format(model_path))
28
+ self.net = DarkFeat_(model_path)
29
+ logger.info("Load DarkFeat model done.")
30
+
31
+ def _forward(self, data):
32
+ pred = self.net({"image": data["image"]})
33
+ keypoints = pred["keypoints"]
34
+ descriptors = pred["descriptors"]
35
+ scores = pred["scores"]
36
+ idxs = scores.argsort()[-self.conf["max_keypoints"] or None :]
37
+ keypoints = keypoints[idxs, :2]
38
+ descriptors = descriptors[:, idxs]
39
+ scores = scores[idxs]
40
+ return {
41
+ "keypoints": keypoints[None], # 1 x N x 2
42
+ "scores": scores[None], # 1 x N
43
+ "descriptors": descriptors[None], # 1 x 128 x N
44
+ }
imcui/hloc/extractors/dedode.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import torch
5
+ import torchvision.transforms as transforms
6
+
7
+ from .. import MODEL_REPO_ID, logger
8
+
9
+ from ..utils.base_model import BaseModel
10
+
11
+ dedode_path = Path(__file__).parent / "../../third_party/DeDoDe"
12
+ sys.path.append(str(dedode_path))
13
+
14
+ from DeDoDe import dedode_descriptor_B, dedode_detector_L
15
+ from DeDoDe.utils import to_pixel_coords
16
+
17
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
18
+
19
+
20
+ class DeDoDe(BaseModel):
21
+ default_conf = {
22
+ "name": "dedode",
23
+ "model_detector_name": "dedode_detector_L.pth",
24
+ "model_descriptor_name": "dedode_descriptor_B.pth",
25
+ "max_keypoints": 2000,
26
+ "match_threshold": 0.2,
27
+ "dense": False, # Now fixed to be false
28
+ }
29
+ required_inputs = [
30
+ "image",
31
+ ]
32
+
33
+ # Initialize the line matcher
34
+ def _init(self, conf):
35
+ model_detector_path = self._download_model(
36
+ repo_id=MODEL_REPO_ID,
37
+ filename="{}/{}".format(Path(__file__).stem, conf["model_detector_name"]),
38
+ )
39
+ model_descriptor_path = self._download_model(
40
+ repo_id=MODEL_REPO_ID,
41
+ filename="{}/{}".format(Path(__file__).stem, conf["model_descriptor_name"]),
42
+ )
43
+ logger.info("Loaded DarkFeat model: {}".format(model_detector_path))
44
+ self.normalizer = transforms.Normalize(
45
+ mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
46
+ )
47
+
48
+ # load the model
49
+ weights_detector = torch.load(model_detector_path, map_location="cpu")
50
+ weights_descriptor = torch.load(model_descriptor_path, map_location="cpu")
51
+ self.detector = dedode_detector_L(weights=weights_detector, device=device)
52
+ self.descriptor = dedode_descriptor_B(weights=weights_descriptor, device=device)
53
+ logger.info("Load DeDoDe model done.")
54
+
55
+ def _forward(self, data):
56
+ """
57
+ data: dict, keys: {'image0','image1'}
58
+ image shape: N x C x H x W
59
+ color mode: RGB
60
+ """
61
+ img0 = self.normalizer(data["image"].squeeze()).float()[None]
62
+ H_A, W_A = img0.shape[2:]
63
+
64
+ # step 1: detect keypoints
65
+ detections_A = None
66
+ batch_A = {"image": img0}
67
+ if self.conf["dense"]:
68
+ detections_A = self.detector.detect_dense(batch_A)
69
+ else:
70
+ detections_A = self.detector.detect(
71
+ batch_A, num_keypoints=self.conf["max_keypoints"]
72
+ )
73
+ keypoints_A, P_A = detections_A["keypoints"], detections_A["confidence"]
74
+
75
+ # step 2: describe keypoints
76
+ # dim: 1 x N x 256
77
+ description_A = self.descriptor.describe_keypoints(batch_A, keypoints_A)[
78
+ "descriptions"
79
+ ]
80
+ keypoints_A = to_pixel_coords(keypoints_A, H_A, W_A)
81
+
82
+ return {
83
+ "keypoints": keypoints_A, # 1 x N x 2
84
+ "descriptors": description_A.permute(0, 2, 1), # 1 x 256 x N
85
+ "scores": P_A, # 1 x N
86
+ }
imcui/hloc/extractors/dir.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from pathlib import Path
4
+ from zipfile import ZipFile
5
+
6
+ import gdown
7
+ import sklearn
8
+ import torch
9
+
10
+ from ..utils.base_model import BaseModel
11
+
12
+ sys.path.append(str(Path(__file__).parent / "../../third_party/deep-image-retrieval"))
13
+ os.environ["DB_ROOT"] = "" # required by dirtorch
14
+
15
+ from dirtorch.extract_features import load_model # noqa: E402
16
+ from dirtorch.utils import common # noqa: E402
17
+
18
+ # The DIR model checkpoints (pickle files) include sklearn.decomposition.pca,
19
+ # which has been deprecated in sklearn v0.24
20
+ # and must be explicitly imported with `from sklearn.decomposition import PCA`.
21
+ # This is a hacky workaround to maintain forward compatibility.
22
+ sys.modules["sklearn.decomposition.pca"] = sklearn.decomposition._pca
23
+
24
+
25
+ class DIR(BaseModel):
26
+ default_conf = {
27
+ "model_name": "Resnet-101-AP-GeM",
28
+ "whiten_name": "Landmarks_clean",
29
+ "whiten_params": {
30
+ "whitenp": 0.25,
31
+ "whitenv": None,
32
+ "whitenm": 1.0,
33
+ },
34
+ "pooling": "gem",
35
+ "gemp": 3,
36
+ }
37
+ required_inputs = ["image"]
38
+
39
+ dir_models = {
40
+ "Resnet-101-AP-GeM": "https://docs.google.com/uc?export=download&id=1UWJGDuHtzaQdFhSMojoYVQjmCXhIwVvy",
41
+ }
42
+
43
+ def _init(self, conf):
44
+ # todo: download from google drive -> huggingface models
45
+ checkpoint = Path(torch.hub.get_dir(), "dirtorch", conf["model_name"] + ".pt")
46
+ if not checkpoint.exists():
47
+ checkpoint.parent.mkdir(exist_ok=True, parents=True)
48
+ link = self.dir_models[conf["model_name"]]
49
+ gdown.download(str(link), str(checkpoint) + ".zip", quiet=False)
50
+ zf = ZipFile(str(checkpoint) + ".zip", "r")
51
+ zf.extractall(checkpoint.parent)
52
+ zf.close()
53
+ os.remove(str(checkpoint) + ".zip")
54
+
55
+ self.net = load_model(checkpoint, False) # first load on CPU
56
+ if conf["whiten_name"]:
57
+ assert conf["whiten_name"] in self.net.pca
58
+
59
+ def _forward(self, data):
60
+ image = data["image"]
61
+ assert image.shape[1] == 3
62
+ mean = self.net.preprocess["mean"]
63
+ std = self.net.preprocess["std"]
64
+ image = image - image.new_tensor(mean)[:, None, None]
65
+ image = image / image.new_tensor(std)[:, None, None]
66
+
67
+ desc = self.net(image)
68
+ desc = desc.unsqueeze(0) # batch dimension
69
+ if self.conf["whiten_name"]:
70
+ pca = self.net.pca[self.conf["whiten_name"]]
71
+ desc = common.whiten_features(
72
+ desc.cpu().numpy(), pca, **self.conf["whiten_params"]
73
+ )
74
+ desc = torch.from_numpy(desc)
75
+
76
+ return {
77
+ "global_descriptor": desc,
78
+ }
imcui/hloc/extractors/disk.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import kornia
2
+
3
+ from .. import logger
4
+
5
+ from ..utils.base_model import BaseModel
6
+
7
+
8
+ class DISK(BaseModel):
9
+ default_conf = {
10
+ "weights": "depth",
11
+ "max_keypoints": None,
12
+ "nms_window_size": 5,
13
+ "detection_threshold": 0.0,
14
+ "pad_if_not_divisible": True,
15
+ }
16
+ required_inputs = ["image"]
17
+
18
+ def _init(self, conf):
19
+ self.model = kornia.feature.DISK.from_pretrained(conf["weights"])
20
+ logger.info("Load DISK model done.")
21
+
22
+ def _forward(self, data):
23
+ image = data["image"]
24
+ features = self.model(
25
+ image,
26
+ n=self.conf["max_keypoints"],
27
+ window_size=self.conf["nms_window_size"],
28
+ score_threshold=self.conf["detection_threshold"],
29
+ pad_if_not_divisible=self.conf["pad_if_not_divisible"],
30
+ )
31
+ return {
32
+ "keypoints": [f.keypoints for f in features][0][None],
33
+ "scores": [f.detection_scores for f in features][0][None],
34
+ "descriptors": [f.descriptors.t() for f in features][0][None],
35
+ }
imcui/hloc/extractors/dog.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import kornia
2
+ import numpy as np
3
+ import pycolmap
4
+ import torch
5
+ from kornia.feature.laf import (
6
+ extract_patches_from_pyramid,
7
+ laf_from_center_scale_ori,
8
+ )
9
+
10
+ from ..utils.base_model import BaseModel
11
+
12
+ EPS = 1e-6
13
+
14
+
15
+ def sift_to_rootsift(x):
16
+ x = x / (np.linalg.norm(x, ord=1, axis=-1, keepdims=True) + EPS)
17
+ x = np.sqrt(x.clip(min=EPS))
18
+ x = x / (np.linalg.norm(x, axis=-1, keepdims=True) + EPS)
19
+ return x
20
+
21
+
22
+ class DoG(BaseModel):
23
+ default_conf = {
24
+ "options": {
25
+ "first_octave": 0,
26
+ "peak_threshold": 0.01,
27
+ },
28
+ "descriptor": "rootsift",
29
+ "max_keypoints": -1,
30
+ "patch_size": 32,
31
+ "mr_size": 12,
32
+ }
33
+ required_inputs = ["image"]
34
+ detection_noise = 1.0
35
+ max_batch_size = 1024
36
+
37
+ def _init(self, conf):
38
+ if conf["descriptor"] == "sosnet":
39
+ self.describe = kornia.feature.SOSNet(pretrained=True)
40
+ elif conf["descriptor"] == "hardnet":
41
+ self.describe = kornia.feature.HardNet(pretrained=True)
42
+ elif conf["descriptor"] not in ["sift", "rootsift"]:
43
+ raise ValueError(f'Unknown descriptor: {conf["descriptor"]}')
44
+
45
+ self.sift = None # lazily instantiated on the first image
46
+ self.dummy_param = torch.nn.Parameter(torch.empty(0))
47
+ self.device = torch.device("cpu")
48
+
49
+ def to(self, *args, **kwargs):
50
+ device = kwargs.get("device")
51
+ if device is None:
52
+ match = [a for a in args if isinstance(a, (torch.device, str))]
53
+ if len(match) > 0:
54
+ device = match[0]
55
+ if device is not None:
56
+ self.device = torch.device(device)
57
+ return super().to(*args, **kwargs)
58
+
59
+ def _forward(self, data):
60
+ image = data["image"]
61
+ image_np = image.cpu().numpy()[0, 0]
62
+ assert image.shape[1] == 1
63
+ assert image_np.min() >= -EPS and image_np.max() <= 1 + EPS
64
+
65
+ if self.sift is None:
66
+ device = self.dummy_param.device
67
+ use_gpu = pycolmap.has_cuda and device.type == "cuda"
68
+ options = {**self.conf["options"]}
69
+ if self.conf["descriptor"] == "rootsift":
70
+ options["normalization"] = pycolmap.Normalization.L1_ROOT
71
+ else:
72
+ options["normalization"] = pycolmap.Normalization.L2
73
+ self.sift = pycolmap.Sift(
74
+ options=pycolmap.SiftExtractionOptions(options),
75
+ device=getattr(pycolmap.Device, "cuda" if use_gpu else "cpu"),
76
+ )
77
+ keypoints, descriptors = self.sift.extract(image_np)
78
+ scales = keypoints[:, 2]
79
+ oris = np.rad2deg(keypoints[:, 3])
80
+
81
+ if self.conf["descriptor"] in ["sift", "rootsift"]:
82
+ # We still renormalize because COLMAP does not normalize well,
83
+ # maybe due to numerical errors
84
+ if self.conf["descriptor"] == "rootsift":
85
+ descriptors = sift_to_rootsift(descriptors)
86
+ descriptors = torch.from_numpy(descriptors)
87
+ elif self.conf["descriptor"] in ("sosnet", "hardnet"):
88
+ center = keypoints[:, :2] + 0.5
89
+ laf_scale = scales * self.conf["mr_size"] / 2
90
+ laf_ori = -oris
91
+ lafs = laf_from_center_scale_ori(
92
+ torch.from_numpy(center)[None],
93
+ torch.from_numpy(laf_scale)[None, :, None, None],
94
+ torch.from_numpy(laf_ori)[None, :, None],
95
+ ).to(image.device)
96
+ patches = extract_patches_from_pyramid(
97
+ image, lafs, PS=self.conf["patch_size"]
98
+ )[0]
99
+ descriptors = patches.new_zeros((len(patches), 128))
100
+ if len(patches) > 0:
101
+ for start_idx in range(0, len(patches), self.max_batch_size):
102
+ end_idx = min(len(patches), start_idx + self.max_batch_size)
103
+ descriptors[start_idx:end_idx] = self.describe(
104
+ patches[start_idx:end_idx]
105
+ )
106
+ else:
107
+ raise ValueError(f'Unknown descriptor: {self.conf["descriptor"]}')
108
+
109
+ keypoints = torch.from_numpy(keypoints[:, :2]) # keep only x, y
110
+ scales = torch.from_numpy(scales)
111
+ oris = torch.from_numpy(oris)
112
+ scores = keypoints.new_zeros(len(keypoints)) # no scores for SIFT yet
113
+
114
+ if self.conf["max_keypoints"] != -1:
115
+ # TODO: check that the scores from PyCOLMAP are 100% correct,
116
+ # follow https://github.com/mihaidusmanu/pycolmap/issues/8
117
+ max_number = (
118
+ scores.shape[0]
119
+ if scores.shape[0] < self.conf["max_keypoints"]
120
+ else self.conf["max_keypoints"]
121
+ )
122
+ values, indices = torch.topk(scores, max_number)
123
+ keypoints = keypoints[indices]
124
+ scales = scales[indices]
125
+ oris = oris[indices]
126
+ scores = scores[indices]
127
+ descriptors = descriptors[indices]
128
+
129
+ return {
130
+ "keypoints": keypoints[None],
131
+ "scales": scales[None],
132
+ "oris": oris[None],
133
+ "scores": scores[None],
134
+ "descriptors": descriptors.T[None],
135
+ }
imcui/hloc/extractors/eigenplaces.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Code for loading models trained with EigenPlaces (or CosPlace) as a global
3
+ features extractor for geolocalization through image retrieval.
4
+ Multiple models are available with different backbones. Below is a summary of
5
+ models available (backbone : list of available output descriptors
6
+ dimensionality). For example you can use a model based on a ResNet50 with
7
+ descriptors dimensionality 1024.
8
+
9
+ EigenPlaces trained models:
10
+ ResNet18: [ 256, 512]
11
+ ResNet50: [128, 256, 512, 2048]
12
+ ResNet101: [128, 256, 512, 2048]
13
+ VGG16: [ 512]
14
+
15
+ CosPlace trained models:
16
+ ResNet18: [32, 64, 128, 256, 512]
17
+ ResNet50: [32, 64, 128, 256, 512, 1024, 2048]
18
+ ResNet101: [32, 64, 128, 256, 512, 1024, 2048]
19
+ ResNet152: [32, 64, 128, 256, 512, 1024, 2048]
20
+ VGG16: [ 64, 128, 256, 512]
21
+
22
+ EigenPlaces paper (ICCV 2023): https://arxiv.org/abs/2308.10832
23
+ CosPlace paper (CVPR 2022): https://arxiv.org/abs/2204.02287
24
+ """
25
+
26
+ import torch
27
+ import torchvision.transforms as tvf
28
+
29
+ from ..utils.base_model import BaseModel
30
+
31
+
32
+ class EigenPlaces(BaseModel):
33
+ default_conf = {
34
+ "variant": "EigenPlaces",
35
+ "backbone": "ResNet101",
36
+ "fc_output_dim": 2048,
37
+ }
38
+ required_inputs = ["image"]
39
+
40
+ def _init(self, conf):
41
+ self.net = torch.hub.load(
42
+ "gmberton/" + conf["variant"],
43
+ "get_trained_model",
44
+ backbone=conf["backbone"],
45
+ fc_output_dim=conf["fc_output_dim"],
46
+ ).eval()
47
+
48
+ mean = [0.485, 0.456, 0.406]
49
+ std = [0.229, 0.224, 0.225]
50
+ self.norm_rgb = tvf.Normalize(mean=mean, std=std)
51
+
52
+ def _forward(self, data):
53
+ image = self.norm_rgb(data["image"])
54
+ desc = self.net(image)
55
+ return {
56
+ "global_descriptor": desc,
57
+ }
imcui/hloc/extractors/example.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import torch
5
+
6
+ from .. import logger
7
+ from ..utils.base_model import BaseModel
8
+
9
+ example_path = Path(__file__).parent / "../../third_party/example"
10
+ sys.path.append(str(example_path))
11
+
12
+ # import some modules here
13
+
14
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
15
+
16
+
17
+ class Example(BaseModel):
18
+ # change to your default configs
19
+ default_conf = {
20
+ "name": "example",
21
+ "keypoint_threshold": 0.1,
22
+ "max_keypoints": 2000,
23
+ "model_name": "model.pth",
24
+ }
25
+ required_inputs = ["image"]
26
+
27
+ def _init(self, conf):
28
+ # set checkpoints paths if needed
29
+ model_path = example_path / "checkpoints" / f'{conf["model_name"]}'
30
+ if not model_path.exists():
31
+ logger.info(f"No model found at {model_path}")
32
+
33
+ # init model
34
+ self.net = callable
35
+ # self.net = ExampleNet(is_test=True)
36
+ state_dict = torch.load(model_path, map_location="cpu")
37
+ self.net.load_state_dict(state_dict["model_state"])
38
+ logger.info("Load example model done.")
39
+
40
+ def _forward(self, data):
41
+ # data: dict, keys: 'image'
42
+ # image color mode: RGB
43
+ # image value range in [0, 1]
44
+ image = data["image"]
45
+
46
+ # B: batch size, N: number of keypoints
47
+ # keypoints shape: B x N x 2, type: torch tensor
48
+ # scores shape: B x N, type: torch tensor
49
+ # descriptors shape: B x 128 x N, type: torch tensor
50
+ keypoints, scores, descriptors = self.net(image)
51
+
52
+ return {
53
+ "keypoints": keypoints,
54
+ "scores": scores,
55
+ "descriptors": descriptors,
56
+ }
imcui/hloc/extractors/fire.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import subprocess
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import torch
7
+ import torchvision.transforms as tvf
8
+
9
+ from ..utils.base_model import BaseModel
10
+
11
+ logger = logging.getLogger(__name__)
12
+ fire_path = Path(__file__).parent / "../../third_party/fire"
13
+ sys.path.append(str(fire_path))
14
+
15
+
16
+ import fire_network
17
+
18
+
19
+ class FIRe(BaseModel):
20
+ default_conf = {
21
+ "global": True,
22
+ "asmk": False,
23
+ "model_name": "fire_SfM_120k.pth",
24
+ "scales": [2.0, 1.414, 1.0, 0.707, 0.5, 0.353, 0.25], # default params
25
+ "features_num": 1000, # TODO:not supported now
26
+ "asmk_name": "asmk_codebook.bin", # TODO:not supported now
27
+ "config_name": "eval_fire.yml",
28
+ }
29
+ required_inputs = ["image"]
30
+
31
+ # Models exported using
32
+ fire_models = {
33
+ "fire_SfM_120k.pth": "http://download.europe.naverlabs.com/ComputerVision/FIRe/official/fire.pth",
34
+ "fire_imagenet.pth": "http://download.europe.naverlabs.com/ComputerVision/FIRe/pretraining/fire_imagenet.pth",
35
+ }
36
+
37
+ def _init(self, conf):
38
+ assert conf["model_name"] in self.fire_models.keys()
39
+ # Config paths
40
+ model_path = fire_path / "model" / conf["model_name"]
41
+
42
+ # Download the model.
43
+ if not model_path.exists():
44
+ model_path.parent.mkdir(exist_ok=True)
45
+ link = self.fire_models[conf["model_name"]]
46
+ cmd = ["wget", "--quiet", link, "-O", str(model_path)]
47
+ logger.info(f"Downloading the FIRe model with `{cmd}`.")
48
+ subprocess.run(cmd, check=True)
49
+
50
+ logger.info("Loading fire model...")
51
+
52
+ # Load net
53
+ state = torch.load(model_path)
54
+ state["net_params"]["pretrained"] = None
55
+ net = fire_network.init_network(**state["net_params"])
56
+ net.load_state_dict(state["state_dict"])
57
+ self.net = net
58
+
59
+ self.norm_rgb = tvf.Normalize(
60
+ **dict(zip(["mean", "std"], net.runtime["mean_std"]))
61
+ )
62
+
63
+ # params
64
+ self.scales = conf["scales"]
65
+
66
+ def _forward(self, data):
67
+ image = self.norm_rgb(data["image"])
68
+
69
+ # Feature extraction.
70
+ desc = self.net.forward_global(image, scales=self.scales)
71
+
72
+ return {"global_descriptor": desc}
imcui/hloc/extractors/fire_local.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ import torch
6
+ import torchvision.transforms as tvf
7
+
8
+ from .. import logger
9
+ from ..utils.base_model import BaseModel
10
+
11
+ fire_path = Path(__file__).parent / "../../third_party/fire"
12
+
13
+ sys.path.append(str(fire_path))
14
+
15
+
16
+ import fire_network
17
+
18
+ EPS = 1e-6
19
+
20
+
21
+ class FIRe(BaseModel):
22
+ default_conf = {
23
+ "global": True,
24
+ "asmk": False,
25
+ "model_name": "fire_SfM_120k.pth",
26
+ "scales": [2.0, 1.414, 1.0, 0.707, 0.5, 0.353, 0.25], # default params
27
+ "features_num": 1000,
28
+ "asmk_name": "asmk_codebook.bin",
29
+ "config_name": "eval_fire.yml",
30
+ }
31
+ required_inputs = ["image"]
32
+
33
+ # Models exported using
34
+ fire_models = {
35
+ "fire_SfM_120k.pth": "http://download.europe.naverlabs.com/ComputerVision/FIRe/official/fire.pth",
36
+ "fire_imagenet.pth": "http://download.europe.naverlabs.com/ComputerVision/FIRe/pretraining/fire_imagenet.pth",
37
+ }
38
+
39
+ def _init(self, conf):
40
+ assert conf["model_name"] in self.fire_models.keys()
41
+
42
+ # Config paths
43
+ model_path = fire_path / "model" / conf["model_name"]
44
+ config_path = fire_path / conf["config_name"] # noqa: F841
45
+ asmk_bin_path = fire_path / "model" / conf["asmk_name"] # noqa: F841
46
+
47
+ # Download the model.
48
+ if not model_path.exists():
49
+ model_path.parent.mkdir(exist_ok=True)
50
+ link = self.fire_models[conf["model_name"]]
51
+ cmd = ["wget", "--quiet", link, "-O", str(model_path)]
52
+ logger.info(f"Downloading the FIRe model with `{cmd}`.")
53
+ subprocess.run(cmd, check=True)
54
+
55
+ logger.info("Loading fire model...")
56
+
57
+ # Load net
58
+ state = torch.load(model_path)
59
+ state["net_params"]["pretrained"] = None
60
+ net = fire_network.init_network(**state["net_params"])
61
+ net.load_state_dict(state["state_dict"])
62
+ self.net = net
63
+
64
+ self.norm_rgb = tvf.Normalize(
65
+ **dict(zip(["mean", "std"], net.runtime["mean_std"]))
66
+ )
67
+
68
+ # params
69
+ self.scales = conf["scales"]
70
+ self.features_num = conf["features_num"]
71
+
72
+ def _forward(self, data):
73
+ image = self.norm_rgb(data["image"])
74
+
75
+ local_desc = self.net.forward_local(
76
+ image, features_num=self.features_num, scales=self.scales
77
+ )
78
+
79
+ logger.info(f"output[0].shape = {local_desc[0].shape}\n")
80
+
81
+ return {
82
+ # 'global_descriptor': desc
83
+ "local_descriptor": local_desc
84
+ }
imcui/hloc/extractors/lanet.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import torch
5
+
6
+ from .. import MODEL_REPO_ID, logger
7
+
8
+ from ..utils.base_model import BaseModel
9
+
10
+ lib_path = Path(__file__).parent / "../../third_party"
11
+ sys.path.append(str(lib_path))
12
+ from lanet.network_v0.model import PointModel
13
+
14
+ lanet_path = Path(__file__).parent / "../../third_party/lanet"
15
+
16
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
17
+
18
+
19
+ class LANet(BaseModel):
20
+ default_conf = {
21
+ "model_name": "PointModel_v0.pth",
22
+ "keypoint_threshold": 0.1,
23
+ "max_keypoints": 1024,
24
+ }
25
+ required_inputs = ["image"]
26
+
27
+ def _init(self, conf):
28
+ logger.info("Loading LANet model...")
29
+
30
+ model_path = self._download_model(
31
+ repo_id=MODEL_REPO_ID,
32
+ filename="{}/{}".format(Path(__file__).stem, self.conf["model_name"]),
33
+ )
34
+ self.net = PointModel(is_test=True)
35
+ state_dict = torch.load(model_path, map_location="cpu")
36
+ self.net.load_state_dict(state_dict["model_state"])
37
+ logger.info("Load LANet model done.")
38
+
39
+ def _forward(self, data):
40
+ image = data["image"]
41
+ keypoints, scores, descriptors = self.net(image)
42
+ _, _, Hc, Wc = descriptors.shape
43
+
44
+ # Scores & Descriptors
45
+ kpts_score = torch.cat([keypoints, scores], dim=1).view(3, -1).t()
46
+ descriptors = descriptors.view(256, Hc, Wc).view(256, -1).t()
47
+
48
+ # Filter based on confidence threshold
49
+ descriptors = descriptors[kpts_score[:, 0] > self.conf["keypoint_threshold"], :]
50
+ kpts_score = kpts_score[kpts_score[:, 0] > self.conf["keypoint_threshold"], :]
51
+ keypoints = kpts_score[:, 1:]
52
+ scores = kpts_score[:, 0]
53
+
54
+ idxs = scores.argsort()[-self.conf["max_keypoints"] or None :]
55
+ keypoints = keypoints[idxs, :2]
56
+ descriptors = descriptors[idxs]
57
+ scores = scores[idxs]
58
+
59
+ return {
60
+ "keypoints": keypoints[None],
61
+ "scores": scores[None],
62
+ "descriptors": descriptors.T[None],
63
+ }
imcui/hloc/extractors/netvlad.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+ import torchvision.models as models
9
+ from scipy.io import loadmat
10
+
11
+ from .. import logger
12
+ from ..utils.base_model import BaseModel
13
+
14
+ EPS = 1e-6
15
+
16
+
17
+ class NetVLADLayer(nn.Module):
18
+ def __init__(self, input_dim=512, K=64, score_bias=False, intranorm=True):
19
+ super().__init__()
20
+ self.score_proj = nn.Conv1d(input_dim, K, kernel_size=1, bias=score_bias)
21
+ centers = nn.parameter.Parameter(torch.empty([input_dim, K]))
22
+ nn.init.xavier_uniform_(centers)
23
+ self.register_parameter("centers", centers)
24
+ self.intranorm = intranorm
25
+ self.output_dim = input_dim * K
26
+
27
+ def forward(self, x):
28
+ b = x.size(0)
29
+ scores = self.score_proj(x)
30
+ scores = F.softmax(scores, dim=1)
31
+ diff = x.unsqueeze(2) - self.centers.unsqueeze(0).unsqueeze(-1)
32
+ desc = (scores.unsqueeze(1) * diff).sum(dim=-1)
33
+ if self.intranorm:
34
+ # From the official MATLAB implementation.
35
+ desc = F.normalize(desc, dim=1)
36
+ desc = desc.view(b, -1)
37
+ desc = F.normalize(desc, dim=1)
38
+ return desc
39
+
40
+
41
+ class NetVLAD(BaseModel):
42
+ default_conf = {"model_name": "VGG16-NetVLAD-Pitts30K", "whiten": True}
43
+ required_inputs = ["image"]
44
+
45
+ # Models exported using
46
+ # https://github.com/uzh-rpg/netvlad_tf_open/blob/master/matlab/net_class2struct.m.
47
+ dir_models = {
48
+ "VGG16-NetVLAD-Pitts30K": "https://cvg-data.inf.ethz.ch/hloc/netvlad/Pitts30K_struct.mat",
49
+ "VGG16-NetVLAD-TokyoTM": "https://cvg-data.inf.ethz.ch/hloc/netvlad/TokyoTM_struct.mat",
50
+ }
51
+
52
+ def _init(self, conf):
53
+ assert conf["model_name"] in self.dir_models.keys()
54
+
55
+ # Download the checkpoint.
56
+ checkpoint = Path(torch.hub.get_dir(), "netvlad", conf["model_name"] + ".mat")
57
+ if not checkpoint.exists():
58
+ checkpoint.parent.mkdir(exist_ok=True, parents=True)
59
+ link = self.dir_models[conf["model_name"]]
60
+ cmd = ["wget", "--quiet", link, "-O", str(checkpoint)]
61
+ logger.info(f"Downloading the NetVLAD model with `{cmd}`.")
62
+ subprocess.run(cmd, check=True)
63
+
64
+ # Create the network.
65
+ # Remove classification head.
66
+ backbone = list(models.vgg16().children())[0]
67
+ # Remove last ReLU + MaxPool2d.
68
+ self.backbone = nn.Sequential(*list(backbone.children())[:-2])
69
+
70
+ self.netvlad = NetVLADLayer()
71
+
72
+ if conf["whiten"]:
73
+ self.whiten = nn.Linear(self.netvlad.output_dim, 4096)
74
+
75
+ # Parse MATLAB weights using https://github.com/uzh-rpg/netvlad_tf_open
76
+ mat = loadmat(checkpoint, struct_as_record=False, squeeze_me=True)
77
+
78
+ # CNN weights.
79
+ for layer, mat_layer in zip(self.backbone.children(), mat["net"].layers):
80
+ if isinstance(layer, nn.Conv2d):
81
+ w = mat_layer.weights[0] # Shape: S x S x IN x OUT
82
+ b = mat_layer.weights[1] # Shape: OUT
83
+ # Prepare for PyTorch - enforce float32 and right shape.
84
+ # w should have shape: OUT x IN x S x S
85
+ # b should have shape: OUT
86
+ w = torch.tensor(w).float().permute([3, 2, 0, 1])
87
+ b = torch.tensor(b).float()
88
+ # Update layer weights.
89
+ layer.weight = nn.Parameter(w)
90
+ layer.bias = nn.Parameter(b)
91
+
92
+ # NetVLAD weights.
93
+ score_w = mat["net"].layers[30].weights[0] # D x K
94
+ # centers are stored as opposite in official MATLAB code
95
+ center_w = -mat["net"].layers[30].weights[1] # D x K
96
+ # Prepare for PyTorch - make sure it is float32 and has right shape.
97
+ # score_w should have shape K x D x 1
98
+ # center_w should have shape D x K
99
+ score_w = torch.tensor(score_w).float().permute([1, 0]).unsqueeze(-1)
100
+ center_w = torch.tensor(center_w).float()
101
+ # Update layer weights.
102
+ self.netvlad.score_proj.weight = nn.Parameter(score_w)
103
+ self.netvlad.centers = nn.Parameter(center_w)
104
+
105
+ # Whitening weights.
106
+ if conf["whiten"]:
107
+ w = mat["net"].layers[33].weights[0] # Shape: 1 x 1 x IN x OUT
108
+ b = mat["net"].layers[33].weights[1] # Shape: OUT
109
+ # Prepare for PyTorch - make sure it is float32 and has right shape
110
+ w = torch.tensor(w).float().squeeze().permute([1, 0]) # OUT x IN
111
+ b = torch.tensor(b.squeeze()).float() # Shape: OUT
112
+ # Update layer weights.
113
+ self.whiten.weight = nn.Parameter(w)
114
+ self.whiten.bias = nn.Parameter(b)
115
+
116
+ # Preprocessing parameters.
117
+ self.preprocess = {
118
+ "mean": mat["net"].meta.normalization.averageImage[0, 0],
119
+ "std": np.array([1, 1, 1], dtype=np.float32),
120
+ }
121
+
122
+ def _forward(self, data):
123
+ image = data["image"]
124
+ assert image.shape[1] == 3
125
+ assert image.min() >= -EPS and image.max() <= 1 + EPS
126
+ image = torch.clamp(image * 255, 0.0, 255.0) # Input should be 0-255.
127
+ mean = self.preprocess["mean"]
128
+ std = self.preprocess["std"]
129
+ image = image - image.new_tensor(mean).view(1, -1, 1, 1)
130
+ image = image / image.new_tensor(std).view(1, -1, 1, 1)
131
+
132
+ # Feature extraction.
133
+ descriptors = self.backbone(image)
134
+ b, c, _, _ = descriptors.size()
135
+ descriptors = descriptors.view(b, c, -1)
136
+
137
+ # NetVLAD layer.
138
+ descriptors = F.normalize(descriptors, dim=1) # Pre-normalization.
139
+ desc = self.netvlad(descriptors)
140
+
141
+ # Whiten if needed.
142
+ if hasattr(self, "whiten"):
143
+ desc = self.whiten(desc)
144
+ desc = F.normalize(desc, dim=1) # Final L2 normalization.
145
+
146
+ return {"global_descriptor": desc}
imcui/hloc/extractors/openibl.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision.transforms as tvf
3
+
4
+ from ..utils.base_model import BaseModel
5
+
6
+
7
+ class OpenIBL(BaseModel):
8
+ default_conf = {
9
+ "model_name": "vgg16_netvlad",
10
+ }
11
+ required_inputs = ["image"]
12
+
13
+ def _init(self, conf):
14
+ self.net = torch.hub.load(
15
+ "yxgeee/OpenIBL", conf["model_name"], pretrained=True
16
+ ).eval()
17
+ mean = [0.48501960784313836, 0.4579568627450961, 0.4076039215686255]
18
+ std = [0.00392156862745098, 0.00392156862745098, 0.00392156862745098]
19
+ self.norm_rgb = tvf.Normalize(mean=mean, std=std)
20
+
21
+ def _forward(self, data):
22
+ image = self.norm_rgb(data["image"])
23
+ desc = self.net(image)
24
+ return {
25
+ "global_descriptor": desc,
26
+ }
imcui/hloc/extractors/r2d2.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import torchvision.transforms as tvf
5
+
6
+ from .. import MODEL_REPO_ID, logger
7
+
8
+ from ..utils.base_model import BaseModel
9
+
10
+ r2d2_path = Path(__file__).parents[2] / "third_party/r2d2"
11
+ sys.path.append(str(r2d2_path))
12
+
13
+ gim_path = Path(__file__).parents[2] / "third_party/gim"
14
+ if str(gim_path) in sys.path:
15
+ sys.path.remove(str(gim_path))
16
+
17
+ from extract import NonMaxSuppression, extract_multiscale, load_network
18
+
19
+
20
+ class R2D2(BaseModel):
21
+ default_conf = {
22
+ "model_name": "r2d2_WASF_N16.pt",
23
+ "max_keypoints": 5000,
24
+ "scale_factor": 2**0.25,
25
+ "min_size": 256,
26
+ "max_size": 1024,
27
+ "min_scale": 0,
28
+ "max_scale": 1,
29
+ "reliability_threshold": 0.7,
30
+ "repetability_threshold": 0.7,
31
+ }
32
+ required_inputs = ["image"]
33
+
34
+ def _init(self, conf):
35
+ model_path = self._download_model(
36
+ repo_id=MODEL_REPO_ID,
37
+ filename="{}/{}".format(Path(__file__).stem, self.conf["model_name"]),
38
+ )
39
+ self.norm_rgb = tvf.Normalize(
40
+ mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
41
+ )
42
+ self.net = load_network(model_path)
43
+ self.detector = NonMaxSuppression(
44
+ rel_thr=conf["reliability_threshold"],
45
+ rep_thr=conf["repetability_threshold"],
46
+ )
47
+ logger.info("Load R2D2 model done.")
48
+
49
+ def _forward(self, data):
50
+ img = data["image"]
51
+ img = self.norm_rgb(img)
52
+
53
+ xys, desc, scores = extract_multiscale(
54
+ self.net,
55
+ img,
56
+ self.detector,
57
+ scale_f=self.conf["scale_factor"],
58
+ min_size=self.conf["min_size"],
59
+ max_size=self.conf["max_size"],
60
+ min_scale=self.conf["min_scale"],
61
+ max_scale=self.conf["max_scale"],
62
+ )
63
+ idxs = scores.argsort()[-self.conf["max_keypoints"] or None :]
64
+ xy = xys[idxs, :2]
65
+ desc = desc[idxs].t()
66
+ scores = scores[idxs]
67
+
68
+ pred = {
69
+ "keypoints": xy[None],
70
+ "descriptors": desc[None],
71
+ "scores": scores[None],
72
+ }
73
+ return pred
imcui/hloc/extractors/rekd.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import torch
5
+
6
+ from .. import MODEL_REPO_ID, logger
7
+
8
+ from ..utils.base_model import BaseModel
9
+
10
+ rekd_path = Path(__file__).parent / "../../third_party"
11
+ sys.path.append(str(rekd_path))
12
+ from REKD.training.model.REKD import REKD as REKD_
13
+
14
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
15
+
16
+
17
+ class REKD(BaseModel):
18
+ default_conf = {
19
+ "model_name": "v0",
20
+ "keypoint_threshold": 0.1,
21
+ }
22
+ required_inputs = ["image"]
23
+
24
+ def _init(self, conf):
25
+ # TODO: download model
26
+ model_path = self._download_model(
27
+ repo_id=MODEL_REPO_ID,
28
+ filename="{}/{}".format(Path(__file__).stem, self.conf["model_name"]),
29
+ )
30
+ if not model_path.exists():
31
+ print(f"No model found at {model_path}")
32
+ self.net = REKD_(is_test=True)
33
+ state_dict = torch.load(model_path, map_location="cpu")
34
+ self.net.load_state_dict(state_dict["model_state"])
35
+ logger.info("Load REKD model done.")
36
+
37
+ def _forward(self, data):
38
+ image = data["image"]
39
+ keypoints, scores, descriptors = self.net(image)
40
+ _, _, Hc, Wc = descriptors.shape
41
+
42
+ # Scores & Descriptors
43
+ kpts_score = (
44
+ torch.cat([keypoints, scores], dim=1).view(3, -1).t().cpu().detach().numpy()
45
+ )
46
+ descriptors = (
47
+ descriptors.view(256, Hc, Wc).view(256, -1).t().cpu().detach().numpy()
48
+ )
49
+
50
+ # Filter based on confidence threshold
51
+ descriptors = descriptors[kpts_score[:, 0] > self.conf["keypoint_threshold"], :]
52
+ kpts_score = kpts_score[kpts_score[:, 0] > self.conf["keypoint_threshold"], :]
53
+ keypoints = kpts_score[:, 1:]
54
+ scores = kpts_score[:, 0]
55
+
56
+ return {
57
+ "keypoints": torch.from_numpy(keypoints)[None],
58
+ "scores": torch.from_numpy(scores)[None],
59
+ "descriptors": torch.from_numpy(descriptors.T)[None],
60
+ }